MMDLoader.js 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911
  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.sharedPhysics = false;
  1288. this.masterPhysics = null;
  1289. this.audioManager = null;
  1290. this.camera = null;
  1291. this.init();
  1292. };
  1293. THREE.MMDHelper.prototype = {
  1294. constructor: THREE.MMDHelper,
  1295. init: function () {
  1296. this.outlineEffect = new THREE.OutlineEffect( this.renderer );
  1297. var size = this.renderer.getSize();
  1298. this.setSize( size.width, size.height );
  1299. },
  1300. add: function ( mesh ) {
  1301. if ( ! ( mesh instanceof THREE.SkinnedMesh ) ) {
  1302. throw new Error( 'THREE.MMDHelper.add() accepts only THREE.SkinnedMesh instance.' );
  1303. }
  1304. if ( mesh.mixer === undefined ) mesh.mixer = null;
  1305. if ( mesh.ikSolver === undefined ) mesh.ikSolver = null;
  1306. if ( mesh.grantSolver === undefined ) mesh.grantSolver = null;
  1307. if ( mesh.physics === undefined ) mesh.physics = null;
  1308. if ( mesh.looped === undefined ) mesh.looped = false;
  1309. this.meshes.push( mesh );
  1310. // workaround until I make IK and Physics Animation plugin
  1311. this.initBackupBones( mesh );
  1312. },
  1313. setSize: function ( width, height ) {
  1314. this.outlineEffect.setSize( width, height );
  1315. },
  1316. /*
  1317. * Note: There may be a possibility that Outline wouldn't work well with Effect.
  1318. * In such a case, try to set doOutlineDrawing = false or
  1319. * manually comment out renderer.clear() in *Effect.render().
  1320. */
  1321. setEffect: function ( effect ) {
  1322. this.effect = effect;
  1323. },
  1324. setAudio: function ( audio, listener, params ) {
  1325. this.audioManager = new THREE.MMDAudioManager( audio, listener, params );
  1326. },
  1327. setCamera: function ( camera ) {
  1328. camera.mixer = null;
  1329. this.camera = camera;
  1330. },
  1331. setPhysicses: function ( params ) {
  1332. for ( var i = 0; i < this.meshes.length; i++ ) {
  1333. this.setPhysics( this.meshes[ i ], params );
  1334. }
  1335. },
  1336. setPhysics: function ( mesh, params ) {
  1337. params = ( params === undefined ) ? {} : Object.assign( {}, params );
  1338. if ( params.world === undefined && this.sharedPhysics ) {
  1339. var masterPhysics = this.getMasterPhysics();
  1340. if ( masterPhysics !== null ) params.world = masterPhysics.world;
  1341. }
  1342. var warmup = params.warmup !== undefined ? params.warmup : 60;
  1343. var physics = new THREE.MMDPhysics( mesh, params );
  1344. if ( mesh.mixer !== null && mesh.mixer !== undefined && params.preventAnimationWarmup !== false ) {
  1345. this.animateOneMesh( 0, mesh );
  1346. physics.reset();
  1347. }
  1348. physics.warmup( warmup );
  1349. this.updateIKParametersDependingOnPhysicsEnabled( mesh, true );
  1350. mesh.physics = physics;
  1351. },
  1352. getMasterPhysics: function () {
  1353. if ( this.masterPhysics !== null ) return this.masterPhysics;
  1354. for ( var i = 0, il = this.meshes.length; i < il; i ++ ) {
  1355. var physics = this.meshes[ i ].physics;
  1356. if ( physics !== undefined && physics !== null ) {
  1357. this.masterPhysics = physics;
  1358. return this.masterPhysics;
  1359. }
  1360. }
  1361. return null;
  1362. },
  1363. enablePhysics: function ( enabled ) {
  1364. if ( enabled === true ) {
  1365. this.doPhysics = true;
  1366. } else {
  1367. this.doPhysics = false;
  1368. }
  1369. for ( var i = 0, il = this.meshes.length; i < il; i ++ ) {
  1370. this.updateIKParametersDependingOnPhysicsEnabled( this.meshes[ i ], enabled );
  1371. }
  1372. },
  1373. updateIKParametersDependingOnPhysicsEnabled: function ( mesh, physicsEnabled ) {
  1374. var iks = mesh.geometry.iks;
  1375. var bones = mesh.geometry.bones;
  1376. for ( var j = 0, jl = iks.length; j < jl; j ++ ) {
  1377. var ik = iks[ j ];
  1378. var links = ik.links;
  1379. for ( var k = 0, kl = links.length; k < kl; k ++ ) {
  1380. var link = links[ k ];
  1381. if ( physicsEnabled === true ) {
  1382. // disable IK of the bone the corresponding rigidBody type of which is 1 or 2
  1383. // because its rotation will be overriden by physics
  1384. link.enabled = bones[ link.index ].rigidBodyType > 0 ? false : true;
  1385. } else {
  1386. link.enabled = true;
  1387. }
  1388. }
  1389. }
  1390. },
  1391. setAnimations: function () {
  1392. for ( var i = 0; i < this.meshes.length; i++ ) {
  1393. this.setAnimation( this.meshes[ i ] );
  1394. }
  1395. },
  1396. setAnimation: function ( mesh ) {
  1397. if ( mesh.geometry.animations !== undefined ) {
  1398. mesh.mixer = new THREE.AnimationMixer( mesh );
  1399. // TODO: find a workaround not to access (seems like) private properties
  1400. // the name of them begins with "_".
  1401. mesh.mixer.addEventListener( 'loop', function ( e ) {
  1402. if ( e.action._clip.tracks[ 0 ].name.indexOf( '.bones' ) !== 0 ) return;
  1403. var mesh = e.target._root;
  1404. mesh.looped = true;
  1405. } );
  1406. var foundAnimation = false;
  1407. var foundMorphAnimation = false;
  1408. for ( var i = 0; i < mesh.geometry.animations.length; i++ ) {
  1409. var clip = mesh.geometry.animations[ i ];
  1410. var action = mesh.mixer.clipAction( clip );
  1411. if ( clip.tracks[ 0 ].name.indexOf( '.morphTargetInfluences' ) === 0 ) {
  1412. if ( ! foundMorphAnimation ) {
  1413. action.play();
  1414. foundMorphAnimation = true;
  1415. }
  1416. } else {
  1417. if ( ! foundAnimation ) {
  1418. action.play();
  1419. foundAnimation = true;
  1420. }
  1421. }
  1422. }
  1423. if ( foundAnimation ) {
  1424. mesh.ikSolver = new THREE.CCDIKSolver( mesh );
  1425. if ( mesh.geometry.grants !== undefined ) {
  1426. mesh.grantSolver = new THREE.MMDGrantSolver( mesh );
  1427. }
  1428. }
  1429. }
  1430. },
  1431. setCameraAnimation: function ( camera ) {
  1432. if ( camera.animations !== undefined ) {
  1433. camera.mixer = new THREE.AnimationMixer( camera );
  1434. camera.mixer.clipAction( camera.animations[ 0 ] ).play();
  1435. }
  1436. },
  1437. /*
  1438. * detect the longest duration among model, camera, and audio animations and then
  1439. * set it to them to sync.
  1440. * TODO: touching private properties ( ._actions and ._clip ) so consider better way
  1441. * to access them for safe and modularity.
  1442. */
  1443. unifyAnimationDuration: function ( params ) {
  1444. params = params === undefined ? {} : params;
  1445. var max = 0.0;
  1446. var camera = this.camera;
  1447. var audioManager = this.audioManager;
  1448. // check the longest duration
  1449. for ( var i = 0; i < this.meshes.length; i++ ) {
  1450. var mesh = this.meshes[ i ];
  1451. var mixer = mesh.mixer;
  1452. if ( mixer === null ) {
  1453. continue;
  1454. }
  1455. for ( var j = 0; j < mixer._actions.length; j++ ) {
  1456. var action = mixer._actions[ j ];
  1457. max = Math.max( max, action._clip.duration );
  1458. }
  1459. }
  1460. if ( camera !== null && camera.mixer !== null ) {
  1461. var mixer = camera.mixer;
  1462. for ( var i = 0; i < mixer._actions.length; i++ ) {
  1463. var action = mixer._actions[ i ];
  1464. max = Math.max( max, action._clip.duration );
  1465. }
  1466. }
  1467. if ( audioManager !== null ) {
  1468. max = Math.max( max, audioManager.duration );
  1469. }
  1470. if ( params.afterglow !== undefined ) {
  1471. max += params.afterglow;
  1472. }
  1473. // set the duration
  1474. for ( var i = 0; i < this.meshes.length; i++ ) {
  1475. var mesh = this.meshes[ i ];
  1476. var mixer = mesh.mixer;
  1477. if ( mixer === null ) {
  1478. continue;
  1479. }
  1480. for ( var j = 0; j < mixer._actions.length; j++ ) {
  1481. var action = mixer._actions[ j ];
  1482. action._clip.duration = max;
  1483. }
  1484. }
  1485. if ( camera !== null && camera.mixer !== null ) {
  1486. var mixer = camera.mixer;
  1487. for ( var i = 0; i < mixer._actions.length; i++ ) {
  1488. var action = mixer._actions[ i ];
  1489. action._clip.duration = max;
  1490. }
  1491. }
  1492. if ( audioManager !== null ) {
  1493. audioManager.duration = max;
  1494. }
  1495. },
  1496. controlAudio: function ( delta ) {
  1497. if ( this.audioManager === null ) {
  1498. return;
  1499. }
  1500. this.audioManager.control( delta );
  1501. },
  1502. animate: function ( delta ) {
  1503. this.controlAudio( delta );
  1504. for ( var i = 0; i < this.meshes.length; i++ ) {
  1505. this.animateOneMesh( delta, this.meshes[ i ] );
  1506. }
  1507. if ( this.sharedPhysics ) this.updateSharedPhysics( delta );
  1508. this.animateCamera( delta );
  1509. },
  1510. animateOneMesh: function ( delta, mesh ) {
  1511. var mixer = mesh.mixer;
  1512. var ikSolver = mesh.ikSolver;
  1513. var grantSolver = mesh.grantSolver;
  1514. var physics = mesh.physics;
  1515. if ( mixer !== null && this.doAnimation === true ) {
  1516. // restore/backupBones are workaround
  1517. // until I make IK, Grant, and Physics Animation plugin
  1518. this.restoreBones( mesh );
  1519. mixer.update( delta );
  1520. this.backupBones( mesh );
  1521. }
  1522. if ( ikSolver !== null && this.doIk === true ) {
  1523. ikSolver.update();
  1524. }
  1525. if ( grantSolver !== null && this.doGrant === true ) {
  1526. grantSolver.update();
  1527. }
  1528. if ( mesh.looped === true ) {
  1529. if ( physics !== null ) physics.reset();
  1530. mesh.looped = false;
  1531. }
  1532. if ( physics !== null && this.doPhysics && ! this.sharedPhysics) {
  1533. physics.update( delta );
  1534. }
  1535. },
  1536. updateSharedPhysics: function ( delta ) {
  1537. if ( this.meshes.length === 0 || ! this.doPhysics || ! this.sharedPhysics ) return;
  1538. var physics = this.getMasterPhysics();
  1539. if ( physics === null ) return;
  1540. for ( var i = 0, il = this.meshes.length; i < il; i ++ ) {
  1541. var p = this.meshes[ i ].physics;
  1542. if ( p !== null && p !== undefined ) {
  1543. p.updateRigidBodies();
  1544. }
  1545. }
  1546. physics.stepSimulation( delta );
  1547. for ( var i = 0, il = this.meshes.length; i < il; i ++ ) {
  1548. var p = this.meshes[ i ].physics;
  1549. if ( p !== null && p !== undefined ) {
  1550. p.updateBones();
  1551. }
  1552. }
  1553. },
  1554. animateCamera: function ( delta ) {
  1555. if ( this.camera === null ) {
  1556. return;
  1557. }
  1558. var mixer = this.camera.mixer;
  1559. if ( mixer !== null && this.camera.center !== undefined && this.doCameraAnimation === true ) {
  1560. mixer.update( delta );
  1561. // TODO: Let PerspectiveCamera automatically update?
  1562. this.camera.updateProjectionMatrix();
  1563. this.camera.up.set( 0, 1, 0 );
  1564. this.camera.up.applyQuaternion( this.camera.quaternion );
  1565. this.camera.lookAt( this.camera.center );
  1566. }
  1567. },
  1568. render: function ( scene, camera ) {
  1569. if ( this.effect === null ) {
  1570. if ( this.doOutlineDrawing ) {
  1571. this.outlineEffect.autoClear = this.autoClear;
  1572. this.outlineEffect.render( scene, camera );
  1573. } else {
  1574. var currentAutoClear = this.renderer.autoClear;
  1575. this.renderer.autoClear = this.autoClear;
  1576. this.renderer.render( scene, camera );
  1577. this.renderer.autoClear = currentAutoClear;
  1578. }
  1579. } else {
  1580. var currentAutoClear = this.renderer.autoClear;
  1581. this.renderer.autoClear = this.autoClear;
  1582. if ( this.doOutlineDrawing ) {
  1583. this.renderWithEffectAndOutline( scene, camera );
  1584. } else {
  1585. this.effect.render( scene, camera );
  1586. }
  1587. this.renderer.autoClear = currentAutoClear;
  1588. }
  1589. },
  1590. /*
  1591. * Currently(r82 dev) there's no way to render with two Effects
  1592. * then attempt to get them to coordinately run by myself.
  1593. *
  1594. * What this method does
  1595. * 1. let OutlineEffect make outline materials (only once)
  1596. * 2. render normally with effect
  1597. * 3. set outline materials
  1598. * 4. render outline with effect
  1599. * 5. restore original materials
  1600. */
  1601. renderWithEffectAndOutline: function ( scene, camera ) {
  1602. var hasOutlineMaterial = false;
  1603. function checkIfObjectHasOutlineMaterial ( object ) {
  1604. if ( object.material === undefined ) return;
  1605. if ( object.userData.outlineMaterial !== undefined ) hasOutlineMaterial = true;
  1606. }
  1607. function setOutlineMaterial ( object ) {
  1608. if ( object.material === undefined ) return;
  1609. if ( object.userData.outlineMaterial === undefined ) return;
  1610. object.userData.originalMaterial = object.material;
  1611. object.material = object.userData.outlineMaterial;
  1612. }
  1613. function restoreOriginalMaterial ( object ) {
  1614. if ( object.material === undefined ) return;
  1615. if ( object.userData.originalMaterial === undefined ) return;
  1616. object.material = object.userData.originalMaterial;
  1617. }
  1618. return function renderWithEffectAndOutline( scene, camera ) {
  1619. hasOutlineMaterial = false;
  1620. var forceClear = false;
  1621. scene.traverse( checkIfObjectHasOutlineMaterial );
  1622. if ( ! hasOutlineMaterial ) {
  1623. this.outlineEffect.render( scene, camera );
  1624. forceClear = true;
  1625. scene.traverse( checkIfObjectHasOutlineMaterial );
  1626. }
  1627. if ( hasOutlineMaterial ) {
  1628. this.renderer.autoClear = this.autoClear || forceClear;
  1629. this.effect.render( scene, camera );
  1630. scene.traverse( setOutlineMaterial );
  1631. var currentShadowMapEnabled = this.renderer.shadowMap.enabled;
  1632. this.renderer.autoClear = false;
  1633. this.renderer.shadowMap.enabled = false;
  1634. this.effect.render( scene, camera );
  1635. this.renderer.shadowMap.enabled = currentShadowMapEnabled;
  1636. scene.traverse( restoreOriginalMaterial );
  1637. } else {
  1638. this.outlineEffect.autoClear = this.autoClear || forceClear;
  1639. this.outlineEffect.render( scene, camera );
  1640. }
  1641. }
  1642. }(),
  1643. poseAsVpd: function ( mesh, vpd, params ) {
  1644. if ( params === undefined ) params = {};
  1645. if ( params.preventResetPose !== true ) mesh.pose();
  1646. var bones = mesh.skeleton.bones;
  1647. var bones2 = vpd.bones;
  1648. var table = {};
  1649. for ( var i = 0; i < bones.length; i++ ) {
  1650. table[ bones[ i ].name ] = i;
  1651. }
  1652. var thV = new THREE.Vector3();
  1653. var thQ = new THREE.Quaternion();
  1654. for ( var i = 0; i < bones2.length; i++ ) {
  1655. var b = bones2[ i ];
  1656. var index = table[ b.name ];
  1657. if ( index === undefined ) continue;
  1658. var b2 = bones[ index ];
  1659. var t = b.translation;
  1660. var q = b.quaternion;
  1661. thV.set( t[ 0 ], t[ 1 ], t[ 2 ] );
  1662. thQ.set( q[ 0 ], q[ 1 ], q[ 2 ], q[ 3 ] );
  1663. b2.position.add( thV );
  1664. b2.quaternion.multiply( thQ );
  1665. }
  1666. mesh.updateMatrixWorld( true );
  1667. if ( params.preventIk !== true ) {
  1668. var solver = new THREE.CCDIKSolver( mesh );
  1669. solver.update( params.saveOriginalBonesBeforeIK );
  1670. }
  1671. if ( params.preventGrant !== true && mesh.geometry.grants !== undefined ) {
  1672. var solver = new THREE.MMDGrantSolver( mesh );
  1673. solver.update();
  1674. }
  1675. },
  1676. /*
  1677. * Note: These following three functions are workaround for r74dev.
  1678. * THREE.PropertyMixer.apply() seems to save values into buffer cache
  1679. * when mixer.update() is called.
  1680. * ikSolver.update() and physics.update() change bone position/quaternion
  1681. * without mixer.update() then buffer cache will be inconsistent.
  1682. * So trying to avoid buffer cache inconsistency by doing
  1683. * backup bones position/quaternion right after mixer.update() call
  1684. * and then restore them after rendering.
  1685. */
  1686. initBackupBones: function ( mesh ) {
  1687. mesh.skeleton.backupBones = [];
  1688. for ( var i = 0; i < mesh.skeleton.bones.length; i++ ) {
  1689. mesh.skeleton.backupBones.push( mesh.skeleton.bones[ i ].clone() );
  1690. }
  1691. },
  1692. backupBones: function ( mesh ) {
  1693. mesh.skeleton.backupBoneIsSaved = true;
  1694. for ( var i = 0; i < mesh.skeleton.bones.length; i++ ) {
  1695. var b = mesh.skeleton.backupBones[ i ];
  1696. var b2 = mesh.skeleton.bones[ i ];
  1697. b.position.copy( b2.position );
  1698. b.quaternion.copy( b2.quaternion );
  1699. }
  1700. },
  1701. restoreBones: function ( mesh ) {
  1702. if ( mesh.skeleton.backupBoneIsSaved !== true ) {
  1703. return;
  1704. }
  1705. mesh.skeleton.backupBoneIsSaved = false;
  1706. for ( var i = 0; i < mesh.skeleton.bones.length; i++ ) {
  1707. var b = mesh.skeleton.bones[ i ];
  1708. var b2 = mesh.skeleton.backupBones[ i ];
  1709. b.position.copy( b2.position );
  1710. b.quaternion.copy( b2.quaternion );
  1711. }
  1712. }
  1713. };
粤ICP备19079148号