port from perforce

This commit is contained in:
2026-04-18 22:31:51 +02:00
commit 8d0ab5b7cc
8409 changed files with 3972376 additions and 0 deletions

40
bp4k/UpgradeLog.XML Normal file
View File

@@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type='text/xsl' href='_UpgradeReport_Files/UpgradeReport.xslt'?><UpgradeLog>
<Properties><Property Name="Solution" Value="bp4k">
</Property><Property Name="Solution File" Value="E:\Private\Frank\Code\blu-flame.org\bp4k\bp4k.sln">
</Property><Property Name="Date" Value="Tuesday, April 12, 2011">
</Property><Property Name="Time" Value="20:13">
</Property></Properties><Event ErrorLevel="0" Project="bp4k" Source="src\bp4k\bp4k.vcproj" Description="Converting project file 'E:\Private\Frank\Code\blu-flame.org\bp4k\src\bp4k\bp4k.vcproj'.">
</Event><Event ErrorLevel="1" Project="bp4k" Source="src\bp4k\bp4k.vcproj" Description="VCWebServiceProxyGeneratorTool is no longer supported. The tool has been removed from your project settings.">
</Event><Event ErrorLevel="1" Project="bp4k" Source="src\bp4k\bp4k.vcproj" Description="MSB8012: $(TargetName) ('bp4k') does not match the Linker's OutputFile property value 'E:\Private\Frank\Code\blu-flame.org\bp4k\bin\bp4k_Debug.exe' ('bp4k_Debug') in project configuration 'Debug|Win32'. This may cause your project to build incorrectly. To correct this, please make sure that $(TargetName) property value matches the value specified in %(Link.OutputFile).">
</Event><Event ErrorLevel="1" Project="bp4k" Source="src\bp4k\bp4k.vcproj" Description="MSB8012: $(TargetPath) ('E:\Private\Frank\Code\blu-flame.org\bp4k\bin\bp4k.exe') does not match the Linker's OutputFile property value 'E:\Private\Frank\Code\blu-flame.org\bp4k\bin\bp4k_Debug.exe' ('E:\Private\Frank\Code\blu-flame.org\bp4k\bin\bp4k_Debug.exe') in project configuration 'Debug|Win32'. This may cause your project to build incorrectly. To correct this, please make sure that $(TargetPath) property value matches the value specified in %(Link.OutputFile).">
</Event><Event ErrorLevel="1" Project="bp4k" Source="src\bp4k\bp4k.vcproj" Description="MSB8012: $(TargetName) ('bp4k') does not match the Linker's OutputFile property value 'E:\Private\Frank\Code\blu-flame.org\bp4k\bin\bp4k_Release.exe' ('bp4k_Release') in project configuration 'Release|Win32'. This may cause your project to build incorrectly. To correct this, please make sure that $(TargetName) property value matches the value specified in %(Link.OutputFile).">
</Event><Event ErrorLevel="1" Project="bp4k" Source="src\bp4k\bp4k.vcproj" Description="MSB8012: $(TargetPath) ('E:\Private\Frank\Code\blu-flame.org\bp4k\bin\bp4k.exe') does not match the Linker's OutputFile property value 'E:\Private\Frank\Code\blu-flame.org\bp4k\bin\bp4k_Release.exe' ('E:\Private\Frank\Code\blu-flame.org\bp4k\bin\bp4k_Release.exe') in project configuration 'Release|Win32'. This may cause your project to build incorrectly. To correct this, please make sure that $(TargetPath) property value matches the value specified in %(Link.OutputFile).">
</Event><Event ErrorLevel="1" Project="bp4k" Source="src\bp4k\bp4k.vcproj" Description="MSB8012: $(TargetName) ('bp4k') does not match the Linker's OutputFile property value 'E:\Private\Frank\Code\blu-flame.org\bp4k\bin\bp4k_Compress (Slow).exe' ('bp4k_Compress (Slow)') in project configuration 'Compress (Slow)|Win32'. This may cause your project to build incorrectly. To correct this, please make sure that $(TargetName) property value matches the value specified in %(Link.OutputFile).">
</Event><Event ErrorLevel="1" Project="bp4k" Source="src\bp4k\bp4k.vcproj" Description="MSB8012: $(TargetPath) ('E:\Private\Frank\Code\blu-flame.org\bp4k\bin\bp4k.exe') does not match the Linker's OutputFile property value 'E:\Private\Frank\Code\blu-flame.org\bp4k\bin\bp4k_Compress (Slow).exe' ('E:\Private\Frank\Code\blu-flame.org\bp4k\bin\bp4k_Compress (Slow).exe') in project configuration 'Compress (Slow)|Win32'. This may cause your project to build incorrectly. To correct this, please make sure that $(TargetPath) property value matches the value specified in %(Link.OutputFile).">
</Event><Event ErrorLevel="0" Project="bp4k" Source="src\bp4k\bp4k.vcproj" Description="Done converting to new project file 'E:\Private\Frank\Code\blu-flame.org\bp4k\src\bp4k\bp4k.vcxproj'.">
</Event><Event ErrorLevel="3" Project="bp4k" Source="src\bp4k\bp4k.vcproj" Description="Converted">
</Event><Event ErrorLevel="0" Project="next4k" Source="src\next4k\next4k.vcproj" Description="Converting project file 'E:\Private\Frank\Code\blu-flame.org\bp4k\src\next4k\next4k.vcproj'.">
</Event><Event ErrorLevel="1" Project="next4k" Source="src\next4k\next4k.vcproj" Description="VCWebServiceProxyGeneratorTool is no longer supported. The tool has been removed from your project settings.">
</Event><Event ErrorLevel="1" Project="next4k" Source="src\next4k\next4k.vcproj" Description="MSB8012: $(TargetName) ('next4k') does not match the Linker's OutputFile property value 'E:\Private\Frank\Code\blu-flame.org\bp4k\bin\next4k_Debug.exe' ('next4k_Debug') in project configuration 'Debug|Win32'. This may cause your project to build incorrectly. To correct this, please make sure that $(TargetName) property value matches the value specified in %(Link.OutputFile).">
</Event><Event ErrorLevel="1" Project="next4k" Source="src\next4k\next4k.vcproj" Description="MSB8012: $(TargetPath) ('E:\Private\Frank\Code\blu-flame.org\bp4k\bin\next4k.exe') does not match the Linker's OutputFile property value 'E:\Private\Frank\Code\blu-flame.org\bp4k\bin\next4k_Debug.exe' ('E:\Private\Frank\Code\blu-flame.org\bp4k\bin\next4k_Debug.exe') in project configuration 'Debug|Win32'. This may cause your project to build incorrectly. To correct this, please make sure that $(TargetPath) property value matches the value specified in %(Link.OutputFile).">
</Event><Event ErrorLevel="1" Project="next4k" Source="src\next4k\next4k.vcproj" Description="MSB8012: $(TargetName) ('next4k') does not match the Linker's OutputFile property value 'E:\Private\Frank\Code\blu-flame.org\bp4k\bin\next4k_Release.exe' ('next4k_Release') in project configuration 'Release|Win32'. This may cause your project to build incorrectly. To correct this, please make sure that $(TargetName) property value matches the value specified in %(Link.OutputFile).">
</Event><Event ErrorLevel="1" Project="next4k" Source="src\next4k\next4k.vcproj" Description="MSB8012: $(TargetPath) ('E:\Private\Frank\Code\blu-flame.org\bp4k\bin\next4k.exe') does not match the Linker's OutputFile property value 'E:\Private\Frank\Code\blu-flame.org\bp4k\bin\next4k_Release.exe' ('E:\Private\Frank\Code\blu-flame.org\bp4k\bin\next4k_Release.exe') in project configuration 'Release|Win32'. This may cause your project to build incorrectly. To correct this, please make sure that $(TargetPath) property value matches the value specified in %(Link.OutputFile).">
</Event><Event ErrorLevel="1" Project="next4k" Source="src\next4k\next4k.vcproj" Description="MSB8012: $(TargetName) ('next4k') does not match the Linker's OutputFile property value 'E:\Private\Frank\Code\blu-flame.org\bp4k\bin\next4k_Compress (Slow).exe' ('next4k_Compress (Slow)') in project configuration 'Compress (Slow)|Win32'. This may cause your project to build incorrectly. To correct this, please make sure that $(TargetName) property value matches the value specified in %(Link.OutputFile).">
</Event><Event ErrorLevel="1" Project="next4k" Source="src\next4k\next4k.vcproj" Description="MSB8012: $(TargetPath) ('E:\Private\Frank\Code\blu-flame.org\bp4k\bin\next4k.exe') does not match the Linker's OutputFile property value 'E:\Private\Frank\Code\blu-flame.org\bp4k\bin\next4k_Compress (Slow).exe' ('E:\Private\Frank\Code\blu-flame.org\bp4k\bin\next4k_Compress (Slow).exe') in project configuration 'Compress (Slow)|Win32'. This may cause your project to build incorrectly. To correct this, please make sure that $(TargetPath) property value matches the value specified in %(Link.OutputFile).">
</Event><Event ErrorLevel="0" Project="next4k" Source="src\next4k\next4k.vcproj" Description="Done converting to new project file 'E:\Private\Frank\Code\blu-flame.org\bp4k\src\next4k\next4k.vcxproj'.">
</Event><Event ErrorLevel="3" Project="next4k" Source="src\next4k\next4k.vcproj" Description="Converted">
</Event><Event ErrorLevel="0" Project="4slang" Source="src\4slang\4slang.vcproj" Description="Converting project file 'E:\Private\Frank\Code\blu-flame.org\bp4k\src\4slang\4slang.vcproj'.">
</Event><Event ErrorLevel="1" Project="4slang" Source="src\4slang\4slang.vcproj" Description="VCWebServiceProxyGeneratorTool is no longer supported. The tool has been removed from your project settings.">
</Event><Event ErrorLevel="0" Project="4slang" Source="src\4slang\4slang.vcproj" Description="Done converting to new project file 'E:\Private\Frank\Code\blu-flame.org\bp4k\src\4slang\4slang.vcxproj'.">
</Event><Event ErrorLevel="3" Project="4slang" Source="src\4slang\4slang.vcproj" Description="Converted">
</Event><Event ErrorLevel="0" Project="flightsim" Source="src\flightsim\flightsim.vcproj" Description="Converting project file 'E:\Private\Frank\Code\blu-flame.org\bp4k\src\flightsim\flightsim.vcproj'.">
</Event><Event ErrorLevel="1" Project="flightsim" Source="src\flightsim\flightsim.vcproj" Description="VCWebServiceProxyGeneratorTool is no longer supported. The tool has been removed from your project settings.">
</Event><Event ErrorLevel="1" Project="flightsim" Source="src\flightsim\flightsim.vcproj" Description="MSB8012: $(TargetName) ('flightsim') does not match the Linker's OutputFile property value 'E:\Private\Frank\Code\blu-flame.org\bp4k\bin\flightsim_Debug.exe' ('flightsim_Debug') in project configuration 'Debug|Win32'. This may cause your project to build incorrectly. To correct this, please make sure that $(TargetName) property value matches the value specified in %(Link.OutputFile).">
</Event><Event ErrorLevel="1" Project="flightsim" Source="src\flightsim\flightsim.vcproj" Description="MSB8012: $(TargetPath) ('E:\Private\Frank\Code\blu-flame.org\bp4k\bin\flightsim.exe') does not match the Linker's OutputFile property value 'E:\Private\Frank\Code\blu-flame.org\bp4k\bin\flightsim_Debug.exe' ('E:\Private\Frank\Code\blu-flame.org\bp4k\bin\flightsim_Debug.exe') in project configuration 'Debug|Win32'. This may cause your project to build incorrectly. To correct this, please make sure that $(TargetPath) property value matches the value specified in %(Link.OutputFile).">
</Event><Event ErrorLevel="1" Project="flightsim" Source="src\flightsim\flightsim.vcproj" Description="MSB8012: $(TargetName) ('flightsim') does not match the Linker's OutputFile property value 'E:\Private\Frank\Code\blu-flame.org\bp4k\bin\flightsim_Release.exe' ('flightsim_Release') in project configuration 'Release|Win32'. This may cause your project to build incorrectly. To correct this, please make sure that $(TargetName) property value matches the value specified in %(Link.OutputFile).">
</Event><Event ErrorLevel="1" Project="flightsim" Source="src\flightsim\flightsim.vcproj" Description="MSB8012: $(TargetPath) ('E:\Private\Frank\Code\blu-flame.org\bp4k\bin\flightsim.exe') does not match the Linker's OutputFile property value 'E:\Private\Frank\Code\blu-flame.org\bp4k\bin\flightsim_Release.exe' ('E:\Private\Frank\Code\blu-flame.org\bp4k\bin\flightsim_Release.exe') in project configuration 'Release|Win32'. This may cause your project to build incorrectly. To correct this, please make sure that $(TargetPath) property value matches the value specified in %(Link.OutputFile).">
</Event><Event ErrorLevel="0" Project="flightsim" Source="src\flightsim\flightsim.vcproj" Description="Done converting to new project file 'E:\Private\Frank\Code\blu-flame.org\bp4k\src\flightsim\flightsim.vcxproj'.">
</Event><Event ErrorLevel="3" Project="flightsim" Source="src\flightsim\flightsim.vcproj" Description="Converted">
</Event><Event ErrorLevel="0" Project="" Source="bp4k.sln" Description="Solution converted successfully">
</Event><Event ErrorLevel="3" Project="" Source="bp4k.sln" Description="Converted">
</Event></UpgradeLog>

BIN
bp4k/bp4k.ncb Normal file

Binary file not shown.

45
bp4k/bp4k.sln Normal file
View File

@@ -0,0 +1,45 @@
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "bp4k", "src\bp4k\bp4k.vcxproj", "{213903DE-E40A-4D23-9310-E520AC2B412E}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "next4k", "src\next4k\next4k.vcxproj", "{B0E00917-3ED1-460E-9ADE-7F2AE0A3C93C}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "4slang", "src\4slang\4slang.vcxproj", "{E0A366EF-1805-44C7-B644-426FEE32B9D9}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "flightsim", "src\flightsim\flightsim.vcxproj", "{EAA2A155-BC7B-4DE4-98DA-4574A06F2772}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Compress (Slow)|Win32 = Compress (Slow)|Win32
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{213903DE-E40A-4D23-9310-E520AC2B412E}.Compress (Slow)|Win32.ActiveCfg = Compress (Slow)|Win32
{213903DE-E40A-4D23-9310-E520AC2B412E}.Compress (Slow)|Win32.Build.0 = Compress (Slow)|Win32
{213903DE-E40A-4D23-9310-E520AC2B412E}.Debug|Win32.ActiveCfg = Debug|Win32
{213903DE-E40A-4D23-9310-E520AC2B412E}.Debug|Win32.Build.0 = Debug|Win32
{213903DE-E40A-4D23-9310-E520AC2B412E}.Release|Win32.ActiveCfg = Release|Win32
{213903DE-E40A-4D23-9310-E520AC2B412E}.Release|Win32.Build.0 = Release|Win32
{B0E00917-3ED1-460E-9ADE-7F2AE0A3C93C}.Compress (Slow)|Win32.ActiveCfg = Compress (Slow)|Win32
{B0E00917-3ED1-460E-9ADE-7F2AE0A3C93C}.Compress (Slow)|Win32.Build.0 = Compress (Slow)|Win32
{B0E00917-3ED1-460E-9ADE-7F2AE0A3C93C}.Debug|Win32.ActiveCfg = Debug|Win32
{B0E00917-3ED1-460E-9ADE-7F2AE0A3C93C}.Debug|Win32.Build.0 = Debug|Win32
{B0E00917-3ED1-460E-9ADE-7F2AE0A3C93C}.Release|Win32.ActiveCfg = Release|Win32
{B0E00917-3ED1-460E-9ADE-7F2AE0A3C93C}.Release|Win32.Build.0 = Release|Win32
{E0A366EF-1805-44C7-B644-426FEE32B9D9}.Compress (Slow)|Win32.ActiveCfg = Debug|Win32
{E0A366EF-1805-44C7-B644-426FEE32B9D9}.Debug|Win32.ActiveCfg = Debug|Win32
{E0A366EF-1805-44C7-B644-426FEE32B9D9}.Debug|Win32.Build.0 = Debug|Win32
{E0A366EF-1805-44C7-B644-426FEE32B9D9}.Release|Win32.ActiveCfg = Debug|Win32
{EAA2A155-BC7B-4DE4-98DA-4574A06F2772}.Compress (Slow)|Win32.ActiveCfg = Release|Win32
{EAA2A155-BC7B-4DE4-98DA-4574A06F2772}.Compress (Slow)|Win32.Build.0 = Release|Win32
{EAA2A155-BC7B-4DE4-98DA-4574A06F2772}.Debug|Win32.ActiveCfg = Debug|Win32
{EAA2A155-BC7B-4DE4-98DA-4574A06F2772}.Debug|Win32.Build.0 = Debug|Win32
{EAA2A155-BC7B-4DE4-98DA-4574A06F2772}.Release|Win32.ActiveCfg = Release|Win32
{EAA2A155-BC7B-4DE4-98DA-4574A06F2772}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

BIN
bp4k/bp4k.suo Normal file

Binary file not shown.

BIN
bp4k/glsl_minifier.exe Normal file

Binary file not shown.

BIN
bp4k/link.exe Normal file

Binary file not shown.

Binary file not shown.

BIN
bp4k/music/valley_ball.4kp Normal file

Binary file not shown.

Binary file not shown.

