CmdSetMaterial.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. /**
  2. * Created by Daniel on 21.07.15.
  3. */
  4. CmdSetMaterial = function ( object, newMaterial ) {
  5. Cmd.call( this );
  6. this.type = 'CmdSetMaterial';
  7. this.name = 'New Material';
  8. this.object = object;
  9. this.oldMaterial = ( object !== undefined ) ? object.material : undefined;
  10. this.newMaterial = newMaterial;
  11. };
  12. CmdSetMaterial.prototype = {
  13. execute: function () {
  14. this.object.material = this.newMaterial;
  15. this.editor.signals.materialChanged.dispatch( this.newMaterial );
  16. },
  17. undo: function () {
  18. this.object.material = this.oldMaterial;
  19. this.editor.signals.materialChanged.dispatch( this.oldMaterial );
  20. },
  21. toJSON: function () {
  22. var output = Cmd.prototype.toJSON.call( this );
  23. output.objectUuid = this.object.uuid;
  24. output.oldMaterial = serializeMaterial( this.oldMaterial );
  25. output.newMaterial = serializeMaterial( this.newMaterial );
  26. return output;
  27. function serializeMaterial ( material ) {
  28. if ( material === undefined ) return null;
  29. var meta = {
  30. geometries: {},
  31. materials: {},
  32. textures: {},
  33. images: {}
  34. };
  35. var json = {};
  36. json.materials = [ material.toJSON( meta ) ];
  37. var textures = extractFromCache( meta.textures );
  38. var images = extractFromCache( meta.images );
  39. if ( textures.length > 0 ) json.textures = textures;
  40. if ( images.length > 0 ) json.images = images;
  41. return json;
  42. }
  43. // Note: The function 'extractFromCache' is copied from Object3D.toJSON()
  44. // extract data from the cache hash
  45. // remove metadata on each item
  46. // and return as array
  47. function extractFromCache ( cache ) {
  48. var values = [];
  49. for ( var key in cache ) {
  50. var data = cache[ key ];
  51. delete data.metadata;
  52. values.push( data );
  53. }
  54. return values;
  55. }
  56. },
  57. fromJSON: function ( json ) {
  58. Cmd.prototype.fromJSON.call( this, json );
  59. this.object = this.editor.objectByUuid( json.objectUuid );
  60. this.oldMaterial = parseMaterial( json.oldMaterial );
  61. this.newMaterial = parseMaterial( json.newMaterial );
  62. function parseMaterial ( json ) {
  63. var loader = new THREE.ObjectLoader();
  64. var images = loader.parseImages( json.images );
  65. var textures = loader.parseTextures( json.textures, images );
  66. var materials = loader.parseMaterials( json.materials, textures );
  67. return materials[ json.materials[ 0 ].uuid ];
  68. }
  69. }
  70. };