Atmosphere shader (from space only)

This commit is contained in:
Evert Prants 2020-03-31 14:17:22 +03:00
parent 9db001d18f
commit ba2bc1a43c
Signed by: evert
GPG Key ID: 1688DA83D222D0B5
7 changed files with 210 additions and 56 deletions

View File

@ -1,5 +1,27 @@
precision mediump float;
void main() {
gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0);
uniform vec3 v3LightPosition;
uniform float g;
uniform float g2;
varying vec3 v3Direction;
varying vec3 c0;
varying vec3 c1;
// Calculates the Mie phase function
float getMiePhase(float fCos, float fCos2, float g, float g2){
return 1.5 * ((1.0 - g2) / (2.0 + g2)) * (1.0 + fCos2) / pow(1.0 + g2 - 2.0 * g * fCos, 1.5);
}
// Calculates the Rayleigh phase function
float getRayleighPhase(float fCos2) {
return 0.75 + 0.75 * fCos2;
}
void main (void) {
float fCos = dot(v3LightPosition, v3Direction) / length(v3Direction);
float fCos2 = fCos * fCos;
vec3 color = getRayleighPhase(fCos2) * c0 +
getMiePhase(fCos, fCos2, g, g2) * c1;
gl_FragColor = vec4(color, 1.0);
gl_FragColor.a = gl_FragColor.b;
}

View File