BIN
bp4k/music/valley_ball.xrns Normal file

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,359 @@
// Time
varying float T;
// Camera data
varying vec3 cameraPos;
// Position of the fragment
varying vec2 Z;
// Forward declarations
vec4 traceRay(vec3, vec3, int);
vec3 shade(vec4, vec3, vec3);
// All data of our world
vec3 lightDir, lightColor, waterColor, ro, rd, interlacing;
float gf_DetailLevel, pi, eps, bigeps;
// Pseudo random number base generator (credits go to iq/rgba)
float rnd(vec2 x)
{
int n = int(x.x * 40 + x.y * 6400);
n = (n << 13) ^ n;
return 1 - float( (n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824;
}
// Generate cubic interpolated random values
float smoothrnd(vec2 x)
{
x = mod(x,1000.0);
vec2 a = fract(x);
x -= a;
vec2 u = a*a*(3.0-2.0*a);
return mix(
mix(rnd(x+vec2(0,0)),rnd(x+vec2(1,0)), u.x),
mix(rnd(x+vec2(0,1)),rnd(x+vec2(1,1)), u.x), u.y);
}
// Convert the cipher range from [-1,1] to [0,1]
float norm(float x)
{
return x * 0.5 + 0.5;
}
// Generate animated (t) caustic values
float caustic(float u, float v, float t)
{
float a = (
norm(sin(pi * 2 * (u + v + T*t))) +
norm(sin(pi * (v - u - T*t))) +
norm(sin(pi * (v + T*t))) +
norm(sin(pi * 3 * (u - T*t)))) * 0.3;
return pow(a, 2.0);
}
// Calculate our TV effects (interlacing, RGB mask and film grain)
vec3 pp(vec3 color)
{
int c = int(mod(gl_FragCoord.x, 3.0));
if (c==0) color *= interlacing.xyz;
if (c==1) color *= interlacing.yzx;
if (c==2) color *= interlacing.zxy;
return mix(color, vec3(norm(smoothrnd(Z * 333 + rnd(vec2(T)) * 33333))), 0.03);
}
// Our fake godray effect (bad if moving fast, but awesome any other time)
vec3 godrays(vec3 color)
{
vec2 dpos = Z*2-1;
float g = dpos.x * (dpos.y + 3);
return color + lightColor *
caustic(g + 50 * ro.x, g + 50 * ro.z, 1.5) *
(norm(dpos.y)) * min(-ro.y * 30, 0.3);
}
// Our heightmap calculation function, we could use some perlin noise here if it wouldn't be so performance killing
float height(vec2 x)
{
return (-0.035 + pow((caustic(x.x * 10, x.y * 10, 0.0) * 2 - 1), 2.0) * 0.05)
- (x.x - 0.1) * 0.2; // This line creates one entire continent and a big ocean!
}
// Gets the terrain normal
vec3 getTerrainNormal(vec3 p)
{
return normalize(vec3(
height(p.xz - vec2(bigeps, 0)) - height(p.xz + vec2(bigeps, 0)),
2 * bigeps,
height(p.xz - vec2(0, bigeps)) - height(p.xz + vec2(0, bigeps))));
}
// Global diffuse lighting formula
vec3 diffuseLight(vec3 incolor, vec3 normal)
{
return (0.3 + 0.7 * max(dot(normal, lightDir), 0.0)) * lightColor * incolor;
}
// Calculates the water "waves". To reduce the bumpiness, increment the y-axis
vec3 getWaterNormal(vec3 p)
{
return normalize(vec3(
caustic(p.x * 160 - cos(p.z * 10) * 12, p.z * 140, 4.0),
8,
caustic(p.z * 160 - sin(p.x * 10) * 12, p.x * 140, 4.0)) * 2 - 1);
}
// Calculate the terrain color for the given voxel
vec3 shadeTerrain(vec3 p, vec3 rd)
{
vec3 n = getTerrainNormal(p);
vec3 color = mix(
// sandy color
vec3(0.66, 0.55, 0.4)
// basic color (big random color spots)
- 0.2 * smoothrnd(abs(p.xz * 150))
// texture (sediment lines)
- 0.2 * smoothrnd(abs(p.yy + 0.002 * smoothrnd(abs(p.xz * 150))) * 3000),
// interleaved grass, hight dependant
vec3(0.1, 0.3, 0) * (smoothrnd(p.xz * 7000.0) * 0.4 + 0.5),
// mixing for the sand/grass transition
clamp(n.y * (caustic(p.x * 111, p.z * 111, 0.0) * 0.5 - p.y * 40), 0.0, 1.0));
// caustics, only underwater (no cloudshadows, though)
if (p.y <= 0)
color += 5 * getWaterNormal(0.8 * p).x * min(0.3, -p.y * 8);
// Light
return diffuseLight(color, n);
}
// Create a blueish sky transition from navy blue to badass dark blue
vec3 shadeSky(vec3 ro, vec3 rd)
{
return ro.y <= -eps*eps ?
waterColor :
mix(vec3(-0.5, -0.25, 0), vec3(2), 1 - (rd.y * 0.5 + 0.5));
}
// Calculates the refraction and reflection of the water surface.
// Also mixes both values by the depth of the water and the fresnel term.
// Possible improvements: fix fake underwater reflection and refraction
vec3 shadeWaterRefl(vec3 p, vec3 newrd)
{
vec3 waterNormal = getWaterNormal(p);
// perform raytracing/raymarching for both reflection and refraction
// calc the water refraction, the refraction index (0.9) will decrease with the distance to allow a better over/under water transition
vec4 refracted = traceRay(p, refract(newrd, waterNormal, 0.9), 2);//mix(0.9, 1.0, smoothstep(0.01, 0.0, length(p-ro)))), 2);
// calculate the depth factor (water entry point to terrain voxel) (black magic involved here!)
float depth = clamp(pow(1.03 * (1 - length(refracted.xyz - p)), 16.0), 0.0, 1.0);
// Finally stir the pot =)
return mix(
ro.y < 0 ? shadeSky(p, newrd) : waterColor, // Water color
mix(
shade(traceRay(p, reflect(newrd, waterNormal), 2), p, newrd), // Reflection color
shade(refracted, p, newrd), // Refraction color
clamp(-rd.y + depth, 0.0, 1.0)), // fresnel term
refracted.w == 3.0 ? 0.5 : pow(depth, 0.5)); // water color contribution
}
// Raymarch the terrain function, returns the distance from the ray origin to the terrain voxel
// This function was originally adopted from an implementation by iq/rgba
float traceTerrain(vec3 ro, vec3 rd, float maxt)
{
float delt, lh, ly, samplePosY;
delt = 0; // If the world would consist of only nVidia GPUs, this line wouldn't exist.
vec3 samplePos = ro;
// advance our sample position from our nearplane to our farplane
for (float t = 0; t < maxt; t += delt)
{
// advance our ray
samplePos += rd * delt;
samplePosY = samplePos.y;
// get the height at the given sample 2d (!) position (we could enhance this by sampling a voxel and returning only the distance to the voxel)
float h = height(samplePos.xz);
if (samplePosY <= h)
{
// we need to know our improved (more accuracy here) real terrainposition and the old sampleposition
// also we precalculate the traveled ray distance (its not a ray anymore if we use stuff like refraction, eg but hey lets stick to this word)
return t - delt + delt*(lh-ly)/(samplePosY-h+lh-ly);
}
// store our last height and last sampleposition on the y-axis
// we need this to calculate the improved terrainposition which will give us a smoother transition between our samplesteps (rd*delt)
lh = h;
ly = samplePosY;
// advance our steplength the more we travel the bigger our stepsize should be
// with this we are able to sample finer details near to our camera
delt = 0.002 + (t/gf_DetailLevel);
}
// we hit nothing
return 9.0;
}
// Ray vs. plane intersection function
float traceWater(vec3 ro, vec3 rd)
{
float tPlane = -ro.y / rd.y;
return tPlane >= eps ? tPlane : 9.0;
}
// Raytracing entry point, returns voxel and object ID
// IDs:
// 0 = sky (not the armageddon, xTr1m!!)
// 1 = terrain
// 2 = water
vec4 traceRay(vec3 ro, vec3 rd, int ignore)
{
float water, terrain, minDist;
// trace only the objects we need (only one could maximally be ignored)
water = ignore != 2 ? traceWater(ro, rd) : 9.0;
terrain = ignore != 1 ? traceTerrain(ro, rd, min(0.5, 0.002 + water)) : 9.0;
// auto detail level reducing (common dude, give the GPU some breathing room)
gf_DetailLevel *= 0.75;
// find the nearest distance
minDist = min(terrain, min(water, 9.0));
// we hit nothing or the hitpoint is too far
if (minDist == 9)
return vec4(0);
// calculate the hit/voxel position
vec3 hitPos = ro + rd * minDist;
// check what we might have hit
if (minDist == terrain)
return vec4(hitPos, 1);
if (minDist == water)
return vec4(hitPos, 2);
// Panic, worry, die to death! Probably we'll land on the moon (this should never happen)
//return vec4(0);
}
// Entrypoint for color calculation
vec3 shadeRefl(vec4 hitPoint, vec3 newRo, vec3 rd)
{
// determine the fog color for this very precise point in the space time continuum
vec3 myFog = newRo.y < eps ? waterColor : shadeSky(ro, rd);
// generate the distance value for the fog calculation
float distance = clamp(length(hitPoint.xyz - newRo) * (ro.y <= 0 ? 4 : 2), 0.0, 1.0);
// get the color of the hit object and mix it with the fog
// in most cases we allow further raytracing here (not for the terrain, its not shiny enough)
if (hitPoint.w == 1)
return mix(shadeTerrain(hitPoint.xyz, rd), myFog, distance);
if (hitPoint.w == 2)
return mix(shadeWaterRefl(hitPoint.xyz, rd), myFog, distance);
return shadeSky(newRo, rd);
}
// Get the color from the object we just hit (without further raytraces)
// this is necessary because no recursion is allowed in GLSL (damn you!)
vec3 shade(vec4 hitPoint, vec3 newRo, vec3 rd)
{
// determine the fog color for the very same point we discussed earlier
vec3 myFog = newRo.y < eps ? waterColor : shadeSky(ro, rd);
// generate the other distance value. Paid attention? If you don't know what value I'm talking about, rtfm or gtfo.
float distance = clamp(length(hitPoint.xyz - newRo) * (ro.y <= 0 ? 4 : 2), 0.0, 1.0);
// get the color of the hit object and mix it with the fog
if (hitPoint.w == 1)
return mix(shadeTerrain(hitPoint.xyz, rd), myFog, distance);
if (hitPoint.w == 2)
return mix(waterColor, myFog, distance);
return myFog;
}
// Now we're just being copycats. We're not creative enough to define own entry points
// Sure, we could "#define MYENTRYPOINT main"! Or just void main(){MyEntryPoint();}
// None of that would help us win the compo, would it?
void main()
{
// Set the quality setting for the raymarcher, a higher value results in a longer processing time
// try to find a good balance between these two, low values will result in a wobbling endresult
// low quality = 50.0 (visual results are ok at 640x480)
// mid quality = 100.0
// high quality = 200.0
gf_DetailLevel = 200;
// Give our saviour global variables some life!
pi = 3.1416;
interlacing = vec3(1.2, 0.9, 0.9);
eps = 0.0001;
bigeps = 0.01;
// Get the look direction for the current pixel (always look forwards)
ro = cameraPos; //set ray origin
if (ro.y < height(ro.xz) + 0.01f)
{
ro.y = height(ro.xz) + 0.01f;
}
rd = vec3(gl_ModelViewMatrix * vec4((Z.xy - 0.5), 1, 1));
// Make our world pretty and worthy to live in (you can cultivate algae and eat them, they're surely enough for survival)
lightDir = vec3(0.58, 0.58, -0.58);
lightColor = vec3(1.2);
waterColor = vec3(0.3, 0.33, 0.4);
// Our GPU feels good underwater, almost like a refreshing experience :) cool, eh?
if (ro.y <= 0)
{
// Less work to do...
gf_DetailLevel *= 0.75;
// ...and a cozy darker atmosphere
lightColor *= 0.8;
}
// Here we go, shoot'em rays and get the color of our fragment!
vec3 color = shadeRefl(traceRay(ro, rd, 0), ro, rd);
// Underwater there are beams of light emanating from god (so called "god" rays...)
// ...this prooves that god is nothing less than a water surface.
if (ro.y <= 0)
color = godrays(color);
// Apply post processing and fade effects to the color, and finally return it.
gl_FragColor.xyz = pp(color);
}

View File

@@ -0,0 +1,11 @@
varying float T;
varying vec2 Z;
varying vec3 cameraPos;
void main()
{
T = gl_Color.x;
Z = (gl_Vertex.xy*vec2(gl_Color.y,1.0))*0.5+0.5;
cameraPos = gl_Normal.xyz;
gl_Position = gl_Vertex;
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,255 @@
// Useful functions for the DEBUG configuration
#include "Shaders.h"
#ifdef _DEBUG
PFNGLCREATESHADERPROC glCreateShader = NULL;
PFNGLSHADERSOURCEPROC glShaderSource = NULL;
PFNGLCOMPILESHADERPROC glCompileShader = NULL;
PFNGLGETSHADERIVPROC glGetShaderiv = NULL;
PFNGLGETPROGRAMIVPROC glGetProgramiv = NULL;
PFNGLCREATEPROGRAMPROC glCreateProgram = NULL;
PFNGLATTACHSHADERPROC glAttachShader = NULL;
PFNGLLINKPROGRAMPROC glLinkProgram = NULL;
PFNGLUSEPROGRAMPROC glUseProgram = NULL;
PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog = NULL;
PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog = NULL;
void useProgram(GLhandleARB ah_Program)
{
glUseProgram(ah_Program);
}
void initShaders()
{
glCreateShader = (PFNGLCREATESHADERPROC)myGetProcAddress("glCreateShader");
glShaderSource = (PFNGLSHADERSOURCEPROC)myGetProcAddress("glShaderSource");
glCompileShader = (PFNGLCOMPILESHADERPROC)myGetProcAddress("glCompileShader");
glGetShaderiv = (PFNGLGETSHADERIVPROC)myGetProcAddress("glGetShaderiv");
glGetProgramiv = (PFNGLGETPROGRAMIVPROC)myGetProcAddress("glGetProgramiv");
glCreateProgram = (PFNGLCREATEPROGRAMPROC)myGetProcAddress("glCreateProgram");
glAttachShader = (PFNGLATTACHSHADERPROC)myGetProcAddress("glAttachShader");
glLinkProgram = (PFNGLLINKPROGRAMPROC)myGetProcAddress("glLinkProgram");
glUseProgram = (PFNGLUSEPROGRAMPROC)myGetProcAddress("glUseProgram");
glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)myGetProcAddress("glGetShaderInfoLog");
glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)myGetProcAddress("glGetProgramInfoLog");
if (!(glCreateShader && glShaderSource && glCompileShader && glGetShaderiv && glGetProgramiv && glCreateProgram && glAttachShader && glLinkProgram && glUseProgram && glGetShaderInfoLog && glGetProgramInfoLog))
{
std::cerr << "Some shader functions are not available!" << std::endl;
}
}
void PrintErrors()
{
GLenum lr_Error = GL_NO_ERROR;
int li_ErrorCount = 5;
do
{
lr_Error = glGetError();
if (lr_Error != GL_NO_ERROR)
{
li_ErrorCount--;
char* ls_ErrorString = (char*)gluErrorString(lr_Error);
if (ls_ErrorString != 0)
std::cout << "OPENGL :: ERROR " << ls_ErrorString << std::endl;
}
if (li_ErrorCount == 0)
{
std::cout << "OPENGL :: ERROR Too many errors!" << std::endl;
break;
}
} while (lr_Error != GL_NO_ERROR);
}
GLhandleARB createVertexShader(const char* as_FileName)
{
GLhandleARB lh_Shader = 0;
char* ls_ShaderSource = textFileRead(as_FileName);
if (ls_ShaderSource == NULL)
{
std::cerr << "Error reading file: " << as_FileName << std::endl;
return lh_Shader;
}
lh_Shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(lh_Shader, 1, (const char**)&ls_ShaderSource, NULL);
glCompileShader(lh_Shader);
free(ls_ShaderSource);
int li_Status = 0;
glGetShaderiv(lh_Shader, GL_COMPILE_STATUS, &li_Status);
if (li_Status == GL_FALSE)
{
std::cerr << "Error compiling vertex shader: " << as_FileName << std::endl;
printShaderInfoLog(lh_Shader);
}
return lh_Shader;
}
GLhandleARB createFragmentShader(const char* as_FileName)
{
GLhandleARB lh_Shader = 0;
char* ls_ShaderSource = textFileRead(as_FileName);
if (ls_ShaderSource == NULL)
{
std::cerr << "Error reading file: " << as_FileName << std::endl;
return lh_Shader;
}
lh_Shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(lh_Shader, 1, (const char**)&ls_ShaderSource, NULL);
glCompileShader(lh_Shader);
int li_Status = 0;
glGetShaderiv(lh_Shader, GL_COMPILE_STATUS, &li_Status);
if (li_Status == GL_FALSE)
{
std::cerr << "Error compiling fragment shader: " << as_FileName << std::endl;
printShaderInfoLog(lh_Shader);
}
free(ls_ShaderSource);
return lh_Shader;
}
GLhandleARB createProgram(GLhandleARB ah_VertexShader, GLhandleARB ah_FragmentShader)
{
GLhandleARB lh_Program = 0;
if (ah_VertexShader + ah_FragmentShader <= 1)
{
std::cerr << "Cannot create program." << std::endl;
return lh_Program;
}
lh_Program = glCreateProgram();
glAttachShader(lh_Program, ah_VertexShader);
glAttachShader(lh_Program, ah_FragmentShader);
glLinkProgram(lh_Program);
int li_Status = 0;
glGetProgramiv(lh_Program, GL_LINK_STATUS, &li_Status);
if (li_Status == GL_FALSE)
{
std::cerr << "Error linking shaders." << std::endl;
printProgramInfoLog(lh_Program);
}
return lh_Program;
}
char* textFileRead(const char* as_FileName)
{
FILE* lh_File;
char* ls_Content = NULL;
size_t li_Count = 0;
if (as_FileName != NULL)
{
fopen_s(&lh_File, as_FileName, "rt");
if (lh_File != NULL)
{
fseek(lh_File, 0, SEEK_END);
li_Count = ftell(lh_File);
rewind(lh_File);
if (li_Count > 0)
{
ls_Content = (char*) malloc(sizeof(char) * (li_Count + 1));
li_Count = fread(ls_Content, sizeof(char), li_Count, lh_File);
ls_Content[li_Count] = '\0';
}
fclose(lh_File);
}
}
return ls_Content;
}
void printShaderInfoLog(GLhandleARB ah_Shader)
{
int li_InfologLength = 0;
int li_CharsWritten = 0;
char* li_InfoLog;
glGetShaderiv(ah_Shader, GL_INFO_LOG_LENGTH, &li_InfologLength);
if (li_InfologLength > 0)
{
li_InfoLog = (char*) malloc(li_InfologLength);
glGetShaderInfoLog(ah_Shader, li_InfologLength, &li_CharsWritten, li_InfoLog);
std::cerr << li_InfoLog << std::endl;
free(li_InfoLog);
}
}
void printProgramInfoLog(GLhandleARB ah_Program)
{
int li_InfologLength = 0;
int li_CharsWritten = 0;
char* ls_InfoLog;
glGetProgramiv(ah_Program, GL_INFO_LOG_LENGTH, &li_InfologLength);
if (li_InfologLength > 0)
{
ls_InfoLog = (char *)malloc(li_InfologLength);
glGetProgramInfoLog(ah_Program, li_InfologLength, &li_CharsWritten, ls_InfoLog);
std::cerr << ls_InfoLog << std::endl;
free(ls_InfoLog);
}
}
bool printShaderStatistics()
{
if (GL_VERSION_2_1) std::cout << "Supports OpenGL 2.1. " << std::endl;
else if (GL_VERSION_2_0) std::cout << "Supports OpenGL 2.0. " << std::endl;
else if (GL_VERSION_1_5) std::cout << "Supports OpenGL 1.5. " << std::endl;
else if (GL_VERSION_1_4) std::cout << "Supports OpenGL 1.4. " << std::endl;
else if (GL_VERSION_1_3) std::cout << "Supports OpenGL 1.3. " << std::endl;
else if (GL_VERSION_1_2) std::cout << "Supports OpenGL 1.2. " << std::endl;
else if (GL_VERSION_1_1) std::cout << "Supports OpenGL 1.1. " << std::endl;
if (GL_ARB_shader_objects && GL_ARB_vertex_shader && GL_ARB_fragment_shader)
{
std::cout << "Status: Using GLSL " << glGetString(GL_SHADING_LANGUAGE_VERSION_ARB) << std::endl;
}
else
{
std::cerr << "No GLSL support!" << std::endl;
return false;
}
return true;
}
#endif

View File

@@ -0,0 +1,20 @@
// Useful functions for the DEBUG configuration
#pragma once
#include <windows.h>
#include <iostream>
#include <GL/gl.h>
#include <GL/glu.h>
#include "glext.h"
#define myGetProcAddress(name) wglGetProcAddress((LPCSTR)name)
void initShaders();
GLhandleARB createVertexShader(const char* as_FileName);
GLhandleARB createFragmentShader(const char* as_FileName);
GLhandleARB createProgram(GLhandleARB ah_VertexShader, GLhandleARB ah_FragmentShader);
void PrintErrors();
void useProgram(GLhandleARB ah_Program);
char* textFileRead(const char* as_FileName);
void printShaderInfoLog(GLhandleARB ah_Shader);
void printProgramInfoLog(GLhandleARB ah_Program);
bool printShaderStatistics();

View File

@@ -0,0 +1,365 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9,00"
Name="bp4k"
ProjectGUID="{213903DE-E40A-4D23-9310-E520AC2B412E}"
RootNamespace="bp4k"
Keyword="Win32Proj"
TargetFrameworkVersion="196613"
>
<Platforms>
<Platform
Name="Win32"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(SolutionDir)obj\$(ProjectName)_$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="0"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="3"
UsePrecompiledHeader="0"
WarningLevel="3"
DebugInformationFormat="4"
CallingConvention="2"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="opengl32.lib winmm.lib glu32.lib"
OutputFile="$(OutDir)\$(ProjectName)_$(ConfigurationName).exe"
LinkIncremental="2"
AdditionalLibraryDirectories="&quot;$(ProjectDir)&quot;"
GenerateDebugInformation="true"
SubSystem="1"
EntryPointSymbol="main"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(SolutionDir)obj\$(ProjectName)_$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="0"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
CommandLine=""
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="1"
EnableIntrinsicFunctions="true"
FavorSizeOrSpeed="2"
WholeProgramOptimization="false"
PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS"
ExceptionHandling="0"
RuntimeLibrary="0"
BufferSecurityCheck="false"
RuntimeTypeInfo="false"
UsePrecompiledHeader="0"
WarningLevel="0"
DebugInformationFormat="3"
CallingConvention="2"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalOptions="/CRINKLER"
AdditionalDependencies="opengl32.lib winmm.lib libcmt.lib"
OutputFile="$(OutDir)\$(ProjectName)_$(ConfigurationName).exe"
AdditionalLibraryDirectories="&quot;$(ProjectDir)&quot;"
GenerateManifest="false"
ManifestFile=""
GenerateDebugInformation="true"
SubSystem="2"
LinkTimeCodeGeneration="0"
EntryPointSymbol="main"
RandomizedBaseAddress="0"
DataExecutionPrevention="0"
TargetMachine="1"
ErrorReporting="0"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Compress (Slow)|Win32"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(SolutionDir)obj\$(ProjectName)_$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="0"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
CommandLine=""
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
AdditionalOptions="/QIfist"
Optimization="1"
EnableIntrinsicFunctions="true"
FavorSizeOrSpeed="2"
WholeProgramOptimization="false"
PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS"
ExceptionHandling="0"
RuntimeLibrary="0"
BufferSecurityCheck="false"
EnableFunctionLevelLinking="false"
FloatingPointModel="2"
RuntimeTypeInfo="false"
UsePrecompiledHeader="0"
WarningLevel="0"
DebugInformationFormat="0"
CallingConvention="2"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalOptions="/CRINKLER /COMPMODE:SLOW /ORDERTRIES:4000 /HASHTRIES:300 /UNSAFEIMPORT /TRUNCATEFLOATS:24 /HASHSIZE:200 /REPORT:report.html /RANGE:opengl32 /PROGRESSGUI /TRANSFORM:CALLS"
AdditionalDependencies="opengl32.lib winmm.lib"
OutputFile="$(OutDir)\$(ProjectName)_$(ConfigurationName).exe"
AdditionalLibraryDirectories="&quot;$(ProjectDir)&quot;"
GenerateManifest="false"
ManifestFile=""
GenerateDebugInformation="false"
SubSystem="2"
LinkTimeCodeGeneration="0"
EntryPointSymbol="main"
RandomizedBaseAddress="0"
DataExecutionPrevention="0"
TargetMachine="1"
ErrorReporting="0"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
>
<File
RelativePath=".\main.cpp"
>
</File>
<File
RelativePath=".\Shaders.cpp"
>
</File>
<File
RelativePath=".\synth.cpp"
>
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
>
<File
RelativePath=".\glext.h"
>
</File>
<File
RelativePath=".\release.h"
>
<FileConfiguration
Name="Release|Win32"
>
<Tool
Name="VCCustomBuildTool"
Description=""
CommandLine=""
AdditionalDependencies=""
Outputs=""
/>
</FileConfiguration>
<FileConfiguration
Name="Compress (Slow)|Win32"
>
<Tool
Name="VCCustomBuildTool"
Description=""
CommandLine=""
AdditionalDependencies=""
Outputs=""
/>
</FileConfiguration>
</File>
<File
RelativePath=".\Shaders.h"
>
</File>
<File
RelativePath=".\small.h"
>
</File>
<File
RelativePath=".\synth.h"
>
</File>
</Filter>
<Filter
Name="Resource Files"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
>
</Filter>
<File
RelativePath=".\4klang.obj"
>
</File>
<File
RelativePath=".\generic.vs"
>
</File>
<File
RelativePath=".\mark.fs"
>
</File>
</Files>
<Globals>
</Globals>
</VisualStudioProject>

View File

@@ -0,0 +1,9 @@
varying vec4 Y;
varying vec2 Z;
void main()
{
Y = gl_Color;
Z = (gl_Vertex.xy*vec2(Y.w,1.0))*0.5+0.5;
gl_Position = gl_Vertex;
}

7271
bp4k/party_pack/src/glext.h Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,162 @@
#ifdef _DEBUG
#include <time.h>
#include <io.h>
#include <process.h>
#include "Shaders.h"
#include "small.h"
#include "synth.h"
#else
#define WIN32_LEAN_AND_MEAN
#define WIN32_EXTRA_LEAN
#include <windows.h>
#include <stdio.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include "glext.h"
#include "small.h"
#include "synth.h"
#include "release.h"
#endif
#pragma data_seg(".vertexshader")
static char* vsh = "varying vec4 Y;varying vec2 Z;void main(){Y=gl_Color;Z=(gl_Vertex.xy*vec2(Y.w,1))*.5+.5;gl_Position=gl_Vertex;}";
#pragma data_seg(".resolutionX")
static const int gi_ScreenWidth = 1368;
#pragma data_seg(".resolutionY")
static const int gi_ScreenHeight = 768;
#pragma data_seg(".aspectratio")
//static const float gf_AspectRatio = 1.3281250000f; // smaller version for 4:3
static const float gf_AspectRatio = 1.7734375000f; // smaller version for 16:9
//static const float gf_AspectRatio = 1.25f; // smaller version for 5:4
//static const float gf_AspectRatio = 1.6015625000f; // smaller version for 16:10
#ifdef _DEBUG
#pragma bss_seg(".debugnothing")
HANDLE gh_ShaderCompileEvent;
static char** gs_LastShader_;
static __time64_t gi_ShaderChangedDate;
static unsigned int gi_ShaderProgram;
static unsigned int gi_LastShaderProgram;
#pragma data_seg(".debuginfo")
static const char* gs_VertexShader = "generic.vs";
static const char* gs_ShaderFile = "mark.fs";
#endif
#pragma data_seg(".pfd")
static const PIXELFORMATDESCRIPTOR pfd={
0, 1, PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, 32, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 8
};
#pragma data_seg(".dms")
static DEVMODE dmScreenSettings={
"",0,0,sizeof(dmScreenSettings),0,DM_PELSWIDTH|DM_PELSHEIGHT,
0,0,0,0,0,0,0,0,0,0,0,0,0,"",0,0,gi_ScreenWidth,gi_ScreenHeight
};
#pragma code_seg(".compile")
__forceinline unsigned int compileShader(const char* vsh, const char* fsh)
{
GLuint s,p;
p = ((PFNGLCREATEPROGRAMPROC)wglGetProcAddress("glCreateProgram"))();
s = ((PFNGLCREATESHADERPROC)(wglGetProcAddress("glCreateShader")))(GL_VERTEX_SHADER);
((PFNGLSHADERSOURCEPROC)wglGetProcAddress("glShaderSource")) (s, 1, &vsh, NULL);
((PFNGLCOMPILESHADERPROC)wglGetProcAddress("glCompileShader"))(s);
((PFNGLATTACHSHADERPROC)wglGetProcAddress("glAttachShader")) (p,s);
s = ((PFNGLCREATESHADERPROC)wglGetProcAddress("glCreateShader"))(GL_FRAGMENT_SHADER);
((PFNGLSHADERSOURCEPROC)wglGetProcAddress("glShaderSource")) (s, 1, &fsh, NULL);
((PFNGLCOMPILESHADERPROC)wglGetProcAddress("glCompileShader"))(s);
((PFNGLATTACHSHADERPROC)wglGetProcAddress("glAttachShader")) (p,s);
((PFNGLLINKPROGRAMPROC)wglGetProcAddress("glLinkProgram"))(p);
((PFNGLUSEPROGRAMPROC)wglGetProcAddress("glUseProgram"))(p);
return p;
}
#ifdef _DEBUG
DWORD WINAPI filemon(void* args)
{
while (true)
{
_finddata_t fdata;
long hfile = _findfirst(gs_ShaderFile, &fdata);
if (hfile != -1)
{
if (fdata.time_write != gi_ShaderChangedDate)
{
gi_ShaderChangedDate = fdata.time_write;
::SetEvent(gh_ShaderCompileEvent);
std::cout << "Shader loaded." << std::endl;
}
_findclose(hfile);
}
::Sleep(100);
}
return 0;
}
#endif
#pragma code_seg(".main")
void _cdecl main()
{
#ifdef _DEBUG
//ChangeDisplaySettings (&dmScreenSettings,CDS_FULLSCREEN);
//HDC hDC = GetDC(CreateWindow("edit", 0, WS_POPUP | WS_VISIBLE | WS_MAXIMIZE, 0, 0, 0, 0, 0, 0, 0, 0));
HDC hDC = GetDC(CreateWindow("static", "Test", WS_EX_APPWINDOW | WS_VISIBLE | WS_SYSMENU, 0, 0, gi_ScreenWidth, gi_ScreenHeight, 0, 0, 0, 0));
SetPixelFormat(hDC, ChoosePixelFormat(hDC, &pfd), &pfd);
wglMakeCurrent(hDC, wglCreateContext(hDC));
initShaders();
gh_ShaderCompileEvent = ::CreateEvent(NULL, FALSE, FALSE, TEXT("WriteEvent"));
SetThreadPriority((HANDLE)CreateThread(0, 0, &filemon, 0, 0, 0), THREAD_PRIORITY_BELOW_NORMAL);
::Sleep(1000);
#else
ChangeDisplaySettings (&dmScreenSettings,CDS_FULLSCREEN);
HDC hDC = GetDC(CreateWindow("edit", 0, WS_POPUP | WS_VISIBLE | WS_MAXIMIZE, 0, 0, 0, 0, 0, 0, 0, 0));
//HDC hDC = GetDC(CreateWindow("static", "Test", WS_EX_APPWINDOW | WS_VISIBLE | WS_SYSMENU, 0, 0, gi_ScreenWidth, gi_ScreenHeight, 0, 0, 0, 0));
SetPixelFormat(hDC, ChoosePixelFormat(hDC, &pfd), &pfd);
wglMakeCurrent(hDC, wglCreateContext(hDC));
compileShader(vsh, fsh);
#endif
#ifdef _DEBUG
if (::WaitForSingleObject(gh_ShaderCompileEvent, 0) == WAIT_OBJECT_0)
{
::Sleep(250);
gi_ShaderProgram = createProgram(createVertexShader(gs_VertexShader), createFragmentShader(gs_ShaderFile));
((PFNGLUSEPROGRAMPROC)wglGetProcAddress("glUseProgram"))(gi_ShaderProgram);
PrintErrors();
}
glColor4f(0,0,0, float(gi_ScreenWidth)/gi_ScreenHeight);
glRectf(-1, -1, 1, 1);
SwapBuffers(hDC);
#endif
InitSound();
ShowCursor(FALSE);
loop:
#ifdef _DEBUG
if (::WaitForSingleObject(gh_ShaderCompileEvent, 0) == WAIT_OBJECT_0)
{
::Sleep(250);
gi_ShaderProgram = createProgram(createVertexShader(gs_VertexShader), createFragmentShader(gs_ShaderFile));
((PFNGLUSEPROGRAMPROC)wglGetProcAddress("glUseProgram"))(gi_ShaderProgram);
PrintErrors();
}
#endif
float lf_Time = get_Time() * 71.0f / 240.0f;
glLoadIdentity();
glRotatef(-90.0f * lf_Time - 90.0f, 0, 1, 0);
glColor4f(get_Envelope(7), lf_Time, get_Envelope(2), gf_AspectRatio);
glRects(-1, -1, 1, 1);
SwapBuffers(hDC);
if (!GetAsyncKeyState(VK_ESCAPE) && lf_Time < 30.0f) goto loop;
ExitProcess(0);
}

462
bp4k/party_pack/src/mark.fs Normal file
View File

@@ -0,0 +1,462 @@
// Parameters from our host
// x: Noise intensity
// y: #sceneid.#scenetime (float)
// z: Snare drum intensity (amiga ball radius gain)
// w: Aspect ratio
varying vec4 Y;
// Position of the fragment
varying vec2 Z;
// Forward declarations
vec4 traceRay(vec3, vec3, int);
vec3 shade(vec4, vec3, vec3);
// All data of our world
vec3 spherePos, lightDir, lightColor, waterColor, ro, rd, interlacing;
float sphereRadius, gf_DetailLevel, pi, eps, bigeps;
// Pseudo random number base generator (credits go to iq/rgba)
float rnd(vec2 x)
{
int n = int(x.x * 40 + x.y * 6400);
n = (n << 13) ^ n;
return 1 - float( (n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824;
}
// Generate cubic interpolated random values
float smoothrnd(vec2 x)
{
x = mod(x,1000.0);
vec2 a = fract(x);
x -= a;
vec2 u = a*a*(3.0-2.0*a);
return mix(
mix(rnd(x+vec2(0,0)),rnd(x+vec2(1,0)), u.x),
mix(rnd(x+vec2(0,1)),rnd(x+vec2(1,1)), u.x), u.y);
}
// Convert the cipher range from [-1,1] to [0,1]
float norm(float x)
{
return x * 0.5 + 0.5;
}
// Generate animated (t) caustic values
float caustic(float u, float v, float t)
{
float a = (
norm(sin(pi * 2 * (u + v + Y.y*t))) +
norm(sin(pi * (v - u - Y.y*t))) +
norm(sin(pi * (v + Y.y*t))) +
norm(sin(pi * 3 * (u - Y.y*t)))) * 0.3;
return pow(a, 2.0);
}
// Calculate our TV effects (interlacing, RGB mask and film grain)
vec3 pp(vec3 color)
{
int c = int(mod(gl_FragCoord.x, 3.0));
if (c==0) color *= interlacing.xyz;
if (c==1) color *= interlacing.yzx;
if (c==2) color *= interlacing.zxy;
return mix(color, vec3(norm(smoothrnd(Z * 333 + rnd(vec2(Y.y)) * 33333))), Y.x * 0.3 + 0.03);
}
// Our fake godray effect (bad if moving fast, but awesome any other time)
vec3 godrays(vec3 color)
{
vec2 dpos = Z*2-1;
float g = dpos.x * (dpos.y + 3);
return color + lightColor *
caustic(g + 50 * ro.x, g + 50 * ro.z, 1.5) *
(norm(dpos.y)) * min(-ro.y * 30, 0.3);
}
// Our heightmap calculation function, we could use some perlin noise here if it wouldn't be so performance killing
float height(vec2 x)
{
return (-0.035 + pow((caustic(x.x * 10, x.y * 10, 0.0) * 2 - 1), 2.0) * 0.05)
- (x.x - 0.1) * 0.2; // This line creates one entire continent and a big ocean!
}
// Gets the terrain normal
vec3 getTerrainNormal(vec3 p)
{
return normalize(vec3(
height(p.xz - vec2(bigeps, 0)) - height(p.xz + vec2(bigeps, 0)),
2 * bigeps,
height(p.xz - vec2(0, bigeps)) - height(p.xz + vec2(0, bigeps))));
}
// Global diffuse lighting formula
vec3 diffuseLight(vec3 incolor, vec3 normal)
{
return (0.3 + 0.7 * max(dot(normal, lightDir), 0.0)) * lightColor * incolor;
}
// Calculates the water "waves". To reduce the bumpiness, increment the y-axis
vec3 getWaterNormal(vec3 p)
{
return normalize(vec3(
caustic(p.x * 160 - cos(p.z * 10) * 12, p.z * 140, 4.0),
8,
caustic(p.z * 160 - sin(p.x * 10) * 12, p.x * 140, 4.0)) * 2 - 1);
}
// Calculate the terrain color for the given voxel
vec3 shadeTerrain(vec3 p, vec3 rd)
{
vec3 n = getTerrainNormal(p);
vec3 color = mix(
// sandy color
vec3(0.66, 0.55, 0.4)
// basic color (big random color spots)
- 0.2 * smoothrnd(abs(p.xz * 150))
// texture (sediment lines)
- 0.2 * smoothrnd(abs(p.yy + 0.002 * smoothrnd(abs(p.xz * 150))) * 3000),
// interleaved grass, hight dependant
vec3(0.1, 0.3, 0) * (smoothrnd(p.xz * 7000.0) * 0.4 + 0.5),
// mixing for the sand/grass transition
clamp(n.y * (caustic(p.x * 111, p.z * 111, 0.0) * 0.5 - p.y * 40), 0.0, 1.0));
// caustics, only underwater (no cloudshadows, though)
if (p.y <= 0)
color += 5 * getWaterNormal(0.8 * p).x * min(0.3, -p.y * 8);
// Light
return diffuseLight(color, n);
}
// Create a blueish sky transition from navy blue to badass dark blue
vec3 shadeSky(vec3 ro, vec3 rd)
{
return ro.y <= -eps*eps ?
waterColor :
mix(vec3(-0.5, -0.25, 0), vec3(2), 1 - (rd.y * 0.5 + 0.5));
}
// Calculates the refraction and reflection of the water surface.
// Also mixes both values by the depth of the water and the fresnel term.
// Possible improvements: fix fake underwater reflection and refraction
vec3 shadeWaterRefl(vec3 p, vec3 newrd)
{
vec3 waterNormal = getWaterNormal(p);
// perform raytracing/raymarching for both reflection and refraction
// calc the water refraction, the refraction index (0.9) will decrease with the distance to allow a better over/under water transition
vec4 refracted = traceRay(p, refract(newrd, waterNormal, 0.9), 2);//mix(0.9, 1.0, smoothstep(0.01, 0.0, length(p-ro)))), 2);
// calculate the depth factor (water entry point to terrain voxel) (black magic involved here!)
float depth = clamp(pow(1.03 * (1 - length(refracted.xyz - p)), 16.0), 0.0, 1.0);
// Finally stir the pot =)
return mix(
ro.y < 0 ? shadeSky(p, newrd) : waterColor, // Water color
mix(
shade(traceRay(p, reflect(newrd, waterNormal), 2), p, newrd), // Reflection color
shade(refracted, p, newrd), // Refraction color
clamp(-rd.y + depth, 0.0, 1.0)), // fresnel term
refracted.w == 3.0 ? 0.5 : pow(depth, 0.5)); // water color contribution
}
// Texture our "AMIGAAAAAAA!!" ball
vec3 shadeAttractor(vec3 p, vec3 rd)
{
vec3 n,color;
// get the sphere normal, first
n = normalize(p - spherePos);
// now calculate the texture coordinates
vec2 uv = 0.5 + 0.5 * vec2(atan(n.z, n.x), acos(n.y)) / pi;
// We'll animate our x-texture coordinate with the time, this gives the impression of a rotating ball
uv.x -= Y.y;
// This spell will convert any dull ball into an amiga ball, caution is advised.
color = mix(vec3(1), vec3(1, 0, 0), mod(step(fract(uv.x * 6), 0.5) + step(fract(uv.y * 6), 0.5), 2.0));
return diffuseLight(color, n)
+ pow(max(dot(n, normalize(lightDir - rd)), 0.0), 33.0) * lightColor; // specular light spot
}
// Raymarch the terrain function, returns the distance from the ray origin to the terrain voxel
// This function was originally adopted from an implementation by iq/rgba
float traceTerrain(vec3 ro, vec3 rd, float maxt)
{
float delt, lh, ly, samplePosY;
delt = 0; // If the world would consist of only nVidia GPUs, this line wouldn't exist.
vec3 samplePos = ro;
// advance our sample position from our nearplane to our farplane
for (float t = 0; t < maxt; t += delt)
{
// advance our ray
samplePos += rd * delt;
samplePosY = samplePos.y;
// get the height at the given sample 2d (!) position (we could enhance this by sampling a voxel and returning only the distance to the voxel)
float h = height(samplePos.xz);
if (samplePosY <= h)
{
// we need to know our improved (more accuracy here) real terrainposition and the old sampleposition
// also we precalculate the traveled ray distance (its not a ray anymore if we use stuff like refraction, eg but hey lets stick to this word)
return t - delt + delt*(lh-ly)/(samplePosY-h+lh-ly);
}
// store our last height and last sampleposition on the y-axis
// we need this to calculate the improved terrainposition which will give us a smoother transition between our samplesteps (rd*delt)
lh = h;
ly = samplePosY;
// advance our steplength the more we travel the bigger our stepsize should be
// with this we are able to sample finer details near to our camera
delt = 0.002 + (t/gf_DetailLevel);
}
// we hit nothing
return 9.0;
}
// Ray vs. sphere intersection function
float traceAttractor(vec3 ro, vec3 rd)
{
vec3 dst = ro - spherePos;
float B,D;
B = dot(dst, rd);
if (B > 0)
return 9.0;
D = B*B - dot(dst, dst) + sphereRadius*sphereRadius;
if (D > 0)
{
return -B - sqrt(D);
}
return 9.0;
}
// Ray vs. plane intersection function
float traceWater(vec3 ro, vec3 rd)
{
float tPlane = -ro.y / rd.y;
return tPlane >= eps ? tPlane : 9.0;
}
// Raytracing entry point, returns voxel and object ID
// IDs:
// 0 = sky (not the armageddon, xTr1m!!)
// 1 = terrain
// 2 = water
// 3 = attractive amiga ball (you have never seen such a sexy amiga ball before, admit it!)
vec4 traceRay(vec3 ro, vec3 rd, int ignore)
{
float water, attractor, terrain, minDist;
// trace only the objects we need (only one could maximally be ignored)
water = ignore != 2 ? traceWater(ro, rd) : 9.0;
attractor = ignore != 3 ? traceAttractor(ro, rd) : 9.0;
terrain = ignore != 1 ? traceTerrain(ro, rd, min(0.5, 0.002+min(water, attractor))) : 9.0;
// auto detail level reducing (common dude, give the GPU some breathing room)
gf_DetailLevel /= 20;
// find the nearest distance
minDist = min(terrain, min(water, min(attractor, 9.0)));
// we hit nothing or the hitpoint is too far
if (minDist == 9)
return vec4(0);
// calculate the hit/voxel position
vec3 hitPos = ro + rd * minDist;
// check what we might have hit
if (minDist == terrain)
return vec4(hitPos, 1);
if (minDist == water)
return vec4(hitPos, 2);
if (minDist == attractor)
return vec4(hitPos, 3);
// Panic, worry, die to death! Probably we'll land on the moon (this should never happen)
//return vec4(0);
}
// Entrypoint for color calculation
vec3 shadeRefl(vec4 hitPoint, vec3 newRo, vec3 rd)
{
// determine the fog color for this very precise point in the space time continuum
vec3 myFog = newRo.y < eps ? waterColor : shadeSky(ro, rd);
// generate the distance value for the fog calculation
float distance = clamp(length(hitPoint.xyz - newRo) * (ro.y <= 0 ? 4 : 2), 0.0, 1.0);
// get the color of the hit object and mix it with the fog
// in most cases we allow further raytracing here (not for the terrain, its not shiny enough)
if (hitPoint.w == 1)
return mix(shadeTerrain(hitPoint.xyz, rd), myFog, distance);
if (hitPoint.w == 2)
return mix(shadeWaterRefl(hitPoint.xyz, rd), myFog, distance);
if (hitPoint.w == 3)
return mix(
// Our amiga ball is shiny so reflect the scene!
mix(shadeAttractor(hitPoint.xyz, rd), shade(traceRay(hitPoint.xyz, reflect(rd, normalize(hitPoint.xyz - spherePos)), 3), hitPoint.xyz, rd), 0.5)
, myFog, distance);
return shadeSky(newRo, rd);
}
// Get the color from the object we just hit (without further raytraces)
// this is necessary because no recursion is allowed in GLSL (damn you!)
vec3 shade(vec4 hitPoint, vec3 newRo, vec3 rd)
{
// determine the fog color for the very same point we discussed earlier
vec3 myFog = newRo.y < eps ? waterColor : shadeSky(ro, rd);
// generate the other distance value. Paid attention? If you don't know what value I'm talking about, rtfm or gtfo.
float distance = clamp(length(hitPoint.xyz - newRo) * (ro.y <= 0 ? 4 : 2), 0.0, 1.0);
// get the color of the hit object and mix it with the fog
if (hitPoint.w == 1)
return mix(shadeTerrain(hitPoint.xyz, rd), myFog, distance);
if (hitPoint.w == 2)
return mix(waterColor, myFog, distance);
if (hitPoint.w == 3)
return mix(shadeAttractor(hitPoint.xyz, rd), myFog, distance);
return myFog;
}
// Now we're just being copycats. We're not creative enough to define own entry points
// Sure, we could "#define MYENTRYPOINT main"! Or just void main(){MyEntryPoint();}
// None of that would help us win the compo, would it?
void main()
{
// Set the quality setting for the raymarcher, a higher value results in a longer processing time
// try to find a good balance between these two, low values will result in a wobbling endresult
// low quality = 50.0 (visual results are ok at 640x480)
// mid quality = 100.0
// high quality = 200.0
gf_DetailLevel = 100;
// Give our saviour global variables some life!
pi = 3.1416;
interlacing = vec3(1.2, 0.9, 0.9);
eps = 0.0001;
bigeps = 0.01;
// Nifty random number generator gets initialized
float seed = 10;
// Determine the scene we're in
int scene = int(Y.y);
// Get the look direction for the current pixel (always look forwards)
rd = vec3((Z.xy - 0.5), 1);
// Merry-go-round on a boat (yeah, this makes no sense. Go watch the intro and see for yourself)
if (scene > 22 && scene < 27)
{
seed = min(1.0, sin((Y.y-23)*pi*0.25)*12);
ro = vec3(0.12, 0.005, Y.y*0.08);
rd = vec3(gl_ModelViewMatrix * vec4(rd, 1));
rd.y += 0.1*cos(Y.y*4);
}
// Intermezzo: Dolphin like animation inside and outside the water, chasing that amiga ball!
else if (scene > 14 && scene < 23)
{
seed = min(1.0, sin((Y.y-15)*pi*0.125)*24);
rd += vec3(0,0.1*cos(Y.y*4), 0);
ro = vec3(0.08, 0.01*sin(Y.y*4)+0.002, Y.y*0.11);
}
// Intro and Outro: Show still scenes
else
{
// Get a random initial position for our camera
ro = vec3(0.1,0.004,0.0) + vec3(0.1,0.005,20)
*vec3(rnd(vec2(scene, seed++)), rnd(vec2(scene, seed++)), rnd(vec2(scene, seed++)));
// Basing on the initial position, choose some "random" start and end points nearby
ro = mix(
ro+vec3(0.008)*vec3(rnd(vec2(scene, seed++)), rnd(vec2(scene, seed++)), rnd(vec2(scene, seed++))),
ro+vec3(0.008)*vec3(rnd(vec2(scene, seed++)), rnd(vec2(scene, seed++)), rnd(vec2(scene, seed++))),
// and move the camera!
Y.y-scene);
// We adjust the height of the camera to the terrain height
ro.y += height(ro.xz)+0.02;
// Deviate the camera position in the direction of the normal of the underlying terrain
ro += 0.02*getTerrainNormal(ro);
// Reusing a float variable here, this controls the scene fade in / fade out animation
seed = min(1.0, step(-28.0, -Y.y) * sin((Y.y-scene)*pi)*3);
}
rd = normalize(rd);
// Now boot the amiga workbench (erm, no...)
// mantain a relative distance to the camera
if (scene > 22 && scene < 27)
spherePos = ro + 0.1 * vec3(gl_ModelViewMatrix * vec4(0, 0, 1, 1));
else
spherePos = ro + 0.02 * vec3(sin(Y.y), 0, 5+cos(Y.y));
spherePos.y += 0.01 + height(spherePos.xz); // mantain a relative height to the underlying terrain
sphereRadius = scene < 14 ? 0.0 : bigeps * 0.5 + bigeps * Y.z; // The amiga ball is bigger when the snare drum is hit!
spherePos += 2*sphereRadius * getTerrainNormal(spherePos); // deviate according to the underlying terrain's normal
// Make our world pretty and worthy to live in (you can cultivate algae and eat them, they're surely enough for survival)
lightDir = vec3(0.58, 0.58, -0.58);
lightColor = vec3(1.2);
waterColor = vec3(0.3, 0.33, 0.4);
// Our GPU feels good underwater, almost like a refreshing experience :) cool, eh?
if (ro.y <= 0)
{
// Less work to do...
gf_DetailLevel *= 0.75;
// ...and a cozy darker atmosphere
lightColor *= 0.8;
}
// Here we go, shoot'em rays and get the color of our fragment!
vec3 color = shadeRefl(traceRay(ro, rd, 0), ro, rd);
// Underwater there are beams of light emanating from god (so called "god" rays...)
// ...this prooves that god is nothing less than a water surface.
if (ro.y <= 0)
color = godrays(color);
// Apply post processing and fade effects to the color, and finally return it.
gl_FragColor.xyz = pp(step(2.0, Y.y) * seed * color);
}

View File

@@ -0,0 +1,194 @@
// 4slang v0.1 by Blu-Flame
// This always generated file is a compressed version of:
// mark.fs
#pragma once
#pragma data_seg(".shaders")
static char* fsh =
"#define ve return\n" // Line 1
"#define ec float\n" // Line 1
"varying vec4 Y;" // Line 6
"varying vec2 Z;" // Line 9
"vec4 R(vec3 n,vec3 m,int k);" // Line 12
"vec3 T(vec4 j,vec3 l,vec3 m);" // Line 13
"vec3 f,b,a,h,e,d,X;" // Line 17
"ec g,W,c,V,U;ec A(vec2 j){" // Line 18
"int i=int(j.x*40+j.y*6400);" // Line 24
"i=(i<<13)^i;" // Line 25
"ve 1-ec((i*(i*i*15731+789221)+1376312589)&0x7fffffff)/1073741824;}ec B(vec2 k){" // Line 26
"k=mod(k,1000.);" // Line 33
"vec2 i=fract(k);" // Line 34
"k-=i;" // Line 35
"vec2 j=i*i*(3.-2.*i);" // Line 36
"ve mix(" // Line 37
"mix(A(k+vec2(0,0)),A(k+vec2(1,0)),j.x)," // Line 38
"mix(A(k+vec2(0,1)),A(k+vec2(1,1)),j.x),j.y);}ec C(ec i){" // Line 39
"ve i*.5+.5;}ec D(ec k,ec l,ec j){" // Line 46
"ec i=(" // Line 53
"C(sin(c*2*(k+l+Y.y*j)))+" // Line 54
"C(sin(c*(l-k-Y.y*j)))+" // Line 55
"C(sin(c*(l+Y.y*j)))+" // Line 56
"C(sin(c*3*(k-Y.y*j))))*.3;" // Line 57
"ve pow(i,2.);}vec3 E(vec3 j){" // Line 58
"int i=int(mod(gl_FragCoord.x,3.));" // Line 65
"if(i==0)j*=X.xyz;" // Line 66
"if(i==1)j*=X.yzx;" // Line 67
"if(i==2)j*=X.zxy;" // Line 68
"ve mix(j,vec3(C(B(Z*333+A(vec2(Y.y))*33333))),Y.x*.3+.03);}vec3 F(vec3 i){" // Line 69
"vec2 j=Z*2-1;" // Line 76
"ec k=j.x*(j.y+3);" // Line 77
"ve i+a*" // Line 78
"D(k+50*e.x,k+50*e.z,1.5)*" // Line 79
"(C(j.y))*min(-e.y*30,.3);}ec G(vec2 i){" // Line 80
"ve (-.035+pow((D(i.x*10,i.y*10,.0)*2-1),2.)*.05)" // Line 87
"-(i.x-.1)*.2;}vec3 H(vec3 i){" // Line 88
"ve normalize(vec3(" // Line 95
"G(i.xz-vec2(U,0))-G(i.xz+vec2(U,0))," // Line 96
"2*U," // Line 97
"G(i.xz-vec2(0,U))-G(i.xz+vec2(0,U))));}vec3 I(vec3 i,vec3 j){" // Line 98
"ve (.3+.7*max(dot(j,b),.0))*a*i;}vec3 J(vec3 i){" // Line 105
"ve normalize(vec3(" // Line 112
"D(i.x*160-cos(i.z*10)*12,i.z*140,4.)," // Line 113
"8," // Line 114
"D(i.z*160-sin(i.x*10)*12,i.x*140,4.))*2-1);}vec3 K(vec3 k,vec3 l){" // Line 115
"vec3 j=H(k);" // Line 122
"vec3 i=mix(" // Line 123
"vec3(.66,.55,.4)" // Line 125
"-.2*B(abs(k.xz*150))" // Line 128
"-.2*B(abs(k.yy+.002*B(abs(k.xz*150)))*3000)," // Line 131
"vec3(.1,.3,0)*(B(k.xz*7000.)*.4+.5)," // Line 134
"clamp(j.y*(D(k.x*111,k.z*111,.0)*.5-k.y*40),.0,1.));" // Line 137
"if(k.y<=0)" // Line 140
"i+=5*J(.8*k).x*min(.3,-k.y*8);" // Line 141
"ve I(i,j);}vec3 L(vec3 j,vec3 i){" // Line 144
"ve j.y<=-V*V?" // Line 151
"h:" // Line 152
"mix(vec3(-.5,-.25,0),vec3(2),1-(i.y*.5+.5));}vec3 M(vec3 k,vec3 j){" // Line 153
"vec3 m=J(k);" // Line 162
"vec4 l=R(k,refract(j,m,.9),2);" // Line 166
"ec i=clamp(pow(1.03*(1-length(l.xyz-k)),16.),.0,1.);" // Line 169
"ve mix(" // Line 172
"e.y<0?L(k,j):h," // Line 173
"mix(" // Line 174
"T(R(k,reflect(j,m),2),k,j)," // Line 175
"T(l,k,j)," // Line 176
"clamp(-d.y+i,.0,1.))," // Line 177
"l.w==3.?.5:pow(i,.5));}vec3 N(vec3 k,vec3 l){" // Line 178
"vec3 j,i;" // Line 186
"j=normalize(k-f);" // Line 189
"vec2 m=.5+.5*vec2(atan(j.z,j.x),acos(j.y))/c;" // Line 192
"m.x-=Y.y;" // Line 195
"i=mix(vec3(1),vec3(1,0,0),mod(step(fract(m.x*6),.5)+step(fract(m.y*6),.5),2.));" // Line 198
"ve I(i,j)" // Line 200
"+pow(max(dot(j,normalize(b-l)),.0),33.)*a;}ec O(vec3 n,vec3 m,ec l){" // Line 201
"ec i,j,k,p;" // Line 209
"i=0;" // Line 210
"vec3 o=n;" // Line 211
"for(ec q=0;q<l;q+=i)" // Line 214
"{" // Line 215
"o+=m*i;" // Line 217
"p=o.y;" // Line 218
"ec r=G(o.xz);" // Line 221
"if(p<=r)" // Line 223
"{" // Line 224
"ve q-i+i*(j-k)/(p-r+j-k);}" // Line 227
"j=r;" // Line 232
"k=p;" // Line 233
"i=.002+(q/W);}" // Line 237
"ve 9.;}ec P(vec3 m,vec3 l){" // Line 241
"vec3 k=m-f;" // Line 248
"ec i,j;" // Line 249
"i=dot(k,l);" // Line 250
"if(i>0)" // Line 251
"ve 9.;" // Line 252
"j=i*i-dot(k,k)+g*g;" // Line 253
"if(j>0)" // Line 254
"{" // Line 255
"ve -i-sqrt(j);}" // Line 256
"ve 9.;}ec Q(vec3 j,vec3 i){" // Line 258
"ec k=-j.y/i.y;" // Line 265
"ve k>=V?k:9.;}vec4 R(vec3 n,vec3 m,int k){" // Line 266
"ec p,i,o,l;" // Line 278
"p=k!=2?Q(n,m):9.;" // Line 281
"i=k!=3?P(n,m):9.;" // Line 282
"o=k!=1?O(n,m,min(.5,.002+min(p,i))):9.;" // Line 283
"W/=20;" // Line 286
"l=min(o,min(p,min(i,9.)));" // Line 289
"if(l==9)" // Line 292
"ve vec4(0);" // Line 293
"vec3 j=n+m*l;" // Line 296
"if(l==o)" // Line 299
"ve vec4(j,1);" // Line 300
"if(l==p)" // Line 301
"ve vec4(j,2);" // Line 302
"if(l==i)" // Line 303
"ve vec4(j,3);}vec3 S(vec4 j,vec3 l,vec3 m){" // Line 304
"vec3 k=l.y<V?h:L(e,m);" // Line 315
"ec i=clamp(length(j.xyz-l)*(e.y<=0?4:2),.0,1.);" // Line 318
"if(j.w==1)" // Line 322
"ve mix(K(j.xyz,m),k,i);" // Line 323
"if(j.w==2)" // Line 324
"ve mix(M(j.xyz,m),k,i);" // Line 325
"if(j.w==3)" // Line 326
"ve mix(" // Line 327
"mix(N(j.xyz,m),T(R(j.xyz,reflect(m,normalize(j.xyz-f)),3),j.xyz,m),.5)" // Line 329
",k,i);" // Line 330
"ve L(l,m);}vec3 T(vec4 j,vec3 l,vec3 m){" // Line 332
"vec3 k=l.y<V?h:L(e,m);" // Line 341
"ec i=clamp(length(j.xyz-l)*(e.y<=0?4:2),.0,1.);" // Line 344
"if(j.w==1)" // Line 347
"ve mix(K(j.xyz,m),k,i);" // Line 348
"if(j.w==2)" // Line 349
"ve mix(h,k,i);" // Line 350
"if(j.w==3)" // Line 351
"ve mix(N(j.xyz,m),k,i);" // Line 352
"ve k;}void main(){" // Line 354
"W=100;" // Line 368
"c=3.1416;" // Line 371
"X=vec3(1.2,.9,.9);" // Line 372
"V=.0001;" // Line 373
"U=.01;" // Line 374
"ec k=10;" // Line 377
"int j=int(Y.y);" // Line 380
"d=vec3((Z.xy-.5),1);" // Line 383
"if(j>22&&j<27)" // Line 386
"{" // Line 387
"k=min(1.,sin((Y.y-23)*c*.25)*12);" // Line 388
"e=vec3(.12,.005,Y.y*.08);" // Line 389
"d=vec3(gl_ModelViewMatrix*vec4(d,1));" // Line 390
"d.y+=.1*cos(Y.y*4);}" // Line 391
"else if(j>14&&j<23)" // Line 394
"{" // Line 395
"k=min(1.,sin((Y.y-15)*c*.125)*24);" // Line 396
"d+=vec3(0,.1*cos(Y.y*4),0);" // Line 397
"e=vec3(.08,.01*sin(Y.y*4)+.002,Y.y*.11);}" // Line 398
"else " // Line 402
"{" // Line 403
"e=vec3(.1,.004,.0)+vec3(.1,.005,20)" // Line 405
"*vec3(A(vec2(j,k++)),A(vec2(j,k++)),A(vec2(j,k++)));" // Line 406
"e=mix(" // Line 409
"e+vec3(.008)*vec3(A(vec2(j,k++)),A(vec2(j,k++)),A(vec2(j,k++)))," // Line 410
"e+vec3(.008)*vec3(A(vec2(j,k++)),A(vec2(j,k++)),A(vec2(j,k++)))," // Line 411
"Y.y-j);" // Line 413
"e.y+=G(e.xz)+.02;" // Line 416
"e+=.02*H(e);" // Line 419
"k=min(1.,step(-28.,-Y.y)*sin((Y.y-j)*c)*3);}" // Line 422
"d=normalize(d);" // Line 425
"if(j>22&&j<27)" // Line 429
"f=e+.1*vec3(gl_ModelViewMatrix*vec4(0,0,1,1));" // Line 430
"else " // Line 432
"f=e+.02*vec3(sin(Y.y),0,5+cos(Y.y));" // Line 433
"f.y+=.01+G(f.xz);" // Line 435
"g=j<14?.0:U*.5+U*Y.z;" // Line 436
"f+=2*g*H(f);" // Line 437
"b=vec3(.58,.58,-.58);" // Line 440
"a=vec3(1.2);" // Line 441
"h=vec3(.3,.33,.4);" // Line 442
"if(e.y<=0)" // Line 445
"{" // Line 446
"W*=.75;" // Line 448
"a*=.8;}" // Line 451
"vec3 i=S(R(e,d,0),e,d);" // Line 455
"if(e.y<=0)" // Line 459
"i=F(i);" // Line 460
"gl_FragColor.xyz=E(step(2.,Y.y)*k*i);}";

127
bp4k/party_pack/src/small.h Normal file
View File

@@ -0,0 +1,127 @@
#pragma once
#pragma code_seg("sm0")
DWORD x_Ftol(float af_Value)
{
DWORD ldw_RetVal;
__asm fld af_Value
__asm fistp ldw_RetVal
return ldw_RetVal;
}
#pragma code_seg("sm1")
__forceinline float x_Frac(float af_Value)
{
return af_Value - x_Ftol(af_Value);
}
#pragma code_seg("sm2")
__forceinline float x_Abs(float af_Value)
{
__asm fld af_Value
__asm fabs
}
#pragma code_seg("sm3")
float x_Sin(float af_Value)
{
__asm fld af_Value
__asm fsin
}
#pragma code_seg("sm4")
float x_Sign(float af_Value)
{
if (af_Value != 0)
return af_Value / x_Abs(af_Value);
return 1.0f;
}
#pragma code_seg("sm5")
float x_Sqrt(float af_Value)
{
__asm fld af_Value
__asm fsqrt
}
#pragma code_seg("sm7")
__forceinline void x_MemCopy(void* av_Dest_, const void* av_Src_, size_t ai_Size)
{
__asm mov esi, av_Src_
__asm mov edi, av_Dest_
__asm mov ecx, ai_Size
__asm rep movsb
}
#pragma code_seg("sm8")
float x_Fmod(float x, float y)
{
__asm fld y
__asm fld x
__asm fprem
__asm fxch
__asm fstp x
}
#pragma data_seg("smA")
static unsigned long seed=0x12345678;
#pragma code_seg("sm9")
__forceinline void x_Randomize(unsigned long x)
{
seed = x;
}
#pragma code_seg("smB")
float x_Rand()
{
seed = seed * 0x76364873 + 1234567;
return (float)(seed & 0x7FFFFFFF) * (const float)(2.0f / (float)0x7FFFFFFF) - 1.0f;
}
#pragma code_seg("smS")
__forceinline size_t x_Strlen(const char* as_String)
{
size_t li_Length = 0;
while (*as_String++) ++li_Length;
return li_Length;
}
#pragma code_seg("smP")
float x_Pow(float x, float y){
float r;
__asm{
fld y
fld x
fyl2x
fld1
fld st(1)
fprem
f2xm1
faddp st(1),st
fscale
fxch st(1)
fstp st(0)
fstp r
}
return r;
}
extern "C"
{
int _fltused = 1;
}

View File

@@ -0,0 +1,87 @@
// Using 4klang by gopher/alcatraz
// The very best synth for 4ks!
#define WIN32_LEAN_AND_MEAN
#define WIN32_EXTRA_LEAN
#include "windows.h"
#include "mmsystem.h"
#include "mmreg.h"
#define USE_SOUND_THREAD
#define SAMPLE_RATE 44100
#define MAX_SAMPLES SAMPLE_RATE*2*60*20
#pragma bss_seg(".synthnothing")
static float lpSoundBuffer[MAX_SAMPLES];
static HWAVEOUT hWaveOut;
#pragma data_seg(".wavefmt")
WAVEFORMATEX WaveFMT =
{
WAVE_FORMAT_IEEE_FLOAT,
2, // channels
SAMPLE_RATE, // samples per sec
SAMPLE_RATE*4*2, // bytes per sec
8, // block alignment;
32, // bits per sample
0 // extension not needed
};
#pragma data_seg(".wavehdr")
WAVEHDR WaveHDR =
{
(LPSTR)lpSoundBuffer,
MAX_SAMPLES*4,
0,
0,
0,
0,
0,
0
};
#pragma data_seg(".mmtime")
MMTIME MMTime =
{
TIME_SAMPLES,
0
};
extern "C" void _4klang_render(float*);
extern "C" float _4klang_envelope_buffer;
#ifdef USE_SOUND_THREAD
#pragma code_seg(".sndthrd")
DWORD WINAPI SoundThread( LPVOID lpParam )
{
_4klang_render(lpSoundBuffer);
return 0;
}
#endif
#pragma code_seg(".initsnd")
extern "C" void InitSound()
{
#ifdef USE_SOUND_THREAD
CreateThread(0, 0, SoundThread, 0, 0, 0);
#else
_4klang_render(lpSoundBuffer);
#endif
waveOutOpen ( &hWaveOut, WAVE_MAPPER, &WaveFMT, NULL, 0, CALLBACK_NULL );
waveOutPrepareHeader( hWaveOut, &WaveHDR, sizeof(WaveHDR) );
waveOutWrite ( hWaveOut, &WaveHDR, sizeof(WaveHDR) );
}
#pragma code_seg(".envelope")
extern "C" float get_Envelope(int instrument)
{
return (&_4klang_envelope_buffer)[((MMTime.u.sample >> 8) << 5) + 2*instrument];
}
#pragma code_seg(".time")
extern "C" float get_Time()
{
waveOutGetPosition(hWaveOut, &MMTime, sizeof(MMTIME));
return float(MMTime.u.sample) / SAMPLE_RATE;
}

View File

@@ -0,0 +1,8 @@
#pragma once
extern "C"
{
void InitSound();
float get_Envelope(int instrument);
float get_Time();
}

View File

@@ -0,0 +1,47 @@
____ __ _____ __ ________
/ _ \ / / / ___/ / / / ______/
/ /_\ _\ / / __ __ / /__ / / _______ ________ / /_____
/ ___ \ / / / / / / / ___/ / / / ___ / / __ __ | /_ ____/
/ /___\ \ / / / /_/ / / / / / / /_ / / / / / / / / / /___
/__________| /_/ /_____/ |_| /_/ /___//_/ /_/ /_/ /_/ /_____/
|========================== http://www.blu-flame.org =========================|
.
·:
. ·:·
·:· ·:·
:·: :·: ==---=<<( blu-flame.org )>>==---==
:·: ·:·: \ P R E S E N T S /
:·:· ·:·:· <|=<(||||||||||||||||||||||)>=|>
:·:· :·:· |/| |/|
:·:· ·:·:· / / Valleyball / /
·:·:· ·:·:· |/| a 4k PC-Intro for |/|
:·:· · ·:·:· / / Breakpoint 09 / /
:·:·: : :·:·:· |/| |/|
:·:·: :·: :·:·: / / Setting new benchmark / /
:·:·: :·:· ·:·:· |/| standards for today's |/|
:·:· ·:·: :·:· / / GPUs! This intro only / /
·:· ·:· ·:· |/| renders 2 triangles, |/|
·:·:·:·:· / / everything is done in / /
|\\·:·:·:·//| |/| a shader. Requires a |/|
|\\-------//| / / Shader Model 4.0 capa- / /
| _ _ _ | |/| ble GPU of the latest |/|
| |_||_||_| | / / generation. Mid/Lowend / /
| _ _ _ | |/| GPUs should run the lo |/|
| |_||_||_| | / / res version (640x480). / /
| _ _ _ | |/| Techniques used: ray- |/|
| |_||_||_| | / / marching and raytra- / /
| . | |/| cing. Enjoy! |/|
:.:.://____|||____\\:.:/ /:.:.:.:.:.:.:.:.:.:.:.:./ /:.:.:.
xTr1m / Hel / raYn / PC-4k Compo / Breakpoint 2009 / Bingen
__
__ / \
/ \___________________________________| |
| : greets: 3ye, ace, bero, chaos, | |
| : cyraxx, iq, jco, kb, las, m0d, | |
| : manx, ryg, scamp, SoDa7, starly, | _ |
| _: tomb, wayfinder, xxx. |_/\|
| /\\_____________________________________/
\_/ xTr1m

View File

@@ -0,0 +1,85 @@
// 4slang.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "LexAnalyzer.h"
#include "SemAnalyzer.h"
#include "Cruncher.h"
#include "Exporter.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
vector<CString> lk_Filenames;
CString ls_OutFile;
try
{
for (int i = 1; i < argc; ++i)
{
_TCHAR* lc_Arg_ = argv[i];
if (lc_Arg_[0] == '/')
{
CString ls_Arg = lc_Arg_ + 1;
if (ls_Arg.Left(4).CompareNoCase(_T("out:")) == 0)
{
ls_OutFile = ls_Arg.Mid(4);
}
}
else
{
lk_Filenames.push_back(lc_Arg_);
}
}
if (lk_Filenames.empty())
{
wcout << _T("Error: No input file(s) passed to 4slang.") << endl;
return -1;
}
if (ls_OutFile.IsEmpty())
{
wcout << _T("Error: No output file passed to 4slang.") << endl;
return -2;
}
vector<r_Program*> lk_Programs;
vector<CString>::iterator lk_Iter = lk_Filenames.begin();
for (; lk_Iter != lk_Filenames.end(); ++lk_Iter)
{
wcout << "Crunching " << (LPCTSTR)*lk_Iter << "..." << endl;
k_LexAnalyzer lk_LexAnalyzer;
if (!lk_LexAnalyzer.Parse(*lk_Iter))
return -3;
k_SemAnalyzer lk_SemAnalyzer;
lk_SemAnalyzer.Analyze(lk_LexAnalyzer);
r_Program* lr_Program_ = lk_SemAnalyzer.mr_Program_;
lk_Programs.push_back(lr_Program_);
}
k_Cruncher lk_Cruncher;
lk_Cruncher.Crunch(lk_Programs);
k_Exporter lk_Exporter;
if (!lk_Exporter.Export(lk_Programs, ls_OutFile))
return -4;
}
catch (const CString& ls_Exception)
{
wcout << (LPCTSTR)ls_Exception << endl;
#ifdef _DEBUG
::MessageBox(NULL, ls_Exception, _T("4slang"), MB_OK);
#endif
return -5;
}
return 0;
}

BIN
bp4k/src/4slang/4slang.ncb Normal file

Binary file not shown.

View File

@@ -0,0 +1,181 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9,00"
Name="4slang"
ProjectGUID="{E0A366EF-1805-44C7-B644-426FEE32B9D9}"
RootNamespace="My4slang"
Keyword="Win32Proj"
TargetFrameworkVersion="196613"
>
<Platforms>
<Platform
Name="Win32"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(SolutionDir)obj\$(ProjectName)_$(ConfigurationName)"
ConfigurationType="1"
UseOfATL="1"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="3"
UsePrecompiledHeader="2"
WarningLevel="3"
DebugInformationFormat="4"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)\$(ProjectName).exe"
LinkIncremental="2"
GenerateDebugInformation="true"
SubSystem="1"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
>
<File
RelativePath=".\4slang.cpp"
>
</File>
<File
RelativePath=".\Cruncher.cpp"
>
</File>
<File
RelativePath=".\Exporter.cpp"
>
</File>
<File
RelativePath=".\LanguageSpecifier.cpp"
>
</File>
<File
RelativePath=".\LexAnalyzer.cpp"
>
</File>
<File
RelativePath=".\SemAnalyzer.cpp"
>
</File>
<File
RelativePath=".\stdafx.cpp"
>
<FileConfiguration
Name="Debug|Win32"
>
<Tool
Name="VCCLCompilerTool"
UsePrecompiledHeader="1"
/>
</FileConfiguration>
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
>
<File
RelativePath=".\Cruncher.h"
>
</File>
<File
RelativePath=".\Exporter.h"
>
</File>
<File
RelativePath=".\LanguageSpecifier.h"
>
</File>
<File
RelativePath=".\LexAnalyzer.h"
>
</File>
<File
RelativePath=".\SemAnalyzer.h"
>
</File>
<File
RelativePath=".\stdafx.h"
>
</File>
<File
RelativePath=".\targetver.h"
>
</File>
</Filter>
<Filter
Name="Resource Files"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>

View File

@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioUserFile
ProjectType="Visual C++"
Version="9,00"
ShowAllFiles="false"
>
<Configurations>
<Configuration
Name="Debug|Win32"
>
<DebugSettings
Command="$(TargetPath)"
WorkingDirectory=""
CommandArguments=""
Attach="false"
DebuggerType="3"
Remote="1"
RemoteMachine="SHAIKUR"
RemoteCommand=""
HttpUrl=""
PDBPath=""
SQLDebugging=""
Environment=""
EnvironmentMerge="true"
DebuggerFlavor=""
MPIRunCommand=""
MPIRunArguments=""
MPIRunWorkingDirectory=""
ApplicationCommand=""
ApplicationArguments=""
ShimCommand=""
MPIAcceptMode=""
MPIAcceptFilter=""
/>
</Configuration>
</Configurations>
</VisualStudioUserFile>

View File

@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioUserFile
ProjectType="Visual C++"
Version="9,00"
ShowAllFiles="true"
>
<Configurations>
<Configuration
Name="Debug|Win32"
>
<DebugSettings
Command="$(TargetPath)"
WorkingDirectory=""
CommandArguments="$(SolutionDir)src\ocean4k\mark.fs /out:$(SolutionDir)src\ocean4k\release.h"
Attach="false"
DebuggerType="3"
Remote="1"
RemoteMachine="SHAIKUR"
RemoteCommand=""
HttpUrl=""
PDBPath=""
SQLDebugging=""
Environment=""
EnvironmentMerge="true"
DebuggerFlavor="0"
MPIRunCommand=""
MPIRunArguments=""
MPIRunWorkingDirectory=""
ApplicationCommand=""
ApplicationArguments=""
ShimCommand=""
MPIAcceptMode=""
MPIAcceptFilter=""
/>
</Configuration>
</Configurations>
</VisualStudioUserFile>

View File

@@ -0,0 +1,74 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{E0A366EF-1805-44C7-B644-426FEE32B9D9}</ProjectGuid>
<RootNamespace>My4slang</RootNamespace>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseOfAtl>Static</UseOfAtl>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)bin\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)obj\$(ProjectName)_$(Configuration)\</IntDir>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
</ClCompile>
<Link>
<OutputFile>$(OutDir)$(ProjectName).exe</OutputFile>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="4slang.cpp" />
<ClCompile Include="Cruncher.cpp" />
<ClCompile Include="Exporter.cpp" />
<ClCompile Include="LanguageSpecifier.cpp" />
<ClCompile Include="LexAnalyzer.cpp" />
<ClCompile Include="SemAnalyzer.cpp" />
<ClCompile Include="stdafx.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="Cruncher.h" />
<ClInclude Include="Exporter.h" />
<ClInclude Include="LanguageSpecifier.h" />
<ClInclude Include="LexAnalyzer.h" />
<ClInclude Include="SemAnalyzer.h" />
<ClInclude Include="stdafx.h" />
<ClInclude Include="targetver.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@@ -0,0 +1,63 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="4slang.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Cruncher.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Exporter.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="LanguageSpecifier.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="LexAnalyzer.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="SemAnalyzer.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="stdafx.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="Cruncher.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Exporter.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="LanguageSpecifier.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="LexAnalyzer.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="SemAnalyzer.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="stdafx.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="targetver.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,3 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
</Project>

