-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathSpriteHook.js
110 lines (102 loc) · 3.61 KB
/
SpriteHook.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
var SpriteHook = {
}
SpriteHook.init = function() {
// 支持自定义Shader
const renderEngine = cc.renderer.renderEngine;
const SpriteMaterial = renderEngine.SpriteMaterial;
const GraySpriteMaterial = renderEngine.GraySpriteMaterial;
const STATE_CUSTOM = 101;
// 取自定义材质
cc.Sprite.prototype.getMaterial = function(name) {
if (this._materials) {
return this._materials[name];
} else {
return undefined;
}
}
// 设置自定义材质
cc.Sprite.prototype.setMaterial = function(name, mat) {
if (!this._materials) {
this._materials = {}
}
this._materials[name] = mat;
}
// 激活某个材质
cc.Sprite.prototype.activateMaterial = function(name) {
var mat = this.getMaterial(name);
if (mat && mat !== this._currMaterial) {
if (mat) {
if (this.node) {
mat.color = this.node.color;
}
if (this.spriteFrame) {
mat.texture = this.spriteFrame.getTexture();
}
this.node._renderFlag |= cc.RenderFlow.FLAG_COLOR;
this._currMaterial = mat;
this._currMaterial.name = name;
this._state = STATE_CUSTOM;
this._activateMaterial();
} else {
console.error("activateMaterial - unknwon material: ", name);
}
}
}
// 取当前的材质
cc.Sprite.prototype.getCurrMaterial = function() {
if (this._state === STATE_CUSTOM) {
return this._currMaterial;
}
}
cc.Sprite.prototype._activateMaterial = function() {
let spriteFrame = this._spriteFrame;
// WebGL
if (cc.game.renderType !== cc.game.RENDER_TYPE_CANVAS) {
// Get material
let material;
if (this._state === cc.Sprite.State.GRAY) {
if (!this._graySpriteMaterial) {
this._graySpriteMaterial = new GraySpriteMaterial();
this.node._renderFlag |= cc.RenderFlow.FLAG_COLOR;
}
material = this._graySpriteMaterial;
this._currMaterial = null;
}
else if (this._state === STATE_CUSTOM) {
if (!this._currMaterial) {
console.error("_activateMaterial: _currMaterial undefined!")
return;
}
material = this._currMaterial;
}
else {
if (!this._spriteMaterial) {
this._spriteMaterial = new SpriteMaterial();
this.node._renderFlag |= cc.RenderFlow.FLAG_COLOR;
}
material = this._spriteMaterial;
this._currMaterial = null;
}
// Set texture
if (spriteFrame && spriteFrame.textureLoaded()) {
let texture = spriteFrame.getTexture();
if (material.texture !== texture) {
material.texture = texture;
this._updateMaterial(material);
}
else if (material !== this._material) {
this._updateMaterial(material);
}
if (this._renderData) {
this._renderData.material = material;
}
this.markForUpdateRenderData(true);
this.markForRender(true);
}
else {
this.disableRender();
}
}
}
}
module.exports = SpriteHook;