‘pre-mature EOF‘ : syntax error syntax error [How to Solve]

1. Version

cocos3.4

2. Defects of stringify

Customized a fragment shader, mimicking the official method, using STRINGIFY to convert the code to strings. Run it and report an error

cocos2d: ERROR: Failed to compile shader: uniform mat4 CC_PMatrix;
uniform mat4 CC_MVMatrix; uniform mat4 CC_MVPMatrix; uniform mat3
CC_NormalMatrix; uniform vec4 CC_Time; uniform vec4 CC_SinTime;
uniform vec4 CC_CosTime; uniform vec4 CC_Random01; uniform sampler2D
CC_Texture0; uniform sampler2D CC_Texture1; uniform sampler2D
CC_Texture2; uniform sampler2D CC_Texture3; //CC INCLUDES END

varying vec4 v_fragmentColor; varying vec2 v_texCoord; uniform float
outlineSize; uniform vec3 outlineColor; uniform vec2 textureSize;
uniform vec3 foregroundColor; const float cosArray[12] = { 1 cocos2d:
ERROR: 0:? : ‘pre-mature EOF’ : syntax error syntax error

The following is the reason for my guess error:
the problem lies in the initialization statement of floating-point array. Stringify is a macro definition function, which is defined as:

#define STRINGIFY(A) #A

Here a # syntax of macro definition is used to convert A into a string. When A contains a ‘,’ character, A is truncated and incomplete. For example, STRINGIFY (int a,b) expects the string to be “int a,b”, but in fact it will be “int a”. In fact, STRINGIFY is expanded with two arguments, the first being int a and the second being b.

3. Solutions

3.1. Add ()

Call STRINGIFY with brackets in the argument: STRINGIFY((AB)). However, the string obtained this way will also be bracketed and needs to be unbracketed, which is more troublesome

3.2. Write directly as a string

For example:

GLchar my_vert[] = "\
attribute vec4 a_position;\n\
attribute vec2 a_texCoord;\n\
attribute vec4 a_color;\n\
\n\
#ifdef GL_ES    \n\
varying lowp vec4 v_fragmentColor;   \n\
varying mediump vec2 v_texCoord;   \n\
#else  \n\
varying vec4 v_fragmentColor;\n\
varying vec2 v_texCoord;  \n\
#endif  \n\
\n\
void main()  \n\
{  \n\
	gl_Position = CC_PMatrix * a_position;  \n\
	v_fragmentColor = a_color;  \n\
	v_texCoord = a_texCoord;  \n\
}";

It’s also troublesome. You need to add \n\ to each line.

3.3. Write the code into a file

For example:

#ifdef GL_ES
precision lowp float;
#endif

varying vec4 v_fragmentColor;
varying vec2 v_texCoord;

void main()
{
	float ff=1;
	gl_FragColor = texture2D(CC_Texture0, v_texCoord);
	float f=(gl_FragColor.r+gl_FragColor.g+gl_FragColor.b)/3.0f; 
	gl_FragColor=vec4(f,f,f,gl_FragColor.a);
}

Save the above code as ccShader_PositionTextureColor_noMVP_Gray.fsh file. Then use

std::string fragmentSource=FileUtils::getInstance()->getStringFromFile(FileUtils::getInstance()->fullPathForFilename("shaders/ccShader_PositionTextureColor_noMVP_Gray.fsh"));

Direct reading.

Read More: