MMDLoader.js 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850
  1. /**
  2. * @author takahiro / https://github.com/takahirox
  3. *
  4. * Dependencies
  5. * - mmd-parser https://github.com/takahirox/mmd-parser
  6. * - ammo.js https://github.com/kripken/ammo.js
  7. * - THREE.TGALoader
  8. * - THREE.MMDPhysics
  9. * - THREE.CCDIKSolver
  10. * - THREE.OutlineEffect
  11. *
  12. *
  13. * This loader loads and parses PMD/PMX and VMD binary files
  14. * then creates mesh for Three.js.
  15. *
  16. * PMD/PMX is a model data format and VMD is a motion data format
  17. * used in MMD(Miku Miku Dance).
  18. *
  19. * MMD is a 3D CG animation tool which is popular in Japan.
  20. *
  21. *
  22. * MMD official site
  23. * http://www.geocities.jp/higuchuu4/index_e.htm
  24. *
  25. * PMD, VMD format
  26. * http://blog.goo.ne.jp/torisu_tetosuki/e/209ad341d3ece2b1b4df24abf619d6e4
  27. *
  28. * PMX format
  29. * http://gulshan-i-raz.geo.jp/labs/2012/10/17/pmx-format1/
  30. *
  31. *
  32. * TODO
  33. * - light motion in vmd support.
  34. * - SDEF support.
  35. * - uv/material/bone morphing support.
  36. * - more precise grant skinning support.
  37. * - shadow support.
  38. */
  39. THREE.MMDLoader = function ( manager ) {
  40. THREE.Loader.call( this );
  41. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  42. this.parser = new MMDParser.Parser();
  43. this.textureCrossOrigin = null;
  44. };
  45. THREE.MMDLoader.prototype = Object.create( THREE.Loader.prototype );
  46. THREE.MMDLoader.prototype.constructor = THREE.MMDLoader;
  47. /*
  48. * base64 encoded defalut toon textures toon00.bmp - toon10.bmp
  49. * Users don't need to prepare default texture files.
  50. *
  51. * This idea is from http://www20.atpages.jp/katwat/three.js_r58/examples/mytest37/mmd.three.js
  52. */
  53. THREE.MMDLoader.prototype.defaultToonTextures = [
  54. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=',
  55. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAN0lEQVRYR+3WQREAMBACsZ5/bWiiMvgEBTt5cW37hjsBBAgQIECAwFwgyfYPCCBAgAABAgTWAh8aBHZBl14e8wAAAABJRU5ErkJggg==',
  56. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAOUlEQVRYR+3WMREAMAwDsYY/yoDI7MLwIiP40+RJklfcCCBAgAABAgTqArfb/QMCCBAgQIAAgbbAB3z/e0F3js2cAAAAAElFTkSuQmCC',
  57. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAN0lEQVRYR+3WQREAMBACsZ5/B5ilMvgEBTt5cW37hjsBBAgQIECAwFwgyfYPCCBAgAABAgTWAh81dWyx0gFwKAAAAABJRU5ErkJggg==',
  58. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAOklEQVRYR+3WoREAMAwDsWb/UQtCy9wxTOQJ/oQ8SXKKGwEECBAgQIBAXeDt7f4BAQQIECBAgEBb4AOz8Hzx7WLY4wAAAABJRU5ErkJggg==',
  59. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABPUlEQVRYR+1XwW7CMAy1+f9fZOMysSEOEweEOPRNdm3HbdOyIhAcklPrOs/PLy9RygBALxzcCDQFmgJNgaZAU6Ap0BR4PwX8gsRMVLssMRH5HcpzJEaWL7EVg9F1IHRlyqQohgVr4FGUlUcMJSjcUlDw0zvjeun70cLWmneoyf7NgBTQSniBTQQSuJAZsOnnaczjIMb5hCiuHKxokCrJfVnrctyZL0PkJAJe1HMil4nxeyi3Ypfn1kX51jpPvo/JeCNC4PhVdHdJw2XjBR8brF8PEIhNVn12AgP7uHsTBguBn53MUZCqv7Lp07Pn5k1Ro+uWmUNn7D+M57rtk7aG0Vo73xyF/fbFf0bPJjDXngnGocDTdFhygZjwUQrMNrDcmZlQT50VJ/g/UwNyHpu778+yW+/ksOz/BFo54P4AsUXMfRq7XWsAAAAASUVORK5CYII=',
  60. '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=',
  61. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=',
  62. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=',
  63. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=',
  64. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII='
  65. ];
  66. /*
  67. * Set 'anonymous' for the the texture image file in other domain
  68. * even if server responds with "Access-Control-Allow-Origin: *"
  69. * because some image operation fails in MMDLoader.
  70. */
  71. THREE.MMDLoader.prototype.setTextureCrossOrigin = function ( value ) {
  72. this.textureCrossOrigin = value;
  73. };
  74. THREE.MMDLoader.prototype.load = function ( modelUrl, vmdUrls, callback, onProgress, onError ) {
  75. var scope = this;
  76. this.loadModel( modelUrl, function ( mesh ) {
  77. scope.loadVmds( vmdUrls, function ( vmd ) {
  78. scope.pourVmdIntoModel( mesh, vmd );
  79. callback( mesh );
  80. }, onProgress, onError );
  81. }, onProgress, onError );
  82. };
  83. THREE.MMDLoader.prototype.loadModel = function ( url, callback, onProgress, onError ) {
  84. var scope = this;
  85. var texturePath = this.extractUrlBase( url );
  86. var modelExtension = this.extractExtension( url );
  87. this.loadFileAsBuffer( url, function ( buffer ) {
  88. callback( scope.createModel( buffer, modelExtension, texturePath, onProgress, onError ) );
  89. }, onProgress, onError );
  90. };
  91. THREE.MMDLoader.prototype.createModel = function ( buffer, modelExtension, texturePath, onProgress, onError ) {
  92. return this.createMesh( this.parseModel( buffer, modelExtension ), texturePath, onProgress, onError );
  93. };
  94. THREE.MMDLoader.prototype.loadVmd = function ( url, callback, onProgress, onError ) {
  95. var scope = this;
  96. this.loadFileAsBuffer( url, function ( buffer ) {
  97. callback( scope.parseVmd( buffer ) );
  98. }, onProgress, onError );
  99. };
  100. THREE.MMDLoader.prototype.loadVmds = function ( urls, callback, onProgress, onError ) {
  101. var scope = this;
  102. var vmds = [];
  103. urls = urls.slice();
  104. function run () {
  105. var url = urls.shift();
  106. scope.loadVmd( url, function ( vmd ) {
  107. vmds.push( vmd );
  108. if ( urls.length > 0 ) {
  109. run();
  110. } else {
  111. callback( scope.mergeVmds( vmds ) );
  112. }
  113. }, onProgress, onError );
  114. }
  115. run();
  116. };
  117. THREE.MMDLoader.prototype.loadAudio = function ( url, callback, onProgress, onError ) {
  118. var listener = new THREE.AudioListener();
  119. var audio = new THREE.Audio( listener );
  120. var loader = new THREE.AudioLoader( this.manager );
  121. loader.load( url, function ( buffer ) {
  122. audio.setBuffer( buffer );
  123. callback( audio, listener );
  124. }, onProgress, onError );
  125. };
  126. THREE.MMDLoader.prototype.loadVpd = function ( url, callback, onProgress, onError, params ) {
  127. var scope = this;
  128. var func = ( ( params && params.charcode === 'unicode' ) ? this.loadFileAsText : this.loadFileAsShiftJISText ).bind( this );
  129. func( url, function ( text ) {
  130. callback( scope.parseVpd( text ) );
  131. }, onProgress, onError );
  132. };
  133. THREE.MMDLoader.prototype.parseModel = function ( buffer, modelExtension ) {
  134. // Should I judge from model data header?
  135. switch( modelExtension.toLowerCase() ) {
  136. case 'pmd':
  137. return this.parsePmd( buffer );
  138. case 'pmx':
  139. return this.parsePmx( buffer );
  140. default:
  141. throw 'extension ' + modelExtension + ' is not supported.';
  142. }
  143. };
  144. THREE.MMDLoader.prototype.parsePmd = function ( buffer ) {
  145. return this.parser.parsePmd( buffer, true );
  146. };
  147. THREE.MMDLoader.prototype.parsePmx = function ( buffer ) {
  148. return this.parser.parsePmx( buffer, true );
  149. };
  150. THREE.MMDLoader.prototype.parseVmd = function ( buffer ) {
  151. return this.parser.parseVmd( buffer, true );
  152. };
  153. THREE.MMDLoader.prototype.parseVpd = function ( text ) {
  154. return this.parser.parseVpd( text, true );
  155. };
  156. THREE.MMDLoader.prototype.mergeVmds = function ( vmds ) {
  157. return this.parser.mergeVmds( vmds );
  158. };
  159. THREE.MMDLoader.prototype.pourVmdIntoModel = function ( mesh, vmd, name ) {
  160. this.createAnimation( mesh, vmd, name );
  161. };
  162. THREE.MMDLoader.prototype.pourVmdIntoCamera = function ( camera, vmd, name ) {
  163. var helper = new THREE.MMDLoader.DataCreationHelper();
  164. var initAnimation = function () {
  165. var orderedMotions = helper.createOrderedMotionArray( vmd.cameras );
  166. var times = [];
  167. var centers = [];
  168. var quaternions = [];
  169. var positions = [];
  170. var fovs = [];
  171. var cInterpolations = [];
  172. var qInterpolations = [];
  173. var pInterpolations = [];
  174. var fInterpolations = [];
  175. var quaternion = new THREE.Quaternion();
  176. var euler = new THREE.Euler();
  177. var position = new THREE.Vector3();
  178. var center = new THREE.Vector3();
  179. var pushVector3 = function ( array, vec ) {
  180. array.push( vec.x );
  181. array.push( vec.y );
  182. array.push( vec.z );
  183. };
  184. var pushQuaternion = function ( array, q ) {
  185. array.push( q.x );
  186. array.push( q.y );
  187. array.push( q.z );
  188. array.push( q.w );
  189. };
  190. var pushInterpolation = function ( array, interpolation, index ) {
  191. array.push( interpolation[ index * 4 + 0 ] / 127 ); // x1
  192. array.push( interpolation[ index * 4 + 1 ] / 127 ); // x2
  193. array.push( interpolation[ index * 4 + 2 ] / 127 ); // y1
  194. array.push( interpolation[ index * 4 + 3 ] / 127 ); // y2
  195. };
  196. var createTrack = function ( node, type, times, values, interpolations ) {
  197. /*
  198. * optimizes here not to let KeyframeTrackPrototype optimize
  199. * because KeyframeTrackPrototype optimizes times and values but
  200. * doesn't optimize interpolations.
  201. */
  202. if ( times.length > 2 ) {
  203. times = times.slice();
  204. values = values.slice();
  205. interpolations = interpolations.slice();
  206. var stride = values.length / times.length;
  207. var interpolateStride = ( stride === 3 ) ? 12 : 4; // 3: Vector3, others: Quaternion or Number
  208. var aheadIndex = 2;
  209. var index = 1;
  210. for ( aheadIndex = 2, endIndex = times.length; aheadIndex < endIndex; aheadIndex ++ ) {
  211. for ( var i = 0; i < stride; i ++ ) {
  212. if ( values[ index * stride + i ] !== values[ ( index - 1 ) * stride + i ] ||
  213. values[ index * stride + i ] !== values[ aheadIndex * stride + i ] ) {
  214. index ++;
  215. break;
  216. }
  217. }
  218. if ( aheadIndex > index ) {
  219. times[ index ] = times[ aheadIndex ];
  220. for ( var i = 0; i < stride; i ++ ) {
  221. values[ index * stride + i ] = values[ aheadIndex * stride + i ];
  222. }
  223. for ( var i = 0; i < interpolateStride; i ++ ) {
  224. interpolations[ index * interpolateStride + i ] = interpolations[ aheadIndex * interpolateStride + i ];
  225. }
  226. }
  227. }
  228. times.length = index + 1;
  229. values.length = ( index + 1 ) * stride;
  230. interpolations.length = ( index + 1 ) * interpolateStride;
  231. }
  232. return new THREE.MMDLoader[ type ]( node, times, values, interpolations );
  233. };
  234. for ( var i = 0; i < orderedMotions.length; i++ ) {
  235. var m = orderedMotions[ i ];
  236. var time = m.frameNum / 30;
  237. var pos = m.position;
  238. var rot = m.rotation;
  239. var distance = m.distance;
  240. var fov = m.fov;
  241. var interpolation = m.interpolation;
  242. position.set( 0, 0, -distance );
  243. center.set( pos[ 0 ], pos[ 1 ], pos[ 2 ] );
  244. euler.set( -rot[ 0 ], -rot[ 1 ], -rot[ 2 ] );
  245. quaternion.setFromEuler( euler );
  246. position.add( center );
  247. position.applyQuaternion( quaternion );
  248. /*
  249. * Note: This is a workaround not to make Animation system calculate lerp
  250. * if the diff from the last frame is 1 frame (in 30fps).
  251. */
  252. if ( times.length > 0 && time < times[ times.length - 1 ] + ( 1 / 30 ) * 1.5 ) {
  253. times[ times.length - 1 ] = time - 1e-13;
  254. }
  255. times.push( time );
  256. pushVector3( centers, center );
  257. pushQuaternion( quaternions, quaternion );
  258. pushVector3( positions, position );
  259. fovs.push( fov );
  260. for ( var j = 0; j < 3; j ++ ) {
  261. pushInterpolation( cInterpolations, interpolation, j );
  262. }
  263. pushInterpolation( qInterpolations, interpolation, 3 );
  264. // use same one parameter for x, y, z axis.
  265. for ( var j = 0; j < 3; j ++ ) {
  266. pushInterpolation( pInterpolations, interpolation, 4 );
  267. }
  268. pushInterpolation( fInterpolations, interpolation, 5 );
  269. }
  270. if ( times.length === 0 ) return;
  271. var tracks = [];
  272. tracks.push( createTrack( '.center', 'VectorKeyframeTrackEx', times, centers, cInterpolations ) );
  273. tracks.push( createTrack( '.quaternion', 'QuaternionKeyframeTrackEx', times, quaternions, qInterpolations ) );
  274. tracks.push( createTrack( '.position', 'VectorKeyframeTrackEx', times, positions, pInterpolations ) );
  275. tracks.push( createTrack( '.fov', 'NumberKeyframeTrackEx', times, fovs, fInterpolations ) );
  276. var clip = new THREE.AnimationClip( name === undefined ? THREE.Math.generateUUID() : name, -1, tracks );
  277. if ( clip !== null ) {
  278. if ( camera.center === undefined ) camera.center = new THREE.Vector3( 0, 0, 0 );
  279. if ( camera.animations === undefined ) camera.animations = [];
  280. camera.animations.push( clip );
  281. }
  282. };
  283. initAnimation();
  284. };
  285. THREE.MMDLoader.prototype.extractExtension = function ( url ) {
  286. var index = url.lastIndexOf( '.' );
  287. if ( index < 0 ) {
  288. return null;
  289. }
  290. return url.slice( index + 1 );
  291. };
  292. THREE.MMDLoader.prototype.loadFile = function ( url, onLoad, onProgress, onError, responseType, mimeType ) {
  293. var loader = new THREE.FileLoader( this.manager );
  294. if ( mimeType !== undefined ) loader.setMimeType( mimeType );
  295. loader.setResponseType( responseType );
  296. var request = loader.load( url, function ( result ) {
  297. onLoad( result );
  298. }, onProgress, onError );
  299. return request;
  300. };
  301. THREE.MMDLoader.prototype.loadFileAsBuffer = function ( url, onLoad, onProgress, onError ) {
  302. this.loadFile( url, onLoad, onProgress, onError, 'arraybuffer' );
  303. };
  304. THREE.MMDLoader.prototype.loadFileAsText = function ( url, onLoad, onProgress, onError ) {
  305. this.loadFile( url, onLoad, onProgress, onError, 'text' );
  306. };
  307. THREE.MMDLoader.prototype.loadFileAsShiftJISText = function ( url, onLoad, onProgress, onError ) {
  308. this.loadFile( url, onLoad, onProgress, onError, 'text', 'text/plain; charset=shift_jis' );
  309. };
  310. THREE.MMDLoader.prototype.createMesh = function ( model, texturePath, onProgress, onError ) {
  311. var scope = this;
  312. var geometry = new THREE.BufferGeometry();
  313. var material = new THREE.MultiMaterial();
  314. var helper = new THREE.MMDLoader.DataCreationHelper();
  315. var buffer = {};
  316. buffer.vertices = [];
  317. buffer.uvs = [];
  318. buffer.normals = [];
  319. buffer.skinIndices = [];
  320. buffer.skinWeights = [];
  321. buffer.indices = [];
  322. var initVartices = function () {
  323. for ( var i = 0; i < model.metadata.vertexCount; i++ ) {
  324. var v = model.vertices[ i ];
  325. for ( var j = 0, jl = v.position.length; j < jl; j ++ ) {
  326. buffer.vertices.push( v.position[ j ] );
  327. }
  328. for ( var j = 0, jl = v.normal.length; j < jl; j ++ ) {
  329. buffer.normals.push( v.normal[ j ] );
  330. }
  331. for ( var j = 0, jl = v.uv.length; j < jl; j ++ ) {
  332. buffer.uvs.push( v.uv[ j ] );
  333. }
  334. for ( var j = 0; j < 4; j ++ ) {
  335. buffer.skinIndices.push( v.skinIndices.length - 1 >= j ? v.skinIndices[ j ] : 0.0 );
  336. }
  337. for ( var j = 0; j < 4; j ++ ) {
  338. buffer.skinWeights.push( v.skinWeights.length - 1 >= j ? v.skinWeights[ j ] : 0.0 );
  339. }
  340. }
  341. };
  342. var initFaces = function () {
  343. for ( var i = 0; i < model.metadata.faceCount; i++ ) {
  344. var f = model.faces[ i ];
  345. for ( var j = 0, jl = f.indices.length; j < jl; j ++ ) {
  346. buffer.indices.push( f.indices[ j ] );
  347. }
  348. }
  349. };
  350. var initBones = function () {
  351. var bones = [];
  352. var rigidBodies = model.rigidBodies;
  353. var dictionary = {};
  354. for ( var i = 0, il = rigidBodies.length; i < il; i ++ ) {
  355. var body = rigidBodies[ i ];
  356. var value = dictionary[ body.boneIndex ];
  357. // keeps greater number if already value is set without any special reasons
  358. value = value === undefined ? body.type : Math.max( body.type, value );
  359. dictionary[ body.boneIndex ] = value;
  360. }
  361. for ( var i = 0; i < model.metadata.boneCount; i++ ) {
  362. var bone = {};
  363. var b = model.bones[ i ];
  364. bone.parent = b.parentIndex;
  365. bone.name = b.name;
  366. bone.pos = [ b.position[ 0 ], b.position[ 1 ], b.position[ 2 ] ];
  367. bone.rotq = [ 0, 0, 0, 1 ];
  368. bone.scl = [ 1, 1, 1 ];
  369. if ( bone.parent !== -1 ) {
  370. bone.pos[ 0 ] -= model.bones[ bone.parent ].position[ 0 ];
  371. bone.pos[ 1 ] -= model.bones[ bone.parent ].position[ 1 ];
  372. bone.pos[ 2 ] -= model.bones[ bone.parent ].position[ 2 ];
  373. }
  374. bone.rigidBodyType = dictionary[ i ] !== undefined ? dictionary[ i ] : -1;
  375. bones.push( bone );
  376. }
  377. geometry.bones = bones;
  378. };
  379. var initIKs = function () {
  380. var iks = [];
  381. // TODO: remove duplicated codes between PMD and PMX
  382. if ( model.metadata.format === 'pmd' ) {
  383. for ( var i = 0; i < model.metadata.ikCount; i++ ) {
  384. var ik = model.iks[i];
  385. var param = {};
  386. param.target = ik.target;
  387. param.effector = ik.effector;
  388. param.iteration = ik.iteration;
  389. param.maxAngle = ik.maxAngle * 4;
  390. param.links = [];
  391. for ( var j = 0; j < ik.links.length; j++ ) {
  392. var link = {};
  393. link.index = ik.links[ j ].index;
  394. if ( model.bones[ link.index ].name.indexOf( 'ひざ' ) >= 0 ) {
  395. link.limitation = new THREE.Vector3( 1.0, 0.0, 0.0 );
  396. }
  397. param.links.push( link );
  398. }
  399. iks.push( param );
  400. }
  401. } else {
  402. for ( var i = 0; i < model.metadata.boneCount; i++ ) {
  403. var b = model.bones[ i ];
  404. var ik = b.ik;
  405. if ( ik === undefined ) {
  406. continue;
  407. }
  408. var param = {};
  409. param.target = i;
  410. param.effector = ik.effector;
  411. param.iteration = ik.iteration;
  412. param.maxAngle = ik.maxAngle;
  413. param.links = [];
  414. for ( var j = 0; j < ik.links.length; j++ ) {
  415. var link = {};
  416. link.index = ik.links[ j ].index;
  417. link.enabled = true;
  418. if ( ik.links[ j ].angleLimitation === 1 ) {
  419. link.limitation = new THREE.Vector3( 1.0, 0.0, 0.0 );
  420. // TODO: use limitation angles
  421. // link.lowerLimitationAngle;
  422. // link.upperLimitationAngle;
  423. }
  424. param.links.push( link );
  425. }
  426. iks.push( param );
  427. }
  428. }
  429. geometry.iks = iks;
  430. };
  431. var initGrants = function () {
  432. if ( model.metadata.format === 'pmd' ) {
  433. return;
  434. }
  435. var grants = [];
  436. for ( var i = 0; i < model.metadata.boneCount; i++ ) {
  437. var b = model.bones[ i ];
  438. var grant = b.grant;
  439. if ( grant === undefined ) {
  440. continue;
  441. }
  442. var param = {};
  443. param.index = i;
  444. param.parentIndex = grant.parentIndex;
  445. param.ratio = grant.ratio;
  446. param.isLocal = grant.isLocal;
  447. param.affectRotation = grant.affectRotation;
  448. param.affectPosition = grant.affectPosition;
  449. param.transformationClass = b.transformationClass;
  450. grants.push( param );
  451. }
  452. grants.sort( function ( a, b ) {
  453. return a.transformationClass - b.transformationClass;
  454. } );
  455. geometry.grants = grants;
  456. };
  457. var initMorphs = function () {
  458. function updateVertex( attribute, index, v, ratio ) {
  459. attribute.array[ index * 3 + 0 ] += v.position[ 0 ] * ratio;
  460. attribute.array[ index * 3 + 1 ] += v.position[ 1 ] * ratio;
  461. attribute.array[ index * 3 + 2 ] += v.position[ 2 ] * ratio;
  462. }
  463. function updateVertices( attribute, m, ratio ) {
  464. for ( var i = 0; i < m.elementCount; i++ ) {
  465. var v = m.elements[ i ];
  466. var index;
  467. if ( model.metadata.format === 'pmd' ) {
  468. index = model.morphs[ 0 ].elements[ v.index ].index;
  469. } else {
  470. index = v.index;
  471. }
  472. updateVertex( attribute, index, v, ratio );
  473. }
  474. }
  475. var morphTargets = [];
  476. var attributes = [];
  477. for ( var i = 0; i < model.metadata.morphCount; i++ ) {
  478. var m = model.morphs[ i ];
  479. var params = { name: m.name };
  480. var attribute = new THREE.Float32BufferAttribute( model.metadata.vertexCount * 3, 3 );
  481. for ( var j = 0; j < model.metadata.vertexCount * 3; j++ ) {
  482. attribute.array[ j ] = buffer.vertices[ j ];
  483. }
  484. if ( model.metadata.format === 'pmd' ) {
  485. if ( i !== 0 ) {
  486. updateVertices( attribute, m, 1.0 );
  487. }
  488. } else {
  489. if ( m.type === 0 ) { // group
  490. for ( var j = 0; j < m.elementCount; j++ ) {
  491. var m2 = model.morphs[ m.elements[ j ].index ];
  492. var ratio = m.elements[ j ].ratio;
  493. if ( m2.type === 1 ) {
  494. updateVertices( attribute, m2, ratio );
  495. } else {
  496. // TODO: implement
  497. }
  498. }
  499. } else if ( m.type === 1 ) { // vertex
  500. updateVertices( attribute, m, 1.0 );
  501. } else if ( m.type === 2 ) { // bone
  502. // TODO: implement
  503. } else if ( m.type === 3 ) { // uv
  504. // TODO: implement
  505. } else if ( m.type === 4 ) { // additional uv1
  506. // TODO: implement
  507. } else if ( m.type === 5 ) { // additional uv2
  508. // TODO: implement
  509. } else if ( m.type === 6 ) { // additional uv3
  510. // TODO: implement
  511. } else if ( m.type === 7 ) { // additional uv4
  512. // TODO: implement
  513. } else if ( m.type === 8 ) { // material
  514. // TODO: implement
  515. }
  516. }
  517. morphTargets.push( params );
  518. attributes.push( attribute );
  519. }
  520. geometry.morphTargets = morphTargets;
  521. geometry.morphAttributes.position = attributes;
  522. };
  523. var initMaterials = function () {
  524. var textures = {};
  525. var textureLoader = new THREE.TextureLoader( scope.manager );
  526. var tgaLoader = new THREE.TGALoader( scope.manager );
  527. var canvas = document.createElement( 'canvas' );
  528. var context = canvas.getContext( '2d' );
  529. var offset = 0;
  530. var materialParams = [];
  531. if ( scope.textureCrossOrigin !== null ) textureLoader.setCrossOrigin( scope.textureCrossOrigin );
  532. function loadTexture ( filePath, params ) {
  533. if ( params === undefined ) {
  534. params = {};
  535. }
  536. var fullPath;
  537. if ( params.defaultTexturePath === true ) {
  538. try {
  539. fullPath = scope.defaultToonTextures[ parseInt( filePath.match( 'toon([0-9]{2})\.bmp$' )[ 1 ] ) ];
  540. } catch ( e ) {
  541. console.warn( 'THREE.MMDLoader: ' + filePath + ' seems like not right default texture path. Using toon00.bmp instead.' );
  542. fullPath = scope.defaultToonTextures[ 0 ];
  543. }
  544. } else {
  545. fullPath = texturePath + filePath;
  546. }
  547. if ( textures[ fullPath ] !== undefined ) return fullPath;
  548. var loader = THREE.Loader.Handlers.get( fullPath );
  549. if ( loader === null ) {
  550. loader = ( filePath.indexOf( '.tga' ) >= 0 ) ? tgaLoader : textureLoader;
  551. }
  552. var texture = loader.load( fullPath, function ( t ) {
  553. // MMD toon texture is Axis-Y oriented
  554. // but Three.js gradient map is Axis-X oriented.
  555. // So here replaces the toon texture image with the rotated one.
  556. if ( params.isToonTexture === true ) {
  557. var image = t.image;
  558. var width = image.width;
  559. var height = image.height;
  560. canvas.width = width;
  561. canvas.height = height;
  562. context.clearRect( 0, 0, width, height );
  563. context.translate( width / 2.0, height / 2.0 );
  564. context.rotate( 0.5 * Math.PI ); // 90.0 * Math.PI / 180.0
  565. context.translate( -width / 2.0, -height / 2.0 );
  566. context.drawImage( image, 0, 0 );
  567. t.image = context.getImageData( 0, 0, width, height );
  568. }
  569. t.flipY = false;
  570. t.wrapS = THREE.RepeatWrapping;
  571. t.wrapT = THREE.RepeatWrapping;
  572. if ( params.sphericalReflectionMapping === true ) {
  573. t.mapping = THREE.SphericalReflectionMapping;
  574. }
  575. for ( var i = 0; i < texture.readyCallbacks.length; i++ ) {
  576. texture.readyCallbacks[ i ]( texture );
  577. }
  578. delete texture.readyCallbacks;
  579. }, onProgress, onError );
  580. texture.readyCallbacks = [];
  581. textures[ fullPath ] = texture;
  582. return fullPath;
  583. }
  584. function getTexture( name, textures ) {
  585. if ( textures[ name ] === undefined ) {
  586. console.warn( 'THREE.MMDLoader: Undefined texture', name );
  587. }
  588. return textures[ name ];
  589. }
  590. for ( var i = 0; i < model.metadata.materialCount; i++ ) {
  591. var m = model.materials[ i ];
  592. var params = {};
  593. params.faceOffset = offset;
  594. params.faceNum = m.faceCount;
  595. offset += m.faceCount;
  596. params.name = m.name;
  597. /*
  598. * Color
  599. *
  600. * MMD MeshToonMaterial
  601. * diffuse - color
  602. * specular - specular
  603. * ambient - emissive * a
  604. * (a = 1.0 without map texture or 0.2 with map texture)
  605. *
  606. * MeshToonMaterial doesn't have ambient. Set it to emissive instead.
  607. * It'll be too bright if material has map texture so using coef 0.2.
  608. */
  609. params.color = new THREE.Color( m.diffuse[ 0 ], m.diffuse[ 1 ], m.diffuse[ 2 ] );
  610. params.opacity = m.diffuse[ 3 ];
  611. params.specular = new THREE.Color( m.specular[ 0 ], m.specular[ 1 ], m.specular[ 2 ] );
  612. params.shininess = m.shininess;
  613. if ( params.opacity === 1.0 ) {
  614. params.side = THREE.FrontSide;
  615. params.transparent = false;
  616. } else {
  617. params.side = THREE.DoubleSide;
  618. params.transparent = true;
  619. }
  620. if ( model.metadata.format === 'pmd' ) {
  621. if ( m.fileName ) {
  622. var fileName = m.fileName;
  623. var fileNames = [];
  624. var index = fileName.lastIndexOf( '*' );
  625. if ( index >= 0 ) {
  626. fileNames.push( fileName.slice( 0, index ) );
  627. fileNames.push( fileName.slice( index + 1 ) );
  628. } else {
  629. fileNames.push( fileName );
  630. }
  631. for ( var j = 0; j < fileNames.length; j++ ) {
  632. var n = fileNames[ j ];
  633. if ( n.indexOf( '.sph' ) >= 0 || n.indexOf( '.spa' ) >= 0 ) {
  634. params.envMap = loadTexture( n, { sphericalReflectionMapping: true } );
  635. if ( n.indexOf( '.sph' ) >= 0 ) {
  636. params.envMapType = THREE.MultiplyOperation;
  637. } else {
  638. params.envMapType = THREE.AddOperation;
  639. }
  640. } else {
  641. params.map = loadTexture( n );
  642. }
  643. }
  644. }
  645. } else {
  646. if ( m.textureIndex !== -1 ) {
  647. var n = model.textures[ m.textureIndex ];
  648. params.map = loadTexture( n );
  649. }
  650. // TODO: support m.envFlag === 3
  651. if ( m.envTextureIndex !== -1 && ( m.envFlag === 1 || m.envFlag == 2 ) ) {
  652. var n = model.textures[ m.envTextureIndex ];
  653. params.envMap = loadTexture( n, { sphericalReflectionMapping: true } );
  654. if ( m.envFlag === 1 ) {
  655. params.envMapType = THREE.MultiplyOperation;
  656. } else {
  657. params.envMapType = THREE.AddOperation;
  658. }
  659. }
  660. }
  661. var coef = ( params.map === undefined ) ? 1.0 : 0.2;
  662. params.emissive = new THREE.Color( m.ambient[ 0 ] * coef, m.ambient[ 1 ] * coef, m.ambient[ 2 ] * coef );
  663. materialParams.push( params );
  664. }
  665. for ( var i = 0; i < materialParams.length; i++ ) {
  666. var p = materialParams[ i ];
  667. var p2 = model.materials[ i ];
  668. var m = new THREE.MeshToonMaterial();
  669. geometry.addGroup( p.faceOffset * 3, p.faceNum * 3, i );
  670. if ( p.name !== undefined ) m.name = p.name;
  671. m.skinning = geometry.bones.length > 0 ? true : false;
  672. m.morphTargets = geometry.morphTargets.length > 0 ? true : false;
  673. m.lights = true;
  674. m.side = ( model.metadata.format === 'pmx' && ( p2.flag & 0x1 ) === 1 ) ? THREE.DoubleSide : p.side;
  675. m.transparent = p.transparent;
  676. m.fog = true;
  677. m.blending = THREE.CustomBlending;
  678. m.blendSrc = THREE.SrcAlphaFactor;
  679. m.blendDst = THREE.OneMinusSrcAlphaFactor;
  680. m.blendSrcAlpha = THREE.SrcAlphaFactor;
  681. m.blendDstAlpha = THREE.DstAlphaFactor;
  682. if ( p.map !== undefined ) {
  683. m.faceOffset = p.faceOffset;
  684. m.faceNum = p.faceNum;
  685. // Check if this part of the texture image the material uses requires transparency
  686. function checkTextureTransparency ( m ) {
  687. m.map.readyCallbacks.push( function ( t ) {
  688. // Is there any efficient ways?
  689. function createImageData ( image ) {
  690. var c = document.createElement( 'canvas' );
  691. c.width = image.width;
  692. c.height = image.height;
  693. var ctx = c.getContext( '2d' );
  694. ctx.drawImage( image, 0, 0 );
  695. return ctx.getImageData( 0, 0, c.width, c.height );
  696. }
  697. function detectTextureTransparency( image, uvs, indices ) {
  698. var width = image.width;
  699. var height = image.height;
  700. var data = image.data;
  701. var threshold = 253;
  702. if ( data.length / ( width * height ) !== 4 ) {
  703. return false;
  704. }
  705. for ( var i = 0; i < indices.length; i += 3 ) {
  706. var centerUV = { x: 0.0, y: 0.0 };
  707. for ( var j = 0; j < 3; j++ ) {
  708. var index = indices[ i * 3 + j ];
  709. var uv = { x: uvs[ index * 2 + 0 ], y: uvs[ index * 2 + 1 ] };
  710. if ( getAlphaByUv( image, uv ) < threshold ) {
  711. return true;
  712. }
  713. centerUV.x += uv.x;
  714. centerUV.y += uv.y;
  715. }
  716. centerUV.x /= 3;
  717. centerUV.y /= 3;
  718. if ( getAlphaByUv( image, centerUV ) < threshold ) {
  719. return true;
  720. }
  721. }
  722. return false;
  723. }
  724. /*
  725. * This method expects
  726. * t.flipY = false
  727. * t.wrapS = THREE.RepeatWrapping
  728. * t.wrapT = THREE.RepeatWrapping
  729. * TODO: more precise
  730. */
  731. function getAlphaByUv ( image, uv ) {
  732. var width = image.width;
  733. var height = image.height;
  734. var x = Math.round( uv.x * width ) % width;
  735. var y = Math.round( uv.y * height ) % height;
  736. if ( x < 0 ) {
  737. x += width;
  738. }
  739. if ( y < 0 ) {
  740. y += height;
  741. }
  742. var index = y * width + x;
  743. return image.data[ index * 4 + 3 ];
  744. }
  745. var imageData = t.image.data !== undefined ? t.image : createImageData( t.image );
  746. var indices = geometry.index.array.slice( m.faceOffset * 3, m.faceOffset * 3 + m.faceNum * 3 );
  747. if ( detectTextureTransparency( imageData, geometry.attributes.uv.array, indices ) ) m.transparent = true;
  748. delete m.faceOffset;
  749. delete m.faceNum;
  750. } );
  751. }
  752. m.map = getTexture( p.map, textures );
  753. checkTextureTransparency( m );
  754. }
  755. if ( p.envMap !== undefined ) {
  756. m.envMap = getTexture( p.envMap, textures );
  757. m.combine = p.envMapType;
  758. // TODO: WebGLRenderer should automatically update?
  759. m.envMap.readyCallbacks.push( function ( t ) {
  760. m.needsUpdate = true;
  761. } );
  762. }
  763. m.opacity = p.opacity;
  764. m.color = p.color;
  765. if ( p.emissive !== undefined ) {
  766. m.emissive = p.emissive;
  767. }
  768. m.specular = p.specular;
  769. m.shininess = Math.max( p.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  770. if ( model.metadata.format === 'pmd' ) {
  771. function isDefaultToonTexture ( n ) {
  772. if ( n.length !== 10 ) {
  773. return false;
  774. }
  775. return n.match( /toon(10|0[0-9]).bmp/ ) === null ? false : true;
  776. }
  777. m.outlineParameters = {
  778. thickness: p2.edgeFlag === 1 ? 0.003 : 0.0,
  779. color: new THREE.Color( 0.0, 0.0, 0.0 ),
  780. alpha: 1.0
  781. };
  782. if ( m.outlineParameters.thickness === 0.0 ) m.outlineParameters.visible = false;
  783. var toonFileName = ( p2.toonIndex === -1 ) ? 'toon00.bmp' : model.toonTextures[ p2.toonIndex ].fileName;
  784. var uuid = loadTexture( toonFileName, { isToonTexture: true, defaultTexturePath: isDefaultToonTexture( toonFileName ) } );
  785. m.gradientMap = getTexture( uuid, textures );
  786. } else {
  787. m.outlineParameters = {
  788. thickness: p2.edgeSize / 300,
  789. color: new THREE.Color( p2.edgeColor[ 0 ], p2.edgeColor[ 1 ], p2.edgeColor[ 2 ] ),
  790. alpha: p2.edgeColor[ 3 ]
  791. };
  792. if ( ( p2.flag & 0x10 ) === 0 || m.outlineParameters.thickness === 0.0 ) m.outlineParameters.visible = false;
  793. var toonFileName, isDefaultToon;
  794. if ( p2.toonIndex === -1 || p2.toonFlag !== 0 ) {
  795. var num = p2.toonIndex + 1;
  796. toonFileName = 'toon' + ( num < 10 ? '0' + num : num ) + '.bmp';
  797. isDefaultToon = true;
  798. } else {
  799. toonFileName = model.textures[ p2.toonIndex ];
  800. isDefaultToon = false;
  801. }
  802. var uuid = loadTexture( toonFileName, { isToonTexture: true, defaultTexturePath: isDefaultToon } );
  803. m.gradientMap = getTexture( uuid, textures );
  804. }
  805. material.materials.push( m );
  806. }
  807. if ( model.metadata.format === 'pmx' ) {
  808. function checkAlphaMorph ( morph, elements ) {
  809. if ( morph.type !== 8 ) {
  810. return;
  811. }
  812. for ( var i = 0; i < elements.length; i++ ) {
  813. var e = elements[ i ];
  814. if ( e.index === -1 ) {
  815. continue;
  816. }
  817. var m = material.materials[ e.index ];
  818. if ( m.opacity !== e.diffuse[ 3 ] ) {
  819. m.transparent = true;
  820. }
  821. }
  822. }
  823. for ( var i = 0; i < model.morphs.length; i++ ) {
  824. var morph = model.morphs[ i ];
  825. var elements = morph.elements;
  826. if ( morph.type === 0 ) {
  827. for ( var j = 0; j < elements.length; j++ ) {
  828. var morph2 = model.morphs[ elements[ j ].index ];
  829. var elements2 = morph2.elements;
  830. checkAlphaMorph( morph2, elements2 );
  831. }
  832. } else {
  833. checkAlphaMorph( morph, elements );
  834. }
  835. }
  836. }
  837. };
  838. var initPhysics = function () {
  839. var rigidBodies = [];
  840. var constraints = [];
  841. for ( var i = 0; i < model.metadata.rigidBodyCount; i++ ) {
  842. var b = model.rigidBodies[ i ];
  843. var keys = Object.keys( b );
  844. var p = {};
  845. for ( var j = 0; j < keys.length; j++ ) {
  846. var key = keys[ j ];
  847. p[ key ] = b[ key ];
  848. }
  849. /*
  850. * RigidBody position parameter in PMX seems global position
  851. * while the one in PMD seems offset from corresponding bone.
  852. * So unify being offset.
  853. */
  854. if ( model.metadata.format === 'pmx' ) {
  855. if ( p.boneIndex !== -1 ) {
  856. var bone = model.bones[ p.boneIndex ];
  857. p.position[ 0 ] -= bone.position[ 0 ];
  858. p.position[ 1 ] -= bone.position[ 1 ];
  859. p.position[ 2 ] -= bone.position[ 2 ];
  860. }
  861. }
  862. rigidBodies.push( p );
  863. }
  864. for ( var i = 0; i < model.metadata.constraintCount; i++ ) {
  865. var c = model.constraints[ i ];
  866. var keys = Object.keys( c );
  867. var p = {};
  868. for ( var j = 0; j < keys.length; j++ ) {
  869. var key = keys[ j ];
  870. p[ key ] = c[ key ];
  871. }
  872. var bodyA = rigidBodies[ p.rigidBodyIndex1 ];
  873. var bodyB = rigidBodies[ p.rigidBodyIndex2 ];
  874. /*
  875. * Refer to http://www20.atpages.jp/katwat/wp/?p=4135
  876. */
  877. if ( bodyA.type !== 0 && bodyB.type === 2 ) {
  878. if ( bodyA.boneIndex !== -1 && bodyB.boneIndex !== -1 &&
  879. model.bones[ bodyB.boneIndex ].parentIndex === bodyA.boneIndex ) {
  880. bodyB.type = 1;
  881. }
  882. }
  883. constraints.push( p );
  884. }
  885. geometry.rigidBodies = rigidBodies;
  886. geometry.constraints = constraints;
  887. };
  888. var initGeometry = function () {
  889. geometry.setIndex( new ( buffer.indices.length > 65535 ? THREE.Uint32BufferAttribute : THREE.Uint16BufferAttribute )( buffer.indices, 1 ) );
  890. geometry.addAttribute( 'position', new THREE.Float32BufferAttribute( buffer.vertices, 3 ) );
  891. geometry.addAttribute( 'normal', new THREE.Float32BufferAttribute( buffer.normals, 3 ) );
  892. geometry.addAttribute( 'uv', new THREE.Float32BufferAttribute( buffer.uvs, 2 ) );
  893. geometry.addAttribute( 'skinIndex', new THREE.Float32BufferAttribute( buffer.skinIndices, 4 ) );
  894. geometry.addAttribute( 'skinWeight', new THREE.Float32BufferAttribute( buffer.skinWeights, 4 ) );
  895. geometry.computeBoundingSphere();
  896. geometry.mmdFormat = model.metadata.format;
  897. };
  898. initVartices();
  899. initFaces();
  900. initBones();
  901. initIKs();
  902. initGrants();
  903. initMorphs();
  904. initMaterials();
  905. initPhysics();
  906. initGeometry();
  907. var mesh = new THREE.SkinnedMesh( geometry, material );
  908. // console.log( mesh ); // for console debug
  909. return mesh;
  910. };
  911. THREE.MMDLoader.prototype.createAnimation = function ( mesh, vmd, name ) {
  912. var helper = new THREE.MMDLoader.DataCreationHelper();
  913. var initMotionAnimations = function () {
  914. if ( vmd.metadata.motionCount === 0 ) {
  915. return;
  916. }
  917. var bones = mesh.geometry.bones;
  918. var orderedMotions = helper.createOrderedMotionArrays( bones, vmd.motions, 'boneName' );
  919. var tracks = [];
  920. var pushInterpolation = function ( array, interpolation, index ) {
  921. array.push( interpolation[ index + 0 ] / 127 ); // x1
  922. array.push( interpolation[ index + 8 ] / 127 ); // x2
  923. array.push( interpolation[ index + 4 ] / 127 ); // y1
  924. array.push( interpolation[ index + 12 ] / 127 ); // y2
  925. };
  926. for ( var i = 0; i < orderedMotions.length; i++ ) {
  927. var times = [];
  928. var positions = [];
  929. var rotations = [];
  930. var pInterpolations = [];
  931. var rInterpolations = [];
  932. var bone = bones[ i ];
  933. var array = orderedMotions[ i ];
  934. for ( var j = 0; j < array.length; j++ ) {
  935. var time = array[ j ].frameNum / 30;
  936. var pos = array[ j ].position;
  937. var rot = array[ j ].rotation;
  938. var interpolation = array[ j ].interpolation;
  939. times.push( time );
  940. for ( var k = 0; k < 3; k ++ ) {
  941. positions.push( bone.pos[ k ] + pos[ k ] );
  942. }
  943. for ( var k = 0; k < 4; k ++ ) {
  944. rotations.push( rot[ k ] );
  945. }
  946. for ( var k = 0; k < 3; k ++ ) {
  947. pushInterpolation( pInterpolations, interpolation, k );
  948. }
  949. pushInterpolation( rInterpolations, interpolation, 3 );
  950. }
  951. if ( times.length === 0 ) continue;
  952. var boneName = '.bones[' + bone.name + ']';
  953. tracks.push( new THREE.MMDLoader.VectorKeyframeTrackEx( boneName + '.position', times, positions, pInterpolations ) );
  954. tracks.push( new THREE.MMDLoader.QuaternionKeyframeTrackEx( boneName + '.quaternion', times, rotations, rInterpolations ) );
  955. }
  956. var clip = new THREE.AnimationClip( name === undefined ? THREE.Math.generateUUID() : name, -1, tracks );
  957. if ( clip !== null ) {
  958. if ( mesh.geometry.animations === undefined ) mesh.geometry.animations = [];
  959. mesh.geometry.animations.push( clip );
  960. }
  961. };
  962. var initMorphAnimations = function () {
  963. if ( vmd.metadata.morphCount === 0 ) {
  964. return;
  965. }
  966. var orderedMorphs = helper.createOrderedMotionArrays( mesh.geometry.morphTargets, vmd.morphs, 'morphName' );
  967. var tracks = [];
  968. for ( var i = 0; i < orderedMorphs.length; i++ ) {
  969. var times = [];
  970. var values = [];
  971. var array = orderedMorphs[ i ];
  972. for ( var j = 0; j < array.length; j++ ) {
  973. times.push( array[ j ].frameNum / 30 );
  974. values.push( array[ j ].weight );
  975. }
  976. if ( times.length === 0 ) continue;
  977. tracks.push( new THREE.NumberKeyframeTrack( '.morphTargetInfluences[' + i + ']', times, values ) );
  978. }
  979. var clip = new THREE.AnimationClip( name === undefined ? THREE.Math.generateUUID() : name + 'Morph', -1, tracks );
  980. if ( clip !== null ) {
  981. if ( mesh.geometry.animations === undefined ) mesh.geometry.animations = [];
  982. mesh.geometry.animations.push( clip );
  983. }
  984. };
  985. initMotionAnimations();
  986. initMorphAnimations();
  987. };
  988. THREE.MMDLoader.DataCreationHelper = function () {
  989. };
  990. THREE.MMDLoader.DataCreationHelper.prototype = {
  991. constructor: THREE.MMDLoader.DataCreationHelper,
  992. /*
  993. * Note: Sometimes to use Japanese Unicode characters runs into problems in Three.js.
  994. * In such a case, use this method to convert it to Unicode hex charcode strings,
  995. * like 'あいう' -> '0x30420x30440x3046'
  996. */
  997. toCharcodeStrings: function ( s ) {
  998. var str = '';
  999. for ( var i = 0; i < s.length; i++ ) {
  1000. str += '0x' + ( '0000' + s[ i ].charCodeAt().toString( 16 ) ).substr( -4 );
  1001. }
  1002. return str;
  1003. },
  1004. createDictionary: function ( array ) {
  1005. var dict = {};
  1006. for ( var i = 0; i < array.length; i++ ) {
  1007. dict[ array[ i ].name ] = i;
  1008. }
  1009. return dict;
  1010. },
  1011. initializeMotionArrays: function ( array ) {
  1012. var result = [];
  1013. for ( var i = 0; i < array.length; i++ ) {
  1014. result[ i ] = [];
  1015. }
  1016. return result;
  1017. },
  1018. sortMotionArray: function ( array ) {
  1019. array.sort( function ( a, b ) {
  1020. return a.frameNum - b.frameNum;
  1021. } ) ;
  1022. },
  1023. sortMotionArrays: function ( arrays ) {
  1024. for ( var i = 0; i < arrays.length; i++ ) {
  1025. this.sortMotionArray( arrays[ i ] );
  1026. }
  1027. },
  1028. createMotionArray: function ( array ) {
  1029. var result = [];
  1030. for ( var i = 0; i < array.length; i++ ) {
  1031. result.push( array[ i ] );
  1032. }
  1033. return result;
  1034. },
  1035. createMotionArrays: function ( array, result, dict, key ) {
  1036. for ( var i = 0; i < array.length; i++ ) {
  1037. var a = array[ i ];
  1038. var num = dict[ a[ key ] ];
  1039. if ( num === undefined ) {
  1040. continue;
  1041. }
  1042. result[ num ].push( a );
  1043. }
  1044. },
  1045. createOrderedMotionArray: function ( array ) {
  1046. var result = this.createMotionArray( array );
  1047. this.sortMotionArray( result );
  1048. return result;
  1049. },
  1050. createOrderedMotionArrays: function ( targetArray, motionArray, key ) {
  1051. var dict = this.createDictionary( targetArray );
  1052. var result = this.initializeMotionArrays( targetArray );
  1053. this.createMotionArrays( motionArray, result, dict, key );
  1054. this.sortMotionArrays( result );
  1055. return result;
  1056. }
  1057. };
  1058. /*
  1059. * extends existing KeyframeTrack for bone and camera animation.
  1060. * - use Float64Array for times
  1061. * - use Cubic Bezier curves interpolation
  1062. */
  1063. THREE.MMDLoader.VectorKeyframeTrackEx = function ( name, times, values, interpolationParameterArray ) {
  1064. this.interpolationParameters = new Float32Array( interpolationParameterArray );
  1065. THREE.VectorKeyframeTrack.call( this, name, times, values );
  1066. };
  1067. THREE.MMDLoader.VectorKeyframeTrackEx.prototype = Object.create( THREE.VectorKeyframeTrack.prototype );
  1068. THREE.MMDLoader.VectorKeyframeTrackEx.prototype.constructor = THREE.MMDLoader.VectorKeyframeTrackEx;
  1069. THREE.MMDLoader.VectorKeyframeTrackEx.prototype.TimeBufferType = Float64Array;
  1070. THREE.MMDLoader.VectorKeyframeTrackEx.prototype.InterpolantFactoryMethodCubicBezier = function( result ) {
  1071. return new THREE.MMDLoader.CubicBezierInterpolation( this.times, this.values, this.getValueSize(), result, this.interpolationParameters );
  1072. };
  1073. THREE.MMDLoader.VectorKeyframeTrackEx.prototype.setInterpolation = function( interpolation ) {
  1074. this.createInterpolant = this.InterpolantFactoryMethodCubicBezier;
  1075. };
  1076. THREE.MMDLoader.QuaternionKeyframeTrackEx = function ( name, times, values, interpolationParameterArray ) {
  1077. this.interpolationParameters = new Float32Array( interpolationParameterArray );
  1078. THREE.QuaternionKeyframeTrack.call( this, name, times, values );
  1079. };
  1080. THREE.MMDLoader.QuaternionKeyframeTrackEx.prototype = Object.create( THREE.QuaternionKeyframeTrack.prototype );
  1081. THREE.MMDLoader.QuaternionKeyframeTrackEx.prototype.constructor = THREE.MMDLoader.QuaternionKeyframeTrackEx;
  1082. THREE.MMDLoader.QuaternionKeyframeTrackEx.prototype.TimeBufferType = Float64Array;
  1083. THREE.MMDLoader.QuaternionKeyframeTrackEx.prototype.InterpolantFactoryMethodCubicBezier = function( result ) {
  1084. return new THREE.MMDLoader.CubicBezierInterpolation( this.times, this.values, this.getValueSize(), result, this.interpolationParameters );
  1085. };
  1086. THREE.MMDLoader.QuaternionKeyframeTrackEx.prototype.setInterpolation = function( interpolation ) {
  1087. this.createInterpolant = this.InterpolantFactoryMethodCubicBezier;
  1088. };
  1089. THREE.MMDLoader.NumberKeyframeTrackEx = function ( name, times, values, interpolationParameterArray ) {
  1090. this.interpolationParameters = new Float32Array( interpolationParameterArray );
  1091. THREE.NumberKeyframeTrack.call( this, name, times, values );
  1092. };
  1093. THREE.MMDLoader.NumberKeyframeTrackEx.prototype = Object.create( THREE.NumberKeyframeTrack.prototype );
  1094. THREE.MMDLoader.NumberKeyframeTrackEx.prototype.constructor = THREE.MMDLoader.NumberKeyframeTrackEx;
  1095. THREE.MMDLoader.NumberKeyframeTrackEx.prototype.TimeBufferType = Float64Array;
  1096. THREE.MMDLoader.NumberKeyframeTrackEx.prototype.InterpolantFactoryMethodCubicBezier = function( result ) {
  1097. return new THREE.MMDLoader.CubicBezierInterpolation( this.times, this.values, this.getValueSize(), result, this.interpolationParameters );
  1098. };
  1099. THREE.MMDLoader.NumberKeyframeTrackEx.prototype.setInterpolation = function( interpolation ) {
  1100. this.createInterpolant = this.InterpolantFactoryMethodCubicBezier;
  1101. };
  1102. THREE.MMDLoader.CubicBezierInterpolation = function ( parameterPositions, sampleValues, sampleSize, resultBuffer, params ) {
  1103. THREE.Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  1104. this.params = params;
  1105. }
  1106. THREE.MMDLoader.CubicBezierInterpolation.prototype = Object.create( THREE.LinearInterpolant.prototype );
  1107. THREE.MMDLoader.CubicBezierInterpolation.prototype.constructor = THREE.MMDLoader.CubicBezierInterpolation;
  1108. THREE.MMDLoader.CubicBezierInterpolation.prototype.interpolate_ = function( i1, t0, t, t1 ) {
  1109. var result = this.resultBuffer;
  1110. var values = this.sampleValues;
  1111. var stride = this.valueSize;
  1112. var offset1 = i1 * stride;
  1113. var offset0 = offset1 - stride;
  1114. var weight1 = ( t - t0 ) / ( t1 - t0 );
  1115. if ( stride === 4 ) { // Quaternion
  1116. var x1 = this.params[ i1 * 4 + 0 ];
  1117. var x2 = this.params[ i1 * 4 + 1 ];
  1118. var y1 = this.params[ i1 * 4 + 2 ];
  1119. var y2 = this.params[ i1 * 4 + 3 ];
  1120. var ratio = this._calculate( x1, x2, y1, y2, weight1 );
  1121. THREE.Quaternion.slerpFlat( result, 0, values, offset0, values, offset1, ratio );
  1122. } else if ( stride === 3 ) { // Vector3
  1123. for ( var i = 0; i !== stride; ++ i ) {
  1124. var x1 = this.params[ i1 * 12 + i * 4 + 0 ];
  1125. var x2 = this.params[ i1 * 12 + i * 4 + 1 ];
  1126. var y1 = this.params[ i1 * 12 + i * 4 + 2 ];
  1127. var y2 = this.params[ i1 * 12 + i * 4 + 3 ];
  1128. var ratio = this._calculate( x1, x2, y1, y2, weight1 );
  1129. result[ i ] = values[ offset0 + i ] * ( 1 - ratio ) + values[ offset1 + i ] * ratio;
  1130. }
  1131. } else { // Number
  1132. var x1 = this.params[ i1 * 4 + 0 ];
  1133. var x2 = this.params[ i1 * 4 + 1 ];
  1134. var y1 = this.params[ i1 * 4 + 2 ];
  1135. var y2 = this.params[ i1 * 4 + 3 ];
  1136. var ratio = this._calculate( x1, x2, y1, y2, weight1 );
  1137. result[ 0 ] = values[ offset0 ] * ( 1 - ratio ) + values[ offset1 ] * ratio;
  1138. }
  1139. return result;
  1140. };
  1141. THREE.MMDLoader.CubicBezierInterpolation.prototype._calculate = function( x1, x2, y1, y2, x ) {
  1142. /*
  1143. * Cubic Bezier curves
  1144. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Cubic_B.C3.A9zier_curves
  1145. *
  1146. * B(t) = ( 1 - t ) ^ 3 * P0
  1147. * + 3 * ( 1 - t ) ^ 2 * t * P1
  1148. * + 3 * ( 1 - t ) * t^2 * P2
  1149. * + t ^ 3 * P3
  1150. * ( 0 <= t <= 1 )
  1151. *
  1152. * MMD uses Cubic Bezier curves for bone and camera animation interpolation.
  1153. * http://d.hatena.ne.jp/edvakf/20111016/1318716097
  1154. *
  1155. * x = ( 1 - t ) ^ 3 * x0
  1156. * + 3 * ( 1 - t ) ^ 2 * t * x1
  1157. * + 3 * ( 1 - t ) * t^2 * x2
  1158. * + t ^ 3 * x3
  1159. * y = ( 1 - t ) ^ 3 * y0
  1160. * + 3 * ( 1 - t ) ^ 2 * t * y1
  1161. * + 3 * ( 1 - t ) * t^2 * y2
  1162. * + t ^ 3 * y3
  1163. * ( x0 = 0, y0 = 0 )
  1164. * ( x3 = 1, y3 = 1 )
  1165. * ( 0 <= t, x1, x2, y1, y2 <= 1 )
  1166. *
  1167. * Here solves this equation with Bisection method,
  1168. * https://en.wikipedia.org/wiki/Bisection_method
  1169. * gets t, and then calculate y.
  1170. *
  1171. * f(t) = 3 * ( 1 - t ) ^ 2 * t * x1
  1172. * + 3 * ( 1 - t ) * t^2 * x2
  1173. * + t ^ 3 - x = 0
  1174. *
  1175. * (Another option: Newton's method
  1176. * https://en.wikipedia.org/wiki/Newton%27s_method)
  1177. */
  1178. var c = 0.5;
  1179. var t = c;
  1180. var s = 1.0 - t;
  1181. var loop = 15;
  1182. var eps = 1e-5;
  1183. var math = Math;
  1184. var sst3, stt3, ttt;
  1185. for ( var i = 0; i < loop; i ++ ) {
  1186. sst3 = 3.0 * s * s * t;
  1187. stt3 = 3.0 * s * t * t;
  1188. ttt = t * t * t;
  1189. var ft = ( sst3 * x1 ) + ( stt3 * x2 ) + ( ttt ) - x;
  1190. if ( math.abs( ft ) < eps ) break;
  1191. c /= 2.0;
  1192. t += ( ft < 0 ) ? c : -c;
  1193. s = 1.0 - t;
  1194. }
  1195. return ( sst3 * y1 ) + ( stt3 * y2 ) + ttt;
  1196. };
  1197. THREE.MMDAudioManager = function ( audio, listener, p ) {
  1198. var params = ( p === null || p === undefined ) ? {} : p;
  1199. this.audio = audio;
  1200. this.listener = listener;
  1201. this.elapsedTime = 0.0;
  1202. this.currentTime = 0.0;
  1203. this.delayTime = params.delayTime !== undefined ? params.delayTime : 0.0;
  1204. this.audioDuration = this.audio.source.buffer.duration;
  1205. this.duration = this.audioDuration + this.delayTime;
  1206. };
  1207. THREE.MMDAudioManager.prototype = {
  1208. constructor: THREE.MMDAudioManager,
  1209. control: function ( delta ) {
  1210. this.elapsed += delta;
  1211. this.currentTime += delta;
  1212. if ( this.checkIfStopAudio() ) {
  1213. this.audio.stop();
  1214. }
  1215. if ( this.checkIfStartAudio() ) {
  1216. this.audio.play();
  1217. }
  1218. },
  1219. checkIfStartAudio: function () {
  1220. if ( this.audio.isPlaying ) {
  1221. return false;
  1222. }
  1223. while ( this.currentTime >= this.duration ) {
  1224. this.currentTime -= this.duration;
  1225. }
  1226. if ( this.currentTime < this.delayTime ) {
  1227. return false;
  1228. }
  1229. this.audio.startTime = this.currentTime - this.delayTime;
  1230. return true;
  1231. },
  1232. checkIfStopAudio: function () {
  1233. if ( ! this.audio.isPlaying ) {
  1234. return false;
  1235. }
  1236. if ( this.currentTime >= this.duration ) {
  1237. return true;
  1238. }
  1239. return false;
  1240. }
  1241. };
  1242. THREE.MMDGrantSolver = function ( mesh ) {
  1243. this.mesh = mesh;
  1244. };
  1245. THREE.MMDGrantSolver.prototype = {
  1246. constructor: THREE.MMDGrantSolver,
  1247. update: function () {
  1248. var q = new THREE.Quaternion();
  1249. return function () {
  1250. for ( var i = 0; i < this.mesh.geometry.grants.length; i ++ ) {
  1251. var g = this.mesh.geometry.grants[ i ];
  1252. var b = this.mesh.skeleton.bones[ g.index ];
  1253. var pb = this.mesh.skeleton.bones[ g.parentIndex ];
  1254. if ( g.isLocal ) {
  1255. // TODO: implement
  1256. if ( g.affectPosition ) {
  1257. }
  1258. // TODO: implement
  1259. if ( g.affectRotation ) {
  1260. }
  1261. } else {
  1262. // TODO: implement
  1263. if ( g.affectPosition ) {
  1264. }
  1265. if ( g.affectRotation ) {
  1266. q.set( 0, 0, 0, 1 );
  1267. q.slerp( pb.quaternion, g.ratio );
  1268. b.quaternion.multiply( q );
  1269. }
  1270. }
  1271. }
  1272. };
  1273. }()
  1274. };
  1275. THREE.MMDHelper = function ( renderer ) {
  1276. this.renderer = renderer;
  1277. this.outlineEffect = null;
  1278. this.effect = null;
  1279. this.autoClear = true;
  1280. this.meshes = [];
  1281. this.doAnimation = true;
  1282. this.doIk = true;
  1283. this.doGrant = true;
  1284. this.doPhysics = true;
  1285. this.doOutlineDrawing = true;
  1286. this.doCameraAnimation = true;
  1287. this.audioManager = null;
  1288. this.camera = null;
  1289. this.init();
  1290. };
  1291. THREE.MMDHelper.prototype = {
  1292. constructor: THREE.MMDHelper,
  1293. init: function () {
  1294. this.outlineEffect = new THREE.OutlineEffect( this.renderer );
  1295. var size = this.renderer.getSize();
  1296. this.setSize( size.width, size.height );
  1297. },
  1298. add: function ( mesh ) {
  1299. if ( ! ( mesh instanceof THREE.SkinnedMesh ) ) {
  1300. throw new Error( 'THREE.MMDHelper.add() accepts only THREE.SkinnedMesh instance.' );
  1301. }
  1302. if ( mesh.mixer === undefined ) mesh.mixer = null;
  1303. if ( mesh.ikSolver === undefined ) mesh.ikSolver = null;
  1304. if ( mesh.grantSolver === undefined ) mesh.grantSolver = null;
  1305. if ( mesh.physics === undefined ) mesh.physics = null;
  1306. if ( mesh.looped === undefined ) mesh.looped = false;
  1307. this.meshes.push( mesh );
  1308. // workaround until I make IK and Physics Animation plugin
  1309. this.initBackupBones( mesh );
  1310. },
  1311. setSize: function ( width, height ) {
  1312. this.outlineEffect.setSize( width, height );
  1313. },
  1314. /*
  1315. * Note: There may be a possibility that Outline wouldn't work well with Effect.
  1316. * In such a case, try to set doOutlineDrawing = false or
  1317. * manually comment out renderer.clear() in *Effect.render().
  1318. */
  1319. setEffect: function ( effect ) {
  1320. this.effect = effect;
  1321. },
  1322. setAudio: function ( audio, listener, params ) {
  1323. this.audioManager = new THREE.MMDAudioManager( audio, listener, params );
  1324. },
  1325. setCamera: function ( camera ) {
  1326. camera.mixer = null;
  1327. this.camera = camera;
  1328. },
  1329. setPhysicses: function ( params ) {
  1330. params = ( params === undefined ) ? {} : Object.assign( {}, params );
  1331. for ( var i = 0; i < this.meshes.length; i++ ) {
  1332. this.setPhysics( this.meshes[ i ], params );
  1333. if ( i === 0 && params.sharePhysicsWorld === true ) {
  1334. params.world = this.meshes[ 0 ].physics.world;
  1335. }
  1336. }
  1337. },
  1338. setPhysics: function ( mesh, params ) {
  1339. if ( params === undefined ) params = {};
  1340. var warmup = params.warmup !== undefined ? params.warmup : 60;
  1341. var physics = new THREE.MMDPhysics( mesh, params );
  1342. if ( mesh.mixer !== null && mesh.mixer !== undefined && this.doAnimation === true && params.preventAnimationWarmup !== false ) {
  1343. this.animateOneMesh( 0, mesh );
  1344. physics.reset();
  1345. }
  1346. physics.warmup( warmup );
  1347. this.updateIKParametersDependingOnPhysicsEnabled( mesh, true );
  1348. mesh.physics = physics;
  1349. },
  1350. enablePhysics: function ( enabled ) {
  1351. if ( enabled === true ) {
  1352. this.doPhysics = true;
  1353. } else {
  1354. this.doPhysics = false;
  1355. }
  1356. for ( var i = 0, il = this.meshes.length; i < il; i ++ ) {
  1357. this.updateIKParametersDependingOnPhysicsEnabled( this.meshes[ i ], enabled );
  1358. }
  1359. },
  1360. updateIKParametersDependingOnPhysicsEnabled: function ( mesh, physicsEnabled ) {
  1361. var iks = mesh.geometry.iks;
  1362. var bones = mesh.geometry.bones;
  1363. for ( var j = 0, jl = iks.length; j < jl; j ++ ) {
  1364. var ik = iks[ j ];
  1365. var links = ik.links;
  1366. for ( var k = 0, kl = links.length; k < kl; k ++ ) {
  1367. var link = links[ k ];
  1368. if ( physicsEnabled === true ) {
  1369. // disable IK of the bone the corresponding rigidBody type of which is 1 or 2
  1370. // because its rotation will be overriden by physics
  1371. link.enabled = bones[ link.index ].rigidBodyType > 0 ? false : true;
  1372. } else {
  1373. link.enabled = true;
  1374. }
  1375. }
  1376. }
  1377. },
  1378. setAnimations: function () {
  1379. for ( var i = 0; i < this.meshes.length; i++ ) {
  1380. this.setAnimation( this.meshes[ i ] );
  1381. }
  1382. },
  1383. setAnimation: function ( mesh ) {
  1384. if ( mesh.geometry.animations !== undefined ) {
  1385. mesh.mixer = new THREE.AnimationMixer( mesh );
  1386. // TODO: find a workaround not to access (seems like) private properties
  1387. // the name of them begins with "_".
  1388. mesh.mixer.addEventListener( 'loop', function ( e ) {
  1389. if ( e.action._clip.tracks[ 0 ].name.indexOf( '.bones' ) !== 0 ) return;
  1390. var mesh = e.target._root;
  1391. mesh.looped = true;
  1392. } );
  1393. var foundAnimation = false;
  1394. var foundMorphAnimation = false;
  1395. for ( var i = 0; i < mesh.geometry.animations.length; i++ ) {
  1396. var clip = mesh.geometry.animations[ i ];
  1397. var action = mesh.mixer.clipAction( clip );
  1398. if ( clip.tracks[ 0 ].name.indexOf( '.morphTargetInfluences' ) === 0 ) {
  1399. if ( ! foundMorphAnimation ) {
  1400. action.play();
  1401. foundMorphAnimation = true;
  1402. }
  1403. } else {
  1404. if ( ! foundAnimation ) {
  1405. action.play();
  1406. foundAnimation = true;
  1407. }
  1408. }
  1409. }
  1410. if ( foundAnimation ) {
  1411. mesh.ikSolver = new THREE.CCDIKSolver( mesh );
  1412. if ( mesh.geometry.grants !== undefined ) {
  1413. mesh.grantSolver = new THREE.MMDGrantSolver( mesh );
  1414. }
  1415. }
  1416. }
  1417. },
  1418. setCameraAnimation: function ( camera ) {
  1419. if ( camera.animations !== undefined ) {
  1420. camera.mixer = new THREE.AnimationMixer( camera );
  1421. camera.mixer.clipAction( camera.animations[ 0 ] ).play();
  1422. }
  1423. },
  1424. /*
  1425. * detect the longest duration among model, camera, and audio animations and then
  1426. * set it to them to sync.
  1427. * TODO: touching private properties ( ._actions and ._clip ) so consider better way
  1428. * to access them for safe and modularity.
  1429. */
  1430. unifyAnimationDuration: function ( params ) {
  1431. params = params === undefined ? {} : params;
  1432. var max = 0.0;
  1433. var camera = this.camera;
  1434. var audioManager = this.audioManager;
  1435. // check the longest duration
  1436. for ( var i = 0; i < this.meshes.length; i++ ) {
  1437. var mesh = this.meshes[ i ];
  1438. var mixer = mesh.mixer;
  1439. if ( mixer === null ) {
  1440. continue;
  1441. }
  1442. for ( var j = 0; j < mixer._actions.length; j++ ) {
  1443. var action = mixer._actions[ j ];
  1444. max = Math.max( max, action._clip.duration );
  1445. }
  1446. }
  1447. if ( camera !== null && camera.mixer !== null ) {
  1448. var mixer = camera.mixer;
  1449. for ( var i = 0; i < mixer._actions.length; i++ ) {
  1450. var action = mixer._actions[ i ];
  1451. max = Math.max( max, action._clip.duration );
  1452. }
  1453. }
  1454. if ( audioManager !== null ) {
  1455. max = Math.max( max, audioManager.duration );
  1456. }
  1457. if ( params.afterglow !== undefined ) {
  1458. max += params.afterglow;
  1459. }
  1460. // set the duration
  1461. for ( var i = 0; i < this.meshes.length; i++ ) {
  1462. var mesh = this.meshes[ i ];
  1463. var mixer = mesh.mixer;
  1464. if ( mixer === null ) {
  1465. continue;
  1466. }
  1467. for ( var j = 0; j < mixer._actions.length; j++ ) {
  1468. var action = mixer._actions[ j ];
  1469. action._clip.duration = max;
  1470. }
  1471. }
  1472. if ( camera !== null && camera.mixer !== null ) {
  1473. var mixer = camera.mixer;
  1474. for ( var i = 0; i < mixer._actions.length; i++ ) {
  1475. var action = mixer._actions[ i ];
  1476. action._clip.duration = max;
  1477. }
  1478. }
  1479. if ( audioManager !== null ) {
  1480. audioManager.duration = max;
  1481. }
  1482. },
  1483. controlAudio: function ( delta ) {
  1484. if ( this.audioManager === null ) {
  1485. return;
  1486. }
  1487. this.audioManager.control( delta );
  1488. },
  1489. animate: function ( delta ) {
  1490. this.controlAudio( delta );
  1491. for ( var i = 0; i < this.meshes.length; i++ ) {
  1492. this.animateOneMesh( delta, this.meshes[ i ] );
  1493. }
  1494. this.animateCamera( delta );
  1495. },
  1496. animateOneMesh: function ( delta, mesh ) {
  1497. var mixer = mesh.mixer;
  1498. var ikSolver = mesh.ikSolver;
  1499. var grantSolver = mesh.grantSolver;
  1500. var physics = mesh.physics;
  1501. if ( mixer !== null && this.doAnimation === true ) {
  1502. // restore/backupBones are workaround
  1503. // until I make IK, Grant, and Physics Animation plugin
  1504. this.restoreBones( mesh );
  1505. mixer.update( delta );
  1506. this.backupBones( mesh );
  1507. }
  1508. if ( ikSolver !== null && this.doIk === true ) {
  1509. ikSolver.update();
  1510. }
  1511. if ( grantSolver !== null && this.doGrant === true ) {
  1512. grantSolver.update();
  1513. }
  1514. if ( mesh.looped === true ) {
  1515. if ( physics !== null ) physics.reset();
  1516. mesh.looped = false;
  1517. }
  1518. if ( physics !== null && this.doPhysics === true ) {
  1519. physics.update( delta );
  1520. }
  1521. },
  1522. animateCamera: function ( delta ) {
  1523. if ( this.camera === null ) {
  1524. return;
  1525. }
  1526. var mixer = this.camera.mixer;
  1527. if ( mixer !== null && this.camera.center !== undefined && this.doCameraAnimation === true ) {
  1528. mixer.update( delta );
  1529. // TODO: Let PerspectiveCamera automatically update?
  1530. this.camera.updateProjectionMatrix();
  1531. this.camera.up.set( 0, 1, 0 );
  1532. this.camera.up.applyQuaternion( this.camera.quaternion );
  1533. this.camera.lookAt( this.camera.center );
  1534. }
  1535. },
  1536. render: function ( scene, camera ) {
  1537. if ( this.effect === null ) {
  1538. if ( this.doOutlineDrawing ) {
  1539. this.outlineEffect.autoClear = this.autoClear;
  1540. this.outlineEffect.render( scene, camera );
  1541. } else {
  1542. var currentAutoClear = this.renderer.autoClear;
  1543. this.renderer.autoClear = this.autoClear;
  1544. this.renderer.render( scene, camera );
  1545. this.renderer.autoClear = currentAutoClear;
  1546. }
  1547. } else {
  1548. var currentAutoClear = this.renderer.autoClear;
  1549. this.renderer.autoClear = this.autoClear;
  1550. if ( this.doOutlineDrawing ) {
  1551. this.renderWithEffectAndOutline( scene, camera );
  1552. } else {
  1553. this.effect.render( scene, camera );
  1554. }
  1555. this.renderer.autoClear = currentAutoClear;
  1556. }
  1557. },
  1558. /*
  1559. * Currently(r82 dev) there's no way to render with two Effects
  1560. * then attempt to get them to coordinately run by myself.
  1561. *
  1562. * What this method does
  1563. * 1. let OutlineEffect make outline materials (only once)
  1564. * 2. render normally with effect
  1565. * 3. set outline materials
  1566. * 4. render outline with effect
  1567. * 5. restore original materials
  1568. */
  1569. renderWithEffectAndOutline: function ( scene, camera ) {
  1570. var hasOutlineMaterial = false;
  1571. function checkIfObjectHasOutlineMaterial ( object ) {
  1572. if ( object.material === undefined ) return;
  1573. if ( object.userData.outlineMaterial !== undefined ) hasOutlineMaterial = true;
  1574. }
  1575. function setOutlineMaterial ( object ) {
  1576. if ( object.material === undefined ) return;
  1577. if ( object.userData.outlineMaterial === undefined ) return;
  1578. object.userData.originalMaterial = object.material;
  1579. object.material = object.userData.outlineMaterial;
  1580. }
  1581. function restoreOriginalMaterial ( object ) {
  1582. if ( object.material === undefined ) return;
  1583. if ( object.userData.originalMaterial === undefined ) return;
  1584. object.material = object.userData.originalMaterial;
  1585. }
  1586. return function renderWithEffectAndOutline( scene, camera ) {
  1587. hasOutlineMaterial = false;
  1588. var forceClear = false;
  1589. scene.traverse( checkIfObjectHasOutlineMaterial );
  1590. if ( ! hasOutlineMaterial ) {
  1591. this.outlineEffect.render( scene, camera );
  1592. forceClear = true;
  1593. scene.traverse( checkIfObjectHasOutlineMaterial );
  1594. }
  1595. if ( hasOutlineMaterial ) {
  1596. this.renderer.autoClear = this.autoClear || forceClear;
  1597. this.effect.render( scene, camera );
  1598. scene.traverse( setOutlineMaterial );
  1599. var currentShadowMapEnabled = this.renderer.shadowMap.enabled;
  1600. this.renderer.autoClear = false;
  1601. this.renderer.shadowMap.enabled = false;
  1602. this.effect.render( scene, camera );
  1603. this.renderer.shadowMap.enabled = currentShadowMapEnabled;
  1604. scene.traverse( restoreOriginalMaterial );
  1605. } else {
  1606. this.outlineEffect.autoClear = this.autoClear || forceClear;
  1607. this.outlineEffect.render( scene, camera );
  1608. }
  1609. }
  1610. }(),
  1611. poseAsVpd: function ( mesh, vpd, params ) {
  1612. if ( params === undefined ) params = {};
  1613. if ( params.preventResetPose !== true ) mesh.pose();
  1614. var bones = mesh.skeleton.bones;
  1615. var bones2 = vpd.bones;
  1616. var table = {};
  1617. for ( var i = 0; i < bones.length; i++ ) {
  1618. table[ bones[ i ].name ] = i;
  1619. }
  1620. var thV = new THREE.Vector3();
  1621. var thQ = new THREE.Quaternion();
  1622. for ( var i = 0; i < bones2.length; i++ ) {
  1623. var b = bones2[ i ];
  1624. var index = table[ b.name ];
  1625. if ( index === undefined ) continue;
  1626. var b2 = bones[ index ];
  1627. var t = b.translation;
  1628. var q = b.quaternion;
  1629. thV.set( t[ 0 ], t[ 1 ], t[ 2 ] );
  1630. thQ.set( q[ 0 ], q[ 1 ], q[ 2 ], q[ 3 ] );
  1631. b2.position.add( thV );
  1632. b2.quaternion.multiply( thQ );
  1633. }
  1634. mesh.updateMatrixWorld( true );
  1635. if ( params.preventIk !== true ) {
  1636. var solver = new THREE.CCDIKSolver( mesh );
  1637. solver.update( params.saveOriginalBonesBeforeIK );
  1638. }
  1639. if ( params.preventGrant !== true && mesh.geometry.grants !== undefined ) {
  1640. var solver = new THREE.MMDGrantSolver( mesh );
  1641. solver.update();
  1642. }
  1643. },
  1644. /*
  1645. * Note: These following three functions are workaround for r74dev.
  1646. * THREE.PropertyMixer.apply() seems to save values into buffer cache
  1647. * when mixer.update() is called.
  1648. * ikSolver.update() and physics.update() change bone position/quaternion
  1649. * without mixer.update() then buffer cache will be inconsistent.
  1650. * So trying to avoid buffer cache inconsistency by doing
  1651. * backup bones position/quaternion right after mixer.update() call
  1652. * and then restore them after rendering.
  1653. */
  1654. initBackupBones: function ( mesh ) {
  1655. mesh.skeleton.backupBones = [];
  1656. for ( var i = 0; i < mesh.skeleton.bones.length; i++ ) {
  1657. mesh.skeleton.backupBones.push( mesh.skeleton.bones[ i ].clone() );
  1658. }
  1659. },
  1660. backupBones: function ( mesh ) {
  1661. mesh.skeleton.backupBoneIsSaved = true;
  1662. for ( var i = 0; i < mesh.skeleton.bones.length; i++ ) {
  1663. var b = mesh.skeleton.backupBones[ i ];
  1664. var b2 = mesh.skeleton.bones[ i ];
  1665. b.position.copy( b2.position );
  1666. b.quaternion.copy( b2.quaternion );
  1667. }
  1668. },
  1669. restoreBones: function ( mesh ) {
  1670. if ( mesh.skeleton.backupBoneIsSaved !== true ) {
  1671. return;
  1672. }
  1673. mesh.skeleton.backupBoneIsSaved = false;
  1674. for ( var i = 0; i < mesh.skeleton.bones.length; i++ ) {
  1675. var b = mesh.skeleton.bones[ i ];
  1676. var b2 = mesh.skeleton.backupBones[ i ];
  1677. b.position.copy( b2.position );
  1678. b.quaternion.copy( b2.quaternion );
  1679. }
  1680. }
  1681. };