View File

@@ -0,0 +1,206 @@
#include "stdafx.h"
#include "Cruncher.h"
using namespace std;
void k_Cruncher::ReplaceFunctionCalls(r_Scope* ar_Scope_)
{
for (vector<r_Keyword>::iterator lk_Iter = ar_Scope_->mk_Keywords.begin(); lk_Iter != ar_Scope_->mk_Keywords.end(); ++lk_Iter)
{
r_Keyword& lr_Keyword = *lk_Iter;
if (lr_Keyword.me_Type == r_KeywordType::Number)
{
if (lr_Keyword.ms_Name.Left(2) == _T("0.") && lr_Keyword.ms_Name != _T("0."))
lr_Keyword.ms_Name = lr_Keyword.ms_Name.Mid(1);
if (lr_Keyword.ms_Name[0] != _T('.') && lr_Keyword.ms_Name.Right(2) == _T(".0"))
lr_Keyword.ms_Name = lr_Keyword.ms_Name.Left(lr_Keyword.ms_Name.GetLength() - 1);
}
if (lr_Keyword.me_Type == r_KeywordType::FunctionCall)
{
if (mk_Functions.find(lr_Keyword.ms_Name) != mk_Functions.end())
lr_Keyword.ms_Name = mk_Functions[lr_Keyword.ms_Name];
}
}
for (vector<r_Scope*>::iterator lk_Iter = ar_Scope_->mk_Scopes.begin(); lk_Iter != ar_Scope_->mk_Scopes.end(); ++lk_Iter)
{
ReplaceFunctionCalls(*lk_Iter);
}
}
CString GetVarName(char ac_Char)
{
if (ac_Char >= 'A' + 104)
throw _T("Too many variables and functions! This is not 4k worthy!");
char* lc_VarNames_[] = {
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z",
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
"aa",
"ab",
"ac",
"ad",
"ae",
"af",
"ag",
"ah",
"ai",
"aj",
"ak",
"al",
"am",
"an",
"ao",
"ap",
"aq",
"ar",
"as",
"at",
"au",
"av",
"aw",
"ax",
"ay",
"az",
"aA",
"aB",
"aC",
"aD",
"aE",
"aF",
"aG",
"aH",
"aI",
"aJ",
"aK",
"aL",
"aM",
"aN",
"aO",
"aP",
"aQ",
"aR",
"aS",
"aT",
"aU",
"aV",
"aW",
"aX",
"aY",
"aZ"
};
return CString(lc_VarNames_[ac_Char - 'A']);
}
void k_Cruncher::RenameVariables(r_Scope* ar_Scope_, char ac_Name)
{
char lc_Char = ac_Name;
map<CString, r_Keyword*>::iterator lk_KeywordIter = ar_Scope_->mr_SymbolTable.mk_Map.begin();
for (; lk_KeywordIter != ar_Scope_->mr_SymbolTable.mk_Map.end(); ++lk_KeywordIter)
{
r_Keyword* lr_Keyword_ = lk_KeywordIter->second;
if (!lr_Keyword_->mb_CanBeRenamed)
continue;
r_Keyword* lr_SymbolTableEntry_ = NULL;
do
{
lr_Keyword_->ms_Name = GetVarName(lc_Char++);
} while (ar_Scope_->SearchVariable(lr_Keyword_->ms_Name, lr_SymbolTableEntry_));
}
vector<r_SymbolTable*>::iterator lk_Iter = ar_Scope_->mr_SymbolTable.mk_Children.begin();
for (; lk_Iter != ar_Scope_->mr_SymbolTable.mk_Children.end(); ++lk_Iter)
{
r_Scope* lr_Scope_ = (*lk_Iter)->mr_Parent_;
RenameVariables(lr_Scope_, lc_Char);
}
}
void k_Cruncher::Crunch(vector<r_Program*> ak_Programs)
{
char lc_FuncName = 'A';
for (vector<r_Program*>::iterator lk_ProgIter = ak_Programs.begin(); lk_ProgIter != ak_Programs.end(); ++lk_ProgIter)
{
r_Program* lr_Program_ = *lk_ProgIter;
for (vector<r_Function*>::iterator lk_Iter = lr_Program_->mk_Functions.begin(); lk_Iter != lr_Program_->mk_Functions.end(); ++lk_Iter)
{
r_Function* lr_Function_ = *lk_Iter;
if (lr_Function_->ms_Name.CompareNoCase(_T("main")) == 0)
continue;
CString ls_NewFuncName = GetVarName(lc_FuncName++);
mk_Functions[lr_Function_->ms_Name] = ls_NewFuncName;
lr_Function_->ms_Name = ls_NewFuncName;
}
for (vector<r_Function*>::iterator lk_Iter = lr_Program_->mk_Functions.begin(); lk_Iter != lr_Program_->mk_Functions.end(); ++lk_Iter)
{
ReplaceFunctionCalls(*lk_Iter);
}
ReplaceFunctionCalls(lr_Program_);
RenameVariables(lr_Program_, lc_FuncName);
}
}

View File

@@ -0,0 +1,27 @@
#pragma once
#include "SemAnalyzer.h"
using namespace std;
class k_Cruncher
{
struct r_NoCaseLess
{
bool operator () (const CString& as_Left, const CString& as_Right) const
{
return as_Left.CompareNoCase(as_Right) < 0;
}
};
public:
map<CString, CString> mk_Functions;
k_Cruncher() {}
virtual ~k_Cruncher() {}
void ReplaceFunctionCalls(r_Scope* ar_Scope_);
void RenameVariables(r_Scope* ar_Scope_, char ac_Name);
void Crunch(vector<r_Program*> ak_Programs);
};

View File

