npm.io
1.1.4 • Published 1 month ago

mmd-parser

Licence
MIT
Version
1.1.4
Deps
0
Size
629 kB
Vulns
0
Weekly
0
Stars
56

MMD Parser

mmd-parser parses MMD ArrayBuffer/Strings and generates Object.

Contributing

See the development flow for Issue authoring, build and test commands, and PR preparation, and the review guidelines for review, merge, and Issue closure guidance for contributors and AI agents. Use the test and CI performance principles when choosing validation or adding coverage. See the release procedure for preparing a release, then running npm publish from a clean, updated master checkout. npm builds and validates the package automatically; authentication and post-publication Git tagging remain separate maintainer actions.

UI/UX

For this parser library, apply these principles to existing commands, parser and console messages, documentation and browser examples, and any future graphical interface.

  1. Keep it simple. Show only necessary information and actions; avoid unnecessary UI elements.
  2. Show, don't tell. Prefer layout, spacing and visual hierarchy over explanatory labels or prose to communicate structure.
  3. Intuitive and predictable. Keep appearance and behavior consistent with user expectations; don't interrupt the user's work.

Keep necessary control labels, accessible names, error messages, and information needed to use the interface. Simplification must preserve meaningful consent, destructive-action safeguards, necessary warnings, and necessary user decisions.

Browser

How to use
<script src="./build/mmdparser.js"></script>
<script>
  var parser = new MMDParser.Parser();

  function load (url, responseType, mimeType, onLoad, onProgress, onError) {
    var request = new XMLHttpRequest();
    request.open('GET', url, true);
    request.addEventListener('load', function (event) {
      var response = event.target.response;
      if (this.status === 200) {
        onLoad(response);
      } else if (this.status === 0) {
        console.warn('HTTP Status 0 received.');
        onLoad(response);
      } else {
        console.warn('HTTP Status ' + this.status + ' received.');
        onError(event);
      }
    }, false);
    if (onProgress !== undefined) request.addEventListener('progress', onProgress, false);
    if (onError !== undefined) request.addEventListener('error', onError, false);
    request.responseType = responseType;
    if (mimeType !== undefined) request.overrideMimeType(mimeType)
    request.send(null);
    console.log('downloading: ' + url);
  }

  function testPmd () {
    console.log('PMD parse test');
    load(
      'https://raw.githubusercontent.com/mrdoob/three.js/2898f5b1ba10b1e94174c0a62d072f5f7b80442c/examples/models/mmd/miku/miku_v2.pmd',
      'arraybuffer',
      undefined,
      function (buffer) {
        var pmd = parser.parsePmd(buffer);
        console.log(pmd);
      }
    );
  }

  testPmd();
</script>
methods
  • MMDParser.Parser
    • parsePmd(buffer, leftToRight)
    • parsePmx(buffer, leftToRight)
    • parseVmd(buffer, leftToRight)
    • parseVpd(text, leftToRight)
    • mergeVmds(vmds)
    • leftToRightModel(model)
    • leftToRightVmd(vmd)
    • leftToRightVpd(vpd)

NPM

PMX version support

parsePmx() accepts the exact float32 encodings of PMX 2.0 and 2.1. The metadata.version value retains the number read from the file: 2 for 2.0 and Math.fround(2.1) (2.0999999046325684) for 2.1. Other versions, including neighboring float32 values and nonfinite values, are rejected.

Accepting the PMX 2.1 header allows parsing structures shared with PMX 2.0; it does not provide full PMX 2.1 support. QDEF (skinning type 4), flip/impulse morphs (types 9/10), soft bodies, and point/line drawing remain unsupported. The parser stops after joints and does not read or validate a trailing PMX 2.1 soft-body section. The generated 2.1 regression fixture includes a zero soft-body count, and its assertions cover only the common sections. Successful parsing of this fixture does not establish support for 2.1-only payloads.

How to install
$ npm install mmd-parser
How to build
$ npm install
$ npm run build-uglify
$ npm run typecheck
$ npm run test:offline

