-
-
Notifications
You must be signed in to change notification settings - Fork 4k
/
material.js
executable file
·351 lines (313 loc) · 10.8 KB
/
material.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
var registerSystem = require('../core/system').registerSystem;
var THREE = require('../lib/three');
var utils = require('../utils/');
var debug = utils.debug;
var error = debug('components:texture:error');
var TextureLoader = new THREE.TextureLoader();
var warn = debug('components:texture:warn');
TextureLoader.setCrossOrigin('anonymous');
/**
* System for material component.
* Handle material registration, updates (for fog), and texture caching.
*
* @member materials {object} - Registered materials.
* @member textureCache {object} - Texture cache for:
* - Images: textureCache has mapping of src -> repeat -> cached three.js texture.
* - Videos: textureCache has mapping of videoElement -> cached three.js texture.
*/
module.exports.System = registerSystem('material', {
init: function () {
this.materials = {};
this.textureCache = {};
},
clearTextureCache: function () {
this.textureCache = {};
},
/**
* Determine whether `src` is a image or video. Then try to load the asset, then call back.
*
* @param {string, or element} src - Texture URL or element.
* @param {string} data - Relevant texture data used for caching.
* @param {function} cb - Callback to pass texture to.
*/
loadTexture: function (src, data, cb) {
var self = this;
// Canvas.
if (src.tagName === 'CANVAS') {
this.loadCanvas(src, data, cb);
return;
}
// Video element.
if (src.tagName === 'VIDEO') {
if (!src.hasAttribute('src') && !src.hasAttribute('srcObject')) {
warn('Video element was defined without `src` nor `srcObject` attributes.');
}
this.loadVideo(src, data, cb);
return;
}
utils.srcLoader.validateSrc(src, loadImageCb, loadVideoCb);
function loadImageCb (src) { self.loadImage(src, data, cb); }
function loadVideoCb (src) { self.loadVideo(src, data, cb); }
},
/**
* High-level function for loading image textures (THREE.Texture).
*
* @param {Element|string} src - Texture source.
* @param {object} data - Texture data.
* @param {function} cb - Callback to pass texture to.
*/
loadImage: function (src, data, handleImageTextureLoaded) {
var hash = this.hash(data);
var textureCache = this.textureCache;
// Texture already being loaded or already loaded. Wait on promise.
if (textureCache[hash]) {
textureCache[hash].then(handleImageTextureLoaded);
return;
}
// Texture not yet being loaded. Start loading it.
textureCache[hash] = loadImageTexture(src, data);
textureCache[hash].then(handleImageTextureLoaded);
},
/**
* High-level function for loading canvas textures (THREE.Texture).
*
* @param {Element|string} src - Texture source.
* @param {object} data - Texture data.
* @param {function} cb - Callback to pass texture to.
*/
loadCanvas: function (src, data, cb) {
// Hack readyState and HAVE_CURRENT_DATA on canvas to work with THREE.VideoTexture
src.readyState = 2;
src.HAVE_CURRENT_DATA = 2;
this.loadVideo(src, data, cb);
},
/**
* Load video texture (THREE.VideoTexture).
* Which is just an image texture that RAFs + needsUpdate.
* Note that creating a video texture is synchronous unlike loading an image texture.
* Made asynchronous to be consistent with image textures.
*
* @param {Element|string} src - Texture source.
* @param {object} data - Texture data.
* @param {function} cb - Callback to pass texture to.
*/
loadVideo: function (src, data, cb) {
var hash;
var texture;
var textureCache = this.textureCache;
var videoEl;
var videoTextureResult;
function handleVideoTextureLoaded (result) {
result.texture.needsUpdate = true;
cb(result.texture, result.videoEl);
}
// Video element provided.
if (typeof src !== 'string') {
// Check cache before creating texture.
videoEl = src;
hash = this.hashVideo(data, videoEl);
if (textureCache[hash]) {
textureCache[hash].then(handleVideoTextureLoaded);
return;
}
// If not in cache, fix up the attributes then start to create the texture.
fixVideoAttributes(videoEl);
}
// Only URL provided. Use video element to create texture.
videoEl = videoEl || createVideoEl(src, data.width, data.height);
// Generated video element already cached. Use that.
hash = this.hashVideo(data, videoEl);
if (textureCache[hash]) {
textureCache[hash].then(handleVideoTextureLoaded);
return;
}
// Create new video texture.
texture = new THREE.VideoTexture(videoEl);
texture.minFilter = THREE.LinearFilter;
setTextureProperties(texture, data);
// Cache as promise to be consistent with image texture caching.
videoTextureResult = {texture: texture, videoEl: videoEl};
textureCache[hash] = Promise.resolve(videoTextureResult);
handleVideoTextureLoaded(videoTextureResult);
},
/**
* Create a hash of the material properties for texture cache key.
*/
hash: function (data) {
if (data.src.tagName) {
// Since `data.src` can be an element, parse out the string if necessary for the hash.
data = utils.extendDeep({}, data);
data.src = data.src.getAttribute('src');
}
return JSON.stringify(data);
},
hashVideo: function (data, videoEl) {
return calculateVideoCacheHash(data, videoEl);
},
/**
* Keep track of material in case an update trigger is needed (e.g., fog).
*
* @param {object} material
*/
registerMaterial: function (material) {
this.materials[material.uuid] = material;
},
/**
* Stop tracking material.
*
* @param {object} material
*/
unregisterMaterial: function (material) {
delete this.materials[material.uuid];
},
/**
* Trigger update to all registered materials.
*/
updateMaterials: function (material) {
var materials = this.materials;
Object.keys(materials).forEach(function (uuid) {
materials[uuid].needsUpdate = true;
});
}
});
/**
* Calculates consistent hash from a video element using its attributes.
* If the video element has an ID, use that.
* Else build a hash that looks like `src:myvideo.mp4;height:200;width:400;`.
*
* @param data {object} - Texture data such as repeat.
* @param videoEl {Element} - Video element.
* @returns {string}
*/
function calculateVideoCacheHash (data, videoEl) {
var i;
var id = videoEl.getAttribute('id');
var hash;
var videoAttributes;
if (id) { return id; }
// Calculate hash using sorted video attributes.
hash = '';
videoAttributes = data || {};
for (i = 0; i < videoEl.attributes.length; i++) {
videoAttributes[videoEl.attributes[i].name] = videoEl.attributes[i].value;
}
Object.keys(videoAttributes).sort().forEach(function (name) {
hash += name + ':' + videoAttributes[name] + ';';
});
return hash;
}
/**
* Load image texture.
*
* @private
* @param {string|object} src - An <img> element or url to an image file.
* @param {object} data - Data to set texture properties like `repeat`.
* @returns {Promise} Resolves once texture is loaded.
*/
function loadImageTexture (src, data) {
return new Promise(doLoadImageTexture);
function doLoadImageTexture (resolve, reject) {
var isEl = typeof src !== 'string';
function resolveTexture (texture) {
setTextureProperties(texture, data);
texture.needsUpdate = true;
resolve(texture);
}
// Create texture from an element.
if (isEl) {
resolveTexture(new THREE.Texture(src));
return;
}
// Request and load texture from src string. THREE will create underlying element.
// Use THREE.TextureLoader (src, onLoad, onProgress, onError) to load texture.
TextureLoader.load(
src,
resolveTexture,
function () { /* no-op */ },
function (xhr) {
error('`$s` could not be fetched (Error code: %s; Response: %s)', xhr.status,
xhr.statusText);
}
);
}
}
/**
* Set texture properties such as repeat and offset.
*
* @param {object} data - With keys like `repeat`.
*/
function setTextureProperties (texture, data) {
var offset = data.offset || {x: 0, y: 0};
var repeat = data.repeat || {x: 1, y: 1};
var npot = data.npot || false;
// To support NPOT textures, wrap must be ClampToEdge (not Repeat),
// and filters must not use mipmaps (i.e. Nearest or Linear).
if (npot) {
texture.wrapS = THREE.ClampToEdgeWrapping;
texture.wrapT = THREE.ClampToEdgeWrapping;
texture.magFilter = THREE.LinearFilter;
texture.minFilter = THREE.LinearFilter;
}
// Don't bother setting repeat if it is 1/1. Power-of-two is required to repeat.
if (repeat.x !== 1 || repeat.y !== 1) {
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set(repeat.x, repeat.y);
}
// Don't bother setting offset if it is 0/0.
if (offset.x !== 0 || offset.y !== 0) {
texture.offset.set(offset.x, offset.y);
}
}
/**
* Create video element to be used as a texture.
*
* @param {string} src - Url to a video file.
* @param {number} width - Width of the video.
* @param {number} height - Height of the video.
* @returns {Element} Video element.
*/
function createVideoEl (src, width, height) {
var videoEl = document.createElement('video');
videoEl.width = width;
videoEl.height = height;
// Support inline videos for iOS webviews.
videoEl.setAttribute('playsinline', '');
videoEl.setAttribute('webkit-playsinline', '');
videoEl.autoplay = true;
videoEl.loop = true;
videoEl.crossOrigin = 'anonymous';
videoEl.addEventListener('error', function () {
warn('`$s` is not a valid video', src);
}, true);
videoEl.src = src;
return videoEl;
}
/**
* Fixes a video element's attributes to prevent developers from accidentally passing the
* wrong attribute values to commonly misused video attributes.
*
* <video> does not treat `autoplay`, `controls`, `crossorigin`, `loop`, and `preload` as
* as booleans. Existence of those attributes will mean truthy.
*
* For example, translates <video loop="false"> to <video>.
*
* @see https://developer.mozilla.org/docs/Web/HTML/Element/video#Attributes
* @param {Element} videoEl - Video element.
* @returns {Element} Video element with the correct properties updated.
*/
function fixVideoAttributes (videoEl) {
videoEl.autoplay = videoEl.hasAttribute('autoplay') && videoEl.getAttribute('autoplay') !== 'false';
videoEl.controls = videoEl.hasAttribute('controls') && videoEl.getAttribute('controls') !== 'false';
if (videoEl.getAttribute('loop') === 'false') {
videoEl.removeAttribute('loop');
}
if (videoEl.getAttribute('preload') === 'false') {
videoEl.preload = 'none';
}
videoEl.crossOrigin = videoEl.crossOrigin || 'anonymous';
// To support inline videos in iOS webviews.
videoEl.setAttribute('playsinline', '');
videoEl.setAttribute('webkit-playsinline', '');
return videoEl;
}