示例#1
0
// prim so we can special case for RECTANGLES :(
void ComputeVertexShaderID(VertexShaderID *id, u32 vertType, int prim, bool useHWTransform) {
	bool doTexture = gstate.isTextureMapEnabled() && !gstate.isModeClear();
	bool doTextureProjection = gstate.getUVGenMode() == GE_TEXMAP_TEXTURE_MATRIX;
	bool doShadeMapping = gstate.getUVGenMode() == GE_TEXMAP_ENVIRONMENT_MAP;

	bool hasColor = (vertType & GE_VTYPE_COL_MASK) != 0;
	bool hasNormal = (vertType & GE_VTYPE_NRM_MASK) != 0;
	bool hasTexcoord = (vertType & GE_VTYPE_TC_MASK) != 0;
	bool enableFog = gstate.isFogEnabled() && !gstate.isModeThrough() && !gstate.isModeClear();
	bool lmode = gstate.isUsingSecondaryColor() && gstate.isLightingEnabled();

	memset(id->d, 0, sizeof(id->d));
	id->d[0] = lmode & 1;
	id->d[0] |= ((int)gstate.isModeThrough()) << 1;
	id->d[0] |= ((int)enableFog) << 2;
	id->d[0] |= (doTexture & 1) << 3;
	id->d[0] |= (hasColor & 1) << 4;
	if (doTexture) {
		id->d[0] |= (gstate_c.flipTexture & 1) << 5;
		id->d[0] |= (doTextureProjection & 1) << 6;
	}

	if (useHWTransform) {
		id->d[0] |= 1 << 8;
		id->d[0] |= (hasNormal & 1) << 9;

		// UV generation mode
		id->d[0] |= gstate.getUVGenMode() << 16;

		// The next bits are used differently depending on UVgen mode
		if (doTextureProjection) {
			id->d[0] |= gstate.getUVProjMode() << 18;
		} else if (doShadeMapping) {
			id->d[0] |= gstate.getUVLS0() << 18;
			id->d[0] |= gstate.getUVLS1() << 20;
		}

		// Bones
		if (vertTypeIsSkinningEnabled(vertType))
			id->d[0] |= (TranslateNumBones(vertTypeGetNumBoneWeights(vertType)) - 1) << 22;

		// Okay, d[1] coming up. ==============

		if (gstate.isLightingEnabled() || doShadeMapping) {
			// Light bits
			for (int i = 0; i < 4; i++) {
				id->d[1] |= gstate.getLightComputation(i) << (i * 4);
				id->d[1] |= gstate.getLightType(i) << (i * 4 + 2);
			}
			id->d[1] |= (gstate.materialupdate & 7) << 16;
			for (int i = 0; i < 4; i++) {
				id->d[1] |= (gstate.isLightChanEnabled(i) & 1) << (20 + i);
			}
		}
		id->d[1] |= gstate.isLightingEnabled() << 24;
		id->d[1] |= (vertTypeGetWeightMask(vertType) >> GE_VTYPE_WEIGHT_SHIFT) << 25;
		id->d[1] |= gstate.areNormalsReversed() << 26;
		if (doTextureProjection && gstate.getUVProjMode() == GE_PROJMAP_UV) {
			id->d[1] |= ((vertType & GE_VTYPE_TC_MASK) >> GE_VTYPE_TC_SHIFT) << 27;  // two bits
		} else {
示例#2
0
void GenerateVertexShader(int prim, u32 vertType, char *buffer, bool useHWTransform) {
	char *p = buffer;

// #define USE_FOR_LOOP

#if defined(USING_GLES2)
	WRITE(p, "#version 100\n");  // GLSL ES 1.0
	WRITE(p, "precision highp float;\n");

#elif !defined(FORCE_OPENGL_2_0)
	WRITE(p, "#version 110\n");
	// Remove lowp/mediump in non-mobile implementations
	WRITE(p, "#define lowp\n");
	WRITE(p, "#define mediump\n");
	WRITE(p, "#define highp\n");
#else
	// Need to remove lowp/mediump for Mac
	WRITE(p, "#define lowp\n");
	WRITE(p, "#define mediump\n");
	WRITE(p, "#define highp\n");
#endif

	int lmode = gstate.isUsingSecondaryColor() && gstate.isLightingEnabled();
	int doTexture = gstate.isTextureMapEnabled() && !gstate.isModeClear();
	bool doTextureProjection = gstate.getUVGenMode() == GE_TEXMAP_TEXTURE_MATRIX;
	bool doShadeMapping = gstate.getUVGenMode() == GE_TEXMAP_ENVIRONMENT_MAP;

	bool hasColor = (vertType & GE_VTYPE_COL_MASK) != 0 || !useHWTransform;
	bool hasNormal = (vertType & GE_VTYPE_NRM_MASK) != 0 && useHWTransform;
	bool enableFog = gstate.isFogEnabled() && !gstate.isModeThrough() && !gstate.isModeClear();
	bool throughmode = (vertType & GE_VTYPE_THROUGH_MASK) != 0;
	bool flipV = gstate_c.flipTexture;  // This also means that we are texturing from a render target
	bool flipNormal = gstate.areNormalsReversed();

	DoLightComputation doLight[4] = {LIGHT_OFF, LIGHT_OFF, LIGHT_OFF, LIGHT_OFF};
	if (useHWTransform) {
		int shadeLight0 = doShadeMapping ? gstate.getUVLS0() : -1;
		int shadeLight1 = doShadeMapping ? gstate.getUVLS1() : -1;
		for (int i = 0; i < 4; i++) {
			if (i == shadeLight0 || i == shadeLight1)
				doLight[i] = LIGHT_SHADE;
			if (gstate.isLightingEnabled() && gstate.isLightChanEnabled(i))
				doLight[i] = LIGHT_FULL;
		}
	}

	if (vertTypeIsSkinningEnabled(vertType)) {
		WRITE(p, "%s", boneWeightAttrDecl[TranslateNumBones(vertTypeGetNumBoneWeights(vertType))]);
	}

	if (useHWTransform)
		WRITE(p, "attribute vec3 position;\n");
	else
		WRITE(p, "attribute vec4 position;\n");  // need to pass the fog coord in w

	if (useHWTransform && hasNormal)
		WRITE(p, "attribute mediump vec3 normal;\n");

	if (doTexture) {
		if (!useHWTransform && doTextureProjection)
			WRITE(p, "attribute vec3 texcoord;\n");
		else
			WRITE(p, "attribute vec2 texcoord;\n");
	}
	if (hasColor) {
		WRITE(p, "attribute lowp vec4 color0;\n");
		if (lmode && !useHWTransform)  // only software transform supplies color1 as vertex data
			WRITE(p, "attribute lowp vec3 color1;\n");
	}

	if (gstate.isModeThrough())	{
		WRITE(p, "uniform mat4 u_proj_through;\n");
	} else {
		WRITE(p, "uniform mat4 u_proj;\n");
		// Add all the uniforms we'll need to transform properly.
	}

	bool prescale = g_Config.bPrescaleUV && !throughmode && gstate.getTextureFunction() == 0;

	if (useHWTransform) {
		// When transforming by hardware, we need a great deal more uniforms...
		WRITE(p, "uniform mat4 u_world;\n");
		WRITE(p, "uniform mat4 u_view;\n");
		if (doTextureProjection)
			WRITE(p, "uniform mediump mat4 u_texmtx;\n");
		if (vertTypeIsSkinningEnabled(vertType)) {
			int numBones = TranslateNumBones(vertTypeGetNumBoneWeights(vertType));
#ifdef USE_BONE_ARRAY
			WRITE(p, "uniform mediump mat4 u_bone[%i];\n", numBones);
#else
			for (int i = 0; i < numBones; i++) {
				WRITE(p, "uniform mat4 u_bone%i;\n", i);
			}
#endif
		}
		if (doTexture && (flipV || !prescale || gstate.getUVGenMode() == GE_TEXMAP_ENVIRONMENT_MAP || gstate.getUVGenMode() == GE_TEXMAP_TEXTURE_MATRIX)) {
			WRITE(p, "uniform vec4 u_uvscaleoffset;\n");
		}
		for (int i = 0; i < 4; i++) {
			if (doLight[i] != LIGHT_OFF) {
				// This is needed for shade mapping
				WRITE(p, "uniform vec3 u_lightpos%i;\n", i);
			}
			if (doLight[i] == LIGHT_FULL) {
				GELightType type = gstate.getLightType(i);

				if (type != GE_LIGHTTYPE_DIRECTIONAL)
					WRITE(p, "uniform mediump vec3 u_lightatt%i;\n", i);

				if (type == GE_LIGHTTYPE_SPOT || type == GE_LIGHTTYPE_UNKNOWN) { 
					WRITE(p, "uniform mediump vec3 u_lightdir%i;\n", i);
					WRITE(p, "uniform mediump float u_lightangle%i;\n", i);
					WRITE(p, "uniform mediump float u_lightspotCoef%i;\n", i);
				}
				WRITE(p, "uniform lowp vec3 u_lightambient%i;\n", i);
				WRITE(p, "uniform lowp vec3 u_lightdiffuse%i;\n", i);

				if (gstate.isUsingSpecularLight(i))
					WRITE(p, "uniform lowp vec3 u_lightspecular%i;\n", i);
			}
		}
		if (gstate.isLightingEnabled()) {
			WRITE(p, "uniform lowp vec4 u_ambient;\n");
			if ((gstate.materialupdate & 2) == 0)
				WRITE(p, "uniform lowp vec3 u_matdiffuse;\n");
			// if ((gstate.materialupdate & 4) == 0)
			WRITE(p, "uniform lowp vec4 u_matspecular;\n");  // Specular coef is contained in alpha
			WRITE(p, "uniform lowp vec3 u_matemissive;\n");
		}
	}

	if (useHWTransform || !hasColor)
		WRITE(p, "uniform lowp vec4 u_matambientalpha;\n");  // matambient + matalpha

	if (enableFog) {
		WRITE(p, "uniform highp vec2 u_fogcoef;\n");
	}

	WRITE(p, "varying lowp vec4 v_color0;\n");
	if (lmode) WRITE(p, "varying lowp vec3 v_color1;\n");
	if (doTexture) {
		if (doTextureProjection)
			WRITE(p, "varying mediump vec3 v_texcoord;\n");
		else
			WRITE(p, "varying mediump vec2 v_texcoord;\n");
	}


	if (enableFog) {
		// See the fragment shader generator
		if (gl_extensions.gpuVendor == GPU_VENDOR_POWERVR) {
			WRITE(p, "varying highp float v_fogdepth;\n");
		} else {
			WRITE(p, "varying mediump float v_fogdepth;\n");
		}
	}

	WRITE(p, "void main() {\n");

	if (!useHWTransform) {
		// Simple pass-through of vertex data to fragment shader
		if (doTexture)
			WRITE(p, "  v_texcoord = texcoord;\n");
		if (hasColor) {
			WRITE(p, "  v_color0 = color0;\n");
			if (lmode)
				WRITE(p, "  v_color1 = color1;\n");
		} else {
			WRITE(p, "  v_color0 = u_matambientalpha;\n");
			if (lmode)
				WRITE(p, "  v_color1 = vec3(0.0);\n");
		}
		if (enableFog) {
			WRITE(p, "  v_fogdepth = position.w;\n");
		}
		if (gstate.isModeThrough())	{
			WRITE(p, "  gl_Position = u_proj_through * vec4(position.xyz, 1.0);\n");
		} else {
			WRITE(p, "  gl_Position = u_proj * vec4(position.xyz, 1.0);\n");
		}
	} else {
		// Step 1: World Transform / Skinning
		if (!vertTypeIsSkinningEnabled(vertType)) {
			// No skinning, just standard T&L.
			WRITE(p, "  vec3 worldpos = (u_world * vec4(position.xyz, 1.0)).xyz;\n");
			if (hasNormal)
				WRITE(p, "  mediump vec3 worldnormal = normalize((u_world * vec4(%snormal, 0.0)).xyz);\n", flipNormal ? "-" : "");
			else
				WRITE(p, "  mediump vec3 worldnormal = vec3(0.0, 0.0, 1.0);\n");
		} else {
			int numWeights = TranslateNumBones(vertTypeGetNumBoneWeights(vertType));

			static const char *rescale[4] = {"", " * 1.9921875", " * 1.999969482421875", ""}; // 2*127.5f/128.f, 2*32767.5f/32768.f, 1.0f};
			const char *factor = rescale[vertTypeGetWeightMask(vertType) >> GE_VTYPE_WEIGHT_SHIFT];

			static const char * const boneWeightAttr[8] = {
				"w1.x", "w1.y", "w1.z", "w1.w",
				"w2.x", "w2.y", "w2.z", "w2.w",
			};

#if defined(USE_FOR_LOOP) && defined(USE_BONE_ARRAY)

			// To loop through the weights, we unfortunately need to put them in a float array.
			// GLSL ES sucks - no way to directly initialize an array!
			switch (numWeights) {
			case 1: WRITE(p, "  float w[1]; w[0] = w1;\n"); break;
			case 2: WRITE(p, "  float w[2]; w[0] = w1.x; w[1] = w1.y;\n"); break;
			case 3: WRITE(p, "  float w[3]; w[0] = w1.x; w[1] = w1.y; w[2] = w1.z;\n"); break;
			case 4: WRITE(p, "  float w[4]; w[0] = w1.x; w[1] = w1.y; w[2] = w1.z; w[3] = w1.w;\n"); break;
			case 5: WRITE(p, "  float w[5]; w[0] = w1.x; w[1] = w1.y; w[2] = w1.z; w[3] = w1.w; w[4] = w2;\n"); break;
			case 6: WRITE(p, "  float w[6]; w[0] = w1.x; w[1] = w1.y; w[2] = w1.z; w[3] = w1.w; w[4] = w2.x; w[5] = w2.y;\n"); break;
			case 7: WRITE(p, "  float w[7]; w[0] = w1.x; w[1] = w1.y; w[2] = w1.z; w[3] = w1.w; w[4] = w2.x; w[5] = w2.y; w[6] = w2.z;\n"); break;
			case 8: WRITE(p, "  float w[8]; w[0] = w1.x; w[1] = w1.y; w[2] = w1.z; w[3] = w1.w; w[4] = w2.x; w[5] = w2.y; w[6] = w2.z; w[7] = w2.w;\n"); break;
			}

			WRITE(p, "  mat4 skinMatrix = w[0] * u_bone[0];\n");
			if (numWeights > 1) {
				WRITE(p, "  for (int i = 1; i < %i; i++) {\n", numWeights);
				WRITE(p, "    skinMatrix += w[i] * u_bone[i];\n");
				WRITE(p, "  }\n");
			}

#else

#ifdef USE_BONE_ARRAY
			if (numWeights == 1)
				WRITE(p, "  mat4 skinMatrix = w1 * u_bone[0]");
			else
				WRITE(p, "  mat4 skinMatrix = w1.x * u_bone[0]");
			for (int i = 1; i < numWeights; i++) {
				const char *weightAttr = boneWeightAttr[i];
				// workaround for "cant do .x of scalar" issue
				if (numWeights == 1 && i == 0) weightAttr = "w1";
				if (numWeights == 5 && i == 4) weightAttr = "w2";
				WRITE(p, " + %s * u_bone[%i]", weightAttr, i);
			}
#else
			// Uncomment this to screw up bone shaders to check the vertex shader software fallback
			// WRITE(p, "THIS SHOULD ERROR! #error");
			if (numWeights == 1)
				WRITE(p, "  mat4 skinMatrix = w1 * u_bone0");
			else
				WRITE(p, "  mat4 skinMatrix = w1.x * u_bone0");
			for (int i = 1; i < numWeights; i++) {
				const char *weightAttr = boneWeightAttr[i];
				// workaround for "cant do .x of scalar" issue
				if (numWeights == 1 && i == 0) weightAttr = "w1";
				if (numWeights == 5 && i == 4) weightAttr = "w2";
				WRITE(p, " + %s * u_bone%i", weightAttr, i);
			}
#endif

#endif

			WRITE(p, ";\n");

			// Trying to simplify this results in bugs in LBP...
			WRITE(p, "  vec3 skinnedpos = (skinMatrix * vec4(position, 1.0)).xyz %s;\n", factor);
			WRITE(p, "  vec3 worldpos = (u_world * vec4(skinnedpos, 1.0)).xyz;\n");

			if (hasNormal) {
				WRITE(p, "  mediump vec3 skinnednormal = (skinMatrix * vec4(%snormal, 0.0)).xyz %s;\n", flipNormal ? "-" : "", factor);
				WRITE(p, "  mediump vec3 worldnormal = normalize((u_world * vec4(skinnednormal, 0.0)).xyz);\n");
			} else {
				WRITE(p, "  mediump vec3 worldnormal = (u_world * (skinMatrix * vec4(0.0, 0.0, 1.0, 0.0))).xyz;\n");
			}
		}

		WRITE(p, "  vec4 viewPos = u_view * vec4(worldpos, 1.0);\n");

		// Final view and projection transforms.
		WRITE(p, "  gl_Position = u_proj * viewPos;\n");

		// TODO: Declare variables for dots for shade mapping if needed.

		const char *ambientStr = (gstate.materialupdate & 1) ? (hasColor ? "color0" : "u_matambientalpha") : "u_matambientalpha";
		const char *diffuseStr = (gstate.materialupdate & 2) ? (hasColor ? "color0.rgb" : "u_matambientalpha.rgb") : "u_matdiffuse";
		const char *specularStr = (gstate.materialupdate & 4) ? (hasColor ? "color0.rgb" : "u_matambientalpha.rgb") : "u_matspecular.rgb";

		bool diffuseIsZero = true;
		bool specularIsZero = true;
		bool distanceNeeded = false;

		if (gstate.isLightingEnabled()) {
			WRITE(p, "  lowp vec4 lightSum0 = u_ambient * %s + vec4(u_matemissive, 0.0);\n", ambientStr);

			for (int i = 0; i < 4; i++) {
				if (doLight[i] != LIGHT_FULL)
					continue;
				diffuseIsZero = false;
				if (gstate.isUsingSpecularLight(i))
					specularIsZero = false;
				GELightType type = gstate.getLightType(i);
				if (type != GE_LIGHTTYPE_DIRECTIONAL)
					distanceNeeded = true;
			}

			if (!specularIsZero) {
				WRITE(p, "  lowp vec3 lightSum1 = vec3(0.0);\n");
			}
			if (!diffuseIsZero) {
				WRITE(p, "  vec3 toLight;\n");
				WRITE(p, "  lowp vec3 diffuse;\n");
			}
			if (distanceNeeded) {
				WRITE(p, "  float distance;\n");
				WRITE(p, "  lowp float lightScale;\n");
			}
		}

		// Calculate lights if needed. If shade mapping is enabled, lights may need to be
		// at least partially calculated.
		for (int i = 0; i < 4; i++) {
			if (doLight[i] != LIGHT_FULL)
				continue;

			GELightType type = gstate.getLightType(i);

			if (type == GE_LIGHTTYPE_DIRECTIONAL) {
				// We prenormalize light positions for directional lights.
				WRITE(p, "  toLight = u_lightpos%i;\n", i);
			} else {
				WRITE(p, "  toLight = u_lightpos%i - worldpos;\n", i);
				WRITE(p, "  distance = length(toLight);\n");
				WRITE(p, "  toLight /= distance;\n");
			}

			bool doSpecular = gstate.isUsingSpecularLight(i);
			bool poweredDiffuse = gstate.isUsingPoweredDiffuseLight(i);

			if (poweredDiffuse) {
				WRITE(p, "  mediump float dot%i = pow(dot(toLight, worldnormal), u_matspecular.a);\n", i);
				// Ugly NaN check.  pow(0.0, 0.0) may be undefined, but PSP seems to treat it as 1.0.
				// Seen in Tales of the World: Radiant Mythology (#2424.)
				WRITE(p, "  if (!(dot%i < 1.0) && !(dot%i > 0.0))\n", i, i);
				WRITE(p, "    dot%i = 1.0;\n", i);
			} else {
				WRITE(p, "  mediump float dot%i = dot(toLight, worldnormal);\n", i);
			}

			const char *timesLightScale = " * lightScale";

			// Attenuation
			switch (type) {
			case GE_LIGHTTYPE_DIRECTIONAL:
				timesLightScale = "";
				break;
			case GE_LIGHTTYPE_POINT:
				WRITE(p, "  lightScale = clamp(1.0 / dot(u_lightatt%i, vec3(1.0, distance, distance*distance)), 0.0, 1.0);\n", i);
				break;
			case GE_LIGHTTYPE_SPOT:
			case GE_LIGHTTYPE_UNKNOWN:
				WRITE(p, "  lowp float angle%i = dot(normalize(u_lightdir%i), toLight);\n", i, i);
				WRITE(p, "  if (angle%i >= u_lightangle%i) {\n", i, i);
				WRITE(p, "    lightScale = clamp(1.0 / dot(u_lightatt%i, vec3(1.0, distance, distance*distance)), 0.0, 1.0) * pow(angle%i, u_lightspotCoef%i);\n", i, i, i);
				WRITE(p, "  } else {\n");
				WRITE(p, "    lightScale = 0.0;\n");
				WRITE(p, "  }\n");
				break;
			default:
				// ILLEGAL
				break;
			}

			WRITE(p, "  diffuse = (u_lightdiffuse%i * %s) * max(dot%i, 0.0);\n", i, diffuseStr, i);
			if (doSpecular) {
				WRITE(p, "  dot%i = dot(normalize(toLight + vec3(0.0, 0.0, 1.0)), worldnormal);\n", i);
				WRITE(p, "  if (dot%i > 0.0)\n", i);
				WRITE(p, "    lightSum1 += u_lightspecular%i * %s * (pow(dot%i, u_matspecular.a) %s);\n", i, specularStr, i, timesLightScale);
			}
			WRITE(p, "  lightSum0.rgb += (u_lightambient%i * %s.rgb + diffuse)%s;\n", i, ambientStr, timesLightScale);
		}

		if (gstate.isLightingEnabled()) {
			// Sum up ambient, emissive here.
			if (lmode) {
				WRITE(p, "  v_color0 = clamp(lightSum0, 0.0, 1.0);\n");
				// v_color1 only exists when lmode = 1.
				if (specularIsZero) {
					WRITE(p, "  v_color1 = vec3(0.0);\n");
				} else {
					WRITE(p, "  v_color1 = clamp(lightSum1, 0.0, 1.0);\n");
				}
			} else {
				if (specularIsZero) {
					WRITE(p, "  v_color0 = clamp(lightSum0, 0.0, 1.0);\n");
				} else {
					WRITE(p, "  v_color0 = clamp(clamp(lightSum0, 0.0, 1.0) + vec4(lightSum1, 0.0), 0.0, 1.0);\n");
				}
			}
		} else {
			// Lighting doesn't affect color.
			if (hasColor) {
				WRITE(p, "  v_color0 = color0;\n");
			} else {
				WRITE(p, "  v_color0 = u_matambientalpha;\n");
			}
			if (lmode)
				WRITE(p, "  v_color1 = vec3(0.0);\n");
		}

		// Step 3: UV generation
		if (doTexture) {
			switch (gstate.getUVGenMode()) {
			case GE_TEXMAP_TEXTURE_COORDS:  // Scale-offset. Easy.
			case GE_TEXMAP_UNKNOWN: // Not sure what this is, but Riviera uses it.  Treating as coords works.
				if (prescale && !flipV) {
					WRITE(p, "  v_texcoord = texcoord;\n");
				} else {
					WRITE(p, "  v_texcoord = texcoord * u_uvscaleoffset.xy + u_uvscaleoffset.zw;\n");
				}
				break;

			case GE_TEXMAP_TEXTURE_MATRIX:  // Projection mapping.
				{
					std::string temp_tc;
					switch (gstate.getUVProjMode()) {
					case GE_PROJMAP_POSITION:  // Use model space XYZ as source
						temp_tc = "vec4(position.xyz, 1.0)";
						break;
					case GE_PROJMAP_UV:  // Use unscaled UV as source
						{
							static const char *rescaleuv[4] = {"", " * 1.9921875", " * 1.999969482421875", ""}; // 2*127.5f/128.f, 2*32767.5f/32768.f, 1.0f};
							const char *factor = rescaleuv[(vertType & GE_VTYPE_TC_MASK) >> GE_VTYPE_TC_SHIFT];
							temp_tc = StringFromFormat("vec4(texcoord.xy %s, 0.0, 1.0)", factor);
						}
						break;
					case GE_PROJMAP_NORMALIZED_NORMAL:  // Use normalized transformed normal as source
						if (hasNormal)
							temp_tc = flipNormal ? "vec4(normalize(-normal), 1.0)" : "vec4(normalize(normal), 1.0)";
						else
							temp_tc = "vec4(0.0, 0.0, 1.0, 1.0)";
						break;
					case GE_PROJMAP_NORMAL:  // Use non-normalized transformed normal as source
						if (hasNormal)
							temp_tc = flipNormal ? "vec4(-normal, 1.0)" : "vec4(normal, 1.0)";
						else
							temp_tc = "vec4(0.0, 0.0, 1.0, 1.0)";
						break;
					}
					// Transform by texture matrix. XYZ as we are doing projection mapping.
					WRITE(p, "  v_texcoord = (u_texmtx * %s).xyz * vec3(u_uvscaleoffset.xy, 1.0);\n", temp_tc.c_str());
				}
				break;

			case GE_TEXMAP_ENVIRONMENT_MAP:  // Shade mapping - use dots from light sources.
				WRITE(p, "  v_texcoord = u_uvscaleoffset.xy * vec2(1.0 + dot(normalize(u_lightpos%i), worldnormal), 1.0 - dot(normalize(u_lightpos%i), worldnormal)) * 0.5;\n", gstate.getUVLS0(), gstate.getUVLS1());
				break;

			default:
				// ILLEGAL
				break;
			}

			if (flipV)
				WRITE(p, "  v_texcoord.y = 1.0 - v_texcoord.y;\n");
		}

		// Compute fogdepth
		if (enableFog)
			WRITE(p, "  v_fogdepth = (viewPos.z + u_fogcoef.x) * u_fogcoef.y;\n");
	}
	WRITE(p, "}\n");
}
示例#3
0
void TransformDrawEngine::SoftwareTransformAndDraw(
    int prim, u8 *decoded, LinkedShader *program, int vertexCount, u32 vertType, void *inds, int indexType, const DecVtxFormat &decVtxFormat, int maxIndex) {

    bool throughmode = (vertType & GE_VTYPE_THROUGH_MASK) != 0;
    bool lmode = gstate.isUsingSecondaryColor() && gstate.isLightingEnabled();

    // TODO: Split up into multiple draw calls for GLES 2.0 where you can't guarantee support for more than 0x10000 verts.

#if defined(MOBILE_DEVICE)
    if (vertexCount > 0x10000/3)
        vertexCount = 0x10000/3;
#endif

    float uscale = 1.0f;
    float vscale = 1.0f;
    bool scaleUV = false;
    if (throughmode) {
        uscale /= gstate_c.curTextureWidth;
        vscale /= gstate_c.curTextureHeight;
    } else {
        scaleUV = !g_Config.bPrescaleUV;
    }

    bool skinningEnabled = vertTypeIsSkinningEnabled(vertType);

    int w = gstate.getTextureWidth(0);
    int h = gstate.getTextureHeight(0);
    float widthFactor = (float) w / (float) gstate_c.curTextureWidth;
    float heightFactor = (float) h / (float) gstate_c.curTextureHeight;

    Lighter lighter(vertType);
    float fog_end = getFloat24(gstate.fog1);
    float fog_slope = getFloat24(gstate.fog2);

    VertexReader reader(decoded, decVtxFormat, vertType);
    for (int index = 0; index < maxIndex; index++) {
        reader.Goto(index);

        float v[3] = {0, 0, 0};
        float c0[4] = {1, 1, 1, 1};
        float c1[4] = {0, 0, 0, 0};
        float uv[3] = {0, 0, 1};
        float fogCoef = 1.0f;

        if (throughmode) {
            // Do not touch the coordinates or the colors. No lighting.
            reader.ReadPos(v);
            if (reader.hasColor0()) {
                reader.ReadColor0(c0);
                for (int j = 0; j < 4; j++) {
                    c1[j] = 0.0f;
                }
            } else {
                c0[0] = gstate.getMaterialAmbientR() / 255.f;
                c0[1] = gstate.getMaterialAmbientG() / 255.f;
                c0[2] = gstate.getMaterialAmbientB() / 255.f;
                c0[3] = gstate.getMaterialAmbientA() / 255.f;
            }

            if (reader.hasUV()) {
                reader.ReadUV(uv);

                uv[0] *= uscale;
                uv[1] *= vscale;
            }
            fogCoef = 1.0f;
            // Scale UV?
        } else {
            // We do software T&L for now
            float out[3], norm[3];
            float pos[3], nrm[3];
            Vec3f normal(0, 0, 1);
            reader.ReadPos(pos);
            if (reader.hasNormal())
                reader.ReadNrm(nrm);

            if (!skinningEnabled) {
                Vec3ByMatrix43(out, pos, gstate.worldMatrix);
                if (reader.hasNormal()) {
                    Norm3ByMatrix43(norm, nrm, gstate.worldMatrix);
                    normal = Vec3f(norm).Normalized();
                }
            } else {
                float weights[8];
                reader.ReadWeights(weights);
                // Skinning
                Vec3f psum(0,0,0);
                Vec3f nsum(0,0,0);
                for (int i = 0; i < vertTypeGetNumBoneWeights(vertType); i++) {
                    if (weights[i] != 0.0f) {
                        Vec3ByMatrix43(out, pos, gstate.boneMatrix+i*12);
                        Vec3f tpos(out);
                        psum += tpos * weights[i];
                        if (reader.hasNormal()) {
                            Norm3ByMatrix43(norm, nrm, gstate.boneMatrix+i*12);
                            Vec3f tnorm(norm);
                            nsum += tnorm * weights[i];
                        }
                    }
                }

                // Yes, we really must multiply by the world matrix too.
                Vec3ByMatrix43(out, psum.AsArray(), gstate.worldMatrix);
                if (reader.hasNormal()) {
                    Norm3ByMatrix43(norm, nsum.AsArray(), gstate.worldMatrix);
                    normal = Vec3f(norm).Normalized();
                }
            }

            // Perform lighting here if enabled. don't need to check through, it's checked above.
            float unlitColor[4] = {1, 1, 1, 1};
            if (reader.hasColor0()) {
                reader.ReadColor0(unlitColor);
            } else {
                unlitColor[0] = gstate.getMaterialAmbientR() / 255.f;
                unlitColor[1] = gstate.getMaterialAmbientG() / 255.f;
                unlitColor[2] = gstate.getMaterialAmbientB() / 255.f;
                unlitColor[3] = gstate.getMaterialAmbientA() / 255.f;
            }
            float litColor0[4];
            float litColor1[4];
            lighter.Light(litColor0, litColor1, unlitColor, out, normal);

            if (gstate.isLightingEnabled()) {
                // Don't ignore gstate.lmode - we should send two colors in that case
                for (int j = 0; j < 4; j++) {
                    c0[j] = litColor0[j];
                }
                if (lmode) {
                    // Separate colors
                    for (int j = 0; j < 4; j++) {
                        c1[j] = litColor1[j];
                    }
                } else {
                    // Summed color into c0
                    for (int j = 0; j < 4; j++) {
                        c0[j] = ((c0[j] + litColor1[j]) > 1.0f) ? 1.0f : (c0[j] + litColor1[j]);
                    }
                }
            } else {
                if (reader.hasColor0()) {
                    for (int j = 0; j < 4; j++) {
                        c0[j] = unlitColor[j];
                    }
                } else {
                    c0[0] = gstate.getMaterialAmbientR() / 255.f;
                    c0[1] = gstate.getMaterialAmbientG() / 255.f;
                    c0[2] = gstate.getMaterialAmbientB() / 255.f;
                    c0[3] = gstate.getMaterialAmbientA() / 255.f;
                }
                if (lmode) {
                    for (int j = 0; j < 4; j++) {
                        c1[j] = 0.0f;
                    }
                }
            }

            float ruv[2] = {0.0f, 0.0f};
            if (reader.hasUV())
                reader.ReadUV(ruv);

            // Perform texture coordinate generation after the transform and lighting - one style of UV depends on lights.
            switch (gstate.getUVGenMode()) {
            case GE_TEXMAP_TEXTURE_COORDS:	// UV mapping
            case GE_TEXMAP_UNKNOWN: // Seen in Riviera.  Unsure of meaning, but this works.
                // Texture scale/offset is only performed in this mode.
                if (scaleUV) {
                    uv[0] = ruv[0]*gstate_c.uv.uScale + gstate_c.uv.uOff;
                    uv[1] = ruv[1]*gstate_c.uv.vScale + gstate_c.uv.vOff;
                } else {
                    uv[0] = ruv[0];
                    uv[1] = ruv[1];
                }
                uv[2] = 1.0f;
                break;

            case GE_TEXMAP_TEXTURE_MATRIX:
            {
                // Projection mapping
                Vec3f source;
                switch (gstate.getUVProjMode())	{
                case GE_PROJMAP_POSITION: // Use model space XYZ as source
                    source = pos;
                    break;

                case GE_PROJMAP_UV: // Use unscaled UV as source
                    source = Vec3f(ruv[0], ruv[1], 0.0f);
                    break;

                case GE_PROJMAP_NORMALIZED_NORMAL: // Use normalized normal as source
                    if (reader.hasNormal()) {
                        source = Vec3f(norm).Normalized();
                    } else {
                        ERROR_LOG_REPORT(G3D, "Normal projection mapping without normal?");
                        source = Vec3f(0.0f, 0.0f, 1.0f);
                    }
                    break;

                case GE_PROJMAP_NORMAL: // Use non-normalized normal as source!
                    if (reader.hasNormal()) {
                        source = Vec3f(norm);
                    } else {
                        ERROR_LOG_REPORT(G3D, "Normal projection mapping without normal?");
                        source = Vec3f(0.0f, 0.0f, 1.0f);
                    }
                    break;
                }

                float uvw[3];
                Vec3ByMatrix43(uvw, &source.x, gstate.tgenMatrix);
                uv[0] = uvw[0];
                uv[1] = uvw[1];
                uv[2] = uvw[2];
            }
            break;

            case GE_TEXMAP_ENVIRONMENT_MAP:
                // Shade mapping - use two light sources to generate U and V.
            {
                Vec3f lightpos0 = Vec3f(gstate_c.lightpos[gstate.getUVLS0()]).Normalized();
                Vec3f lightpos1 = Vec3f(gstate_c.lightpos[gstate.getUVLS1()]).Normalized();

                uv[0] = (1.0f + Dot(lightpos0, normal))/2.0f;
                uv[1] = (1.0f - Dot(lightpos1, normal))/2.0f;
                uv[2] = 1.0f;
            }
            break;

            default:
                // Illegal
                ERROR_LOG_REPORT(G3D, "Impossible UV gen mode? %d", gstate.getUVGenMode());
                break;
            }

            uv[0] = uv[0] * widthFactor;
            uv[1] = uv[1] * heightFactor;

            // Transform the coord by the view matrix.
            Vec3ByMatrix43(v, out, gstate.viewMatrix);
            fogCoef = (v[2] + fog_end) * fog_slope;
        }

        // TODO: Write to a flexible buffer, we don't always need all four components.
        memcpy(&transformed[index].x, v, 3 * sizeof(float));
        transformed[index].fog = fogCoef;
        memcpy(&transformed[index].u, uv, 3 * sizeof(float));
        if (gstate_c.flipTexture) {
            transformed[index].v = 1.0f - transformed[index].v;
        }
        for (int i = 0; i < 4; i++) {
            transformed[index].color0[i] = c0[i] * 255.0f;
        }
        for (int i = 0; i < 3; i++) {
            transformed[index].color1[i] = c1[i] * 255.0f;
        }
    }

    // Here's the best opportunity to try to detect rectangles used to clear the screen, and
    // replace them with real OpenGL clears. This can provide a speedup on certain mobile chips.
    // Disabled for now - depth does not come out exactly the same.
    //
    // An alternative option is to simply ditch all the verts except the first and last to create a single
    // rectangle out of many. Quite a small optimization though.
    if (false && maxIndex > 1 && gstate.isModeClear() && prim == GE_PRIM_RECTANGLES && IsReallyAClear(maxIndex)) {
        u32 clearColor;
        memcpy(&clearColor, transformed[0].color0, 4);
        float clearDepth = transformed[0].z;
        const float col[4] = {
            ((clearColor & 0xFF)) / 255.0f,
            ((clearColor & 0xFF00) >> 8) / 255.0f,
            ((clearColor & 0xFF0000) >> 16) / 255.0f,
            ((clearColor & 0xFF000000) >> 24) / 255.0f,
        };

        bool colorMask = gstate.isClearModeColorMask();
        bool alphaMask = gstate.isClearModeAlphaMask();
        glstate.colorMask.set(colorMask, colorMask, colorMask, alphaMask);
        if (alphaMask) {
            glstate.stencilTest.set(true);
            // Clear stencil
            // TODO: extract the stencilValue properly, see below
            int stencilValue = 0;
            glstate.stencilFunc.set(GL_ALWAYS, stencilValue, 255);
        } else {
            // Don't touch stencil
            glstate.stencilTest.set(false);
        }
        glstate.scissorTest.set(false);
        bool depthMask = gstate.isClearModeDepthMask();

        int target = 0;
        if (colorMask || alphaMask) target |= GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT;
        if (depthMask) target |= GL_DEPTH_BUFFER_BIT;

        glClearColor(col[0], col[1], col[2], col[3]);
#ifdef USING_GLES2
        glClearDepthf(clearDepth);
#else
        glClearDepth(clearDepth);
#endif
        glClearStencil(0);  // TODO - take from alpha?
        glClear(target);
        return;
    }
示例#4
0
VertexData TransformUnit::ReadVertex(VertexReader& vreader)
{
	VertexData vertex;

	float pos[3];
	// VertexDecoder normally scales z, but we want it unscaled.
	vreader.ReadPosThroughZ16(pos);

	if (!gstate.isModeClear() && gstate.isTextureMapEnabled() && vreader.hasUV()) {
		float uv[2];
		vreader.ReadUV(uv);
		vertex.texturecoords = Vec2<float>(uv[0], uv[1]);
	}

	if (vreader.hasNormal()) {
		float normal[3];
		vreader.ReadNrm(normal);
		vertex.normal = Vec3<float>(normal[0], normal[1], normal[2]);

		if (gstate.areNormalsReversed())
			vertex.normal = -vertex.normal;
	}

	if (vertTypeIsSkinningEnabled(gstate.vertType) && !gstate.isModeThrough()) {
		float W[8] = { 1.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f };
		vreader.ReadWeights(W);

		Vec3<float> tmppos(0.f, 0.f, 0.f);
		Vec3<float> tmpnrm(0.f, 0.f, 0.f);

		for (int i = 0; i < vertTypeGetNumBoneWeights(gstate.vertType); ++i) {
			Mat3x3<float> bone(&gstate.boneMatrix[12*i]);
			tmppos += (bone * ModelCoords(pos[0], pos[1], pos[2]) + Vec3<float>(gstate.boneMatrix[12*i+9], gstate.boneMatrix[12*i+10], gstate.boneMatrix[12*i+11])) * W[i];
			if (vreader.hasNormal())
				tmpnrm += (bone * vertex.normal) * W[i];
		}

		pos[0] = tmppos.x;
		pos[1] = tmppos.y;
		pos[2] = tmppos.z;
		if (vreader.hasNormal())
			vertex.normal = tmpnrm;
	}

	if (vreader.hasColor0()) {
		float col[4];
		vreader.ReadColor0(col);
		vertex.color0 = Vec4<int>(col[0]*255, col[1]*255, col[2]*255, col[3]*255);
	} else {
		vertex.color0 = Vec4<int>(gstate.getMaterialAmbientR(), gstate.getMaterialAmbientG(), gstate.getMaterialAmbientB(), gstate.getMaterialAmbientA());
	}

	if (vreader.hasColor1()) {
		float col[3];
		vreader.ReadColor1(col);
		vertex.color1 = Vec3<int>(col[0]*255, col[1]*255, col[2]*255);
	} else {
		vertex.color1 = Vec3<int>(0, 0, 0);
	}

	if (!gstate.isModeThrough()) {
		vertex.modelpos = ModelCoords(pos[0], pos[1], pos[2]);
		vertex.worldpos = WorldCoords(TransformUnit::ModelToWorld(vertex.modelpos));
		ModelCoords viewpos = TransformUnit::WorldToView(vertex.worldpos);
		vertex.clippos = ClipCoords(TransformUnit::ViewToClip(viewpos));
		if (gstate.isFogEnabled()) {
			float fog_end = getFloat24(gstate.fog1);
			float fog_slope = getFloat24(gstate.fog2);
			// Same fixup as in ShaderManagerGLES.cpp
			if (my_isnanorinf(fog_end)) {
				// Not really sure what a sensible value might be, but let's try 64k.
				fog_end = std::signbit(fog_end) ? -65535.0f : 65535.0f;
			}
			if (my_isnanorinf(fog_slope)) {
				fog_slope = std::signbit(fog_slope) ? -65535.0f : 65535.0f;
			}
			vertex.fogdepth = (viewpos.z + fog_end) * fog_slope;
		} else {
			vertex.fogdepth = 1.0f;
		}
		vertex.screenpos = ClipToScreenInternal(vertex.clippos, &outside_range_flag);

		if (vreader.hasNormal()) {
			vertex.worldnormal = TransformUnit::ModelToWorldNormal(vertex.normal);
			// TODO: Isn't there a flag that controls whether to normalize the normal?
			vertex.worldnormal /= vertex.worldnormal.Length();
		} else {
			vertex.worldnormal = Vec3<float>(0.0f, 0.0f, 1.0f);
		}

		Lighting::Process(vertex, vreader.hasColor0());
	} else {
		vertex.screenpos.x = (int)(pos[0] * 16) + gstate.getOffsetX16();
		vertex.screenpos.y = (int)(pos[1] * 16) + gstate.getOffsetY16();
		vertex.screenpos.z = pos[2];
		vertex.clippos.w = 1.f;
		vertex.fogdepth = 1.f;
	}

	return vertex;
}
示例#5
0
static VertexData ReadVertex(VertexReader& vreader)
{
    VertexData vertex;

    float pos[3];
    // VertexDecoder normally scales z, but we want it unscaled.
    vreader.ReadPosZ16(pos);

    if (!gstate.isModeClear() && gstate.isTextureMapEnabled() && vreader.hasUV()) {
        float uv[2];
        vreader.ReadUV(uv);
        vertex.texturecoords = Vec2<float>(uv[0], uv[1]);
    }

    if (vreader.hasNormal()) {
        float normal[3];
        vreader.ReadNrm(normal);
        vertex.normal = Vec3<float>(normal[0], normal[1], normal[2]);

        if (gstate.areNormalsReversed())
            vertex.normal = -vertex.normal;
    }

    if (vertTypeIsSkinningEnabled(gstate.vertType) && !gstate.isModeThrough()) {
        float W[8] = { 1.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f };
        vreader.ReadWeights(W);

        Vec3<float> tmppos(0.f, 0.f, 0.f);
        Vec3<float> tmpnrm(0.f, 0.f, 0.f);

        for (int i = 0; i < vertTypeGetNumBoneWeights(gstate.vertType); ++i) {
            Mat3x3<float> bone(&gstate.boneMatrix[12*i]);
            tmppos += (bone * ModelCoords(pos[0], pos[1], pos[2]) * W[i] + Vec3<float>(gstate.boneMatrix[12*i+9], gstate.boneMatrix[12*i+10], gstate.boneMatrix[12*i+11]));
            if (vreader.hasNormal())
                tmpnrm += (bone * vertex.normal) * W[i];
        }

        pos[0] = tmppos.x;
        pos[1] = tmppos.y;
        pos[2] = tmppos.z;
        if (vreader.hasNormal())
            vertex.normal = tmpnrm;
    }

    if (vreader.hasColor0()) {
        float col[4];
        vreader.ReadColor0(col);
        vertex.color0 = Vec4<int>(col[0]*255, col[1]*255, col[2]*255, col[3]*255);
    } else {
        vertex.color0 = Vec4<int>(gstate.getMaterialAmbientR(), gstate.getMaterialAmbientG(), gstate.getMaterialAmbientB(), gstate.getMaterialAmbientA());
    }

    if (vreader.hasColor1()) {
        float col[3];
        vreader.ReadColor1(col);
        vertex.color1 = Vec3<int>(col[0]*255, col[1]*255, col[2]*255);
    } else {
        vertex.color1 = Vec3<int>(0, 0, 0);
    }

    if (!gstate.isModeThrough()) {
        vertex.modelpos = ModelCoords(pos[0], pos[1], pos[2]);
        vertex.worldpos = WorldCoords(TransformUnit::ModelToWorld(vertex.modelpos));
        vertex.clippos = ClipCoords(TransformUnit::ViewToClip(TransformUnit::WorldToView(vertex.worldpos)));
        vertex.screenpos = ClipToScreenInternal(vertex.clippos);

        if (vreader.hasNormal()) {
            vertex.worldnormal = TransformUnit::ModelToWorldNormal(vertex.normal);
            // TODO: Isn't there a flag that controls whether to normalize the normal?
            vertex.worldnormal /= vertex.worldnormal.Length();
        }

        Lighting::Process(vertex);
    } else {
        vertex.screenpos.x = (u32)pos[0] * 16 + gstate.getOffsetX16();
        vertex.screenpos.y = (u32)pos[1] * 16 + gstate.getOffsetY16();
        vertex.screenpos.z = pos[2];
        vertex.clippos.w = 1.f;
    }

    return vertex;
}
示例#6
0
void SoftwareTransform(
	int prim, int vertexCount, u32 vertType, u16 *&inds, int indexType,
	const DecVtxFormat &decVtxFormat, int &maxIndex, TransformedVertex *&drawBuffer, int &numTrans, bool &drawIndexed, const SoftwareTransformParams *params, SoftwareTransformResult *result) {
	u8 *decoded = params->decoded;
	FramebufferManagerCommon *fbman = params->fbman;
	TextureCacheCommon *texCache = params->texCache;
	TransformedVertex *transformed = params->transformed;
	TransformedVertex *transformedExpanded = params->transformedExpanded;
	float ySign = 1.0f;
	bool throughmode = (vertType & GE_VTYPE_THROUGH_MASK) != 0;
	bool lmode = gstate.isUsingSecondaryColor() && gstate.isLightingEnabled();

	// TODO: Split up into multiple draw calls for GLES 2.0 where you can't guarantee support for more than 0x10000 verts.

#if defined(MOBILE_DEVICE)
	if (vertexCount > 0x10000/3)
		vertexCount = 0x10000/3;
#endif

	float uscale = 1.0f;
	float vscale = 1.0f;
	if (throughmode) {
		uscale /= gstate_c.curTextureWidth;
		vscale /= gstate_c.curTextureHeight;
	}

	bool skinningEnabled = vertTypeIsSkinningEnabled(vertType);

	const int w = gstate.getTextureWidth(0);
	const int h = gstate.getTextureHeight(0);
	float widthFactor = (float) w / (float) gstate_c.curTextureWidth;
	float heightFactor = (float) h / (float) gstate_c.curTextureHeight;

	Lighter lighter(vertType);
	float fog_end = getFloat24(gstate.fog1);
	float fog_slope = getFloat24(gstate.fog2);
	// Same fixup as in ShaderManager.cpp
	if (my_isinf(fog_slope)) {
		// not really sure what a sensible value might be.
		fog_slope = fog_slope < 0.0f ? -10000.0f : 10000.0f;
	}
	if (my_isnan(fog_slope)) {
		// Workaround for https://github.com/hrydgard/ppsspp/issues/5384#issuecomment-38365988
		// Just put the fog far away at a large finite distance.
		// Infinities and NaNs are rather unpredictable in shaders on many GPUs
		// so it's best to just make it a sane calculation.
		fog_end = 100000.0f;
		fog_slope = 1.0f;
	}

	VertexReader reader(decoded, decVtxFormat, vertType);
	if (throughmode) {
		for (int index = 0; index < maxIndex; index++) {
			// Do not touch the coordinates or the colors. No lighting.
			reader.Goto(index);
			// TODO: Write to a flexible buffer, we don't always need all four components.
			TransformedVertex &vert = transformed[index];
			reader.ReadPos(vert.pos);

			if (reader.hasColor0()) {
				reader.ReadColor0_8888(vert.color0);
			} else {
				vert.color0_32 = gstate.getMaterialAmbientRGBA();
			}

			if (reader.hasUV()) {
				reader.ReadUV(vert.uv);

				vert.u *= uscale;
				vert.v *= vscale;
			} else {
				vert.u = 0.0f;
				vert.v = 0.0f;
			}

			// Ignore color1 and fog, never used in throughmode anyway.
			// The w of uv is also never used (hardcoded to 1.0.)
		}
	} else {
		// Okay, need to actually perform the full transform.
		for (int index = 0; index < maxIndex; index++) {
			reader.Goto(index);

			float v[3] = {0, 0, 0};
			Vec4f c0 = Vec4f(1, 1, 1, 1);
			Vec4f c1 = Vec4f(0, 0, 0, 0);
			float uv[3] = {0, 0, 1};
			float fogCoef = 1.0f;

			// We do software T&L for now
			float out[3];
			float pos[3];
			Vec3f normal(0, 0, 1);
			Vec3f worldnormal(0, 0, 1);
			reader.ReadPos(pos);

			if (!skinningEnabled) {
				Vec3ByMatrix43(out, pos, gstate.worldMatrix);
				if (reader.hasNormal()) {
					reader.ReadNrm(normal.AsArray());
					if (gstate.areNormalsReversed()) {
						normal = -normal;
					}
					Norm3ByMatrix43(worldnormal.AsArray(), normal.AsArray(), gstate.worldMatrix);
					worldnormal = worldnormal.Normalized();
				}
			} else {
				float weights[8];
				reader.ReadWeights(weights);
				if (reader.hasNormal())
					reader.ReadNrm(normal.AsArray());

				// Skinning
				Vec3f psum(0, 0, 0);
				Vec3f nsum(0, 0, 0);
				for (int i = 0; i < vertTypeGetNumBoneWeights(vertType); i++) {
					if (weights[i] != 0.0f) {
						Vec3ByMatrix43(out, pos, gstate.boneMatrix+i*12);
						Vec3f tpos(out);
						psum += tpos * weights[i];
						if (reader.hasNormal()) {
							Vec3f norm;
							Norm3ByMatrix43(norm.AsArray(), normal.AsArray(), gstate.boneMatrix+i*12);
							nsum += norm * weights[i];
						}
					}
				}

				// Yes, we really must multiply by the world matrix too.
				Vec3ByMatrix43(out, psum.AsArray(), gstate.worldMatrix);
				if (reader.hasNormal()) {
					normal = nsum;
					if (gstate.areNormalsReversed()) {
						normal = -normal;
					}
					Norm3ByMatrix43(worldnormal.AsArray(), normal.AsArray(), gstate.worldMatrix);
					worldnormal = worldnormal.Normalized();
				}
			}

			// Perform lighting here if enabled. don't need to check through, it's checked above.
			Vec4f unlitColor = Vec4f(1, 1, 1, 1);
			if (reader.hasColor0()) {
				reader.ReadColor0(&unlitColor.x);
			} else {
				unlitColor = Vec4f::FromRGBA(gstate.getMaterialAmbientRGBA());
			}

			if (gstate.isLightingEnabled()) {
				float litColor0[4];
				float litColor1[4];
				lighter.Light(litColor0, litColor1, unlitColor.AsArray(), out, worldnormal);

				// Don't ignore gstate.lmode - we should send two colors in that case
				for (int j = 0; j < 4; j++) {
					c0[j] = litColor0[j];
				}
				if (lmode) {
					// Separate colors
					for (int j = 0; j < 4; j++) {
						c1[j] = litColor1[j];
					}
				} else {
					// Summed color into c0 (will clamp in ToRGBA().)
					for (int j = 0; j < 4; j++) {
						c0[j] += litColor1[j];
					}
				}
			} else {
				if (reader.hasColor0()) {
					for (int j = 0; j < 4; j++) {
						c0[j] = unlitColor[j];
					}
				} else {
					c0 = Vec4f::FromRGBA(gstate.getMaterialAmbientRGBA());
				}
				if (lmode) {
					// c1 is already 0.
				}
			}

			float ruv[2] = {0.0f, 0.0f};
			if (reader.hasUV())
				reader.ReadUV(ruv);

			// Perform texture coordinate generation after the transform and lighting - one style of UV depends on lights.
			switch (gstate.getUVGenMode()) {
			case GE_TEXMAP_TEXTURE_COORDS:	// UV mapping
			case GE_TEXMAP_UNKNOWN: // Seen in Riviera.  Unsure of meaning, but this works.
				// We always prescale in the vertex decoder now.
				uv[0] = ruv[0];
				uv[1] = ruv[1];
				uv[2] = 1.0f;
				break;

			case GE_TEXMAP_TEXTURE_MATRIX:
				{
					// Projection mapping
					Vec3f source;
					switch (gstate.getUVProjMode())	{
					case GE_PROJMAP_POSITION: // Use model space XYZ as source
						source = pos;
						break;

					case GE_PROJMAP_UV: // Use unscaled UV as source
						source = Vec3f(ruv[0], ruv[1], 0.0f);
						break;

					case GE_PROJMAP_NORMALIZED_NORMAL: // Use normalized normal as source
						source = normal.Normalized();
						if (!reader.hasNormal()) {
							ERROR_LOG_REPORT(G3D, "Normal projection mapping without normal?");
						}
						break;

					case GE_PROJMAP_NORMAL: // Use non-normalized normal as source!
						source = normal;
						if (!reader.hasNormal()) {
							ERROR_LOG_REPORT(G3D, "Normal projection mapping without normal?");
						}
						break;
					}

					float uvw[3];
					Vec3ByMatrix43(uvw, &source.x, gstate.tgenMatrix);
					uv[0] = uvw[0];
					uv[1] = uvw[1];
					uv[2] = uvw[2];
				}
				break;

			case GE_TEXMAP_ENVIRONMENT_MAP:
				// Shade mapping - use two light sources to generate U and V.
				{
					Vec3f lightpos0 = Vec3f(&lighter.lpos[gstate.getUVLS0() * 3]).Normalized();
					Vec3f lightpos1 = Vec3f(&lighter.lpos[gstate.getUVLS1() * 3]).Normalized();

					uv[0] = (1.0f + Dot(lightpos0, worldnormal))/2.0f;
					uv[1] = (1.0f + Dot(lightpos1, worldnormal))/2.0f;
					uv[2] = 1.0f;
				}
				break;

			default:
				// Illegal
				ERROR_LOG_REPORT(G3D, "Impossible UV gen mode? %d", gstate.getUVGenMode());
				break;
			}

			uv[0] = uv[0] * widthFactor;
			uv[1] = uv[1] * heightFactor;

			// Transform the coord by the view matrix.
			Vec3ByMatrix43(v, out, gstate.viewMatrix);
			fogCoef = (v[2] + fog_end) * fog_slope;

			// TODO: Write to a flexible buffer, we don't always need all four components.
			memcpy(&transformed[index].x, v, 3 * sizeof(float));
			transformed[index].fog = fogCoef;
			memcpy(&transformed[index].u, uv, 3 * sizeof(float));
			transformed[index].color0_32 = c0.ToRGBA();
			transformed[index].color1_32 = c1.ToRGBA();

			// The multiplication by the projection matrix is still performed in the vertex shader.
			// So is vertex depth rounding, to simulate the 16-bit depth buffer.
		}
	}

	// Here's the best opportunity to try to detect rectangles used to clear the screen, and
	// replace them with real clears. This can provide a speedup on certain mobile chips.
	//
	// An alternative option is to simply ditch all the verts except the first and last to create a single
	// rectangle out of many. Quite a small optimization though.
	// Experiment: Disable on PowerVR (see issue #6290)
	// TODO: This bleeds outside the play area in non-buffered mode. Big deal? Probably not.
	bool reallyAClear = false;
	if (maxIndex > 1 && prim == GE_PRIM_RECTANGLES && gstate.isModeClear()) {
		int scissorX2 = gstate.getScissorX2() + 1;
		int scissorY2 = gstate.getScissorY2() + 1;
		reallyAClear = IsReallyAClear(transformed, maxIndex, scissorX2, scissorY2);
	}
	if (reallyAClear && gl_extensions.gpuVendor != GPU_VENDOR_POWERVR) {  // && g_Config.iRenderingMode != FB_NON_BUFFERED_MODE) {
		// If alpha is not allowed to be separate, it must match for both depth/stencil and color.  Vulkan requires this.
		bool alphaMatchesColor = gstate.isClearModeColorMask() == gstate.isClearModeAlphaMask();
		bool depthMatchesStencil = gstate.isClearModeAlphaMask() == gstate.isClearModeDepthMask();
		if (params->allowSeparateAlphaClear || (alphaMatchesColor && depthMatchesStencil)) {
			result->color = transformed[1].color0_32;
			// Need to rescale from a [0, 1] float.  This is the final transformed value.
			result->depth = ToScaledDepth((s16)(int)(transformed[1].z * 65535.0f));
			result->action = SW_CLEAR;
			return;
		}
	}

	// This means we're using a framebuffer (and one that isn't big enough.)
	if (gstate_c.curTextureHeight < (u32)h && maxIndex >= 2) {
		// Even if not rectangles, this will detect if either of the first two are outside the framebuffer.
		// HACK: Adding one pixel margin to this detection fixes issues in Assassin's Creed : Bloodlines,
		// while still keeping BOF working (see below).
		const float invTexH = 1.0f / gstate_c.curTextureHeight; // size of one texel.
		bool tlOutside;
		bool tlAlmostOutside;
		bool brOutside;
		// If we're outside heightFactor, then v must be wrapping or clamping.  Avoid this workaround.
		// If we're <= 1.0f, we're inside the framebuffer (workaround not needed.)
		// We buffer that 1.0f a little more with a texel to avoid some false positives.
		tlOutside = transformed[0].v <= heightFactor && transformed[0].v > 1.0f + invTexH;
		brOutside = transformed[1].v <= heightFactor && transformed[1].v > 1.0f + invTexH;
		// Careful: if br is outside, but tl is well inside, this workaround still doesn't make sense.
		// We go with halfway, since we overestimate framebuffer heights sometimes but not by much.
		tlAlmostOutside = transformed[0].v <= heightFactor && transformed[0].v >= 0.5f;
		if (tlOutside || (brOutside && tlAlmostOutside)) {
			// Okay, so we're texturing from outside the framebuffer, but inside the texture height.
			// Breath of Fire 3 does this to access a render surface at an offset.
			const u32 bpp = fbman->GetTargetFormat() == GE_FORMAT_8888 ? 4 : 2;
			const u32 prevH = texCache->AttachedDrawingHeight();
			const u32 fb_size = bpp * fbman->GetTargetStride() * prevH;
			const u32 prevYOffset = gstate_c.curTextureYOffset;
			if (texCache->SetOffsetTexture(fb_size)) {
				const float oldWidthFactor = widthFactor;
				const float oldHeightFactor = heightFactor;
				widthFactor = (float) w / (float) gstate_c.curTextureWidth;
				heightFactor = (float) h / (float) gstate_c.curTextureHeight;

				// We've already baked in the old gstate_c.curTextureYOffset, so correct.
				const float yDiff = (float) (prevH + prevYOffset - gstate_c.curTextureYOffset) / (float) h;
				for (int index = 0; index < maxIndex; ++index) {
					transformed[index].u *= widthFactor / oldWidthFactor;
					// Inverse it back to scale to the new FBO, and add 1.0f to account for old FBO.
					transformed[index].v = (transformed[index].v / oldHeightFactor - yDiff) * heightFactor;
				}
			}
		}
	}

	// Step 2: expand rectangles.
	drawBuffer = transformed;
	numTrans = 0;
	drawIndexed = false;

	if (prim != GE_PRIM_RECTANGLES) {
		// We can simply draw the unexpanded buffer.
		numTrans = vertexCount;
		drawIndexed = true;
	} else {
		bool useBufferedRendering = g_Config.iRenderingMode != FB_NON_BUFFERED_MODE;
		if (useBufferedRendering)
			ySign = -ySign;

		float flippedMatrix[16];
		if (!throughmode) {
			memcpy(&flippedMatrix, gstate.projMatrix, 16 * sizeof(float));

			const bool invertedY = useBufferedRendering ? (gstate_c.vpHeight < 0) : (gstate_c.vpHeight > 0);
			if (invertedY) {
				flippedMatrix[1] = -flippedMatrix[1];
				flippedMatrix[5] = -flippedMatrix[5];
				flippedMatrix[9] = -flippedMatrix[9];
				flippedMatrix[13] = -flippedMatrix[13];
			}
			const bool invertedX = gstate_c.vpWidth < 0;
			if (invertedX) {
				flippedMatrix[0] = -flippedMatrix[0];
				flippedMatrix[4] = -flippedMatrix[4];
				flippedMatrix[8] = -flippedMatrix[8];
				flippedMatrix[12] = -flippedMatrix[12];
			}
		}

		//rectangles always need 2 vertices, disregard the last one if there's an odd number
		vertexCount = vertexCount & ~1;
		numTrans = 0;
		drawBuffer = transformedExpanded;
		TransformedVertex *trans = &transformedExpanded[0];
		const u16 *indsIn = (const u16 *)inds;
		u16 *newInds = inds + vertexCount;
		u16 *indsOut = newInds;
		maxIndex = 4 * vertexCount;
		for (int i = 0; i < vertexCount; i += 2) {
			const TransformedVertex &transVtxTL = transformed[indsIn[i + 0]];
			const TransformedVertex &transVtxBR = transformed[indsIn[i + 1]];

			// We have to turn the rectangle into two triangles, so 6 points.
			// This is 4 verts + 6 indices.

			// bottom right
			trans[0] = transVtxBR;

			// top right
			trans[1] = transVtxBR;
			trans[1].y = transVtxTL.y;
			trans[1].v = transVtxTL.v;

			// top left
			trans[2] = transVtxBR;
			trans[2].x = transVtxTL.x;
			trans[2].y = transVtxTL.y;
			trans[2].u = transVtxTL.u;
			trans[2].v = transVtxTL.v;

			// bottom left
			trans[3] = transVtxBR;
			trans[3].x = transVtxTL.x;
			trans[3].u = transVtxTL.u;

			// That's the four corners. Now process UV rotation.
			if (throughmode)
				RotateUVThrough(trans);
			else
				RotateUV(trans, flippedMatrix, ySign);

			// Triangle: BR-TR-TL
			indsOut[0] = i * 2 + 0;
			indsOut[1] = i * 2 + 1;
			indsOut[2] = i * 2 + 2;
			// Triangle: BL-BR-TL
			indsOut[3] = i * 2 + 3;
			indsOut[4] = i * 2 + 0;
			indsOut[5] = i * 2 + 2;
			trans += 4;
			indsOut += 6;

			numTrans += 6;
		}
		inds = newInds;
		drawIndexed = true;

		// We don't know the color until here, so we have to do it now, instead of in StateMapping.
		// Might want to reconsider the order of things later...
		if (gstate.isModeClear() && gstate.isClearModeAlphaMask()) {
			result->setStencil = true;
			if (vertexCount > 1) {
				// Take the bottom right alpha value of the first rect as the stencil value.
				// Technically, each rect could individually fill its stencil, but most of the
				// time they use the same one.
				result->stencilValue = transformed[indsIn[1]].color0[3];
			} else {
				result->stencilValue = 0;
			}
		}
	}

	result->action = SW_DRAW_PRIMITIVES;
}