MMDLoader.js 50 KB

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