bgfx/examples/41-tess/terrain_common.sh

100 lines
2.0 KiB
Bash
Raw Normal View History

#include "bgfx_compute.sh"
#include "matrices.sh"
#include "isubd.sh"
#include "uniforms.sh"
BUFFER_RW(u_AtomicCounterBuffer, uint, 4);
BUFFER_RW(u_SubdBufferOut, uint, 1);
SAMPLER2D(u_DmapSampler, 0); // displacement map
SAMPLER2D(u_SmapSampler, 1); // slope map
// displacement map
float dmap(vec2 pos)
{
2019-07-22 08:02:07 +03:00
return (texture2DLod(u_DmapSampler, pos * 0.5 + 0.5, 0).x) * u_DmapFactor;
}
float distanceToLod(float z, float lodFactor)
{
2019-07-22 08:02:07 +03:00
// Note that we multiply the result by two because the triangles
// edge lengths decreases by half every two subdivision steps.
return -2.0 * log2(clamp(z * lodFactor, 0.0f, 1.0f));
}
float computeLod(vec3 c)
{
//displace
2019-07-22 08:02:07 +03:00
c.z += dmap(mtxGetColumn(u_invView, 3).xy);
2019-07-22 08:02:07 +03:00
vec3 cxf = mul(u_modelView, vec4(c.x, c.y, c.z, 1)).xyz;
float z = length(cxf);
2019-07-22 08:02:07 +03:00
return distanceToLod(z, u_LodFactor);
}
float computeLod(in vec4 v[3])
{
2019-07-22 08:02:07 +03:00
vec3 c = (v[1].xyz + v[2].xyz) / 2.0;
return computeLod(c);
}
2019-07-22 08:02:07 +03:00
float computeLod(in vec3 v[3])
{
2019-07-22 08:02:07 +03:00
vec3 c = (v[1].xyz + v[2].xyz) / 2.0;
return computeLod(c);
}
void writeKey(uint primID, uint key)
{
2019-07-22 08:02:07 +03:00
uint idx = 0;
atomicFetchAndAdd(u_AtomicCounterBuffer[0], 2, idx);
2019-07-22 08:02:07 +03:00
u_SubdBufferOut[idx] = primID;
u_SubdBufferOut[idx+1] = key;
}
void updateSubdBuffer(
2019-07-22 08:02:07 +03:00
uint primID
, uint key
, uint targetLod
, uint parentLod
, bool isVisible
)
{
// extract subdivision level associated to the key
uint keyLod = findMSB(key);
// update the key accordingly
if (/* subdivide ? */ keyLod < targetLod && !isLeafKey(key) && isVisible)
{
uint children[2]; childrenKeys(key, children);
writeKey(primID, children[0]);
writeKey(primID, children[1]);
}
else if (/* keep ? */ keyLod < (parentLod + 1) && isVisible)
{
writeKey(primID, key);
}
else /* merge ? */
{
if (/* is root ? */isRootKey(key))
{
writeKey(primID, key);
}
else if (/* is zero child ? */isChildZeroKey(key)) {
writeKey(primID, parentKey(key));
}
}
}
void updateSubdBuffer(uint primID, uint key, uint targetLod, uint parentLod)
{
2019-07-22 08:02:07 +03:00
updateSubdBuffer(primID, key, targetLod, parentLod, true);
}