SplitNode.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import Node from '../core/Node.js';
  2. import { vector } from '../core/NodeBuilder.js';
  3. const vectorComponents = 'xyzw';
  4. class SplitNode extends Node {
  5. constructor( node, components = 'x' ) {
  6. super();
  7. this.node = node;
  8. this.components = components;
  9. }
  10. getVectorLength() {
  11. let vectorLength = this.components.length;
  12. for ( const c of this.components ) {
  13. vectorLength = Math.max( vector.indexOf( c ) + 1, vectorLength );
  14. }
  15. return vectorLength;
  16. }
  17. getNodeType( builder ) {
  18. return builder.getTypeFromLength( this.components.length );
  19. }
  20. generate( builder, output ) {
  21. const node = this.node;
  22. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  23. let snippet = null;
  24. if ( nodeTypeLength > 1 ) {
  25. let type = null;
  26. const componentsLength = this.getVectorLength();
  27. if ( componentsLength >= nodeTypeLength ) {
  28. // needed expand the input node
  29. type = builder.getTypeFromLength( this.getVectorLength() );
  30. }
  31. const nodeSnippet = node.build( builder, type );
  32. if ( this.components.length === nodeTypeLength && this.components === vectorComponents.slice( 0, this.components.length ) ) {
  33. // unecessary swizzle
  34. snippet = builder.format( nodeSnippet, type, output );
  35. } else {
  36. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  37. }
  38. } else {
  39. // ignore .components if .node returns float/integer
  40. snippet = node.build( builder, output );
  41. }
  42. return snippet;
  43. }
  44. serialize( data ) {
  45. super.serialize( data );
  46. data.components = this.components;
  47. }
  48. deserialize( data ) {
  49. super.deserialize( data );
  50. this.components = data.components;
  51. }
  52. }
  53. export default SplitNode;