MMDLoader.js 50 KB

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