The maintained source is index.ts and src/*.ts. TypeScript runs with strict and noUncheckedIndexedAccess; npm run typecheck checks the source and compile-only public type contracts. npm run build compiles to an ignored .typescript-tmp/compiled/ directory, bundles the UMD, browser ES module, and native Node ESM outputs, and writes declarations to build/types/. build-uglify also regenerates the minified browser bundle. npm run dev watches TypeScript and rebuilds the bundles and declarations after each successful compilation.

The offline tests use small synthetic PMD, PMX, VMD, and VPD fixtures with assertions against all four rebuilt bundles and a browser global smoke check. They cover the parser's currently supported sections; they do not establish support for additional PMX features. npm test runs the same offline suite, including exact PMX 2.0/2.1 version recognition and rejection of invalid versions. npm run test:samples retains the original optional sample smoke script, which downloads real PMD, VMD, and VPD samples from raw.githubusercontent.com, pinned to Three.js r171 commit 2898f5b1ba10b1e94174c0a62d072f5f7b80442c, as in three-mmd-loader. It requires network access and does not exercise PMX. npm run all runs the build, type checks, and offline tests in sequence.

After building, npm run test:package packs and inspects the npm artifact, installs it in a temporary consumer outside the repository, and checks CommonJS and native Node ESM runtime exports and strict TypeScript imports from mmd-parser with node, node16, nodenext, and bundler resolution. Only runtime bundles, declarations, package metadata, the README, and the license are distributed. The validator packs the completed build with lifecycle scripts disabled, so it can also run safely inside prepublishOnly. npm publish runs the build, type checks, offline tests, and package consumer checks before publication; prepack builds all bundles and declarations for both publication and standalone npm pack.

How to load

ES modules (including native Node ESM):

import { MMDParser, Parser, CharsetEncoder } from 'mmd-parser';

const parser = new Parser(); // also new MMDParser.Parser()

CommonJS:

const { MMDParser, Parser, CharsetEncoder } = require('mmd-parser');

const parser = new Parser();

The package's conditional exports select the native .mjs bundle for imports and the UMD/CommonJS bundle for require(). Package-root imports do not require an internal build/ path or the legacy jsnext:main field. The existing main and jsnext:main entries remain for older tools.

For direct browser loading, build/mmdparser.js and build/mmdparser.min.js remain UMD script bundles, and build/mmdparser.module.js remains an ES module bundle for <script type="module">. These bundle subpaths remain exported for tools that resolve them through the package.

TypeScript

The existing exports and runtime methods are unchanged. Declarations are resolved through conditional types exports for ESM and CommonJS, with the top-level types entry retained for older TypeScript resolution. Parser results and nested records can be imported as types:

import { MMDParser, Parser, CharsetEncoder } from 'mmd-parser';
import type { Pmd, Pmx, Vmd, Vpd, Vector3 } from 'mmd-parser';

const parser = new Parser(); // also new MMDParser.Parser()
const model: Pmd = parser.parsePmd(buffer, true); // buffer is an ArrayBuffer
const position: Vector3 | undefined = model.vertices[0]?.position;

The types describe existing runtime behavior: English PMD fields are optional, merged VMD metadata omits magic, and coordinate state is left or right. PMX skinning and supported morphs use variant records and fixed tuples. Skinning types are BDEF1 (0), BDEF2 (1), BDEF4 (2), and SDEF (3). SDEF exposes two bone indices, two weights, and the three-component skinC, skinR0, and skinR1 vectors. This corrects the earlier SDEF type 1 fallback; consumers should use vertex.type === 3 to access SDEF data. These vectors retain their original parsed values, without shader-specific corrections. parsePmx(buffer, true) and leftToRightModel negate their Z components along with vertex positions and normals; converting an already right-handed model has no effect. PMX bone morphs (type === 2) retain { index, position, rotation } elements. Right-handed conversion negates translation Z and quaternion X/Y, preserving quaternion Z/W, as for VMD bone motions and VPD poses. Parsing with conversion omitted or false preserves the original values. Group references and UV/material morph payloads remain unchanged. Unsupported morph types retain empty element arrays. Existing PMX text decoding is unchanged; see the version support and feature limitations above.

The sample assets have separate terms and are not covered by this package's MIT license. Consult the pinned Three.js asset license summary and each author's original archive and notices before using them. Downloading these samples does not grant redistribution or commercial-use rights.

  • Miku v2 model: bundled MikuMikuDance model (MMD / Yu Higuchi), modeled by Animasa; character Crypton Future Media. Model notice.
  • WAVEFILE dance: hino. Motion notice.
  • Shooting poses: KEITEL. Pose notice.

You are allowed to use Crypton's Vocaloid(Hatsune Miku, Kagamine Rin, and so on) stuffs (MMD models, songs, and so on) only if you follow the guideline set by Crypton Future Media, INC. for the usage of its characters.

For detail, see http://piapro.net/en_for_creators.html