@@ -0,0 +1,136 @@
#include "stdafx.h"
#include "Exporter.h"
static int gi_LastLine = 1;
void ExportScope(r_Scope* ar_Scope_, FILE* ar_File_)
{
_ftprintf_s(ar_File_, _T("{"));
for (vector<r_Keyword>::iterator lk_Iter = ar_Scope_->mk_Keywords.begin(); lk_Iter != ar_Scope_->mk_Keywords.end(); ++lk_Iter)
{
if (lk_Iter->me_Type == r_KeywordType::Variable)
{
if (lk_Iter->mb_CanBeRenamed)
lk_Iter->ms_Name = lk_Iter->mr_SymbolTableEntry_->ms_Name;
}
if (lk_Iter->mi_LineNumber != gi_LastLine)
{
for (int i = gi_LastLine; i < lk_Iter->mi_LineNumber; ++i)
{
//_ftprintf_s(ar_File_, _T("\\n"));
}
_ftprintf_s(ar_File_, _T("\" // Line %d\n\t\""), gi_LastLine);
gi_LastLine = lk_Iter->mi_LineNumber;
}
if (lk_Iter->me_Type == r_KeywordType::Scope)
{
int li_ScopeId = 0;
_stscanf_s(lk_Iter->ms_Name, _T("%d"), &li_ScopeId);
ExportScope(ar_Scope_->mk_Scopes[li_ScopeId], ar_File_);
}
else
{
if (lk_Iter->ms_Name == _T("%"))
_ftprintf_s(ar_File_, _T("%%"));
else
_ftprintf_s(ar_File_, lk_Iter->ms_Name);
switch (lk_Iter->me_Type)
{
case r_KeywordType::Identifier:
case r_KeywordType::Type:
_ftprintf_s(ar_File_, _T(" "));
default:
break;
}
}
}
_ftprintf_s(ar_File_, _T("}"));
}
void ExportFunction(r_Function* ar_Function_, FILE* ar_File_)
{
_ftprintf_s(ar_File_, ar_Function_->ms_ReturnType);
_ftprintf_s(ar_File_, _T(" "));
_ftprintf_s(ar_File_, ar_Function_->ms_Name);
_ftprintf_s(ar_File_, _T("("));
for (vector<r_Parameter>::iterator lk_Iter = ar_Function_->mk_Parameters.begin(); lk_Iter != ar_Function_->mk_Parameters.end(); ++lk_Iter)
{
_ftprintf_s(ar_File_, lk_Iter->ms_VarType);
_ftprintf_s(ar_File_, _T(" "));
_ftprintf_s(ar_File_, lk_Iter->ms_Name);
if (lk_Iter + 1 != ar_Function_->mk_Parameters.end())
_ftprintf_s(ar_File_, _T(","));
}
_ftprintf_s(ar_File_, _T(")"));
ExportScope(ar_Function_, ar_File_);
}
void ExportProgram(r_Program* ar_Program_, FILE* ar_File_)
{
_ftprintf_s(ar_File_, _T("\t\""));
for (vector<r_Keyword>::iterator lk_Iter = ar_Program_->mk_Keywords.begin(); lk_Iter != ar_Program_->mk_Keywords.end(); ++lk_Iter)
{
if (lk_Iter->me_Type == r_KeywordType::Variable)
{
if (lk_Iter->mb_CanBeRenamed)
lk_Iter->ms_Name = lk_Iter->mr_SymbolTableEntry_->ms_Name;
}
if (lk_Iter->mi_LineNumber != gi_LastLine)
{
for (int i = gi_LastLine; i < lk_Iter->mi_LineNumber; ++i)
{
//_ftprintf_s(ar_File_, _T("\\n"));
}
_ftprintf_s(ar_File_, _T("\" // Line %d\n\t\""), gi_LastLine);
gi_LastLine = lk_Iter->mi_LineNumber;
}
_ftprintf_s(ar_File_, lk_Iter->ms_Name);
switch (lk_Iter->me_Type)
{
case r_KeywordType::Identifier:
case r_KeywordType::Type:
_ftprintf_s(ar_File_, _T(" "));
default:
break;
}
}
for (vector<r_Function*>::iterator lk_Iter = ar_Program_->mk_Functions.begin(); lk_Iter != ar_Program_->mk_Functions.end(); ++lk_Iter)
{
ExportFunction(*lk_Iter, ar_File_);
}
_ftprintf_s(ar_File_, _T("\""));
}
bool k_Exporter::Export(const vector<r_Program*>& ak_Programs, const CString& as_Filename)
{
FILE* lr_File_ = NULL;
_tfopen_s(&lr_File_, as_Filename, _T("w"));
if (lr_File_ == NULL)
{
wcout << _T("Error: Couldn't open ") << (LPCTSTR)as_Filename << _T(" for writing.") << endl;
return false;
}
_ftprintf_s(lr_File_, _T("#pragma once\n\n"));
_ftprintf_s(lr_File_, _T("#pragma data_seg(\".shaders\")\n"));
_ftprintf_s(lr_File_, _T("static char* fsh =\n"));
std::vector<r_Program*>::const_iterator lk_Iter = ak_Programs.begin();
for (; lk_Iter != ak_Programs.end(); ++lk_Iter)
{
r_Program* lr_Program_ = *lk_Iter;
gi_LastLine = 1;
ExportProgram(lr_Program_, lr_File_);
}
_ftprintf_s(lr_File_, _T(";\n"));
return true;
}

View File

@@ -0,0 +1,15 @@
#pragma once
#include "SemAnalyzer.h"
using namespace std;
class k_Exporter
{
public:
k_Exporter() {}
virtual ~k_Exporter() {}
bool Export(const vector<r_Program*>& ak_Programs, const CString& as_Filename);
};

View File

@@ -0,0 +1,202 @@
#include "stdafx.h"
#include "LanguageSpecifier.h"
using namespace std;
k_LanguageSpecifier::k_LanguageSpecifier()
: mi_LineNumber(1)
{
mk_Identifiers.push_back(_T("return"));
mk_Identifiers.push_back(_T("varying"));
mk_Identifiers.push_back(_T("inout"));
mk_Identifiers.push_back(_T("in"));
mk_Identifiers.push_back(_T("out"));
mk_Identifiers.push_back(_T("uniform"));
mk_Identifiers.push_back(_T("sampler2D"));
mk_Identifiers.push_back(_T("const"));
mk_Identifiers.push_back(_T("then"));
mk_Identifiers.push_back(_T("else"));
mk_Identifiers.push_back(_T("break"));
mk_Identifiers.push_back(_T("struct"));
mk_ReservedVariables.push_back(_T("gl_FragColor"));
mk_ReservedVariables.push_back(_T("gl_FragCoord"));
mk_ReservedVariables.push_back(_T("gl_ModelViewMatrix"));
mk_ReservedVariables.push_back(_T("gl_ModelViewMatrixInverse"));
mk_ReservedVariables.push_back(_T("true"));
mk_ReservedVariables.push_back(_T("false"));
mk_Functions.push_back(_T("if"));
mk_Functions.push_back(_T("for"));
mk_Functions.push_back(_T("do"));
mk_Functions.push_back(_T("while"));
mk_Functions.push_back(_T("texture2D"));
mk_Functions.push_back(_T("atan"));
mk_Functions.push_back(_T("sin"));
mk_Functions.push_back(_T("cos"));
mk_Functions.push_back(_T("acos"));
mk_Functions.push_back(_T("atan"));
mk_Functions.push_back(_T("fract"));
mk_Functions.push_back(_T("length"));
mk_Functions.push_back(_T("floor"));
mk_Functions.push_back(_T("ceil"));
mk_Functions.push_back(_T("step"));
mk_Functions.push_back(_T("smoothstep"));
mk_Functions.push_back(_T("normalize"));
mk_Functions.push_back(_T("dot"));
mk_Functions.push_back(_T("cross"));
mk_Functions.push_back(_T("pow"));
mk_Functions.push_back(_T("mix"));
mk_Functions.push_back(_T("asin"));
mk_Functions.push_back(_T("mod"));
mk_Functions.push_back(_T("abs"));
mk_Functions.push_back(_T("clamp"));
mk_Functions.push_back(_T("reflect"));
mk_Functions.push_back(_T("refract"));
mk_Functions.push_back(_T("min"));
mk_Functions.push_back(_T("max"));
mk_Functions.push_back(_T("sqrt"));
mk_Types.push_back(_T("void"));
mk_Types.push_back(_T("vec2"));
mk_Types.push_back(_T("vec3"));
mk_Types.push_back(_T("vec4"));
mk_Types.push_back(_T("float"));
mk_Types.push_back(_T("int"));
mk_Types.push_back(_T("bool"));
mk_Symbols.push_back(_T(";"));
mk_Symbols.push_back(_T("{"));
mk_Symbols.push_back(_T("}"));
mk_Symbols.push_back(_T("("));
mk_Symbols.push_back(_T(")"));
mk_Symbols.push_back(_T("["));
mk_Symbols.push_back(_T("]"));
mk_Symbols.push_back(_T("."));
mk_Symbols.push_back(_T(","));
mk_Symbols.push_back(_T("*"));
mk_Symbols.push_back(_T("+"));
mk_Symbols.push_back(_T("-"));
mk_Symbols.push_back(_T("/"));
mk_Symbols.push_back(_T("^"));
mk_Symbols.push_back(_T("&"));
mk_Symbols.push_back(_T("|"));
mk_Symbols.push_back(_T("<"));
mk_Symbols.push_back(_T(">"));
mk_Symbols.push_back(_T("="));
mk_Symbols.push_back(_T("%"));
mk_Symbols.push_back(_T("!"));
mk_Symbols.push_back(_T("?"));
mk_Symbols.push_back(_T(":"));
}
r_Keyword k_LanguageSpecifier::Classify(const CString& as_Keyword, char* ac_Char_)
{
r_KeywordType::Enumeration le_Type = r_KeywordType::Variable;
if (!as_Keyword.IsEmpty())
{
if (find(mk_Identifiers.begin(), mk_Identifiers.end(), as_Keyword) != mk_Identifiers.end())
{
le_Type = r_KeywordType::Identifier;
}
if (find(mk_Types.begin(), mk_Types.end(), as_Keyword) != mk_Types.end())
{
char* lc_Pointer_ = ac_Char_;
while (*lc_Pointer_ == '\t' || *lc_Pointer_ == '\n' || *lc_Pointer_ == ' ')
{
++lc_Pointer_;
}
if (*lc_Pointer_ == '(')
le_Type = r_KeywordType::FunctionCall;
else if (*lc_Pointer_ == ')')
le_Type = r_KeywordType::Identifier;
else
le_Type = r_KeywordType::Type;
}
if (find(mk_Functions.begin(), mk_Functions.end(), as_Keyword) != mk_Functions.end())
{
le_Type = r_KeywordType::FunctionCall;
}
if (find(mk_ReservedVariables.begin(), mk_ReservedVariables.end(), as_Keyword) != mk_ReservedVariables.end())
{
le_Type = r_KeywordType::ReservedVariable;
}
if (find(mk_Symbols.begin(), mk_Symbols.end(), as_Keyword) != mk_Symbols.end())
{
le_Type = r_KeywordType::Symbol;
}
}
return r_Keyword(le_Type, as_Keyword, mi_LineNumber);
}
r_Keyword k_LanguageSpecifier::get_NextKeyword(char** ac_Chars__)
{
CString ls_Keyword;
r_Keyword lr_Keyword(r_KeywordType::Unknown, ls_Keyword, mi_LineNumber);
char* lc_Char_ = *ac_Chars__;
while (*lc_Char_ != 0)
{
if (lc_Char_[0] == '/' && lc_Char_[1] == '/')
{
while (*lc_Char_ != '\n' && *lc_Char_ != 0)
{
if (*lc_Char_ == '\n')
++mi_LineNumber;
++lc_Char_;
}
ls_Keyword = CString();
continue;
}
if (ls_Keyword.IsEmpty() && (*lc_Char_ == '\t' || *lc_Char_ == '\n' || *lc_Char_ == ' ' || *lc_Char_ == 0))
{
if (*lc_Char_ == '\n')
++mi_LineNumber;
++lc_Char_;
continue;
}
if (ls_Keyword.IsEmpty() && (*lc_Char_ >= '0' && *lc_Char_ <= '9'))
{
char* lc_Pointer_ = lc_Char_;
while ((*lc_Pointer_ >= '0' && *lc_Pointer_ <= '9') || (*lc_Pointer_ >= 'A' && *lc_Pointer_ <= 'F') || (*lc_Pointer_ >= 'a' && *lc_Pointer_ <= 'f') || *lc_Pointer_ == 'x' || *lc_Pointer_ == '.')
{
++lc_Pointer_;
}
char* ls_Temp_ = new char[lc_Pointer_ - lc_Char_ + 1];
ls_Temp_[lc_Pointer_ - lc_Char_] = 0;
memcpy_s(ls_Temp_, lc_Pointer_ - lc_Char_, lc_Char_, lc_Pointer_ - lc_Char_);
lc_Char_ = lc_Pointer_;
lr_Keyword = r_Keyword(r_KeywordType::Number, CString(ls_Temp_), mi_LineNumber);
delete [] ls_Temp_;
break;
}
ls_Keyword += *lc_Char_++;
if (find(mk_Symbols.begin(), mk_Symbols.end(), ls_Keyword) != mk_Symbols.end())
{
lr_Keyword = Classify(ls_Keyword, lc_Char_);
break;
}
if ((find(mk_Symbols.begin(), mk_Symbols.end(), CString(*lc_Char_)) != mk_Symbols.end()) || (*lc_Char_ == '\t' || *lc_Char_ == '\n' || *lc_Char_ == '\r' || *lc_Char_ == ' ' || *lc_Char_ == 0))
{
if (*lc_Char_ == '\n')
++mi_LineNumber;
lr_Keyword = Classify(ls_Keyword, lc_Char_);
break;
}
}
*ac_Chars__ = lc_Char_;
return lr_Keyword;
}

View File

@@ -0,0 +1,58 @@
#pragma once
struct r_KeywordType
{
enum Enumeration
{
Identifier,
Type,
Symbol,
Number,
FunctionDeclaration,
ArgumentDeclaration,
VariableDeclaration,
Variable,
ReservedVariable,
Scope, // Reserved for the semantic analyzer
FunctionCall, // Reserved for the semantic analyzer
Unknown
};
};
struct r_Keyword
{
r_Keyword(r_KeywordType::Enumeration ae_Type, const CString& as_Name, int ai_LineNumber)
: me_Type(ae_Type)
, ms_Name(as_Name)
, mi_LineNumber(ai_LineNumber)
, mr_SymbolTableEntry_(NULL)
, mb_CanBeRenamed(true)
{
}
r_KeywordType::Enumeration me_Type;
CString ms_Name;
int mi_LineNumber;
bool mb_CanBeRenamed;
r_Keyword* mr_SymbolTableEntry_;
};
class k_LanguageSpecifier
{
std::vector<CString> mk_Identifiers;
std::vector<CString> mk_Symbols;
std::vector<CString> mk_Functions;
std::vector<CString> mk_Types;
std::vector<CString> mk_ReservedVariables;
int mi_LineNumber;
public:
k_LanguageSpecifier();
virtual ~k_LanguageSpecifier() {}
r_Keyword Classify(const CString& as_Keyword, char* ac_Char_);
r_Keyword get_NextKeyword(char** ac_Chars__);
};

View File

@@ -0,0 +1,74 @@
#include "stdafx.h"
#include "LexAnalyzer.h"
using namespace std;
char* TextFileRead(const CString& as_FileName)
{
FILE* lh_File;
char* ls_Content_ = NULL;
size_t li_Count = 0;
if (as_FileName.IsEmpty())
{
throw _T("Error: No file to parse!");
}
_tfopen_s(&lh_File, as_FileName, _T("rt"));
if (lh_File == NULL)
{
CString ls_Message = _T("Error: Can't open ");
ls_Message += as_FileName;
throw (LPCTSTR)ls_Message;
}
fseek(lh_File, 0, SEEK_END);
li_Count = ftell(lh_File);
rewind(lh_File);
if (li_Count <= 0)
{
CString ls_Message = _T("Error: File ");
ls_Message += as_FileName;
ls_Message += _T(" was empty or returned negative file size!");
throw (LPCTSTR)ls_Message;
}
ls_Content_ = new char[li_Count + 2];
ls_Content_[0] = (char)0xBF;
ls_Content_ += 1;
li_Count = fread_s(ls_Content_, li_Count + 1, sizeof(char), li_Count, lh_File);
ls_Content_[li_Count] = 0;
fclose(lh_File);
return ls_Content_;
}
bool k_LexAnalyzer::Parse(const CString& as_FileName)
{
char* ls_Text = NULL;
try
{
ls_Text = TextFileRead(as_FileName);
}
catch (LPCTSTR ls_Error)
{
wcout << ls_Error << endl;
return false;
}
r_Keyword lr_Keyword(r_KeywordType::Unknown, CString(), -1);
do
{
lr_Keyword = mk_Glsl.get_NextKeyword(&ls_Text);
if (lr_Keyword.me_Type != r_KeywordType::Unknown)
{
mk_Keywords.push_back(lr_Keyword);
}
} while (lr_Keyword.me_Type != r_KeywordType::Unknown);
return true;
}

View File

@@ -0,0 +1,19 @@
#pragma once
#include "LanguageSpecifier.h"
class k_LexAnalyzer
{
public:
k_LanguageSpecifier mk_Glsl;
std::vector<r_Keyword> mk_Keywords;
k_LexAnalyzer()
{
}
virtual ~k_LexAnalyzer()
{
}
bool Parse(const CString& as_File);
};

View File

@@ -0,0 +1,303 @@
#include "stdafx.h"
#include "SemAnalyzer.h"
void k_SemAnalyzer::ParseScope(r_Scope* ar_Scope_, vector<r_Keyword>::iterator& ak_Iter, k_LexAnalyzer& ak_LexAnalyzer)
{
if (ak_Iter->ms_Name == _T("{"))
++ak_Iter;
while (ak_Iter != ak_LexAnalyzer.mk_Keywords.end())
{
r_Keyword& lr_Keyword = *ak_Iter;
if (lr_Keyword.me_Type == r_KeywordType::Variable)
{
r_Keyword& lr_LastKeyword = *(ak_Iter - 1);
r_Keyword& lr_NextKeyword = *(ak_Iter + 1);
if (lr_LastKeyword.ms_Name != _T("."))
{
if (lr_NextKeyword.ms_Name == _T("("))
{
if (!ar_Scope_->ParentHasFunction(lr_Keyword.ms_Name))
{
CString ls_Message = _T("ERROR: Function call \"");
ls_Message += lr_Keyword.ms_Name;
ls_Message += _T("\" wasn't declared in the GLSL specs. Fix this!");
throw ls_Message;
}
else
{
lr_Keyword.me_Type = r_KeywordType::FunctionCall;
}
}
else if (lr_LastKeyword.me_Type == r_KeywordType::Type || lr_LastKeyword.ms_Name == _T(","))
{
if (lr_LastKeyword.ms_Name == _T(","))
{
vector<r_Keyword>::iterator lr_LastKeywordIter = ak_Iter;
bool lb_VarDecl = false;
do
{
r_Keyword& lr_TempLastKeyword = *lr_LastKeywordIter--;
if (lr_TempLastKeyword.me_Type == r_KeywordType::Type)
{
lb_VarDecl = true;
break;
}
else if (lr_TempLastKeyword.ms_Name == _T("("))
{
lb_VarDecl = false;
break;
}
} while (true);
if (lb_VarDecl)
lr_Keyword.me_Type = r_KeywordType::VariableDeclaration;
}
else
{
lr_Keyword.me_Type = r_KeywordType::VariableDeclaration;
}
}
}
else
{
lr_Keyword.me_Type = r_KeywordType::ReservedVariable;
}
}
else if (lr_Keyword.ms_Name == _T("{"))
{
r_Scope* lr_NewScope_ = new r_Scope();
lr_NewScope_->mr_ParentScope_ = ar_Scope_;
ar_Scope_->mk_Scopes.push_back(lr_NewScope_);
ParseScope(lr_NewScope_, ak_Iter, ak_LexAnalyzer);
CString ls_ScopeId;
ls_ScopeId.Format(_T("%d"), ar_Scope_->mk_Scopes.size() - 1);
ar_Scope_->mk_Keywords.push_back(r_Keyword(r_KeywordType::Scope, ls_ScopeId, lr_Keyword.mi_LineNumber));
continue;
}
else if (lr_Keyword.ms_Name == _T("}"))
{
++ak_Iter;
break;
}
ar_Scope_->mk_Keywords.push_back(lr_Keyword);
++ak_Iter;
}
}
void k_SemAnalyzer::ParseFunction(r_Function* ar_Function_, vector<r_Keyword>::iterator& ak_Iter, k_LexAnalyzer& ak_LexAnalyzer)
{
CString ls_LastType;
while (ak_Iter != ak_LexAnalyzer.mk_Keywords.end())
{
r_Keyword& lr_Keyword = *ak_Iter;
if (lr_Keyword.me_Type == r_KeywordType::Identifier)
{
ls_LastType = lr_Keyword.ms_Name + _T(" ");
}
if (lr_Keyword.me_Type == r_KeywordType::Type)
{
ls_LastType += lr_Keyword.ms_Name;
}
if (lr_Keyword.me_Type == r_KeywordType::Variable)
{
lr_Keyword.me_Type = r_KeywordType::ArgumentDeclaration;
ar_Function_->mk_Parameters.push_back(r_Parameter(ls_LastType, lr_Keyword.ms_Name, lr_Keyword.mi_LineNumber));
ls_LastType = _T("");
++ak_Iter;
}
else if (lr_Keyword.ms_Name == _T("{"))
{
ParseScope(ar_Function_, ak_Iter, ak_LexAnalyzer);
break;
}
else if (lr_Keyword.ms_Name == _T(";"))
{
++ak_Iter;
break;
}
++ak_Iter;
}
}
void k_SemAnalyzer::ParseProgram(r_Program* ar_Program_, vector<r_Keyword>::iterator& ak_Iter, k_LexAnalyzer& ak_LexAnalyzer)
{
bool lb_CanBeRenamed = true;
while (ak_Iter != ak_LexAnalyzer.mk_Keywords.end())
{
r_Keyword& lr_Keyword = *ak_Iter;
bool lb_IgnoreKeyword = false;
if (lr_Keyword.ms_Name.CompareNoCase(_T("varying")) == 0 ||
lr_Keyword.ms_Name.CompareNoCase(_T("attribute")) == 0 ||
lr_Keyword.ms_Name.CompareNoCase(_T("uniform")) == 0)
{
lb_CanBeRenamed = false;
}
if (lr_Keyword.ms_Name == _T(";"))
{
lb_CanBeRenamed = true;
}
if (lr_Keyword.me_Type == r_KeywordType::Type)
{
r_Keyword& lr_NextKeyword = *(ak_Iter + 1);
r_Keyword& lr_SuperNextKeyword = *(ak_Iter + 2);
if (lr_SuperNextKeyword.ms_Name == _T("("))
{
vector<r_Keyword>::const_iterator lk_TempIter = ak_Iter;
do
{
++lk_TempIter;
} while (lk_TempIter->ms_Name != ';' && lk_TempIter->ms_Name != '{');
if (lk_TempIter->ms_Name == ';')
{
ar_Program_->mk_Keywords.push_back(lr_Keyword);
lr_NextKeyword.me_Type = r_KeywordType::FunctionCall;
ar_Program_->mk_Keywords.push_back(lr_NextKeyword); ++ak_Iter;
ar_Program_->mk_Keywords.push_back(*++ak_Iter);
}
else
{
++ak_Iter;
++ak_Iter;
}
r_Function* lr_Function_ = new r_Function();
lr_Function_->mr_ParentScope_ = ar_Program_;
lr_Function_->ms_Name = lr_NextKeyword.ms_Name;
lr_Function_->ms_ReturnType = lr_Keyword.ms_Name;
if (lk_TempIter->ms_Name != ';')
{
ParseFunction(lr_Function_, ak_Iter, ak_LexAnalyzer);
vector<r_Function*>::iterator lk_Existing = ar_Program_->mk_Functions.begin();
for (; lk_Existing != ar_Program_->mk_Functions.end(); ++lk_Existing)
{
if ((*lk_Existing)->ms_Name.Compare(lr_Function_->ms_Name) == 0)
{
ar_Program_->mk_Functions.erase(lk_Existing);
break;
}
}
ar_Program_->mk_Functions.push_back(lr_Function_);
}
else
{
lk_TempIter = ak_Iter;
ParseFunction(lr_Function_, ak_Iter, ak_LexAnalyzer);
while (lk_TempIter != ak_Iter-1)
ar_Program_->mk_Keywords.push_back(*++lk_TempIter);
ar_Program_->mk_Functions.push_back(lr_Function_);
}
continue;
}
else
{
lr_NextKeyword.me_Type = r_KeywordType::VariableDeclaration;
lr_NextKeyword.mb_CanBeRenamed = lb_CanBeRenamed;
do
{
if (lr_SuperNextKeyword.ms_Name == _T(","))
{
if (!lb_IgnoreKeyword)
{
lb_IgnoreKeyword = true;
ar_Program_->mk_Keywords.push_back(lr_Keyword);
}
lr_NextKeyword = *++ak_Iter;
lr_NextKeyword.me_Type = r_KeywordType::VariableDeclaration;
lr_NextKeyword.mb_CanBeRenamed = lb_CanBeRenamed;
ar_Program_->mk_Keywords.push_back(lr_NextKeyword);
lr_SuperNextKeyword = *++ak_Iter;
ar_Program_->mk_Keywords.push_back(lr_SuperNextKeyword);
}
} while (lr_SuperNextKeyword.ms_Name == _T(","));
}
}
if (!lb_IgnoreKeyword)
{
ar_Program_->mk_Keywords.push_back(lr_Keyword);
}
++ak_Iter;
}
}
void k_SemAnalyzer::FillSymbolTables(r_Scope* ar_Scope_)
{
r_SymbolTable& lr_SymbolTable = ar_Scope_->mr_SymbolTable;
r_Function* lr_Function_ = dynamic_cast<r_Function*>(ar_Scope_);
if (lr_Function_ != NULL)
{
vector<r_Parameter>::iterator lk_ParamIter = lr_Function_->mk_Parameters.begin();
for (; lk_ParamIter != lr_Function_->mk_Parameters.end(); ++lk_ParamIter)
{
lr_SymbolTable.mk_Map[lk_ParamIter->ms_Name] = &(r_Keyword&)(*lk_ParamIter);
}
}
vector<r_Keyword>::iterator lk_KeywordIter = ar_Scope_->mk_Keywords.begin();
for (; lk_KeywordIter != ar_Scope_->mk_Keywords.end(); ++lk_KeywordIter)
{
r_Keyword& lr_Keyword = *lk_KeywordIter;
if (lr_Keyword.me_Type == r_KeywordType::VariableDeclaration)
{
lr_SymbolTable.mk_Map[lr_Keyword.ms_Name] = &lr_Keyword;
}
else if (lr_Keyword.me_Type == r_KeywordType::ArgumentDeclaration && dynamic_cast<r_Program*>(ar_Scope_) == NULL)
{
lr_SymbolTable.mk_Map[lr_Keyword.ms_Name] = &lr_Keyword;
}
else if (lr_Keyword.me_Type == r_KeywordType::Variable)
{
r_Keyword* lr_SymbolTableEntry_ = NULL;
if (!ar_Scope_->SearchVariable(lr_Keyword.ms_Name, lr_SymbolTableEntry_))
{
throw _T("Syntax error, variable undefined!");
}
else
{
lr_Keyword.mr_SymbolTableEntry_ = lr_SymbolTableEntry_;
}
}
}
vector<r_Scope*>::iterator lk_ScopeIter = ar_Scope_->mk_Scopes.begin();
for (; lk_ScopeIter != ar_Scope_->mk_Scopes.end(); ++lk_ScopeIter)
{
r_Scope* lr_Scope_ = *lk_ScopeIter;
lr_SymbolTable.mk_Children.push_back(&lr_Scope_->mr_SymbolTable);
lr_Scope_->mr_SymbolTable.mr_Parent_ = lr_Scope_;
FillSymbolTables(lr_Scope_);
}
r_Program* lr_Program_ = dynamic_cast<r_Program*>(ar_Scope_);
if (lr_Program_ != NULL)
{
vector<r_Function*>::iterator lk_FuncIter = lr_Program_->mk_Functions.begin();
for (; lk_FuncIter != lr_Program_->mk_Functions.end(); ++lk_FuncIter)
{
r_Scope* lr_Scope_ = (r_Scope*)*lk_FuncIter;
lr_SymbolTable.mk_Children.push_back(&lr_Scope_->mr_SymbolTable);
lr_Scope_->mr_SymbolTable.mr_Parent_ = lr_Scope_;
FillSymbolTables(lr_Scope_);
}
}
}
void k_SemAnalyzer::Analyze(k_LexAnalyzer& ak_LexAnalyzer)
{
vector<r_Keyword>::iterator lk_KeywordIter = ak_LexAnalyzer.mk_Keywords.begin();
mr_Program_ = new r_Program();
ParseProgram(mr_Program_, lk_KeywordIter, ak_LexAnalyzer);
FillSymbolTables(mr_Program_);
}

View File

@@ -0,0 +1,116 @@
#pragma once
#include "LexAnalyzer.h"
using namespace std;
struct r_Scope;
struct r_SymbolTable
{
map<CString, r_Keyword*> mk_Map;
vector<r_SymbolTable*> mk_Children;
r_Scope* mr_Parent_;
};
struct r_Scope
{
r_Scope() : mr_ParentScope_(NULL) {};
vector<r_Keyword> mk_Keywords;
vector<CString> mk_Variables;
vector<r_Scope*> mk_Scopes;
r_Scope* mr_ParentScope_;
r_SymbolTable mr_SymbolTable;
virtual bool ParentHasFunction(const CString& as_Function)
{
if (mr_ParentScope_ == NULL)
return false;
return mr_ParentScope_->ParentHasFunction(as_Function);
}
bool SearchVariable(const CString& as_Name, r_Keyword*& ar_SymbolTableEntry_)
{
if (mr_SymbolTable.mk_Map.find(as_Name) == mr_SymbolTable.mk_Map.end())
{
if (mr_ParentScope_ == NULL)
return false;
return mr_ParentScope_->SearchVariable(as_Name, ar_SymbolTableEntry_);
}
ar_SymbolTableEntry_ = mr_SymbolTable.mk_Map[as_Name];
return true;
}
};
struct r_Parameter
: r_Keyword
{
r_Parameter(const CString& as_Type, const CString& as_Name, int ai_LineNumber)
: r_Keyword(r_KeywordType::VariableDeclaration, as_Name, ai_LineNumber)
, ms_VarType(as_Type)
{
}
CString ms_VarType;
};
struct r_Function : r_Scope
{
r_Function() : r_Scope() {};
CString ms_Name;
CString ms_ReturnType;
vector<r_Parameter> mk_Parameters;
};
struct r_Program : r_Scope
{
r_Program() : r_Scope() {};
virtual bool ParentHasFunction(const CString& as_Function)
{
if (mr_ParentScope_ != NULL)
{
if (mr_ParentScope_->ParentHasFunction(as_Function))
return true;
}
vector<r_Function*>::iterator lk_Iter = mk_Functions.begin();
for (; lk_Iter != mk_Functions.end(); ++lk_Iter)
{
if ((*lk_Iter)->ms_Name == as_Function)
return true;
}
return false;
}
vector<r_Function*> mk_Functions;
};
class k_SemAnalyzer
{
public:
r_Program* mr_Program_;
k_SemAnalyzer() {}
virtual ~k_SemAnalyzer() {}
void ParseScope(r_Scope* ar_Scope_, vector<r_Keyword>::iterator& ak_Iter, k_LexAnalyzer& ak_LexAnalyzer);
void ParseFunction(r_Function* ar_Function_, vector<r_Keyword>::iterator& ak_Iter, k_LexAnalyzer& ak_LexAnalyzer);
void ParseProgram(r_Program* ar_Program_, vector<r_Keyword>::iterator& ak_Iter, k_LexAnalyzer& ak_LexAnalyzer);
void FillSymbolTables(r_Scope* ar_Scope_);
void Analyze(k_LexAnalyzer& ak_LexAnalyzer);
};

View File

@@ -0,0 +1,8 @@
// stdafx.cpp : source file that includes just the standard includes
// 4slang.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file

23
bp4k/src/4slang/stdafx.h Normal file
View File

@@ -0,0 +1,23 @@
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <tchar.h>
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit
#include <atlbase.h>
#include <atlstr.h>
#include <vector>
#include <map>
#include <algorithm>
// TODO: reference additional headers your program requires here

View File

@@ -0,0 +1,24 @@
#pragma once
// The following macros define the minimum required platform. The minimum required platform
// is the earliest version of Windows, Internet Explorer etc. that has the necessary features to run
// your application. The macros work by enabling all features available on platform versions up to and
// including the version specified.
// Modify the following defines if you have to target a platform prior to the ones specified below.
// Refer to MSDN for the latest info on corresponding values for different platforms.
#ifndef WINVER // Specifies that the minimum required platform is Windows Vista.
#define WINVER 0x0600 // Change this to the appropriate value to target other versions of Windows.
#endif
#ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista.
#define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows.
#endif
#ifndef _WIN32_WINDOWS // Specifies that the minimum required platform is Windows 98.
#define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later.
#endif
#ifndef _WIN32_IE // Specifies that the minimum required platform is Internet Explorer 7.0.
#define _WIN32_IE 0x0700 // Change this to the appropriate value to target other versions of IE.
#endif

BIN
bp4k/src/bp4k/4klang.obj Normal file

Binary file not shown.

254
bp4k/src/bp4k/Shaders.cpp Normal file
View File