@ -1,12 +1,80 @@
precision mediump float;
attribute vec3 aVertexPosition;
attribute vec2 aTexCoords;
uniform vec3 v3CameraPosition; // The camera position
uniform vec3 v3LightPosition; // The direction vector to the light source
uniform vec3 v3InvWavelength; // 1 / pow(wavelength, 4) for the red, green, and blue channels
uniform float fCameraHeight; // The camera's current height
uniform float fCameraHeight2; // fCameraHeight^2
uniform float fOuterRadius; // The outer (atmosphere) radius
uniform float fOuterRadius2; // fOuterRadius^2
uniform float fInnerRadius; // The inner (planetary) radius
uniform float fInnerRadius2; // fInnerRadius^2
uniform float fKrESun; // Kr * ESun
uniform float fKmESun; // Km * ESun
uniform float fKr4PI; // Kr * 4 * PI
uniform float fKm4PI; // Km * 4 * PI
uniform float fScale; // 1 / (fOuterRadius - fInnerRadius)
uniform float fScaleDepth; // The scale depth (i.e. the altitude at which the atmosphere's average density is found)
uniform float fScaleOverScaleDepth; // fScale / fScaleDepth
const int nSamples = 3;
const float fSamples = 3.0;
varying vec3 v3Direction;
varying vec3 c0;
varying vec3 c1;
uniform mat4 uModelMatrix;
uniform mat4 uViewMatrix;
uniform mat4 uProjectionMatrix;
void main() {
gl_Position = uProjectionMatrix * uViewMatrix * uModelMatrix * vec4(aVertexPosition,1);
float scale(float fCos)
{
float x = 1.0 - fCos;
return fScaleDepth * exp(-0.00287 + x*(0.459 + x*(3.83 + x*(-6.80 + x*5.25))));
}
void main(void)
{
// Get the ray from the camera to the vertex and its length (which is the far point of the ray passing through the atmosphere)
vec3 v3Ray = aVertexPosition - v3CameraPosition;
float fFar = length(v3Ray);
v3Ray /= fFar;
// Calculate the closest intersection of the ray with the outer atmosphere (which is the near point of the ray passing through the atmosphere)
float B = 2.0 * dot(v3CameraPosition, v3Ray);
float C = fCameraHeight2 - fOuterRadius2;
float fDet = max(0.0, B*B - 4.0 * C);
float fNear = 0.5 * (-B - sqrt(fDet));
// Calculate the ray's starting position, then calculate its scattering offset
vec3 v3Start = v3CameraPosition + v3Ray * fNear;
fFar -= fNear;
float fStartAngle = dot(v3Ray, v3Start) / fOuterRadius;
float fStartDepth = exp(-1.0 / fScaleDepth);
float fStartOffset = fStartDepth * scale(fStartAngle);
//c0 = vec3(1.0, 0, 0) * fStartAngle;
// Initialize the scattering loop variables
float fSampleLength = fFar / fSamples;
float fScaledLength = fSampleLength * fScale;
vec3 v3SampleRay = v3Ray * fSampleLength;
vec3 v3SamplePoint = v3Start + v3SampleRay * 0.5;
//gl_FrontColor = vec4(0.0, 0.0, 0.0, 0.0);
// Now loop through the sample rays
vec3 v3FrontColor = vec3(0.0, 0.0, 0.0);
for(int i=0; i<nSamples; i++)
{
float fHeight = length(v3SamplePoint);
float fDepth = exp(fScaleOverScaleDepth * (fInnerRadius - fHeight));
float fLightAngle = dot(v3LightPosition, v3SamplePoint) / fHeight;
float fCameraAngle = dot(v3Ray, v3SamplePoint) / fHeight;
float fScatter = (fStartOffset + fDepth * (scale(fLightAngle) - scale(fCameraAngle)));
vec3 v3Attenuate = exp(-fScatter * (v3InvWavelength * fKr4PI + fKm4PI));
v3FrontColor += v3Attenuate * (fDepth * fScaledLength);
v3SamplePoint += v3SampleRay;
}
// Finally, scale the Mie and Rayleigh colors and set up the varying variables for the pixel shader
gl_Position = uProjectionMatrix * uViewMatrix * uModelMatrix * vec4(aVertexPosition,1);
c0 = v3FrontColor * (v3InvWavelength * fKrESun);
c1 = v3FrontColor * fKmESun;
v3Direction = v3CameraPosition - aVertexPosition;
}

View File

@ -1,28 +1,57 @@
import { MeshInstance } from '../'
import Sphere from '../../mesh/geometry/sphere'
import { vec3 } from 'gl-matrix'
import { normalv3 } from '../../utility'
import { subv3, normalv3 } from '../../utility'
class Atmosphere extends MeshInstance {
constructor (pos, innerRadius, outerRadius, scale, color) {
super(Sphere.new(outerRadius, 64, 64), pos)
constructor (pos, innerRadius, outerRadius, wavelength = [0.650, 0.570, 0.475]) {
super(Sphere.new(outerRadius, 200, 200), pos)
this.outerRadius = outerRadius
this.innerRadius = innerRadius
this.scale = scale
this.color = color
this.wavelength = wavelength
this.Kr = 0.0025
this.Km = 0.0010
this.ESun = 20.0
this.g = -0.950
this.scaleDepth = 0.25
this.mieScaleDepth = 0.1
}
draw (gl, shader, camera, sun, sky) {
// Set model transform matrix uniform
gl.uniformMatrix4fv(shader.getUniformLocation(gl, 'uModelMatrix'), false, this.transform)
const camHeight = vec3.length(subv3(camera.pos, this.pos))
gl.uniform3fv(shader.getUniformLocation(gl, 'v3CameraPosition'), camera.pos)
gl.uniform3fv(shader.getUniformLocation(gl, 'v3LightPosition'), normalv3(sun.pos.slice()))
gl.uniform3f(shader.getUniformLocation(gl, 'v3InvWavelength'), 1 / Math.pow(this.wavelength[0], 4), 1 / Math.pow(this.wavelength[1], 4), 1 / Math.pow(this.wavelength[2], 4))
gl.uniform1f(shader.getUniformLocation(gl, 'fCameraHeight'), camHeight)
gl.uniform1f(shader.getUniformLocation(gl, 'fCameraHeight2'), camHeight * camHeight)
gl.uniform1f(shader.getUniformLocation(gl, 'fInnerRadius'), this.innerRadius)
gl.uniform1f(shader.getUniformLocation(gl, 'fInnerRadius2'), this.innerRadius * this.innerRadius)
gl.uniform1f(shader.getUniformLocation(gl, 'fOuterRadius'), this.outerRadius)
gl.uniform1f(shader.getUniformLocation(gl, 'fOuterRadius2'), this.outerRadius * this.outerRadius)
gl.uniform1f(shader.getUniformLocation(gl, 'fKrESun'), this.Kr * this.ESun)
gl.uniform1f(shader.getUniformLocation(gl, 'fKmESun'), this.Km * this.ESun)
gl.uniform1f(shader.getUniformLocation(gl, 'fKr4PI'), this.Kr * 4 * Math.PI)
gl.uniform1f(shader.getUniformLocation(gl, 'fKm4PI'), this.Km * 4 * Math.PI)
gl.uniform1f(shader.getUniformLocation(gl, 'fScale'), 1 / (this.outerRadius - this.innerRadius))
gl.uniform1f(shader.getUniformLocation(gl, 'fScaleDepth'), this.scaleDepth)
gl.uniform1f(shader.getUniformLocation(gl, 'fScaleOverScaleDepth'), 1 / (this.outerRadius - this.innerRadius) / this.scaleDepth)
gl.uniform1f(shader.getUniformLocation(gl, 'g'), this.g)
gl.uniform1f(shader.getUniformLocation(gl, 'g2'), this.g * this.g)
// Draw the mesh
gl.disable(gl.CULL_FACE)
gl.enable(gl.BLEND)
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)
gl.cullFace(gl.FRONT)
this.mesh.prepare(gl, shader)
this.mesh.draw(gl, shader)
this.mesh.postdraw(gl, shader)
gl.enable(gl.CULL_FACE)
gl.cullFace(gl.BACK)
gl.disable(gl.BLEND)
}
}

View File

@ -67,7 +67,7 @@ class CubeFace {
// Normalize and multiply by radius to create a spherical mesh
const normal = normalv3(vertex)
const pos = mulv3(normal, (this.generator.noise.getNoise3D(this.level + 1, normal[0], normal[1], normal[2]) * 2 + radius))
const pos = mulv3(normal, (this.generator.noise.getNoise3D(this.level + 1, normal[0], normal[1], normal[2]) + radius))
vertices[vertexPointer * 3] = pos[0]
vertices[vertexPointer * 3 + 1] = pos[1]

View File

@ -42,7 +42,7 @@ class Environment {
this.fogEnd = 0
this.fogColor = [0.8, 0.8, 0.8]
this.sun = new Light([0.0, 1000.0, -2000.0], [1.0, 1.0, 1.0])
this.sun = new Light([0.0, 10000.0, -20000.0], [1.0, 1.0, 1.0])
this.lights = [this.sun]
this.maxEnvironmentLights = ENV_MAX_LIGHTS

View File

@ -1,49 +1,84 @@
import { Mesh } from '..'
import Screen from '../../screen'
import { normalv3 } from '../../utility'
class Sphere extends Mesh {
static new (radius, rings, sectors) {
const R = 1.0 / (rings - 1)
const S = 1.0 / (sectors - 1)
static new (radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
radius = radius || 1
widthSegments = Math.max(3, Math.floor(widthSegments) || 8)
heightSegments = Math.max(2, Math.floor(heightSegments) || 6)
phiStart = phiStart !== undefined ? phiStart : 0
phiLength = phiLength !== undefined ? phiLength : Math.PI * 2
thetaStart = thetaStart !== undefined ? thetaStart : 0
thetaLength = thetaLength !== undefined ? thetaLength : Math.PI
const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI)
let ix
let iy
let index = 0
const grid = []
// buffers
const indices = []
const vertices = []
const normals = []
const textureCoords = []
const indices = []
const uvs = []
for (let r = 0, vertexPointer = 0; r < rings; r++) {
for (let s = 0; s < sectors; s++, vertexPointer++) {
const y = Math.sin(Math.PI / 2 + Math.PI * r * R)
const x = Math.cos(2 * Math.PI * s * S) * Math.sin(Math.PI * r * R)
const z = Math.sin(2 * Math.PI * s * S) * Math.sin(Math.PI * r * R)
// generate vertices, normals and uvs
for (iy = 0; iy <= heightSegments; iy++) {
const verticesRow = []
const v = iy / heightSegments
vertices[vertexPointer * 3] = x * radius
vertices[vertexPointer * 3 + 1] = y * radius
vertices[vertexPointer * 3 + 2] = z * radius
normals[vertexPointer * 3] = x
normals[vertexPointer * 3 + 1] = y
normals[vertexPointer * 3 + 2] = z
textureCoords[vertexPointer * 2] = s * S
textureCoords[vertexPointer * 2 + 1] = r * R
// special case for the poles
let uOffset = 0
if (iy === 0 && thetaStart === 0) {
uOffset = 0.5 / widthSegments
} else if (iy === heightSegments && thetaEnd === Math.PI) {
uOffset = -0.5 / widthSegments
}
for (ix = 0; ix <= widthSegments; ix++) {
const u = ix / widthSegments
// vertex
const x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength)
const y = radius * Math.cos(thetaStart + v * thetaLength)
const z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength)
vertices.push(x, y, z)
// normal
const normal = normalv3([x, y, z])
normals.push(normal[0], normal[1], normal[2])
// uv
uvs.push(u + uOffset, 1 - v)
verticesRow.push(index++)
}
grid.push(verticesRow)
}
// indices
for (iy = 0; iy < heightSegments; iy++) {
for (ix = 0; ix < widthSegments; ix++) {
const a = grid[iy][ix + 1]
const b = grid[iy][ix]
const c = grid[iy + 1][ix]
const d = grid[iy + 1][ix + 1]
if (iy !== 0 || thetaStart > 0) indices.push(a, b, d)
if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d)
}
}
for (let r = 0, pointer = 0; r < rings - 1; r++) {
for (let s = 0; s < sectors - 1; s++) {
const topLeft = r * sectors + s
const topRight = topLeft + 1
const bottomLeft = (r + 1) * sectors + s
const bottomRight = bottomLeft + 1
indices[pointer++] = bottomLeft
indices[pointer++] = topLeft
indices[pointer++] = topRight
indices[pointer++] = topRight
indices[pointer++] = bottomRight
indices[pointer++] = bottomLeft
}
}
return Mesh.construct(Screen.gl, vertices, indices, textureCoords, normals)
return Mesh.construct(Screen.gl, vertices, indices, uvs, normals)
}
}

View File

@ -29,7 +29,7 @@ async function pipeline () {
const entity = await loadMesh(game.gl, 'test')
const terrainShader = await game.shaders.createShaderFromFiles(game.gl, 'terrain', false)
const skyboxShader = await game.shaders.createShaderFromFiles(game.gl, 'skybox', false)
// let atmosShader = await game.shaders.createShaderFromFiles(game.gl, 'atmosphere', false)
const atmosShader = await game.shaders.createShaderFromFiles(game.gl, 'atmosphere', false)
entity.setRotation([0.0, 0.0, -90.0])
@ -96,7 +96,7 @@ async function pipeline () {
// Planet test
const planet = new CubePlanet([0.0, 0.0, 0.0], new PlanetGenerator(16, 1000, hmap))
// let atmosphere = new Atmosphere([0.0, 0.0, 0.0], 1000, 1025, 1, [0.0, 0.0, 1.0])
const atmosphere = new Atmosphere([0.0, 0.0, 0.0], 1000, 1025, [0.650, 0.570, 0.475])
// Update function for camera and terrain
let fpsTimer = 0
@ -157,8 +157,8 @@ async function pipeline () {
game.prepare()
// Draw the skybox
skyboxShader.use(gl)
skybox.draw(gl, skyboxShader, cam)
//skyboxShader.use(gl)
//skybox.draw(gl, skyboxShader, cam)
// Use terrain shader
terrainShader.use(gl)
@ -176,9 +176,9 @@ async function pipeline () {
material.apply(gl, terrainShader)
planet.draw(gl, terrainShader)
// atmosShader.use(gl)
// cam.draw(gl, atmosShader)
// atmosphere.draw(gl, atmosShader, cam, env.sun, true)
atmosShader.use(gl)
cam.draw(gl, atmosShader)
atmosphere.draw(gl, atmosShader, cam, env.sun, true)
}
// Render function for the triangle