function getObjectBody(mqoText, startIndex) {
    var braceStart = mqoText.indexOf("{", startIndex);
    if (braceStart === -1) return null;

    var depth = 1;
    var i = braceStart + 1;
    while (i < mqoText.length && depth > 0) {
        var ch = mqoText.charAt(i);
        if (ch === "{") depth++;
        else if (ch === "}") depth--;
        i++;
    }
    if (depth !== 0) return null; // 沒有正確配對

    return mqoText.substring(braceStart + 1, i - 1);
}

function parseMqoObject(mqoText) {
    var objects = {};
    var nameRe = /Object\s+"([^"]+)"/g;
    var match;

    while ((match = nameRe.exec(mqoText)) !== null) {
      var name = match[1];
      var body = getObjectBody(mqoText, match.index);
      if (!body) {
          console.log("Object:", name, "body not found");
          continue;
      }
      // 在這裡解析 vertex / face
    }
    while ((match = nameRe.exec(mqoText)) !== null) {
        var name = match[1];
        var body = getObjectBody(mqoText, match.index);
        if (!body) continue;

        // 抓 vertex block
        var vertices = [];
        var vertexRe = /vertex\s+(\d+)\s*{([^}]*)}/i;
        var vertexMatch = vertexRe.exec(body);
        if (vertexMatch) {
            var expectedCount = parseInt(vertexMatch[1], 10);
            var allNums = vertexMatch[2].trim().split(/\s+/).map(parseFloat).filter(n => !isNaN(n));
            for (var i = 0; i < expectedCount; i++) {
                vertices.push([
                    allNums[i * 3],
                    allNums[i * 3 + 1],
                    allNums[i * 3 + 2]
                ]);
            }
        }

        // 抓 face block
        var face = null;
        var faceRe = /face\s+\d+\s*{([^}]*)}/i;
        var faceMatch = faceRe.exec(body);
        if (faceMatch) {
            var fLines = faceMatch[1].split(/\r?\n|\r/);
            for (var fLine of fLines) {
                fLine = fLine.trim();
                if (!fLine) continue;
                var vMatch = fLine.match(/V\(([^)]+)\)/i);
                var uvMatch = fLine.match(/UV\(([^)]+)\)/i);
                if (vMatch) {
                    var Vnums = vMatch[1].trim().split(/\s+/).map(Number);
                    var uvNums = uvMatch ? uvMatch[1].trim().split(/\s+/).map(Number) : [];
                    face = { vertexCount: Vnums.length, V: Vnums, uv: uvNums };
                    break;
                }
            }
        }

        console.log("Object:", name, "vertex count:", vertices.length);
        objects[name] = { vertex: vertices, face: face };
    }

    return objects;
}
