1
0

ArrayNode.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. import TempNode from './TempNode.js';
  2. import { addMethodChaining, nodeObject } from '../tsl/TSLCore.js';
  3. /**
  4. * ArrayNode represents a collection of nodes, typically created using the {@link marray} function.
  5. * ```js
  6. * const colors = array( [
  7. * vec3( 1, 0, 0 ),
  8. * vec3( 0, 1, 0 ),
  9. * vec3( 0, 0, 1 )
  10. * ] );
  11. *
  12. * const redColor = tintColors.element( 0 );
  13. *
  14. * @augments Node
  15. */
  16. class ArrayNode extends TempNode {
  17. static get type() {
  18. return 'ArrayNode';
  19. }
  20. /**
  21. * Constructs a new array node.
  22. *
  23. * @param {String} [nodeType] - The data type of the elements.
  24. * @param {Number} [count] - Size of the array.
  25. * @param {Array<Node>?} [values=null] - Array default values.
  26. */
  27. constructor( nodeType, count, values = null ) {
  28. super( nodeType );
  29. /**
  30. * Array size.
  31. *
  32. * @type {Array<Node>}
  33. */
  34. this.count = count;
  35. /**
  36. * Array default values.
  37. *
  38. * @type {Array<Node>}
  39. */
  40. this.values = values;
  41. /**
  42. * This flag can be used for type testing.
  43. *
  44. * @type {Boolean}
  45. * @readonly
  46. * @default true
  47. */
  48. this.isArrayNode = true;
  49. }
  50. getNodeType( builder ) {
  51. if ( this.nodeType === null ) {
  52. this.nodeType = this.values[ 0 ].getNodeType( builder );
  53. }
  54. return this.nodeType;
  55. }
  56. getElementType( builder ) {
  57. return this.getNodeType( builder );
  58. }
  59. generate( builder ) {
  60. const type = this.getNodeType( builder );
  61. return builder.generateArray( type, this.count, this.values );
  62. }
  63. }
  64. export default ArrayNode;
  65. /**
  66. * TSL function for creating an array node.
  67. *
  68. * @tsl
  69. * @function
  70. * @param {String|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  71. * or an array containing the default values (e.g., [ vec3() ]).
  72. * @param {Number?} [count] - Size of the array.
  73. * @returns {ArrayNode}
  74. */
  75. export const array = ( ...params ) => {
  76. let node;
  77. if ( params.length === 1 ) {
  78. const values = params[ 0 ];
  79. node = new ArrayNode( null, values.length, values );
  80. } else {
  81. const nodeType = params[ 0 ];
  82. const count = params[ 1 ];
  83. node = new ArrayNode( nodeType, count );
  84. }
  85. return nodeObject( node );
  86. };
  87. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
粤ICP备19079148号