MMDLoader.js 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038
  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.skinning = geometry.bones.length > 0 ? true : false;
  729. params.morphTargets = geometry.morphTargets.length > 0 ? true : false;
  730. params.fog = true;
  731. // blend
  732. params.blending = CustomBlending;
  733. params.blendSrc = SrcAlphaFactor;
  734. params.blendDst = OneMinusSrcAlphaFactor;
  735. params.blendSrcAlpha = SrcAlphaFactor;
  736. params.blendDstAlpha = DstAlphaFactor;
  737. // side
  738. if ( data.metadata.format === 'pmx' && ( material.flag & 0x1 ) === 1 ) {
  739. params.side = DoubleSide;
  740. } else {
  741. params.side = params.opacity === 1.0 ? FrontSide : DoubleSide;
  742. }
  743. if ( data.metadata.format === 'pmd' ) {
  744. // map, envMap
  745. if ( material.fileName ) {
  746. const fileName = material.fileName;
  747. const fileNames = fileName.split( '*' );
  748. // fileNames[ 0 ]: mapFileName
  749. // fileNames[ 1 ]: envMapFileName( optional )
  750. params.map = this._loadTexture( fileNames[ 0 ], textures );
  751. if ( fileNames.length > 1 ) {
  752. const extension = fileNames[ 1 ].slice( - 4 ).toLowerCase();
  753. params.envMap = this._loadTexture(
  754. fileNames[ 1 ],
  755. textures
  756. );
  757. params.combine = extension === '.sph'
  758. ? MultiplyOperation
  759. : AddOperation;
  760. }
  761. }
  762. // gradientMap
  763. const toonFileName = ( material.toonIndex === - 1 )
  764. ? 'toon00.bmp'
  765. : data.toonTextures[ material.toonIndex ].fileName;
  766. params.gradientMap = this._loadTexture(
  767. toonFileName,
  768. textures,
  769. {
  770. isToonTexture: true,
  771. isDefaultToonTexture: this._isDefaultToonTexture( toonFileName )
  772. }
  773. );
  774. // parameters for OutlineEffect
  775. params.userData.outlineParameters = {
  776. thickness: material.edgeFlag === 1 ? 0.003 : 0.0,
  777. color: [ 0, 0, 0 ],
  778. alpha: 1.0,
  779. visible: material.edgeFlag === 1
  780. };
  781. } else {
  782. // map
  783. if ( material.textureIndex !== - 1 ) {
  784. params.map = this._loadTexture( data.textures[ material.textureIndex ], textures );
  785. }
  786. // envMap TODO: support m.envFlag === 3
  787. if ( material.envTextureIndex !== - 1 && ( material.envFlag === 1 || material.envFlag == 2 ) ) {
  788. params.envMap = this._loadTexture(
  789. data.textures[ material.envTextureIndex ],
  790. textures
  791. );
  792. params.combine = material.envFlag === 1
  793. ? MultiplyOperation
  794. : AddOperation;
  795. }
  796. // gradientMap
  797. let toonFileName, isDefaultToon;
  798. if ( material.toonIndex === - 1 || material.toonFlag !== 0 ) {
  799. toonFileName = 'toon' + ( '0' + ( material.toonIndex + 1 ) ).slice( - 2 ) + '.bmp';
  800. isDefaultToon = true;
  801. } else {
  802. toonFileName = data.textures[ material.toonIndex ];
  803. isDefaultToon = false;
  804. }
  805. params.gradientMap = this._loadTexture(
  806. toonFileName,
  807. textures,
  808. {
  809. isToonTexture: true,
  810. isDefaultToonTexture: isDefaultToon
  811. }
  812. );
  813. // parameters for OutlineEffect
  814. params.userData.outlineParameters = {
  815. thickness: material.edgeSize / 300, // TODO: better calculation?
  816. color: material.edgeColor.slice( 0, 3 ),
  817. alpha: material.edgeColor[ 3 ],
  818. visible: ( material.flag & 0x10 ) !== 0 && material.edgeSize > 0.0
  819. };
  820. }
  821. if ( params.map !== undefined ) {
  822. if ( ! params.transparent ) {
  823. this._checkImageTransparency( params.map, geometry, i );
  824. }
  825. params.emissive.multiplyScalar( 0.2 );
  826. }
  827. materials.push( new MeshToonMaterial( params ) );
  828. }
  829. if ( data.metadata.format === 'pmx' ) {
  830. // set transparent true if alpha morph is defined.
  831. function checkAlphaMorph( elements, materials ) {
  832. for ( let i = 0, il = elements.length; i < il; i ++ ) {
  833. const element = elements[ i ];
  834. if ( element.index === - 1 ) continue;
  835. const material = materials[ element.index ];
  836. if ( material.opacity !== element.diffuse[ 3 ] ) {
  837. material.transparent = true;
  838. }
  839. }
  840. }
  841. for ( let i = 0, il = data.morphs.length; i < il; i ++ ) {
  842. const morph = data.morphs[ i ];
  843. const elements = morph.elements;
  844. if ( morph.type === 0 ) {
  845. for ( let j = 0, jl = elements.length; j < jl; j ++ ) {
  846. const morph2 = data.morphs[ elements[ j ].index ];
  847. if ( morph2.type !== 8 ) continue;
  848. checkAlphaMorph( morph2.elements, materials );
  849. }
  850. } else if ( morph.type === 8 ) {
  851. checkAlphaMorph( elements, materials );
  852. }
  853. }
  854. }
  855. return materials;
  856. }
  857. // private methods
  858. _getTGALoader() {
  859. if ( this.tgaLoader === null ) {
  860. if ( TGALoader === undefined ) {
  861. throw new Error( 'THREE.MMDLoader: Import TGALoader' );
  862. }
  863. this.tgaLoader = new TGALoader( this.manager );
  864. }
  865. return this.tgaLoader;
  866. }
  867. _isDefaultToonTexture( name ) {
  868. if ( name.length !== 10 ) return false;
  869. return /toon(10|0[0-9])\.bmp/.test( name );
  870. }
  871. _loadTexture( filePath, textures, params, onProgress, onError ) {
  872. params = params || {};
  873. const scope = this;
  874. let fullPath;
  875. if ( params.isDefaultToonTexture === true ) {
  876. let index;
  877. try {
  878. index = parseInt( filePath.match( /toon([0-9]{2})\.bmp$/ )[ 1 ] );
  879. } catch ( e ) {
  880. console.warn( 'THREE.MMDLoader: ' + filePath + ' seems like a '
  881. + 'not right default texture path. Using toon00.bmp instead.' );
  882. index = 0;
  883. }
  884. fullPath = DEFAULT_TOON_TEXTURES[ index ];
  885. } else {
  886. fullPath = this.resourcePath + filePath;
  887. }
  888. if ( textures[ fullPath ] !== undefined ) return textures[ fullPath ];
  889. let loader = this.manager.getHandler( fullPath );
  890. if ( loader === null ) {
  891. loader = ( filePath.slice( - 4 ).toLowerCase() === '.tga' )
  892. ? this._getTGALoader()
  893. : this.textureLoader;
  894. }
  895. const texture = loader.load( fullPath, function ( t ) {
  896. // MMD toon texture is Axis-Y oriented
  897. // but Three.js gradient map is Axis-X oriented.
  898. // So here replaces the toon texture image with the rotated one.
  899. if ( params.isToonTexture === true ) {
  900. t.image = scope._getRotatedImage( t.image );
  901. t.magFilter = NearestFilter;
  902. t.minFilter = NearestFilter;
  903. }
  904. t.flipY = false;
  905. t.wrapS = RepeatWrapping;
  906. t.wrapT = RepeatWrapping;
  907. for ( let i = 0; i < texture.readyCallbacks.length; i ++ ) {
  908. texture.readyCallbacks[ i ]( texture );
  909. }
  910. delete texture.readyCallbacks;
  911. }, onProgress, onError );
  912. texture.readyCallbacks = [];
  913. textures[ fullPath ] = texture;
  914. return texture;
  915. }
  916. _getRotatedImage( image ) {
  917. const canvas = document.createElement( 'canvas' );
  918. const context = canvas.getContext( '2d' );
  919. const width = image.width;
  920. const height = image.height;
  921. canvas.width = width;
  922. canvas.height = height;
  923. context.clearRect( 0, 0, width, height );
  924. context.translate( width / 2.0, height / 2.0 );
  925. context.rotate( 0.5 * Math.PI ); // 90.0 * Math.PI / 180.0
  926. context.translate( - width / 2.0, - height / 2.0 );
  927. context.drawImage( image, 0, 0 );
  928. return context.getImageData( 0, 0, width, height );
  929. }
  930. // Check if the partial image area used by the texture is transparent.
  931. _checkImageTransparency( map, geometry, groupIndex ) {
  932. map.readyCallbacks.push( function ( texture ) {
  933. // Is there any efficient ways?
  934. function createImageData( image ) {
  935. const canvas = document.createElement( 'canvas' );
  936. canvas.width = image.width;
  937. canvas.height = image.height;
  938. const context = canvas.getContext( '2d' );
  939. context.drawImage( image, 0, 0 );
  940. return context.getImageData( 0, 0, canvas.width, canvas.height );
  941. }
  942. function detectImageTransparency( image, uvs, indices ) {
  943. const width = image.width;
  944. const height = image.height;
  945. const data = image.data;
  946. const threshold = 253;
  947. if ( data.length / ( width * height ) !== 4 ) return false;
  948. for ( let i = 0; i < indices.length; i += 3 ) {
  949. const centerUV = { x: 0.0, y: 0.0 };
  950. for ( let j = 0; j < 3; j ++ ) {
  951. const index = indices[ i * 3 + j ];
  952. const uv = { x: uvs[ index * 2 + 0 ], y: uvs[ index * 2 + 1 ] };
  953. if ( getAlphaByUv( image, uv ) < threshold ) return true;
  954. centerUV.x += uv.x;
  955. centerUV.y += uv.y;
  956. }
  957. centerUV.x /= 3;
  958. centerUV.y /= 3;
  959. if ( getAlphaByUv( image, centerUV ) < threshold ) return true;
  960. }
  961. return false;
  962. }
  963. /*
  964. * This method expects
  965. * texture.flipY = false
  966. * texture.wrapS = RepeatWrapping
  967. * texture.wrapT = RepeatWrapping
  968. * TODO: more precise
  969. */
  970. function getAlphaByUv( image, uv ) {
  971. const width = image.width;
  972. const height = image.height;
  973. let x = Math.round( uv.x * width ) % width;
  974. let y = Math.round( uv.y * height ) % height;
  975. if ( x < 0 ) x += width;
  976. if ( y < 0 ) y += height;
  977. const index = y * width + x;
  978. return image.data[ index * 4 + 3 ];
  979. }
  980. const imageData = texture.image.data !== undefined
  981. ? texture.image
  982. : createImageData( texture.image );
  983. const group = geometry.groups[ groupIndex ];
  984. if ( detectImageTransparency(
  985. imageData,
  986. geometry.attributes.uv.array,
  987. geometry.index.array.slice( group.start, group.start + group.count ) ) ) {
  988. map.transparent = true;
  989. }
  990. } );
  991. }
  992. }
  993. //
  994. class AnimationBuilder {
  995. /**
  996. * @param {Object} vmd - parsed VMD data
  997. * @param {SkinnedMesh} mesh - tracks will be fitting to mesh
  998. * @return {AnimationClip}
  999. */
  1000. build( vmd, mesh ) {
  1001. // combine skeletal and morph animations
  1002. const tracks = this.buildSkeletalAnimation( vmd, mesh ).tracks;
  1003. const tracks2 = this.buildMorphAnimation( vmd, mesh ).tracks;
  1004. for ( let i = 0, il = tracks2.length; i < il; i ++ ) {
  1005. tracks.push( tracks2[ i ] );
  1006. }
  1007. return new AnimationClip( '', - 1, tracks );
  1008. }
  1009. /**
  1010. * @param {Object} vmd - parsed VMD data
  1011. * @param {SkinnedMesh} mesh - tracks will be fitting to mesh
  1012. * @return {AnimationClip}
  1013. */
  1014. buildSkeletalAnimation( vmd, mesh ) {
  1015. function pushInterpolation( array, interpolation, index ) {
  1016. array.push( interpolation[ index + 0 ] / 127 ); // x1
  1017. array.push( interpolation[ index + 8 ] / 127 ); // x2
  1018. array.push( interpolation[ index + 4 ] / 127 ); // y1
  1019. array.push( interpolation[ index + 12 ] / 127 ); // y2
  1020. }
  1021. const tracks = [];
  1022. const motions = {};
  1023. const bones = mesh.skeleton.bones;
  1024. const boneNameDictionary = {};
  1025. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  1026. boneNameDictionary[ bones[ i ].name ] = true;
  1027. }
  1028. for ( let i = 0; i < vmd.metadata.motionCount; i ++ ) {
  1029. const motion = vmd.motions[ i ];
  1030. const boneName = motion.boneName;
  1031. if ( boneNameDictionary[ boneName ] === undefined ) continue;
  1032. motions[ boneName ] = motions[ boneName ] || [];
  1033. motions[ boneName ].push( motion );
  1034. }
  1035. for ( const key in motions ) {
  1036. const array = motions[ key ];
  1037. array.sort( function ( a, b ) {
  1038. return a.frameNum - b.frameNum;
  1039. } );
  1040. const times = [];
  1041. const positions = [];
  1042. const rotations = [];
  1043. const pInterpolations = [];
  1044. const rInterpolations = [];
  1045. const basePosition = mesh.skeleton.getBoneByName( key ).position.toArray();
  1046. for ( let i = 0, il = array.length; i < il; i ++ ) {
  1047. const time = array[ i ].frameNum / 30;
  1048. const position = array[ i ].position;
  1049. const rotation = array[ i ].rotation;
  1050. const interpolation = array[ i ].interpolation;
  1051. times.push( time );
  1052. for ( let j = 0; j < 3; j ++ ) positions.push( basePosition[ j ] + position[ j ] );
  1053. for ( let j = 0; j < 4; j ++ ) rotations.push( rotation[ j ] );
  1054. for ( let j = 0; j < 3; j ++ ) pushInterpolation( pInterpolations, interpolation, j );
  1055. pushInterpolation( rInterpolations, interpolation, 3 );
  1056. }
  1057. const targetName = '.bones[' + key + ']';
  1058. tracks.push( this._createTrack( targetName + '.position', VectorKeyframeTrack, times, positions, pInterpolations ) );
  1059. tracks.push( this._createTrack( targetName + '.quaternion', QuaternionKeyframeTrack, times, rotations, rInterpolations ) );
  1060. }
  1061. return new AnimationClip( '', - 1, tracks );
  1062. }
  1063. /**
  1064. * @param {Object} vmd - parsed VMD data
  1065. * @param {SkinnedMesh} mesh - tracks will be fitting to mesh
  1066. * @return {AnimationClip}
  1067. */
  1068. buildMorphAnimation( vmd, mesh ) {
  1069. const tracks = [];
  1070. const morphs = {};
  1071. const morphTargetDictionary = mesh.morphTargetDictionary;
  1072. for ( let i = 0; i < vmd.metadata.morphCount; i ++ ) {
  1073. const morph = vmd.morphs[ i ];
  1074. const morphName = morph.morphName;
  1075. if ( morphTargetDictionary[ morphName ] === undefined ) continue;
  1076. morphs[ morphName ] = morphs[ morphName ] || [];
  1077. morphs[ morphName ].push( morph );
  1078. }
  1079. for ( const key in morphs ) {
  1080. const array = morphs[ key ];
  1081. array.sort( function ( a, b ) {
  1082. return a.frameNum - b.frameNum;
  1083. } );
  1084. const times = [];
  1085. const values = [];
  1086. for ( let i = 0, il = array.length; i < il; i ++ ) {
  1087. times.push( array[ i ].frameNum / 30 );
  1088. values.push( array[ i ].weight );
  1089. }
  1090. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluences[' + morphTargetDictionary[ key ] + ']', times, values ) );
  1091. }
  1092. return new AnimationClip( '', - 1, tracks );
  1093. }
  1094. /**
  1095. * @param {Object} vmd - parsed VMD data
  1096. * @return {AnimationClip}
  1097. */
  1098. buildCameraAnimation( vmd ) {
  1099. function pushVector3( array, vec ) {
  1100. array.push( vec.x );
  1101. array.push( vec.y );
  1102. array.push( vec.z );
  1103. }
  1104. function pushQuaternion( array, q ) {
  1105. array.push( q.x );
  1106. array.push( q.y );
  1107. array.push( q.z );
  1108. array.push( q.w );
  1109. }
  1110. function pushInterpolation( array, interpolation, index ) {
  1111. array.push( interpolation[ index * 4 + 0 ] / 127 ); // x1
  1112. array.push( interpolation[ index * 4 + 1 ] / 127 ); // x2
  1113. array.push( interpolation[ index * 4 + 2 ] / 127 ); // y1
  1114. array.push( interpolation[ index * 4 + 3 ] / 127 ); // y2
  1115. }
  1116. const cameras = vmd.cameras === undefined ? [] : vmd.cameras.slice();
  1117. cameras.sort( function ( a, b ) {
  1118. return a.frameNum - b.frameNum;
  1119. } );
  1120. const times = [];
  1121. const centers = [];
  1122. const quaternions = [];
  1123. const positions = [];
  1124. const fovs = [];
  1125. const cInterpolations = [];
  1126. const qInterpolations = [];
  1127. const pInterpolations = [];
  1128. const fInterpolations = [];
  1129. const quaternion = new Quaternion();
  1130. const euler = new Euler();
  1131. const position = new Vector3();
  1132. const center = new Vector3();
  1133. for ( let i = 0, il = cameras.length; i < il; i ++ ) {
  1134. const motion = cameras[ i ];
  1135. const time = motion.frameNum / 30;
  1136. const pos = motion.position;
  1137. const rot = motion.rotation;
  1138. const distance = motion.distance;
  1139. const fov = motion.fov;
  1140. const interpolation = motion.interpolation;
  1141. times.push( time );
  1142. position.set( 0, 0, - distance );
  1143. center.set( pos[ 0 ], pos[ 1 ], pos[ 2 ] );
  1144. euler.set( - rot[ 0 ], - rot[ 1 ], - rot[ 2 ] );
  1145. quaternion.setFromEuler( euler );
  1146. position.add( center );
  1147. position.applyQuaternion( quaternion );
  1148. pushVector3( centers, center );
  1149. pushQuaternion( quaternions, quaternion );
  1150. pushVector3( positions, position );
  1151. fovs.push( fov );
  1152. for ( let j = 0; j < 3; j ++ ) {
  1153. pushInterpolation( cInterpolations, interpolation, j );
  1154. }
  1155. pushInterpolation( qInterpolations, interpolation, 3 );
  1156. // use the same parameter for x, y, z axis.
  1157. for ( let j = 0; j < 3; j ++ ) {
  1158. pushInterpolation( pInterpolations, interpolation, 4 );
  1159. }
  1160. pushInterpolation( fInterpolations, interpolation, 5 );
  1161. }
  1162. const tracks = [];
  1163. // I expect an object whose name 'target' exists under THREE.Camera
  1164. tracks.push( this._createTrack( 'target.position', VectorKeyframeTrack, times, centers, cInterpolations ) );
  1165. tracks.push( this._createTrack( '.quaternion', QuaternionKeyframeTrack, times, quaternions, qInterpolations ) );
  1166. tracks.push( this._createTrack( '.position', VectorKeyframeTrack, times, positions, pInterpolations ) );
  1167. tracks.push( this._createTrack( '.fov', NumberKeyframeTrack, times, fovs, fInterpolations ) );
  1168. return new AnimationClip( '', - 1, tracks );
  1169. }
  1170. // private method
  1171. _createTrack( node, typedKeyframeTrack, times, values, interpolations ) {
  1172. /*
  1173. * optimizes here not to let KeyframeTrackPrototype optimize
  1174. * because KeyframeTrackPrototype optimizes times and values but
  1175. * doesn't optimize interpolations.
  1176. */
  1177. if ( times.length > 2 ) {
  1178. times = times.slice();
  1179. values = values.slice();
  1180. interpolations = interpolations.slice();
  1181. const stride = values.length / times.length;
  1182. const interpolateStride = interpolations.length / times.length;
  1183. let index = 1;
  1184. for ( let aheadIndex = 2, endIndex = times.length; aheadIndex < endIndex; aheadIndex ++ ) {
  1185. for ( let i = 0; i < stride; i ++ ) {
  1186. if ( values[ index * stride + i ] !== values[ ( index - 1 ) * stride + i ] ||
  1187. values[ index * stride + i ] !== values[ aheadIndex * stride + i ] ) {
  1188. index ++;
  1189. break;
  1190. }
  1191. }
  1192. if ( aheadIndex > index ) {
  1193. times[ index ] = times[ aheadIndex ];
  1194. for ( let i = 0; i < stride; i ++ ) {
  1195. values[ index * stride + i ] = values[ aheadIndex * stride + i ];
  1196. }
  1197. for ( let i = 0; i < interpolateStride; i ++ ) {
  1198. interpolations[ index * interpolateStride + i ] = interpolations[ aheadIndex * interpolateStride + i ];
  1199. }
  1200. }
  1201. }
  1202. times.length = index + 1;
  1203. values.length = ( index + 1 ) * stride;
  1204. interpolations.length = ( index + 1 ) * interpolateStride;
  1205. }
  1206. const track = new typedKeyframeTrack( node, times, values );
  1207. track.createInterpolant = function InterpolantFactoryMethodCubicBezier( result ) {
  1208. return new CubicBezierInterpolation( this.times, this.values, this.getValueSize(), result, new Float32Array( interpolations ) );
  1209. };
  1210. return track;
  1211. }
  1212. }
  1213. // interpolation
  1214. class CubicBezierInterpolation extends Interpolant {
  1215. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer, params ) {
  1216. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  1217. this.interpolationParams = params;
  1218. }
  1219. interpolate_( i1, t0, t, t1 ) {
  1220. const result = this.resultBuffer;
  1221. const values = this.sampleValues;
  1222. const stride = this.valueSize;
  1223. const params = this.interpolationParams;
  1224. const offset1 = i1 * stride;
  1225. const offset0 = offset1 - stride;
  1226. // No interpolation if next key frame is in one frame in 30fps.
  1227. // This is from MMD animation spec.
  1228. // '1.5' is for precision loss. times are Float32 in Three.js Animation system.
  1229. const weight1 = ( ( t1 - t0 ) < 1 / 30 * 1.5 ) ? 0.0 : ( t - t0 ) / ( t1 - t0 );
  1230. if ( stride === 4 ) { // Quaternion
  1231. const x1 = params[ i1 * 4 + 0 ];
  1232. const x2 = params[ i1 * 4 + 1 ];
  1233. const y1 = params[ i1 * 4 + 2 ];
  1234. const y2 = params[ i1 * 4 + 3 ];
  1235. const ratio = this._calculate( x1, x2, y1, y2, weight1 );
  1236. Quaternion.slerpFlat( result, 0, values, offset0, values, offset1, ratio );
  1237. } else if ( stride === 3 ) { // Vector3
  1238. for ( let i = 0; i !== stride; ++ i ) {
  1239. const x1 = params[ i1 * 12 + i * 4 + 0 ];
  1240. const x2 = params[ i1 * 12 + i * 4 + 1 ];
  1241. const y1 = params[ i1 * 12 + i * 4 + 2 ];
  1242. const y2 = params[ i1 * 12 + i * 4 + 3 ];
  1243. const ratio = this._calculate( x1, x2, y1, y2, weight1 );
  1244. result[ i ] = values[ offset0 + i ] * ( 1 - ratio ) + values[ offset1 + i ] * ratio;
  1245. }
  1246. } else { // Number
  1247. const x1 = params[ i1 * 4 + 0 ];
  1248. const x2 = params[ i1 * 4 + 1 ];
  1249. const y1 = params[ i1 * 4 + 2 ];
  1250. const y2 = params[ i1 * 4 + 3 ];
  1251. const ratio = this._calculate( x1, x2, y1, y2, weight1 );
  1252. result[ 0 ] = values[ offset0 ] * ( 1 - ratio ) + values[ offset1 ] * ratio;
  1253. }
  1254. return result;
  1255. }
  1256. _calculate( x1, x2, y1, y2, x ) {
  1257. /*
  1258. * Cubic Bezier curves
  1259. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Cubic_B.C3.A9zier_curves
  1260. *
  1261. * B(t) = ( 1 - t ) ^ 3 * P0
  1262. * + 3 * ( 1 - t ) ^ 2 * t * P1
  1263. * + 3 * ( 1 - t ) * t^2 * P2
  1264. * + t ^ 3 * P3
  1265. * ( 0 <= t <= 1 )
  1266. *
  1267. * MMD uses Cubic Bezier curves for bone and camera animation interpolation.
  1268. * http://d.hatena.ne.jp/edvakf/20111016/1318716097
  1269. *
  1270. * x = ( 1 - t ) ^ 3 * x0
  1271. * + 3 * ( 1 - t ) ^ 2 * t * x1
  1272. * + 3 * ( 1 - t ) * t^2 * x2
  1273. * + t ^ 3 * x3
  1274. * y = ( 1 - t ) ^ 3 * y0
  1275. * + 3 * ( 1 - t ) ^ 2 * t * y1
  1276. * + 3 * ( 1 - t ) * t^2 * y2
  1277. * + t ^ 3 * y3
  1278. * ( x0 = 0, y0 = 0 )
  1279. * ( x3 = 1, y3 = 1 )
  1280. * ( 0 <= t, x1, x2, y1, y2 <= 1 )
  1281. *
  1282. * Here solves this equation with Bisection method,
  1283. * https://en.wikipedia.org/wiki/Bisection_method
  1284. * gets t, and then calculate y.
  1285. *
  1286. * f(t) = 3 * ( 1 - t ) ^ 2 * t * x1
  1287. * + 3 * ( 1 - t ) * t^2 * x2
  1288. * + t ^ 3 - x = 0
  1289. *
  1290. * (Another option: Newton's method
  1291. * https://en.wikipedia.org/wiki/Newton%27s_method)
  1292. */
  1293. let c = 0.5;
  1294. let t = c;
  1295. let s = 1.0 - t;
  1296. const loop = 15;
  1297. const eps = 1e-5;
  1298. const math = Math;
  1299. let sst3, stt3, ttt;
  1300. for ( let i = 0; i < loop; i ++ ) {
  1301. sst3 = 3.0 * s * s * t;
  1302. stt3 = 3.0 * s * t * t;
  1303. ttt = t * t * t;
  1304. const ft = ( sst3 * x1 ) + ( stt3 * x2 ) + ( ttt ) - x;
  1305. if ( math.abs( ft ) < eps ) break;
  1306. c /= 2.0;
  1307. t += ( ft < 0 ) ? c : - c;
  1308. s = 1.0 - t;
  1309. }
  1310. return ( sst3 * y1 ) + ( stt3 * y2 ) + ttt;
  1311. }
  1312. }
  1313. export { MMDLoader };