PropertyBinding.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. /**
  2. *
  3. * A reference to a real property in the scene graph.
  4. *
  5. *
  6. * @author Ben Houston / http://clara.io/
  7. * @author David Sarno / http://lighthaus.us/
  8. * @author tschw
  9. */
  10. // Characters [].:/ are reserved for track binding syntax.
  11. var RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  12. function Composite( targetGroup, path, optionalParsedPath ) {
  13. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  14. this._targetGroup = targetGroup;
  15. this._bindings = targetGroup.subscribe_( path, parsedPath );
  16. }
  17. Object.assign( Composite.prototype, {
  18. getValue: function ( array, offset ) {
  19. this.bind(); // bind all binding
  20. var firstValidIndex = this._targetGroup.nCachedObjects_,
  21. binding = this._bindings[ firstValidIndex ];
  22. // and only call .getValue on the first
  23. if ( binding !== undefined ) binding.getValue( array, offset );
  24. },
  25. setValue: function ( array, offset ) {
  26. var bindings = this._bindings;
  27. for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  28. bindings[ i ].setValue( array, offset );
  29. }
  30. },
  31. bind: function () {
  32. var bindings = this._bindings;
  33. for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  34. bindings[ i ].bind();
  35. }
  36. },
  37. unbind: function () {
  38. var bindings = this._bindings;
  39. for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  40. bindings[ i ].unbind();
  41. }
  42. }
  43. } );
  44. function PropertyBinding( rootNode, path, parsedPath ) {
  45. this.path = path;
  46. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  47. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  48. this.rootNode = rootNode;
  49. }
  50. Object.assign( PropertyBinding, {
  51. Composite: Composite,
  52. create: function ( root, path, parsedPath ) {
  53. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  54. return new PropertyBinding( root, path, parsedPath );
  55. } else {
  56. return new PropertyBinding.Composite( root, path, parsedPath );
  57. }
  58. },
  59. /**
  60. * Replaces spaces with underscores and removes unsupported characters from
  61. * node names, to ensure compatibility with parseTrackName().
  62. *
  63. * @param {string} name Node name to be sanitized.
  64. * @return {string}
  65. */
  66. sanitizeNodeName: ( function () {
  67. var reservedRe = new RegExp( '[' + RESERVED_CHARS_RE + ']', 'g' );
  68. return function sanitizeNodeName( name ) {
  69. return name.replace( /\s/g, '_' ).replace( reservedRe, '' );
  70. };
  71. }() ),
  72. parseTrackName: function () {
  73. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  74. // only latin characters, and the unicode \p{L} is not yet supported. So
  75. // instead, we exclude reserved characters and match everything else.
  76. var wordChar = '[^' + RESERVED_CHARS_RE + ']';
  77. var wordCharOrDot = '[^' + RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  78. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  79. // be matched to parse the rest of the track name.
  80. var directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', wordChar );
  81. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  82. var nodeRe = /(WCOD+)?/.source.replace( 'WCOD', wordCharOrDot );
  83. // Object on target node, and accessor. May not contain reserved
  84. // characters. Accessor may contain any character except closing bracket.
  85. var objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', wordChar );
  86. // Property and accessor. May not contain reserved characters. Accessor may
  87. // contain any non-bracket characters.
  88. var propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', wordChar );
  89. var trackRe = new RegExp( ''
  90. + '^'
  91. + directoryRe
  92. + nodeRe
  93. + objectRe
  94. + propertyRe
  95. + '$'
  96. );
  97. var supportedObjectNames = [ 'material', 'materials', 'bones' ];
  98. return function parseTrackName( trackName ) {
  99. var matches = trackRe.exec( trackName );
  100. if ( ! matches ) {
  101. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  102. }
  103. var results = {
  104. // directoryName: matches[ 1 ], // (tschw) currently unused
  105. nodeName: matches[ 2 ],
  106. objectName: matches[ 3 ],
  107. objectIndex: matches[ 4 ],
  108. propertyName: matches[ 5 ], // required
  109. propertyIndex: matches[ 6 ]
  110. };
  111. var lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  112. if ( lastDot !== undefined && lastDot !== - 1 ) {
  113. var objectName = results.nodeName.substring( lastDot + 1 );
  114. // Object names must be checked against a whitelist. Otherwise, there
  115. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  116. // 'bar' could be the objectName, or part of a nodeName (which can
  117. // include '.' characters).
  118. if ( supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  119. results.nodeName = results.nodeName.substring( 0, lastDot );
  120. results.objectName = objectName;
  121. }
  122. }
  123. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  124. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  125. }
  126. return results;
  127. };
  128. }(),
  129. findNode: function ( root, nodeName ) {
  130. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  131. return root;
  132. }
  133. // search into skeleton bones.
  134. if ( root.skeleton ) {
  135. var bone = root.skeleton.getBoneByName( nodeName );
  136. if ( bone !== undefined ) {
  137. return bone;
  138. }
  139. }
  140. // search into node subtree.
  141. if ( root.children ) {
  142. var searchNodeSubtree = function ( children ) {
  143. for ( var i = 0; i < children.length; i ++ ) {
  144. var childNode = children[ i ];
  145. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  146. return childNode;
  147. }
  148. var result = searchNodeSubtree( childNode.children );
  149. if ( result ) return result;
  150. }
  151. return null;
  152. };
  153. var subTreeNode = searchNodeSubtree( root.children );
  154. if ( subTreeNode ) {
  155. return subTreeNode;
  156. }
  157. }
  158. return null;
  159. }
  160. } );
  161. Object.assign( PropertyBinding.prototype, { // prototype, continued
  162. // these are used to "bind" a nonexistent property
  163. _getValue_unavailable: function () {},
  164. _setValue_unavailable: function () {},
  165. BindingType: {
  166. Direct: 0,
  167. EntireArray: 1,
  168. ArrayElement: 2,
  169. HasFromToArray: 3
  170. },
  171. Versioning: {
  172. None: 0,
  173. NeedsUpdate: 1,
  174. MatrixWorldNeedsUpdate: 2
  175. },
  176. GetterByBindingType: [
  177. function getValue_direct( buffer, offset ) {
  178. buffer[ offset ] = this.node[ this.propertyName ];
  179. },
  180. function getValue_array( buffer, offset ) {
  181. var source = this.resolvedProperty;
  182. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  183. buffer[ offset ++ ] = source[ i ];
  184. }
  185. },
  186. function getValue_arrayElement( buffer, offset ) {
  187. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  188. },
  189. function getValue_toArray( buffer, offset ) {
  190. this.resolvedProperty.toArray( buffer, offset );
  191. }
  192. ],
  193. SetterByBindingTypeAndVersioning: [
  194. [
  195. // Direct
  196. function setValue_direct( buffer, offset ) {
  197. this.targetObject[ this.propertyName ] = buffer[ offset ];
  198. },
  199. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  200. this.targetObject[ this.propertyName ] = buffer[ offset ];
  201. this.targetObject.needsUpdate = true;
  202. },
  203. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  204. this.targetObject[ this.propertyName ] = buffer[ offset ];
  205. this.targetObject.matrixWorldNeedsUpdate = true;
  206. }
  207. ], [
  208. // EntireArray
  209. function setValue_array( buffer, offset ) {
  210. var dest = this.resolvedProperty;
  211. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  212. dest[ i ] = buffer[ offset ++ ];
  213. }
  214. },
  215. function setValue_array_setNeedsUpdate( buffer, offset ) {
  216. var dest = this.resolvedProperty;
  217. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  218. dest[ i ] = buffer[ offset ++ ];
  219. }
  220. this.targetObject.needsUpdate = true;
  221. },
  222. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  223. var dest = this.resolvedProperty;
  224. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  225. dest[ i ] = buffer[ offset ++ ];
  226. }
  227. this.targetObject.matrixWorldNeedsUpdate = true;
  228. }
  229. ], [
  230. // ArrayElement
  231. function setValue_arrayElement( buffer, offset ) {
  232. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  233. },
  234. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  235. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  236. this.targetObject.needsUpdate = true;
  237. },
  238. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  239. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  240. this.targetObject.matrixWorldNeedsUpdate = true;
  241. }
  242. ], [
  243. // HasToFromArray
  244. function setValue_fromArray( buffer, offset ) {
  245. this.resolvedProperty.fromArray( buffer, offset );
  246. },
  247. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  248. this.resolvedProperty.fromArray( buffer, offset );
  249. this.targetObject.needsUpdate = true;
  250. },
  251. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  252. this.resolvedProperty.fromArray( buffer, offset );
  253. this.targetObject.matrixWorldNeedsUpdate = true;
  254. }
  255. ]
  256. ],
  257. getValue: function getValue_unbound( targetArray, offset ) {
  258. this.bind();
  259. this.getValue( targetArray, offset );
  260. // Note: This class uses a State pattern on a per-method basis:
  261. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  262. // prototype version of these methods with one that represents
  263. // the bound state. When the property is not found, the methods
  264. // become no-ops.
  265. },
  266. setValue: function getValue_unbound( sourceArray, offset ) {
  267. this.bind();
  268. this.setValue( sourceArray, offset );
  269. },
  270. // create getter / setter pair for a property in the scene graph
  271. bind: function () {
  272. var targetObject = this.node,
  273. parsedPath = this.parsedPath,
  274. objectName = parsedPath.objectName,
  275. propertyName = parsedPath.propertyName,
  276. propertyIndex = parsedPath.propertyIndex;
  277. if ( ! targetObject ) {
  278. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  279. this.node = targetObject;
  280. }
  281. // set fail state so we can just 'return' on error
  282. this.getValue = this._getValue_unavailable;
  283. this.setValue = this._setValue_unavailable;
  284. // ensure there is a value node
  285. if ( ! targetObject ) {
  286. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  287. return;
  288. }
  289. if ( objectName ) {
  290. var objectIndex = parsedPath.objectIndex;
  291. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  292. switch ( objectName ) {
  293. case 'materials':
  294. if ( ! targetObject.material ) {
  295. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  296. return;
  297. }
  298. if ( ! targetObject.material.materials ) {
  299. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  300. return;
  301. }
  302. targetObject = targetObject.material.materials;
  303. break;
  304. case 'bones':
  305. if ( ! targetObject.skeleton ) {
  306. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  307. return;
  308. }
  309. // potential future optimization: skip this if propertyIndex is already an integer
  310. // and convert the integer string to a true integer.
  311. targetObject = targetObject.skeleton.bones;
  312. // support resolving morphTarget names into indices.
  313. for ( var i = 0; i < targetObject.length; i ++ ) {
  314. if ( targetObject[ i ].name === objectIndex ) {
  315. objectIndex = i;
  316. break;
  317. }
  318. }
  319. break;
  320. default:
  321. if ( targetObject[ objectName ] === undefined ) {
  322. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  323. return;
  324. }
  325. targetObject = targetObject[ objectName ];
  326. }
  327. if ( objectIndex !== undefined ) {
  328. if ( targetObject[ objectIndex ] === undefined ) {
  329. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  330. return;
  331. }
  332. targetObject = targetObject[ objectIndex ];
  333. }
  334. }
  335. // resolve property
  336. var nodeProperty = targetObject[ propertyName ];
  337. if ( nodeProperty === undefined ) {
  338. var nodeName = parsedPath.nodeName;
  339. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  340. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  341. return;
  342. }
  343. // determine versioning scheme
  344. var versioning = this.Versioning.None;
  345. this.targetObject = targetObject;
  346. if ( targetObject.needsUpdate !== undefined ) { // material
  347. versioning = this.Versioning.NeedsUpdate;
  348. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  349. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  350. }
  351. // determine how the property gets bound
  352. var bindingType = this.BindingType.Direct;
  353. if ( propertyIndex !== undefined ) {
  354. // access a sub element of the property array (only primitives are supported right now)
  355. if ( propertyName === "morphTargetInfluences" ) {
  356. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  357. // support resolving morphTarget names into indices.
  358. if ( ! targetObject.geometry ) {
  359. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  360. return;
  361. }
  362. if ( targetObject.geometry.isBufferGeometry ) {
  363. if ( ! targetObject.geometry.morphAttributes ) {
  364. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  365. return;
  366. }
  367. for ( var i = 0; i < this.node.geometry.morphAttributes.position.length; i ++ ) {
  368. if ( targetObject.geometry.morphAttributes.position[ i ].name === propertyIndex ) {
  369. propertyIndex = i;
  370. break;
  371. }
  372. }
  373. } else {
  374. if ( ! targetObject.geometry.morphTargets ) {
  375. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this );
  376. return;
  377. }
  378. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  379. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  380. propertyIndex = i;
  381. break;
  382. }
  383. }
  384. }
  385. }
  386. bindingType = this.BindingType.ArrayElement;
  387. this.resolvedProperty = nodeProperty;
  388. this.propertyIndex = propertyIndex;
  389. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  390. // must use copy for Object3D.Euler/Quaternion
  391. bindingType = this.BindingType.HasFromToArray;
  392. this.resolvedProperty = nodeProperty;
  393. } else if ( Array.isArray( nodeProperty ) ) {
  394. bindingType = this.BindingType.EntireArray;
  395. this.resolvedProperty = nodeProperty;
  396. } else {
  397. this.propertyName = propertyName;
  398. }
  399. // select getter / setter
  400. this.getValue = this.GetterByBindingType[ bindingType ];
  401. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  402. },
  403. unbind: function () {
  404. this.node = null;
  405. // back to the prototype version of getValue / setValue
  406. // note: avoiding to mutate the shape of 'this' via 'delete'
  407. this.getValue = this._getValue_unbound;
  408. this.setValue = this._setValue_unbound;
  409. }
  410. } );
  411. //!\ DECLARE ALIAS AFTER assign prototype !
  412. Object.assign( PropertyBinding.prototype, {
  413. // initial state of these methods that calls 'bind'
  414. _getValue_unbound: PropertyBinding.prototype.getValue,
  415. _setValue_unbound: PropertyBinding.prototype.setValue,
  416. } );
  417. export { PropertyBinding };
粤ICP备19079148号