198 lines
14 KiB
JavaScript
198 lines
14 KiB
JavaScript
// Мини-библиотека: модель из кубов в студах → .bbmodel (Generic), Bedrock geo.json (для импорта в Blockbench) и палитра PNG.
|
|
// Оси как в Blockbench: Y вверх, фасад смотрит в −Z. 1 студ = 16 px.
|
|
const fs = require('fs');
|
|
const zlib = require('zlib');
|
|
const crypto = require('crypto');
|
|
|
|
const PX = 16;
|
|
const r3 = v => Math.round(v * 1000) / 1000;
|
|
|
|
class Model {
|
|
constructor(name) { this.name = name; this.colors = []; this.colorIdx = {}; this.groups = []; this.cubes = []; this.cur = null; }
|
|
color(key, rgb) { if (!(key in this.colorIdx)) { this.colorIdx[key] = this.colors.length; this.colors.push(rgb); } return key; }
|
|
group(name, parent = null) { if (!this.groups.find(g => g.name === name)) this.groups.push({ name, parent, uuid: crypto.randomUUID() }); this.cur = name; return name; }
|
|
// box(имя, цвет, [x0,y0,z0], [x1,y1,z1], {rot:[x,y,z], pivot:[x,y,z]}) в студах
|
|
box(name, col, a, b, o = {}) {
|
|
if (!(col in this.colorIdx)) throw new Error('no color ' + col);
|
|
const from = [0, 1, 2].map(i => Math.min(a[i], b[i])), to = [0, 1, 2].map(i => Math.max(a[i], b[i]));
|
|
const c = { name, col, group: o.group || this.cur, from, to, rot: o.rot || [0, 0, 0], pivot: o.pivot || [0, 0, 0] };
|
|
this.cubes.push(c); return c;
|
|
}
|
|
// куб по центру и полуразмерам
|
|
cbox(name, col, c, h, o) { return this.box(name, col, [c[0] - h[0], c[1] - h[1], c[2] - h[2]], [c[0] + h[0], c[1] + h[1], c[2] + h[2]], o); }
|
|
|
|
cellUV(col) { const i = this.colorIdx[col], cx = i % 8, cy = Math.floor(i / 8); return [cx * 8 + 1, cy * 8 + 1, cx * 8 + 7, cy * 8 + 7]; }
|
|
|
|
png() {
|
|
const W = 64, H = 64, raw = Buffer.alloc((W * 4 + 1) * H);
|
|
for (let y = 0; y < H; y++) {
|
|
raw[y * (W * 4 + 1)] = 0;
|
|
for (let x = 0; x < W; x++) {
|
|
const i = Math.floor(y / 8) * 8 + Math.floor(x / 8), c = this.colors[i] || [255, 0, 255], p = y * (W * 4 + 1) + 1 + x * 4;
|
|
raw[p] = c[0]; raw[p + 1] = c[1]; raw[p + 2] = c[2]; raw[p + 3] = 255;
|
|
}
|
|
}
|
|
const crcT = []; for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; crcT[n] = c >>> 0; }
|
|
const crc = b => { let c = 0xffffffff; for (const x of b) c = crcT[(c ^ x) & 255] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; };
|
|
const chunk = (t, d) => { const l = Buffer.alloc(4); l.writeUInt32BE(d.length); const td = Buffer.concat([Buffer.from(t), d]); const cb = Buffer.alloc(4); cb.writeUInt32BE(crc(td)); return Buffer.concat([l, td, cb]); };
|
|
const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(W, 0); ihdr.writeUInt32BE(H, 4); ihdr[8] = 8; ihdr[9] = 6;
|
|
return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]);
|
|
}
|
|
|
|
write(dir, scratch) {
|
|
const png = this.png(), palPath = `${dir}\\${this.name}_palette.png`;
|
|
fs.writeFileSync(palPath, png);
|
|
// .bbmodel
|
|
const elements = this.cubes.map(c => {
|
|
const uv = this.cellUV(c.col), faces = {};
|
|
for (const f of ['north', 'east', 'south', 'west', 'up', 'down']) faces[f] = { uv, texture: 0 };
|
|
c.uuid = crypto.randomUUID();
|
|
const e = { name: c.name, box_uv: false, render_order: 'default', locked: false, export: true, scope: 0, allow_mirror_modeling: true,
|
|
from: c.from.map(v => r3(v * PX)), to: c.to.map(v => r3(v * PX)), autouv: 0, color: 0, origin: c.pivot.map(v => r3(v * PX)), faces, type: 'cube', uuid: c.uuid };
|
|
if (c.rot.some(v => v)) e.rotation = c.rot;
|
|
return e;
|
|
});
|
|
const groups = this.groups.map(g => ({ name: g.name, uuid: g.uuid, export: true, locked: false, scope: 0, selected: false, visibility: true, origin: [0, 0, 0], rotation: [0, 0, 0], color: 0, children: [], reset: false, shade: true, mirror_uv: false, autouv: 0, isOpen: false }));
|
|
const node = g => ({ uuid: g.uuid, isOpen: false, children: [...this.groups.filter(x => x.parent === g.name).map(node), ...this.cubes.filter(c => c.group === g.name).map(c => c.uuid)] });
|
|
const outliner = [...this.groups.filter(g => !g.parent).map(node), ...this.cubes.filter(c => !c.group).map(c => c.uuid)];
|
|
const bb = { meta: { format_version: '5.0', model_format: 'free', box_uv: false }, name: this.name, model_identifier: '', visible_box: [1, 1, 0], variable_placeholders: '', variable_placeholder_buttons: [], timeline_setups: [], unhandled_root_fields: {},
|
|
resolution: { width: 64, height: 64 }, elements, groups, outliner,
|
|
textures: [{ name: `${this.name}_palette`, path: palPath, folder: '', namespace: '', id: '0', group: '', scope: 0, width: 64, height: 64, uv_width: 64, uv_height: 64, particle: false, use_as_default: false, layers_enabled: false, sync_to_project: '', file_format: 'png', render_mode: 'default', render_sides: 'auto', wrap_mode: 'limited', pbr_channel: 'color', visible: true, internal: true, saved: true, uuid: crypto.randomUUID(), source: 'data:image/png;base64,' + png.toString('base64') }] };
|
|
fs.writeFileSync(`${dir}\\${this.name}.bbmodel`, JSON.stringify(bb));
|
|
// Bedrock geo (X зеркалится при импорте в Blockbench)
|
|
const bones = this.groups.map(g => ({ name: g.name, ...(g.parent ? { parent: g.parent } : {}), pivot: [0, 0, 0],
|
|
cubes: this.cubes.filter(c => c.group === g.name).map(c => {
|
|
const uv = this.cellUV(c.col), fu = { uv: [uv[0], uv[1]], uv_size: [6, 6] };
|
|
const cube = { origin: [r3(-c.to[0] * PX), r3(c.from[1] * PX), r3(c.from[2] * PX)], size: [0, 1, 2].map(i => r3((c.to[i] - c.from[i]) * PX)),
|
|
uv: { north: fu, east: fu, south: fu, west: fu, up: fu, down: fu } };
|
|
if (c.rot.some(v => v)) { cube.pivot = [r3(-c.pivot[0] * PX), r3(c.pivot[1] * PX), r3(c.pivot[2] * PX)]; cube.rotation = [-c.rot[0], -c.rot[1], c.rot[2]]; }
|
|
return cube;
|
|
}) }));
|
|
const geo = { format_version: '1.12.0', 'minecraft:geometry': [{ description: { identifier: 'geometry.' + this.name, texture_width: 64, texture_height: 64, visible_bounds_width: 20, visible_bounds_height: 20, visible_bounds_offset: [0, 8, 0] }, bones }] };
|
|
fs.writeFileSync(`${scratch}\\${this.name}.geo.json`, JSON.stringify(geo));
|
|
// габариты
|
|
const mn = [1e9, 1e9, 1e9], mx = [-1e9, -1e9, -1e9];
|
|
for (const c of this.cubes) for (let i = 0; i < 3; i++) { mn[i] = Math.min(mn[i], c.from[i]); mx[i] = Math.max(mx[i], c.to[i]); }
|
|
console.log(`${this.name}: cubes ${this.cubes.length}, groups ${this.groups.length}, colors ${this.colors.length}, bounds ${mn.map(r3)} .. ${mx.map(r3)}`);
|
|
this.writeObj(dir);
|
|
}
|
|
|
|
// OBJ без Blockbench: 1 единица = 1 студ, поворот как в Blockbench (Rz·Ry·Rx вокруг pivot), группа = объект
|
|
writeObj(dir) {
|
|
const d2r = Math.PI / 180, v = [], vt = [], out = [`# lobby model ${this.name}`, `mtllib ${this.name}.mtl`];
|
|
const rot = (p, r, c) => {
|
|
let [x, y, z] = [p[0] - c[0], p[1] - c[1], p[2] - c[2]];
|
|
const [ax, ay, az] = r.map(a => a * d2r);
|
|
[y, z] = [y * Math.cos(ax) - z * Math.sin(ax), y * Math.sin(ax) + z * Math.cos(ax)];
|
|
[x, z] = [x * Math.cos(ay) + z * Math.sin(ay), -x * Math.sin(ay) + z * Math.cos(ay)];
|
|
[x, y] = [x * Math.cos(az) - y * Math.sin(az), x * Math.sin(az) + y * Math.cos(az)];
|
|
return [x + c[0], y + c[1], z + c[2]];
|
|
};
|
|
let vi = 0, ti = 0;
|
|
const faces = [[0, 1, 3, 2], [4, 6, 7, 5], [0, 4, 5, 1], [2, 3, 7, 6], [0, 2, 6, 4], [1, 5, 7, 3]];
|
|
for (const g of [...this.groups, { name: null }]) {
|
|
const cubes = this.cubes.filter(c => (c.group || null) === g.name);
|
|
if (!cubes.length) continue;
|
|
out.push(`o ${g.name || 'Root'}`, `usemtl palette`);
|
|
for (const c of cubes) {
|
|
const pts = [];
|
|
for (let i = 0; i < 8; i++) pts.push(rot([i & 4 ? c.to[0] : c.from[0], i & 2 ? c.to[1] : c.from[1], i & 1 ? c.to[2] : c.from[2]], c.rot, c.pivot));
|
|
for (const p of pts) out.push(`v ${p.map(r3).join(' ')}`);
|
|
const uv = this.cellUV(c.col); out.push(`vt ${r3((uv[0] + uv[2]) / 128)} ${r3(1 - (uv[1] + uv[3]) / 128)}`); ti++;
|
|
for (const f of faces) out.push('f ' + f.map(k => `${vi + k + 1}/${ti}`).join(' '));
|
|
vi += 8;
|
|
}
|
|
}
|
|
fs.writeFileSync(`${dir}\\${this.name}.obj`, out.join('\n') + '\n');
|
|
fs.writeFileSync(`${dir}\\${this.name}.mtl`, `newmtl palette\nKd 1 1 1\nmap_Kd ${this.name}_palette.png\n`);
|
|
}
|
|
}
|
|
|
|
// ---------- общие детали ----------
|
|
const AX = { x: 0, y: 1, z: 2 };
|
|
// Рыба-силуэт: ось длины a (голова в сторону dir), ширина w, толщина t. L — длина в студах.
|
|
function fish(m, name, c, L, { a = 'x', w = 'y', t = 'z', dir = 1, body, belly, fin, eye = 'fishEye', eyeSide = -1 } = {}) {
|
|
const A = AX[a], W = AX[w], T = AX[t];
|
|
const part = (nm, col, a0, a1, hw, ht, woff = 0, o) => {
|
|
const lo = [0, 0, 0], hi = [0, 0, 0];
|
|
const p0 = c[A] + dir * a0 * L, p1 = c[A] + dir * a1 * L;
|
|
lo[A] = Math.min(p0, p1); hi[A] = Math.max(p0, p1);
|
|
lo[W] = c[W] + (woff - hw) * L; hi[W] = c[W] + (woff + hw) * L;
|
|
lo[T] = c[T] - ht * L; hi[T] = c[T] + ht * L;
|
|
return m.box(`${name}_${nm}`, col, lo, hi, o);
|
|
};
|
|
part('Snout', body, 0.42, 0.5, 0.05, 0.05);
|
|
part('Head', body, 0.24, 0.42, 0.12, 0.07);
|
|
part('Body', body, -0.12, 0.24, 0.16, 0.08);
|
|
part('Belly', belly, -0.08, 0.28, 0.05, 0.085, -0.12);
|
|
part('Rear', body, -0.3, -0.12, 0.1, 0.065);
|
|
part('Stalk', body, -0.38, -0.3, 0.045, 0.045);
|
|
part('Dorsal', fin, -0.08, 0.14, 0.05, 0.03, 0.19);
|
|
part('Gill', fin, 0.22, 0.25, 0.11, 0.085);
|
|
// хвост-вилка: две лопасти, повернуты в плоскости a-w вокруг оси t
|
|
const piv = [0, 0, 0]; piv[A] = c[A] - dir * 0.37 * L; piv[W] = c[W]; piv[T] = c[T];
|
|
for (const s of [1, -1]) {
|
|
const rot = [0, 0, 0];
|
|
// знак угла: поворот вокруг оси T, чтобы лопасть уходила назад и в сторону s
|
|
const cyc = (T === 2) ? (A === 0 ? 1 : -1) : (T === 1 ? (A === 0 ? -1 : 1) : (A === 1 ? 1 : -1));
|
|
rot[T] = 35 * s * dir * cyc;
|
|
part('Tail' + (s > 0 ? 'A' : 'B'), fin, -0.62, -0.36, 0.045, 0.03, 0, { rot, pivot: piv });
|
|
}
|
|
// глаз на обеих сторонах толщины
|
|
for (const s of [1, -1]) {
|
|
const lo = [0, 0, 0], hi = [0, 0, 0];
|
|
const p = c[A] + dir * 0.36 * L; lo[A] = p - 0.025 * L; hi[A] = p + 0.025 * L;
|
|
lo[W] = c[W] + 0.02 * L; hi[W] = c[W] + 0.07 * L;
|
|
lo[T] = c[T] + s * 0.075 * L - 0.012; hi[T] = c[T] + s * 0.075 * L + 0.012;
|
|
m.box(`${name}_Eye`, eye, lo, hi);
|
|
}
|
|
}
|
|
|
|
// Бочка: восьмигранник из двух квадратов (0° и 45°), три пояса высоты, железные обручи
|
|
function barrel(m, name, cx, cz, y0, h, r, wood, wood2, band, lid) {
|
|
const sec = [[0, 0.22, 0.9], [0.22, 0.78, 1], [0.78, 1, 0.9]];
|
|
sec.forEach(([a, b, k], i) => {
|
|
const s = r * k * 0.83;
|
|
m.box(`${name}_S${i}`, i === 1 ? wood : wood2, [cx - s, y0 + a * h, cz - s], [cx + s, y0 + b * h, cz + s]);
|
|
m.box(`${name}_S${i}R`, i === 1 ? wood : wood2, [cx - s, y0 + a * h, cz - s], [cx + s, y0 + b * h, cz + s], { rot: [0, 45, 0], pivot: [cx, 0, cz] });
|
|
});
|
|
for (const yy of [0.15, 0.8]) {
|
|
const s = r * 0.83 * (yy < 0.5 ? 0.97 : 0.97) + 0.04, y = y0 + yy * h;
|
|
m.box(`${name}_Band`, band, [cx - s, y, cz - s], [cx + s, y + 0.12, cz + s]);
|
|
m.box(`${name}_BandR`, band, [cx - s, y, cz - s], [cx + s, y + 0.12, cz + s], { rot: [0, 45, 0], pivot: [cx, 0, cz] });
|
|
}
|
|
if (lid) { const s = r * 0.9 * 0.83 - 0.06; m.box(`${name}_Lid`, lid, [cx - s, y0 + h, cz - s], [cx + s, y0 + h + 0.04, cz + s]); m.box(`${name}_LidR`, lid, [cx - s, y0 + h, cz - s], [cx + s, y0 + h + 0.04, cz + s], { rot: [0, 45, 0], pivot: [cx, 0, cz] }); }
|
|
}
|
|
|
|
// Ящик из досок: каркас + доски по бокам
|
|
function crate(m, name, x0, y0, z0, x1, y1, z1, wood, frame, open = false) {
|
|
m.box(`${name}_Box`, wood, [x0 + 0.05, y0, z0 + 0.05], [x1 - 0.05, open ? y1 - 0.25 : y1 - 0.02, z1 - 0.05]);
|
|
const t = 0.12;
|
|
for (const [xa, za] of [[x0, z0], [x1 - t, z0], [x0, z1 - t], [x1 - t, z1 - t]]) m.box(`${name}_Post`, frame, [xa, y0, za], [xa + t, y1, za + t]);
|
|
for (const y of [y0, y1 - t]) {
|
|
m.box(`${name}_RailF`, frame, [x0, y, z0 - 0.02], [x1, y + t, z0 + t]);
|
|
m.box(`${name}_RailB`, frame, [x0, y, z1 - t], [x1, y + t, z1 + 0.02]);
|
|
m.box(`${name}_RailL`, frame, [x0 - 0.02, y, z0], [x0 + t, y + t, z1]);
|
|
m.box(`${name}_RailR`, frame, [x1 - t, y, z0], [x1 + 0.02, y + t, z1]);
|
|
}
|
|
// диагональ спереди
|
|
const w = x1 - x0, hgt = y1 - y0, len = Math.hypot(w, hgt) - 0.25, ang = Math.atan2(hgt, w) * 180 / Math.PI;
|
|
m.box(`${name}_Diag`, frame, [x0 + 0.08, y0 + 0.06, z0 - 0.03], [x0 + 0.08 + len, y0 + 0.16, z0 + 0.04], { rot: [0, 0, ang], pivot: [x0 + 0.08, y0 + 0.06, z0] });
|
|
}
|
|
|
|
// Фонарь на кронштейне от стойки (side = -1 слева, 1 справа)
|
|
function lantern(m, tag, px, y, z, side, cols) {
|
|
const { iron, glow, brass } = cols;
|
|
const x = px + side * 0.75;
|
|
m.box(`Lantern${tag}_Arm`, iron, [Math.min(px, x), y + 0.95, z - 0.05], [Math.max(px, x) + 0.05, y + 1.05, z + 0.05]);
|
|
m.box(`Lantern${tag}_Brace`, iron, [Math.min(px, px + side * 0.45), y + 0.6, z - 0.04], [Math.max(px, px + side * 0.45), y + 0.68, z + 0.04], { rot: [0, 0, side * 40], pivot: [px, y + 0.64, z] });
|
|
m.box(`Lantern${tag}_Hook`, iron, [x - 0.03, y + 0.7, z - 0.03], [x + 0.03, y + 0.95, z + 0.03]);
|
|
m.box(`Lantern${tag}_Cap`, brass, [x - 0.22, y + 0.6, z - 0.22], [x + 0.22, y + 0.7, z + 0.22]);
|
|
m.box(`Lantern${tag}_Roof`, iron, [x - 0.12, y + 0.7, z - 0.12], [x + 0.12, y + 0.78, z + 0.12]);
|
|
m.box(`Lantern${tag}_Glow`, glow, [x - 0.15, y + 0.05, z - 0.15], [x + 0.15, y + 0.6, z + 0.15]);
|
|
for (const [dx, dz] of [[-1, -1], [1, -1], [-1, 1], [1, 1]]) m.box(`Lantern${tag}_Bar`, iron, [x + dx * 0.18 - 0.03, y + 0.05, z + dz * 0.18 - 0.03], [x + dx * 0.18 + 0.03, y + 0.6, z + dz * 0.18 + 0.03]);
|
|
m.box(`Lantern${tag}_Base`, brass, [x - 0.22, y - 0.03, z - 0.22], [x + 0.22, y + 0.05, z + 0.22]);
|
|
}
|
|
|
|
module.exports = { Model, fish, barrel, crate, lantern };
|