effect initialization

This commit is contained in:
Yun Hsiao Wu
2019-01-03 18:53:02 +08:00
parent 47f8711dd5
commit 3a5926a673
9 changed files with 211 additions and 177 deletions
+19 -11
View File
@@ -1,9 +1,9 @@
import Asset from '../../assets/CCAsset';
import { ccclass, property } from '../../core/data/class-decorator';
import { PassInfo } from '../../renderer/core/pass';
import { PassInfoBase } from '../../renderer/core/pass';
export interface TechniqueInfo {
passes: PassInfo[];
passes: PassInfoBase[];
queue?: number;
priority?: number;
lod?: number;
@@ -16,30 +16,38 @@ export interface PropertyInfo {
pass?: number;
}
export interface UniformInfo {
export interface BlockMember {
name: string;
type: number;
bindingType: number;
count: number;
}
export interface BlockInfo {
name: string;
binding: number;
defines: string[];
members?: Array< { name: string, type: number } >;
size: number;
members: BlockMember[];
}
export interface SamplerInfo {
name: string;
binding: number;
defines: string[];
type: number;
count: number;
}
export interface DefineInfo {
name: string;
type: string;
defines: string[];
}
export interface ExtensionInfo {
name: string;
define: string;
}
export interface ShaderInfo {
name: string;
vert: string;
frag: string;
defines: DefineInfo[];
uniforms: UniformInfo[];
extensions: ExtensionInfo[];
blocks: BlockInfo[];
samplers: SamplerInfo[];
dependencies: { [name: string]: string };
}
const effects: { [name: string]: EffectAsset } = {};
+1 -3
View File
@@ -124,9 +124,7 @@ class Material extends Asset {
}
this._effectAsset = effectAsset;
if (!effectAsset) return;
this._effect = Effect.parseEffect(effectAsset);
for (let def in this._defines)
this._effect.define(def, this._defines[def]);
this._effect = Effect.parseEffect(effectAsset, this._defines);
for (let prop in this._props)
this.setProperty(prop, this._props[prop]);
}
+50 -46
View File
@@ -1,12 +1,50 @@
export default [
{
"name": "builtin-effect-skybox",
"techniques": [{"queue": 0, "lod": 200, "passes": [{"rasterizerState": {"cullMode": 0}, "depthStencilState": {"depthTest": false, "depthWrite": false}, "program": "d9cd35729516d899db5cd6b6ecf025e61a484094405a391a3056591d"}], "priority": -1000}],
"properties": {"cubeMap": {"type": 32, "value": null}},
"shaders": [
{
"name": "d9cd35729516d899db5cd6b6ecf025e61a484094405a391a3056591d",
"vert": "\n attribute vec3 a_position;\n \n uniform mat4 cc_matProj;\n uniform mat4 cc_matProjInv;\n uniform mat4 cc_matView;\n uniform mat4 cc_matViewInv;\n uniform mat4 cc_matViewProj;\n uniform mat4 cc_matViewProjInv;\n uniform vec4 cc_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection;\n uniform vec4 cc_dirLightColor;\n uniform vec4 cc_pointLightPositionAndRange;\n uniform vec4 cc_pointLightColor;\n uniform vec4 cc_spotLightPositionAndRange;\n uniform vec4 cc_spotLightDirection;\n uniform vec4 cc_spotLightColor;\n uniform mat4 cc_matViewProjLight;\n uniform vec4 cc_shadowParam1;\n uniform vec4 cc_shadowParam2;\n varying vec3 viewDir;\n void main() {\n mat4 rotView = mat4(mat3(cc_matView));\n vec4 clipPos = cc_matProj * rotView * vec4(a_position, 1.0);\n gl_Position = clipPos.xyww;\n viewDir = a_position;\n }\n",
"frag": "\n varying vec3 viewDir;\n uniform samplerCube cubeMap;\n \nvec3 gammaToLinearSpaceRGB(vec3 sRGB) { \n return sRGB * (sRGB * (sRGB * 0.305306011 + 0.682171111) + 0.012522878);\n}\nvec3 linearToGammaSpaceRGB(vec3 RGB) { \n vec3 S1 = sqrt(RGB);\n vec3 S2 = sqrt(S1);\n vec3 S3 = sqrt(S2);\n return 0.585122381 * S1 + 0.783140355 * S2 - 0.368262736 * S3;\n}\nvec4 gammaToLinearSpaceRGBA(vec4 sRGBA) {\n return vec4(gammaToLinearSpaceRGB(sRGBA.rgb), sRGBA.a);\n}\nvec4 linearToGammaSpaceRGBA(vec4 RGBA) {\n return vec4(linearToGammaSpaceRGB(RGBA.rgb), RGBA.a);\n}\nfloat gammaToLinearSpaceExact(float val) {\n if (val <= 0.04045) {\n return val / 12.92;\n } else if (val < 1.0) {\n return pow((val + 0.055) / 1.055, 2.4);\n } else {\n return pow(val, 2.2);\n }\n}\nfloat linearToGammaSpaceExact(float val) {\n if (val <= 0.0) {\n return 0.0;\n } else if (val <= 0.0031308) {\n return 12.92 * val;\n } else if (val < 1.0) {\n return 1.055 * pow(val, 0.4166667) - 0.055;\n } else {\n return pow(val, 0.45454545);\n }\n}\n \nvec3 unpackNormal(vec4 nmap) {\n return nmap.xyz * 2.0 - 1.0;\n}\nvec3 unpackRGBE(vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\n void main() {\n #if USE_RGBE_CUBEMAP\n vec3 c = unpackRGBE(textureCube(cubeMap, viewDir));\n c = linearToGammaSpaceRGB(c / (1.0 + c));\n gl_FragColor = vec4(c, 1.0);\n #else\n gl_FragColor = textureCube(cubeMap, viewDir);\n #endif\n }\n",
"defines": [
{"name": "USE_RGBE_CUBEMAP", "type": "boolean", "defines": []}
],
"blocks": [],
"samplers": [
{"name": "cubeMap", "type": 32, "count": 1, "defines": [], "binding": 0}
],
"dependencies": {}
}
]
},
{
"name": "builtin-effect-sprite",
"techniques": [{"queue": 2, "passes": [{"depthStencilState": {"depthTest": true, "depthWrite": false}, "blendState": {"targets": [{"blend": true, "blendSrc": 2, "blendDst": 4, "blendDstAlpha": 4}]}, "program": "a86b95b64dc75bf2cc5b528318547813f86f5cd9e03ee48ca69556f6"}], "priority": 0}],
"properties": {"mainTexture": {"type": 29, "value": null}},
"shaders": [
{
"name": "a86b95b64dc75bf2cc5b528318547813f86f5cd9e03ee48ca69556f6",
"vert": "\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\n uniform mat4 cc_matProj;\n uniform mat4 cc_matProjInv;\n uniform mat4 cc_matView;\n uniform mat4 cc_matViewInv;\n uniform mat4 cc_matViewProj;\n uniform mat4 cc_matViewProjInv;\n uniform vec4 cc_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection;\n uniform vec4 cc_dirLightColor;\n uniform vec4 cc_pointLightPositionAndRange;\n uniform vec4 cc_pointLightColor;\n uniform vec4 cc_spotLightPositionAndRange;\n uniform vec4 cc_spotLightDirection;\n uniform vec4 cc_spotLightColor;\n uniform mat4 cc_matViewProjLight;\n uniform vec4 cc_shadowParam1;\n uniform vec4 cc_shadowParam2;\n uniform mat4 cc_matWorld;\n uniform mat4 cc_matWorldIT;\nvarying vec2 uv0;\nvarying vec4 color;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matViewProj * cc_matWorld * pos;\n uv0 = a_texCoord;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n",
"frag": "\nuniform sampler2D mainTexture;\nvarying vec2 uv0;\nvarying vec4 color;\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n o *= texture2D(mainTexture, uv0);\n o *= color;\n return o;\n}\nvoid main() { gl_FragColor = frag(); }\n",
"defines": [],
"blocks": [],
"samplers": [
{"name": "mainTexture", "type": 29, "count": 1, "defines": [], "binding": 0}
],
"dependencies": {}
}
]
},
{
"name": "builtin-effect-unlit",
"techniques": [{"queue": 0, "lod": 100, "passes": [{"program": "7781d6cc411d5facce7fc3d4aeb5349e804ddd9a58c002017c53682b"}], "priority": 0}],
"techniques": [{"queue": 0, "lod": 100, "passes": [{"program": "e238b675dacba30ad29961fac06cb18d8c771e16d4fb0f9662acbe3c"}], "priority": 0}],
"properties": {"color": {"type": 17, "value": [1, 1, 1, 1]}, "mainTiling": {"type": 14, "value": [1, 1]}, "mainOffset": {"type": 14, "value": [0, 0]}, "mainTexture": {"type": 29, "value": null}},
"shaders": [
{
"name": "7781d6cc411d5facce7fc3d4aeb5349e804ddd9a58c002017c53682b",
"vert": "\nattribute vec3 a_position;\n uniform mat4 cc_matProj;\n uniform mat4 cc_matProjInv;\n uniform mat4 cc_matView;\n uniform mat4 cc_matViewInv;\n uniform mat4 cc_matViewProj;\n uniform mat4 cc_matViewProjInv;\n uniform vec4 cc_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection[4];\n uniform vec4 cc_dirLightColor[4];\n uniform vec4 cc_pointLightPositionAndRange[4];\n uniform vec4 cc_pointLightColor[4];\n uniform vec4 cc_spotLightPositionAndRange[4];\n uniform vec4 cc_spotLightDirection[4];\n uniform vec4 cc_spotLightColor[4];\n uniform mat4 cc_matViewProjLight;\n uniform vec4 cc_shadowParam1;\n uniform vec4 cc_shadowParam2;\n uniform mat4 cc_matWorld;\n uniform mat4 cc_matWorldIT;\n#if USE_TEXTURE\n attribute vec2 a_texCoord1;\n uniform vec2 mainTiling;\n uniform vec2 mainOffset;\n varying vec2 uv0;\n#endif\n#if CC_USE_SKINNING\n \nattribute vec4 a_weights;\nattribute vec4 a_joints;\n uniform mat4 cc_matJoint[128];\n uniform vec4 cc_jointsTextureSize;\n#if CC_USE_JOINTS_TEXTURE\nuniform sampler2D cc_jointsTexture;\nmat4 getBoneMatrix(const in float i) {\n float size = cc_jointsTextureSize.x;\n float j = i * 4.0;\n float x = mod(j, size);\n float y = floor(j / size);\n float dx = 1.0 / size;\n float dy = 1.0 / size;\n y = dy * (y + 0.5);\n vec4 v1 = texture2D(cc_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture2D(cc_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture2D(cc_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture2D(cc_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\n#else\nmat4 getBoneMatrix(const in float i) {\n return cc_matJoint[int(i)];\n}\n#endif\nmat4 skinMatrix() {\n return\n getBoneMatrix(a_joints.x) * a_weights.x +\n getBoneMatrix(a_joints.y) * a_weights.y +\n getBoneMatrix(a_joints.z) * a_weights.z +\n getBoneMatrix(a_joints.w) * a_weights.w;\n}\nvoid skinVertex(inout vec4 a1) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2, inout vec4 a3) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n a3 = m * a3;\n}\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n #if CC_USE_SKINNING\n skinVertex(pos);\n #endif\n pos = cc_matViewProj * cc_matWorld * pos;\n #if USE_TEXTURE\n uv0 = a_texCoord1 * mainTiling + mainOffset;\n #endif\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n",
"name": "e238b675dacba30ad29961fac06cb18d8c771e16d4fb0f9662acbe3c",
"vert": "\nattribute vec3 a_position;\n uniform mat4 cc_matProj;\n uniform mat4 cc_matProjInv;\n uniform mat4 cc_matView;\n uniform mat4 cc_matViewInv;\n uniform mat4 cc_matViewProj;\n uniform mat4 cc_matViewProjInv;\n uniform vec4 cc_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection;\n uniform vec4 cc_dirLightColor;\n uniform vec4 cc_pointLightPositionAndRange;\n uniform vec4 cc_pointLightColor;\n uniform vec4 cc_spotLightPositionAndRange;\n uniform vec4 cc_spotLightDirection;\n uniform vec4 cc_spotLightColor;\n uniform mat4 cc_matViewProjLight;\n uniform vec4 cc_shadowParam1;\n uniform vec4 cc_shadowParam2;\n uniform mat4 cc_matWorld;\n uniform mat4 cc_matWorldIT;\n#if USE_TEXTURE\n attribute vec2 a_texCoord1;\n uniform vec2 mainTiling;\n uniform vec2 mainOffset;\n varying vec2 uv0;\n#endif\n#if CC_USE_SKINNING\n \nattribute vec4 a_weights;\nattribute vec4 a_joints;\n uniform mat4 cc_matJoint;\n uniform vec4 cc_jointsTextureSize;\n#if CC_USE_JOINTS_TEXTURE\nuniform sampler2D cc_jointsTexture;\nmat4 getBoneMatrix(const in float i) {\n float size = cc_jointsTextureSize.x;\n float j = i * 4.0;\n float x = mod(j, size);\n float y = floor(j / size);\n float dx = 1.0 / size;\n float dy = 1.0 / size;\n y = dy * (y + 0.5);\n vec4 v1 = texture2D(cc_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture2D(cc_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture2D(cc_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture2D(cc_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\n#else\nmat4 getBoneMatrix(const in float i) {\n return cc_matJoint[int(i)];\n}\n#endif\nmat4 skinMatrix() {\n return\n getBoneMatrix(a_joints.x) * a_weights.x +\n getBoneMatrix(a_joints.y) * a_weights.y +\n getBoneMatrix(a_joints.z) * a_weights.z +\n getBoneMatrix(a_joints.w) * a_weights.w;\n}\nvoid skinVertex(inout vec4 a1) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2, inout vec4 a3) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n a3 = m * a3;\n}\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n #if CC_USE_SKINNING\n skinVertex(pos);\n #endif\n pos = cc_matViewProj * cc_matWorld * pos;\n #if USE_TEXTURE\n uv0 = a_texCoord1 * mainTiling + mainOffset;\n #endif\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n",
"frag": "\n#if USE_TEXTURE\n uniform sampler2D mainTexture;\n varying vec2 uv0;\n#endif\n#if USE_COLOR\n uniform vec4 color;\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= texture2D(mainTexture, uv0);\n #endif\n #if USE_COLOR\n o *= color;\n #endif\n return o;\n}\nvoid main() { gl_FragColor = frag(); }\n",
"defines": [
{"name": "USE_TEXTURE", "type": "boolean", "defines": []},
@@ -14,53 +52,19 @@ export default [
{"name": "CC_USE_JOINTS_TEXTURE", "type": "boolean", "defines": ["CC_USE_SKINNING"]},
{"name": "USE_COLOR", "type": "boolean", "defines": []}
],
"uniforms": [
{"name": "TexCoords", "type": 0, "bindingType": 1, "defines": ["USE_TEXTURE"], "binding": 0, "members": [
{"name": "mainTiling", "type": 14},
{"name": "mainOffset", "type": 14}
"blocks": [
{"name": "TexCoords", "defines": ["USE_TEXTURE"], "binding": 0, "size": 16, "members": [
{"name": "mainTiling", "type": 14, "count": 1},
{"name": "mainOffset", "type": 14, "count": 1}
]},
{"name": "mainTexture", "type": 29, "bindingType": 2, "defines": ["USE_TEXTURE"], "binding": 1},
{"name": "Constant", "type": 0, "bindingType": 1, "defines": ["USE_COLOR"], "binding": 2, "members": [
{"name": "color", "type": 16}
{"name": "Constant", "defines": ["USE_COLOR"], "binding": 1, "size": 16, "members": [
{"name": "color", "type": 16, "count": 1}
]}
],
"extensions": []
}
]
},
{
"name": "builtin-effect-skybox",
"techniques": [{"queue": 0, "lod": 200, "passes": [{"rasterizerState": {"cullMode": 0}, "depthStencilState": {"depthTest": false, "depthWrite": false}, "program": "e4ea21ace566a0976909c9b0d082bf97c4a115f78bafe08d6c5edec7"}], "priority": -1000}],
"properties": {"cubeMap": {"type": 32, "value": null}},
"shaders": [
{
"name": "e4ea21ace566a0976909c9b0d082bf97c4a115f78bafe08d6c5edec7",
"vert": "\n attribute vec3 a_position;\n \n uniform mat4 cc_matProj;\n uniform mat4 cc_matProjInv;\n uniform mat4 cc_matView;\n uniform mat4 cc_matViewInv;\n uniform mat4 cc_matViewProj;\n uniform mat4 cc_matViewProjInv;\n uniform vec4 cc_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection[4];\n uniform vec4 cc_dirLightColor[4];\n uniform vec4 cc_pointLightPositionAndRange[4];\n uniform vec4 cc_pointLightColor[4];\n uniform vec4 cc_spotLightPositionAndRange[4];\n uniform vec4 cc_spotLightDirection[4];\n uniform vec4 cc_spotLightColor[4];\n uniform mat4 cc_matViewProjLight;\n uniform vec4 cc_shadowParam1;\n uniform vec4 cc_shadowParam2;\n varying vec3 viewDir;\n void main() {\n mat4 rotView = mat4(mat3(cc_matView));\n vec4 clipPos = cc_matProj * rotView * vec4(a_position, 1.0);\n gl_Position = clipPos.xyww;\n viewDir = a_position;\n }\n",
"frag": "\n varying vec3 viewDir;\n uniform samplerCube cubeMap;\n \nvec3 gammaToLinearSpaceRGB(vec3 sRGB) { \n return sRGB * (sRGB * (sRGB * 0.305306011 + 0.682171111) + 0.012522878);\n}\nvec3 linearToGammaSpaceRGB(vec3 RGB) { \n vec3 S1 = sqrt(RGB);\n vec3 S2 = sqrt(S1);\n vec3 S3 = sqrt(S2);\n return 0.585122381 * S1 + 0.783140355 * S2 - 0.368262736 * S3;\n}\nvec4 gammaToLinearSpaceRGBA(vec4 sRGBA) {\n return vec4(gammaToLinearSpaceRGB(sRGBA.rgb), sRGBA.a);\n}\nvec4 linearToGammaSpaceRGBA(vec4 RGBA) {\n return vec4(linearToGammaSpaceRGB(RGBA.rgb), RGBA.a);\n}\nfloat gammaToLinearSpaceExact(float val) {\n if (val <= 0.04045) {\n return val / 12.92;\n } else if (val < 1.0) {\n return pow((val + 0.055) / 1.055, 2.4);\n } else {\n return pow(val, 2.2);\n }\n}\nfloat linearToGammaSpaceExact(float val) {\n if (val <= 0.0) {\n return 0.0;\n } else if (val <= 0.0031308) {\n return 12.92 * val;\n } else if (val < 1.0) {\n return 1.055 * pow(val, 0.4166667) - 0.055;\n } else {\n return pow(val, 0.45454545);\n }\n}\n \nvec3 unpackNormal(vec4 nmap) {\n return nmap.xyz * 2.0 - 1.0;\n}\nvec3 unpackRGBE(vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\n void main() {\n #if USE_RGBE_CUBEMAP\n vec3 c = unpackRGBE(textureCube(cubeMap, viewDir));\n c = linearToGammaSpaceRGB(c / (1.0 + c));\n gl_FragColor = vec4(c, 1.0);\n #else\n gl_FragColor = textureCube(cubeMap, viewDir);\n #endif\n }\n",
"defines": [
{"name": "USE_RGBE_CUBEMAP", "type": "boolean", "defines": []}
"samplers": [
{"name": "mainTexture", "type": 29, "count": 1, "defines": ["USE_TEXTURE"], "binding": 2}
],
"uniforms": [
{"name": "cubeMap", "type": 32, "bindingType": 2, "defines": [], "binding": 0}
],
"extensions": []
}
]
},
{
"name": "builtin-effect-sprite",
"techniques": [{"queue": 2, "passes": [{"depthStencilState": {"depthTest": true, "depthWrite": false}, "blendState": {"targets": [{"blend": true, "blendSrc": 2, "blendDst": 4, "blendDstAlpha": 4}]}, "program": "b28a508b291d9314faba527c0f13b99420d5feebd86bd4d38554b256"}], "priority": 0}],
"properties": {"mainTexture": {"type": 29, "value": null}},
"shaders": [
{
"name": "b28a508b291d9314faba527c0f13b99420d5feebd86bd4d38554b256",
"vert": "\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\n uniform mat4 cc_matProj;\n uniform mat4 cc_matProjInv;\n uniform mat4 cc_matView;\n uniform mat4 cc_matViewInv;\n uniform mat4 cc_matViewProj;\n uniform mat4 cc_matViewProjInv;\n uniform vec4 cc_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection[4];\n uniform vec4 cc_dirLightColor[4];\n uniform vec4 cc_pointLightPositionAndRange[4];\n uniform vec4 cc_pointLightColor[4];\n uniform vec4 cc_spotLightPositionAndRange[4];\n uniform vec4 cc_spotLightDirection[4];\n uniform vec4 cc_spotLightColor[4];\n uniform mat4 cc_matViewProjLight;\n uniform vec4 cc_shadowParam1;\n uniform vec4 cc_shadowParam2;\n uniform mat4 cc_matWorld;\n uniform mat4 cc_matWorldIT;\nvarying vec2 uv0;\nvarying vec4 color;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matViewProj * cc_matWorld * pos;\n uv0 = a_texCoord;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n",
"frag": "\nuniform sampler2D mainTexture;\nvarying vec2 uv0;\nvarying vec4 color;\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n o *= texture2D(mainTexture, uv0);\n o *= color;\n return o;\n}\nvoid main() { gl_FragColor = frag(); }\n",
"defines": [],
"uniforms": [
{"name": "mainTexture", "type": 29, "bindingType": 2, "defines": [], "binding": 0}
],
"extensions": []
"dependencies": {}
}
]
},
+1 -1
View File
@@ -22,7 +22,7 @@ export class GFXUniformBlock {
binding: number = -1;
name: string = "";
//instance : string;
uniforms: GFXUniform[] = [];
members: GFXUniform[] = [];
};
export class GFXUniformSampler {
+3 -3
View File
@@ -897,15 +897,15 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG
binding: block.binding,
name: block.name,
size: 0,
glUniforms: new Array<WebGLGPUUniform>(block.uniforms.length),
glUniforms: new Array<WebGLGPUUniform>(block.members.length),
isUniformPackage: true,
buffer: null,
};
gpuShader.glBlocks[i] = glBlock;
for (let u = 0; u < block.uniforms.length; ++u) {
let uniform = block.uniforms[u];
for (let u = 0; u < block.members.length; ++u) {
let uniform = block.members[u];
let glType = GFXTypeToWebGLType(uniform.type);
let stride = WebGLGetTypeSize(glType);
let size = stride * uniform.count;
+2 -2
View File
@@ -90,11 +90,11 @@ export class TestStage extends RenderStage {
name: "test",
stages: [vsStage, fsStage],
blocks: [{
binding: 0, name: "Global", uniforms: [
binding: 0, name: "Global", members: [
{ name: "u_matWorldViewProj", type: GFXType.MAT4, count: 1 },
]
}, {
binding: 5, name: "UBO", uniforms: [
binding: 5, name: "UBO", members: [
{ name: "u_color", type: GFXType.FLOAT4, count: 1 },
]
}],
+32 -17
View File
@@ -1,12 +1,13 @@
// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
import { EffectAsset, PropertyInfo, ShaderInfo, UniformInfo } from '../../3d/assets/effect-asset';
import { EffectAsset, PropertyInfo, ShaderInfo } from '../../3d/assets/effect-asset';
import { CCObject } from '../../core/data';
import { Color, Mat4, Vec2, Vec3, Vec4 } from '../../core/value-types';
import { GFXType } from '../../gfx/define';
import Texture2D from '../gfx/texture-2d';
import TextureCube from '../gfx/texture-cube';
import { Pass } from './pass';
import { PassStage } from './constants';
import { Pass, PassInfo } from './pass';
import Technique from './technique';
const _typeMap = {
@@ -37,6 +38,10 @@ const typeCheck = (value: any, type: number) => {
}
};
const createPass = () => {
};
let _globalTechLod = 600;
type PropValue = number | boolean | Vec2 | Vec3 | Vec4 | Color | Mat4 | Texture2D | TextureCube | null;
@@ -47,7 +52,7 @@ interface DependencyMap { [name: string]: string; }
interface ProgramMap { [name: string]: ShaderInfo; }
class Effect {
public static parseEffect(effect: EffectAsset, programs: ProgramMap) { return new Effect(); }
public static parseEffect(effect: EffectAsset, defines: DefineMap) { return new Effect(); }
public static parseForInspector(effect: EffectAsset) { return { props: {}, defines: {} }; }
public static setGlobalLod(lod: number) { _globalTechLod = lod; }
@@ -161,8 +166,8 @@ class Effect {
this._defines[def.name] = def.type === 'number' ? 0 : false));
// extensions
this._dependencies = {};
this._techniques[this._activeTechIdx].passes.forEach((pass) => this._programs[pass.programName].extensions
.filter((ext) => ext.define).forEach((ext) => this._dependencies[ext.define] = ext.name));
this._techniques[this._activeTechIdx].passes.forEach((pass) =>
Object.assign(this._dependencies, this._programs[pass.programName].dependencies));
}
}
@@ -206,6 +211,7 @@ interface ExtractedPropInfo {
displayName?: string;
}
const parseProperties = (() => {
interface UniformInfo { type: number; defines: string[]; }
function genPropInfo(propInfo: PropertyInfo, uniformInfo: UniformInfo): ExtractedPropInfo {
const type = propInfo.type || uniformInfo.type;
return {
@@ -216,6 +222,13 @@ const parseProperties = (() => {
defines: uniformInfo.defines,
};
}
function findUniformInfo(program: ShaderInfo, name: string) {
for (const b of program.blocks) {
const i = b.members.find((u) => u.name === name);
if (i) { return Object.assign({ defines: b.defines }, i); }
}
return program.samplers.find((u) => u.name === name);
}
return (effect: EffectAsset, programs: ProgramMap) => {
const props: { [name: string]: ExtractedPropInfo } = {};
for (const prop of Object.keys(effect.properties)) {
@@ -223,11 +236,11 @@ const parseProperties = (() => {
let uniformInfo: UniformInfo | undefined;
// always try getting the type from shaders first
if (propInfo.tech !== undefined && propInfo.pass !== undefined) {
const pname = effect.techniques[propInfo.tech].passes[propInfo.pass].program;
uniformInfo = programs[pname].uniforms.find((u) => u.name === prop);
const p = effect.techniques[propInfo.tech].passes[propInfo.pass].program;
uniformInfo = findUniformInfo(programs[p], prop);
} else {
for (const p of Object.keys(programs)) {
uniformInfo = programs[p].uniforms.find((u) => u.name === prop);
uniformInfo = findUniformInfo(programs[p], prop);
if (uniformInfo) { break; }
}
}
@@ -243,7 +256,7 @@ const parseProperties = (() => {
};
})();
Effect.parseEffect = (effect: EffectAsset) => {
Effect.parseEffect = (effect: EffectAsset, defines: DefineMap) => {
// techniques
const techNum = effect.techniques.length;
const techniques = new Array<Technique>(techNum);
@@ -253,12 +266,14 @@ Effect.parseEffect = (effect: EffectAsset) => {
const passNum = tech.passes.length;
const passes: Pass[] = new Array(passNum);
for (let k = 0; k < passNum; ++k) {
const passInfo = tech.passes[k];
passInfo.device = cc.game._gfxDevice;
passInfo.bindingLayoutInfo = programs[passInfo.program].uniforms.map((u) => {
return { name: u.name, type: u.bindingType, binding: u.binding };
});
passes[k] = Pass.create(passInfo);
const passInfo = <PassInfo>tech.passes[k];
passInfo.shader = cc.game._programLib.getGFXShader(passInfo.program, defines);
passInfo.renderPass = cc.director.root.pipeline.getRenderPass(passInfo.stage || PassStage.DEFAULT);
passInfo.blocks = programs[passInfo.program].blocks;
passInfo.samplers = programs[passInfo.program].samplers;
const pass = new Pass(cc.game._gfxDevice);
pass.initialize(passInfo);
passes[k] = pass;
}
techniques[j] = new Technique(tech.queue, tech.priority, tech.lod, passes);
}
@@ -266,13 +281,13 @@ Effect.parseEffect = (effect: EffectAsset) => {
const props = parseProperties(effect, programs);
const uniforms = {};
for (const pn of Object.keys(programs)) {
programs[pn].uniforms.forEach((u) => {
programs[pn].blocks.forEach((b) => b.members.forEach((u) => {
const prop = props[u.name];
uniforms[u.name] = {
type: prop ? prop.type : u.type,
value: prop ? prop.value : getInstanceCtor(u.type)(),
};
});
}));
}
return new Effect(effect.name, techniques, programs, uniforms);
+81 -32
View File
@@ -1,18 +1,19 @@
// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
import { GFXBinding } from '../../gfx/binding-layout';
import { BlockInfo, SamplerInfo } from '../../3d/assets/effect-asset';
import { GFXBindingLayout } from '../../gfx/binding-layout';
import { GFXBuffer } from '../../gfx/buffer';
import { GFXPrimitiveMode } from '../../gfx/define';
import { GFXBindingType, GFXBufferUsageBit, GFXMemoryUsageBit, GFXPrimitiveMode } from '../../gfx/define';
import { GFXDevice } from '../../gfx/device';
import { GFXPipelineLayout } from '../../gfx/pipeline-layout';
import { GFXBlendState, GFXBlendTarget, GFXDepthStencilState,
GFXInputState, GFXPipelineState, GFXRasterizerState } from '../../gfx/pipeline-state';
import { GFXRenderPass } from '../../gfx/render-pass';
import { GFXSampler } from '../../gfx/sampler';
import { GFXShader } from '../../gfx/shader';
import { PassStage } from './constants';
export interface PassInfo {
// generated part
device: GFXDevice;
bindingLayoutInfo: GFXBinding[];
export interface PassInfoBase {
program: string;
// effect-writer part
primitive?: GFXPrimitiveMode;
@@ -21,23 +22,43 @@ export interface PassInfo {
depthStencilState?: GFXDepthStencilState;
blendState?: GFXBlendState;
}
export interface PassInfo extends PassInfoBase {
// generated part
blocks: BlockInfo[];
samplers: SamplerInfo[];
shader: GFXShader;
renderPass: GFXRenderPass;
}
export class Pass {
public static create(info: PassInfo) {
const pass = new Pass();
const device = pass._device = info.device;
pass._programName = info.program;
pass._stage = info.stage || PassStage.DEFAULT;
protected _device: GFXDevice;
protected _programName: string = '';
protected _stage: PassStage = PassStage.DEFAULT;
protected _pipelineState: GFXPipelineState | null = null;
protected _pipelineLayout: GFXPipelineLayout | null = null;
protected _bindingLayout: GFXBindingLayout | null = null;
protected _buffers: GFXBuffer[] = [];
protected _samplers: GFXSampler[] = [];
public constructor(device: GFXDevice) {
this._device = device;
}
public initialize(info: PassInfo) {
const device = this._device;
this._programName = info.program;
this._stage = info.stage || PassStage.DEFAULT;
// pipeline state
const shader = device.createShader({ name: info.program, stages: [] });
if (!shader) { console.error('create shader failed'); return pass; }
const bindingLayout = device.createBindingLayout({ bindings: info.bindingLayoutInfo });
if (!bindingLayout) { console.error('create binding layout failed'); return pass; }
const layout = device.createPipelineLayout({ layouts: [bindingLayout] });
if (!layout) { console.error('create pipeline layout failed'); return pass; }
const renderPass = cc.director.root.pipeline.getRenderPass(pass._stage);
if (!renderPass) { console.error('create render pass failed'); return pass; }
const bindings = info.blocks.map((u) =>
({ name: u.name, binding: u.binding, type: GFXBindingType.UNIFORM_BUFFER })
).concat(info.samplers.map((u) =>
({ name: u.name, binding: u.binding, type: GFXBindingType.SAMPLER })
));
this._bindingLayout = device.createBindingLayout({ bindings });
if (!this._bindingLayout) { console.error('create binding layout failed'); return; }
this._pipelineLayout = device.createPipelineLayout({ layouts: [this._bindingLayout] });
if (!this._pipelineLayout) { console.error('create pipeline layout failed'); return; }
const bs = new GFXBlendState();
if (info.blendState) {
const bsInfo = Object.assign({}, info.blendState);
@@ -48,24 +69,52 @@ export class Pass {
delete bsInfo.targets;
Object.assign(bs, bsInfo);
}
pass._pipelineState = device.createPipelineState({
this._pipelineState = device.createPipelineState({
primitive: info.primitive || GFXPrimitiveMode.TRIANGLE_LIST,
rs: Object.assign(new GFXRasterizerState(), info.rasterizerState),
dss: Object.assign(new GFXDepthStencilState(), info.rasterizerState),
dss: Object.assign(new GFXDepthStencilState(), info.depthStencilState),
is: new GFXInputState(), bs,
shader, layout, renderPass,
shader: info.shader,
layout: this._pipelineLayout,
renderPass: info.renderPass,
});
return pass;
for (const u of info.blocks) {
const buffer = device.createBuffer({
usage: GFXBufferUsageBit.UNIFORM,
memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE,
size: u.size,
stride: 1, // N/A for blocks
});
if (buffer) {
this._bindingLayout.bindBuffer(u.binding, buffer);
this._buffers.push(buffer);
} else {
console.error('create buffer failed.');
}
}
for (const u of info.samplers) {
const sampler = device.createSampler({
name: u.name,
// TODO: specify filter modes in effect
});
if (sampler) {
this._bindingLayout.bindSampler(u.binding, sampler);
this._samplers.push(sampler);
} else {
console.error('create sampler failed.');
}
}
}
public destroy() {
if (this._buffers) { this._buffers.forEach((b) => b.destroy()); this._buffers.length = 0; }
if (this._samplers) { this._samplers.forEach((b) => b.destroy()); this._samplers.length = 0; }
if (this._bindingLayout) { this._bindingLayout.destroy(); this._bindingLayout = null; }
if (this._pipelineLayout) { this._pipelineLayout.destroy(); this._pipelineLayout = null; }
if (this._pipelineState) { this._pipelineState.destroy(); this._pipelineState = null; }
}
get programName() { return this._programName; }
get pipelineState(): GFXPipelineState { return <GFXPipelineState>this._pipelineState; }
protected _device: GFXDevice | null = null;
protected _programName: string = '';
protected _stage: PassStage = PassStage.DEFAULT;
protected _pipelineState: GFXPipelineState | null = null;
protected _buffers: GFXBuffer[] = [];
protected _samplers: GFXSampler[] = [];
get pipelineState() { return this._pipelineState; }
}
+22 -62
View File
@@ -1,56 +1,24 @@
// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
import gfx from '../gfx';
import { GFXShaderType } from '../../gfx/define';
let _shdID = 0;
function _generateDefines(device, defs, deps) {
function _generateDefines(device, defs, tDefs, deps) {
let defines = [];
for (let def in defs) {
let d = defs[def];
let result = typeof d === 'number' ? d : d ? 1 : 0;
for (const { name, type } of tDefs) {
let d = defs[name];
let result = (type === 'number') ? (d || 0) : (d ? 1 : 0);
// fallback if extension dependency not supported
if (result && deps[def] && !device[deps[def]]) {
console.warn(`${deps[def]} not supported on this platform, disabled ${def}`);
if (result && deps[name] && !device[deps[name]]) {
console.warn(`${deps[name]} not supported on this platform, disabled ${name}`);
result = 0;
}
defines.push(`#define ${def} ${result}`);
defines.push(`#define ${name} ${result}`);
}
return defines.join('\n');
}
function _replaceMacroNums(string, defs) {
let cache = {};
let tmp = string;
for (let def in defs) {
if (Number.isInteger(defs[def])) {
cache[def] = defs[def];
}
}
for (let def in cache) {
let reg = new RegExp(def, 'g');
tmp = tmp.replace(reg, cache[def]);
}
return tmp;
}
function _unrollLoops(string) {
let pattern = /#pragma for (\w+) in range\(\s*(\d+)\s*,\s*(\d+)\s*\)([\s\S]+?)#pragma endFor/g;
function replace(match, index, begin, end, snippet) {
let unroll = '';
let parsedBegin = parseInt(begin);
let parsedEnd = parseInt(end);
if (parsedBegin.isNaN || parsedEnd.isNaN) {
console.error('Unroll For Loops Error: begin and end of range must be an int num.');
}
for (let i = parsedBegin; i < parsedEnd; ++i) {
unroll += snippet.replace(new RegExp(`{${index}}`, 'g'), i);
}
return unroll;
}
return string.replace(pattern, replace);
}
export default class ProgramLib {
/**
* @param {gfx.Device} device
@@ -79,9 +47,8 @@ export default class ProgramLib {
* { name: 'shadow', type: 'boolean' },
* { name: 'lightCount', type: 'number', min: 1, max: 4 }
* ],
* attributes: [{ name: 'a_position', type: 'vec3' }],
* uniforms: [{ name: 'color', type: 'vec4' }],
* extensions: [{ name: 'GL_OES_standard_derivatives', defines: ['USE_NORMAL_TEXTURE'] }],
* blocks: [{ name: 'Constants', binding: 0, size: 16, members: [{ name: 'color', type: 'vec4' }], defines: [] }],
* dependencies: { 'USE_NORMAL_TEXTURE': 'OES_standard_derivatives' },
* };
* programLib.define(program);
*/
@@ -158,12 +125,7 @@ export default class ProgramLib {
return key << 8 | (tmpl.id & 0xff);
}
/**
* @param {string} name
* @param {Object} defines
* @param {Object} extensions
*/
getProgram(name, defines, extensions, effectName) {
getGFXShader(name, defines = {}) {
let key = this.getKey(name, defines);
let program = this._cache[key];
if (program) {
@@ -172,22 +134,20 @@ export default class ProgramLib {
// get template
let tmpl = this._templates[name];
let customDef = _generateDefines(this._device, defines, extensions) + '\n';
let vert = _replaceMacroNums(tmpl.vert, defines);
vert = customDef + _unrollLoops(vert);
let frag = _replaceMacroNums(tmpl.frag, defines);
frag = customDef + _unrollLoops(frag);
let customDef = _generateDefines(this._device, defines, tmpl.defines, tmpl.dependencies) + '\n';
let vert = customDef + tmpl.vert;
let frag = customDef + tmpl.frag;
program = new gfx.Program(this._device, {
vert,
frag
program = this._device.createShader({
name,
blocks: tmpl.blocks,
samplers: tmpl.samplers,
stages: [
{ type: GFXShaderType.VERTEX, source: vert },
{ type: GFXShaderType.FRAGMENT, source: frag },
],
});
program.link();
if (!program._linked) {
console.warn(`Failed to link program from effect ${effectName}.`);
}
this._cache[key] = program;
return program;
}
}