MMDLoader.js 47 KB

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