MMDLoader.js 50 KB

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