NodeMaterial.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import { Material, ShaderMaterial } from 'three';
  2. import { getNodesKeys } from '../core/NodeUtils.js';
  3. class NodeMaterial extends ShaderMaterial {
  4. constructor() {
  5. super();
  6. this.type = this.constructor.name;
  7. this.lights = true;
  8. }
  9. setDefaultValues( values ) {
  10. // This approach is to reuse the native refreshUniforms*
  11. // and turn available the use of features like transmission and environment in core
  12. for ( const property in values ) {
  13. if ( this[ property ] === undefined ) {
  14. this[ property ] = values[ property ];
  15. }
  16. }
  17. Object.assign( this.defines, values.defines );
  18. }
  19. toJSON( meta ) {
  20. const isRoot = ( meta === undefined || typeof meta === 'string' );
  21. if ( isRoot ) {
  22. meta = {
  23. textures: {},
  24. images: {},
  25. nodes: {}
  26. };
  27. }
  28. const data = Material.prototype.toJSON.call( this, meta );
  29. const nodeKeys = getNodesKeys( this );
  30. data.inputNodes = {};
  31. for ( const name of nodeKeys ) {
  32. data.inputNodes[ name ] = this[ name ].toJSON( meta ).uuid;
  33. }
  34. // TODO: Copied from Object3D.toJSON
  35. function extractFromCache( cache ) {
  36. const values = [];
  37. for ( const key in cache ) {
  38. const data = cache[ key ];
  39. delete data.metadata;
  40. values.push( data );
  41. }
  42. return values;
  43. }
  44. if ( isRoot ) {
  45. const textures = extractFromCache( meta.textures );
  46. const images = extractFromCache( meta.images );
  47. const nodes = extractFromCache( meta.nodes );
  48. if ( textures.length > 0 ) data.textures = textures;
  49. if ( images.length > 0 ) data.images = images;
  50. if ( nodes.length > 0 ) data.nodes = nodes;
  51. }
  52. return data;
  53. }
  54. }
  55. NodeMaterial.prototype.isNodeMaterial = true;
  56. export default NodeMaterial;