MMDLoader.js 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037
  1. import {
  2. AddOperation,
  3. AnimationClip,
  4. Bone,
  5. BufferGeometry,
  6. Color,
  7. CustomBlending,
  8. DoubleSide,
  9. DstAlphaFactor,
  10. Euler,
  11. FileLoader,
  12. Float32BufferAttribute,
  13. FrontSide,
  14. Interpolant,
  15. Loader,
  16. LoaderUtils,
  17. MeshToonMaterial,
  18. MultiplyOperation,
  19. NearestFilter,
  20. NumberKeyframeTrack,
  21. OneMinusSrcAlphaFactor,
  22. Quaternion,
  23. QuaternionKeyframeTrack,
  24. RepeatWrapping,
  25. Skeleton,
  26. SkinnedMesh,
  27. SrcAlphaFactor,
  28. TextureLoader,
  29. Uint16BufferAttribute,
  30. Vector3,
  31. VectorKeyframeTrack
  32. } from '../../../build/three.module.js';
  33. import { TGALoader } from '../loaders/TGALoader.js';
  34. import { MMDParser } from '../libs/mmdparser.module.js';
  35. /**
  36. * Dependencies
  37. * - mmd-parser https://github.com/takahirox/mmd-parser
  38. * - TGALoader
  39. * - OutlineEffect
  40. *
  41. * MMDLoader creates Three.js Objects from MMD resources as
  42. * PMD, PMX, VMD, and VPD files.
  43. *
  44. * PMD/PMX is a model data format, VMD is a motion data format
  45. * VPD is a posing data format used in MMD(Miku Miku Dance).
  46. *
  47. * MMD official site
  48. * - https://sites.google.com/view/evpvp/
  49. *
  50. * PMD, VMD format (in Japanese)
  51. * - http://blog.goo.ne.jp/torisu_tetosuki/e/209ad341d3ece2b1b4df24abf619d6e4
  52. *
  53. * PMX format
  54. * - https://gist.github.com/felixjones/f8a06bd48f9da9a4539f
  55. *
  56. * TODO
  57. * - light motion in vmd support.
  58. * - SDEF support.
  59. * - uv/material/bone morphing support.
  60. * - more precise grant skinning support.
  61. * - shadow support.
  62. */
  63. /**
  64. * @param {THREE.LoadingManager} manager
  65. */
  66. class MMDLoader extends Loader {
  67. constructor( manager ) {
  68. super( manager );
  69. this.loader = new FileLoader( this.manager );
  70. this.parser = null; // lazy generation
  71. this.meshBuilder = new MeshBuilder( this.manager );
  72. this.animationBuilder = new AnimationBuilder();
  73. }
  74. /**
  75. * @param {string} animationPath
  76. * @return {MMDLoader}
  77. */
  78. setAnimationPath( animationPath ) {
  79. this.animationPath = animationPath;
  80. return this;
  81. }
  82. // Load MMD assets as Three.js Object
  83. /**
  84. * Loads Model file (.pmd or .pmx) as a SkinnedMesh.
  85. *
  86. * @param {string} url - url to Model(.pmd or .pmx) file
  87. * @param {function} onLoad
  88. * @param {function} onProgress
  89. * @param {function} onError
  90. */
  91. load( url, onLoad, onProgress, onError ) {
  92. const builder = this.meshBuilder.setCrossOrigin( this.crossOrigin );
  93. // resource path
  94. let resourcePath;
  95. if ( this.resourcePath !== '' ) {
  96. resourcePath = this.resourcePath;
  97. } else if ( this.path !== '' ) {
  98. resourcePath = this.path;
  99. } else {
  100. resourcePath = LoaderUtils.extractUrlBase( url );
  101. }
  102. const modelExtension = this._extractExtension( url ).toLowerCase();
  103. // Should I detect by seeing header?
  104. if ( modelExtension !== 'pmd' && modelExtension !== 'pmx' ) {
  105. if ( onError ) onError( new Error( 'THREE.MMDLoader: Unknown model file extension .' + modelExtension + '.' ) );
  106. return;
  107. }
  108. this[ modelExtension === 'pmd' ? 'loadPMD' : 'loadPMX' ]( url, function ( data ) {
  109. onLoad( builder.build( data, resourcePath, onProgress, onError ) );
  110. }, onProgress, onError );
  111. }
  112. /**
  113. * Loads Motion file(s) (.vmd) as a AnimationClip.
  114. * If two or more files are specified, they'll be merged.
  115. *
  116. * @param {string|Array<string>} url - url(s) to animation(.vmd) file(s)
  117. * @param {SkinnedMesh|THREE.Camera} object - tracks will be fitting to this object
  118. * @param {function} onLoad
  119. * @param {function} onProgress
  120. * @param {function} onError
  121. */
  122. loadAnimation( url, object, onLoad, onProgress, onError ) {
  123. const builder = this.animationBuilder;
  124. this.loadVMD( url, function ( vmd ) {
  125. onLoad( object.isCamera
  126. ? builder.buildCameraAnimation( vmd )
  127. : builder.build( vmd, object ) );
  128. }, onProgress, onError );
  129. }
  130. /**
  131. * Loads mode file and motion file(s) as an object containing
  132. * a SkinnedMesh and a AnimationClip.
  133. * Tracks of AnimationClip are fitting to the model.
  134. *
  135. * @param {string} modelUrl - url to Model(.pmd or .pmx) file
  136. * @param {string|Array{string}} vmdUrl - url(s) to animation(.vmd) file
  137. * @param {function} onLoad
  138. * @param {function} onProgress
  139. * @param {function} onError
  140. */
  141. loadWithAnimation( modelUrl, vmdUrl, onLoad, onProgress, onError ) {
  142. const scope = this;
  143. this.load( modelUrl, function ( mesh ) {
  144. scope.loadAnimation( vmdUrl, mesh, function ( animation ) {
  145. onLoad( {
  146. mesh: mesh,
  147. animation: animation
  148. } );
  149. }, onProgress, onError );
  150. }, onProgress, onError );
  151. }
  152. // Load MMD assets as Object data parsed by MMDParser
  153. /**
  154. * Loads .pmd file as an Object.
  155. *
  156. * @param {string} url - url to .pmd file
  157. * @param {function} onLoad
  158. * @param {function} onProgress
  159. * @param {function} onError
  160. */
  161. loadPMD( url, onLoad, onProgress, onError ) {
  162. const parser = this._getParser();
  163. this.loader
  164. .setMimeType( undefined )
  165. .setPath( this.path )
  166. .setResponseType( 'arraybuffer' )
  167. .setRequestHeader( this.requestHeader )
  168. .setWithCredentials( this.withCredentials )
  169. .load( url, function ( buffer ) {
  170. onLoad( parser.parsePmd( buffer, true ) );
  171. }, onProgress, onError );
  172. }
  173. /**
  174. * Loads .pmx file as an Object.
  175. *
  176. * @param {string} url - url to .pmx file
  177. * @param {function} onLoad
  178. * @param {function} onProgress
  179. * @param {function} onError
  180. */
  181. loadPMX( url, onLoad, onProgress, onError ) {
  182. const parser = this._getParser();
  183. this.loader
  184. .setMimeType( undefined )
  185. .setPath( this.path )
  186. .setResponseType( 'arraybuffer' )
  187. .setRequestHeader( this.requestHeader )
  188. .setWithCredentials( this.withCredentials )
  189. .load( url, function ( buffer ) {
  190. onLoad( parser.parsePmx( buffer, true ) );
  191. }, onProgress, onError );
  192. }
  193. /**
  194. * Loads .vmd file as an Object. If two or more files are specified
  195. * they'll be merged.
  196. *
  197. * @param {string|Array<string>} url - url(s) to .vmd file(s)
  198. * @param {function} onLoad
  199. * @param {function} onProgress
  200. * @param {function} onError
  201. */
  202. loadVMD( url, onLoad, onProgress, onError ) {
  203. const urls = Array.isArray( url ) ? url : [ url ];
  204. const vmds = [];
  205. const vmdNum = urls.length;
  206. const parser = this._getParser();
  207. this.loader
  208. .setMimeType( undefined )
  209. .setPath( this.animationPath )
  210. .setResponseType( 'arraybuffer' )
  211. .setRequestHeader( this.requestHeader )
  212. .setWithCredentials( this.withCredentials );
  213. for ( let i = 0, il = urls.length; i < il; i ++ ) {
  214. this.loader.load( urls[ i ], function ( buffer ) {
  215. vmds.push( parser.parseVmd( buffer, true ) );
  216. if ( vmds.length === vmdNum ) onLoad( parser.mergeVmds( vmds ) );
  217. }, onProgress, onError );
  218. }
  219. }
  220. /**
  221. * Loads .vpd file as an Object.
  222. *
  223. * @param {string} url - url to .vpd file
  224. * @param {boolean} isUnicode
  225. * @param {function} onLoad
  226. * @param {function} onProgress
  227. * @param {function} onError
  228. */
  229. loadVPD( url, isUnicode, onLoad, onProgress, onError ) {
  230. const parser = this._getParser();
  231. this.loader
  232. .setMimeType( isUnicode ? undefined : 'text/plain; charset=shift_jis' )
  233. .setPath( this.animationPath )
  234. .setResponseType( 'text' )
  235. .setRequestHeader( this.requestHeader )
  236. .setWithCredentials( this.withCredentials )
  237. .load( url, function ( text ) {
  238. onLoad( parser.parseVpd( text, true ) );
  239. }, onProgress, onError );
  240. }
  241. // private methods
  242. _extractExtension( url ) {
  243. const index = url.lastIndexOf( '.' );
  244. return index < 0 ? '' : url.slice( index + 1 );
  245. }
  246. _getParser() {
  247. if ( this.parser === null ) {
  248. if ( typeof MMDParser === 'undefined' ) {
  249. throw new Error( 'THREE.MMDLoader: Import MMDParser https://github.com/takahirox/mmd-parser' );
  250. }
  251. this.parser = new MMDParser.Parser(); // eslint-disable-line no-undef
  252. }
  253. return this.parser;
  254. }
  255. }
  256. // Utilities
  257. /*
  258. * base64 encoded defalut toon textures toon00.bmp - toon10.bmp.
  259. * We don't need to request external toon image files.
  260. * This idea is from http://www20.atpages.jp/katwat/three.js_r58/examples/mytest37/mmd.three.js
  261. */
  262. const DEFAULT_TOON_TEXTURES = [
  263. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=',
  264. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAN0lEQVRYR+3WQREAMBACsZ5/bWiiMvgEBTt5cW37hjsBBAgQIECAwFwgyfYPCCBAgAABAgTWAh8aBHZBl14e8wAAAABJRU5ErkJggg==',
  265. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAOUlEQVRYR+3WMREAMAwDsYY/yoDI7MLwIiP40+RJklfcCCBAgAABAgTqArfb/QMCCBAgQIAAgbbAB3z/e0F3js2cAAAAAElFTkSuQmCC',
  266. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAN0lEQVRYR+3WQREAMBACsZ5/B5ilMvgEBTt5cW37hjsBBAgQIECAwFwgyfYPCCBAgAABAgTWAh81dWyx0gFwKAAAAABJRU5ErkJggg==',
  267. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAOklEQVRYR+3WoREAMAwDsWb/UQtCy9wxTOQJ/oQ8SXKKGwEECBAgQIBAXeDt7f4BAQQIECBAgEBb4AOz8Hzx7WLY4wAAAABJRU5ErkJggg==',
  268. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABPUlEQVRYR+1XwW7CMAy1+f9fZOMysSEOEweEOPRNdm3HbdOyIhAcklPrOs/PLy9RygBALxzcCDQFmgJNgaZAU6Ap0BR4PwX8gsRMVLssMRH5HcpzJEaWL7EVg9F1IHRlyqQohgVr4FGUlUcMJSjcUlDw0zvjeun70cLWmneoyf7NgBTQSniBTQQSuJAZsOnnaczjIMb5hCiuHKxokCrJfVnrctyZL0PkJAJe1HMil4nxeyi3Ypfn1kX51jpPvo/JeCNC4PhVdHdJw2XjBR8brF8PEIhNVn12AgP7uHsTBguBn53MUZCqv7Lp07Pn5k1Ro+uWmUNn7D+M57rtk7aG0Vo73xyF/fbFf0bPJjDXngnGocDTdFhygZjwUQrMNrDcmZlQT50VJ/g/UwNyHpu778+yW+/ksOz/BFo54P4AsUXMfRq7XWsAAAAASUVORK5CYII=',
  269. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACMElEQVRYR+2Xv4pTQRTGf2dubhLdICiii2KnYKHVolhauKWPoGAnNr6BD6CvIVaihYuI2i1ia0BY0MZGRHQXjZj/mSPnnskfNWiWZUlzJ5k7M2cm833nO5Mziej2DWWJRUoCpQKlAntSQCqgw39/iUWAGmh37jrRnVsKlgpiqmkoGVABA7E57fvY+pJDdgKqF6HzFCSADkDq+F6AHABtQ+UMVE5D7zXod7fFNhTEckTbj5XQgHzNN+5tQvc5NG7C6BNkp6D3EmpXHDR+dQAjFLchW3VS9rlw3JBh+B7ys5Cf9z0GW1C/7P32AyBAOAz1q4jGliIH3YPuBnSfQX4OGreTIgEYQb/pBDtPnEQ4CivXYPAWBk13oHrB54yA9QuSn2H4AcKRpEILDt0BUzj+RLR1V5EqjD66NPRBVpLcQwjHoHYJOhsQv6U4mnzmrIXJCFr4LDwm/xBUoboG9XX4cc9VKdYoSA2yk5NQLJaKDUjTBoveG3Z2TElTxwjNK4M3LEZgUdDdruvcXzKBpStgp2NPiWi3ks9ZXxIoFVi+AvHLdc9TqtjL3/aYjpPlrzOcEnK62Szhimdd7xX232zFDTgtxezOu3WNMRLjiKgjtOhHVMd1loynVHvOgjuIIJMaELEqhJAV/RCSLbWTcfPFakFgFlALTRRvx+ok6Hlp/Q+v3fmx90bMyUzaEAhmM3KvHlXTL5DxnbGf/1M8RNNACLL5MNtPxP/mypJAqcDSFfgFhpYqWUzhTEAAAAAASUVORK5CYII=',
  270. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=',
  271. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=',
  272. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=',
  273. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII='
  274. ];
  275. // Builders. They build Three.js object from Object data parsed by MMDParser.
  276. /**
  277. * @param {THREE.LoadingManager} manager
  278. */
  279. class MeshBuilder {
  280. constructor( manager ) {
  281. this.crossOrigin = 'anonymous';
  282. this.geometryBuilder = new GeometryBuilder();
  283. this.materialBuilder = new MaterialBuilder( manager );
  284. }
  285. /**
  286. * @param {string} crossOrigin
  287. * @return {MeshBuilder}
  288. */
  289. setCrossOrigin( crossOrigin ) {
  290. this.crossOrigin = crossOrigin;
  291. return this;
  292. }
  293. /**
  294. * @param {Object} data - parsed PMD/PMX data
  295. * @param {string} resourcePath
  296. * @param {function} onProgress
  297. * @param {function} onError
  298. * @return {SkinnedMesh}
  299. */
  300. build( data, resourcePath, onProgress, onError ) {
  301. const geometry = this.geometryBuilder.build( data );
  302. const material = this.materialBuilder
  303. .setCrossOrigin( this.crossOrigin )
  304. .setResourcePath( resourcePath )
  305. .build( data, geometry, onProgress, onError );
  306. const mesh = new SkinnedMesh( geometry, material );
  307. const skeleton = new Skeleton( initBones( mesh ) );
  308. mesh.bind( skeleton );
  309. // console.log( mesh ); // for console debug
  310. return mesh;
  311. }
  312. }
  313. // TODO: Try to remove this function
  314. function initBones( mesh ) {
  315. const geometry = mesh.geometry;
  316. const bones = [];
  317. if ( geometry && geometry.bones !== undefined ) {
  318. // first, create array of 'Bone' objects from geometry data
  319. for ( let i = 0, il = geometry.bones.length; i < il; i ++ ) {
  320. const gbone = geometry.bones[ i ];
  321. // create new 'Bone' object
  322. const bone = new Bone();
  323. bones.push( bone );
  324. // apply values
  325. bone.name = gbone.name;
  326. bone.position.fromArray( gbone.pos );
  327. bone.quaternion.fromArray( gbone.rotq );
  328. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  329. }
  330. // second, create bone hierarchy
  331. for ( let i = 0, il = geometry.bones.length; i < il; i ++ ) {
  332. const gbone = geometry.bones[ i ];
  333. if ( ( gbone.parent !== - 1 ) && ( gbone.parent !== null ) && ( bones[ gbone.parent ] !== undefined ) ) {
  334. // subsequent bones in the hierarchy
  335. bones[ gbone.parent ].add( bones[ i ] );
  336. } else {
  337. // topmost bone, immediate child of the skinned mesh
  338. mesh.add( bones[ i ] );
  339. }
  340. }
  341. }
  342. // now the bones are part of the scene graph and children of the skinned mesh.
  343. // let's update the corresponding matrices
  344. mesh.updateMatrixWorld( true );
  345. return bones;
  346. }
  347. //
  348. class GeometryBuilder {
  349. /**
  350. * @param {Object} data - parsed PMD/PMX data
  351. * @return {BufferGeometry}
  352. */
  353. build( data ) {
  354. // for geometry
  355. const positions = [];
  356. const uvs = [];
  357. const normals = [];
  358. const indices = [];
  359. const groups = [];
  360. const bones = [];
  361. const skinIndices = [];
  362. const skinWeights = [];
  363. const morphTargets = [];
  364. const morphPositions = [];
  365. const iks = [];
  366. const grants = [];
  367. const rigidBodies = [];
  368. const constraints = [];
  369. // for work
  370. let offset = 0;
  371. const boneTypeTable = {};
  372. // positions, normals, uvs, skinIndices, skinWeights
  373. for ( let i = 0; i < data.metadata.vertexCount; i ++ ) {
  374. const v = data.vertices[ i ];
  375. for ( let j = 0, jl = v.position.length; j < jl; j ++ ) {
  376. positions.push( v.position[ j ] );
  377. }
  378. for ( let j = 0, jl = v.normal.length; j < jl; j ++ ) {
  379. normals.push( v.normal[ j ] );
  380. }
  381. for ( let j = 0, jl = v.uv.length; j < jl; j ++ ) {
  382. uvs.push( v.uv[ j ] );
  383. }
  384. for ( let j = 0; j < 4; j ++ ) {
  385. skinIndices.push( v.skinIndices.length - 1 >= j ? v.skinIndices[ j ] : 0.0 );
  386. }
  387. for ( let j = 0; j < 4; j ++ ) {
  388. skinWeights.push( v.skinWeights.length - 1 >= j ? v.skinWeights[ j ] : 0.0 );
  389. }
  390. }
  391. // indices
  392. for ( let i = 0; i < data.metadata.faceCount; i ++ ) {
  393. const face = data.faces[ i ];
  394. for ( let j = 0, jl = face.indices.length; j < jl; j ++ ) {
  395. indices.push( face.indices[ j ] );
  396. }
  397. }
  398. // groups
  399. for ( let i = 0; i < data.metadata.materialCount; i ++ ) {
  400. const material = data.materials[ i ];
  401. groups.push( {
  402. offset: offset * 3,
  403. count: material.faceCount * 3
  404. } );
  405. offset += material.faceCount;
  406. }
  407. // bones
  408. for ( let i = 0; i < data.metadata.rigidBodyCount; i ++ ) {
  409. const body = data.rigidBodies[ i ];
  410. let value = boneTypeTable[ body.boneIndex ];
  411. // keeps greater number if already value is set without any special reasons
  412. value = value === undefined ? body.type : Math.max( body.type, value );
  413. boneTypeTable[ body.boneIndex ] = value;
  414. }
  415. for ( let i = 0; i < data.metadata.boneCount; i ++ ) {
  416. const boneData = data.bones[ i ];
  417. const bone = {
  418. index: i,
  419. transformationClass: boneData.transformationClass,
  420. parent: boneData.parentIndex,
  421. name: boneData.name,
  422. pos: boneData.position.slice( 0, 3 ),
  423. rotq: [ 0, 0, 0, 1 ],
  424. scl: [ 1, 1, 1 ],
  425. rigidBodyType: boneTypeTable[ i ] !== undefined ? boneTypeTable[ i ] : - 1
  426. };
  427. if ( bone.parent !== - 1 ) {
  428. bone.pos[ 0 ] -= data.bones[ bone.parent ].position[ 0 ];
  429. bone.pos[ 1 ] -= data.bones[ bone.parent ].position[ 1 ];
  430. bone.pos[ 2 ] -= data.bones[ bone.parent ].position[ 2 ];
  431. }
  432. bones.push( bone );
  433. }
  434. // iks
  435. // TODO: remove duplicated codes between PMD and PMX
  436. if ( data.metadata.format === 'pmd' ) {
  437. for ( let i = 0; i < data.metadata.ikCount; i ++ ) {
  438. const ik = data.iks[ i ];
  439. const param = {
  440. target: ik.target,
  441. effector: ik.effector,
  442. iteration: ik.iteration,
  443. maxAngle: ik.maxAngle * 4,
  444. links: []
  445. };
  446. for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) {
  447. const link = {};
  448. link.index = ik.links[ j ].index;
  449. link.enabled = true;
  450. if ( data.bones[ link.index ].name.indexOf( 'ひざ' ) >= 0 ) {
  451. link.limitation = new Vector3( 1.0, 0.0, 0.0 );
  452. }
  453. param.links.push( link );
  454. }
  455. iks.push( param );
  456. }
  457. } else {
  458. for ( let i = 0; i < data.metadata.boneCount; i ++ ) {
  459. const ik = data.bones[ i ].ik;
  460. if ( ik === undefined ) continue;
  461. const param = {
  462. target: i,
  463. effector: ik.effector,
  464. iteration: ik.iteration,
  465. maxAngle: ik.maxAngle,
  466. links: []
  467. };
  468. for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) {
  469. const link = {};
  470. link.index = ik.links[ j ].index;
  471. link.enabled = true;
  472. if ( ik.links[ j ].angleLimitation === 1 ) {
  473. // Revert if rotationMin/Max doesn't work well
  474. // link.limitation = new Vector3( 1.0, 0.0, 0.0 );
  475. const rotationMin = ik.links[ j ].lowerLimitationAngle;
  476. const rotationMax = ik.links[ j ].upperLimitationAngle;
  477. // Convert Left to Right coordinate by myself because
  478. // MMDParser doesn't convert. It's a MMDParser's bug
  479. const tmp1 = - rotationMax[ 0 ];
  480. const tmp2 = - rotationMax[ 1 ];
  481. rotationMax[ 0 ] = - rotationMin[ 0 ];
  482. rotationMax[ 1 ] = - rotationMin[ 1 ];
  483. rotationMin[ 0 ] = tmp1;
  484. rotationMin[ 1 ] = tmp2;
  485. link.rotationMin = new Vector3().fromArray( rotationMin );
  486. link.rotationMax = new Vector3().fromArray( rotationMax );
  487. }
  488. param.links.push( link );
  489. }
  490. iks.push( param );
  491. // Save the reference even from bone data for efficiently
  492. // simulating PMX animation system
  493. bones[ i ].ik = param;
  494. }
  495. }
  496. // grants
  497. if ( data.metadata.format === 'pmx' ) {
  498. // bone index -> grant entry map
  499. const grantEntryMap = {};
  500. for ( let i = 0; i < data.metadata.boneCount; i ++ ) {
  501. const boneData = data.bones[ i ];
  502. const grant = boneData.grant;
  503. if ( grant === undefined ) continue;
  504. const param = {
  505. index: i,
  506. parentIndex: grant.parentIndex,
  507. ratio: grant.ratio,
  508. isLocal: grant.isLocal,
  509. affectRotation: grant.affectRotation,
  510. affectPosition: grant.affectPosition,
  511. transformationClass: boneData.transformationClass
  512. };
  513. grantEntryMap[ i ] = { parent: null, children: [], param: param, visited: false };
  514. }
  515. const rootEntry = { parent: null, children: [], param: null, visited: false };
  516. // Build a tree representing grant hierarchy
  517. for ( const boneIndex in grantEntryMap ) {
  518. const grantEntry = grantEntryMap[ boneIndex ];
  519. const parentGrantEntry = grantEntryMap[ grantEntry.parentIndex ] || rootEntry;
  520. grantEntry.parent = parentGrantEntry;
  521. parentGrantEntry.children.push( grantEntry );
  522. }
  523. // Sort grant parameters from parents to children because
  524. // grant uses parent's transform that parent's grant is already applied
  525. // so grant should be applied in order from parents to children
  526. function traverse( entry ) {
  527. if ( entry.param ) {
  528. grants.push( entry.param );
  529. // Save the reference even from bone data for efficiently
  530. // simulating PMX animation system
  531. bones[ entry.param.index ].grant = entry.param;
  532. }
  533. entry.visited = true;
  534. for ( let i = 0, il = entry.children.length; i < il; i ++ ) {
  535. const child = entry.children[ i ];
  536. // Cut off a loop if exists. (Is a grant loop invalid?)
  537. if ( ! child.visited ) traverse( child );
  538. }
  539. }
  540. traverse( rootEntry );
  541. }
  542. // morph
  543. function updateAttributes( attribute, morph, ratio ) {
  544. for ( let i = 0; i < morph.elementCount; i ++ ) {
  545. const element = morph.elements[ i ];
  546. let index;
  547. if ( data.metadata.format === 'pmd' ) {
  548. index = data.morphs[ 0 ].elements[ element.index ].index;
  549. } else {
  550. index = element.index;
  551. }
  552. attribute.array[ index * 3 + 0 ] += element.position[ 0 ] * ratio;
  553. attribute.array[ index * 3 + 1 ] += element.position[ 1 ] * ratio;
  554. attribute.array[ index * 3 + 2 ] += element.position[ 2 ] * ratio;
  555. }
  556. }
  557. for ( let i = 0; i < data.metadata.morphCount; i ++ ) {
  558. const morph = data.morphs[ i ];
  559. const params = { name: morph.name };
  560. const attribute = new Float32BufferAttribute( data.metadata.vertexCount * 3, 3 );
  561. attribute.name = morph.name;
  562. for ( let j = 0; j < data.metadata.vertexCount * 3; j ++ ) {
  563. attribute.array[ j ] = positions[ j ];
  564. }
  565. if ( data.metadata.format === 'pmd' ) {
  566. if ( i !== 0 ) {
  567. updateAttributes( attribute, morph, 1.0 );
  568. }
  569. } else {
  570. if ( morph.type === 0 ) { // group
  571. for ( let j = 0; j < morph.elementCount; j ++ ) {
  572. const morph2 = data.morphs[ morph.elements[ j ].index ];
  573. const ratio = morph.elements[ j ].ratio;
  574. if ( morph2.type === 1 ) {
  575. updateAttributes( attribute, morph2, ratio );
  576. } else {
  577. // TODO: implement
  578. }
  579. }
  580. } else if ( morph.type === 1 ) { // vertex
  581. updateAttributes( attribute, morph, 1.0 );
  582. } else if ( morph.type === 2 ) { // bone
  583. // TODO: implement
  584. } else if ( morph.type === 3 ) { // uv
  585. // TODO: implement
  586. } else if ( morph.type === 4 ) { // additional uv1
  587. // TODO: implement
  588. } else if ( morph.type === 5 ) { // additional uv2
  589. // TODO: implement
  590. } else if ( morph.type === 6 ) { // additional uv3
  591. // TODO: implement
  592. } else if ( morph.type === 7 ) { // additional uv4
  593. // TODO: implement
  594. } else if ( morph.type === 8 ) { // material
  595. // TODO: implement
  596. }
  597. }
  598. morphTargets.push( params );
  599. morphPositions.push( attribute );
  600. }
  601. // rigid bodies from rigidBodies field.
  602. for ( let i = 0; i < data.metadata.rigidBodyCount; i ++ ) {
  603. const rigidBody = data.rigidBodies[ i ];
  604. const params = {};
  605. for ( const key in rigidBody ) {
  606. params[ key ] = rigidBody[ key ];
  607. }
  608. /*
  609. * RigidBody position parameter in PMX seems global position
  610. * while the one in PMD seems offset from corresponding bone.
  611. * So unify being offset.
  612. */
  613. if ( data.metadata.format === 'pmx' ) {
  614. if ( params.boneIndex !== - 1 ) {
  615. const bone = data.bones[ params.boneIndex ];
  616. params.position[ 0 ] -= bone.position[ 0 ];
  617. params.position[ 1 ] -= bone.position[ 1 ];
  618. params.position[ 2 ] -= bone.position[ 2 ];
  619. }
  620. }
  621. rigidBodies.push( params );
  622. }
  623. // constraints from constraints field.
  624. for ( let i = 0; i < data.metadata.constraintCount; i ++ ) {
  625. const constraint = data.constraints[ i ];
  626. const params = {};
  627. for ( const key in constraint ) {
  628. params[ key ] = constraint[ key ];
  629. }
  630. const bodyA = rigidBodies[ params.rigidBodyIndex1 ];
  631. const bodyB = rigidBodies[ params.rigidBodyIndex2 ];
  632. // Refer to http://www20.atpages.jp/katwat/wp/?p=4135
  633. if ( bodyA.type !== 0 && bodyB.type === 2 ) {
  634. if ( bodyA.boneIndex !== - 1 && bodyB.boneIndex !== - 1 &&
  635. data.bones[ bodyB.boneIndex ].parentIndex === bodyA.boneIndex ) {
  636. bodyB.type = 1;
  637. }
  638. }
  639. constraints.push( params );
  640. }
  641. // build BufferGeometry.
  642. const geometry = new BufferGeometry();
  643. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  644. geometry.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  645. geometry.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  646. geometry.setAttribute( 'skinIndex', new Uint16BufferAttribute( skinIndices, 4 ) );
  647. geometry.setAttribute( 'skinWeight', new Float32BufferAttribute( skinWeights, 4 ) );
  648. geometry.setIndex( indices );
  649. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  650. geometry.addGroup( groups[ i ].offset, groups[ i ].count, i );
  651. }
  652. geometry.bones = bones;
  653. geometry.morphTargets = morphTargets;
  654. geometry.morphAttributes.position = morphPositions;
  655. geometry.morphTargetsRelative = false;
  656. geometry.userData.MMD = {
  657. bones: bones,
  658. iks: iks,
  659. grants: grants,
  660. rigidBodies: rigidBodies,
  661. constraints: constraints,
  662. format: data.metadata.format
  663. };
  664. geometry.computeBoundingSphere();
  665. return geometry;
  666. }
  667. }
  668. //
  669. /**
  670. * @param {THREE.LoadingManager} manager
  671. */
  672. class MaterialBuilder {
  673. constructor( manager ) {
  674. this.manager = manager;
  675. this.textureLoader = new TextureLoader( this.manager );
  676. this.tgaLoader = null; // lazy generation
  677. this.crossOrigin = 'anonymous';
  678. this.resourcePath = undefined;
  679. }
  680. /**
  681. * @param {string} crossOrigin
  682. * @return {MaterialBuilder}
  683. */
  684. setCrossOrigin( crossOrigin ) {
  685. this.crossOrigin = crossOrigin;
  686. return this;
  687. }
  688. /**
  689. * @param {string} resourcePath
  690. * @return {MaterialBuilder}
  691. */
  692. setResourcePath( resourcePath ) {
  693. this.resourcePath = resourcePath;
  694. return this;
  695. }
  696. /**
  697. * @param {Object} data - parsed PMD/PMX data
  698. * @param {BufferGeometry} geometry - some properties are dependend on geometry
  699. * @param {function} onProgress
  700. * @param {function} onError
  701. * @return {Array<MeshToonMaterial>}
  702. */
  703. build( data, geometry /*, onProgress, onError */ ) {
  704. const materials = [];
  705. const textures = {};
  706. this.textureLoader.setCrossOrigin( this.crossOrigin );
  707. // materials
  708. for ( let i = 0; i < data.metadata.materialCount; i ++ ) {
  709. const material = data.materials[ i ];
  710. const params = { userData: {} };
  711. if ( material.name !== undefined ) params.name = material.name;
  712. /*
  713. * Color
  714. *
  715. * MMD MeshToonMaterial
  716. * diffuse - color
  717. * ambient - emissive * a
  718. * (a = 1.0 without map texture or 0.2 with map texture)
  719. *
  720. * MeshToonMaterial doesn't have ambient. Set it to emissive instead.
  721. * It'll be too bright if material has map texture so using coef 0.2.
  722. */
  723. params.color = new Color().fromArray( material.diffuse );
  724. params.opacity = material.diffuse[ 3 ];
  725. params.emissive = new Color().fromArray( material.ambient );
  726. params.transparent = params.opacity !== 1.0;
  727. //
  728. params.morphTargets = geometry.morphTargets.length > 0 ? true : false;
  729. params.fog = true;
  730. // blend
  731. params.blending = CustomBlending;
  732. params.blendSrc = SrcAlphaFactor;
  733. params.blendDst = OneMinusSrcAlphaFactor;
  734. params.blendSrcAlpha = SrcAlphaFactor;
  735. params.blendDstAlpha = DstAlphaFactor;
  736. // side
  737. if ( data.metadata.format === 'pmx' && ( material.flag & 0x1 ) === 1 ) {
  738. params.side = DoubleSide;
  739. } else {
  740. params.side = params.opacity === 1.0 ? FrontSide : DoubleSide;
  741. }
  742. if ( data.metadata.format === 'pmd' ) {
  743. // map, envMap
  744. if ( material.fileName ) {
  745. const fileName = material.fileName;
  746. const fileNames = fileName.split( '*' );
  747. // fileNames[ 0 ]: mapFileName
  748. // fileNames[ 1 ]: envMapFileName( optional )
  749. params.map = this._loadTexture( fileNames[ 0 ], textures );
  750. if ( fileNames.length > 1 ) {
  751. const extension = fileNames[ 1 ].slice( - 4 ).toLowerCase();
  752. params.envMap = this._loadTexture(
  753. fileNames[ 1 ],
  754. textures
  755. );
  756. params.combine = extension === '.sph'
  757. ? MultiplyOperation
  758. : AddOperation;
  759. }
  760. }
  761. // gradientMap
  762. const toonFileName = ( material.toonIndex === - 1 )
  763. ? 'toon00.bmp'
  764. : data.toonTextures[ material.toonIndex ].fileName;
  765. params.gradientMap = this._loadTexture(
  766. toonFileName,
  767. textures,
  768. {
  769. isToonTexture: true,
  770. isDefaultToonTexture: this._isDefaultToonTexture( toonFileName )
  771. }
  772. );
  773. // parameters for OutlineEffect
  774. params.userData.outlineParameters = {
  775. thickness: material.edgeFlag === 1 ? 0.003 : 0.0,
  776. color: [ 0, 0, 0 ],
  777. alpha: 1.0,
  778. visible: material.edgeFlag === 1
  779. };
  780. } else {
  781. // map
  782. if ( material.textureIndex !== - 1 ) {
  783. params.map = this._loadTexture( data.textures[ material.textureIndex ], textures );
  784. }
  785. // envMap TODO: support m.envFlag === 3
  786. if ( material.envTextureIndex !== - 1 && ( material.envFlag === 1 || material.envFlag == 2 ) ) {
  787. params.envMap = this._loadTexture(
  788. data.textures[ material.envTextureIndex ],
  789. textures
  790. );
  791. params.combine = material.envFlag === 1
  792. ? MultiplyOperation
  793. : AddOperation;
  794. }
  795. // gradientMap
  796. let toonFileName, isDefaultToon;
  797. if ( material.toonIndex === - 1 || material.toonFlag !== 0 ) {
  798. toonFileName = 'toon' + ( '0' + ( material.toonIndex + 1 ) ).slice( - 2 ) + '.bmp';
  799. isDefaultToon = true;
  800. } else {
  801. toonFileName = data.textures[ material.toonIndex ];
  802. isDefaultToon = false;
  803. }
  804. params.gradientMap = this._loadTexture(
  805. toonFileName,
  806. textures,
  807. {
  808. isToonTexture: true,
  809. isDefaultToonTexture: isDefaultToon
  810. }
  811. );
  812. // parameters for OutlineEffect
  813. params.userData.outlineParameters = {
  814. thickness: material.edgeSize / 300, // TODO: better calculation?
  815. color: material.edgeColor.slice( 0, 3 ),
  816. alpha: material.edgeColor[ 3 ],
  817. visible: ( material.flag & 0x10 ) !== 0 && material.edgeSize > 0.0
  818. };
  819. }
  820. if ( params.map !== undefined ) {
  821. if ( ! params.transparent ) {
  822. this._checkImageTransparency( params.map, geometry, i );
  823. }
  824. params.emissive.multiplyScalar( 0.2 );
  825. }
  826. materials.push( new MeshToonMaterial( params ) );
  827. }
  828. if ( data.metadata.format === 'pmx' ) {
  829. // set transparent true if alpha morph is defined.
  830. function checkAlphaMorph( elements, materials ) {
  831. for ( let i = 0, il = elements.length; i < il; i ++ ) {
  832. const element = elements[ i ];
  833. if ( element.index === - 1 ) continue;
  834. const material = materials[ element.index ];
  835. if ( material.opacity !== element.diffuse[ 3 ] ) {
  836. material.transparent = true;
  837. }
  838. }
  839. }
  840. for ( let i = 0, il = data.morphs.length; i < il; i ++ ) {
  841. const morph = data.morphs[ i ];
  842. const elements = morph.elements;
  843. if ( morph.type === 0 ) {
  844. for ( let j = 0, jl = elements.length; j < jl; j ++ ) {
  845. const morph2 = data.morphs[ elements[ j ].index ];
  846. if ( morph2.type !== 8 ) continue;
  847. checkAlphaMorph( morph2.elements, materials );
  848. }
  849. } else if ( morph.type === 8 ) {
  850. checkAlphaMorph( elements, materials );
  851. }
  852. }
  853. }
  854. return materials;
  855. }
  856. // private methods
  857. _getTGALoader() {
  858. if ( this.tgaLoader === null ) {
  859. if ( TGALoader === undefined ) {
  860. throw new Error( 'THREE.MMDLoader: Import TGALoader' );
  861. }
  862. this.tgaLoader = new TGALoader( this.manager );
  863. }
  864. return this.tgaLoader;
  865. }
  866. _isDefaultToonTexture( name ) {
  867. if ( name.length !== 10 ) return false;
  868. return /toon(10|0[0-9])\.bmp/.test( name );
  869. }
  870. _loadTexture( filePath, textures, params, onProgress, onError ) {
  871. params = params || {};
  872. const scope = this;
  873. let fullPath;
  874. if ( params.isDefaultToonTexture === true ) {
  875. let index;
  876. try {
  877. index = parseInt( filePath.match( /toon([0-9]{2})\.bmp$/ )[ 1 ] );
  878. } catch ( e ) {
  879. console.warn( 'THREE.MMDLoader: ' + filePath + ' seems like a '
  880. + 'not right default texture path. Using toon00.bmp instead.' );
  881. index = 0;
  882. }
  883. fullPath = DEFAULT_TOON_TEXTURES[ index ];
  884. } else {
  885. fullPath = this.resourcePath + filePath;
  886. }
  887. if ( textures[ fullPath ] !== undefined ) return textures[ fullPath ];
  888. let loader = this.manager.getHandler( fullPath );
  889. if ( loader === null ) {
  890. loader = ( filePath.slice( - 4 ).toLowerCase() === '.tga' )
  891. ? this._getTGALoader()
  892. : this.textureLoader;
  893. }
  894. const texture = loader.load( fullPath, function ( t ) {
  895. // MMD toon texture is Axis-Y oriented
  896. // but Three.js gradient map is Axis-X oriented.
  897. // So here replaces the toon texture image with the rotated one.
  898. if ( params.isToonTexture === true ) {
  899. t.image = scope._getRotatedImage( t.image );
  900. t.magFilter = NearestFilter;
  901. t.minFilter = NearestFilter;
  902. }
  903. t.flipY = false;
  904. t.wrapS = RepeatWrapping;
  905. t.wrapT = RepeatWrapping;
  906. for ( let i = 0; i < texture.readyCallbacks.length; i ++ ) {
  907. texture.readyCallbacks[ i ]( texture );
  908. }
  909. delete texture.readyCallbacks;
  910. }, onProgress, onError );
  911. texture.readyCallbacks = [];
  912. textures[ fullPath ] = texture;
  913. return texture;
  914. }
  915. _getRotatedImage( image ) {
  916. const canvas = document.createElement( 'canvas' );
  917. const context = canvas.getContext( '2d' );
  918. const width = image.width;
  919. const height = image.height;
  920. canvas.width = width;
  921. canvas.height = height;
  922. context.clearRect( 0, 0, width, height );
  923. context.translate( width / 2.0, height / 2.0 );
  924. context.rotate( 0.5 * Math.PI ); // 90.0 * Math.PI / 180.0
  925. context.translate( - width / 2.0, - height / 2.0 );
  926. context.drawImage( image, 0, 0 );
  927. return context.getImageData( 0, 0, width, height );
  928. }
  929. // Check if the partial image area used by the texture is transparent.
  930. _checkImageTransparency( map, geometry, groupIndex ) {
  931. map.readyCallbacks.push( function ( texture ) {
  932. // Is there any efficient ways?
  933. function createImageData( image ) {
  934. const canvas = document.createElement( 'canvas' );
  935. canvas.width = image.width;
  936. canvas.height = image.height;
  937. const context = canvas.getContext( '2d' );
  938. context.drawImage( image, 0, 0 );
  939. return context.getImageData( 0, 0, canvas.width, canvas.height );
  940. }
  941. function detectImageTransparency( image, uvs, indices ) {
  942. const width = image.width;
  943. const height = image.height;
  944. const data = image.data;
  945. const threshold = 253;
  946. if ( data.length / ( width * height ) !== 4 ) return false;
  947. for ( let i = 0; i < indices.length; i += 3 ) {
  948. const centerUV = { x: 0.0, y: 0.0 };
  949. for ( let j = 0; j < 3; j ++ ) {
  950. const index = indices[ i * 3 + j ];
  951. const uv = { x: uvs[ index * 2 + 0 ], y: uvs[ index * 2 + 1 ] };
  952. if ( getAlphaByUv( image, uv ) < threshold ) return true;
  953. centerUV.x += uv.x;
  954. centerUV.y += uv.y;
  955. }
  956. centerUV.x /= 3;
  957. centerUV.y /= 3;
  958. if ( getAlphaByUv( image, centerUV ) < threshold ) return true;
  959. }
  960. return false;
  961. }
  962. /*
  963. * This method expects
  964. * texture.flipY = false
  965. * texture.wrapS = RepeatWrapping
  966. * texture.wrapT = RepeatWrapping
  967. * TODO: more precise
  968. */
  969. function getAlphaByUv( image, uv ) {
  970. const width = image.width;
  971. const height = image.height;
  972. let x = Math.round( uv.x * width ) % width;
  973. let y = Math.round( uv.y * height ) % height;
  974. if ( x < 0 ) x += width;
  975. if ( y < 0 ) y += height;
  976. const index = y * width + x;
  977. return image.data[ index * 4 + 3 ];
  978. }
  979. const imageData = texture.image.data !== undefined
  980. ? texture.image
  981. : createImageData( texture.image );
  982. const group = geometry.groups[ groupIndex ];
  983. if ( detectImageTransparency(
  984. imageData,
  985. geometry.attributes.uv.array,
  986. geometry.index.array.slice( group.start, group.start + group.count ) ) ) {
  987. map.transparent = true;
  988. }
  989. } );
  990. }
  991. }
  992. //
  993. class AnimationBuilder {
  994. /**
  995. * @param {Object} vmd - parsed VMD data
  996. * @param {SkinnedMesh} mesh - tracks will be fitting to mesh
  997. * @return {AnimationClip}
  998. */
  999. build( vmd, mesh ) {
  1000. // combine skeletal and morph animations
  1001. const tracks = this.buildSkeletalAnimation( vmd, mesh ).tracks;
  1002. const tracks2 = this.buildMorphAnimation( vmd, mesh ).tracks;
  1003. for ( let i = 0, il = tracks2.length; i < il; i ++ ) {
  1004. tracks.push( tracks2[ i ] );
  1005. }
  1006. return new AnimationClip( '', - 1, tracks );
  1007. }
  1008. /**
  1009. * @param {Object} vmd - parsed VMD data
  1010. * @param {SkinnedMesh} mesh - tracks will be fitting to mesh
  1011. * @return {AnimationClip}
  1012. */
  1013. buildSkeletalAnimation( vmd, mesh ) {
  1014. function pushInterpolation( array, interpolation, index ) {
  1015. array.push( interpolation[ index + 0 ] / 127 ); // x1
  1016. array.push( interpolation[ index + 8 ] / 127 ); // x2
  1017. array.push( interpolation[ index + 4 ] / 127 ); // y1
  1018. array.push( interpolation[ index + 12 ] / 127 ); // y2
  1019. }
  1020. const tracks = [];
  1021. const motions = {};
  1022. const bones = mesh.skeleton.bones;
  1023. const boneNameDictionary = {};
  1024. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  1025. boneNameDictionary[ bones[ i ].name ] = true;
  1026. }
  1027. for ( let i = 0; i < vmd.metadata.motionCount; i ++ ) {
  1028. const motion = vmd.motions[ i ];
  1029. const boneName = motion.boneName;
  1030. if ( boneNameDictionary[ boneName ] === undefined ) continue;
  1031. motions[ boneName ] = motions[ boneName ] || [];
  1032. motions[ boneName ].push( motion );
  1033. }
  1034. for ( const key in motions ) {
  1035. const array = motions[ key ];
  1036. array.sort( function ( a, b ) {
  1037. return a.frameNum - b.frameNum;
  1038. } );
  1039. const times = [];
  1040. const positions = [];
  1041. const rotations = [];
  1042. const pInterpolations = [];
  1043. const rInterpolations = [];
  1044. const basePosition = mesh.skeleton.getBoneByName( key ).position.toArray();
  1045. for ( let i = 0, il = array.length; i < il; i ++ ) {
  1046. const time = array[ i ].frameNum / 30;
  1047. const position = array[ i ].position;
  1048. const rotation = array[ i ].rotation;
  1049. const interpolation = array[ i ].interpolation;
  1050. times.push( time );
  1051. for ( let j = 0; j < 3; j ++ ) positions.push( basePosition[ j ] + position[ j ] );
  1052. for ( let j = 0; j < 4; j ++ ) rotations.push( rotation[ j ] );
  1053. for ( let j = 0; j < 3; j ++ ) pushInterpolation( pInterpolations, interpolation, j );
  1054. pushInterpolation( rInterpolations, interpolation, 3 );
  1055. }
  1056. const targetName = '.bones[' + key + ']';
  1057. tracks.push( this._createTrack( targetName + '.position', VectorKeyframeTrack, times, positions, pInterpolations ) );
  1058. tracks.push( this._createTrack( targetName + '.quaternion', QuaternionKeyframeTrack, times, rotations, rInterpolations ) );
  1059. }
  1060. return new AnimationClip( '', - 1, tracks );
  1061. }
  1062. /**
  1063. * @param {Object} vmd - parsed VMD data
  1064. * @param {SkinnedMesh} mesh - tracks will be fitting to mesh
  1065. * @return {AnimationClip}
  1066. */
  1067. buildMorphAnimation( vmd, mesh ) {
  1068. const tracks = [];
  1069. const morphs = {};
  1070. const morphTargetDictionary = mesh.morphTargetDictionary;
  1071. for ( let i = 0; i < vmd.metadata.morphCount; i ++ ) {
  1072. const morph = vmd.morphs[ i ];
  1073. const morphName = morph.morphName;
  1074. if ( morphTargetDictionary[ morphName ] === undefined ) continue;
  1075. morphs[ morphName ] = morphs[ morphName ] || [];
  1076. morphs[ morphName ].push( morph );
  1077. }
  1078. for ( const key in morphs ) {
  1079. const array = morphs[ key ];
  1080. array.sort( function ( a, b ) {
  1081. return a.frameNum - b.frameNum;
  1082. } );
  1083. const times = [];
  1084. const values = [];
  1085. for ( let i = 0, il = array.length; i < il; i ++ ) {
  1086. times.push( array[ i ].frameNum / 30 );
  1087. values.push( array[ i ].weight );
  1088. }
  1089. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluences[' + morphTargetDictionary[ key ] + ']', times, values ) );
  1090. }
  1091. return new AnimationClip( '', - 1, tracks );
  1092. }
  1093. /**
  1094. * @param {Object} vmd - parsed VMD data
  1095. * @return {AnimationClip}
  1096. */
  1097. buildCameraAnimation( vmd ) {
  1098. function pushVector3( array, vec ) {
  1099. array.push( vec.x );
  1100. array.push( vec.y );
  1101. array.push( vec.z );
  1102. }
  1103. function pushQuaternion( array, q ) {
  1104. array.push( q.x );
  1105. array.push( q.y );
  1106. array.push( q.z );
  1107. array.push( q.w );
  1108. }
  1109. function pushInterpolation( array, interpolation, index ) {
  1110. array.push( interpolation[ index * 4 + 0 ] / 127 ); // x1
  1111. array.push( interpolation[ index * 4 + 1 ] / 127 ); // x2
  1112. array.push( interpolation[ index * 4 + 2 ] / 127 ); // y1
  1113. array.push( interpolation[ index * 4 + 3 ] / 127 ); // y2
  1114. }
  1115. const cameras = vmd.cameras === undefined ? [] : vmd.cameras.slice();
  1116. cameras.sort( function ( a, b ) {
  1117. return a.frameNum - b.frameNum;
  1118. } );
  1119. const times = [];
  1120. const centers = [];
  1121. const quaternions = [];
  1122. const positions = [];
  1123. const fovs = [];
  1124. const cInterpolations = [];
  1125. const qInterpolations = [];
  1126. const pInterpolations = [];
  1127. const fInterpolations = [];
  1128. const quaternion = new Quaternion();
  1129. const euler = new Euler();
  1130. const position = new Vector3();
  1131. const center = new Vector3();
  1132. for ( let i = 0, il = cameras.length; i < il; i ++ ) {
  1133. const motion = cameras[ i ];
  1134. const time = motion.frameNum / 30;
  1135. const pos = motion.position;
  1136. const rot = motion.rotation;
  1137. const distance = motion.distance;
  1138. const fov = motion.fov;
  1139. const interpolation = motion.interpolation;
  1140. times.push( time );
  1141. position.set( 0, 0, - distance );
  1142. center.set( pos[ 0 ], pos[ 1 ], pos[ 2 ] );
  1143. euler.set( - rot[ 0 ], - rot[ 1 ], - rot[ 2 ] );
  1144. quaternion.setFromEuler( euler );
  1145. position.add( center );
  1146. position.applyQuaternion( quaternion );
  1147. pushVector3( centers, center );
  1148. pushQuaternion( quaternions, quaternion );
  1149. pushVector3( positions, position );
  1150. fovs.push( fov );
  1151. for ( let j = 0; j < 3; j ++ ) {
  1152. pushInterpolation( cInterpolations, interpolation, j );
  1153. }
  1154. pushInterpolation( qInterpolations, interpolation, 3 );
  1155. // use the same parameter for x, y, z axis.
  1156. for ( let j = 0; j < 3; j ++ ) {
  1157. pushInterpolation( pInterpolations, interpolation, 4 );
  1158. }
  1159. pushInterpolation( fInterpolations, interpolation, 5 );
  1160. }
  1161. const tracks = [];
  1162. // I expect an object whose name 'target' exists under THREE.Camera
  1163. tracks.push( this._createTrack( 'target.position', VectorKeyframeTrack, times, centers, cInterpolations ) );
  1164. tracks.push( this._createTrack( '.quaternion', QuaternionKeyframeTrack, times, quaternions, qInterpolations ) );
  1165. tracks.push( this._createTrack( '.position', VectorKeyframeTrack, times, positions, pInterpolations ) );
  1166. tracks.push( this._createTrack( '.fov', NumberKeyframeTrack, times, fovs, fInterpolations ) );
  1167. return new AnimationClip( '', - 1, tracks );
  1168. }
  1169. // private method
  1170. _createTrack( node, typedKeyframeTrack, times, values, interpolations ) {
  1171. /*
  1172. * optimizes here not to let KeyframeTrackPrototype optimize
  1173. * because KeyframeTrackPrototype optimizes times and values but
  1174. * doesn't optimize interpolations.
  1175. */
  1176. if ( times.length > 2 ) {
  1177. times = times.slice();
  1178. values = values.slice();
  1179. interpolations = interpolations.slice();
  1180. const stride = values.length / times.length;
  1181. const interpolateStride = interpolations.length / times.length;
  1182. let index = 1;
  1183. for ( let aheadIndex = 2, endIndex = times.length; aheadIndex < endIndex; aheadIndex ++ ) {
  1184. for ( let i = 0; i < stride; i ++ ) {
  1185. if ( values[ index * stride + i ] !== values[ ( index - 1 ) * stride + i ] ||
  1186. values[ index * stride + i ] !== values[ aheadIndex * stride + i ] ) {
  1187. index ++;
  1188. break;
  1189. }
  1190. }
  1191. if ( aheadIndex > index ) {
  1192. times[ index ] = times[ aheadIndex ];
  1193. for ( let i = 0; i < stride; i ++ ) {
  1194. values[ index * stride + i ] = values[ aheadIndex * stride + i ];
  1195. }
  1196. for ( let i = 0; i < interpolateStride; i ++ ) {
  1197. interpolations[ index * interpolateStride + i ] = interpolations[ aheadIndex * interpolateStride + i ];
  1198. }
  1199. }
  1200. }
  1201. times.length = index + 1;
  1202. values.length = ( index + 1 ) * stride;
  1203. interpolations.length = ( index + 1 ) * interpolateStride;
  1204. }
  1205. const track = new typedKeyframeTrack( node, times, values );
  1206. track.createInterpolant = function InterpolantFactoryMethodCubicBezier( result ) {
  1207. return new CubicBezierInterpolation( this.times, this.values, this.getValueSize(), result, new Float32Array( interpolations ) );
  1208. };
  1209. return track;
  1210. }
  1211. }
  1212. // interpolation
  1213. class CubicBezierInterpolation extends Interpolant {
  1214. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer, params ) {
  1215. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  1216. this.interpolationParams = params;
  1217. }
  1218. interpolate_( i1, t0, t, t1 ) {
  1219. const result = this.resultBuffer;
  1220. const values = this.sampleValues;
  1221. const stride = this.valueSize;
  1222. const params = this.interpolationParams;
  1223. const offset1 = i1 * stride;
  1224. const offset0 = offset1 - stride;
  1225. // No interpolation if next key frame is in one frame in 30fps.
  1226. // This is from MMD animation spec.
  1227. // '1.5' is for precision loss. times are Float32 in Three.js Animation system.
  1228. const weight1 = ( ( t1 - t0 ) < 1 / 30 * 1.5 ) ? 0.0 : ( t - t0 ) / ( t1 - t0 );
  1229. if ( stride === 4 ) { // Quaternion
  1230. const x1 = params[ i1 * 4 + 0 ];
  1231. const x2 = params[ i1 * 4 + 1 ];
  1232. const y1 = params[ i1 * 4 + 2 ];
  1233. const y2 = params[ i1 * 4 + 3 ];
  1234. const ratio = this._calculate( x1, x2, y1, y2, weight1 );
  1235. Quaternion.slerpFlat( result, 0, values, offset0, values, offset1, ratio );
  1236. } else if ( stride === 3 ) { // Vector3
  1237. for ( let i = 0; i !== stride; ++ i ) {
  1238. const x1 = params[ i1 * 12 + i * 4 + 0 ];
  1239. const x2 = params[ i1 * 12 + i * 4 + 1 ];
  1240. const y1 = params[ i1 * 12 + i * 4 + 2 ];
  1241. const y2 = params[ i1 * 12 + i * 4 + 3 ];
  1242. const ratio = this._calculate( x1, x2, y1, y2, weight1 );
  1243. result[ i ] = values[ offset0 + i ] * ( 1 - ratio ) + values[ offset1 + i ] * ratio;
  1244. }
  1245. } else { // Number
  1246. const x1 = params[ i1 * 4 + 0 ];
  1247. const x2 = params[ i1 * 4 + 1 ];
  1248. const y1 = params[ i1 * 4 + 2 ];
  1249. const y2 = params[ i1 * 4 + 3 ];
  1250. const ratio = this._calculate( x1, x2, y1, y2, weight1 );
  1251. result[ 0 ] = values[ offset0 ] * ( 1 - ratio ) + values[ offset1 ] * ratio;
  1252. }
  1253. return result;
  1254. }
  1255. _calculate( x1, x2, y1, y2, x ) {
  1256. /*
  1257. * Cubic Bezier curves
  1258. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Cubic_B.C3.A9zier_curves
  1259. *
  1260. * B(t) = ( 1 - t ) ^ 3 * P0
  1261. * + 3 * ( 1 - t ) ^ 2 * t * P1
  1262. * + 3 * ( 1 - t ) * t^2 * P2
  1263. * + t ^ 3 * P3
  1264. * ( 0 <= t <= 1 )
  1265. *
  1266. * MMD uses Cubic Bezier curves for bone and camera animation interpolation.
  1267. * http://d.hatena.ne.jp/edvakf/20111016/1318716097
  1268. *
  1269. * x = ( 1 - t ) ^ 3 * x0
  1270. * + 3 * ( 1 - t ) ^ 2 * t * x1
  1271. * + 3 * ( 1 - t ) * t^2 * x2
  1272. * + t ^ 3 * x3
  1273. * y = ( 1 - t ) ^ 3 * y0
  1274. * + 3 * ( 1 - t ) ^ 2 * t * y1
  1275. * + 3 * ( 1 - t ) * t^2 * y2
  1276. * + t ^ 3 * y3
  1277. * ( x0 = 0, y0 = 0 )
  1278. * ( x3 = 1, y3 = 1 )
  1279. * ( 0 <= t, x1, x2, y1, y2 <= 1 )
  1280. *
  1281. * Here solves this equation with Bisection method,
  1282. * https://en.wikipedia.org/wiki/Bisection_method
  1283. * gets t, and then calculate y.
  1284. *
  1285. * f(t) = 3 * ( 1 - t ) ^ 2 * t * x1
  1286. * + 3 * ( 1 - t ) * t^2 * x2
  1287. * + t ^ 3 - x = 0
  1288. *
  1289. * (Another option: Newton's method
  1290. * https://en.wikipedia.org/wiki/Newton%27s_method)
  1291. */
  1292. let c = 0.5;
  1293. let t = c;
  1294. let s = 1.0 - t;
  1295. const loop = 15;
  1296. const eps = 1e-5;
  1297. const math = Math;
  1298. let sst3, stt3, ttt;
  1299. for ( let i = 0; i < loop; i ++ ) {
  1300. sst3 = 3.0 * s * s * t;
  1301. stt3 = 3.0 * s * t * t;
  1302. ttt = t * t * t;
  1303. const ft = ( sst3 * x1 ) + ( stt3 * x2 ) + ( ttt ) - x;
  1304. if ( math.abs( ft ) < eps ) break;
  1305. c /= 2.0;
  1306. t += ( ft < 0 ) ? c : - c;
  1307. s = 1.0 - t;
  1308. }
  1309. return ( sst3 * y1 ) + ( stt3 * y2 ) + ttt;
  1310. }
  1311. }
  1312. export { MMDLoader };