@@ -0,0 +1,254 @@
#include "Shaders.h"
#ifdef _DEBUG
PFNGLCREATESHADERPROC glCreateShader = NULL;
PFNGLSHADERSOURCEPROC glShaderSource = NULL;
PFNGLCOMPILESHADERPROC glCompileShader = NULL;
PFNGLGETSHADERIVPROC glGetShaderiv = NULL;
PFNGLGETPROGRAMIVPROC glGetProgramiv = NULL;
PFNGLCREATEPROGRAMPROC glCreateProgram = NULL;
PFNGLATTACHSHADERPROC glAttachShader = NULL;
PFNGLLINKPROGRAMPROC glLinkProgram = NULL;
PFNGLUSEPROGRAMPROC glUseProgram = NULL;
PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog = NULL;
PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog = NULL;
void useProgram(GLhandleARB ah_Program)
{
glUseProgram(ah_Program);
}
void initShaders()
{
glCreateShader = (PFNGLCREATESHADERPROC)myGetProcAddress("glCreateShader");
glShaderSource = (PFNGLSHADERSOURCEPROC)myGetProcAddress("glShaderSource");
glCompileShader = (PFNGLCOMPILESHADERPROC)myGetProcAddress("glCompileShader");
glGetShaderiv = (PFNGLGETSHADERIVPROC)myGetProcAddress("glGetShaderiv");
glGetProgramiv = (PFNGLGETPROGRAMIVPROC)myGetProcAddress("glGetProgramiv");
glCreateProgram = (PFNGLCREATEPROGRAMPROC)myGetProcAddress("glCreateProgram");
glAttachShader = (PFNGLATTACHSHADERPROC)myGetProcAddress("glAttachShader");
glLinkProgram = (PFNGLLINKPROGRAMPROC)myGetProcAddress("glLinkProgram");
glUseProgram = (PFNGLUSEPROGRAMPROC)myGetProcAddress("glUseProgram");
glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)myGetProcAddress("glGetShaderInfoLog");
glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)myGetProcAddress("glGetProgramInfoLog");
if (!(glCreateShader && glShaderSource && glCompileShader && glGetShaderiv && glGetProgramiv && glCreateProgram && glAttachShader && glLinkProgram && glUseProgram && glGetShaderInfoLog && glGetProgramInfoLog))
{
std::cerr << "Some shader functions are not available!" << std::endl;
}
}
void PrintErrors()
{
GLenum lr_Error = GL_NO_ERROR;
int li_ErrorCount = 5;
do
{
lr_Error = glGetError();
if (lr_Error != GL_NO_ERROR)
{
li_ErrorCount--;
char* ls_ErrorString = (char*)gluErrorString(lr_Error);
if (ls_ErrorString != 0)
std::cout << "OPENGL :: ERROR " << ls_ErrorString << std::endl;
}
if (li_ErrorCount == 0)
{
std::cout << "OPENGL :: ERROR Too many errors!" << std::endl;
break;
}
} while (lr_Error != GL_NO_ERROR);
}
GLhandleARB createVertexShader(const char* as_FileName)
{
GLhandleARB lh_Shader = 0;
char* ls_ShaderSource = textFileRead(as_FileName);
if (ls_ShaderSource == NULL)
{
std::cerr << "Error reading file: " << as_FileName << std::endl;
return lh_Shader;
}
lh_Shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(lh_Shader, 1, (const char**)&ls_ShaderSource, NULL);
glCompileShader(lh_Shader);
free(ls_ShaderSource);
int li_Status = 0;
glGetShaderiv(lh_Shader, GL_COMPILE_STATUS, &li_Status);
if (li_Status == GL_FALSE)
{
std::cerr << "Error compiling vertex shader: " << as_FileName << std::endl;
printShaderInfoLog(lh_Shader);
}
return lh_Shader;
}
GLhandleARB createFragmentShader(const char* as_FileName)
{
GLhandleARB lh_Shader = 0;
char* ls_ShaderSource = textFileRead(as_FileName);
if (ls_ShaderSource == NULL)
{
std::cerr << "Error reading file: " << as_FileName << std::endl;
return lh_Shader;
}
lh_Shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(lh_Shader, 1, (const char**)&ls_ShaderSource, NULL);
glCompileShader(lh_Shader);
int li_Status = 0;
glGetShaderiv(lh_Shader, GL_COMPILE_STATUS, &li_Status);
if (li_Status == GL_FALSE)
{
std::cerr << "Error compiling fragment shader: " << as_FileName << std::endl;
printShaderInfoLog(lh_Shader);
}
free(ls_ShaderSource);
return lh_Shader;
}
GLhandleARB createProgram(GLhandleARB ah_VertexShader, GLhandleARB ah_FragmentShader)
{
GLhandleARB lh_Program = 0;
if (ah_VertexShader + ah_FragmentShader <= 1)
{
std::cerr << "Cannot create program." << std::endl;
return lh_Program;
}
lh_Program = glCreateProgram();
glAttachShader(lh_Program, ah_VertexShader);
glAttachShader(lh_Program, ah_FragmentShader);
glLinkProgram(lh_Program);
int li_Status = 0;
glGetProgramiv(lh_Program, GL_LINK_STATUS, &li_Status);
if (li_Status == GL_FALSE)
{
std::cerr << "Error linking shaders." << std::endl;
printProgramInfoLog(lh_Program);
}
return lh_Program;
}
char* textFileRead(const char* as_FileName)
{
FILE* lh_File;
char* ls_Content = NULL;
size_t li_Count = 0;
if (as_FileName != NULL)
{
fopen_s(&lh_File, as_FileName, "rt");
if (lh_File != NULL)
{
fseek(lh_File, 0, SEEK_END);
li_Count = ftell(lh_File);
rewind(lh_File);
if (li_Count > 0)
{
ls_Content = (char*) malloc(sizeof(char) * (li_Count + 1));
li_Count = fread(ls_Content, sizeof(char), li_Count, lh_File);
ls_Content[li_Count] = '\0';
}
fclose(lh_File);
}
}
return ls_Content;
}
void printShaderInfoLog(GLhandleARB ah_Shader)
{
int li_InfologLength = 0;
int li_CharsWritten = 0;
char* li_InfoLog;
glGetShaderiv(ah_Shader, GL_INFO_LOG_LENGTH, &li_InfologLength);
if (li_InfologLength > 0)
{
li_InfoLog = (char*) malloc(li_InfologLength);
glGetShaderInfoLog(ah_Shader, li_InfologLength, &li_CharsWritten, li_InfoLog);
std::cerr << li_InfoLog << std::endl;
free(li_InfoLog);
}
}
void printProgramInfoLog(GLhandleARB ah_Program)
{
int li_InfologLength = 0;
int li_CharsWritten = 0;
char* ls_InfoLog;
glGetProgramiv(ah_Program, GL_INFO_LOG_LENGTH, &li_InfologLength);
if (li_InfologLength > 0)
{
ls_InfoLog = (char *)malloc(li_InfologLength);
glGetProgramInfoLog(ah_Program, li_InfologLength, &li_CharsWritten, ls_InfoLog);
std::cerr << ls_InfoLog << std::endl;
free(ls_InfoLog);
}
}
bool printShaderStatistics()
{
if (GL_VERSION_2_1) std::cout << "Supports OpenGL 2.1. " << std::endl;
else if (GL_VERSION_2_0) std::cout << "Supports OpenGL 2.0. " << std::endl;
else if (GL_VERSION_1_5) std::cout << "Supports OpenGL 1.5. " << std::endl;
else if (GL_VERSION_1_4) std::cout << "Supports OpenGL 1.4. " << std::endl;
else if (GL_VERSION_1_3) std::cout << "Supports OpenGL 1.3. " << std::endl;
else if (GL_VERSION_1_2) std::cout << "Supports OpenGL 1.2. " << std::endl;
else if (GL_VERSION_1_1) std::cout << "Supports OpenGL 1.1. " << std::endl;
if (GL_ARB_shader_objects && GL_ARB_vertex_shader && GL_ARB_fragment_shader)
{
std::cout << "Status: Using GLSL " << glGetString(GL_SHADING_LANGUAGE_VERSION_ARB) << std::endl;
}
else
{
std::cerr << "No GLSL support!" << std::endl;
return false;
}
return true;
}
#endif

19
bp4k/src/bp4k/Shaders.h Normal file
View File

@@ -0,0 +1,19 @@
#pragma once
#include <windows.h>
#include <iostream>
#include <GL/gl.h>
#include <GL/glu.h>
#include "glext.h"
#define myGetProcAddress(name) wglGetProcAddress((LPCSTR)name)
void initShaders();
GLhandleARB createVertexShader(const char* as_FileName);
GLhandleARB createFragmentShader(const char* as_FileName);
GLhandleARB createProgram(GLhandleARB ah_VertexShader, GLhandleARB ah_FragmentShader);
void PrintErrors();
void useProgram(GLhandleARB ah_Program);
char* textFileRead(const char* as_FileName);
void printShaderInfoLog(GLhandleARB ah_Shader);
void printProgramInfoLog(GLhandleARB ah_Program);
bool printShaderStatistics();

365
bp4k/src/bp4k/bp4k.vcproj Normal file
View File

@@ -0,0 +1,365 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9,00"
Name="bp4k"
ProjectGUID="{213903DE-E40A-4D23-9310-E520AC2B412E}"
RootNamespace="bp4k"
Keyword="Win32Proj"
TargetFrameworkVersion="196613"
>
<Platforms>
<Platform
Name="Win32"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(SolutionDir)obj\$(ProjectName)_$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="0"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="3"
UsePrecompiledHeader="0"
WarningLevel="3"
DebugInformationFormat="4"
CallingConvention="2"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="opengl32.lib winmm.lib glu32.lib"
OutputFile="$(OutDir)\$(ProjectName)_$(ConfigurationName).exe"
LinkIncremental="2"
AdditionalLibraryDirectories="&quot;$(ProjectDir)&quot;"
GenerateDebugInformation="true"
SubSystem="1"
EntryPointSymbol="main"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(SolutionDir)obj\$(ProjectName)_$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="0"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
CommandLine=""
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="1"
EnableIntrinsicFunctions="true"
FavorSizeOrSpeed="2"
WholeProgramOptimization="false"
PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS"
ExceptionHandling="0"
RuntimeLibrary="0"
BufferSecurityCheck="false"
RuntimeTypeInfo="false"
UsePrecompiledHeader="0"
WarningLevel="0"
DebugInformationFormat="3"
CallingConvention="2"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalOptions="/CRINKLER"
AdditionalDependencies="opengl32.lib winmm.lib libcmt.lib"
OutputFile="$(OutDir)\$(ProjectName)_$(ConfigurationName).exe"
AdditionalLibraryDirectories="&quot;$(ProjectDir)&quot;"
GenerateManifest="false"
ManifestFile=""
GenerateDebugInformation="true"
SubSystem="2"
LinkTimeCodeGeneration="0"
EntryPointSymbol="main"
RandomizedBaseAddress="0"
DataExecutionPrevention="0"
TargetMachine="1"
ErrorReporting="0"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Compress (Slow)|Win32"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(SolutionDir)obj\$(ProjectName)_$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="0"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
CommandLine=""
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
AdditionalOptions="/QIfist"
Optimization="1"
EnableIntrinsicFunctions="true"
FavorSizeOrSpeed="2"
WholeProgramOptimization="false"
PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS"
ExceptionHandling="0"
RuntimeLibrary="0"
BufferSecurityCheck="false"
EnableFunctionLevelLinking="false"
FloatingPointModel="2"
RuntimeTypeInfo="false"
UsePrecompiledHeader="0"
WarningLevel="0"
DebugInformationFormat="0"
CallingConvention="2"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalOptions="/CRINKLER /COMPMODE:SLOW /ORDERTRIES:4000 /HASHTRIES:300 /UNSAFEIMPORT /TRUNCATEFLOATS:24 /HASHSIZE:200 /REPORT:report.html /RANGE:opengl32 /PROGRESSGUI /TRANSFORM:CALLS"
AdditionalDependencies="opengl32.lib winmm.lib"
OutputFile="$(OutDir)\$(ProjectName)_$(ConfigurationName).exe"
AdditionalLibraryDirectories="&quot;$(ProjectDir)&quot;"
GenerateManifest="false"
ManifestFile=""
GenerateDebugInformation="false"
SubSystem="2"
LinkTimeCodeGeneration="0"
EntryPointSymbol="main"
RandomizedBaseAddress="0"
DataExecutionPrevention="0"
TargetMachine="1"
ErrorReporting="0"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
>
<File
RelativePath=".\main.cpp"
>
</File>
<File
RelativePath=".\Shaders.cpp"
>
</File>
<File
RelativePath=".\synth.cpp"
>
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
>
<File
RelativePath=".\glext.h"
>
</File>
<File
RelativePath=".\release.h"
>
<FileConfiguration
Name="Release|Win32"
>
<Tool
Name="VCCustomBuildTool"
Description=""
CommandLine=""
AdditionalDependencies=""
Outputs=""
/>
</FileConfiguration>
<FileConfiguration
Name="Compress (Slow)|Win32"
>
<Tool
Name="VCCustomBuildTool"
Description=""
CommandLine=""
AdditionalDependencies=""
Outputs=""
/>
</FileConfiguration>
</File>
<File
RelativePath=".\Shaders.h"
>
</File>
<File
RelativePath=".\small.h"
>
</File>
<File
RelativePath=".\synth.h"
>
</File>
</Filter>
<Filter
Name="Resource Files"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
>
</Filter>
<File
RelativePath=".\4klang.obj"
>
</File>
<File
RelativePath=".\generic.vs"
>
</File>
<File
RelativePath=".\mark.fs"
>
</File>
</Files>
<Globals>
</Globals>
</VisualStudioProject>

View File

@@ -0,0 +1,93 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioUserFile
ProjectType="Visual C++"
Version="9,00"
ShowAllFiles="true"
>
<Configurations>
<Configuration
Name="Debug|Win32"
>
<DebugSettings
Command="$(TargetPath)"
WorkingDirectory=""
CommandArguments=""
Attach="false"
DebuggerType="3"
Remote="1"
RemoteMachine="SHAIKUR"
RemoteCommand=""
HttpUrl=""
PDBPath=""
SQLDebugging=""
Environment=""
EnvironmentMerge="true"
DebuggerFlavor=""
MPIRunCommand=""
MPIRunArguments=""
MPIRunWorkingDirectory=""
ApplicationCommand=""
ApplicationArguments=""
ShimCommand=""
MPIAcceptMode=""
MPIAcceptFilter=""
/>
</Configuration>
<Configuration
Name="Release|Win32"
>
<DebugSettings
Command="$(TargetPath)"
WorkingDirectory=""
CommandArguments=""
Attach="false"
DebuggerType="3"
Remote="1"
RemoteMachine="SHAIKUR"
RemoteCommand=""
HttpUrl=""
PDBPath=""
SQLDebugging=""
Environment=""
EnvironmentMerge="true"
DebuggerFlavor=""
MPIRunCommand=""
MPIRunArguments=""
MPIRunWorkingDirectory=""
ApplicationCommand=""
ApplicationArguments=""
ShimCommand=""
MPIAcceptMode=""
MPIAcceptFilter=""
/>
</Configuration>
<Configuration
Name="Compress (Slow)|Win32"
>
<DebugSettings
Command="$(TargetPath)"
WorkingDirectory=""
CommandArguments=""
Attach="false"
DebuggerType="3"
Remote="1"
RemoteMachine="SHAIKUR"
RemoteCommand=""
HttpUrl=""
PDBPath=""
SQLDebugging=""
Environment=""
EnvironmentMerge="true"
DebuggerFlavor=""
MPIRunCommand=""
MPIRunArguments=""
MPIRunWorkingDirectory=""
ApplicationCommand=""
ApplicationArguments=""
ShimCommand=""
MPIAcceptMode=""
MPIAcceptFilter=""
/>
</Configuration>
</Configurations>
</VisualStudioUserFile>

View File

@@ -0,0 +1,93 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioUserFile
ProjectType="Visual C++"
Version="9,00"
ShowAllFiles="true"
>
<Configurations>
<Configuration
Name="Debug|Win32"
>
<DebugSettings
Command="$(TargetPath)"
WorkingDirectory=""
CommandArguments=""
Attach="false"
DebuggerType="3"
Remote="1"
RemoteMachine="SHAIKUR"
RemoteCommand=""
HttpUrl=""
PDBPath=""
SQLDebugging=""
Environment=""
EnvironmentMerge="true"
DebuggerFlavor=""
MPIRunCommand=""
MPIRunArguments=""
MPIRunWorkingDirectory=""
ApplicationCommand=""
ApplicationArguments=""
ShimCommand=""
MPIAcceptMode=""
MPIAcceptFilter=""
/>
</Configuration>
<Configuration
Name="Release|Win32"
>
<DebugSettings
Command="$(TargetPath)"
WorkingDirectory=""
CommandArguments=""
Attach="false"
DebuggerType="3"
Remote="1"
RemoteMachine="SHAIKUR"
RemoteCommand=""
HttpUrl=""
PDBPath=""
SQLDebugging=""
Environment=""
EnvironmentMerge="true"
DebuggerFlavor=""
MPIRunCommand=""
MPIRunArguments=""
MPIRunWorkingDirectory=""
ApplicationCommand=""
ApplicationArguments=""
ShimCommand=""
MPIAcceptMode=""
MPIAcceptFilter=""
/>
</Configuration>
<Configuration
Name="Compress (Slow)|Win32"
>
<DebugSettings
Command="$(TargetPath)"
WorkingDirectory=""
CommandArguments=""
Attach="false"
DebuggerType="3"
Remote="1"
RemoteMachine="SHAIKUR"
RemoteCommand=""
HttpUrl=""
PDBPath=""
SQLDebugging=""
Environment=""
EnvironmentMerge="true"
DebuggerFlavor=""
MPIRunCommand=""
MPIRunArguments=""
MPIRunWorkingDirectory=""
ApplicationCommand=""
ApplicationArguments=""
ShimCommand=""
MPIAcceptMode=""
MPIAcceptFilter=""
/>
</Configuration>
</Configurations>
</VisualStudioUserFile>

216
bp4k/src/bp4k/bp4k.vcxproj Normal file
View File

@@ -0,0 +1,216 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Compress (Slow)|Win32">
<Configuration>Compress (Slow)</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{213903DE-E40A-4D23-9310-E520AC2B412E}</ProjectGuid>
<RootNamespace>bp4k</RootNamespace>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Compress (Slow)|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>NotSet</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>NotSet</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>NotSet</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Compress (Slow)|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)bin\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)obj\$(ProjectName)_$(Configuration)\</IntDir>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)bin\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)obj\$(ProjectName)_$(Configuration)\</IntDir>
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</GenerateManifest>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Compress (Slow)|Win32'">$(SolutionDir)bin\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Compress (Slow)|Win32'">$(SolutionDir)obj\$(ProjectName)_$(Configuration)\</IntDir>
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Compress (Slow)|Win32'">false</GenerateManifest>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<CallingConvention>StdCall</CallingConvention>
</ClCompile>
<Link>
<AdditionalDependencies>opengl32.lib;winmm.lib;glu32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>$(OutDir)$(ProjectName)_$(Configuration).exe</OutputFile>
<AdditionalLibraryDirectories>$(ProjectDir);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<EntryPointSymbol>main</EntryPointSymbol>
<TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<PreBuildEvent>
<Command>
</Command>
</PreBuildEvent>
<ClCompile>
<Optimization>MinSpace</Optimization>
<IntrinsicFunctions>true</IntrinsicFunctions>
<FavorSizeOrSpeed>Size</FavorSizeOrSpeed>
<WholeProgramOptimization>false</WholeProgramOptimization>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ExceptionHandling>
</ExceptionHandling>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<BufferSecurityCheck>false</BufferSecurityCheck>
<RuntimeTypeInfo>false</RuntimeTypeInfo>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>TurnOffAllWarnings</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<CallingConvention>StdCall</CallingConvention>
</ClCompile>
<Link>
<AdditionalOptions>/CRINKLER %(AdditionalOptions)</AdditionalOptions>
<AdditionalDependencies>opengl32.lib;winmm.lib;libcmt.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>$(OutDir)$(ProjectName)_$(Configuration).exe</OutputFile>
<AdditionalLibraryDirectories>$(ProjectDir);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<ManifestFile>
</ManifestFile>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
<LinkTimeCodeGeneration>
</LinkTimeCodeGeneration>
<EntryPointSymbol>main</EntryPointSymbol>
<RandomizedBaseAddress>
</RandomizedBaseAddress>
<DataExecutionPrevention>
</DataExecutionPrevention>
<TargetMachine>MachineX86</TargetMachine>
<LinkErrorReporting>
</LinkErrorReporting>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Compress (Slow)|Win32'">
<PreBuildEvent>
<Command>
</Command>
</PreBuildEvent>
<ClCompile>
<AdditionalOptions>/QIfist %(AdditionalOptions)</AdditionalOptions>
<Optimization>MinSpace</Optimization>
<IntrinsicFunctions>true</IntrinsicFunctions>
<FavorSizeOrSpeed>Size</FavorSizeOrSpeed>
<WholeProgramOptimization>false</WholeProgramOptimization>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ExceptionHandling>
</ExceptionHandling>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<BufferSecurityCheck>false</BufferSecurityCheck>
<FunctionLevelLinking>false</FunctionLevelLinking>
<FloatingPointModel>Fast</FloatingPointModel>
<RuntimeTypeInfo>false</RuntimeTypeInfo>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>TurnOffAllWarnings</WarningLevel>
<DebugInformationFormat>
</DebugInformationFormat>
<CallingConvention>StdCall</CallingConvention>
</ClCompile>
<Link>
<AdditionalOptions>/CRINKLER /COMPMODE:SLOW /ORDERTRIES:4000 /HASHTRIES:300 /UNSAFEIMPORT /TRUNCATEFLOATS:24 /HASHSIZE:200 /REPORT:report.html /RANGE:opengl32 /PROGRESSGUI /TRANSFORM:CALLS %(AdditionalOptions)</AdditionalOptions>
<AdditionalDependencies>opengl32.lib;winmm.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>$(OutDir)$(ProjectName)_$(Configuration).exe</OutputFile>
<AdditionalLibraryDirectories>$(ProjectDir);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<ManifestFile>
</ManifestFile>
<GenerateDebugInformation>false</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
<LinkTimeCodeGeneration>
</LinkTimeCodeGeneration>
<EntryPointSymbol>main</EntryPointSymbol>
<RandomizedBaseAddress>
</RandomizedBaseAddress>
<DataExecutionPrevention>
</DataExecutionPrevention>
<TargetMachine>MachineX86</TargetMachine>
<LinkErrorReporting>
</LinkErrorReporting>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="main.cpp" />
<ClCompile Include="Shaders.cpp" />
<ClCompile Include="synth.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="glext.h" />
<CustomBuild Include="release.h">
<Message Condition="'$(Configuration)|$(Platform)'=='Compress (Slow)|Win32'">
</Message>
<Command Condition="'$(Configuration)|$(Platform)'=='Compress (Slow)|Win32'">
</Command>
<AdditionalInputs Condition="'$(Configuration)|$(Platform)'=='Compress (Slow)|Win32'">%(AdditionalInputs)</AdditionalInputs>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Compress (Slow)|Win32'">%(Outputs)</Outputs>
<Message Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
</Message>
<Command Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
</Command>
<AdditionalInputs Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(AdditionalInputs)</AdditionalInputs>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(Outputs)</Outputs>
</CustomBuild>
<ClInclude Include="Shaders.h" />
<ClInclude Include="small.h" />
<ClInclude Include="synth.h" />
</ItemGroup>
<ItemGroup>
<Object Include="4klang.obj" />
</ItemGroup>
<ItemGroup>
<None Include="generic.vs" />
<None Include="mark.fs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\4slang\4slang.vcxproj">
<Project>{e0a366ef-1805-44c7-b644-426fee32b9d9}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@@ -0,0 +1,54 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="main.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Shaders.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="synth.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="glext.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Shaders.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="small.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="synth.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<Object Include="4klang.obj" />
</ItemGroup>
<ItemGroup>
<None Include="generic.vs" />
<None Include="mark.fs" />
</ItemGroup>
<ItemGroup>
<CustomBuild Include="release.h">
<Filter>Header Files</Filter>
</CustomBuild>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ShowAllFiles>true</ShowAllFiles>
</PropertyGroup>
</Project>

9
bp4k/src/bp4k/generic.vs Normal file
View File

@@ -0,0 +1,9 @@
varying vec4 Y;
varying vec2 Z;
void main()
{
Y = gl_Color;
Z = (gl_Vertex.xy*vec2(Y.w,1.0))*0.5+0.5;
gl_Position = gl_Vertex;
}

7271
bp4k/src/bp4k/glext.h Normal file

File diff suppressed because it is too large Load Diff

163
bp4k/src/bp4k/main.cpp Normal file
View File

@@ -0,0 +1,163 @@
#ifdef _DEBUG
#include <time.h>
#include <io.h>
#include <process.h>
#include "Shaders.h"
#include "small.h"
#include "synth.h"
#else
#define WIN32_LEAN_AND_MEAN
#define WIN32_EXTRA_LEAN
#include <windows.h>
#include <stdio.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include "glext.h"
#include "small.h"
#include "synth.h"
#include "release.h"
#endif
#pragma data_seg(".vertexshader")
static char* vsh = "varying vec4 Y;varying vec2 Z;void main(){Y=gl_Color;Z=(gl_Vertex.xy*vec2(Y.w,1))*.5+.5;gl_Position=gl_Vertex;}";
#pragma data_seg(".resolutionX")
static const int gi_ScreenWidth = 1368;
#pragma data_seg(".resolutionY")
static const int gi_ScreenHeight = 768;
#pragma data_seg(".aspectratio")
//static const float gf_AspectRatio = 1.3281250000f; // smaller version for 4:3
static const float gf_AspectRatio = 1.7734375000f; // smaller version for 16:9
//static const float gf_AspectRatio = 1.25f; // smaller version for 5:4
//static const float gf_AspectRatio = 1.6015625000f; // smaller version for 16:10
#ifdef _DEBUG
#pragma bss_seg(".debugnothing")
HANDLE gh_ShaderCompileEvent;
static char** gs_LastShader_;
static __time64_t gi_ShaderChangedDate;
static unsigned int gi_ShaderProgram;
static unsigned int gi_LastShaderProgram;
#pragma data_seg(".debuginfo")
static const char* gs_VertexShader = "generic.vs";
static const char* gs_ShaderFile = "mark.fs";
#endif
#pragma data_seg(".pfd")
static const PIXELFORMATDESCRIPTOR pfd={
0, 1, PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, 32, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 8
};
#pragma data_seg(".dms")
static DEVMODE dmScreenSettings={
"",0,0,sizeof(dmScreenSettings),0,DM_PELSWIDTH|DM_PELSHEIGHT,
0,0,0,0,0,0,0,0,0,0,0,0,0,"",0,0,gi_ScreenWidth,gi_ScreenHeight
};
#pragma code_seg(".compile")
__forceinline unsigned int compileShader(const char* vsh, const char* fsh)
{
GLuint s,p;
p = ((PFNGLCREATEPROGRAMPROC)wglGetProcAddress("glCreateProgram"))();
s = ((PFNGLCREATESHADERPROC)(wglGetProcAddress("glCreateShader")))(GL_VERTEX_SHADER);
((PFNGLSHADERSOURCEPROC)wglGetProcAddress("glShaderSource")) (s, 1, &vsh, NULL);
((PFNGLCOMPILESHADERPROC)wglGetProcAddress("glCompileShader"))(s);
((PFNGLATTACHSHADERPROC)wglGetProcAddress("glAttachShader")) (p,s);
s = ((PFNGLCREATESHADERPROC)wglGetProcAddress("glCreateShader"))(GL_FRAGMENT_SHADER);
((PFNGLSHADERSOURCEPROC)wglGetProcAddress("glShaderSource")) (s, 1, &fsh, NULL);
((PFNGLCOMPILESHADERPROC)wglGetProcAddress("glCompileShader"))(s);
((PFNGLATTACHSHADERPROC)wglGetProcAddress("glAttachShader")) (p,s);
((PFNGLLINKPROGRAMPROC)wglGetProcAddress("glLinkProgram"))(p);
((PFNGLUSEPROGRAMPROC)wglGetProcAddress("glUseProgram"))(p);
return p;
}
#pragma code_seg(".main")
#ifdef _DEBUG
DWORD WINAPI filemon(void* args)
{
while (true)
{
_finddata_t fdata;
long hfile = _findfirst(gs_ShaderFile, &fdata);
if (hfile != -1)
{
if (fdata.time_write != gi_ShaderChangedDate)
{
gi_ShaderChangedDate = fdata.time_write;
::SetEvent(gh_ShaderCompileEvent);
std::cout << "Shader loaded." << std::endl;
}
_findclose(hfile);
}
::Sleep(100);
}
return 0;
}
#endif
void _cdecl main()
{
#ifdef _DEBUG
//ChangeDisplaySettings (&dmScreenSettings,CDS_FULLSCREEN);
//HDC hDC = GetDC(CreateWindow("edit", 0, WS_POPUP | WS_VISIBLE | WS_MAXIMIZE, 0, 0, 0, 0, 0, 0, 0, 0));
HDC hDC = GetDC(CreateWindow("static", "Test", WS_EX_APPWINDOW | WS_VISIBLE | WS_SYSMENU, 0, 0, gi_ScreenWidth, gi_ScreenHeight, 0, 0, 0, 0));
SetPixelFormat(hDC, ChoosePixelFormat(hDC, &pfd), &pfd);
wglMakeCurrent(hDC, wglCreateContext(hDC));
initShaders();
gh_ShaderCompileEvent = ::CreateEvent(NULL, FALSE, FALSE, TEXT("WriteEvent"));
SetThreadPriority((HANDLE)CreateThread(0, 0, &filemon, 0, 0, 0), THREAD_PRIORITY_BELOW_NORMAL);
::Sleep(1000);
#else
ChangeDisplaySettings (&dmScreenSettings,CDS_FULLSCREEN);
HDC hDC = GetDC(CreateWindow("edit", 0, WS_POPUP | WS_VISIBLE | WS_MAXIMIZE, 0, 0, 0, 0, 0, 0, 0, 0));
//HDC hDC = GetDC(CreateWindow("static", "Test", WS_EX_APPWINDOW | WS_VISIBLE | WS_SYSMENU, 0, 0, gi_ScreenWidth, gi_ScreenHeight, 0, 0, 0, 0));
SetPixelFormat(hDC, ChoosePixelFormat(hDC, &pfd), &pfd);
wglMakeCurrent(hDC, wglCreateContext(hDC));
compileShader(vsh, fsh);
#endif
#ifdef _DEBUG
if (::WaitForSingleObject(gh_ShaderCompileEvent, 0) == WAIT_OBJECT_0)
{
::Sleep(250);
gi_ShaderProgram = createProgram(createVertexShader(gs_VertexShader), createFragmentShader(gs_ShaderFile));
((PFNGLUSEPROGRAMPROC)wglGetProcAddress("glUseProgram"))(gi_ShaderProgram);
PrintErrors();
}
glColor4f(0,0,0, float(gi_ScreenWidth)/gi_ScreenHeight);
glRectf(-1, -1, 1, 1);
SwapBuffers(hDC);
#endif
InitSound();
ShowCursor(FALSE);
loop:
#ifdef _DEBUG
if (::WaitForSingleObject(gh_ShaderCompileEvent, 0) == WAIT_OBJECT_0)
{
::Sleep(250);
gi_ShaderProgram = createProgram(createVertexShader(gs_VertexShader), createFragmentShader(gs_ShaderFile));
((PFNGLUSEPROGRAMPROC)wglGetProcAddress("glUseProgram"))(gi_ShaderProgram);
PrintErrors();
}
#endif
float lf_Time = get_Time() * 71.0f / 240.0f;
glLoadIdentity();
glRotatef(-90.0f * lf_Time - 90.0f, 0, 1, 0);
glColor4f(get_Envelope(7), lf_Time, get_Envelope(2), gf_AspectRatio);
glRects(-1, -1, 1, 1);
SwapBuffers(hDC);
if (!GetAsyncKeyState(VK_ESCAPE) && lf_Time < 30.0f) goto loop;
ExitProcess(0);
}

462
bp4k/src/bp4k/mark.fs Normal file
View File

