Add adv mesh functionalities. (#16009)

* stage

* update

* update

* fix physics & ray cast problem

* fix default value, clean unused code, fix lint errors

* clean code

* update meta file

* update external, license

* fix tidy, circular dep

* fix type cast

* rm unit test

* fix unit test

* update comment
This commit is contained in:
Yiwen
2023-08-21 10:15:24 +08:00
committed by GitHub
parent c19d63d921
commit bde3cd4cc3
29 changed files with 1048 additions and 402 deletions
+12
View File
@@ -3343,6 +3343,18 @@ Can not update a static mesh.
The primitiveIndex is out of range.
### 14202
meshopt asm decoder initialized
### 14203
meshopt wasm decoder initialized
### 14204
meshopt decoder error: %d
### 14300
Can not keep world transform due to the zero scaling of parent node
+148 -8
View File
@@ -28,7 +28,7 @@ import { Asset } from '../../asset/assets/asset';
import { IDynamicGeometry } from '../../primitive/define';
import { BufferBlob } from '../misc/buffer-blob';
import { Skeleton } from './skeleton';
import { geometry, cclegacy, sys, warnID, Mat4, Quat, Vec3, assertIsTrue, murmurhash2_32_gc } from '../../core';
import { geometry, cclegacy, sys, warnID, Mat4, Quat, Vec3, assertIsTrue, murmurhash2_32_gc, errorID } from '../../core';
import { RenderingSubMesh } from '../../asset/assets';
import {
Attribute, Device, Buffer, BufferInfo, AttributeName, BufferUsageBit, Feature, Format,
@@ -36,6 +36,8 @@ import {
} from '../../gfx';
import { Morph } from './morph';
import { MorphRendering, createMorphRendering } from './morph-rendering';
import { MeshoptDecoder } from '../misc/mesh-codec';
import zlib from '../../../external/compression/zlib.min';
function getIndexStrideCtor (stride: number): Uint8ArrayConstructor | Uint16ArrayConstructor | Uint32ArrayConstructor {
switch (stride) {
@@ -77,6 +79,13 @@ export declare namespace Mesh {
attributes: Attribute[];
}
export interface IMeshCluster {
clusterView: IBufferView;
triangleView: IBufferView;
vertexView: IBufferView;
coneView?: IBufferView;
}
/**
* @en Sub mesh contains a list of primitives with the same type (Point, Line or Triangle)
* @zh 子网格。子网格由一系列相同类型的图元组成(例如点、线、面等)。
@@ -106,6 +115,11 @@ export declare namespace Mesh {
* 如未定义或指向的映射表不存在,则默认 VB 内所有关节索引数据直接对应骨骼资源数据。
*/
jointMapIndex?: number;
/**
* @en The cluster data of the sub mesh
*/
cluster?: IMeshCluster;
}
/**
@@ -197,6 +211,30 @@ export declare namespace Mesh {
* @zh 动态网格特有数据
*/
dynamic?: IDynamicStruct;
/**
* @en Whether the mesh data is quantized to reduce memory usage
* @zh 此网格数据是否经过量化以减少内存占用。
*/
quantized?: boolean;
/**
* @en Whether the mesh data is encoded to reduce memory usage
* @zh
*/
encoded?: boolean;
/**
* @en Whether the mesh data is compressed to reduce memory usage
* @zh 此网格数据是否经过压缩以减少内存占用。
*/
compressed?: boolean;
/**
* @en Whether the mesh contains cluster data
* @zh 此网格是否包含 cluster 数据。
*/
cluster?: boolean;
}
/**
@@ -362,9 +400,19 @@ export class Mesh extends Asset {
if (this._initialized) {
return;
}
this._initialized = true;
let info = { struct: this.struct, data: this.data };
if (info.struct.compressed) { // decompress mesh data
info = inflateMesh(info);
}
if (this.struct.encoded) { // decode mesh data
info = decodeMesh(info);
}
this._struct = info.struct;
this._data = info.data;
if (this._struct.dynamic) {
const device: Device = deviceManager.gfxDevice;
const vertexBuffers: Buffer[] = [];
@@ -436,7 +484,7 @@ export class Mesh extends Asset {
}
let indexBuffer: Buffer | null = null;
let ib: any = null;
let ib: Uint8Array | Uint16Array | Uint32Array | undefined;
if (prim.indexView) {
const idxView = prim.indexView;
@@ -752,7 +800,8 @@ export class Mesh extends Asset {
for (let i = 0; i < struct.vertexBundles.length; i++) {
const vtxBdl = struct.vertexBundles[i];
for (let j = 0; j < vtxBdl.attributes.length; j++) {
if (vtxBdl.attributes[j].name === AttributeName.ATTR_POSITION || vtxBdl.attributes[j].name === AttributeName.ATTR_NORMAL) {
if (vtxBdl.attributes[j].name === (AttributeName.ATTR_POSITION as string)
|| vtxBdl.attributes[j].name === (AttributeName.ATTR_NORMAL as string)) {
const { format } = vtxBdl.attributes[j];
const inputView = new DataView(
@@ -852,7 +901,8 @@ export class Mesh extends Asset {
for (let v = 0; v < dstBundle.view.count; ++v) {
dstAttrView = dstVBView.subarray(dstVBOffset, dstVBOffset + attrSize);
vbView.set(dstAttrView, srcVBOffset);
if ((attr.name === AttributeName.ATTR_POSITION || attr.name === AttributeName.ATTR_NORMAL) && worldMatrix) {
if ((attr.name === (AttributeName.ATTR_POSITION as string)
|| attr.name === (AttributeName.ATTR_NORMAL as string)) && worldMatrix) {
const f32_temp = new Float32Array(vbView.buffer, srcVBOffset, 3);
vec3_temp.set(f32_temp[0], f32_temp[1], f32_temp[2]);
switch (attr.name) {
@@ -1258,7 +1308,7 @@ export class Mesh extends Asset {
const primitive = this._struct.primitives[primitiveIndex];
for (const vertexBundleIndex of primitive.vertexBundelIndices) {
const vertexBundle = this._struct.vertexBundles[vertexBundleIndex];
const iAttribute = vertexBundle.attributes.findIndex((a) => a.name === attributeName);
const iAttribute = vertexBundle.attributes.findIndex((a) => a.name === (attributeName as string));
if (iAttribute < 0) {
continue;
}
@@ -1383,7 +1433,12 @@ function getReader (dataView: DataView, format: Format): ((offset: number) => nu
break;
}
case FormatType.FLOAT: {
return (offset: number): number => dataView.getFloat32(offset, isLittleEndian);
switch (stride) {
case 2: return (offset: number) => dataView.getUint16(offset, isLittleEndian);
case 4: return (offset: number) => dataView.getFloat32(offset, isLittleEndian);
default:
}
break;
}
default:
}
@@ -1433,7 +1488,12 @@ function getWriter (dataView: DataView, format: Format): ((offset: number, value
break;
}
case FormatType.FLOAT: {
return (offset: number, value: number): void => dataView.setFloat32(offset, value, isLittleEndian);
switch (stride) {
case 2: return (offset: number, value: number) => dataView.setUint16(offset, value, isLittleEndian);
case 4: return (offset: number, value: number) => dataView.setFloat32(offset, value, isLittleEndian);
default:
}
break;
}
default:
}
@@ -1441,4 +1501,84 @@ function getWriter (dataView: DataView, format: Format): ((offset: number, value
return null;
}
export function decodeMesh (mesh: Mesh.ICreateInfo): Mesh.ICreateInfo {
if (!mesh.struct.encoded) {
// the mesh is not encoded, so no need to decode
return mesh;
}
// decode the mesh
if (!MeshoptDecoder.supported) {
return mesh;
}
const res_checker = (res: number): void => {
if (res < 0) {
errorID(14204, res);
}
};
const struct = JSON.parse(JSON.stringify(mesh.struct)) as Mesh.IStruct;
const bufferBlob = new BufferBlob();
bufferBlob.setNextAlignment(0);
for (const bundle of struct.vertexBundles) {
const view = bundle.view;
const bound = view.count * view.stride;
const buffer = new Uint8Array(bound);
const vertex = new Uint8Array(mesh.data.buffer, view.offset, view.length);
const res = MeshoptDecoder.decodeVertexBuffer(buffer, view.count, view.stride, vertex) as number;
res_checker(res);
bufferBlob.setNextAlignment(view.stride);
const newView: Mesh.IBufferView = {
offset: bufferBlob.getLength(),
length: buffer.byteLength,
count: view.count,
stride: view.stride,
};
bundle.view = newView;
bufferBlob.addBuffer(buffer);
}
for (const primitive of struct.primitives) {
if (primitive.indexView === undefined) {
continue;
}
const view = primitive.indexView;
const bound = view.count * view.stride;
const buffer = new Uint8Array(bound);
const index = new Uint8Array(mesh.data.buffer, view.offset, view.length);
const res = MeshoptDecoder.decodeIndexBuffer(buffer, view.count, view.stride, index) as number;
res_checker(res);
bufferBlob.setNextAlignment(view.stride);
const newView: Mesh.IBufferView = {
offset: bufferBlob.getLength(),
length: buffer.byteLength,
count: view.count,
stride: view.stride,
};
primitive.indexView = newView;
bufferBlob.addBuffer(buffer);
}
const data = new Uint8Array(bufferBlob.getCombined());
return {
struct,
data,
};
}
export function inflateMesh (mesh: Mesh.ICreateInfo): Mesh.ICreateInfo {
const inflator = new zlib.Inflate(mesh.data);
const decompressed = inflator.decompress();
mesh.data = decompressed;
mesh.struct.compressed = false;
return mesh;
}
// function get
+24 -6
View File
@@ -22,7 +22,7 @@
THE SOFTWARE.
*/
import { Mesh } from '../assets/mesh';
import { Mesh, decodeMesh, inflateMesh } from '../assets/mesh';
import { AttributeName, Format, FormatInfos, PrimitiveMode, Attribute } from '../../gfx';
import { Vec3 } from '../../core';
import { IGeometry, IDynamicGeometry, ICreateMeshOptions, ICreateDynamicMeshOptions } from '../../primitive/define';
@@ -56,7 +56,7 @@ export function createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMe
attr = null;
if (geometry.attributes) {
for (const att of geometry.attributes) {
if (att.name === AttributeName.ATTR_POSITION) {
if (att.name === (AttributeName.ATTR_POSITION as string)) {
attr = att;
break;
}
@@ -78,7 +78,7 @@ export function createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMe
attr = null;
if (geometry.attributes) {
for (const att of geometry.attributes) {
if (att.name === AttributeName.ATTR_NORMAL) {
if (att.name === (AttributeName.ATTR_NORMAL as string)) {
attr = att;
break;
}
@@ -100,7 +100,7 @@ export function createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMe
attr = null;
if (geometry.attributes) {
for (const att of geometry.attributes) {
if (att.name === AttributeName.ATTR_TEX_COORD) {
if (att.name === (AttributeName.ATTR_TEX_COORD as string)) {
attr = att;
break;
}
@@ -122,7 +122,7 @@ export function createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMe
attr = null;
if (geometry.attributes) {
for (const att of geometry.attributes) {
if (att.name === AttributeName.ATTR_TANGENT) {
if (att.name === (AttributeName.ATTR_TANGENT as string)) {
attr = att;
break;
}
@@ -144,7 +144,7 @@ export function createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMe
attr = null;
if (geometry.attributes) {
for (const att of geometry.attributes) {
if (att.name === AttributeName.ATTR_COLOR) {
if (att.name === (AttributeName.ATTR_COLOR as string)) {
attr = att;
break;
}
@@ -434,6 +434,24 @@ export class MeshUtils {
static createDynamicMesh (primitiveIndex: number, geometry: IDynamicGeometry, out?: Mesh, options?: ICreateDynamicMeshOptions): Mesh {
return createDynamicMesh(primitiveIndex, geometry, out, options);
}
/**
* @en decode a mesh.
*
* @engineInternal
*/
static decodeMesh (mesh: Mesh.ICreateInfo): Mesh.ICreateInfo {
return decodeMesh(mesh);
}
/**
* @en inflate a mesh.
*
* @engineInternal
*/
static inflateMesh (mesh: Mesh.ICreateInfo): Mesh.ICreateInfo {
return inflateMesh(mesh);
}
}
export declare namespace createMesh {
+81
View File
@@ -0,0 +1,81 @@
/*
Copyright (c) 2023 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import meshopt_asm_factory from 'external:emscripten/meshopt/meshopt_decoder.asm.js';
import meshopt_wasm_factory from 'external:emscripten/meshopt/meshopt_decoder.wasm.js';
import { WASM_SUPPORT_MODE } from 'internal:constants';
import { sys, logID } from '../../core';
import { game } from '../../game';
import { WebAssemblySupportMode } from '../../misc/webassembly-support';
export const MeshoptDecoder = {} as any;
function initDecoderASM (): Promise<void> {
const Module = meshopt_asm_factory;
return Promise.all([Module.ready]).then(() => {
MeshoptDecoder.supported = true;
MeshoptDecoder.ready = Promise.resolve();
MeshoptDecoder.decodeVertexBuffer = Module.decodeVertexBuffer;
MeshoptDecoder.decodeIndexBuffer = Module.decodeIndexBuffer;
MeshoptDecoder.decodeIndexSequence = Module.decodeIndexSequence;
MeshoptDecoder.decodeGltfBuffer = Module.decodeGltfBuffer;
MeshoptDecoder.useWorkers = Module.useWorkers;
MeshoptDecoder.decodeGltfBufferAsync = Module.decodeGltfBufferAsync;
logID(14202);
});
}
function initDecoderWASM (): Promise<void> {
const Module = meshopt_wasm_factory;
return Promise.all([Module.ready]).then(() => {
MeshoptDecoder.supported = true;
MeshoptDecoder.ready = Promise.resolve();
MeshoptDecoder.decodeVertexBuffer = Module.decodeVertexBuffer;
MeshoptDecoder.decodeIndexBuffer = Module.decodeIndexBuffer;
MeshoptDecoder.decodeIndexSequence = Module.decodeIndexSequence;
MeshoptDecoder.decodeGltfBuffer = Module.decodeGltfBuffer;
MeshoptDecoder.useWorkers = Module.useWorkers;
MeshoptDecoder.decodeGltfBufferAsync = Module.decodeGltfBufferAsync;
logID(14203);
});
}
export function InitDecoder (): Promise<void> {
if (WASM_SUPPORT_MODE === (WebAssemblySupportMode.MAYBE_SUPPORT as number)) {
if (sys.hasFeature(sys.Feature.WASM)) {
return initDecoderWASM();
} else {
return initDecoderASM();
}
} else if (WASM_SUPPORT_MODE === (WebAssemblySupportMode.SUPPORT as number)) {
return initDecoderWASM();
} else {
return initDecoderASM();
}
}
game.onPostInfrastructureInitDelegate.add(InitDecoder);
+115 -33
View File
@@ -27,8 +27,9 @@ import {
Attribute, Device, InputAssemblerInfo, Buffer, BufferInfo, AttributeName, BufferUsageBit,
Format, FormatInfos, MemoryUsageBit, PrimitiveMode, DrawInfo,
} from '../../gfx';
import { Vec3, cclegacy } from '../../core';
import { Vec3, approx, cclegacy, floatToHalf, halfToFloat, pseudoRandomRange } from '../../core';
import { Mesh } from '../../3d/assets/mesh';
import { Root } from '../../root';
/**
* @en Array views for index buffer
@@ -123,6 +124,12 @@ export class RenderingSubMesh {
private _drawInfo?: DrawInfo | null = null;
private static EMPTY_GEOMETRIC_INFO: IGeometricInfo = {
positions: new Float32Array(),
indices: new Uint8Array(),
boundingBox: { min: Vec3.ZERO, max: Vec3.ZERO },
};
/**
* @en
* sub mesh's constructor.
@@ -135,8 +142,11 @@ export class RenderingSubMesh {
* @param indirectBuffer @en indirect buffer. @zh 间接缓冲区。
*/
constructor (
vertexBuffers: Buffer[], attributes: Attribute[], primitiveMode: PrimitiveMode,
indexBuffer: Buffer | null = null, indirectBuffer: Buffer | null = null,
vertexBuffers: Buffer[],
attributes: Attribute[],
primitiveMode: PrimitiveMode,
indexBuffer: Buffer | null = null,
indirectBuffer: Buffer | null = null,
isOwnerOfIndexBuffer = true,
) {
this._attributes = attributes;
@@ -187,40 +197,105 @@ export class RenderingSubMesh {
return this._geometricInfo;
}
if (this.mesh === undefined) {
return { positions: new Float32Array(), indices: new Uint8Array(), boundingBox: { min: Vec3.ZERO, max: Vec3.ZERO } };
return RenderingSubMesh.EMPTY_GEOMETRIC_INFO;
}
if (this.subMeshIdx === undefined) {
return { positions: new Float32Array(), indices: new Uint8Array(), boundingBox: { min: Vec3.ZERO, max: Vec3.ZERO } };
return RenderingSubMesh.EMPTY_GEOMETRIC_INFO;
}
const { mesh } = this; const index = this.subMeshIdx;
const positions = mesh.readAttribute(index, AttributeName.ATTR_POSITION) as unknown as Float32Array;
const indices = mesh.readIndices(index) as Uint16Array;
const pAttri = this.attributes.find((element) => element.name === (AttributeName.ATTR_POSITION as string));
if (!pAttri) {
return RenderingSubMesh.EMPTY_GEOMETRIC_INFO;
}
let positions: Float32Array | undefined;
switch (pAttri.format) {
case Format.RG32F:
case Format.RGB32F:
{
positions = mesh.readAttribute(index, AttributeName.ATTR_POSITION) as unknown as Float32Array;
if (!positions) {
return RenderingSubMesh.EMPTY_GEOMETRIC_INFO;
}
break;
}
case Format.RGBA32F:
{
const data = mesh.readAttribute(index, AttributeName.ATTR_POSITION) as unknown as Float32Array;
if (!data) {
return RenderingSubMesh.EMPTY_GEOMETRIC_INFO;
}
const count = data.length / 4;
positions = new Float32Array(count * 3);
for (let i = 0; i < count; ++i) {
const dstPtr = i * 3;
const srcPtr = i * 4;
positions[dstPtr] = data[srcPtr];
positions[dstPtr + 1] = data[srcPtr + 1];
positions[dstPtr + 2] = data[srcPtr + 2];
}
break;
}
case Format.RG16F:
case Format.RGB16F:
{
const data = mesh.readAttribute(index, AttributeName.ATTR_POSITION) as unknown as Uint16Array;
if (!data) {
return RenderingSubMesh.EMPTY_GEOMETRIC_INFO;
}
positions = new Float32Array(data.length);
for (let i = 0; i < data.length; ++i) {
positions[i] = halfToFloat(data[i]);
}
break;
}
case Format.RGBA16F:
{
const data = mesh.readAttribute(index, AttributeName.ATTR_POSITION) as unknown as Uint16Array;
if (!data) {
return RenderingSubMesh.EMPTY_GEOMETRIC_INFO;
}
const count = data.length / 4;
positions = new Float32Array(count * 3);
for (let i = 0; i < count; ++i) {
const dstPtr = i * 3;
const srcPtr = i * 4;
positions[dstPtr] = halfToFloat(data[srcPtr]);
positions[dstPtr + 1] = halfToFloat(data[srcPtr + 1]);
positions[dstPtr + 2] = halfToFloat(data[srcPtr + 2]);
}
break;
}
default:
return RenderingSubMesh.EMPTY_GEOMETRIC_INFO;
}
const indices = mesh.readIndices(index) || undefined;
const max = new Vec3();
const min = new Vec3();
const pAttri = this.attributes.find((element): boolean => element.name === AttributeName.ATTR_POSITION);
if (pAttri) {
const conut = FormatInfos[pAttri.format].count;
const conut = FormatInfos[pAttri.format].count;
if (conut === 2) {
max.set(positions[0], positions[1], 0);
min.set(positions[0], positions[1], 0);
} else {
max.set(positions[0], positions[1], positions[2]);
min.set(positions[0], positions[1], positions[2]);
}
for (let i = 0; i < positions.length; i += conut) {
if (conut === 2) {
max.set(positions[0], positions[1], 0);
min.set(positions[0], positions[1], 0);
max.x = positions[i] > max.x ? positions[i] : max.x;
max.y = positions[i + 1] > max.y ? positions[i + 1] : max.y;
min.x = positions[i] < min.x ? positions[i] : min.x;
min.y = positions[i + 1] < min.y ? positions[i + 1] : min.y;
} else {
max.set(positions[0], positions[1], positions[2]);
min.set(positions[0], positions[1], positions[2]);
}
for (let i = 0; i < positions.length; i += conut) {
if (conut === 2) {
max.x = positions[i] > max.x ? positions[i] : max.x;
max.y = positions[i + 1] > max.y ? positions[i + 1] : max.y;
min.x = positions[i] < min.x ? positions[i] : min.x;
min.y = positions[i + 1] < min.y ? positions[i + 1] : min.y;
} else {
max.x = positions[i] > max.x ? positions[i] : max.x;
max.y = positions[i + 1] > max.y ? positions[i + 1] : max.y;
max.z = positions[i + 2] > max.z ? positions[i + 2] : max.z;
min.x = positions[i] < min.x ? positions[i] : min.x;
min.y = positions[i + 1] < min.y ? positions[i + 1] : min.y;
min.z = positions[i + 2] < min.z ? positions[i + 2] : min.z;
}
max.x = positions[i] > max.x ? positions[i] : max.x;
max.y = positions[i + 1] > max.y ? positions[i + 1] : max.y;
max.z = positions[i + 2] > max.z ? positions[i + 2] : max.z;
min.x = positions[i] < min.x ? positions[i] : min.x;
min.y = positions[i + 1] < min.y ? positions[i + 1] : min.y;
min.z = positions[i + 2] < min.z ? positions[i + 2] : min.z;
}
}
this._geometricInfo = { positions, indices, boundingBox: { max, min } };
@@ -307,14 +382,14 @@ export class RenderingSubMesh {
}
let jointFormat: Format;
let jointOffset: number;
const { device } = cclegacy.director.root;
const { device } = cclegacy.director.root as Root;
for (let i = 0; i < prim.vertexBundelIndices.length; i++) {
const bundle = struct.vertexBundles[prim.vertexBundelIndices[i]];
jointOffset = 0;
jointFormat = Format.UNKNOWN;
for (let j = 0; j < bundle.attributes.length; j++) {
const attr = bundle.attributes[j];
if (attr.name === AttributeName.ATTR_JOINTS) {
if (attr.name === (AttributeName.ATTR_JOINTS as string)) {
jointFormat = attr.format;
break;
}
@@ -324,8 +399,15 @@ export class RenderingSubMesh {
const data = new Uint8Array(this.mesh.data.buffer, bundle.view.offset, bundle.view.length);
const dataView = new DataView(data.slice().buffer);
const idxMap = struct.jointMaps[prim.jointMapIndex];
mapBuffer(dataView, (cur): number => idxMap.indexOf(cur), jointFormat, jointOffset,
bundle.view.length, bundle.view.stride, dataView);
mapBuffer(
dataView,
(cur): number => idxMap.indexOf(cur),
jointFormat,
jointOffset,
bundle.view.length,
bundle.view.stride,
dataView,
);
const buffer = device.createBuffer(new BufferInfo(
BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST,
MemoryUsageBit.DEVICE,
+66
View File
@@ -299,3 +299,69 @@ export function enumerableProps (prototype: ValueType, attrs: string[]): void {
Object.defineProperty(prototype, key, { enumerable: true });
});
}
/**
* convert float to half (short)
*/
const toHalf = (function () {
// https://stackoverflow.com/questions/32633585/how-do-you-convert-to-half-floats-in-javascript
const floatView = new Float32Array(1);
const int32View = new Int32Array(floatView.buffer);
return function toHalf (fval: number): number {
floatView[0] = fval;
const fbits = int32View[0];
const s = (fbits >> 16) & 0x8000; // sign
const em = fbits & 0x7fffffff; // exp and mantissa
let h = (em - (112 << 23) + (1 << 12)) >> 13;
h = (em < (113 << 23)) ? 0 : h; // denormals-as-zero
h = (em >= (143 << 23)) ? 0x7c00 : h; // overflow
h = (em > (255 << 23)) ? 0x7e00 : h; // NaN
int32View[0] = (s | h); // pack sign and half
return int32View[0];
};
}());
const fromHalf = (function () {
const floatView = new Float32Array(1);
const int32View = new Int32Array(floatView.buffer);
return function fromHalf (hval: number /* uint16 */): number {
const s = (hval >> 15) & 0x00000001; // sign
const em = hval & 0x00007fff; // exp and mantissa
let h = (em << 13); // exponent/mantissa bits
let fbits = 0;
if (h !== 0x7c00) { // // NaN/Inf
h += (112 << 23); // exp adjust
if (em === 0) { // // Denormals-as-zero
h = (h & 0xfffff) >> 1; // // Mantissa shift
} else if (em === 0x7fff) { // // Inf/NaN?
h = 0x7fffffff; // // NaN
}
} else {
h = 0x7f800000; // // +/-Inf
}
fbits = (s << 31) | h; // // Sign | Exponent | Mantissa
int32View[0] = fbits;
return floatView[0];
};
}());
export function floatToHalf (val: number) {
return toHalf(val);
}
export function halfToFloat (val: number) {
return fromHalf(val);
}
+5 -1
View File
@@ -2344,7 +2344,11 @@ export function getTypedArrayConstructor (info: FormatInfo): TypedArrayConstruct
}
}
case FormatType.FLOAT: {
return Float32Array;
switch (stride) {
case 2: return Uint16Array;
case 4: return Float32Array;
default: return Float32Array;
}
}
default:
}
@@ -48,8 +48,16 @@ export class CannonTrimeshShape extends CannonShape implements ITrimeshShape {
if (this._shape != null) {
if (mesh && mesh.renderingSubMeshes.length > 0) {
const vertices = mesh.renderingSubMeshes[0].geometricInfo.positions;
const indices = mesh.renderingSubMeshes[0].geometricInfo.indices as Uint16Array;
this.updateProperties(vertices, indices);
const indices = mesh.renderingSubMeshes[0].geometricInfo.indices;
if (indices instanceof Uint8Array) {
this.updateProperties(vertices, new Uint16Array(indices));
} else if (indices instanceof Uint16Array) {
this.updateProperties(vertices, indices);
} else if (indices instanceof Uint32Array) {
this.updateProperties(vertices, new Uint16Array(indices));
} else {
this.updateProperties(vertices, new Uint16Array());
}
} else {
this.updateProperties(new Float32Array(), new Uint16Array());
}
@@ -110,8 +110,6 @@ export class MeshCollider extends Collider {
}
}
/// PRIVATE PROPERTY ///
@serializable
private _mesh: Mesh | null = null;
@@ -54,10 +54,17 @@ export class PhysXTrimeshShape extends PhysXShape implements ITrimeshShape {
const meshScale = PhysXShape.MESH_SCALE;
meshScale.setScale(Vec3.ONE);
meshScale.setRotation(Quat.IDENTITY);
if (collider.convex) {
const posBuf = v.renderingSubMeshes[0].geometricInfo.positions;
let indBuf = v.renderingSubMeshes[0].geometricInfo.indices;
if (indBuf instanceof Uint16Array) {
indBuf = new Uint32Array(indBuf);
}
if (indBuf instanceof Uint8Array) {
indBuf = new Uint32Array(indBuf);
}
if (collider.convex || indBuf === undefined) {
if (PX.MESH_CONVEX[v._uuid] == null) {
const cooking = PhysXInstance.cooking;
const posBuf = v.readAttribute(0, AttributeName.ATTR_POSITION)! as unknown as Float32Array;
PX.MESH_CONVEX[v._uuid] = createConvexMesh(posBuf, cooking, physics);
}
const convexMesh = PX.MESH_CONVEX[v._uuid];
@@ -65,8 +72,6 @@ export class PhysXTrimeshShape extends PhysXShape implements ITrimeshShape {
} else {
if (PX.MESH_STATIC[v._uuid] == null) {
const cooking = PhysXInstance.cooking;
const posBuf = v.readAttribute(0, AttributeName.ATTR_POSITION)! as unknown as Float32Array;
const indBuf = v.readIndices(0)! as unknown as Uint32Array; // Uint16Array ?
PX.MESH_STATIC[v._uuid] = createTriangleMesh(posBuf, indBuf, cooking, physics);
}
const trimesh = PX.MESH_STATIC[v._uuid];
+5 -1
View File
@@ -36,7 +36,11 @@ import { IMacroPatch } from '../core/pass';
import { Mat4, Vec3, Vec4, geometry, cclegacy, EPSILON } from '../../core';
import { Attribute, DescriptorSet, Device, Buffer, BufferInfo,
BufferUsageBit, MemoryUsageBit, Filter, Address, SamplerInfo, deviceManager, Texture } from '../../gfx';
import { UBOLocal, UBOSH, UBOWorldBound, UNIFORM_LIGHTMAP_TEXTURE_BINDING, UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING, UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING, UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING, UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING } from '../../rendering/define';
import {
UBOLocal, UBOSH, UBOWorldBound, UNIFORM_LIGHTMAP_TEXTURE_BINDING, UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING,
UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING, UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING,
UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING,
} from '../../rendering/define';
import { Root } from '../../root';
import { TextureCube } from '../../asset/assets';
import { ShadowType } from './shadows';
@@ -55,4 +55,4 @@ layout(location = 2) in vec2 a_texCoord;
#if __VERSION__ < 450
in float a_vertexId;
#endif
#endif
#endif
+53 -72
View File
@@ -327,84 +327,65 @@ module.exports = {
name: 'Add Vertex Color',
title: 'Fill vertex color with white if the model file does not contain vertex color attribute.',
},
meshOptimizer: {
name: 'Mesh Optimizer',
title: 'Mesh Optimizer is used to simplify imported mesh.<br>Use it when you need to reduce model face count.<br>In some cases, face reduction could lead to various model defect. <br>Tweak properties and try again in those cases.',
simplification: {
name: 'Simplification',
title: 'Simplification',
si: {
name: 'Achieve The Ratio R',
title: 'Achieve The Ratio R',
},
sa: {
name: 'Aggressively Simplify',
title: 'Aggressively Simplify',
},
meshOptimize: {
name: 'Mesh Optimize',
title: 'Whether to optimize the mesh data.',
vertexCache: {
name: 'Vertex Cache',
title: 'Optimize the vertex buffer to improve vertex cache hit rate. <br>It is recommended to enable this option for models with high vertex count.',
},
scene: {
name: 'Scene',
title: 'Scene',
kn: {
name: 'Keep Nodes Transform',
title: 'Keep Nodes Transform',
},
ke: {
name: 'Keep Extras Data',
title: 'Keep Extras Data',
},
vertexFetch: {
name: 'Vertex Fetch',
title: 'Optimize the vertex buffer to improve vertex fetch efficiency. <br>It is recommended to enable this option for models with high vertex count.',
},
miscellaneous: {
name: 'Miscellaneous',
title: 'Miscellaneous',
noq: {
name: 'Disable Quantization',
title: 'Disable Quantization',
},
v: {
name: 'Verbose Output',
title: 'Verbose Output',
},
overdraw: {
name: 'Overdraw',
title: 'Optimize the vertex buffer to reduce overdraw. <br>It is recommended to enable this option for models with high vertex count.',
},
algorithm: {
name: 'Algorithm',
simplify: 'simplify',
gltfpack: 'gltfpack (deprecated)',
},
meshSimplify: {
name: 'Mesh Simplify',
title: 'Whether to simplify the mesh data.',
targetRatio: {
name: 'Target Ratio',
title: 'The target ratio of the simplified mesh data. <br>It is recommended to set this value to 0.5.',
},
simplify:{
targetRatio: {
name: 'Ratio',
title: 'The target face count ratio after face reduction. <br>0 means reduce to minimum, and 1 means no face reduction at all. ',
},
preserveSurfaceCurvature: {
name: 'Surface Curvature',
title: 'Preserve Surface Curvature',
},
preserveBorderEdges: {
name: 'Border Edges',
title: 'Preserve Border Edges',
},
preserveUVSeamEdges: {
name: 'UV Seam Edges',
title: 'Preserve UV Seam Edges',
},
preserveUVFoldoverEdges: {
name: 'UV Foldover Edges',
title: 'Preserve UV Foldover Edges',
},
agressiveness: {
name: 'Agressiveness',
title: 'Face reduction algorithm aggressiveness. <br>The higher it sets, the more aggressive the face reduction algorithm tries to delete faces. <br>High aggressiveness setting is more likely to cause defects in result.',
},
maxIterationCount: {
name: 'Max Iteration Count',
title: 'The max iteration counts that the algorithm tries to further reduce faces of a model. <br>High iteration count is more likely to reach face reduction target, yet it is more likely to take more time and has higher chance to cause mistakes.',
},
autoErrorRate: {
name: 'Auto Error Rate',
title: 'Whether to automatically calculate the error rate of the simplified mesh data.',
},
gltfpack: {
warn: 'The current asset uses the gltfpack mesh optimization algorithm, which has been deprecated. Please use the new simplify face reduction algorithm.',
errorRate: {
name: 'Error Rate',
title: 'The max error rate of the simplified mesh data. <br>This value also alters the result size. <br>It is recommended to tune until you get a good result.',
},
lockBoundary: {
name: 'Lock Boundary',
title: 'Whether to lock the boundary of the simplified mesh data.',
},
},
meshCluster: {
name: 'Mesh Cluster',
title: 'Whether to cluster the mesh data.',
generateBounding: {
name: 'Generate Bounding',
title: 'Whether to generate bounding sphere and normal cone for the clustered mesh data.',
},
},
meshCompress:{
name: 'Mesh Compress',
title: 'Whether to compress the mesh data.',
encode: {
name: 'Encode',
title: 'Encode the mesh data to reduce data size.',
},
compress: {
name: 'Compress',
title: 'Compress the mesh data to reduce data size.',
},
quantize: {
name: 'Quantize',
title: 'Quantize the mesh data to reduce data size.',
},
warn: 'Warning: After optimization, the number and names of mesh resources will change, which will cause the loss of resources referenced by the components, please update them manually in time. (In addition, for prefabs pre-generated in the model resources, the resource synchronization mechanism will update them automatically)',
},
animationBakeRate: {
name: 'Animation Bake Rate',
+3 -3
View File
@@ -325,9 +325,9 @@ module.exports = {
name: '填充顶点色',
title: '如果模型没有顶点颜色属性,添加颜色属性,填充为白色。',
},
meshOptimizer: {
name: 'Mesh 优化',
title: 'Mesh 优化可以被用来简化导入的模型,可以在需要模型减面时使用。<br>在一些少数情况下减面后的模型可能会出现显示异常,如发生这种情况请尝试调整参数并重试。',
meshSimplify: {
name: 'Mesh 简化',
title: 'Mesh 简化可以被用来简化导入的模型,可以在需要模型减面时使用。<br>在一些少数情况下减面后的模型可能会出现显示异常,如发生这种情况请尝试调整参数并重试。',
simplification: {
name: 'Simplification',
title: 'Simplification',
+1 -1
View File
@@ -117,7 +117,7 @@ exports.listeners = {
if (!value) { return; } // 只有被勾选的时候上报埋点
const trackMap = {
meshOptimizer: 'A100000',
meshSimplify: 'A100000',
'fbx.smartMaterialEnabled': 'A100001',
disableMeshSplit: 'A100002',
};
+197 -216
View File
@@ -40,91 +40,83 @@ exports.template = /* html */`
<ui-label slot="label" value="i18n:ENGINE.assets.fbx.generateLightmapUVNode.name" tooltip="i18n:ENGINE.assets.fbx.generateLightmapUVNode.title"></ui-label>
<ui-checkbox slot="content" class="generateLightmapUVNode-checkbox"></ui-checkbox>
</ui-prop>
<ui-section class="mesh-optimizer config" cache-expand="fbx-model-mesh-optimizer">
<div slot="header" class="header">
<ui-checkbox slot="content" class="meshOptimizer-checkbox"></ui-checkbox>
<ui-label value="i18n:ENGINE.assets.fbx.meshOptimizer.name" tooltip="i18n:ENGINE.assets.fbx.meshOptimizer.title"></ui-label>
<ui-section class="meshOptimize config" cache-expand="fbx-model-mesh-optimizer">
<div slot="header" class="meshOptimize-header">
<ui-checkbox slot="content" class="meshOptimize-checkbox"></ui-checkbox>
<ui-label value="i18n:ENGINE.assets.fbx.meshOptimize.name" tooltip="i18n:ENGINE.assets.fbx.meshOptimize.title"></ui-label>
</div>
<div>
<ui-prop class="algorithm">
<ui-label slot="label" value="i18n:ENGINE.assets.fbx.meshOptimizer.algorithm.name"></ui-label>
<ui-select slot="content" class="meshOptimizer-algorithm-select"></ui-select>
</ui-prop>
</div>
<div class="gltfpack-options">
<div class="meshOptimize-options">
<ui-prop>
<div class="warn-words" slot="content">
<ui-label value="i18n:ENGINE.assets.fbx.meshOptimizer.gltfpack.warn"></ui-label>
</div>
</ui-prop>
<ui-section expand cache-expand="fbx-model-mesh-optimizer-simplification">
<ui-label slot="header" value="i18n:ENGINE.assets.fbx.meshOptimizer.simplification.name" tooltip="i18n:ENGINE.assets.fbx.meshOptimizer.simplification.title"></ui-label>
<ui-prop>
<ui-label slot="label" value="i18n:ENGINE.assets.fbx.meshOptimizer.simplification.si.name" tooltip="i18n:ENGINE.assets.fbx.meshOptimizer.simplification.si.title"></ui-label>
<ui-slider slot="content" class="meshOptimizer-si-slider" min="0" max="1" step="0.01"></ui-slider>
</ui-prop>
<ui-prop>
<ui-label slot="label" value="i18n:ENGINE.assets.fbx.meshOptimizer.simplification.sa.name" tooltip="i18n:ENGINE.assets.fbx.meshOptimizer.simplification.sa.title"></ui-label>
<ui-checkbox slot="content" class="meshOptimizer-sa-checkbox"></ui-checkbox>
</ui-prop>
</ui-section>
<ui-section expand cache-expand="fbx-model-mesh-optimizer-scene">
<ui-label slot="header" value="i18n:ENGINE.assets.fbx.meshOptimizer.scene.name" tooltip="i18n:ENGINE.assets.fbx.meshOptimizer.scene.title"></ui-label>
<ui-prop>
<ui-label slot="label" value="i18n:ENGINE.assets.fbx.meshOptimizer.scene.kn.name" tooltip="i18n:ENGINE.assets.fbx.meshOptimizer.scene.kn.title"></ui-label>
<ui-checkbox slot="content" class="meshOptimizer-kn-checkbox"></ui-checkbox>
</ui-prop>
<ui-prop>
<ui-label slot="label" value="i18n:ENGINE.assets.fbx.meshOptimizer.scene.ke.name" tooltip="i18n:ENGINE.assets.fbx.meshOptimizer.scene.ke.title"></ui-label>
<ui-checkbox slot="content" class="meshOptimizer-ke-checkbox"></ui-checkbox>
</ui-prop>
</ui-section>
<ui-section expand cache-expand="fbx-model-mesh-optimizer-miscellaneous">
<ui-label slot="header" value="i18n:ENGINE.assets.fbx.meshOptimizer.miscellaneous.name" tooltip="i18n:ENGINE.assets.fbx.meshOptimizer.miscellaneous.title"></ui-label>
<ui-prop>
<ui-label slot="label" value="i18n:ENGINE.assets.fbx.meshOptimizer.miscellaneous.noq.name" tooltip="i18n:ENGINE.assets.fbx.meshOptimizer.miscellaneous.noq.title"></ui-label>
<ui-checkbox slot="content" class="meshOptimizer-noq-checkbox"></ui-checkbox>
</ui-prop>
<ui-prop>
<ui-label slot="label" value="i18n:ENGINE.assets.fbx.meshOptimizer.miscellaneous.v.name" tooltip="i18n:ENGINE.assets.fbx.meshOptimizer.miscellaneous.v.title"></ui-label>
<ui-checkbox slot="content" class="meshOptimizer-v-checkbox"></ui-checkbox>
</ui-prop>
</ui-section>
<div class="warn-words">
<ui-label value="i18n:ENGINE.assets.fbx.meshOptimizer.warn"></ui-label>
</div>
</div>
<div class="simplify-options">
<ui-prop>
<ui-label slot="label" value="i18n:ENGINE.assets.fbx.meshOptimizer.simplify.targetRatio.name" tooltip="i18n:ENGINE.assets.fbx.meshOptimizer.simplify.targetRatio.title"></ui-label>
<ui-slider slot="content" class="meshOptimizer-targetRatio-slider" min="0" max="1" step="0.01"></ui-slider>
<ui-label slot="label" value="i18n:ENGINE.assets.fbx.meshOptimize.vertexCache.name" tooltip="i18n:ENGINE.assets.fbx.meshOptimize.vertexCache.title"></ui-label>
<ui-checkbox slot="content" class="meshOptimize-vertexCache-checkbox"></ui-checkbox>
</ui-prop>
<ui-prop>
<ui-label slot="label" value="i18n:ENGINE.assets.fbx.meshOptimizer.simplify.preserveSurfaceCurvature.name" tooltip="i18n:ENGINE.assets.fbx.meshOptimizer.simplify.preserveSurfaceCurvature.title"></ui-label>
<ui-checkbox slot="content" class="meshOptimizer-preserveSurfaceCurvature-checkbox"></ui-checkbox>
<ui-label slot="label" value="i18n:ENGINE.assets.fbx.meshOptimize.vertexFetch.name" tooltip="i18n:ENGINE.assets.fbx.meshOptimize.vertexFetch.title"></ui-label>
<ui-checkbox slot="content" class="meshOptimize-vertexFetch-checkbox"></ui-checkbox>
</ui-prop>
<ui-prop>
<ui-label slot="label" value="i18n:ENGINE.assets.fbx.meshOptimizer.simplify.preserveBorderEdges.name" tooltip="i18n:ENGINE.assets.fbx.meshOptimizer.simplify.preserveBorderEdges.title"></ui-label>
<ui-checkbox slot="content" class="meshOptimizer-preserveBorderEdges-checkbox"></ui-checkbox>
</ui-prop>
<ui-prop>
<ui-label slot="label" value="i18n:ENGINE.assets.fbx.meshOptimizer.simplify.preserveUVSeamEdges.name" tooltip="i18n:ENGINE.assets.fbx.meshOptimizer.simplify.preserveUVSeamEdges.title"></ui-label>
<ui-checkbox slot="content" class="meshOptimizer-preserveUVSeamEdges-checkbox"></ui-checkbox>
</ui-prop>
<ui-prop>
<ui-label slot="label" value="i18n:ENGINE.assets.fbx.meshOptimizer.simplify.preserveUVFoldoverEdges.name" tooltip="i18n:ENGINE.assets.fbx.meshOptimizer.simplify.preserveUVFoldoverEdges.title"></ui-label>
<ui-checkbox slot="content" class="meshOptimizer-preserveUVFoldoverEdges-checkbox"></ui-checkbox>
</ui-prop>
<ui-prop>
<ui-label slot="label" value="i18n:ENGINE.assets.fbx.meshOptimizer.simplify.agressiveness.name" tooltip="i18n:ENGINE.assets.fbx.meshOptimizer.simplify.agressiveness.title"></ui-label>
<ui-slider slot="content" class="meshOptimizer-agressiveness-slider" min="5" max="20" step="1"></ui-slider>
</ui-prop>
<ui-prop>
<ui-label slot="label" value="i18n:ENGINE.assets.fbx.meshOptimizer.simplify.maxIterationCount.name" tooltip="i18n:ENGINE.assets.fbx.meshOptimizer.simplify.maxIterationCount.title"></ui-label>
<ui-slider slot="content" class="meshOptimizer-maxIterationCount-slider" min="100" max="200" step="1"></ui-slider>
<ui-label slot="label" value="i18n:ENGINE.assets.fbx.meshOptimize.overdraw.name" tooltip="i18n:ENGINE.assets.fbx.meshOptimize.overdraw.title"></ui-label>
<ui-checkbox slot="content" class="meshOptimize-overdraw-checkbox"></ui-checkbox>
</ui-prop>
</div>
</ui-section>
<ui-section class="meshSimplify config" cache-expand="fbx-model-mesh-simplifier">
<div slot="header" class="meshSimplify-header">
<ui-checkbox slot="content" class="meshSimplify-checkbox"></ui-checkbox>
<ui-label value="i18n:ENGINE.assets.fbx.meshSimplify.name" tooltip="i18n:ENGINE.assets.fbx.meshSimplify.title"></ui-label>
</div>
<div class="meshSimplify-options">
<ui-prop>
<ui-label slot="label" value="i18n:ENGINE.assets.fbx.meshSimplify.targetRatio.name" tooltip="i18n:ENGINE.assets.fbx.meshSimplify.targetRatio.title"></ui-label>
<ui-slider slot="content" class="meshSimplify-targetRatio-slider" min="0" max="1" step="0.01"></ui-slider>
</ui-prop>
<ui-prop>
<ui-label slot="label" value="i18n:ENGINE.assets.fbx.meshSimplify.autoErrorRate.name" tooltip="i18n:ENGINE.assets.fbx.meshSimplify.autoErrorRate.title"></ui-label>
<ui-checkbox slot="content" class="meshSimplify-autoErrorRate-checkbox"></ui-checkbox>
</ui-prop>
<ui-prop>
<ui-label slot="label" value="i18n:ENGINE.assets.fbx.meshSimplify.errorRate.name" tooltip="i18n:ENGINE.assets.fbx.meshSimplify.errorRate.title"></ui-label>
<ui-slider slot="content" class="meshSimplify-errorRate-slider" min="0" max="1" step="0.01"></ui-slider>
</ui-prop>
<ui-prop>
<ui-label slot="label" value="i18n:ENGINE.assets.fbx.meshSimplify.lockBoundary.name" tooltip="i18n:ENGINE.assets.fbx.meshSimplify.lockBoundary.title"></ui-label>
<ui-checkbox slot="content" class="meshSimplify-lockBoundary-checkbox"></ui-checkbox>
</ui-prop>
</div>
</ui-section>
<ui-section class="meshCluster config" cache-expand="fbx-model-mesh-cluster">
<div slot="header" class="meshCluster-header">
<ui-checkbox slot="content" class="meshCluster-checkbox"></ui-checkbox>
<ui-label value="i18n:ENGINE.assets.fbx.meshCluster.name" tooltip="i18n:ENGINE.assets.fbx.meshCluster.title"></ui-label>
</div>
<div class="meshCluster-options">
<ui-prop>
<ui-label slot="label" value="i18n:ENGINE.assets.fbx.meshCluster.generateBounding.name" tooltip="i18n:ENGINE.assets.fbx.meshCluster.generateBounding.title"></ui-label>
<ui-checkbox slot="content" class="meshCluster-generateBounding-checkbox"></ui-checkbox>
</ui-prop>
</div>
</ui-section>
<ui-section class="meshCompress config" cache-expand="fbx-model-mesh-compressor">
<div slot="header" class="meshCompress-header">
<ui-checkbox slot="content" class="meshCompress-checkbox"></ui-checkbox>
<ui-label value="i18n:ENGINE.assets.fbx.meshCompress.name" tooltip="i18n:ENGINE.assets.fbx.meshCompress.title"></ui-label>
</div>
<div class="meshCompress-options">
<ui-prop>
<ui-label slot="label" value="i18n:ENGINE.assets.fbx.meshCompress.encode.name" tooltip="i18n:ENGINE.assets.fbx.meshCompress.encode.title"></ui-label>
<ui-checkbox slot="content" class="meshCompress-encode-checkbox"></ui-checkbox>
</ui-prop>
<ui-prop>
<ui-label slot="label" value="i18n:ENGINE.assets.fbx.meshCompress.compress.name" tooltip="i18n:ENGINE.assets.fbx.meshCompress.compress.title"></ui-label>
<ui-checkbox slot="content" class="meshCompress-compress-checkbox"></ui-checkbox>
</ui-prop>
<ui-prop>
<ui-label slot="label" value="i18n:ENGINE.assets.fbx.meshCompress.quantize.name" tooltip="i18n:ENGINE.assets.fbx.meshCompress.quantize.title"></ui-label>
<ui-checkbox slot="content" class="meshCompress-quantize-checkbox"></ui-checkbox>
</ui-prop>
</div>
</ui-section>
<ui-section class="lods config" cache-expand="fbx-mode-lods">
<div slot="header" class="lods-header">
<ui-checkbox class="lods-checkbox"></ui-checkbox>
@@ -254,25 +246,28 @@ exports.$ = {
addVertexColorCheckbox: '.addVertexColor-checkbox',
promoteSingleRootNodeCheckbox: '.promoteSingleRootNode-checkbox',
generateLightmapUVNodeCheckbox: '.generateLightmapUVNode-checkbox',
meshOptimizerCheckbox: '.meshOptimizer-checkbox',
meshOptimizerAlgorithmSelect: '.meshOptimizer-algorithm-select',
// gltfpackOptions
meshOptimizerGltfpackOptions: '.gltfpack-options',
meshOptimizerSISlider: '.meshOptimizer-si-slider',
meshOptimizerSACheckbox: '.meshOptimizer-sa-checkbox',
meshOptimizerKNCheckbox: '.meshOptimizer-kn-checkbox',
meshOptimizerKECheckbox: '.meshOptimizer-ke-checkbox',
meshOptimizerNOQCheckbox: '.meshOptimizer-noq-checkbox',
meshOptimizerVCheckbox: '.meshOptimizer-v-checkbox',
// meshOptimizeOptions
meshOptimizeCheckbox: '.meshOptimize-checkbox',
meshOptimizeVertexCacheCheckbox: '.meshOptimize-vertexCache-checkbox',
meshOptimizeVertexFetchCheckbox: '.meshOptimize-vertexFetch-checkbox',
meshOptimizeOverdrawCheckbox: '.meshOptimize-overdraw-checkbox',
// simplifyOptions
meshOptimizerSimplifyOptions: '.simplify-options',
meshOptimizerTargetRatioSlider: '.meshOptimizer-targetRatio-slider',
meshOptimizerPreserveSurfaceCurvatureCheckbox: '.meshOptimizer-preserveSurfaceCurvature-checkbox',
meshOptimizerPreserveBorderEdgesCheckbox: '.meshOptimizer-preserveBorderEdges-checkbox',
meshOptimizerPreserveUVSeamEdgesCheckbox: '.meshOptimizer-preserveUVSeamEdges-checkbox',
meshOptimizerPreserveUVFoldoverEdgesCheckbox: '.meshOptimizer-preserveUVFoldoverEdges-checkbox',
meshOptimizerAgressivenessSlider: '.meshOptimizer-agressiveness-slider',
meshOptimizerMaxIterationCountSlider: '.meshOptimizer-maxIterationCount-slider',
meshSimplifyCheckbox: '.meshSimplify-checkbox',
meshSimplifyTargetRatioSlider: '.meshSimplify-targetRatio-slider',
meshSimplifyAutoErrorRateCheckbox: '.meshSimplify-autoErrorRate-checkbox',
meshSimplifyErrorRateSlider: '.meshSimplify-errorRate-slider',
meshSimplifyLockBoundaryCheckbox: '.meshSimplify-lockBoundary-checkbox',
meshClusterCheckbox: '.meshCluster-checkbox',
meshClusterGenerateBoundingCheckbox: '.meshCluster-generateBounding-checkbox',
meshCompressCheckbox: '.meshCompress-checkbox',
meshCompressEncodeCheckbox: '.meshCompress-encode-checkbox',
meshCompressCompressCheckbox: '.meshCompress-compress-checkbox',
meshCompressQuantizeCheckbox: '.meshCompress-quantize-checkbox',
// lods
lodsCheckbox: '.lods-checkbox',
lodItems: '.lod-items',
@@ -488,292 +483,278 @@ const Elements = {
},
},
meshOptimizer: {
// meshOptimize start
meshOptimize: {
ready() {
const panel = this;
panel.$.meshOptimizerCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.enable', 'boolean'));
panel.$.meshOptimizerCheckbox.addEventListener('confirm', () => {
panel.$.meshOptimizeCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimize.enable', 'boolean'));
panel.$.meshOptimizeCheckbox.addEventListener('confirm', () => {
panel.dispatch('snapshot');
});
},
update() {
const panel = this;
panel.$.meshOptimizerCheckbox.value = getPropValue.call(panel, panel.meta.userData.meshOptimizer, false, 'enable');
panel.$.meshOptimizeCheckbox.value = getPropValue.call(panel, panel.meta.userData.meshOptimize, false, 'enable');
updateElementInvalid.call(panel, panel.$.meshOptimizerCheckbox, 'meshOptimizer.enable');
updateElementReadonly.call(panel, panel.$.meshOptimizerCheckbox);
updateElementInvalid.call(panel, panel.$.meshOptimizeCheckbox, 'meshOptimize.enable');
updateElementReadonly.call(panel, panel.$.meshOptimizeCheckbox);
},
},
meshOptimizerAlgorithm: {
meshOptimizeVertexCache: {
ready() {
const panel = this;
panel.$.meshOptimizerAlgorithmSelect.addEventListener('change', (event) => {
panel.setProp.call(panel, 'meshOptimizer.algorithm', 'string', event);
Elements.meshOptimizerAlgorithm.update.call(panel);
});
panel.$.meshOptimizerAlgorithmSelect.addEventListener('confirm', () => {
panel.$.meshOptimizeVertexCacheCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimize.vertexCache', 'boolean'));
panel.$.meshOptimizeVertexCacheCheckbox.addEventListener('confirm', () => {
panel.dispatch('snapshot');
});
},
update() {
const panel = this;
let optionsHtml = '';
const types = ['simplify', 'gltfpack'];
types.forEach((type) => {
optionsHtml += `<option value="${type}">${panel.t(`meshOptimizer.algorithm.${type}`)}</option>`;
});
panel.$.meshOptimizerAlgorithmSelect.innerHTML = optionsHtml;
panel.$.meshOptimizeVertexCacheCheckbox.value = getPropValue.call(panel, panel.meta.userData.meshOptimize, false, 'vertexCache');
const defaultValue = 'simplify';
panel.$.meshOptimizerAlgorithmSelect.value = getPropValue.call(panel, panel.meta.userData.meshOptimizer, defaultValue, 'algorithm');
updateElementInvalid.call(panel, panel.$.meshOptimizerAlgorithmSelect, 'meshOptimizer.algorithm');
updateElementReadonly.call(panel, panel.$.meshOptimizerAlgorithmSelect);
if (panel.$.meshOptimizerAlgorithmSelect.value === defaultValue) {
panel.$.meshOptimizerGltfpackOptions.setAttribute('hidden', '');
panel.$.meshOptimizerSimplifyOptions.removeAttribute('hidden');
} else {
panel.$.meshOptimizerGltfpackOptions.removeAttribute('hidden');
panel.$.meshOptimizerSimplifyOptions.setAttribute('hidden', '');
}
if (panel.$.meshOptimizerAlgorithmSelect.hasAttribute('invalid')) {
panel.$.meshOptimizerGltfpackOptions.setAttribute('hidden', '');
panel.$.meshOptimizerSimplifyOptions.setAttribute('hidden', '');
}
updateElementInvalid.call(panel, panel.$.meshOptimizeVertexCacheCheckbox, 'meshOptimize.vertexCache');
updateElementReadonly.call(panel, panel.$.meshOptimizeVertexCacheCheckbox);
},
},
// gltfpackOptions start
si: {
meshOptimizeVertexFetch: {
ready() {
const panel = this;
panel.$.meshOptimizerSISlider.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.gltfpackOptions.si', 'number'));
panel.$.meshOptimizerSISlider.addEventListener('confirm', () => {
panel.$.meshOptimizeVertexFetchCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimize.vertexFetch', 'boolean'));
panel.$.meshOptimizeVertexFetchCheckbox.addEventListener('confirm', () => {
panel.dispatch('snapshot');
});
},
update() {
const panel = this;
panel.$.meshOptimizerSISlider.value = getPropValue.call(panel, panel.meta.userData, 1, 'meshOptimizer.gltfpackOptions.si');
panel.$.meshOptimizeVertexFetchCheckbox.value = getPropValue.call(panel, panel.meta.userData.meshOptimize, false, 'vertexFetch');
updateElementInvalid.call(panel, panel.$.meshOptimizerSISlider, 'meshOptimizer.gltfpackOptions.si');
updateElementReadonly.call(panel, panel.$.meshOptimizerSISlider, true);
updateElementInvalid.call(panel, panel.$.meshOptimizeVertexFetchCheckbox, 'meshOptimize.vertexFetch');
updateElementReadonly.call(panel, panel.$.meshOptimizeVertexFetchCheckbox);
},
},
sa: {
meshOptimizeOverdraw: {
ready() {
const panel = this;
panel.$.meshOptimizerSACheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.gltfpackOptions.sa', 'boolean'));
panel.$.meshOptimizerSACheckbox.addEventListener('confirm', () => {
panel.$.meshOptimizeOverdrawCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimize.overdraw', 'boolean'));
panel.$.meshOptimizeOverdrawCheckbox.addEventListener('confirm', () => {
panel.dispatch('snapshot');
});
},
update() {
const panel = this;
panel.$.meshOptimizerSACheckbox.value = getPropValue.call(panel, panel.meta.userData, false, 'meshOptimizer.gltfpackOptions.sa');
panel.$.meshOptimizeOverdrawCheckbox.value = getPropValue.call(panel, panel.meta.userData.meshOptimize, false, 'overdraw');
updateElementInvalid.call(panel, panel.$.meshOptimizerSACheckbox, 'meshOptimizer.gltfpackOptions.sa');
updateElementReadonly.call(panel, panel.$.meshOptimizerSACheckbox, true);
updateElementInvalid.call(panel, panel.$.meshOptimizeOverdrawCheckbox, 'meshOptimize.overdraw');
updateElementReadonly.call(panel, panel.$.meshOptimizeOverdrawCheckbox);
},
},
kn: {
// meshOptimize end
// meshSimplify start
meshSimplify: {
ready() {
const panel = this;
panel.$.meshOptimizerKNCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.gltfpackOptions.kn', 'boolean'));
panel.$.meshOptimizerKNCheckbox.addEventListener('confirm', () => {
panel.$.meshSimplifyCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshSimplify.enable', 'boolean'));
panel.$.meshSimplifyCheckbox.addEventListener('confirm', () => {
panel.dispatch('snapshot');
});
},
update() {
const panel = this;
panel.$.meshOptimizerKNCheckbox.value = getPropValue.call(panel, panel.meta.userData, false, 'meshOptimizer.gltfpackOptions.kn');
panel.$.meshSimplifyCheckbox.value = getPropValue.call(panel, panel.meta.userData.meshSimplify, false, 'enable');
updateElementInvalid.call(panel, panel.$.meshOptimizerKNCheckbox, 'meshOptimizer.gltfpackOptions.kn');
updateElementReadonly.call(panel, panel.$.meshOptimizerKNCheckbox, true);
updateElementInvalid.call(panel, panel.$.meshSimplifyCheckbox, 'meshSimplify.enable');
updateElementReadonly.call(panel, panel.$.meshSimplifyCheckbox);
},
},
ke: {
meshSimplifyTargetRatio: {
ready() {
const panel = this;
panel.$.meshOptimizerKECheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.gltfpackOptions.ke', 'boolean'));
panel.$.meshOptimizerKECheckbox.addEventListener('confirm', () => {
panel.$.meshSimplifyTargetRatioSlider.addEventListener('change', panel.setProp.bind(panel, 'meshSimplify.targetRatio', 'number'));
panel.$.meshSimplifyTargetRatioSlider.addEventListener('confirm', () => {
panel.dispatch('snapshot');
});
},
update() {
const panel = this;
panel.$.meshOptimizerKECheckbox.value = getPropValue.call(panel, panel.meta.userData, false, 'meshOptimizer.gltfpackOptions.ke');
panel.$.meshSimplifyTargetRatioSlider.value = getPropValue.call(panel, panel.meta.userData.meshSimplify, 1, 'targetRatio');
updateElementInvalid.call(panel, panel.$.meshOptimizerKECheckbox, 'meshOptimizer.gltfpackOptions.ke');
updateElementReadonly.call(panel, panel.$.meshOptimizerKECheckbox, true);
updateElementInvalid.call(panel, panel.$.meshSimplifyTargetRatioSlider, 'meshSimplify.targetRatio');
updateElementReadonly.call(panel, panel.$.meshSimplifyTargetRatioSlider);
},
},
noq: {
meshSimplifyAutoErrorRateCheckbox: {
ready() {
const panel = this;
panel.$.meshOptimizerNOQCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.gltfpackOptions.noq', 'boolean'));
panel.$.meshOptimizerNOQCheckbox.addEventListener('confirm', () => {
panel.$.meshSimplifyAutoErrorRateCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshSimplify.autoErrorRate', 'boolean'));
panel.$.meshSimplifyAutoErrorRateCheckbox.addEventListener('confirm', () => {
panel.dispatch('snapshot');
});
},
update() {
const panel = this;
panel.$.meshOptimizerNOQCheckbox.value = getPropValue.call(panel, panel.meta.userData, true, 'meshOptimizer.gltfpackOptions.noq');
panel.$.meshSimplifyAutoErrorRateCheckbox.value = getPropValue.call(panel, panel.meta.userData.meshSimplify, false, 'autoErrorRate');
updateElementInvalid.call(panel, panel.$.meshOptimizerNOQCheckbox, 'meshOptimizer.gltfpackOptions.noq');
updateElementReadonly.call(panel, panel.$.meshOptimizerNOQCheckbox, true);
updateElementInvalid.call(panel, panel.$.meshSimplifyAutoErrorRateCheckbox, 'meshSimplify.autoErrorRate');
updateElementReadonly.call(panel, panel.$.meshSimplifyAutoErrorRateCheckbox);
},
},
v: {
meshSimplifyErrorRate: {
ready() {
const panel = this;
panel.$.meshOptimizerVCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.gltfpackOptions.v', 'boolean'));
panel.$.meshOptimizerVCheckbox.addEventListener('confirm', () => {
panel.$.meshSimplifyErrorRateSlider.addEventListener('change', panel.setProp.bind(panel, 'meshSimplify.errorRate', 'number'));
panel.$.meshSimplifyErrorRateSlider.addEventListener('confirm', () => {
panel.dispatch('snapshot');
});
},
update() {
const panel = this;
panel.$.meshOptimizerVCheckbox.value = getPropValue.call(panel, panel.meta.userData, true, 'meshOptimizer.gltfpackOptions.v');
panel.$.meshSimplifyErrorRateSlider.value = getPropValue.call(panel, panel.meta.userData.meshSimplify, 1, 'errorRate');
updateElementInvalid.call(panel, panel.$.meshOptimizerVCheckbox, 'meshOptimizer.gltfpackOptions.v');
updateElementReadonly.call(panel, panel.$.meshOptimizerVCheckbox, true);
updateElementInvalid.call(panel, panel.$.meshSimplifyErrorRateSlider, 'meshSimplify.errorRate');
updateElementReadonly.call(panel, panel.$.meshSimplifyErrorRateSlider);
},
},
// gltfpackOptions end
// simplifyOptions start
targetRatio: {
meshSimplifyLockBoundaryCheckbox: {
ready() {
const panel = this;
panel.$.meshOptimizerTargetRatioSlider.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.simplifyOptions.targetRatio', 'number'));
panel.$.meshOptimizerTargetRatioSlider.addEventListener('confirm', () => {
panel.$.meshSimplifyLockBoundaryCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshSimplify.lockBoundary', 'boolean'));
panel.$.meshSimplifyLockBoundaryCheckbox.addEventListener('confirm', () => {
panel.dispatch('snapshot');
});
},
update() {
const panel = this;
panel.$.meshOptimizerTargetRatioSlider.value = getPropValue.call(panel, panel.meta.userData, 1, 'meshOptimizer.simplifyOptions.targetRatio');
panel.$.meshSimplifyLockBoundaryCheckbox.value = getPropValue.call(panel, panel.meta.userData.meshSimplify, false, 'lockBoundary');
updateElementInvalid.call(panel, panel.$.meshOptimizerTargetRatioSlider, 'meshOptimizer.simplifyOptions.targetRatio');
updateElementReadonly.call(panel, panel.$.meshOptimizerTargetRatioSlider);
updateElementInvalid.call(panel, panel.$.meshSimplifyLockBoundaryCheckbox, 'meshSimplify.lockBoundary');
updateElementReadonly.call(panel, panel.$.meshSimplifyLockBoundaryCheckbox);
},
},
preserveSurfaceCurvature: {
meshClusterCheckbox: {
ready() {
const panel = this;
panel.$.meshOptimizerPreserveSurfaceCurvatureCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.simplifyOptions.preserveSurfaceCurvature', 'boolean'));
panel.$.meshOptimizerPreserveSurfaceCurvatureCheckbox.addEventListener('confirm', () => {
panel.$.meshClusterCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshCluster.enable', 'boolean'));
panel.$.meshClusterCheckbox.addEventListener('confirm', () => {
panel.dispatch('snapshot');
});
},
update() {
const panel = this;
panel.$.meshOptimizerPreserveSurfaceCurvatureCheckbox.value = getPropValue.call(panel, panel.meta.userData, false, 'meshOptimizer.simplifyOptions.preserveSurfaceCurvature');
panel.$.meshClusterCheckbox.value = getPropValue.call(panel, panel.meta.userData.meshCluster, false, 'enable');
updateElementInvalid.call(panel, panel.$.meshOptimizerPreserveSurfaceCurvatureCheckbox, 'meshOptimizer.simplifyOptions.preserveSurfaceCurvature');
updateElementReadonly.call(panel, panel.$.meshOptimizerPreserveSurfaceCurvatureCheckbox);
updateElementInvalid.call(panel, panel.$.meshClusterCheckbox, 'meshCluster.enable');
updateElementReadonly.call(panel, panel.$.meshClusterCheckbox);
},
},
preserveBorderEdges: {
meshClusterGenerateBoundingCheckbox: {
ready() {
const panel = this;
panel.$.meshOptimizerPreserveBorderEdgesCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.simplifyOptions.preserveBorderEdges', 'boolean'));
panel.$.meshOptimizerPreserveBorderEdgesCheckbox.addEventListener('confirm', () => {
panel.$.meshClusterGenerateBoundingCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshCluster.generateBounding', 'boolean'));
panel.$.meshClusterGenerateBoundingCheckbox.addEventListener('confirm', () => {
panel.dispatch('snapshot');
});
},
update() {
const panel = this;
panel.$.meshOptimizerPreserveBorderEdgesCheckbox.value = getPropValue.call(panel, panel.meta.userData, false, 'meshOptimizer.simplifyOptions.preserveBorderEdges');
panel.$.meshClusterGenerateBoundingCheckbox.value = getPropValue.call(panel, panel.meta.userData.meshCluster, false, 'generateBounding');
updateElementInvalid.call(panel, panel.$.meshOptimizerPreserveBorderEdgesCheckbox, 'meshOptimizer.simplifyOptions.preserveBorderEdges');
updateElementReadonly.call(panel, panel.$.meshOptimizerPreserveBorderEdgesCheckbox);
updateElementInvalid.call(panel, panel.$.meshClusterGenerateBoundingCheckbox, 'meshCluster.generateBounding');
updateElementReadonly.call(panel, panel.$.meshClusterGenerateBoundingCheckbox);
},
},
preserveUVSeamEdges: {
// meshSimplify end
// meshCompress start
meshCompress: {
ready() {
const panel = this;
panel.$.meshOptimizerPreserveUVSeamEdgesCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.simplifyOptions.preserveUVSeamEdges', 'boolean'));
panel.$.meshOptimizerPreserveUVSeamEdgesCheckbox.addEventListener('confirm', () => {
panel.$.meshCompressCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshCompress.enable', 'boolean'));
panel.$.meshCompressCheckbox.addEventListener('confirm', () => {
panel.dispatch('snapshot');
});
},
update() {
const panel = this;
panel.$.meshOptimizerPreserveUVSeamEdgesCheckbox.value = getPropValue.call(panel, panel.meta.userData, false, 'meshOptimizer.simplifyOptions.preserveUVSeamEdges');
panel.$.meshCompressCheckbox.value = getPropValue.call(panel, panel.meta.userData.meshCompress, false, 'enable');
updateElementInvalid.call(panel, panel.$.meshOptimizerPreserveUVSeamEdgesCheckbox, 'meshOptimizer.simplifyOptions.preserveUVSeamEdges');
updateElementReadonly.call(panel, panel.$.meshOptimizerPreserveUVSeamEdgesCheckbox);
updateElementInvalid.call(panel, panel.$.meshCompressCheckbox, 'meshCompress.enable');
updateElementReadonly.call(panel, panel.$.meshCompressCheckbox);
},
},
preserveUVFoldoverEdges: {
meshCompressEncode: {
ready() {
const panel = this;
panel.$.meshOptimizerPreserveUVFoldoverEdgesCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.simplifyOptions.preserveUVFoldoverEdges', 'boolean'));
panel.$.meshOptimizerPreserveUVFoldoverEdgesCheckbox.addEventListener('confirm', () => {
panel.$.meshCompressEncodeCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshCompress.encode', 'boolean'));
panel.$.meshCompressEncodeCheckbox.addEventListener('confirm', () => {
panel.dispatch('snapshot');
});
},
update() {
const panel = this;
panel.$.meshOptimizerPreserveUVFoldoverEdgesCheckbox.value = getPropValue.call(panel, panel.meta.userData, false, 'meshOptimizer.simplifyOptions.preserveUVFoldoverEdges');
panel.$.meshCompressEncodeCheckbox.value = getPropValue.call(panel, panel.meta.userData.meshCompress, false, 'encode');
updateElementInvalid.call(panel, panel.$.meshOptimizerPreserveUVFoldoverEdgesCheckbox, 'meshOptimizer.simplifyOptions.preserveUVFoldoverEdges');
updateElementReadonly.call(panel, panel.$.meshOptimizerPreserveUVFoldoverEdgesCheckbox);
updateElementInvalid.call(panel, panel.$.meshCompressEncodeCheckbox, 'meshCompress.encode');
updateElementReadonly.call(panel, panel.$.meshCompressEncodeCheckbox);
},
},
agressiveness: {
meshCompressCompress: {
ready() {
const panel = this;
panel.$.meshOptimizerAgressivenessSlider.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.simplifyOptions.agressiveness', 'number'));
panel.$.meshOptimizerAgressivenessSlider.addEventListener('confirm', () => {
panel.$.meshCompressCompressCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshCompress.compress', 'boolean'));
panel.$.meshCompressCompressCheckbox.addEventListener('confirm', () => {
panel.dispatch('snapshot');
});
},
update() {
const panel = this;
panel.$.meshOptimizerAgressivenessSlider.value = getPropValue.call(panel, panel.meta.userData, 7, 'meshOptimizer.simplifyOptions.agressiveness');
panel.$.meshCompressCompressCheckbox.value = getPropValue.call(panel, panel.meta.userData.meshCompress, false, 'compress');
updateElementInvalid.call(panel, panel.$.meshOptimizerAgressivenessSlider, 'meshOptimizer.simplifyOptions.agressiveness');
updateElementReadonly.call(panel, panel.$.meshOptimizerAgressivenessSlider);
updateElementInvalid.call(panel, panel.$.meshCompressCompressCheckbox, 'meshCompress.compress');
updateElementReadonly.call(panel, panel.$.meshCompressCompressCheckbox);
},
},
maxIterationCount: {
meshCompressQuantize: {
ready() {
const panel = this;
panel.$.meshOptimizerMaxIterationCountSlider.addEventListener('change', panel.setProp.bind(panel, 'meshOptimizer.simplifyOptions.maxIterationCount', 'number'));
panel.$.meshOptimizerMaxIterationCountSlider.addEventListener('confirm', () => {
panel.$.meshCompressQuantizeCheckbox.addEventListener('change', panel.setProp.bind(panel, 'meshCompress.quantize', 'boolean'));
panel.$.meshCompressQuantizeCheckbox.addEventListener('confirm', () => {
panel.dispatch('snapshot');
});
},
update() {
const panel = this;
panel.$.meshOptimizerMaxIterationCountSlider.value = getPropValue.call(panel, panel.meta.userData, 100, 'meshOptimizer.simplifyOptions.maxIterationCount');
panel.$.meshCompressQuantizeCheckbox.value = getPropValue.call(panel, panel.meta.userData.meshCompress, false, 'quantize');
updateElementInvalid.call(panel, panel.$.meshOptimizerMaxIterationCountSlider, 'meshOptimizer.simplifyOptions.maxIterationCount');
updateElementReadonly.call(panel, panel.$.meshOptimizerMaxIterationCountSlider);
updateElementInvalid.call(panel, panel.$.meshCompressQuantizeCheckbox, 'meshCompress.quantize');
updateElementReadonly.call(panel, panel.$.meshCompressQuantizeCheckbox);
},
},
// simplifyOptions end
// meshCompress end
// lods start
lods: {
ready() {
@@ -1003,18 +984,18 @@ function getLodItemHTML(lodOptions, LODTriangleCounts, hasBuiltinLOD = false) {
<div class="left">
<span>LOD ${index}</span>
</div>
<div class="middle" ${ index == 0 || lodOptions[0].faceCount == 0 ? 'hidden' : '' }>
<div class="middle" ${index == 0 || lodOptions[0].faceCount == 0 ? 'hidden' : ''}>
<span class="face-count">Face count(%)</span>
<ui-num-input path="faceCount" min="0" max="100" key="${index}"
value="${Editor.Utils.Math.multi(lodItem.faceCount, 100)}"
${ hasBuiltinLOD ? 'disabled' : '' }>
${hasBuiltinLOD ? 'disabled' : ''}>
</ui-num-input>
</div>
<div class="right">
<div class="triangles">
<span> ${LODTriangleCounts[index] || 0} Triangles</span>
</div>
<div class="operator" ${ hasBuiltinLOD ? 'hidden' : '' }>
<div class="operator" ${hasBuiltinLOD ? 'hidden' : ''}>
<ui-icon value="add" key="${index}" path="insertLod" tooltip="insert after this LOD"></ui-icon>
<ui-icon value="reduce" key="${index}" path="deleteLod" tooltip="delete this LOD"></ui-icon>
</div>
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2016-2023 Arseny Kapoulkine
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+31 -3
View File
@@ -26,6 +26,7 @@
#include "3d/assets/Morph.h"
#include "3d/assets/Skeleton.h"
#include "3d/misc/BufferBlob.h"
#include "3d/misc/CreateMesh.h"
#include "base/std/hash/hash.h"
#include "core/DataView.h"
#include "core/assets/RenderingSubMesh.h"
@@ -102,7 +103,13 @@ DataReaderCallback getReader(const DataView &dataView, gfx::Format format) {
break;
}
case gfx::FormatType::FLOAT: {
return [&](uint32_t offset) -> TypedArrayElementType { return dataView.getFloat32(offset); };
switch (stride) {
case 2: return [&](uint32_t offset) -> TypedArrayElementType { return dataView.getUint16(offset); };
case 4: return [&](uint32_t offset) -> TypedArrayElementType { return dataView.getFloat32(offset); };
default:
break;
}
break;
}
default:
break;
@@ -159,7 +166,13 @@ DataWritterCallback getWriter(DataView &dataView, gfx::Format format) {
break;
}
case gfx::FormatType::FLOAT: {
return [&](uint32_t offset, const TypedArrayElementType &value) { dataView.setFloat32(offset, ccstd::get<float>(value)); };
switch (stride) {
case 2: return [&](uint32_t offset, const TypedArrayElementType &value) { dataView.setUint16(offset, ccstd::get<uint16_t>(value)); };
case 4: return [&](uint32_t offset, const TypedArrayElementType &value) { dataView.setFloat32(offset, ccstd::get<float>(value)); };
default:
break;
}
break;
}
default:
break;
@@ -293,6 +306,15 @@ void Mesh::initialize() {
_initialized = true;
if (_struct.compressed) {
// decompress
MeshUtils::inflateMesh(_struct, _data);
}
if (_struct.encoded) {
// decode
MeshUtils::decodeMesh(_struct, _data);
}
if (_struct.dynamic.has_value()) {
auto *device = gfx::Device::getInstance();
gfx::BufferList vertexBuffers;
@@ -1301,7 +1323,13 @@ TypedArray Mesh::createTypedArrayWithGFXFormat(gfx::Format format, uint32_t coun
break;
}
case gfx::FormatType::FLOAT: {
return Float32Array(count);
switch (stride) {
case 2: return Uint16Array(count);
case 4: return Float32Array(count);
default:
break;
}
break;
}
default:
break;
+6
View File
@@ -196,6 +196,12 @@ public:
* @zh 动态网格特有数据
*/
ccstd::optional<IDynamicStruct> dynamic;
ccstd::optional<bool> encoded;
ccstd::optional<bool> compressed;
ccstd::optional<bool> quantized;
};
struct ICreateInfo {
+68
View File
@@ -23,12 +23,14 @@
****************************************************************************/
#include "3d/misc/CreateMesh.h"
#include <zlib.h>
#include <algorithm>
#include "3d/misc/Buffer.h"
#include "3d/misc/BufferBlob.h"
#include "core/ArrayBuffer.h"
#include "core/DataView.h"
#include "core/assets/RenderingSubMesh.h"
#include "meshopt/meshoptimizer.h"
#include "renderer/gfx-base/GFXDef-common.h"
namespace cc {
@@ -404,4 +406,70 @@ Mesh::ICreateInfo MeshUtils::createDynamicMeshInfo(const IDynamicGeometry &geome
return createInfo;
}
void MeshUtils::inflateMesh(const Mesh::IStruct &structInfo, Uint8Array &data) {
uLongf uncompressedSize = 0U;
for (const auto &prim : structInfo.primitives) {
uncompressedSize += prim.indexView->length;
}
for (const auto &vb : structInfo.vertexBundles) {
uncompressedSize += vb.view.length;
}
auto uncompressedData = Uint8Array(static_cast<uint32_t>(uncompressedSize));
auto res = uncompress(uncompressedData.buffer()->getData(), &uncompressedSize, data.buffer()->getData(), data.byteLength());
data = uncompressedData;
}
void MeshUtils::decodeMesh(Mesh::IStruct &structInfo, Uint8Array &data) {
BufferBlob bufferBlob;
for (auto &bundle : structInfo.vertexBundles) {
auto &view = bundle.view;
auto bound = view.count * view.stride;
auto *buffer = ccnew ArrayBuffer(bound);
auto vertex = Uint8Array(data.buffer(), view.offset, view.length);
int res = meshopt_decodeVertexBuffer(buffer->getData(), view.count, view.stride, vertex.buffer()->getData() + vertex.byteOffset(), view.length);
if (res < 0) {
assert(false && "failed to decode vertex buffer");
}
bufferBlob.setNextAlignment(view.stride);
Mesh::IVertexBundle vertexBundle;
Mesh::IBufferView buffferView;
buffferView.offset = bufferBlob.getLength();
buffferView.length = bound;
buffferView.count = view.count;
buffferView.stride = view.stride;
bufferBlob.addBuffer(buffer);
bundle.view = buffferView;
}
for (auto &primitive : structInfo.primitives) {
if (!primitive.indexView.has_value()) {
continue;
}
auto view = *primitive.indexView;
auto bound = view.count * view.stride;
auto *buffer = ccnew ArrayBuffer(bound);
auto index = DataView(data.buffer(), view.offset, view.length);
int res = meshopt_decodeIndexBuffer(buffer->getData(), view.count, view.stride, index.buffer()->getData() + index.byteOffset(), view.length);
if (res < 0) {
assert(false && "failed to decode index buffer");
}
bufferBlob.setNextAlignment(view.stride);
Mesh::IBufferView buffferView;
buffferView.offset = bufferBlob.getLength();
buffferView.length = bound;
buffferView.count = view.count;
buffferView.stride = view.stride;
bufferBlob.addBuffer(buffer);
primitive.indexView = buffferView;
}
data = Uint8Array(bufferBlob.getCombined());
}
} // namespace cc
+7
View File
@@ -87,6 +87,13 @@ public:
* @zh 创建一个动态网格ICreateInfo。
*/
static Mesh::ICreateInfo createDynamicMeshInfo(const IDynamicGeometry &geometry, const ICreateDynamicMeshOptions &options = {});
/**
*
*/
static void inflateMesh(const Mesh::IStruct &structInfo, Uint8Array &data);
static void decodeMesh(Mesh::IStruct &structInfo, Uint8Array &data);
};
} // namespace cc
+103 -43
View File
@@ -28,6 +28,7 @@
#include "3d/misc/Buffer.h"
#include "core/DataView.h"
#include "core/TypedArray.h"
#include "math/Utils.h"
#include "math/Vec3.h"
#include "renderer/gfx-base/GFXBuffer.h"
#include "renderer/gfx-base/GFXDevice.h"
@@ -91,59 +92,118 @@ const IGeometricInfo &RenderingSubMesh::getGeometricInfo() {
return EMPTY_GEOMETRIC_INFO;
}
auto iter = std::find_if(_attributes.cbegin(), _attributes.cend(), [](const gfx::Attribute &element) -> bool {
return element.name == gfx::ATTR_NAME_POSITION;
});
if (iter != _attributes.end()) {
return EMPTY_GEOMETRIC_INFO;
}
const auto &attri = *iter;
const uint32_t count = gfx::GFX_FORMAT_INFOS[static_cast<uint32_t>(attri.format)].count;
auto index = static_cast<index_t>(_subMeshIdx.value());
const auto &positionsVar = _mesh->readAttribute(index, gfx::ATTR_NAME_POSITION);
const auto *pPositions = ccstd::get_if<Float32Array>(&positionsVar);
if (pPositions != nullptr) {
const auto &positions = *pPositions;
const auto &indicesVar = _mesh->readIndices(index);
Vec3 max;
Vec3 min;
auto iter = std::find_if(_attributes.cbegin(), _attributes.cend(), [](const gfx::Attribute &element) -> bool {
return element.name == gfx::ATTR_NAME_POSITION;
});
if (iter != _attributes.cend()) {
const auto &attri = *iter;
const uint32_t count = gfx::GFX_FORMAT_INFOS[static_cast<uint32_t>(attri.format)].count;
if (count == 2) {
max.set(positions[0], positions[1], 0);
min.set(positions[0], positions[1], 0);
} else {
max.set(positions[0], positions[1], positions[2]);
min.set(positions[0], positions[1], positions[2]);
Float32Array const *pPositions = nullptr;
switch (attri.format) {
case gfx::Format::RG32F:
case gfx::Format::RGB32F: {
pPositions = ccstd::get_if<Float32Array>(&positionsVar);
if (pPositions == nullptr) {
return EMPTY_GEOMETRIC_INFO;
}
for (int i = 0; i < positions.length(); i += static_cast<int>(count)) {
if (count == 2) {
max.x = positions[i] > max.x ? positions[i] : max.x;
max.y = positions[i + 1] > max.y ? positions[i + 1] : max.y;
min.x = positions[i] < min.x ? positions[i] : min.x;
min.y = positions[i + 1] < min.y ? positions[i + 1] : min.y;
} else {
max.x = positions[i] > max.x ? positions[i] : max.x;
max.y = positions[i + 1] > max.y ? positions[i + 1] : max.y;
max.z = positions[i + 2] > max.z ? positions[i + 2] : max.z;
min.x = positions[i] < min.x ? positions[i] : min.x;
min.y = positions[i + 1] < min.y ? positions[i + 1] : min.y;
min.z = positions[i + 2] < min.z ? positions[i + 2] : min.z;
}
break;
}
case gfx::Format::RGBA32F: {
const auto *data = ccstd::get_if<Float32Array>(&positionsVar);
if (data == nullptr) {
return EMPTY_GEOMETRIC_INFO;
}
const auto count = data->length() / 4;
auto *pos = ccnew Float32Array(count * 3);
for (uint32_t i = 0; i < count; i++) {
const auto dstPtr = i * 3;
const auto srcPtr = i * 4;
(*pos)[dstPtr] = (*data)[srcPtr];
(*pos)[dstPtr + 1] = (*data)[srcPtr + 1];
(*pos)[dstPtr + 2] = (*data)[srcPtr + 2];
}
pPositions = pos;
break;
}
case gfx::Format::RG16F:
case gfx::Format::RGB16F: {
const auto *data = ccstd::get_if<Uint16Array>(&positionsVar);
if (data == nullptr) {
return EMPTY_GEOMETRIC_INFO;
}
auto *pos = ccnew Float32Array(data->length());
for (uint32_t i = 0; i < data->length(); ++i) {
(*pos)[i] = mathutils::halfToFloat((*data)[i]);
}
pPositions = pos;
break;
}
case gfx::Format::RGBA16F: {
const auto *data = ccstd::get_if<Uint16Array>(&positionsVar);
if (data == nullptr) {
return EMPTY_GEOMETRIC_INFO;
}
const auto count = data->length() / 4;
auto *pos = ccnew Float32Array(count * 3);
for (uint32_t i = 0; i < count; i++) {
const auto dstPtr = i * 3;
const auto srcPtr = i * 4;
(*pos)[dstPtr] = mathutils::halfToFloat((*data)[srcPtr]);
(*pos)[dstPtr + 1] = mathutils::halfToFloat((*data)[srcPtr + 1]);
(*pos)[dstPtr + 2] = mathutils::halfToFloat((*data)[srcPtr + 2]);
}
pPositions = pos;
break;
}
default:
return EMPTY_GEOMETRIC_INFO;
};
IGeometricInfo info;
info.positions = positions;
info.indices = indicesVar;
info.boundingBox.max = max;
info.boundingBox.min = min;
const auto &positions = *pPositions;
const auto &indicesVar = _mesh->readIndices(index);
_geometricInfo = info;
return _geometricInfo.value();
Vec3 max;
Vec3 min;
if (count == 2) {
max.set(positions[0], positions[1], 0);
min.set(positions[0], positions[1], 0);
} else {
max.set(positions[0], positions[1], positions[2]);
min.set(positions[0], positions[1], positions[2]);
}
for (int i = 0; i < positions.length(); i += static_cast<int>(count)) {
if (count == 2) {
max.x = positions[i] > max.x ? positions[i] : max.x;
max.y = positions[i + 1] > max.y ? positions[i + 1] : max.y;
min.x = positions[i] < min.x ? positions[i] : min.x;
min.y = positions[i + 1] < min.y ? positions[i + 1] : min.y;
} else {
max.x = positions[i] > max.x ? positions[i] : max.x;
max.y = positions[i + 1] > max.y ? positions[i + 1] : max.y;
max.z = positions[i + 2] > max.z ? positions[i + 2] : max.z;
min.x = positions[i] < min.x ? positions[i] : min.x;
min.y = positions[i + 1] < min.y ? positions[i + 1] : min.y;
min.z = positions[i + 2] < min.z ? positions[i + 2] : min.z;
}
}
return EMPTY_GEOMETRIC_INFO;
IGeometricInfo info;
info.positions = positions;
info.indices = indicesVar;
info.boundingBox.max = max;
info.boundingBox.min = min;
_geometricInfo = info;
return _geometricInfo.value();
}
void RenderingSubMesh::genFlatBuffers() {
+57
View File
@@ -50,6 +50,63 @@ float maxComponent(const Vec3 &v) {
return std::max(std::max(v.x, v.y), v.z);
}
uint16_t floatToHalf(float fval) {
union {
float f;
unsigned int ui;
} u = {fval};
unsigned int ui = u.ui;
int s = (ui >> 16) & 0x8000; // NOLINT
int em = ui & 0x7fffffff; // NOLINT
/* bias exponent and round to nearest; 112 is relative exponent bias (127-15) */
int h = (em - (112 << 23) + (1 << 12)) >> 13;
/* underflow: flush to zero; 113 encodes exponent -14 */
h = (em < (113 << 23)) ? 0 : h;
/* overflow: infinity; 143 encodes exponent 16 */
h = (em >= (143 << 23)) ? 0x7c00 : h;
/* NaN; note that we convert all types of NaN to qNaN */
h = (em > (255 << 23)) ? 0x7e00 : h;
return static_cast<uint16_t>(s | h);
}
float halfToFloat(uint16_t hval) {
union {
float f;
unsigned int ui;
} u;
int s = (hval >> 15) & 0x00000001;
int em = hval & 0x00007fff;
int m = 0;
if (em > 0) {
/* normalized */
if (em > 30 << 10) {
/* overflow: infinity */
em = 255 << 23;
} else {
em = (em + (112 << 10)) << 13;
}
} else {
/* denormalized */
if (em > 25 << 10) {
/* underflow: flush to zero */
em = 0;
} else {
em = (em + (113 << 10)) >> 1;
}
}
u.ui = ((uint16_t)(s << 31)) | em | m; // NOLINT
return u.f;
}
} // namespace mathutils
} // namespace cc
+4
View File
@@ -284,5 +284,9 @@ auto absMax(F a, F b) {
return std::fabs(a) > std::fabs(b) ? a : b;
}
uint16_t floatToHalf(float fval);
float halfToFloat(uint16_t hval);
} // namespace mathutils
} // namespace cc
+2 -2
View File
@@ -3,6 +3,6 @@
"type": "github",
"owner": "cocos-creator",
"name": "engine-native-external",
"checkout": "v3.8.1-11"
"checkout": "v3.8.1-12"
}
}
}
@@ -22,6 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include <math.h>
#include <stdlib.h>
#include <vector>
#include "cocos/math/Math.h"
#include "cocos/math/MathUtil.h"
+3 -4
View File
@@ -675,7 +675,7 @@ class PlaneShape extends Shape {
function getConvexMesh (v) {
if (!jsbPhy.CACHE.convex[v._uuid]) {
const posArr = cc.physics.utils.shrinkPositions(v.readAttribute(0, 'a_position'));
const posArr = cc.physics.utils.shrinkPositions(v.renderingSubMeshes[0].geometricInfo.positions);
const world = cc.PhysicsSystem.instance.physicsWorld.impl;
const convex = { positions: new Float32Array(posArr), positionLength: posArr.length / 3 };
jsbPhy.CACHE.convex[v._uuid] = world.createConvex(convex);
@@ -685,9 +685,8 @@ function getConvexMesh (v) {
function getTriangleMesh (v) {
if (!jsbPhy.CACHE.trimesh[v._uuid]) {
const indArr = v.readIndices(0);
// const posArr = cc.physics.utils.shrinkPositions(v.readAttribute(0, 'a_position'));
const posArr = v.readAttribute(0, 'a_position');
const posArr = v.renderingSubMeshes[0].geometricInfo.positions;
const indArr = v.renderingSubMeshes[0].geometricInfo.indices;
const world = cc.PhysicsSystem.instance.physicsWorld.impl;
const trimesh = {
positions: new Float32Array(posArr),
+14
View File
@@ -109,6 +109,14 @@ jest.mock(
);
});
jest.mock('external:emscripten/meshopt/meshopt_decoder.wasm.js',
() => ({
__esModule: true,
default: function factory () { return Promise.resolve({}); },
}),
{ virtual: true, },
);
jest.mock(
'external:emscripten/physx/physx.release.asm.js',
() => jest.requireActual('../native/external/emscripten/physx/physx.release.asm.js'),
@@ -122,6 +130,12 @@ jest.mock(
{ virtual: true },
);
jest.mock(
'external:emscripten/meshopt/meshopt_decoder.asm.js',
() => jest.requireActual('../native/external/emscripten/meshopt/meshopt_decoder.asm.js'),
{ virtual: true },
);
jest.mock(
'external:emscripten/spine/spine.asm.js',
() => jest.requireActual('../native/external/emscripten/spine/spine.asm.js'),
+1
View File
@@ -36,6 +36,7 @@
"./native/external/emscripten/physx/physx",
"./native/external/emscripten/webgpu/webgpu",
"./native/external/emscripten/spine/spine",
"./native/external/emscripten/meshopt/meshopt_decoder",
"./native/external/emscripten/box2d/box2d",
// pal