-
Notifications
You must be signed in to change notification settings - Fork 1
/
texture.js
83 lines (69 loc) · 2.39 KB
/
texture.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
const WRAP = {
clamp: 'CLAMP_TO_EDGE',
mirror: 'MIRRORED_REPEAT',
repeat: 'REPEAT',
}
const FILTER = {
nearest: 'NEAREST',
linear: 'LINEAR',
// NEAREST_MIPMAP_NEAREST
// LINEAR_MIPMAP_NEAREST
// NEAREST_MIPMAP_LINEAR
// LINEAR_MIPMAP_LINEAR
}
export default class Texture {
constructor(gl, image, wrapS, wrapT, filter, flipY) {
const texture = gl.createTexture()
this.gl = gl
this.texture = texture
this.image = image
this.flipY = flipY
this.wrapS = getProp(gl, WRAP, wrapS)
this.wrapT = getProp(gl, WRAP, wrapT)
this.filter = getProp(gl, FILTER, filter)
if (image.complete && image.width && image.height || image instanceof Image === false) {
// Update if already loaded or not an image element
this.update()
} else {
// Fill texture with black pixel if image isn't ready
gl.bindTexture(gl.TEXTURE_2D, texture)
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([0, 0, 0, 255]))
this.onLoad = this.onLoad.bind(this)
image.addEventListener('load', this.onLoad)
}
}
onLoad() {
this.image.removeEventListener('load', this.onLoad)
this.update()
}
update() {
const gl = this.gl
const image = this.image
gl.bindTexture(gl.TEXTURE_2D, this.texture)
if (this.flipY === true) {
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true)
}
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image)
if (isPowerOf2(image.width) && isPowerOf2(image.height)) {
gl.generateMipmap(gl.TEXTURE_2D)
}
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, this.wrapS || gl.CLAMP_TO_EDGE)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, this.wrapT || gl.CLAMP_TO_EDGE)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, this.filter || gl.LINEAR)
}
destroy() {
this.update = noop => noop
this.image.removeEventListener('load', this.onLoad)
this.gl.deleteTexture(this.texture)
}
}
function isPowerOf2(value) {
return (value & (value - 1)) == 0
}
function getProp(gl, constants, prop) {
if (prop !== undefined) {
let value = constants[prop]
if (!value) return
return gl[value]
}
}