@@ -0,0 +1,462 @@
// Parameters from our host
// x: #sceneid.#scenetime (float)
// y: undefined
// z: Snare drum intensity (amiga ball radius gain)
// w: undefined
varying vec4 Y;
// Position of the fragment
varying vec2 Z;
// Forward declarations
vec4 traceRay(vec3, vec3, int);
vec3 shade(vec4, vec3, vec3);
// All data of our world
vec3 spherePos, lightDir, lightColor, waterColor, ro, rd, interlacing;
float sphereRadius, gf_DetailLevel, pi, eps, bigeps;
// Pseudo random number base generator (credits go to iq/rgba)
float rnd(vec2 x)
{
int n = int(x.x * 40 + x.y * 6400);
n = (n << 13) ^ n;
return 1 - float( (n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824;
}
// Generate cubic interpolated random values
float smoothrnd(vec2 x)
{
x = mod(x,1000.0);
vec2 a = fract(x);
x -= a;
vec2 u = a*a*(3.0-2.0*a);
return mix(
mix(rnd(x+vec2(0,0)),rnd(x+vec2(1,0)), u.x),
mix(rnd(x+vec2(0,1)),rnd(x+vec2(1,1)), u.x), u.y);
}
// Convert the cipher range from [-1,1] to [0,1]
float norm(float x)
{
return x * 0.5 + 0.5;
}
// Generate animated (t) caustic values
float caustic(float u, float v, float t)
{
float a = (
norm(sin(pi * 2 * (u + v + Y.x*t))) +
norm(sin(pi * (v - u - Y.x*t))) +
norm(sin(pi * (v + Y.x*t))) +
norm(sin(pi * 3 * (u - Y.x*t)))) * 0.3;
return pow(a, 2.0);
}
// Calculate our TV effects (interlacing and RGB mask)
vec3 pp(vec3 color)
{
int c = int(mod(gl_FragCoord.x, 3.0));
if (c==0) color *= interlacing.xyz;
if (c==1) color *= interlacing.yzx;
if (c==2) color *= interlacing.zxy;
return color;
}
// Our fake godray effect (bad if moving fast, but awesome any other time)
vec3 godrays(vec3 color)
{
vec2 dpos = Z*2-1;
float g = dpos.x * (dpos.y + 3);
return color + lightColor *
caustic(g + 50 * ro.x, g + 50 * ro.z, 1.5) *
(norm(dpos.y)) * min(-ro.y * 30, 0.3);
}
// Our heightmap calculation function, we could use some perlin noise here if it wouldn't be so performance killing
float height(vec2 x)
{
return (-0.035 + pow((caustic(x.x * 10, x.y * 10, 0.0) * 2 - 1), 2.0) * 0.05)
- (x.x - 0.1) * 0.2; // This line creates one entire continent and a big ocean!
}
// Gets the terrain normal
vec3 getTerrainNormal(vec3 p)
{
return normalize(vec3(
height(p.xz - vec2(bigeps, 0)) - height(p.xz + vec2(bigeps, 0)),
2 * bigeps,
height(p.xz - vec2(0, bigeps)) - height(p.xz + vec2(0, bigeps))));
}
// Global diffuse lighting formula
vec3 diffuseLight(vec3 incolor, vec3 normal)
{
return (0.3 + 0.7 * max(dot(normal, lightDir), 0.0)) * lightColor * incolor;
}
// Calculates the water "waves". To reduce the bumpiness, increment the y-axis
vec3 getWaterNormal(vec3 p)
{
return normalize(vec3(
caustic(p.x * 160 - cos(p.z * 10) * 12, p.z * 140, 4.0),
8,
caustic(p.z * 160 - sin(p.x * 10) * 12, p.x * 140, 4.0)) * 2 - 1);
}
// Calculate the terrain color for the given voxel
vec3 shadeTerrain(vec3 p, vec3 rd)
{
vec3 n = getTerrainNormal(p);
vec3 color = mix(
// sandy color
vec3(0.66, 0.55, 0.4)
// basic color (big random color spots)
- 0.2 * smoothrnd(abs(p.xz * 150))
// texture (sediment lines)
- 0.2 * smoothrnd(abs(p.yy + 0.002 * smoothrnd(abs(p.xz * 150))) * 3000),
// interleaved grass, hight dependant
vec3(0.1, 0.3, 0) * (smoothrnd(p.xz * 7000.0) * 0.4 + 0.5),
// mixing for the sand/grass transition
clamp(n.y * (caustic(p.x * 111, p.z * 111, 0.0) * 0.5 - p.y * 40), 0.0, 1.0));
// caustics, only underwater (no cloudshadows, though)
if (p.y <= 0)
color += 5 * getWaterNormal(0.8 * p).x * min(0.3, -p.y * 8);
// Light
return diffuseLight(color, n);
}
// Create a blueish sky transition from navy blue to badass dark blue
vec3 shadeSky(vec3 ro, vec3 rd)
{
return ro.y <= -eps*eps ?
waterColor :
mix(vec3(-0.5, -0.25, 0), vec3(2), 1 - (rd.y * 0.5 + 0.5));
}
// Calculates the refraction and reflection of the water surface.
// Also mixes both values by the depth of the water and the fresnel term.
// Possible improvements: fix fake underwater reflection and refraction
vec3 shadeWaterRefl(vec3 p, vec3 newrd)
{
vec3 waterNormal = getWaterNormal(p);
// perform raytracing/raymarching for both reflection and refraction
// calc the water refraction, the refraction index (0.9) will decrease with the distance to allow a better over/under water transition
vec4 refracted = traceRay(p, refract(newrd, waterNormal, 0.9), 2);//mix(0.9, 1.0, smoothstep(0.01, 0.0, length(p-ro)))), 2);
// calculate the depth factor (water entry point to terrain voxel) (black magic involved here!)
float depth = clamp(pow(1.03 * (1 - length(refracted.xyz - p)), 16.0), 0.0, 1.0);
// Finally stir the pot =)
return mix(
ro.y < 0 ? shadeSky(p, newrd) : waterColor, // Water color
mix(
shade(traceRay(p, reflect(newrd, waterNormal), 2), p, newrd), // Reflection color
shade(refracted, p, newrd), // Refraction color
clamp(-rd.y + depth, 0.0, 1.0)), // fresnel term
refracted.w == 3.0 ? 0.5 : pow(depth, 0.5)); // water color contribution
}
// Texture our "AMIGAAAAAAA!!" ball
vec3 shadeAttractor(vec3 p, vec3 rd)
{
vec3 n,color;
// get the sphere normal, first
n = normalize(p - spherePos);
// now calculate the texture coordinates
vec2 uv = 0.5 + 0.5 * vec2(atan(n.z, n.x), acos(n.y)) / pi;
// We'll animate our x-texture coordinate with the time, this gives the impression of a rotating ball
uv.x -= Y.x;
// This spell will convert any dull ball into an amiga ball, caution is advised.
color = mix(vec3(1), vec3(1, 0, 0), mod(step(fract(uv.x * 6), 0.5) + step(fract(uv.y * 6), 0.5), 2.0));
return diffuseLight(color, n)
+ pow(max(dot(n, normalize(lightDir - rd)), 0.0), 33.0) * lightColor; // specular light spot
}
// Raymarch the terrain function, returns the distance from the ray origin to the terrain voxel
// This function was originally adopted from an implementation by iq/rgba
float traceTerrain(vec3 ro, vec3 rd, float maxt)
{
float delt, lh, ly, samplePosY;
delt = 0; // If the world would consist of only nVidia GPUs, this line wouldn't exist.
vec3 samplePos = ro;
// advance our sample position from our nearplane to our farplane
for (float t = 0; t < maxt; t += delt)
{
// advance our ray
samplePos += rd * delt;
samplePosY = samplePos.y;
// get the height at the given sample 2d (!) position (we could enhance this by sampling a voxel and returning only the distance to the voxel)
float h = height(samplePos.xz);
if (samplePosY <= h)
{
// we need to know our improved (more accuracy here) real terrainposition and the old sampleposition
// also we precalculate the traveled ray distance (its not a ray anymore if we use stuff like refraction, eg but hey lets stick to this word)
return t - delt + delt*(lh-ly)/(samplePosY-h+lh-ly);
}
// store our last height and last sampleposition on the y-axis
// we need this to calculate the improved terrainposition which will give us a smoother transition between our samplesteps (rd*delt)
lh = h;
ly = samplePosY;
// advance our steplength the more we travel the bigger our stepsize should be
// with this we are able to sample finer details near to our camera
delt = 0.002 + (t/gf_DetailLevel);
}
// we hit nothing
return 9.0;
}
// Ray vs. sphere intersection function
float traceAttractor(vec3 ro, vec3 rd)
{
vec3 dst = ro - spherePos;
float B,D;
B = dot(dst, rd);
if (B > 0)
return 9.0;
D = B*B - dot(dst, dst) + sphereRadius*sphereRadius;
if (D > 0)
{
return -B - sqrt(D);
}
return 9.0;
}
// Ray vs. plane intersection function
float traceWater(vec3 ro, vec3 rd)
{
float tPlane = -ro.y / rd.y;
return tPlane >= eps ? tPlane : 9.0;
}
// Raytracing entry point, returns voxel and object ID
// IDs:
// 0 = sky (not the armageddon, xTr1m!!)
// 1 = terrain
// 2 = water
// 3 = attractive amiga ball (you have never seen such a sexy amiga ball before, admit it!)
vec4 traceRay(vec3 ro, vec3 rd, int ignore)
{
float water, attractor, terrain, minDist;
// trace only the objects we need (only one could maximally be ignored)
water = ignore != 2 ? traceWater(ro, rd) : 9.0;
attractor = ignore != 3 ? traceAttractor(ro, rd) : 9.0;
terrain = ignore != 1 ? traceTerrain(ro, rd, min(0.5, 0.002+min(water, attractor))) : 9.0;
// auto detail level reducing (common dude, give the GPU some breathing room)
gf_DetailLevel /= 20;
// find the nearest distance
minDist = min(terrain, min(water, min(attractor, 9.0)));
// we hit nothing or the hitpoint is too far
if (minDist == 9)
return vec4(0);
// calculate the hit/voxel position
vec3 hitPos = ro + rd * minDist;
// check what we might have hit
if (minDist == terrain)
return vec4(hitPos, 1);
if (minDist == water)
return vec4(hitPos, 2);
if (minDist == attractor)
return vec4(hitPos, 3);
// Panic, worry, die to death! Probably we'll land on the moon (this should never happen)
//return vec4(0);
}
// Entrypoint for color calculation
vec3 shadeRefl(vec4 hitPoint, vec3 newRo, vec3 rd)
{
// determine the fog color for this very precise point in the space time continuum
vec3 myFog = newRo.y < eps ? waterColor : shadeSky(ro, rd);
// generate the distance value for the fog calculation
float distance = clamp(length(hitPoint.xyz - newRo) * (ro.y <= 0 ? 4 : 2), 0.0, 1.0);
// get the color of the hit object and mix it with the fog
// in most cases we allow further raytracing here (not for the terrain, its not shiny enough)
if (hitPoint.w == 1)
return mix(shadeTerrain(hitPoint.xyz, rd), myFog, distance);
if (hitPoint.w == 2)
return mix(shadeWaterRefl(hitPoint.xyz, rd), myFog, distance);
if (hitPoint.w == 3)
return mix(
// Our amiga ball is shiny so reflect the scene!
mix(shadeAttractor(hitPoint.xyz, rd), shade(traceRay(hitPoint.xyz, reflect(rd, normalize(hitPoint.xyz - spherePos)), 3), hitPoint.xyz, rd), 0.5)
, myFog, distance);
return shadeSky(newRo, rd);
}
// Get the color from the object we just hit (without further raytraces)
// this is necessary because no recursion is allowed in GLSL (damn you!)
vec3 shade(vec4 hitPoint, vec3 newRo, vec3 rd)
{
// determine the fog color for the very same point we discussed earlier
vec3 myFog = newRo.y < eps ? waterColor : shadeSky(ro, rd);
// generate the other distance value. Paid attention? If you don't know what value I'm talking about, rtfm or gtfo.
float distance = clamp(length(hitPoint.xyz - newRo) * (ro.y <= 0 ? 4 : 2), 0.0, 1.0);
// get the color of the hit object and mix it with the fog
if (hitPoint.w == 1)
return mix(shadeTerrain(hitPoint.xyz, rd), myFog, distance);
if (hitPoint.w == 2)
return mix(waterColor, myFog, distance);
if (hitPoint.w == 3)
return mix(shadeAttractor(hitPoint.xyz, rd), myFog, distance);
return myFog;
}
// Now we're just being copycats. We're not creative enough to define own entry points
// Sure, we could "#define MYENTRYPOINT main"! Or just void main(){MyEntryPoint();}
// None of that would help us win the compo, would it?
void main()
{
// Set the quality setting for the raymarcher, a higher value results in a longer processing time
// try to find a good balance between these two, low values will result in a wobbling endresult
// low quality = 50.0 (visual results are ok at 640x480)
// mid quality = 100.0
// high quality = 200.0
gf_DetailLevel = 100;
// Give our saviour global variables some life!
pi = 3.1416;
interlacing = vec3(1.2, 0.9, 0.9);
eps = 0.0001;
bigeps = 0.01;
// Nifty random number generator gets initialized
float seed = 10;
// Determine the scene we're in
int scene = int(Y.x);
// Get the look direction for the current pixel (always look forwards)
rd = vec3((Z.xy - 0.5), 1);
// Merry-go-round on a boat (yeah, this makes no sense. Go watch the intro and see for yourself)
if (scene > 22 && scene < 27)
{
seed = min(1.0, sin((Y.x-23)*pi*0.25)*12);
ro = vec3(0.12, 0.005, Y.x*0.08);
rd = vec3(gl_ModelViewMatrix * vec4(rd, 1));
rd.y += 0.1*cos(Y.x*4);
}
// Intermezzo: Dolphin like animation inside and outside the water, chasing that amiga ball!
else if (scene > 14 && scene < 23)
{
seed = min(1.0, sin((Y.x-15)*pi*0.125)*24);
rd += vec3(0,0.1*cos(Y.x*4), 0);
ro = vec3(0.08, 0.01*sin(Y.x*4)+0.002, Y.x*0.11);
}
// Intro and Outro: Show still scenes
else
{
// Get a random initial position for our camera
ro = vec3(0.1,0.004,0.0) + vec3(0.1,0.005,20)
*vec3(rnd(vec2(scene, seed++)), rnd(vec2(scene, seed++)), rnd(vec2(scene, seed++)));
// Basing on the initial position, choose some "random" start and end points nearby
ro = mix(
ro+vec3(0.008)*vec3(rnd(vec2(scene, seed++)), rnd(vec2(scene, seed++)), rnd(vec2(scene, seed++))),
ro+vec3(0.008)*vec3(rnd(vec2(scene, seed++)), rnd(vec2(scene, seed++)), rnd(vec2(scene, seed++))),
// and move the camera!
Y.x-scene);
// We adjust the height of the camera to the terrain height
ro.y += height(ro.xz)+0.02;
// Deviate the camera position in the direction of the normal of the underlying terrain
ro += 0.02*getTerrainNormal(ro);
// Reusing a float variable here, this controls the scene fade in / fade out animation
seed = min(1.0, step(-28.0, -Y.x) * sin((Y.x-scene)*pi)*3);
}
rd = normalize(rd);
// Now boot the amiga workbench (erm, no...)
// mantain a relative distance to the camera
if (scene > 22 && scene < 27)
spherePos = ro + 0.1 * vec3(gl_ModelViewMatrix * vec4(0, 0, 1, 1));
else
spherePos = ro + 0.02 * vec3(sin(Y.x), 0, 5+cos(Y.x));
spherePos.y += 0.01 + height(spherePos.xz); // mantain a relative height to the underlying terrain
sphereRadius = scene < 14 ? 0.0 : bigeps * 0.5 + bigeps * Y.z; // The amiga ball is bigger when the snare drum is hit!
spherePos += 2*sphereRadius * getTerrainNormal(spherePos); // deviate according to the underlying terrain's normal
// Make our world pretty and worthy to live in (you can cultivate algae and eat them, they're surely enough for survival)
lightDir = vec3(0.58, 0.58, -0.58);
lightColor = vec3(1.2);
waterColor = vec3(0.3, 0.33, 0.4);
// Our GPU feels good underwater, almost like a refreshing experience :) cool, eh?
if (ro.y <= 0)
{
// Less work to do...
gf_DetailLevel *= 0.75;
// ...and a cozy darker atmosphere
lightColor *= 0.8;
}
// Here we go, shoot'em rays and get the color of our fragment!
vec3 color = shadeRefl(traceRay(ro, rd, 0), ro, rd);
// Underwater there are beams of light emanating from god (so called "god" rays...)
// ...this prooves that god is nothing less than a water surface.
if (ro.y <= 0)
color = godrays(color);
// Apply post processing and fade effects to the color, and finally return it.
gl_FragColor.xyz = pp(step(2.0, Y.x) * seed * color);
}

191
bp4k/src/bp4k/release.h Normal file
View File

@@ -0,0 +1,191 @@
#pragma once
#pragma data_seg(".shaders")
static char* fsh =
"#define ve return\n" // Line 1
"#define ec float\n" // Line 1
"varying vec4 Y;" // Line 6
"varying vec2 Z;" // Line 9
"vec4 R(vec3 n,vec3 m,int k);" // Line 12
"vec3 T(vec4 j,vec3 l,vec3 m);" // Line 13
"vec3 f,b,a,h,e,d,X;" // Line 17
"ec g,W,c,V,U;ec A(vec2 j){" // Line 18
"int i=int(j.x*40+j.y*6400);" // Line 24
"i=(i<<13)^i;" // Line 25
"ve 1-ec((i*(i*i*15731+789221)+1376312589)&0x7fffffff)/1073741824;}ec B(vec2 k){" // Line 26
"k=mod(k,1000.);" // Line 33
"vec2 i=fract(k);" // Line 34
"k-=i;" // Line 35
"vec2 j=i*i*(3.-2.*i);" // Line 36
"ve mix(" // Line 37
"mix(A(k+vec2(0,0)),A(k+vec2(1,0)),j.x)," // Line 38
"mix(A(k+vec2(0,1)),A(k+vec2(1,1)),j.x),j.y);}ec C(ec i){" // Line 39
"ve i*.5+.5;}ec D(ec k,ec l,ec j){" // Line 46
"ec i=(" // Line 53
"C(sin(c*2*(k+l+Y.y*j)))+" // Line 54
"C(sin(c*(l-k-Y.y*j)))+" // Line 55
"C(sin(c*(l+Y.y*j)))+" // Line 56
"C(sin(c*3*(k-Y.y*j))))*.3;" // Line 57
"ve pow(i,2.);}vec3 E(vec3 j){" // Line 58
"int i=int(mod(gl_FragCoord.x,3.));" // Line 65
"if(i==0)j*=X.xyz;" // Line 66
"if(i==1)j*=X.yzx;" // Line 67
"if(i==2)j*=X.zxy;" // Line 68
"ve mix(j,vec3(C(B(Z*333+A(vec2(Y.y))*33333))),Y.x*.3+.03);}vec3 F(vec3 i){" // Line 69
"vec2 j=Z*2-1;" // Line 76
"ec k=j.x*(j.y+3);" // Line 77
"ve i+a*" // Line 78
"D(k+50*e.x,k+50*e.z,1.5)*" // Line 79
"(C(j.y))*min(-e.y*30,.3);}ec G(vec2 i){" // Line 80
"ve (-.035+pow((D(i.x*10,i.y*10,.0)*2-1),2.)*.05)" // Line 87
"-(i.x-.1)*.2;}vec3 H(vec3 i){" // Line 88
"ve normalize(vec3(" // Line 95
"G(i.xz-vec2(U,0))-G(i.xz+vec2(U,0))," // Line 96
"2*U," // Line 97
"G(i.xz-vec2(0,U))-G(i.xz+vec2(0,U))));}vec3 I(vec3 i,vec3 j){" // Line 98
"ve (.3+.7*max(dot(j,b),.0))*a*i;}vec3 J(vec3 i){" // Line 105
"ve normalize(vec3(" // Line 112
"D(i.x*160-cos(i.z*10)*12,i.z*140,4.)," // Line 113
"8," // Line 114
"D(i.z*160-sin(i.x*10)*12,i.x*140,4.))*2-1);}vec3 K(vec3 k,vec3 l){" // Line 115
"vec3 j=H(k);" // Line 122
"vec3 i=mix(" // Line 123
"vec3(.66,.55,.4)" // Line 125
"-.2*B(abs(k.xz*150))" // Line 128
"-.2*B(abs(k.yy+.002*B(abs(k.xz*150)))*3000)," // Line 131
"vec3(.1,.3,0)*(B(k.xz*7000.)*.4+.5)," // Line 134
"clamp(j.y*(D(k.x*111,k.z*111,.0)*.5-k.y*40),.0,1.));" // Line 137
"if(k.y<=0)" // Line 140
"i+=5*J(.8*k).x*min(.3,-k.y*8);" // Line 141
"ve I(i,j);}vec3 L(vec3 j,vec3 i){" // Line 144
"ve j.y<=-V*V?" // Line 151
"h:" // Line 152
"mix(vec3(-.5,-.25,0),vec3(2),1-(i.y*.5+.5));}vec3 M(vec3 k,vec3 j){" // Line 153
"vec3 m=J(k);" // Line 162
"vec4 l=R(k,refract(j,m,.9),2);" // Line 166
"ec i=clamp(pow(1.03*(1-length(l.xyz-k)),16.),.0,1.);" // Line 169
"ve mix(" // Line 172
"e.y<0?L(k,j):h," // Line 173
"mix(" // Line 174
"T(R(k,reflect(j,m),2),k,j)," // Line 175
"T(l,k,j)," // Line 176
"clamp(-d.y+i,.0,1.))," // Line 177
"l.w==3.?.5:pow(i,.5));}vec3 N(vec3 k,vec3 l){" // Line 178
"vec3 j,i;" // Line 186
"j=normalize(k-f);" // Line 189
"vec2 m=.5+.5*vec2(atan(j.z,j.x),acos(j.y))/c;" // Line 192
"m.x-=Y.y;" // Line 195
"i=mix(vec3(1),vec3(1,0,0),mod(step(fract(m.x*6),.5)+step(fract(m.y*6),.5),2.));" // Line 198
"ve I(i,j)" // Line 200
"+pow(max(dot(j,normalize(b-l)),.0),33.)*a;}ec O(vec3 n,vec3 m,ec l){" // Line 201
"ec i,j,k,p;" // Line 209
"i=0;" // Line 210
"vec3 o=n;" // Line 211
"for(ec q=0;q<l;q+=i)" // Line 214
"{" // Line 215
"o+=m*i;" // Line 217
"p=o.y;" // Line 218
"ec r=G(o.xz);" // Line 221
"if(p<=r)" // Line 223
"{" // Line 224
"ve q-i+i*(j-k)/(p-r+j-k);}" // Line 227
"j=r;" // Line 232
"k=p;" // Line 233
"i=.002+(q/W);}" // Line 237
"ve 9.;}ec P(vec3 m,vec3 l){" // Line 241
"vec3 k=m-f;" // Line 248
"ec i,j;" // Line 249
"i=dot(k,l);" // Line 250
"if(i>0)" // Line 251
"ve 9.;" // Line 252
"j=i*i-dot(k,k)+g*g;" // Line 253
"if(j>0)" // Line 254
"{" // Line 255
"ve -i-sqrt(j);}" // Line 256
"ve 9.;}ec Q(vec3 j,vec3 i){" // Line 258
"ec k=-j.y/i.y;" // Line 265
"ve k>=V?k:9.;}vec4 R(vec3 n,vec3 m,int k){" // Line 266
"ec p,i,o,l;" // Line 278
"p=k!=2?Q(n,m):9.;" // Line 281
"i=k!=3?P(n,m):9.;" // Line 282
"o=k!=1?O(n,m,min(.5,.002+min(p,i))):9.;" // Line 283
"W/=20;" // Line 286
"l=min(o,min(p,min(i,9.)));" // Line 289
"if(l==9)" // Line 292
"ve vec4(0);" // Line 293
"vec3 j=n+m*l;" // Line 296
"if(l==o)" // Line 299
"ve vec4(j,1);" // Line 300
"if(l==p)" // Line 301
"ve vec4(j,2);" // Line 302
"if(l==i)" // Line 303
"ve vec4(j,3);}vec3 S(vec4 j,vec3 l,vec3 m){" // Line 304
"vec3 k=l.y<V?h:L(e,m);" // Line 315
"ec i=clamp(length(j.xyz-l)*(e.y<=0?4:2),.0,1.);" // Line 318
"if(j.w==1)" // Line 322
"ve mix(K(j.xyz,m),k,i);" // Line 323
"if(j.w==2)" // Line 324
"ve mix(M(j.xyz,m),k,i);" // Line 325
"if(j.w==3)" // Line 326
"ve mix(" // Line 327
"mix(N(j.xyz,m),T(R(j.xyz,reflect(m,normalize(j.xyz-f)),3),j.xyz,m),.5)" // Line 329
",k,i);" // Line 330
"ve L(l,m);}vec3 T(vec4 j,vec3 l,vec3 m){" // Line 332
"vec3 k=l.y<V?h:L(e,m);" // Line 341
"ec i=clamp(length(j.xyz-l)*(e.y<=0?4:2),.0,1.);" // Line 344
"if(j.w==1)" // Line 347
"ve mix(K(j.xyz,m),k,i);" // Line 348
"if(j.w==2)" // Line 349
"ve mix(h,k,i);" // Line 350
"if(j.w==3)" // Line 351
"ve mix(N(j.xyz,m),k,i);" // Line 352
"ve k;}void main(){" // Line 354
"W=100;" // Line 368
"c=3.1416;" // Line 371
"X=vec3(1.2,.9,.9);" // Line 372
"V=.0001;" // Line 373
"U=.01;" // Line 374
"ec k=10;" // Line 377
"int j=int(Y.y);" // Line 380
"d=vec3((Z.xy-.5),1);" // Line 383
"if(j>22&&j<27)" // Line 386
"{" // Line 387
"k=min(1.,sin((Y.y-23)*c*.25)*12);" // Line 388
"e=vec3(.12,.005,Y.y*.08);" // Line 389
"d=vec3(gl_ModelViewMatrix*vec4(d,1));" // Line 390
"d.y+=.1*cos(Y.y*4);}" // Line 391
"else if(j>14&&j<23)" // Line 394
"{" // Line 395
"k=min(1.,sin((Y.y-15)*c*.125)*24);" // Line 396
"d+=vec3(0,.1*cos(Y.y*4),0);" // Line 397
"e=vec3(.08,.01*sin(Y.y*4)+.002,Y.y*.11);}" // Line 398
"else " // Line 402
"{" // Line 403
"e=vec3(.1,.004,.0)+vec3(.1,.005,20)" // Line 405
"*vec3(A(vec2(j,k++)),A(vec2(j,k++)),A(vec2(j,k++)));" // Line 406
"e=mix(" // Line 409
"e+vec3(.008)*vec3(A(vec2(j,k++)),A(vec2(j,k++)),A(vec2(j,k++)))," // Line 410
"e+vec3(.008)*vec3(A(vec2(j,k++)),A(vec2(j,k++)),A(vec2(j,k++)))," // Line 411
"Y.y-j);" // Line 413
"e.y+=G(e.xz)+.02;" // Line 416
"e+=.02*H(e);" // Line 419
"k=min(1.,step(-28.,-Y.y)*sin((Y.y-j)*c)*3);}" // Line 422
"d=normalize(d);" // Line 425
"if(j>22&&j<27)" // Line 429
"f=e+.1*vec3(gl_ModelViewMatrix*vec4(0,0,1,1));" // Line 430
"else " // Line 432
"f=e+.02*vec3(sin(Y.y),0,5+cos(Y.y));" // Line 433
"f.y+=.01+G(f.xz);" // Line 435
"g=j<14?.0:U*.5+U*Y.z;" // Line 436
"f+=2*g*H(f);" // Line 437
"b=vec3(.58,.58,-.58);" // Line 440
"a=vec3(1.2);" // Line 441
"h=vec3(.3,.33,.4);" // Line 442
"if(e.y<=0)" // Line 445
"{" // Line 446
"W*=.75;" // Line 448
"a*=.8;}" // Line 451
"vec3 i=S(R(e,d,0),e,d);" // Line 455
"if(e.y<=0)" // Line 459
"i=F(i);" // Line 460
"gl_FragColor.xyz=E(step(2.,Y.y)*k*i);}";

127
bp4k/src/bp4k/small.h Normal file
View File

@@ -0,0 +1,127 @@
#pragma once
#pragma code_seg("sm0")
DWORD x_Ftol(float af_Value)
{
DWORD ldw_RetVal;
__asm fld af_Value
__asm fistp ldw_RetVal
return ldw_RetVal;
}
#pragma code_seg("sm1")
__forceinline float x_Frac(float af_Value)
{
return af_Value - x_Ftol(af_Value);
}
#pragma code_seg("sm2")
__forceinline float x_Abs(float af_Value)
{
__asm fld af_Value
__asm fabs
}
#pragma code_seg("sm3")
float x_Sin(float af_Value)
{
__asm fld af_Value
__asm fsin
}
#pragma code_seg("sm4")
float x_Sign(float af_Value)
{
if (af_Value != 0)
return af_Value / x_Abs(af_Value);
return 1.0f;
}
#pragma code_seg("sm5")
float x_Sqrt(float af_Value)
{
__asm fld af_Value
__asm fsqrt
}
#pragma code_seg("sm7")
__forceinline void x_MemCopy(void* av_Dest_, const void* av_Src_, size_t ai_Size)
{
__asm mov esi, av_Src_
__asm mov edi, av_Dest_
__asm mov ecx, ai_Size
__asm rep movsb
}
#pragma code_seg("sm8")
float x_Fmod(float x, float y)
{
__asm fld y
__asm fld x
__asm fprem
__asm fxch
__asm fstp x
}
#pragma data_seg("smA")
static unsigned long seed=0x12345678;
#pragma code_seg("sm9")
__forceinline void x_Randomize(unsigned long x)
{
seed = x;
}
#pragma code_seg("smB")
float x_Rand()
{
seed = seed * 0x76364873 + 1234567;
return (float)(seed & 0x7FFFFFFF) * (const float)(2.0f / (float)0x7FFFFFFF) - 1.0f;
}
#pragma code_seg("smS")
__forceinline size_t x_Strlen(const char* as_String)
{
size_t li_Length = 0;
while (*as_String++) ++li_Length;
return li_Length;
}
#pragma code_seg("smP")
float x_Pow(float x, float y){
float r;
__asm{
fld y
fld x
fyl2x
fld1
fld st(1)
fprem
f2xm1
faddp st(1),st
fscale
fxch st(1)
fstp st(0)
fstp r
}
return r;
}
extern "C"
{
int _fltused = 1;
}

99
bp4k/src/bp4k/synth.cpp Normal file
View File

@@ -0,0 +1,99 @@
#define WIN32_LEAN_AND_MEAN
#define WIN32_EXTRA_LEAN
#include "windows.h"
#include "mmsystem.h"
#include "mmreg.h"
// define this if you have a multicore cpu and can spare ~15 bytes for realtime playback
// undef for sound precalc
#define USE_SOUND_THREAD
////////////////////////////////////////////////
// sound
////////////////////////////////////////////////
#define SAMPLE_RATE 44100
#define MAX_SAMPLES SAMPLE_RATE*2*60*20
#pragma bss_seg(".synthnothing")
static float lpSoundBuffer[MAX_SAMPLES];
static HWAVEOUT hWaveOut;
/////////////////////////////////////////////////////////////////////////////////
// initialized data
/////////////////////////////////////////////////////////////////////////////////
#pragma data_seg(".wavefmt")
WAVEFORMATEX WaveFMT =
{
WAVE_FORMAT_IEEE_FLOAT,
2, // channels
SAMPLE_RATE, // samples per sec
SAMPLE_RATE*4*2, // bytes per sec
8, // block alignment;
32, // bits per sample
0 // extension not needed
};
#pragma data_seg(".wavehdr")
WAVEHDR WaveHDR =
{
(LPSTR)lpSoundBuffer,
MAX_SAMPLES*4,
0,
0,
0,
0,
0,
0
};
#pragma data_seg(".mmtime")
MMTIME MMTime =
{
TIME_SAMPLES,
0
};
// declaration of the external synth render function, you'll always need that
extern "C" void _4klang_render(float*);
// declaration of the external envelope buffer. only include if you're song was exported with that option
extern "C" float _4klang_envelope_buffer;
/////////////////////////////////////////////////////////////////////////////////
// Initialization
/////////////////////////////////////////////////////////////////////////////////
#ifdef USE_SOUND_THREAD
#pragma code_seg(".sndthrd")
DWORD WINAPI SoundThread( LPVOID lpParam )
{
_4klang_render(lpSoundBuffer);
return 0;
}
#endif
#pragma code_seg(".initsnd")
extern "C" void InitSound()
{
#ifdef USE_SOUND_THREAD
CreateThread(0, 0, SoundThread, 0, 0, 0);
#else
_4klang_render(lpSoundBuffer);
#endif
waveOutOpen ( &hWaveOut, WAVE_MAPPER, &WaveFMT, NULL, 0, CALLBACK_NULL );
waveOutPrepareHeader( hWaveOut, &WaveHDR, sizeof(WaveHDR) );
waveOutWrite ( hWaveOut, &WaveHDR, sizeof(WaveHDR) );
}
#pragma code_seg(".envelope")
extern "C" float get_Envelope(int instrument)
{
return (&_4klang_envelope_buffer)[((MMTime.u.sample >> 8) << 5) + 2*instrument];
}
#pragma code_seg(".time")
extern "C" float get_Time()
{
waveOutGetPosition(hWaveOut, &MMTime, sizeof(MMTIME));
return float(MMTime.u.sample) / SAMPLE_RATE;
}

8
bp4k/src/bp4k/synth.h Normal file
View File

@@ -0,0 +1,8 @@
#pragma once
extern "C"
{
void InitSound();
float get_Envelope(int instrument);
float get_Time();
}

View File

@@ -0,0 +1,42 @@
#pragma once
class k_Camera
{
public:
k_Camera()
: mk_Position()
, mk_Center(0.0f, 0.0f, -1.0f)
, mk_Up(0.0f, 1.0f, 0.0f)
{
}
virtual ~k_Camera() {};
virtual void set_Position(const k_Vector& ak_Position) { mk_Position = ak_Position; };
virtual void set_Center(const k_Vector& ak_Center) { mk_Center = ak_Center; };
virtual void set_Up(const k_Vector& ak_Up) { mk_Up = ak_Up; mk_Up.normalize(); };
virtual k_Vector get_Position() { return mk_Position; };
virtual k_Vector get_Center() { return mk_Center; };
virtual k_Vector get_Up() { return mk_Up; };
virtual void Level(float af_Time)
{
k_Vector lk_Up(mk_Up);
k_Vector lk_Dir(mk_Center - mk_Position);
k_Vector lk_Right;
lk_Right = lk_Dir.cross(lk_Up);
lk_Up = lk_Right.cross(lk_Dir);
lk_Up.normalize();
k_Vector lk_Level(k_Vector(0.0f, 1.0f, 0.0f) - lk_Up);
lk_Up = (lk_Up + lk_Level * af_Time * 4.0f);
lk_Up.normalize();
mk_Up = lk_Up;
}
protected:
k_Vector mk_Position;
k_Vector mk_Center;
k_Vector mk_Up;
};

View File

@@ -0,0 +1,131 @@
#include "stdafx.h"
#include "FlightSimApplication.h"
#include "Shaders.h"
k_FlightSimApplication::k_FlightSimApplication()
{
}
k_FlightSimApplication::~k_FlightSimApplication()
{
}
void k_FlightSimApplication::OnInitialize()
{
initShaders();
mh_Shader = createProgram(createVertexShader("FlightSimShader.vs"), createFragmentShader("FlightSimShader.fs"));
mk_FlightDirection = k_Vector(0.0f, 0.0f, -1.0f);
mf_Speed = 0.0f;
mb_Dragging = false;
mf_ElapsedTime = 0.0f;
}
void k_FlightSimApplication::OnResize(int ai_Width, int ai_Height)
{
mi_Width = ai_Width;
mi_Height = ai_Height;
glViewport(0, 0, mi_Width, mi_Height);
}
void k_FlightSimApplication::OnDisplay(float af_Time)
{
mf_ElapsedTime += af_Time * 0.5f;
useProgram(mh_Shader);
glMatrixMode(GL_MODELVIEW);
k_Matrix lk_ModelViewMatrix = k_Matrix::rotateX(mk_YawPitchRoll.y);
lk_ModelViewMatrix *= k_Matrix::rotateY(mk_YawPitchRoll.x);
mk_FlightDirection = lk_ModelViewMatrix * k_Vector(0.0f, 0.0f, -1.0f);
mk_FlightDirection.normalize();
k_Vector lk_Pos = mk_Camera.get_Position() + mk_FlightDirection * af_Time * mf_Speed;
k_Vector lk_Right = mk_FlightDirection.cross(mk_Camera.get_Up());
k_Vector lk_Up = lk_Right.cross(mk_FlightDirection);
mk_Camera.set_Position(lk_Pos);
mk_Camera.set_Center(lk_Pos + mk_FlightDirection);
mk_Camera.set_Up(lk_Up);
mk_Camera.Level(af_Time);
glLoadIdentity();
gluLookAt(0, 0, 0,
-mk_FlightDirection.x, mk_FlightDirection.y, mk_FlightDirection.z,
mk_Camera.get_Up().x, mk_Camera.get_Up().y, mk_Camera.get_Up().z);
glNormal3fv(mk_Camera.get_Position().m);
glColor3f(mf_ElapsedTime, float(mi_Width) / mi_Height, 0);
glRects(-1, -1, 1, 1);
}
void k_FlightSimApplication::OnMouseButton(int ai_Button, bool ab_Pressed, int ai_PosX, int ai_PosY)
{
if (ab_Pressed)
{
mk_Mouse.x = (float)ai_PosX;
mk_Mouse.y = (float)ai_PosY;
mb_Dragging = true;
}
else
{
mb_Dragging = false;
}
}
void k_FlightSimApplication::OnMouseMove(int ai_PosX, int ai_PosY)
{
float lf_DeltaX = ai_PosX - mk_Mouse.x;
float lf_DeltaY = ai_PosY - mk_Mouse.y;
mk_Mouse.x = (float)ai_PosX;
mk_Mouse.y = (float)ai_PosY;
if (mb_Dragging)
{
mk_YawPitchRoll.x += lf_DeltaX * 0.01f;
mk_YawPitchRoll.y += lf_DeltaY * 0.01f;
}
}
void k_FlightSimApplication::OnKeyPressed(char ac_Char)
{
if (ac_Char == 'k') //+
{
mf_Speed -= 0.001f;
}
else if (ac_Char == 'm') //-
{
mf_Speed += 0.001f;
}
else if (ac_Char == 'W')
{
mk_Camera.set_Position(mk_Camera.get_Position() + k_Vector(0, 0.001f, 0, 0));
}
else if (ac_Char == 'A')
{
mk_Camera.set_Position(mk_Camera.get_Position() - k_Vector(0.001f, 0, 0, 0));
}
else if (ac_Char == 'S')
{
mk_Camera.set_Position(mk_Camera.get_Position() - k_Vector(0, 0.001f, 0, 0));
}
else if (ac_Char == 'D')
{
mk_Camera.set_Position(mk_Camera.get_Position() + k_Vector(0.001f, 0, 0, 0));
}
else
{
mk_YawPitchRoll = k_Vector();
mf_Speed = 0.0f;
}
}

View File

@@ -0,0 +1,35 @@
#pragma once
#include "Camera.h"
class __declspec(align(16)) k_FlightSimApplication
{
public:
HEAP_ALIGNED_CLASS(16);
k_FlightSimApplication();
~k_FlightSimApplication();
// IApplication:
void OnInitialize();
void OnResize(int ai_Width, int ai_Height);
void OnDisplay(float af_Time);
void OnMouseButton(int ai_Button, bool ab_Pressed, int ai_PosX, int ai_PosY);
void OnMouseMove(int ai_PosX, int ai_PosY);
void OnKeyPressed(char ac_Char);
private:
GLhandleARB mh_Shader;
k_Camera mk_Camera;
k_Vector mk_FlightDirection;
k_Vector mk_YawPitchRoll;
k_Quaternion mk_Orientation;
bool mb_Dragging;
float mf_Speed;
float mf_ElapsedTime;
int mi_Width;
int mi_Height;
k_Vector mk_Mouse;
};

View File

@@ -0,0 +1,359 @@
// Time
varying float T;
// Camera data
varying vec3 cameraPos;
// Position of the fragment
varying vec2 Z;
// Forward declarations
vec4 traceRay(vec3, vec3, int);
vec3 shade(vec4, vec3, vec3);
// All data of our world
vec3 lightDir, lightColor, waterColor, ro, rd, interlacing;
float gf_DetailLevel, pi, eps, bigeps;
// Pseudo random number base generator (credits go to iq/rgba)
float rnd(vec2 x)
{
int n = int(x.x * 40 + x.y * 6400);
n = (n << 13) ^ n;
return 1 - float( (n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824;
}
// Generate cubic interpolated random values
float smoothrnd(vec2 x)
{
x = mod(x,1000.0);
vec2 a = fract(x);
x -= a;
vec2 u = a*a*(3.0-2.0*a);
return mix(
mix(rnd(x+vec2(0,0)),rnd(x+vec2(1,0)), u.x),
mix(rnd(x+vec2(0,1)),rnd(x+vec2(1,1)), u.x), u.y);
}
// Convert the cipher range from [-1,1] to [0,1]
float norm(float x)
{
return x * 0.5 + 0.5;
}
// Generate animated (t) caustic values
float caustic(float u, float v, float t)
{
float a = (
norm(sin(pi * 2 * (u + v + T*t))) +
norm(sin(pi * (v - u - T*t))) +
norm(sin(pi * (v + T*t))) +
norm(sin(pi * 3 * (u - T*t)))) * 0.3;
return pow(a, 2.0);
}
// Calculate our TV effects (interlacing, RGB mask and film grain)
vec3 pp(vec3 color)
{
int c = int(mod(gl_FragCoord.x, 3.0));
if (c==0) color *= interlacing.xyz;
if (c==1) color *= interlacing.yzx;
if (c==2) color *= interlacing.zxy;
return mix(color, vec3(norm(smoothrnd(Z * 333 + rnd(vec2(T)) * 33333))), 0.03);
}
// Our fake godray effect (bad if moving fast, but awesome any other time)
vec3 godrays(vec3 color)
{
vec2 dpos = Z*2-1;
float g = dpos.x * (dpos.y + 3);
return color + lightColor *
caustic(g + 50 * ro.x, g + 50 * ro.z, 1.5) *
(norm(dpos.y)) * min(-ro.y * 30, 0.3);
}
// Our heightmap calculation function, we could use some perlin noise here if it wouldn't be so performance killing
float height(vec2 x)
{
return (-0.035 + pow((caustic(x.x * 10, x.y * 10, 0.0) * 2 - 1), 2.0) * 0.05)
- (x.x - 0.1) * 0.2; // This line creates one entire continent and a big ocean!
}
// Gets the terrain normal
vec3 getTerrainNormal(vec3 p)
{
return normalize(vec3(
height(p.xz - vec2(bigeps, 0)) - height(p.xz + vec2(bigeps, 0)),
2 * bigeps,
height(p.xz - vec2(0, bigeps)) - height(p.xz + vec2(0, bigeps))));
}
// Global diffuse lighting formula
vec3 diffuseLight(vec3 incolor, vec3 normal)
{
return (0.3 + 0.7 * max(dot(normal, lightDir), 0.0)) * lightColor * incolor;
}
// Calculates the water "waves". To reduce the bumpiness, increment the y-axis
vec3 getWaterNormal(vec3 p)
{
return normalize(vec3(
caustic(p.x * 160 - cos(p.z * 10) * 12, p.z * 140, 4.0),
8,
caustic(p.z * 160 - sin(p.x * 10) * 12, p.x * 140, 4.0)) * 2 - 1);
}
// Calculate the terrain color for the given voxel
vec3 shadeTerrain(vec3 p, vec3 rd)
{
vec3 n = getTerrainNormal(p);
vec3 color = mix(
// sandy color
vec3(0.66, 0.55, 0.4)
// basic color (big random color spots)
- 0.2 * smoothrnd(abs(p.xz * 150))
// texture (sediment lines)
- 0.2 * smoothrnd(abs(p.yy + 0.002 * smoothrnd(abs(p.xz * 150))) * 3000),
// interleaved grass, hight dependant
vec3(0.1, 0.3, 0) * (smoothrnd(p.xz * 7000.0) * 0.4 + 0.5),
// mixing for the sand/grass transition
clamp(n.y * (caustic(p.x * 111, p.z * 111, 0.0) * 0.5 - p.y * 40), 0.0, 1.0));
// caustics, only underwater (no cloudshadows, though)
if (p.y <= 0)
color += 5 * getWaterNormal(0.8 * p).x * min(0.3, -p.y * 8);
// Light
return diffuseLight(color, n);
}
// Create a blueish sky transition from navy blue to badass dark blue
vec3 shadeSky(vec3 ro, vec3 rd)
{
return ro.y <= -eps*eps ?
waterColor :
mix(vec3(-0.5, -0.25, 0), vec3(2), 1 - (rd.y * 0.5 + 0.5));
}
// Calculates the refraction and reflection of the water surface.
// Also mixes both values by the depth of the water and the fresnel term.
// Possible improvements: fix fake underwater reflection and refraction
vec3 shadeWaterRefl(vec3 p, vec3 newrd)
{
vec3 waterNormal = getWaterNormal(p);
// perform raytracing/raymarching for both reflection and refraction
// calc the water refraction, the refraction index (0.9) will decrease with the distance to allow a better over/under water transition
vec4 refracted = traceRay(p, refract(newrd, waterNormal, 0.9), 2);//mix(0.9, 1.0, smoothstep(0.01, 0.0, length(p-ro)))), 2);
// calculate the depth factor (water entry point to terrain voxel) (black magic involved here!)
float depth = clamp(pow(1.03 * (1 - length(refracted.xyz - p)), 16.0), 0.0, 1.0);
// Finally stir the pot =)
return mix(
ro.y < 0 ? shadeSky(p, newrd) : waterColor, // Water color
mix(
shade(traceRay(p, reflect(newrd, waterNormal), 2), p, newrd), // Reflection color
shade(refracted, p, newrd), // Refraction color
clamp(-rd.y + depth, 0.0, 1.0)), // fresnel term
refracted.w == 3.0 ? 0.5 : pow(depth, 0.5)); // water color contribution
}
// Raymarch the terrain function, returns the distance from the ray origin to the terrain voxel
// This function was originally adopted from an implementation by iq/rgba
float traceTerrain(vec3 ro, vec3 rd, float maxt)
{
float delt, lh, ly, samplePosY;
delt = 0; // If the world would consist of only nVidia GPUs, this line wouldn't exist.
vec3 samplePos = ro;
// advance our sample position from our nearplane to our farplane
for (float t = 0; t < maxt; t += delt)
{
// advance our ray
samplePos += rd * delt;
samplePosY = samplePos.y;
// get the height at the given sample 2d (!) position (we could enhance this by sampling a voxel and returning only the distance to the voxel)
float h = height(samplePos.xz);
if (samplePosY <= h)
{
// we need to know our improved (more accuracy here) real terrainposition and the old sampleposition
// also we precalculate the traveled ray distance (its not a ray anymore if we use stuff like refraction, eg but hey lets stick to this word)
return t - delt + delt*(lh-ly)/(samplePosY-h+lh-ly);
}
// store our last height and last sampleposition on the y-axis
// we need this to calculate the improved terrainposition which will give us a smoother transition between our samplesteps (rd*delt)
lh = h;
ly = samplePosY;
// advance our steplength the more we travel the bigger our stepsize should be
// with this we are able to sample finer details near to our camera
delt = 0.002 + (t/gf_DetailLevel);
}
// we hit nothing
return 9.0;
}
// Ray vs. plane intersection function
float traceWater(vec3 ro, vec3 rd)
{
float tPlane = -ro.y / rd.y;
return tPlane >= eps ? tPlane : 9.0;
}
// Raytracing entry point, returns voxel and object ID
// IDs:
// 0 = sky (not the armageddon, xTr1m!!)
// 1 = terrain
// 2 = water
vec4 traceRay(vec3 ro, vec3 rd, int ignore)
{
float water, terrain, minDist;
// trace only the objects we need (only one could maximally be ignored)
water = ignore != 2 ? traceWater(ro, rd) : 9.0;
terrain = ignore != 1 ? traceTerrain(ro, rd, min(0.5, 0.002 + water)) : 9.0;
// auto detail level reducing (common dude, give the GPU some breathing room)
gf_DetailLevel *= 0.75;
// find the nearest distance
minDist = min(terrain, min(water, 9.0));
// we hit nothing or the hitpoint is too far
if (minDist == 9)
return vec4(0);
// calculate the hit/voxel position
vec3 hitPos = ro + rd * minDist;
// check what we might have hit
if (minDist == terrain)
return vec4(hitPos, 1);
if (minDist == water)
return vec4(hitPos, 2);
// Panic, worry, die to death! Probably we'll land on the moon (this should never happen)
//return vec4(0);
}
// Entrypoint for color calculation
vec3 shadeRefl(vec4 hitPoint, vec3 newRo, vec3 rd)
{
// determine the fog color for this very precise point in the space time continuum
vec3 myFog = newRo.y < eps ? waterColor : shadeSky(ro, rd);
// generate the distance value for the fog calculation
float distance = clamp(length(hitPoint.xyz - newRo) * (ro.y <= 0 ? 4 : 2), 0.0, 1.0);
// get the color of the hit object and mix it with the fog
// in most cases we allow further raytracing here (not for the terrain, its not shiny enough)
if (hitPoint.w == 1)
return mix(shadeTerrain(hitPoint.xyz, rd), myFog, distance);
if (hitPoint.w == 2)
return mix(shadeWaterRefl(hitPoint.xyz, rd), myFog, distance);
return shadeSky(newRo, rd);
}
// Get the color from the object we just hit (without further raytraces)
// this is necessary because no recursion is allowed in GLSL (damn you!)
vec3 shade(vec4 hitPoint, vec3 newRo, vec3 rd)
{
// determine the fog color for the very same point we discussed earlier
vec3 myFog = newRo.y < eps ? waterColor : shadeSky(ro, rd);
// generate the other distance value. Paid attention? If you don't know what value I'm talking about, rtfm or gtfo.
float distance = clamp(length(hitPoint.xyz - newRo) * (ro.y <= 0 ? 4 : 2), 0.0, 1.0);
// get the color of the hit object and mix it with the fog
if (hitPoint.w == 1)
return mix(shadeTerrain(hitPoint.xyz, rd), myFog, distance);
if (hitPoint.w == 2)
return mix(waterColor, myFog, distance);
return myFog;
}
// Now we're just being copycats. We're not creative enough to define own entry points
// Sure, we could "#define MYENTRYPOINT main"! Or just void main(){MyEntryPoint();}
// None of that would help us win the compo, would it?
void main()
{
// Set the quality setting for the raymarcher, a higher value results in a longer processing time
// try to find a good balance between these two, low values will result in a wobbling endresult
// low quality = 50.0 (visual results are ok at 640x480)
// mid quality = 100.0
// high quality = 200.0
gf_DetailLevel = 200;
// Give our saviour global variables some life!
pi = 3.1416;
interlacing = vec3(1.2, 0.9, 0.9);
eps = 0.0001;
bigeps = 0.01;
// Get the look direction for the current pixel (always look forwards)
ro = cameraPos; //set ray origin
if (ro.y < height(ro.xz) + 0.01f)
{
ro.y = height(ro.xz) + 0.01f;
}
rd = vec3(gl_ModelViewMatrix * vec4((Z.xy - 0.5), 1, 1));
// Make our world pretty and worthy to live in (you can cultivate algae and eat them, they're surely enough for survival)
lightDir = vec3(0.58, 0.58, -0.58);
lightColor = vec3(1.2);
waterColor = vec3(0.3, 0.33, 0.4);
// Our GPU feels good underwater, almost like a refreshing experience :) cool, eh?
if (ro.y <= 0)
{
// Less work to do...
gf_DetailLevel *= 0.75;
// ...and a cozy darker atmosphere
lightColor *= 0.8;
}
// Here we go, shoot'em rays and get the color of our fragment!
vec3 color = shadeRefl(traceRay(ro, rd, 0), ro, rd);
// Underwater there are beams of light emanating from god (so called "god" rays...)
// ...this prooves that god is nothing less than a water surface.
if (ro.y <= 0)
color = godrays(color);
// Apply post processing and fade effects to the color, and finally return it.
gl_FragColor.xyz = pp(color);
}

View File

@@ -0,0 +1,11 @@
varying float T;
varying vec2 Z;
varying vec3 cameraPos;
void main()
{
T = gl_Color.x;
Z = (gl_Vertex.xy*vec2(gl_Color.y,1.0))*0.5+0.5;
cameraPos = gl_Normal.xyz;
gl_Position = gl_Vertex;
}

View File

@@ -0,0 +1,164 @@
#include "stdafx.h"
#include "Shaders.h"
PFNGLCREATESHADERPROC glCreateShader = NULL;
PFNGLSHADERSOURCEPROC glShaderSource = NULL;
PFNGLCOMPILESHADERPROC glCompileShader = NULL;
PFNGLGETSHADERIVPROC glGetShaderiv = NULL;
PFNGLGETPROGRAMIVPROC glGetProgramiv = NULL;
PFNGLCREATEPROGRAMPROC glCreateProgram = NULL;
PFNGLATTACHSHADERPROC glAttachShader = NULL;
PFNGLLINKPROGRAMPROC glLinkProgram = NULL;
PFNGLUSEPROGRAMPROC glUseProgram = NULL;
PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog = NULL;
PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog = NULL;
void useProgram(GLhandleARB ah_Program)
{
glUseProgram(ah_Program);
}
void initShaders()
{
glCreateShader = (PFNGLCREATESHADERPROC)myGetProcAddress("glCreateShader");
glShaderSource = (PFNGLSHADERSOURCEPROC)myGetProcAddress("glShaderSource");
glCompileShader = (PFNGLCOMPILESHADERPROC)myGetProcAddress("glCompileShader");
glGetShaderiv = (PFNGLGETSHADERIVPROC)myGetProcAddress("glGetShaderiv");
glGetProgramiv = (PFNGLGETPROGRAMIVPROC)myGetProcAddress("glGetProgramiv");
glCreateProgram = (PFNGLCREATEPROGRAMPROC)myGetProcAddress("glCreateProgram");
glAttachShader = (PFNGLATTACHSHADERPROC)myGetProcAddress("glAttachShader");
glLinkProgram = (PFNGLLINKPROGRAMPROC)myGetProcAddress("glLinkProgram");
glUseProgram = (PFNGLUSEPROGRAMPROC)myGetProcAddress("glUseProgram");
glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)myGetProcAddress("glGetShaderInfoLog");
glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)myGetProcAddress("glGetProgramInfoLog");
if (!(glCreateShader && glShaderSource && glCompileShader && glGetShaderiv && glGetProgramiv && glCreateProgram && glAttachShader && glLinkProgram && glUseProgram && glGetShaderInfoLog && glGetProgramInfoLog))
{
std::cerr << "Some shader functions are not available!" << std::endl;
}
}
GLhandleARB createVertexShader(const char* as_FileName)
{
GLhandleARB lh_Shader = 0;
char* ls_ShaderSource = textFileRead(as_FileName);
if (ls_ShaderSource == NULL)
{
std::cerr << "Error reading file: " << as_FileName << std::endl;
return lh_Shader;
}
lh_Shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(lh_Shader, 1, (const char**)&ls_ShaderSource, NULL);
glCompileShader(lh_Shader);
free(ls_ShaderSource);
int li_Status = 0;
glGetShaderiv(lh_Shader, GL_COMPILE_STATUS, &li_Status);
if (li_Status == GL_FALSE)
{
std::cerr << "Error compiling vertex shader: " << as_FileName << std::endl;
}
return lh_Shader;
}
GLhandleARB createFragmentShader(const char* as_FileName)
{
GLhandleARB lh_Shader = 0;
char* ls_ShaderSource = textFileRead(as_FileName);
if (ls_ShaderSource == NULL)
{
std::cerr << "Error reading file: " << as_FileName << std::endl;
return lh_Shader;
}
lh_Shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(lh_Shader, 1, (const char**)&ls_ShaderSource, NULL);
glCompileShader(lh_Shader);
int li_Status = 0;
glGetShaderiv(lh_Shader, GL_COMPILE_STATUS, &li_Status);
if (li_Status == GL_FALSE)
{
std::cerr << "Error compiling fragment shader: " << as_FileName << std::endl;
}
free(ls_ShaderSource);
return lh_Shader;
}
GLhandleARB createProgram(GLhandleARB ah_VertexShader, GLhandleARB ah_FragmentShader)
{
GLhandleARB lh_Program = 0;
if (ah_VertexShader + ah_FragmentShader <= 1)
{
std::cerr << "Cannot create program." << std::endl;
return lh_Program;
}
lh_Program = glCreateProgram();
glAttachShader(lh_Program, ah_VertexShader);
glAttachShader(lh_Program, ah_FragmentShader);
glLinkProgram(lh_Program);
int li_Status = 0;
glGetProgramiv(lh_Program, GL_LINK_STATUS, &li_Status);
if (li_Status == GL_FALSE)
{
std::cerr << "Error linking shaders." << std::endl;
}
return lh_Program;
}
char* textFileRead(const char* as_FileName)
{
FILE* lh_File;
char* ls_Content = NULL;
size_t li_Count = 0;
if (as_FileName != NULL)
{
fopen_s(&lh_File, as_FileName, "rt");
if (lh_File != NULL)
{
fseek(lh_File, 0, SEEK_END);
li_Count = ftell(lh_File);
rewind(lh_File);
if (li_Count > 0)
{
ls_Content = (char*) malloc(sizeof(char) * (li_Count + 1));
li_Count = fread(ls_Content, sizeof(char), li_Count, lh_File);
ls_Content[li_Count] = '\0';
}
fclose(lh_File);
}
}
return ls_Content;
}

View File

@@ -0,0 +1,11 @@
#pragma once
#define myGetProcAddress(name) wglGetProcAddress((LPCSTR)name)
void initShaders();
GLhandleARB createVertexShader(const char* as_FileName);
GLhandleARB createFragmentShader(const char* as_FileName);
GLhandleARB createProgram(GLhandleARB ah_VertexShader, GLhandleARB ah_FragmentShader);
void useProgram(GLhandleARB ah_Program);
char* textFileRead(const char* as_FileName);

View File

@@ -0,0 +1,332 @@
#include "stdafx.h"
#include "Window.h"
#define WINDOW_CLASS _T("BluFlameOpenGLIntroClass")
k_Window::k_Window(LPCTSTR as_Title, int ai_Width, int ai_Height, bool ab_Fullscreen, k_FlightSimApplication* ar_Application_)
: mr_Application_(ar_Application_)
, mb_Fullscreen(ab_Fullscreen)
, mb_Active(true)
, mr_DeviceContext(NULL)
, mr_Handle(NULL)
, mr_Instance(NULL)
, ms_Title(as_Title)
, mi_Width(ai_Width)
, mi_Height(ai_Height)
{
}
k_Window::~k_Window()
{
::SetWindowLong(mr_Handle, GWL_USERDATA, PtrToLong(NULL));
if (mb_Fullscreen)
{
ChangeDisplaySettings(NULL, 0);
ShowCursor(TRUE);
}
if (mr_DeviceContext)
{
ReleaseDC(mr_Handle, mr_DeviceContext);
mr_Handle = NULL;
}
if (mr_Handle)
{
DestroyWindow(mr_Handle);
mr_Handle = NULL;
}
UnregisterClass(WINDOW_CLASS, mr_Instance);
mr_Instance = NULL;
}
void k_Window::Initialize()
{
WNDCLASS lr_WindowClass;
DWORD ldw_ExStyle;
DWORD ldw_Style;
RECT lr_WindowRect;
if (mb_Fullscreen)
{
//mi_Width = GetSystemMetrics(SM_CXSCREEN);
//mi_Height = GetSystemMetrics(SM_CYSCREEN);
DEVMODE lr_ScreenSettings;
memset(&lr_ScreenSettings, 0, sizeof(lr_ScreenSettings));
lr_ScreenSettings.dmSize = sizeof(lr_ScreenSettings);
lr_ScreenSettings.dmPelsWidth = mi_Width;
lr_ScreenSettings.dmPelsHeight = mi_Height;
lr_ScreenSettings.dmBitsPerPel = GetDeviceCaps(GetDC(NULL), BITSPIXEL);
lr_ScreenSettings.dmDisplayFrequency = GetDeviceCaps(GetDC(NULL), VREFRESH);
lr_ScreenSettings.dmFields = DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT|DM_DISPLAYFREQUENCY;
ShowCursor(FALSE);
if (ChangeDisplaySettings(&lr_ScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
mb_Fullscreen = FALSE;
}
lr_WindowRect.left = (long)0;
lr_WindowRect.right = (long)mi_Width;
lr_WindowRect.top = (long)0;
lr_WindowRect.bottom = (long)mi_Height;
mr_Instance = GetModuleHandle(NULL);
lr_WindowClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
lr_WindowClass.lpfnWndProc = (WNDPROC)MessageCallback;
lr_WindowClass.cbClsExtra = 0;
lr_WindowClass.cbWndExtra = sizeof(this);
lr_WindowClass.hInstance = mr_Instance;
lr_WindowClass.hIcon = LoadIcon(NULL, IDI_WINLOGO);
lr_WindowClass.hCursor = LoadCursor(NULL, IDC_ARROW);
lr_WindowClass.hbrBackground = NULL;
lr_WindowClass.lpszMenuName = NULL;
lr_WindowClass.lpszClassName = WINDOW_CLASS;
if (!RegisterClass(&lr_WindowClass))
throw _T("Cannot register window class!");
if (mb_Fullscreen)
{
ldw_ExStyle = WS_EX_APPWINDOW | WS_EX_TOPMOST;
ldw_Style = WS_POPUP | WS_VISIBLE;
}
else
{
ShowCursor(TRUE);
ldw_ExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
ldw_Style = WS_OVERLAPPEDWINDOW;
}
AdjustWindowRectEx(&lr_WindowRect, ldw_Style, FALSE, ldw_ExStyle);
if (!(mr_Handle = CreateWindowEx(
ldw_ExStyle,
WINDOW_CLASS,
ms_Title,
ldw_Style |
WS_CLIPSIBLINGS |
WS_CLIPCHILDREN,
0, 0,
lr_WindowRect.right - lr_WindowRect.left,
lr_WindowRect.bottom - lr_WindowRect.top,
NULL,
NULL,
mr_Instance,
this)))
{
throw _T("Cannot create Window!");
}
if (!(mr_DeviceContext = GetDC(mr_Handle)))
{
throw _T("Cannot get Device Context!");
}
static const PIXELFORMATDESCRIPTOR pfd =
{
0, 1, PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, 32, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 8
};
int li_PixelFormat = 0;
if (!(li_PixelFormat = ::ChoosePixelFormat(mr_DeviceContext, &pfd)))
{
throw _T("Cannot choose pixel format!");
}
if (!::SetPixelFormat(mr_DeviceContext, li_PixelFormat, NULL))
{
throw _T("Cannot set pixel format!");
}
wglMakeCurrent(mr_DeviceContext, wglCreateContext(mr_DeviceContext));
mr_Application_->OnInitialize();
mr_Application_->OnResize(mi_Width, mi_Height);
ShowWindow(mr_Handle, SW_SHOW);
SetForegroundWindow(mr_Handle);
SetFocus(mr_Handle);
}
LRESULT k_Window::MessageCallback(HWND ar_Handle, UINT aw_Message, WPARAM aw_Param, LPARAM al_Param)
{
k_Window* lr_Window_;
if (aw_Message == WM_NCCREATE)
{
lr_Window_ = reinterpret_cast<k_Window*>(((LPCREATESTRUCT)al_Param)->lpCreateParams);
lr_Window_->mr_Handle = ar_Handle;
::SetWindowLong(ar_Handle, GWL_USERDATA, PtrToLong((PVOID)(reinterpret_cast<LONG_PTR>(lr_Window_))));
}
else
{
lr_Window_ = reinterpret_cast<k_Window*>(::GetWindowLong(ar_Handle, GWL_USERDATA));
}
if (lr_Window_ != NULL)
{
return lr_Window_->ProcessMessage(aw_Message, aw_Param, al_Param);
}
return DefWindowProc(ar_Handle, aw_Message, aw_Param, al_Param);
}
LRESULT k_Window::ProcessMessage(UINT aw_Message, WPARAM aw_Param, LPARAM al_Param)
{
switch (aw_Message)
{
case WM_ACTIVATE:
{
if (!HIWORD(aw_Param))
{
set_Active(true);
}
else
{
set_Active(false);
}
return 0;
}
case WM_SYSCOMMAND:
{
switch (aw_Param)
{
case SC_SCREENSAVE:
case SC_MONITORPOWER:
return 0;
case SC_MINIMIZE:
set_Active(false);
break;
case SC_RESTORE:
set_Active(true);
break;
}
break;
}
case WM_CLOSE:
{
PostQuitMessage(0);
return 0;
}
case WM_KEYDOWN:
{
mr_Application_->OnKeyPressed((char)aw_Param);
if (aw_Param == 27)
PostQuitMessage(0);
return 0;
}
case WM_SIZE:
{
mr_Application_->OnResize(LOWORD(al_Param), HIWORD(al_Param));
return 0;
}
case WM_MOUSEMOVE:
{
mr_Application_->OnMouseMove(GET_X_LPARAM(al_Param), GET_Y_LPARAM(al_Param));
return 0;
}
case WM_LBUTTONDOWN:
{
mr_Application_->OnMouseButton(0, true, GET_X_LPARAM(al_Param), GET_Y_LPARAM(al_Param));
return 0;
}
case WM_MBUTTONDOWN:
{
mr_Application_->OnMouseButton(1, true, GET_X_LPARAM(al_Param), GET_Y_LPARAM(al_Param));
return 0;
}
case WM_RBUTTONDOWN:
{
mr_Application_->OnMouseButton(2, true, GET_X_LPARAM(al_Param), GET_Y_LPARAM(al_Param));
return 0;
}
case WM_LBUTTONUP:
{
mr_Application_->OnMouseButton(0, false, GET_X_LPARAM(al_Param), GET_Y_LPARAM(al_Param));
return 0;
}
case WM_MBUTTONUP:
{
mr_Application_->OnMouseButton(1, false, GET_X_LPARAM(al_Param), GET_Y_LPARAM(al_Param));
return 0;
}
case WM_RBUTTONUP:
{
mr_Application_->OnMouseButton(2, false, GET_X_LPARAM(al_Param), GET_Y_LPARAM(al_Param));
return 0;
}
}
return DefWindowProc(mr_Handle, aw_Message, aw_Param, al_Param);
}
void k_Window::SwapBuffers(float af_Time)
{
mr_Application_->OnDisplay(af_Time);
::SwapBuffers(mr_DeviceContext);
}
void k_Window::set_Active(bool ab_Active)
{
mb_Active = ab_Active;
}
bool k_Window::get_Active()
{
return mb_Active;
}
void k_Window::set_Fullscreen(bool ab_Fullscreen)
{
mb_Fullscreen = ab_Fullscreen;
}
bool k_Window::get_Fullscreen()
{
return mb_Fullscreen;
}
void k_Window::set_DeviceContext(HDC ar_DeviceContext)
{
mr_DeviceContext = ar_DeviceContext;
}
HDC k_Window::get_DeviceContext()
{
return mr_DeviceContext;
}
HWND k_Window::get_Handle()
{
return mr_Handle;
}
void k_Window::set_Title(LPCTSTR as_Title)
{
SetWindowText(mr_Handle, as_Title);
}
LPCTSTR k_Window::get_Title()
{
TCHAR* ls_Text = _T("");
GetWindowText(mr_Handle, ls_Text, GetWindowTextLength(mr_Handle));
return ls_Text;
}

View File

@@ -0,0 +1,38 @@
#pragma once
#include "FlightSimApplication.h"
class k_Window
{
public:
k_Window(LPCTSTR as_Title, int ai_Width, int ai_Height, bool ab_Fullscreen, k_FlightSimApplication* ar_Application_);
virtual ~k_Window();
virtual void Initialize();
virtual LRESULT ProcessMessage(UINT aw_Message, WPARAM aw_Param, LPARAM al_Param);
virtual void SwapBuffers(float af_Time);
virtual void set_Active(bool ab_Active);
virtual bool get_Active();
virtual void set_Fullscreen(bool ab_Fullscreen);
virtual bool get_Fullscreen();
virtual void set_DeviceContext(HDC ar_DeviceContext);
virtual void set_Title(LPCTSTR as_Title);
virtual LPCTSTR get_Title();
virtual HDC get_DeviceContext();
virtual HWND get_Handle();
private:
static LRESULT CALLBACK MessageCallback(HWND ar_Handle, UINT aw_Message, WPARAM aw_Param, LPARAM al_Param);
LPCTSTR ms_Title;
int mi_Width;
int mi_Height;
HDC mr_DeviceContext;
HWND mr_Handle;
HINSTANCE mr_Instance;
k_FlightSimApplication* mr_Application_;
bool mb_Active;
bool mb_Fullscreen;
};

View File

@@ -0,0 +1,305 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9,00"
Name="flightsim"
ProjectGUID="{EAA2A155-BC7B-4DE4-98DA-4574A06F2772}"
RootNamespace="flightsim"
Keyword="Win32Proj"
TargetFrameworkVersion="196613"
>
<Platforms>
<Platform
Name="Win32"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(SolutionDir)obj\$(ProjectName)_$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="3"
UsePrecompiledHeader="2"
WarningLevel="3"
DebugInformationFormat="4"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="opengl32.lib glu32.lib"
OutputFile="$(OutDir)\$(ProjectName)_$(ConfigurationName).exe"
LinkIncremental="2"
GenerateDebugInformation="true"
SubSystem="1"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(SolutionDir)obj\$(ProjectName)_$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="2"
EnableIntrinsicFunctions="true"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
RuntimeLibrary="0"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="2"
WarningLevel="3"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="opengl32.lib glu32.lib"
OutputFile="$(OutDir)\$(ProjectName)_$(ConfigurationName).exe"
LinkIncremental="1"
GenerateDebugInformation="true"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
>
<File
RelativePath=".\FlightSimApplication.cpp"
>
</File>
<File
RelativePath=".\main.cpp"
>
</File>
<File
RelativePath=".\Shaders.cpp"
>
</File>
<File
RelativePath=".\stdafx.cpp"
>
<FileConfiguration
Name="Debug|Win32"
>
<Tool
Name="VCCLCompilerTool"
UsePrecompiledHeader="1"
/>
</FileConfiguration>
<FileConfiguration
Name="Release|Win32"
>
<Tool
Name="VCCLCompilerTool"
UsePrecompiledHeader="1"
/>
</FileConfiguration>
</File>
<File
RelativePath=".\Window.cpp"
>
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
>
<File
RelativePath=".\Camera.h"
>
</File>
<File
RelativePath=".\FlightSimApplication.h"
>
</File>
<File
RelativePath=".\glext.h"
>
</File>
<File
RelativePath=".\moremath.h"
>
</File>
<File
RelativePath=".\Shaders.h"
>
</File>
<File
RelativePath=".\stdafx.h"
>
</File>
<File
RelativePath=".\Window.h"
>
</File>
</Filter>
<Filter
Name="Resource Files"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
>
</Filter>
<File
RelativePath=".\FlightSimShader.fs"
>
<FileConfiguration
Name="Debug|Win32"
>
<Tool
Name="VCCustomBuildTool"
Description="Copying $(InputFileName)..."
CommandLine="copy /Y &quot;$(InputPath)&quot; &quot;$(TargetDir)$(InputFileName)&quot;&#x0D;&#x0A;"
Outputs="$(TargetDir)$(InputFileName)"
/>
</FileConfiguration>
<FileConfiguration
Name="Release|Win32"
>
<Tool
Name="VCCustomBuildTool"
Description="Copying $(InputFileName)..."
CommandLine="copy /Y &quot;$(InputPath)&quot; &quot;$(TargetDir)$(InputFileName)&quot;&#x0D;&#x0A;"
Outputs="$(TargetDir)$(InputFileName)"
/>
</FileConfiguration>
</File>
<File
RelativePath=".\FlightSimShader.vs"
>
<FileConfiguration
Name="Debug|Win32"
>
<Tool
Name="VCCustomBuildTool"
Description="Copying $(InputFileName)..."
CommandLine="copy /Y &quot;$(InputPath)&quot; &quot;$(TargetDir)$(InputFileName)&quot;&#x0D;&#x0A;"
Outputs="$(TargetDir)$(InputFileName)"
/>
</FileConfiguration>
<FileConfiguration
Name="Release|Win32"
>
<Tool
Name="VCCustomBuildTool"
Description="Copying $(InputFileName)..."
CommandLine="copy /Y &quot;$(InputPath)&quot; &quot;$(TargetDir)$(InputFileName)&quot;&#x0D;&#x0A;"
Outputs="$(TargetDir)$(InputFileName)"
/>
</FileConfiguration>
</File>
</Files>
<Globals>
</Globals>
</VisualStudioProject>

View File

@@ -0,0 +1,65 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioUserFile
ProjectType="Visual C++"
Version="9,00"
ShowAllFiles="false"
>
<Configurations>
<Configuration
Name="Debug|Win32"
>
<DebugSettings
Command="$(TargetPath)"
WorkingDirectory=""
CommandArguments=""
Attach="false"
DebuggerType="3"
Remote="1"
RemoteMachine="SHAIKUR"
RemoteCommand=""
HttpUrl=""
PDBPath=""
SQLDebugging=""
Environment=""
EnvironmentMerge="true"
DebuggerFlavor=""
MPIRunCommand=""
MPIRunArguments=""
MPIRunWorkingDirectory=""
ApplicationCommand=""
ApplicationArguments=""
ShimCommand=""
MPIAcceptMode=""
MPIAcceptFilter=""
/>
</Configuration>
<Configuration
Name="Release|Win32"
>
<DebugSettings
Command="$(TargetPath)"
WorkingDirectory=""
CommandArguments=""
Attach="false"
DebuggerType="3"
Remote="1"
RemoteMachine="SHAIKUR"
RemoteCommand=""
HttpUrl=""
PDBPath=""
SQLDebugging=""
Environment=""
EnvironmentMerge="true"
DebuggerFlavor=""
MPIRunCommand=""
MPIRunArguments=""
MPIRunWorkingDirectory=""
ApplicationCommand=""
ApplicationArguments=""
ShimCommand=""
MPIAcceptMode=""
MPIAcceptFilter=""
/>
</Configuration>
</Configurations>
</VisualStudioUserFile>

View File

@@ -0,0 +1,65 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioUserFile
ProjectType="Visual C++"
Version="9,00"
ShowAllFiles="true"
>
<Configurations>
<Configuration
Name="Debug|Win32"
>
<DebugSettings
Command="$(TargetPath)"
WorkingDirectory=""
CommandArguments=""
Attach="false"
DebuggerType="3"
Remote="1"
RemoteMachine="SHAIKUR"
RemoteCommand=""
HttpUrl=""
PDBPath=""
SQLDebugging=""
Environment=""
EnvironmentMerge="true"
DebuggerFlavor=""
MPIRunCommand=""
MPIRunArguments=""
MPIRunWorkingDirectory=""
ApplicationCommand=""
ApplicationArguments=""
ShimCommand=""
MPIAcceptMode=""
MPIAcceptFilter=""
/>
</Configuration>
<Configuration
Name="Release|Win32"
>
<DebugSettings
Command="$(TargetPath)"
WorkingDirectory=""
CommandArguments=""
Attach="false"
DebuggerType="3"
Remote="1"
RemoteMachine="SHAIKUR"
RemoteCommand=""
HttpUrl=""
PDBPath=""
SQLDebugging=""
Environment=""
EnvironmentMerge="true"
DebuggerFlavor=""
MPIRunCommand=""
MPIRunArguments=""
MPIRunWorkingDirectory=""
ApplicationCommand=""
ApplicationArguments=""
ShimCommand=""
MPIAcceptMode=""
MPIAcceptFilter=""
/>
</Configuration>
</Configurations>
</VisualStudioUserFile>

View File

@@ -0,0 +1,131 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{EAA2A155-BC7B-4DE4-98DA-4574A06F2772}</ProjectGuid>
<RootNamespace>flightsim</RootNamespace>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>Unicode</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)bin\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)obj\$(ProjectName)_$(Configuration)\</IntDir>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)bin\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)obj\$(ProjectName)_$(Configuration)\</IntDir>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
</ClCompile>
<Link>
<AdditionalDependencies>opengl32.lib;glu32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>$(OutDir)$(ProjectName)_$(Configuration).exe</OutputFile>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<AdditionalDependencies>opengl32.lib;glu32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>$(OutDir)$(ProjectName)_$(Configuration).exe</OutputFile>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="FlightSimApplication.cpp" />
<ClCompile Include="main.cpp" />
<ClCompile Include="Shaders.cpp" />
<ClCompile Include="stdafx.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
</ClCompile>
<ClCompile Include="Window.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="Camera.h" />
<ClInclude Include="FlightSimApplication.h" />
<ClInclude Include="glext.h" />
<ClInclude Include="moremath.h" />
<ClInclude Include="Shaders.h" />
<ClInclude Include="stdafx.h" />
<ClInclude Include="Window.h" />
</ItemGroup>
<ItemGroup>
<CustomBuild Include="FlightSimShader.fs">
<Message Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Copying %(Filename)%(Extension)...</Message>
<Command Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">copy /Y "%(FullPath)" "$(TargetDir)%(Filename)%(Extension)"
</Command>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(TargetDir)%(Filename)%(Extension);%(Outputs)</Outputs>
<Message Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Copying %(Filename)%(Extension)...</Message>
<Command Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">copy /Y "%(FullPath)" "$(TargetDir)%(Filename)%(Extension)"
</Command>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(TargetDir)%(Filename)%(Extension);%(Outputs)</Outputs>
</CustomBuild>
<CustomBuild Include="FlightSimShader.vs">
<Message Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Copying %(Filename)%(Extension)...</Message>
<Command Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">copy /Y "%(FullPath)" "$(TargetDir)%(Filename)%(Extension)"
</Command>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(TargetDir)%(Filename)%(Extension);%(Outputs)</Outputs>
<Message Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Copying %(Filename)%(Extension)...</Message>
<Command Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">copy /Y "%(FullPath)" "$(TargetDir)%(Filename)%(Extension)"
</Command>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(TargetDir)%(Filename)%(Extension);%(Outputs)</Outputs>
</CustomBuild>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@@ -0,0 +1,61 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="FlightSimApplication.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="main.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Shaders.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="stdafx.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Window.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="Camera.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="FlightSimApplication.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="glext.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="moremath.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Shaders.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="stdafx.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Window.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<CustomBuild Include="FlightSimShader.fs" />
<CustomBuild Include="FlightSimShader.vs" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,3 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
</Project>

