MMDLoader.js 47 KB

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