mson-three/src/cli.ts

89 lines
2.5 KiB
TypeScript

import { resolve } from 'path';
import { ModelStore, MsonEvaluate } from './mson';
import { fillStoreFromFilesystem, saveGeometry, saveModel } from './node';
import { ThreeBuilder } from './three';
import { MeshStandardMaterial } from 'three';
import { Command } from 'commander';
import { saveGLTF } from './node';
interface CliOptions {
format: string;
evaluated?: boolean;
store: string;
target: string;
}
const store = new ModelStore();
const evaluate = new MsonEvaluate(store);
const exportModel = async (model: string, options: CliOptions) => {
console.log(`\nStarting to evaluate model ${model}`);
console.log(` ... Evaluating Mson model`);
const evaluated = evaluate.evaluateModel(model);
console.log(` ... Building geometry`);
const mat = new MeshStandardMaterial();
const builder = new ThreeBuilder(mat);
const geometry = builder.buildGeometry(evaluated);
const outputName = model.replace(/[:\/]/g, '-');
console.log(`Saving as ${outputName}.${options.format}`);
const outputs = resolve(process.cwd(), options.target || 'outputs');
if (options.evaluated) {
await saveModel(outputs, outputName, evaluated);
}
switch (options.format) {
case 'json':
await saveGeometry(outputs, outputName, geometry);
break;
case 'gltf':
case 'glb':
await saveGLTF(outputs, outputName, geometry, options.format === 'glb');
break;
default:
throw new Error(`Unexpected format ${options.format}`);
}
};
const program = new Command();
program
.name('mson-three')
.description('Convert Mson models to THREE.js models (and others)')
.version('1.0.0');
program
.command('export')
.description('Export a Mson model')
.argument('models...', 'Model(s) to export')
.option(
'-f, --format <name>',
'Output format, one of: json, gltf, glb',
'json',
)
.option('-e, --evaluated', 'Save the evaluated final Mson json file as well')
.option('-s, --store <path>', 'Path containing Mson models', 'inputs')
.option('-t, --target <path>', 'Path to place outputs into', 'outputs')
.action(async (models: string[], options: CliOptions) => {
console.log(` ... Reading Mson resources`);
await fillStoreFromFilesystem(
store,
resolve(process.cwd(), options.store || 'inputs'),
);
for (const model of models) {
try {
await exportModel(model, options);
} catch (error: any) {
console.error(
` !!! Model "${model}" failed: ${error.message}`,
error.stack,
);
}
}
});
program.parse();