7271
bp4k/src/flightsim/glext.h Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,65 @@
#include "stdafx.h"
#include "Window.h"
#include "FlightSimApplication.h"
int _tmain(int argc, TCHAR* argv[])
{
LARGE_INTEGER lli_OldTime, lli_StartTime, lli_TicksPerSecond;
k_FlightSimApplication* lr_Application_ = new k_FlightSimApplication();
k_Window lk_Window(_T("BluFlame - Valleyball Flight Simulator"), 640, 480, false, lr_Application_);
try
{
lk_Window.Initialize();
QueryPerformanceCounter(&lli_OldTime);
QueryPerformanceFrequency(&lli_TicksPerSecond);
lli_StartTime = lli_OldTime;
BOOL lb_Done = false;
while (!lb_Done)
{
MSG lr_Message;
if (PeekMessage(&lr_Message, NULL, 0, 0, PM_REMOVE))
{
if (lr_Message.message == WM_QUIT)
{
lb_Done = TRUE;
}
else
{
TranslateMessage(&lr_Message);
DispatchMessage(&lr_Message);
}
}
else
{
if (lk_Window.get_Active())
{
LARGE_INTEGER lli_Time;
QueryPerformanceCounter(&lli_Time);
lli_Time.QuadPart -= lli_OldTime.QuadPart;
float lf_Time = float(lli_Time.QuadPart) / (lli_TicksPerSecond.QuadPart);
QueryPerformanceCounter(&lli_OldTime);
TCHAR ls_Title[255];
_stprintf_s(ls_Title, 255, _T("FPS: %.2f"), 1.0f / lf_Time);
lk_Window.set_Title(ls_Title);
lk_Window.SwapBuffers(lf_Time);
}
}
}
}
catch (LPCTSTR ls_Exception)
{
HWND lh_WindowHandle = lk_Window.get_Handle();
::MessageBox(lh_WindowHandle, ls_Exception, _T("BluFlame demo system"), MB_OK);
::ExitProcess(0);
}
delete lr_Application_;
return 0;
}

View File

@@ -0,0 +1,751 @@
#pragma once
#include <intrin.h>
#define ANG2RAD 3.14159265358979323846/180.0
typedef __declspec(align(16)) struct k_VectorUA k_Vector;
typedef __declspec(align(16)) struct k_MatrixUA k_Matrix;
typedef __declspec(align(16)) struct k_QuaternionUA k_Quaternion;
typedef __declspec(align(16)) struct k_PlaneUA k_Plane;
#define HEAP_ALIGNED_CLASS(x) \
void* operator new[](size_t allocSize) { void* p = _mm_malloc(allocSize, x); return p; }; \
void operator delete[](void *p) { _mm_free(p); }; \
void* operator new (size_t allocSize) { void* p = _mm_malloc(allocSize, x); return p; }; \
void operator delete(void* p) { _mm_free(p); }
template <class T , int Alignment=16>
class k_AlignedAllocator
{
public:
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
template <class U>
struct rebind
{
typedef k_AlignedAllocator<U> other;
};
pointer address (reference value) const
{
return &value;
};
const_pointer address (const_reference value) const
{
return &value;
};
k_AlignedAllocator() throw()
{
};
k_AlignedAllocator(const k_AlignedAllocator&) throw()
{
};
template <class U>
k_AlignedAllocator(const k_AlignedAllocator<U>&) throw()
{
};
~k_AlignedAllocator() throw()
{
};
//max capacity
size_type max_size() const throw()
{
return 268435455;
};
pointer allocate(size_type num, const_pointer *hint = 0)
{
return (pointer) _aligned_malloc( num*sizeof(T),Alignment);
};
void construct(pointer p, const T& value)
{
*p=value;
};
void destroy(pointer p)
{
p->~T();
};
void deallocate(pointer p, size_type num)
{
_aligned_free( p );
};
};
struct __declspec(align(16)) k_VectorUA
{
HEAP_ALIGNED_CLASS(16)
union
{
struct __declspec(align(16))
{
float x;
float y;
float z;
float w;
};
__declspec(align(16)) float m[4];
};
k_Vector()
: x(0)
, y(0)
, z(0)
, w(0)
{
};
k_Vector(const k_Vector& arg)
: x(arg.x)
, y(arg.y)
, z(arg.z)
, w(arg.w)
{
};
k_Vector(const float* M)
{
memcpy_s(m, 4 * sizeof(float), M, 4 * sizeof(float));
};
k_Vector(float X, float Y, float Z, float W = 0.0f)
: x(X)
, y(Y)
, z(Z)
, w(W)
{
};
k_Vector(const __m128& arg)
{
_mm_store_ps(m, arg);
};
operator __m128() const
{
return _mm_load_ps(m);
}
operator float*()
{
return m;
}
k_Vector operator + (const k_Vector& arg) const
{
return _mm_add_ps(*this, arg);
}
k_Vector operator + (float arg) const
{
return *this + _mm_set_ps1(arg);
}
void operator += (const k_Vector& arg)
{
_mm_store_ps(m, _mm_add_ps(*this, arg));
}
void operator += (float arg)
{
*this += _mm_set_ps1(arg);
}
k_Vector operator - (const k_Vector& arg) const
{
k_Vector lk_Result = _mm_sub_ps(_mm_load_ps(m), arg);
return lk_Result;
}
k_Vector operator - (float arg) const
{
return *this - _mm_set_ps1(arg);
}
void operator -= (const k_Vector& arg)
{
_mm_store_ps(m, _mm_sub_ps(*this, arg));
}
void operator -= (float arg)
{
*this -= _mm_set_ps1(arg);
}
k_Vector operator * (const k_Vector& arg) const
{
return _mm_mul_ps(*this, arg);
}
k_Vector operator * (float arg) const
{
return *this * _mm_set_ps1(arg);
}
void operator *= (const k_Vector& arg)
{
_mm_store_ps(m, _mm_mul_ps(*this, arg));
}
void operator *= (float arg)
{
*this *= _mm_set_ps1(arg);
}
k_Vector operator / (float arg) const
{
return *this * _mm_set_ps1(1.0f / arg);
}
void operator /= (float arg)
{
*this *= _mm_set_ps1(1.0f / arg);
}
k_Vector operator -() const
{
return *this * -1.0f;
}
float dot(const k_Vector& arg) const
{
__m128 temp = _mm_mul_ps(*this, arg);
temp = _mm_hadd_ps(temp, temp);
temp = _mm_hadd_ps(temp, temp);
return temp.m128_f32[0];
}
k_Vector cross(const k_Vector& arg) const
{
__m128 a = *this;
__m128 b = arg;
__m128 ea = _mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 0, 2, 1));
__m128 eb = _mm_shuffle_ps(b, b, _MM_SHUFFLE(3, 1, 0, 2));
__m128 xa = _mm_mul_ps(ea, eb);
a = _mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 1, 0, 2));
b = _mm_shuffle_ps(b, b, _MM_SHUFFLE(3, 0, 2, 1));
__m128 xb = _mm_mul_ps(a, b);
return _mm_sub_ps(xa, xb);
}
float lengthSquared() const
{
return dot(*this);
}
float length() const
{
return sqrt(lengthSquared());
}
void normalize()
{
operator *= (_mm_rsqrt_ss(_mm_set_ps1(lengthSquared())).m128_f32[0]);
}
void clamp(float lo, float hi)
{
*this = _mm_max_ps(_mm_min_ps(*this, _mm_set_ps1(hi)), _mm_set_ps1(lo));
}
k_Vector reflect(k_Vector& arg) const
{
return *this - arg * 2.0f * arg.dot(*this);
}
};
struct __declspec(align(16)) k_QuaternionUA
{
HEAP_ALIGNED_CLASS(16)
union
{
struct __declspec(align(16))
{
float x;
float y;
float z;
float w;
};
__declspec(align(16)) float m[4];
};
k_Quaternion()
: x(0)
, y(0)
, z(0)
, w(1)
{
};
k_Quaternion(const k_Quaternion& arg)
: x(arg.x)
, y(arg.y)
, z(arg.z)
, w(arg.w)
{
};
k_Quaternion(const float* M)
{
memcpy_s(m, 4 * sizeof(float), M, 4 * sizeof(float));
};
operator __m128() const
{
return _mm_load_ps(m);
}
k_Quaternion(const k_Vector& axis, float angle)
: x(axis.x)
, y(axis.y)
, z(axis.z)
, w(angle)
{
angle *= float(M_PI);
angle /= 180.0;
w = 0.0f;
normalize();
_mm_store_ps(m, _mm_mul_ps(*this, _mm_set_ps1(sin(angle / 2.0f))));
w = cos(angle / 2.0f);
};
k_Quaternion(const k_Vector& ak_YawPitchRoll)
{
float c1 = cos(ak_YawPitchRoll.x / 2);
float c2 = cos(ak_YawPitchRoll.y / 2);
float c3 = cos(ak_YawPitchRoll.z / 2);
float s1 = sin(ak_YawPitchRoll.x / 2);
float s2 = sin(ak_YawPitchRoll.y / 2);
float s3 = sin(ak_YawPitchRoll.z / 2);
w = c1 * c2 * c3 - s1 * s2 * s3;
x = s1 * s2 * c3 + c1 * c2 * s3;
y = s1 * c2 * c3 + c1 * s2 * s3;
z = c1 * s2 * c3 - s1 * c2 * s3;
};
k_Quaternion(const __m128& arg)
{
_mm_store_ps(m, arg);
};
operator float*()
{
return m;
}
k_Quaternion operator * (const k_Quaternion& arg) const
{
return _mm_set_ps(
x * -arg.x - y * arg.y - z * arg.z * w * arg.w,
x * -arg.y + y * arg.x + z * arg.w - w * arg.z,
x * -arg.z - y * arg.w + z * arg.x + w * arg.y,
x * -arg.w + y * arg.z - z * arg.y + w * arg.x);
}
k_Quaternion operator -() const
{
return _mm_set_ps(-x, -y, -z, -w);
}
void operator *= (const k_Quaternion& arg)
{
_mm_store_ps(m, *this * arg);
}
void operator += (const k_Quaternion& arg)
{
_mm_store_ps(m, _mm_add_ps(*this, arg));
}
void rotate (const k_Quaternion& arg)
{
_mm_store_ps(m, -arg * *this * arg);
}
float lengthSquared() const
{
__m128 temp = _mm_mul_ps(*this, *this);
temp = _mm_hadd_ps(temp, temp);
temp = _mm_hadd_ps(temp, temp);
return temp.m128_f32[0];
}
float length() const
{
return sqrt(lengthSquared());
}
void normalize()
{
_mm_store_ps(m, _mm_mul_ps(*this, _mm_set_ps1(_mm_rsqrt_ss(_mm_set_ps1(lengthSquared())).m128_f32[0])));
}
};
struct __declspec(align(16)) k_MatrixUA
{
HEAP_ALIGNED_CLASS(16)
union
{
struct __declspec(align(16))
{
k_Vector r1;
k_Vector r2;
k_Vector r3;
k_Vector r4;
};
__declspec(align(16)) float m[16];
};
k_Matrix()
: r1(1, 0, 0, 0)
, r2(0, 1, 0, 0)
, r3(0, 0, 1, 0)
, r4(0, 0, 0, 1)
{
};
k_Matrix(const k_Matrix& arg)
: r1(arg.r1)
, r2(arg.r2)
, r3(arg.r3)
, r4(arg.r4)
{
};
k_Matrix(const k_Vector& R1, const k_Vector& R2, const k_Vector& R3, const k_Vector& R4)
: r1(R1)
, r2(R2)
, r3(R3)
, r4(R4)
{
};
k_Matrix(const float* M)
: r1(&M[0])
, r2(&M[4])
, r3(&M[8])
, r4(&M[12])
{
};
k_Matrix(const k_Quaternion& ak_Quaternion)
{
k_Quaternion lk_Quaterion(ak_Quaternion);
float lf_Length2 = lk_Quaterion.lengthSquared();
if (lf_Length2 != 1.0 && lf_Length2 != 0.0)
{
lk_Quaterion.normalize();
}
float wx, wy, wz, xx, yy, yz, xy, xz, zz, x2, y2, z2;
x2 = lk_Quaterion.m[0] + lk_Quaterion.m[0];
y2 = lk_Quaterion.m[1] + lk_Quaterion.m[1];
z2 = lk_Quaterion.m[2] + lk_Quaterion.m[2];
xx = lk_Quaterion.m[0] * x2;
xy = lk_Quaterion.m[0] * y2;
xz = lk_Quaterion.m[0] * z2;
yy = lk_Quaterion.m[1] * y2;
yz = lk_Quaterion.m[1] * z2;
zz = lk_Quaterion.m[2] * z2;
wx = lk_Quaterion.m[3] * x2;
wy = lk_Quaterion.m[3] * y2;
wz = lk_Quaterion.m[3] * z2;
r1 = k_Vector(1.0f - (yy + zz), xy - wz, xz + wy, 0.0f);
r2 = k_Vector(xy + wz, 1.0f - (xx + zz), yz - wx, 0.0f);
r3 = k_Vector(xz - wy, yz + wx, 1.0f - (xx + yy), 0.0f);
r4 = k_Vector(0.0f, 0.0f, 0.0f, 1.0f);
};
k_Vector operator * (const k_Vector& arg) const
{
return k_Vector(r1.dot(arg), r2.dot(arg), r3.dot(arg), r4.dot(arg));
}
k_Matrix operator * (const k_Matrix& arg) const
{
return k_Matrix(
*this * arg.r1,
*this * arg.r2,
*this * arg.r3,
*this * arg.r4);
}
void GetAxisAndAngle(k_Vector& ak_Axis, float& af_Angle)
{
float lf_Spur = m[0] + m[5] + m[10];
af_Angle = acos((lf_Spur - 1.0f) / 2.0f);
float lf_Factor = -2.0f * sin(af_Angle);
if (lf_Factor == 0.0f)
{
ak_Axis = k_Vector(0.0f, 0.0f, -1.0f, 0.0f);
}
else
{
ak_Axis.x = m[4] / lf_Factor;
ak_Axis.y = m[2] / lf_Factor;
ak_Axis.z = m[8] / lf_Factor;
ak_Axis.w = 1.0f;
}
}
void operator *= (const k_Matrix& arg)
{
k_Matrix lk_Temp = *this;
r1 = lk_Temp * arg.r1;
r2 = lk_Temp * arg.r2;
r3 = lk_Temp * arg.r3;
r4 = lk_Temp * arg.r4;
}
static k_Matrix rotateX(float af_Rad)
{
float s = sin(af_Rad);
float c = cos(af_Rad);
return k_Matrix(
k_Vector(1,0,0,0),
k_Vector(0,c,-s,0),
k_Vector(0,s,c,0),
k_Vector(0,0,0,1));
}
static k_Matrix rotateY(float af_Rad)
{
float s = sin(af_Rad);
float c = cos(af_Rad);
return k_Matrix(
k_Vector(c,0,s,0),
k_Vector(0,1,0,0),
k_Vector(-s,0,c,0),
k_Vector(0,0,0,1));
}
static k_Matrix rotateZ(float af_Rad)
{
float s = sin(af_Rad);
float c = cos(af_Rad);
return k_Matrix(
k_Vector(c,-s,0,0),
k_Vector(s,c,0,0),
k_Vector(0,0,1,0),
k_Vector(0,0,0,1));
}
static k_Matrix scale(float s)
{
return k_Matrix(
k_Vector(s,0,0,0),
k_Vector(0,s,0,0),
k_Vector(0,0,s,0),
k_Vector(0,0,0,1));
}
static k_Matrix scale(const k_Vector& s)
{
return k_Matrix(
k_Vector(s.x,0,0,0),
k_Vector(0,s.y,0,0),
k_Vector(0,0,s.z,0),
k_Vector(0,0,0,1));
}
static k_Matrix translate(const k_Vector& ak_Translation)
{
return k_Matrix(
k_Vector(1,0,0,ak_Translation.x),
k_Vector(0,1,0,ak_Translation.y),
k_Vector(0,0,1,ak_Translation.z),
k_Vector(0,0,0,ak_Translation.w));
}
void transpose()
{
k_Matrix lk_Temp(
k_Vector(r1.x, r2.x, r3.x, r4.x),
k_Vector(r1.y, r2.y, r3.y, r4.y),
k_Vector(r1.z, r2.z, r3.z, r4.z),
k_Vector(r1.w, r2.w, r3.w, r4.w));
r1 = lk_Temp.r1;
r2 = lk_Temp.r2;
r3 = lk_Temp.r3;
r4 = lk_Temp.r4;
}
float Determinante2x2(float a1, float a2, float b1, float b2)
{
return a1 * b2 - b1 * a2;
}
float Determinante3x3( float a1, float a2, float a3,
float b1, float b2, float b3,
float c1, float c2, float c3)
{
return a1 * Determinante2x2( b2, b3, c2, c3 ) - b1 * Determinante2x2( a2, a3, c2, c3 ) + c1 * Determinante2x2( a2, a3, b2, b3 );
}
void inverse()
{
k_Matrix lk_Result;
lk_Result.m[0] = Determinante3x3( m[5], m[9], m[13], m[6], m[10], m[14], m[7], m[11], m[15] );
lk_Result.m[4] = -Determinante3x3( m[4], m[8], m[12], m[6], m[10], m[14], m[7], m[11], m[15] );
lk_Result.m[8] = Determinante3x3( m[4], m[8], m[12], m[5], m[9], m[13], m[7], m[11], m[15] );
lk_Result.m[12] = -Determinante3x3( m[4], m[8], m[12], m[5], m[9], m[13], m[6], m[10], m[14] );
lk_Result.m[1] = -Determinante3x3( m[1], m[9], m[13], m[2], m[10], m[14], m[3], m[11], m[15] );
lk_Result.m[5] = Determinante3x3( m[0], m[8], m[12], m[2], m[10], m[14], m[3], m[11], m[15] );
lk_Result.m[9] = -Determinante3x3( m[0], m[8], m[12], m[1], m[9], m[13], m[3], m[11], m[15] );
lk_Result.m[13] = Determinante3x3( m[0], m[8], m[12], m[1], m[9], m[13], m[2], m[10], m[14] );
lk_Result.m[2] = Determinante3x3( m[1], m[5], m[13], m[2], m[6], m[14], m[3], m[7], m[15] );
lk_Result.m[6] = -Determinante3x3( m[0], m[4], m[12], m[2], m[6], m[14], m[3], m[7], m[15] );
lk_Result.m[10] = Determinante3x3( m[0], m[4], m[12], m[1], m[5], m[13], m[3], m[7], m[15] );
lk_Result.m[14] = -Determinante3x3( m[0], m[4], m[12], m[1], m[5], m[13], m[2], m[6], m[14] );
lk_Result.m[3] = -Determinante3x3( m[1], m[5], m[9], m[2], m[6], m[10], m[3], m[7], m[11] );
lk_Result.m[7] = Determinante3x3( m[0], m[4], m[8], m[2], m[6], m[10], m[3], m[7], m[11] );
lk_Result.m[11] = -Determinante3x3( m[0], m[4], m[8], m[1], m[5], m[9], m[3], m[7], m[11] );
lk_Result.m[15] = Determinante3x3( m[0], m[4], m[8], m[1], m[5], m[9], m[2], m[6], m[10] );
float lf_Det = (m[0] * lk_Result.m[0]) + (m[1] * lk_Result.m[4]) + (m[2] * lk_Result.m[8]) + (m[3] * lk_Result.m[12]);
if (lf_Det == 0.0f)
return; // matrix is singular
lf_Det = 1.0f / lf_Det;
*this = lk_Result;
m[0] *= lf_Det;
m[4] *= lf_Det;
m[8] *= lf_Det;
m[12] *= lf_Det;
m[1] *= lf_Det;
m[5] *= lf_Det;
m[9] *= lf_Det;
m[13] *= lf_Det;
m[2] *= lf_Det;
m[6] *= lf_Det;
m[10] *= lf_Det;
m[14] *= lf_Det;
m[3] *= lf_Det;
m[7] *= lf_Det;
m[11] *= lf_Det;
m[15] *= lf_Det;
}
};
struct __declspec(align(16)) k_PlaneUA
{
HEAP_ALIGNED_CLASS(16)
k_Vector Normal;
k_Vector Point;
float D;
k_Plane() {}
k_Plane(const k_Vector& V1, const k_Vector& V2, const k_Vector& V3)
{
k_Vector aux1, aux2;
aux1 = V1 - V2;
aux2 = V3 - V2;
Normal = aux2 * aux1;
Normal.normalize();
Point = V2;
D = -Normal.dot(Point);
}
k_Plane(const k_Vector& ak_Normal, const k_Vector& ak_Point)
{
Normal = ak_Normal;
Normal.normalize();
Point = ak_Point;
D = -Normal.dot(Point);
}
k_Plane(float a, float b, float c, float d)
{
Normal = k_Vector(a, b, c);
float lf_Length = Normal.length();
Normal.normalize();
D = d / lf_Length;
}
float GetDistanceToPoint(const k_Vector& ak_Point)
{
return (D + Normal.dot(ak_Point));
}
};
float smoothstep(float x, float a, float b)
{
if (x < a) return 0.0f;
if (x > b) return 1.0f;
x = (x - a) / (b - a);
return x * x * (3.0f - 2.0f * x);
}
k_Vector mix(k_Vector& arg1, k_Vector& arg2, float t)
{
return arg1 * (1.0f - t) + arg2 * t;
}
float clamp(float arg, float lo, float hi)
{
return max(min(arg, hi), lo);
}
template<typename T>
T catmullRomSpline(float x, const T& v0, const T& v1, const T& v2, const T& v3)
{
T c1, c2, c3, c4;
T a = v0 * -0.5f;
T b = v3 * 0.5f;
c1 = v1;
c2 = a + v2 * 0.5f;
c3 = v0 - v1 * 2.5f + v2 * 2.0f - b;
c4 = a + v1 * 1.5f - v2 * 1.5f + b;
return ((c4 * x + c3) * x +c2) * x + c1;
}

View File

@@ -0,0 +1,8 @@
// stdafx.cpp : source file that includes just the standard includes
// demo09.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file

View File

@@ -0,0 +1,33 @@
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>
#include <windowsx.h>
#include <Shlwapi.h>
// C RunTime Header Files
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <tchar.h>
#define _USE_MATH_DEFINES
#include <cmath>
// TODO: reference additional headers your program requires here
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <time.h>
#include <io.h>
#include <iostream>
#include <GL/gl.h>
#include <GL/glu.h>
#include "glext.h"
#include "moremath.h"

BIN
bp4k/src/next4k/4klang.obj Normal file

Binary file not shown.

74
bp4k/src/next4k/d3d10.inc Normal file
View File

@@ -0,0 +1,74 @@
option casemap:none
; include file generated by lib2inc V2.2
D3D10CompileEffectFromMemory PROTO :DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD
D3D10CompileShader PROTO :DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD
D3D10CreateBlob PROTO :DWORD,:DWORD
D3D10CreateDevice PROTO :DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD
D3D10CreateDeviceAndSwapChain PROTO :DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD
D3D10CreateEffectFromMemory PROTO :DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD
D3D10CreateEffectPoolFromMemory PROTO :DWORD,:DWORD,:DWORD,:DWORD,:DWORD
D3D10CreateStateBlock PROTO :DWORD,:DWORD,:DWORD
D3D10DisassembleEffect PROTO :DWORD,:DWORD,:DWORD
D3D10DisassembleShader PROTO :DWORD,:DWORD,:DWORD,:DWORD,:DWORD
D3D10GetGeometryShaderProfile PROTO :DWORD
D3D10GetInputAndOutputSignatureBlob PROTO :DWORD,:DWORD,:DWORD
D3D10GetInputSignatureBlob PROTO :DWORD,:DWORD,:DWORD
D3D10GetOutputSignatureBlob PROTO :DWORD,:DWORD,:DWORD
D3D10GetPixelShaderProfile PROTO :DWORD
D3D10GetShaderDebugInfo PROTO :DWORD,:DWORD,:DWORD
D3D10GetVersion PROTO
D3D10GetVertexShaderProfile PROTO :DWORD
D3D10PreprocessShader PROTO :DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD
D3D10ReflectShader PROTO :DWORD,:DWORD,:DWORD
D3D10RegisterLayers PROTO
D3D10StateBlockMaskDifference PROTO :DWORD,:DWORD,:DWORD
D3D10StateBlockMaskDisableAll PROTO :DWORD
D3D10StateBlockMaskDisableCapture PROTO :DWORD,:DWORD,:DWORD,:DWORD
D3D10StateBlockMaskEnableAll PROTO :DWORD
D3D10StateBlockMaskEnableCapture PROTO :DWORD,:DWORD,:DWORD,:DWORD
D3D10StateBlockMaskGetSetting PROTO :DWORD,:DWORD,:DWORD
D3D10StateBlockMaskIntersect PROTO :DWORD,:DWORD,:DWORD
D3D10StateBlockMaskUnion PROTO :DWORD,:DWORD,:DWORD
D3D10_SDK_VERSION EQU 29
D3D10_CREATE_DEVICE_DEBUG EQU 2
DXGI_RATIONAL STRUCT
Numerator DWORD ?
Denominator DWORD ?
DXGI_RATIONAL ENDS
DXGI_MODE_DESC STRUCT
nWidth DWORD ?
Height DWORD ?
RefreshRate DXGI_RATIONAL <>
Format DWORD ?
ScanlineOrdering DWORD ? ; or byte
Scaling DWORD ? ; or byte
DXGI_MODE_DESC ENDS
DXGI_SAMPLE_DESC STRUCT
Count DWORD ?
Quality DWORD ?
DXGI_SAMPLE_DESC ENDS
DXGI_SWAP_CHAIN_DESC STRUCT
BufferDesc DXGI_MODE_DESC <>
SampleDesc DXGI_SAMPLE_DESC <>
BufferUsage DWORD ?
BufferCount DWORD ?
OutputWindow HWND ?
Windowed BOOL ?
SWAP_EFFECT DWORD ? ; or byte
Flags DWORD ?
DXGI_SWAP_CHAIN_DESC ENDS
D3D10_VIEWPORT STRUCT
TopLeftX DWORD ?
TopLeftY DWORD ?
nWidth DWORD ?
Height DWORD ?
MinDepth FLOAT ?
MaxDepth FLOAT ?
D3D10_VIEWPORT ENDS

Some files were not shown because too many files have changed in this diff Show More