Procedural Planets

Integrated Sebastian Lague's Planet Generator
Created Tour function in SectorRenderer which makes the camera follow each terrestrial planet in turn
This commit is contained in:
Reinier Vens 2020-12-05 23:43:02 +00:00
commit 53a91351b7
332 changed files with 11904 additions and 78 deletions

View file

@ -0,0 +1,113 @@
using UnityEngine;
public static class CameraUtility {
static readonly Vector3[] cubeCornerOffsets = {
new Vector3 (1, 1, 1),
new Vector3 (-1, 1, 1),
new Vector3 (-1, -1, 1),
new Vector3 (-1, -1, -1),
new Vector3 (-1, 1, -1),
new Vector3 (1, -1, -1),
new Vector3 (1, 1, -1),
new Vector3 (1, -1, 1),
};
// http://wiki.unity3d.com/index.php/IsVisibleFrom
public static bool VisibleFromCamera (Renderer renderer, Camera camera) {
Plane[] frustumPlanes = GeometryUtility.CalculateFrustumPlanes (camera);
return GeometryUtility.TestPlanesAABB (frustumPlanes, renderer.bounds);
}
public static bool BoundsOverlap (MeshFilter nearObject, MeshFilter farObject, Camera camera) {
var near = GetScreenRectFromBounds (nearObject, camera);
var far = GetScreenRectFromBounds (farObject, camera);
// ensure far object is indeed further away than near object
if (far.zMax > near.zMin) {
// Doesn't overlap on x axis
if (far.xMax < near.xMin || far.xMin > near.xMax) {
return false;
}
// Doesn't overlap on y axis
if (far.yMax < near.yMin || far.yMin > near.yMax) {
return false;
}
// Overlaps
return true;
}
return false;
}
public static float GetScreenHeight (Vector3 a, Vector3 b, Camera camera) {
Debug.DrawLine(a,b,Color.red);
Vector3 viewA = camera.WorldToViewportPoint (a);
Vector3 viewB = camera.WorldToViewportPoint (b);
float dst = Mathf.Abs (viewA.y - viewB.y);
Debug.Log ("A: " + viewA.y + " B: " + viewB.y + " " + dst);
return dst;
}
// With thanks to http://www.turiyaware.com/a-solution-to-unitys-camera-worldtoscreenpoint-causing-ui-elements-to-display-when-object-is-behind-the-camera/
public static MinMax3D GetScreenRectFromBounds (MeshFilter meshFilter, Camera camera) {
MinMax3D minMax = new MinMax3D (float.MaxValue, float.MinValue);
Vector3[] screenBoundsExtents = new Vector3[8];
var localBounds = meshFilter.sharedMesh.bounds;
bool anyPointIsInFrontOfCamera = false;
for (int i = 0; i < 8; i++) {
Vector3 localSpaceCorner = localBounds.center + Vector3.Scale (localBounds.extents, cubeCornerOffsets[i]);
Vector3 worldSpaceCorner = meshFilter.transform.TransformPoint (localSpaceCorner);
Vector3 viewportSpaceCorner = camera.WorldToViewportPoint (worldSpaceCorner);
if (viewportSpaceCorner.z > 0) {
anyPointIsInFrontOfCamera = true;
} else {
// If point is behind camera, it gets flipped to the opposite side
// So clamp to opposite edge to correct for this
viewportSpaceCorner.x = (viewportSpaceCorner.x <= 0.5f) ? 1 : 0;
viewportSpaceCorner.y = (viewportSpaceCorner.y <= 0.5f) ? 1 : 0;
}
// Update bounds with new corner point
minMax.AddPoint (viewportSpaceCorner);
}
// All points are behind camera so just return empty bounds
if (!anyPointIsInFrontOfCamera) {
return new MinMax3D ();
}
return minMax;
}
[System.Serializable]
public struct MinMax3D {
public float xMin;
public float xMax;
public float yMin;
public float yMax;
public float zMin;
public float zMax;
public MinMax3D (float min, float max) {
this.xMin = min;
this.xMax = max;
this.yMin = min;
this.yMax = max;
this.zMin = min;
this.zMax = max;
}
public void AddPoint (Vector3 point) {
xMin = Mathf.Min (xMin, point.x);
xMax = Mathf.Max (xMax, point.x);
yMin = Mathf.Min (yMin, point.y);
yMax = Mathf.Max (yMax, point.y);
zMin = Mathf.Min (zMin, point.z);
zMax = Mathf.Max (zMax, point.z);
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 111ff470e49f24bdfb0aa86a56f773a4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,450 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class CelestialBodyGenerator : MonoBehaviour {
public enum PreviewMode { LOD0, LOD1, LOD2, CollisionRes }
public ResolutionSettings resolutionSettings;
public PreviewMode previewMode;
public bool logTimers;
public CelestialBodySettings body;
bool debugDoubleUpdate = true;
int debug_numUpdates;
// Private variables
Mesh previewMesh;
Mesh collisionMesh;
Mesh[] lodMeshes;
ComputeBuffer vertexBuffer;
bool shapeSettingsUpdated;
bool shadingNoiseSettingsUpdated;
Camera cam;
Vector2 heightMinMax;
// Game mode data
int activeLODIndex = -1;
MeshFilter terrainMeshFilter;
Material terrainMatInstance;
static Dictionary<int, SphereMesh> sphereGenerators;
void Start () {
if (InGameMode) {
cam = Camera.main;
HandleGameModeGeneration ();
}
}
void Update () {
if (InEditMode) {
HandleEditModeGeneration ();
}
}
// Handles creation of celestial body when entering game mode
// This differs from the edit-mode version in the following ways:
// • creates all LOD meshes and stores them in mesh array (to be picked based on player position)
// • creates its own instances of materials so multiple bodies can exist with their own shading
// • doesn't support updating of shape/shading values once generated
void HandleGameModeGeneration () {
if (CanGenerateMesh ()) {
Dummy ();
// Generate LOD meshes
lodMeshes = new Mesh[ResolutionSettings.numLODLevels];
for (int i = 0; i < lodMeshes.Length; i++) {
Vector2 lodTerrainHeightMinMax = GenerateTerrainMesh (ref lodMeshes[i], resolutionSettings.GetLODResolution (i));
// Use min/max height of first (most detailed) LOD
if (i == 0) {
heightMinMax = lodTerrainHeightMinMax;
}
}
// Generate collision mesh
GenerateCollisionMesh (resolutionSettings.collider);
// Create terrain renderer and set shading properties on the instanced material
terrainMatInstance = new Material (body.shading.terrainMaterial);
body.shading.Initialize (body.shape);
body.shading.SetTerrainProperties (terrainMatInstance, heightMinMax, BodyScale);
GameObject terrainHolder = GetOrCreateMeshObject ("Terrain Mesh", null, terrainMatInstance);
terrainMeshFilter = terrainHolder.GetComponent<MeshFilter> ();
// Add collider
MeshCollider collider;
if (!terrainHolder.TryGetComponent<MeshCollider> (out collider)) {
collider = terrainHolder.AddComponent<MeshCollider> ();
}
var collisionBakeTimer = System.Diagnostics.Stopwatch.StartNew ();
MeshBaker.BakeMeshImmediate (collisionMesh);
collider.sharedMesh = collisionMesh;
LogTimer (collisionBakeTimer, "Mesh collider");
} else {
Debug.Log ("Could not generate mesh");
}
ReleaseAllBuffers ();
}
// Handles creation of celestial body in the editor
// This allows for updating the shape/shading settings
void HandleEditModeGeneration () {
if (InEditMode) {
ComputeHelper.shouldReleaseEditModeBuffers -= ReleaseAllBuffers;
ComputeHelper.shouldReleaseEditModeBuffers += ReleaseAllBuffers;
}
if (CanGenerateMesh ()) {
// Update shape settings and shading noise
if (shapeSettingsUpdated) {
shapeSettingsUpdated = false;
shadingNoiseSettingsUpdated = false;
Dummy ();
var terrainMeshTimer = System.Diagnostics.Stopwatch.StartNew ();
heightMinMax = GenerateTerrainMesh (ref previewMesh, PickTerrainRes ());
LogTimer (terrainMeshTimer, "Generate terrain mesh");
DrawEditModeMesh ();
}
// If only shading noise has changed, update it separately from shape to save time
else if (shadingNoiseSettingsUpdated) {
shadingNoiseSettingsUpdated = false;
ComputeHelper.CreateStructuredBuffer<Vector3> (ref vertexBuffer, previewMesh.vertices);
body.shading.Initialize (body.shape);
Vector4[] shadingData = body.shading.GenerateShadingData (vertexBuffer);
previewMesh.SetUVs (0, shadingData);
// Sometimes when changing a colour property, invalid data is returned from compute shader
// Running the shading a second time fixes it.
// Not sure if this is my bug, or Unity's (TODO: investigate)
debug_numUpdates++;
if (debugDoubleUpdate && debug_numUpdates < 2) {
shadingNoiseSettingsUpdated = true;
HandleEditModeGeneration ();
}
if (debug_numUpdates == 2) {
debug_numUpdates = 0;
}
}
}
// Update shading
if (body && body.shading) {
// Set material properties
body.shading.Initialize (body.shape);
body.shading.SetTerrainProperties (body.shading.terrainMaterial, heightMinMax, BodyScale);
}
ReleaseAllBuffers (); //
}
public void SetLOD (int lodIndex) {
if (lodIndex != activeLODIndex && terrainMeshFilter) {
activeLODIndex = lodIndex;
terrainMeshFilter.sharedMesh = lodMeshes[lodIndex];
}
}
public void OnShapeSettingChanged () {
shapeSettingsUpdated = true;
}
public void OnShadingNoiseSettingChanged () {
shadingNoiseSettingsUpdated = true;
}
void OnValidate () {
if (body) {
if (body.shape) {
body.shape.OnSettingChanged -= OnShapeSettingChanged;
body.shape.OnSettingChanged += OnShapeSettingChanged;
}
if (body.shading) {
body.shading.OnSettingChanged -= OnShadingNoiseSettingChanged;
body.shading.OnSettingChanged += OnShadingNoiseSettingChanged;
}
}
if (resolutionSettings != null) {
resolutionSettings.ClampResolutions ();
}
OnShapeSettingChanged ();
}
void Dummy () {
// Crude fix for a problem I was having where the values in the vertex buffer were *occasionally* all zero at start of game
// This function runs the compute shader once with single dummy input, after which it seems the problem doesn't occur
// (Waiting until Time.frameCount > 3 before generating is another gross hack that seems to fix the problem)
// I don't know why...
Vector3[] vertices = new Vector3[] { Vector3.zero };
ComputeHelper.CreateStructuredBuffer<Vector3> (ref vertexBuffer, vertices);
body.shape.CalculateHeights (vertexBuffer);
}
// Generates terrain mesh based on heights generated by the Shape object
// Shading data from the Shading object is stored in the mesh uvs
// Returns the min/max height of the terrain
Vector2 GenerateTerrainMesh (ref Mesh mesh, int resolution) {
var (vertices, triangles) = CreateSphereVertsAndTris (resolution);
ComputeHelper.CreateStructuredBuffer<Vector3> (ref vertexBuffer, vertices);
float edgeLength = (vertices[triangles[0]] - vertices[triangles[1]]).magnitude;
// Set heights
float[] heights = body.shape.CalculateHeights (vertexBuffer);
// Perturb vertices to give terrain a less perfectly smooth appearance
if (body.shape.perturbVertices && body.shape.perturbCompute) {
ComputeShader perturbShader = body.shape.perturbCompute;
float maxperturbStrength = body.shape.perturbStrength * edgeLength / 2;
perturbShader.SetBuffer (0, "points", vertexBuffer);
perturbShader.SetInt ("numPoints", vertices.Length);
perturbShader.SetFloat ("maxStrength", maxperturbStrength);
ComputeHelper.Run (perturbShader, vertices.Length);
Vector3[] pertData = new Vector3[vertices.Length];
vertexBuffer.GetData (vertices);
}
// Calculate terrain min/max height and set heights of vertices
float minHeight = float.PositiveInfinity;
float maxHeight = float.NegativeInfinity;
for (int i = 0; i < heights.Length; i++) {
float height = heights[i];
vertices[i] *= height;
minHeight = Mathf.Min (minHeight, height);
maxHeight = Mathf.Max (maxHeight, height);
}
// Create mesh
CreateMesh (ref mesh, vertices.Length);
mesh.SetVertices (vertices);
mesh.SetTriangles (triangles, 0, true);
mesh.RecalculateNormals (); //
// Shading noise data
body.shading.Initialize (body.shape);
Vector4[] shadingData = body.shading.GenerateShadingData (vertexBuffer);
mesh.SetUVs (0, shadingData);
// Create crude tangents (vectors perpendicular to surface normal)
// This is needed (even though normal mapping is being done with triplanar)
// because surfaceshader wants normals in tangent space
var normals = mesh.normals;
var crudeTangents = new Vector4[mesh.vertices.Length];
for (int i = 0; i < vertices.Length; i++) {
Vector3 normal = normals[i];
crudeTangents[i] = new Vector4 (-normal.z, 0, normal.x, 1);
}
mesh.SetTangents (crudeTangents);
return new Vector2 (minHeight, maxHeight);
}
void GenerateCollisionMesh (int resolution) {
var (vertices, triangles) = CreateSphereVertsAndTris (resolution);
ComputeHelper.CreateStructuredBuffer<Vector3> (ref vertexBuffer, vertices);
// Set heights
float[] heights = body.shape.CalculateHeights (vertexBuffer);
for (int i = 0; i < vertices.Length; i++) {
float height = heights[i];
vertices[i] *= height;
}
// Create mesh
CreateMesh (ref collisionMesh, vertices.Length);
collisionMesh.vertices = vertices;
collisionMesh.triangles = triangles;
}
void CreateMesh (ref Mesh mesh, int numVertices) {
const int vertexLimit16Bit = 1 << 16 - 1; // 65535
if (mesh == null) {
mesh = new Mesh ();
} else {
mesh.Clear ();
}
mesh.indexFormat = (numVertices < vertexLimit16Bit) ? UnityEngine.Rendering.IndexFormat.UInt16 : UnityEngine.Rendering.IndexFormat.UInt32;
}
void DrawEditModeMesh () {
GameObject terrainHolder = GetOrCreateMeshObject ("Terrain Mesh", previewMesh, body.shading.terrainMaterial);
}
// Gets child object with specified name.
// If it doesn't exist, then creates object with that name, adds mesh renderer/filter and attaches mesh and material
GameObject GetOrCreateMeshObject (string name, Mesh mesh, Material material) {
// Find/create object
var child = transform.Find (name);
if (!child) {
child = new GameObject (name).transform;
child.parent = transform;
child.localPosition = Vector3.zero;
child.localRotation = Quaternion.identity;
child.localScale = Vector3.one;
child.gameObject.layer = gameObject.layer;
}
// Add mesh components
MeshFilter filter;
if (!child.TryGetComponent<MeshFilter> (out filter)) {
filter = child.gameObject.AddComponent<MeshFilter> ();
}
filter.sharedMesh = mesh;
MeshRenderer renderer;
if (!child.TryGetComponent<MeshRenderer> (out renderer)) {
renderer = child.gameObject.AddComponent<MeshRenderer> ();
}
renderer.sharedMaterial = material;
return child.gameObject;
}
public int PickTerrainRes () {
if (!Application.isPlaying) {
switch (previewMode) {
case PreviewMode.LOD0:
return resolutionSettings.lod0;
case PreviewMode.LOD1:
return resolutionSettings.lod1;
case PreviewMode.LOD2:
return resolutionSettings.lod2;
case PreviewMode.CollisionRes:
return resolutionSettings.collider;
}
}
return 0;
}
// Radius of the ocean (0 if no ocean exists)
// public float GetOceanRadius () {
// if (!body.shading.hasOcean) {
// return 0;
// }
// return UnscaledOceanRadius * BodyScale;
// }
// float UnscaledOceanRadius {
// get {
// return Mathf.Lerp (heightMinMax.x, 1, body.shading.oceanLevel);
// }
// }
public float BodyScale {
get {
// Body radius is determined by the celestial body class,
// which sets the local scale of the generator object (this object)
return transform.localScale.x;
}
}
// Generate sphere (or reuse if already generated) and return a copy of the vertices and triangles
(Vector3[] vertices, int[] triangles) CreateSphereVertsAndTris (int resolution) {
if (sphereGenerators == null) {
sphereGenerators = new Dictionary<int, SphereMesh> ();
}
if (!sphereGenerators.ContainsKey (resolution)) {
sphereGenerators.Add (resolution, new SphereMesh (resolution));
}
var generator = sphereGenerators[resolution];
var vertices = new Vector3[generator.Vertices.Length];
var triangles = new int[generator.Triangles.Length];
System.Array.Copy (generator.Vertices, vertices, vertices.Length);
System.Array.Copy (generator.Triangles, triangles, triangles.Length);
return (vertices, triangles);
}
void ReleaseAllBuffers () {
ComputeHelper.Release (vertexBuffer);
if (body && body.shape) {
body.shape.ReleaseBuffers ();
}
if (body && body.shading) {
body.shading.ReleaseBuffers ();
}
}
void OnDestroy () {
ReleaseAllBuffers ();
}
bool CanGenerateMesh () {
if (body == null) return false;
return ComputeHelper.CanRunEditModeCompute && body.shape && body.shape.heightMapCompute;
}
void LogTimer (System.Diagnostics.Stopwatch sw, string text) {
if (logTimers) {
Debug.Log (text + " " + sw.ElapsedMilliseconds + " ms.");
}
}
bool InGameMode {
get {
return Application.isPlaying;
}
}
bool InEditMode {
get {
return !Application.isPlaying;
}
}
public class TerrainData {
public float[] heights;
public Vector4[] uvs;
}
[System.Serializable]
public class ResolutionSettings {
public const int numLODLevels = 3;
const int maxAllowedResolution = 500;
public int lod0 = 300;
public int lod1 = 100;
public int lod2 = 50;
public int collider = 100;
public int GetLODResolution (int lodLevel) {
switch (lodLevel) {
case 0:
return lod0;
case 1:
return lod1;
case 2:
return lod2;
}
return lod2;
}
public void ClampResolutions () {
lod0 = Mathf.Min (maxAllowedResolution, lod0);
lod1 = Mathf.Min (maxAllowedResolution, lod1);
lod2 = Mathf.Min (maxAllowedResolution, lod2);
collider = Mathf.Min (maxAllowedResolution, collider);
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: bbe3bd5182f0f47d6a8a90fe1aaadc52
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,7 @@
using UnityEngine;
[CreateAssetMenu (menuName = "Celestial Body/Settings Holder")]
public class CelestialBodySettings : ScriptableObject {
public CelestialBodyShape shape;
public CelestialBodyShading shading;
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1cf43e303dd354502bcaddeec557e12a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: c548d41dd6e37458e85fc5cee48e1799
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,98 @@
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
[CustomEditor (typeof (CelestialBodyGenerator))]
public class GeneratorEditor : Editor {
CelestialBodyGenerator generator;
Editor shapeEditor;
Editor shadingEditor;
bool shapeFoldout;
bool shadingFoldout;
public override void OnInspectorGUI ()
{
using (var check = new EditorGUI.ChangeCheckScope ()) {
DrawDefaultInspector ();
if (check.changed) {
Regenerate ();
}
}
if (generator.body == null) return;
if (GUILayout.Button ("Generate")) {
Regenerate ();
}
if (GUILayout.Button ("Randomize Shading")) {
var prng = new System.Random ();
generator.body.shading.randomize = true;
generator.body.shading.seed = prng.Next (-10000, 10000);
Regenerate ();
}
if (GUILayout.Button ("Randomize Shape")) {
var prng = new System.Random ();
generator.body.shape.randomize = true;
generator.body.shape.seed = prng.Next (-10000, 10000);
Regenerate ();
}
if (GUILayout.Button ("Randomize Both")) {
var prng = new System.Random ();
generator.body.shading.randomize = true;
generator.body.shape.randomize = true;
generator.body.shape.seed = prng.Next (-10000, 10000);
generator.body.shading.seed = prng.Next (-10000, 10000);
Regenerate ();
}
bool randomized = generator.body.shading.randomize || generator.body.shape.randomize;
randomized |= generator.body.shading.seed != 0 || generator.body.shape.seed != 0;
using (new EditorGUI.DisabledGroupScope (!randomized)) {
if (GUILayout.Button ("Reset Randomization")) {
var prng = new System.Random ();
generator.body.shading.randomize = false;
generator.body.shape.randomize = false;
generator.body.shape.seed = 0;
generator.body.shading.seed = 0;
Regenerate ();
}
}
// Draw shape/shading object editors
DrawSettingsEditor (generator.body.shape, ref shapeFoldout, ref shapeEditor);
DrawSettingsEditor (generator.body.shading, ref shadingFoldout, ref shadingEditor);
SaveState ();
}
void Regenerate () {
generator.OnShapeSettingChanged ();
generator.OnShadingNoiseSettingChanged ();
EditorApplication.QueuePlayerLoopUpdate ();
}
void DrawSettingsEditor (Object settings, ref bool foldout, ref Editor editor) {
if (settings != null) {
foldout = EditorGUILayout.InspectorTitlebar (foldout, settings);
if (foldout) {
CreateCachedEditor (settings, null, ref editor);
editor.OnInspectorGUI ();
}
}
}
private void OnEnable () {
shapeFoldout = EditorPrefs.GetBool (nameof (shapeFoldout), false);
shadingFoldout = EditorPrefs.GetBool (nameof (shadingFoldout), false);
generator = (CelestialBodyGenerator) target;
}
void SaveState () {
EditorPrefs.SetBool (nameof (shapeFoldout), shapeFoldout);
EditorPrefs.SetBool (nameof (shadingFoldout), shadingFoldout);
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 823a5227efa6c4baa801dd74ca50ab82
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,21 @@
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
[CustomEditor (typeof (TextureCombiner), true)]
public class TextureCombinerEditor : Editor {
public override void OnInspectorGUI () {
DrawDefaultInspector ();
var textureCombiner = (TextureCombiner) target;
if (GUILayout.Button ("Save")) {
string path = Application.dataPath + "/Resources";
textureCombiner.SaveTexture (path);
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 441a3534f217d45a6945869ae94c0e63
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,57 @@
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
[CustomEditor (typeof (TextureViewer), true)]
public class TextureEditor : Editor {
Editor generatorEditor;
bool generatorFoldout;
public override void OnInspectorGUI () {
DrawDefaultInspector ();
var textureViewer = (TextureViewer) target;
if (GUILayout.Button ("Generate")) {
textureViewer.UpdateTexture ();
}
if (GUILayout.Button ("Save")) {
string path = Application.dataPath + "/Resources";
textureViewer.SaveTexture (path);
}
if (textureViewer.generator) {
bool settingsUpdated = DrawSettingsEditor (textureViewer.generator, ref generatorFoldout, ref generatorEditor);
if (settingsUpdated) {
textureViewer.UpdateTexture ();
}
}
}
bool DrawSettingsEditor (Object settings, ref bool foldout, ref Editor editor) {
if (settings != null) {
foldout = EditorGUILayout.InspectorTitlebar (foldout, settings);
if (foldout) {
using (var check = new EditorGUI.ChangeCheckScope ()) {
CreateCachedEditor (settings, null, ref editor);
editor.OnInspectorGUI ();
if (check.changed) {
return true;
}
}
}
}
return false;
}
private void OnEnable () {
generatorFoldout = EditorPrefs.GetBool (nameof (generatorFoldout), false);
}
void OnDisable () {
EditorPrefs.SetBool (nameof (generatorFoldout), generatorFoldout);
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c73be003ed7554257819b982d1816b59
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,78 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class LODHandler : MonoBehaviour {
[Header ("LOD screen heights")]
// LOD level is determined by body's screen height (1 = taking up entire screen, 0 = teeny weeny speck)
public float lod1Threshold = .5f;
public float lod2Threshold = .2f;
// [Header ("Debug")]
// public bool debug;
// public CelestialBody debugBody;
Camera cam;
Transform camT;
// CelestialBody[] bodies;
CelestialBodyGenerator[] generators;
public void FindPlanets()
{
generators = FindObjectsOfType<CelestialBodyGenerator> ();
}
void Update () {
//DebugLODInfo ();
if (Application.isPlaying) {
HandleLODs ();
}
}
void HandleLODs () {
for (int i = 0; i < generators.Length; i++) {
float screenHeight = CalculateScreenHeight (generators[i]);
int lodIndex = CalculateLODIndex (screenHeight);
generators[i].SetLOD (lodIndex);
}
}
int CalculateLODIndex (float screenHeight) {
if (screenHeight > lod1Threshold) {
return 0;
} else if (screenHeight > lod2Threshold) {
return 1;
}
return 2;
}
// void DebugLODInfo () {
// if (debugBody && debug) {
// float h = CalculateScreenHeight (debugBody);
// int index = CalculateLODIndex (h);
// Debug.Log ($"Screen height of {debugBody.name}: {h} (lod = {index})");
// }
// }
float CalculateScreenHeight (CelestialBodyGenerator body) {
if (cam == null) {
cam = Camera.main;
camT = cam.transform;
}
Quaternion originalRot = camT.rotation;
Vector3 bodyCentre = body.transform.position;
camT.LookAt (bodyCentre);
var radius = body.transform.localScale.x;
Vector3 viewA = cam.WorldToViewportPoint (bodyCentre - camT.up * radius);
Vector3 viewB = cam.WorldToViewportPoint (bodyCentre + camT.up * radius);
float screenHeight = Mathf.Abs (viewA.y - viewB.y);
camT.rotation = originalRot;
return screenHeight;
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 57b1674fe39b4584faf5fa92c3e4e024
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,48 @@
using System.Collections;
using System.Collections.Generic;
using Unity.Collections;
using Unity.Jobs;
using UnityEngine;
public static class MeshBaker {
static Dictionary<Mesh, JobHandle> jobsByMesh;
static MeshBaker () {
jobsByMesh = new Dictionary<Mesh, JobHandle> ();
}
public static void BakeMeshImmediate (Mesh mesh) {
var job = new BakeJob (mesh.GetInstanceID ());
JobHandle currentJob = job.Schedule ();
currentJob.Complete ();
}
public static void StartBakingMesh (Mesh mesh) {
var job = new BakeJob (mesh.GetInstanceID ());
JobHandle currentJob = job.Schedule ();
jobsByMesh.Add (mesh, currentJob);
}
public static void EnsureBakingComplete (Mesh mesh) {
if (jobsByMesh.ContainsKey (mesh)) {
jobsByMesh[mesh].Complete ();
jobsByMesh.Remove (mesh);
} else {
BakeMeshImmediate (mesh);
}
}
}
public struct BakeJob : IJob {
int meshID;
public BakeJob (int meshID) {
this.meshID = meshID;
}
public void Execute () {
Physics.BakeMesh (meshID, false);
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e6efe2e9f564c464e8b47696ab6a5752
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 944baa69d640f4d979fe5e813b8a0aaa
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,78 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class CraterSettings {
// Exposed settings
public bool enabled = true;
public int craterSeed;
public int numCraters = 400;
public Vector2 craterSizeMinMax = new Vector2 (0.01f, 0.1f);
public float rimSteepness = 0.13f;
public float rimWidth = 1.6f;
public Vector2 smoothMinMax = new Vector2 (0.4f, 1.5f);
[Range (0, 1)]
public float sizeDistribution = 0.6f;
[HideInInspector]
public Crater[] cachedCraters;
// Private
ComputeBuffer craterBuffer;
// Set values using exposed settings
public void SetComputeValues (ComputeShader computeShader, int masterSeed) {
SetComputeValues (computeShader, masterSeed, numCraters, craterSizeMinMax, sizeDistribution);
}
// Set values using custom numCraters
public void SetComputeValues (ComputeShader computeShader, int masterSeed, int numCraters) {
SetComputeValues (computeShader, masterSeed, numCraters, craterSizeMinMax, sizeDistribution);
}
// Set values using custom numCraters and sizeMinMax
public void SetComputeValues (ComputeShader computeShader, int masterSeed, int numCraters, Vector2 craterSizeMinMax, float sizeDistribution) {
if (!enabled) {
numCraters = 1;
craterSizeMinMax = Vector2.zero;
}
Random.InitState (craterSeed + masterSeed);
Crater[] craters = new Crater[numCraters];
PRNG prng = new PRNG (masterSeed);
// Create craters
for (int i = 0; i < numCraters; i++) {
float t = prng.ValueBiasLower (sizeDistribution);
float size = Mathf.Lerp (craterSizeMinMax.x, craterSizeMinMax.y, t);
float floorHeight = Mathf.Lerp (-1.2f, -0.2f, t + prng.ValueBiasLower (0.3f));
float smooth = Mathf.Lerp (smoothMinMax.x, smoothMinMax.y, 1 - t);
craters[i] = new Crater () { centre = Random.onUnitSphere, size = size, floorHeight = floorHeight, smoothness = smooth };
}
cachedCraters = craters;
// Set shape data
ComputeHelper.CreateAndSetBuffer<Crater> (ref craterBuffer, craters, computeShader, "craters");
computeShader.SetInt ("numCraters", numCraters);
computeShader.SetFloat (nameof (rimSteepness), rimSteepness);
computeShader.SetFloat (nameof (rimWidth), rimWidth);
//computeShader.SetFloat (nameof (smoothFactor), smoothFactor);
}
public void ReleaseBuffers () {
ComputeHelper.Release (craterBuffer);
}
[System.Serializable]
public struct Crater {
public Vector3 centre;
public float size;
public float floorHeight;
public float smoothness;
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a9d550c3b804444558e4efd3f7b16c46
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,47 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class RidgeNoiseSettings {
public int numLayers = 5;
public float lacunarity = 2;
public float persistence = 0.5f;
public float scale = 1;
public float power = 2;
public float elevation = 1;
public float gain = 1;
public float verticalShift = 0;
public float peakSmoothing = 0;
public Vector3 offset;
// Set values using exposed settings
public void SetComputeValues (ComputeShader cs, PRNG prng, string varSuffix) {
SetComputeValues (cs, prng, varSuffix, scale, elevation, power);
}
// Set values using custom scale and elevation
public void SetComputeValues (ComputeShader cs, PRNG prng, string varSuffix, float scale, float elevation, float power) {
Vector3 seededOffset = new Vector3 (prng.Value (), prng.Value (), prng.Value ()) * prng.Value () * 10000;
float[] noiseParams = {
// [0]
seededOffset.x + offset.x,
seededOffset.y + offset.y,
seededOffset.z + offset.z,
numLayers,
// [1]
persistence,
lacunarity,
scale,
elevation,
// [2]
power,
gain,
verticalShift,
peakSmoothing
};
cs.SetFloats ("noiseParams" + varSuffix, noiseParams);
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5ce43a491b81c44459b8660e15e2ca80
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,46 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class SimpleNoiseSettings {
public int numLayers = 4;
public float lacunarity = 2;
public float persistence = 0.5f;
public float scale = 1;
public float elevation = 1;
public float verticalShift = 0;
public Vector3 offset;
// Set values using exposed settings
public void SetComputeValues (ComputeShader cs, PRNG prng, string varSuffix) {
SetComputeValues (cs, prng, varSuffix, scale, elevation, persistence);
}
// Set values using custom scale and elevation
public void SetComputeValues (ComputeShader cs, PRNG prng, string varSuffix, float scale, float elevation) {
SetComputeValues (cs, prng, varSuffix, scale, elevation, persistence);
}
// Set values using custom scale and elevation
public void SetComputeValues (ComputeShader cs, PRNG prng, string varSuffix, float scale, float elevation, float persistence) {
Vector3 seededOffset = new Vector3 (prng.Value (), prng.Value (), prng.Value ()) * prng.Value () * 10000;
float[] noiseParams = {
// [0]
seededOffset.x + offset.x,
seededOffset.y + offset.y,
seededOffset.z + offset.z,
numLayers,
// [1]
persistence,
lacunarity,
scale,
elevation,
// [2]
verticalShift
};
cs.SetFloats ("noiseParams" + varSuffix, noiseParams);
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b9fcbd96d66fe4c07b65caa879fc4898
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,21 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class Normalizer {
public static void Normalize (System.Func<int, float> getValue, System.Action<int, float> setValue, int length) {
float min = float.PositiveInfinity;
float max = float.NegativeInfinity;
for (int i = 0; i < length; i++) {
float value = getValue (i);
min = System.Math.Min (min, value);
max = System.Math.Max (max, value);
}
for (int i = 0; i < length; i++) {
setValue (i, Mathf.InverseLerp (min, max, getValue (i)));
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1d100b5aa20444f8fb097d412a664190
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,55 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu (menuName = "Celestial Body/Ocean")]
public class OceanSettings : ScriptableObject {
public float depthMultiplier = 10;
public float alphaMultiplier = 70;
public Color colA;
public Color colB;
public Color specularCol = Color.white;
[Header ("Waves")]
public Texture2D waveNormalA;
public Texture2D waveNormalB;
[Range (0, 1)]
public float waveStrength = 0.15f;
public float waveScale = 15;
public float waveSpeed = 0.5f;
//[Header("")]
[Range (0, 1)]
public float smoothness = 0.92f;
public Vector4 testParams;
public void SetProperties (Material material, int seed, bool randomize) {
material.SetFloat ("depthMultiplier", depthMultiplier);
material.SetFloat ("alphaMultiplier", alphaMultiplier);
material.SetTexture ("waveNormalA", waveNormalA);
material.SetTexture ("waveNormalB", waveNormalB);
material.SetFloat ("waveStrength", waveStrength);
material.SetFloat ("waveNormalScale", waveScale);
material.SetFloat ("waveSpeed", waveSpeed);
material.SetFloat ("smoothness", smoothness);
material.SetVector ("params", testParams);
if (randomize) {
var random = new PRNG (seed);
var randomColA = Color.HSVToRGB (random.Value (), random.Range (0.6f, 0.8f), random.Range (0.65f, 1));
var randomColB = ColourHelper.TweakHSV (randomColA,
random.SignedValue() * 0.2f,
random.SignedValue() * 0.2f,
random.Range (-0.5f, -0.4f)
);
material.SetColor ("colA", randomColA);
material.SetColor ("colB", randomColB);
material.SetColor ("specularCol", Color.white);
} else {
material.SetColor ("colA", colA);
material.SetColor ("colB", colB);
material.SetColor ("specularCol", specularCol);
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0467bf655a1214b878d6510a0b2bb09f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 0fae4e8ac2d2c4b0d8f5537209e54de2
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 3ecf2f56406b74719a8e779682350f40
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,78 @@
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
[CustomEditor (typeof (SceneCamManager))]
public class SceneCamEditor : Editor {
SceneCamManager manager;
public override void OnInspectorGUI () {
DrawDefaultInspector ();
var activeSceneView = SceneView.lastActiveSceneView;
var allViews = SceneView.sceneViews;
if (manager.savedViews.Count > 0) {
GUILayout.Label ($"Saved views: ({manager.savedViews.Count})");
int deleteIndex = -1;
for (int i = 0; i < manager.savedViews.Count; i++) {
GUILayout.BeginVertical ("GroupBox");
var savedView = manager.savedViews[i];
savedView.name = GUILayout.TextField (savedView.name);
GUILayout.BeginHorizontal ();
if (GUILayout.Button ("Set Camera View")) {
Undo.RecordObject (manager, "Set Camera View");
activeSceneView.pivot = savedView.pivot;
activeSceneView.rotation = savedView.rotation;
activeSceneView.size = savedView.size;
}
if (GUILayout.Button ("Replace")) {
Undo.RecordObject (manager, "Replace View");
savedView.pivot = activeSceneView.pivot;
savedView.rotation = activeSceneView.rotation;
savedView.size = activeSceneView.size;
}
if (GUILayout.Button ("Delete")) {
Undo.RecordObject (manager, "Delete View");
deleteIndex = i;
}
GUILayout.EndHorizontal ();
GUILayout.EndVertical ();
}
if (deleteIndex != -1) {
manager.savedViews.RemoveAt (deleteIndex);
}
GUILayout.Space (15);
}
foreach (var v in allViews) {
//GUILayout.Label (v.ToString ());
}
if (GUILayout.Button ("Save Current View")) {
Undo.RecordObject (manager, "Save View");
var newView = new SceneCamManager.SavedView ();
newView.name = $"View ({manager.savedViews.Count})";
newView.pivot = activeSceneView.pivot;
newView.rotation = activeSceneView.rotation;
newView.size = activeSceneView.size;
manager.savedViews.Add (newView);
}
}
void OnEnable () {
manager = (SceneCamManager) target;
if (manager.savedViews == null) {
manager.savedViews = new List<SceneCamManager.SavedView> ();
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 56eb8740038fb43b9b80a07a6899dc39
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,17 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SceneCamManager : MonoBehaviour {
[HideInInspector]
public List<SavedView> savedViews;
[System.Serializable]
public class SavedView {
public string name;
public float size;
public Vector3 pivot;
public Quaternion rotation;
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4fb6cca85fa094435b4d21a471e78d89
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: a9a51a36c3395ef458da81b0bc1d4e6f
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,48 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class ChanceTest : MonoBehaviour {
public Chance chance;
public int total;
void Update () {
if (Input.GetKeyDown (KeyCode.Space)) {
chance = new Chance (new System.Random ());
total++;
if (chance.Percent (10)) {
Debug.Log ("1");
}
if (chance.Percent (70)) {
Debug.Log ("7");
}
if (chance.Percent (20)) {
Debug.Log ("2");
}
}
}
}
public class Chance {
float value;
public Chance (System.Random prng) {
value = (float) prng.NextDouble ();
}
public Chance (PRNG prng) {
value = prng.Value ();
}
public bool Percent (float percent) {
if (value <= 0) {
return false;
}
float t = percent / 100f;
value -= t;
return value <= 0;
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: dbd90d6e181eb5145ad5cb26288bb585
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,176 @@
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
public static class ComputeHelper {
// Subscribe to this event to be notified when buffers created in edit mode should be released
// (i.e before script compilation occurs, and when exitting edit mode)
public static event System.Action shouldReleaseEditModeBuffers;
// Convenience method for dispatching a compute shader.
// It calculates the number of thread groups based on the number of iterations needed.
public static void Run (ComputeShader cs, int numIterationsX, int numIterationsY = 1, int numIterationsZ = 1, int kernelIndex = 0) {
Vector3Int threadGroupSizes = GetThreadGroupSizes (cs, kernelIndex);
int numGroupsX = Mathf.CeilToInt (numIterationsX / (float) threadGroupSizes.x);
int numGroupsY = Mathf.CeilToInt (numIterationsY / (float) threadGroupSizes.y);
int numGroupsZ = Mathf.CeilToInt (numIterationsZ / (float) threadGroupSizes.y);
cs.Dispatch (kernelIndex, numGroupsX, numGroupsY, numGroupsZ);
}
// Only run compute shaders if this is true
// This is only relevant for compute shaders that run outside of playmode
public static bool CanRunEditModeCompute {
get {
return CheckIfCanRunInEditMode ();
}
}
// Set all values from settings object on the shader. Note, variable names must be an exact match in the shader.
// Settings object can be any class/struct containing vectors/ints/floats/bools
public static void SetParams (System.Object settings, ComputeShader shader, string variableNamePrefix = "", string variableNameSuffix = "") {
var fields = settings.GetType ().GetFields ();
foreach (var field in fields) {
var fieldType = field.FieldType;
string shaderVariableName = variableNamePrefix + field.Name + variableNameSuffix;
if (fieldType == typeof (UnityEngine.Vector4) || fieldType == typeof (Vector3) || fieldType == typeof (Vector2)) {
shader.SetVector (shaderVariableName, (Vector4) field.GetValue (settings));
} else if (fieldType == typeof (int)) {
shader.SetInt (shaderVariableName, (int) field.GetValue (settings));
} else if (fieldType == typeof (float)) {
shader.SetFloat (shaderVariableName, (float) field.GetValue (settings));
} else if (fieldType == typeof (bool)) {
shader.SetBool (shaderVariableName, (bool) field.GetValue (settings));
} else {
Debug.Log ($"Type {fieldType} not implemented");
}
}
}
public static void CreateStructuredBuffer<T> (ref ComputeBuffer buffer, int count) {
int stride = System.Runtime.InteropServices.Marshal.SizeOf (typeof (T));
bool createNewBuffer = buffer == null || !buffer.IsValid () || buffer.count != count || buffer.stride != stride;
if (createNewBuffer) {
Release (buffer);
buffer = new ComputeBuffer (count, stride);
}
}
public static void CreateStructuredBuffer<T> (ref ComputeBuffer buffer, T[] data) {
CreateStructuredBuffer<T> (ref buffer, data.Length);
buffer.SetData (data);
}
// Test
public static ComputeBuffer CreateAndSetBuffer<T> (T[] data, ComputeShader cs, string nameID, int kernelIndex = 0) {
ComputeBuffer buffer = null;
CreateAndSetBuffer<T> (ref buffer, data, cs, nameID, kernelIndex);
return buffer;
}
public static void CreateAndSetBuffer<T> (ref ComputeBuffer buffer, T[] data, ComputeShader cs, string nameID, int kernelIndex = 0) {
int stride = System.Runtime.InteropServices.Marshal.SizeOf (typeof (T));
CreateStructuredBuffer<T> (ref buffer, data.Length);
buffer.SetData (data);
cs.SetBuffer (kernelIndex, nameID, buffer);
}
public static ComputeBuffer CreateAndSetBuffer<T> (int length, ComputeShader cs, string nameID, int kernelIndex = 0) {
ComputeBuffer buffer = null;
CreateAndSetBuffer<T> (ref buffer, length, cs, nameID, kernelIndex);
return buffer;
}
public static void CreateAndSetBuffer<T> (ref ComputeBuffer buffer, int length, ComputeShader cs, string nameID, int kernelIndex = 0) {
CreateStructuredBuffer<T> (ref buffer, length);
cs.SetBuffer (kernelIndex, nameID, buffer);
}
// Releases supplied buffer/s if not null
public static void Release (params ComputeBuffer[] buffers) {
for (int i = 0; i < buffers.Length; i++) {
if (buffers[i] != null) {
buffers[i].Release ();
}
}
}
public static Vector3Int GetThreadGroupSizes (ComputeShader compute, int kernelIndex = 0) {
uint x, y, z;
compute.GetKernelThreadGroupSizes (kernelIndex, out x, out y, out z);
return new Vector3Int ((int) x, (int) y, (int) z);
}
public static void CreateRenderTexture (ref RenderTexture texture, int size, FilterMode filterMode = FilterMode.Bilinear, GraphicsFormat format = GraphicsFormat.R16G16B16A16_SFloat) {
CreateRenderTexture (ref texture, size, size, filterMode, format);
}
public static void CreateRenderTexture (ref RenderTexture texture, int width, int height, FilterMode filterMode = FilterMode.Bilinear, GraphicsFormat format = GraphicsFormat.R16G16B16A16_SFloat) {
if (texture == null || !texture.IsCreated () || texture.width != width || texture.height != height || texture.graphicsFormat != format) {
if (texture != null) {
texture.Release ();
}
texture = new RenderTexture (width, height, 0);
texture.graphicsFormat = format;
texture.enableRandomWrite = true;
texture.autoGenerateMips = false;
texture.Create ();
}
texture.wrapMode = TextureWrapMode.Clamp;
texture.filterMode = filterMode;
}
// https://cmwdexint.com/2017/12/04/computeshader-setfloats/
public static float[] PackFloats (params float[] values) {
float[] packed = new float[values.Length * 4];
for (int i = 0; i < values.Length; i++) {
packed[i * 4] = values[i];
}
return values;
}
// Editor helpers:
#if UNITY_EDITOR
static UnityEditor.PlayModeStateChange playModeState;
static ComputeHelper () {
// Monitor play mode state
UnityEditor.EditorApplication.playModeStateChanged -= MonitorPlayModeState;
UnityEditor.EditorApplication.playModeStateChanged += MonitorPlayModeState;
// Monitor script compilation
UnityEditor.Compilation.CompilationPipeline.compilationStarted -= OnCompilationStarted;
UnityEditor.Compilation.CompilationPipeline.compilationStarted += OnCompilationStarted;
}
static void MonitorPlayModeState (UnityEditor.PlayModeStateChange state) {
playModeState = state;
if (state == UnityEditor.PlayModeStateChange.ExitingEditMode) {
if (shouldReleaseEditModeBuffers != null) {
shouldReleaseEditModeBuffers (); //
}
}
}
static void OnCompilationStarted (System.Object obj) {
if (shouldReleaseEditModeBuffers != null) {
shouldReleaseEditModeBuffers ();
}
}
#endif
static bool CheckIfCanRunInEditMode () {
bool isCompilingOrExitingEditMode = false;
#if UNITY_EDITOR
isCompilingOrExitingEditMode |= UnityEditor.EditorApplication.isCompiling;
isCompilingOrExitingEditMode |= playModeState == UnityEditor.PlayModeStateChange.ExitingEditMode;
#endif
bool canRun = !isCompilingOrExitingEditMode;
return canRun;
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 711fda09f27fe41dfa8af54cab7ed80c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,116 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class MathUtility {
public static bool RaySphere (Vector3 centre, float radius, Vector3 rayOrigin, Vector3 rayDir, out Vector3 intersectionPoint) {
// See: http://viclw17.github.io/2018/07/16/raytracing-ray-sphere-intersection/
Vector3 offset = rayOrigin - centre;
float a = Vector3.Dot (rayDir, rayDir); // sqr ray length (in case of non-normalized rayDir)
float b = 2 * Vector3.Dot (offset, rayDir);
float c = Vector3.Dot (offset, offset) - radius * radius;
float discriminant = b * b - 4 * a * c;
// No intersections: discriminant < 0
// 1 intersection: discriminant == 0
// 2 intersections: discriminant > 0
if (discriminant >= 0) {
float t = (-b - Mathf.Sqrt (discriminant)) / (2 * a);
//float t2 = (-b + Mathf.Sqrt (discriminant)) / (2 * a); // The further away intersection point
// If t is negative, the intersection was in negative ray direction so ignore it
if (t >= 0) {
intersectionPoint = rayOrigin + rayDir * t;
return true;
}
}
intersectionPoint = Vector3.zero;
return false;
}
public static bool LineSegmentsIntersect (Vector2 a1, Vector2 a2, Vector2 b1, Vector2 b2) {
float d = (b2.x - b1.x) * (a1.y - a2.y) - (a1.x - a2.x) * (b2.y - b1.y);
if (d == 0)
return false;
float t = ((b1.y - b2.y) * (a1.x - b1.x) + (b2.x - b1.x) * (a1.y - b1.y)) / d;
float u = ((a1.y - a2.y) * (a1.x - b1.x) + (a2.x - a1.x) * (a1.y - b1.y)) / d;
return t >= 0 && t <= 1 && u >= 0 && u <= 1;
}
public static bool LinesIntersect (Vector2 a1, Vector2 a2, Vector2 a3, Vector2 a4) {
return (a1.x - a2.x) * (a3.y - a4.y) - (a1.y - a2.y) * (a3.x - a4.x) != 0;
}
public static Vector2 PointOfLineLineIntersection (Vector2 a1, Vector2 a2, Vector2 a3, Vector2 a4) {
float d = (a1.x - a2.x) * (a3.y - a4.y) - (a1.y - a2.y) * (a3.x - a4.x);
if (d == 0) {
Debug.LogError ("Lines are parallel, please check that this is not the case before calling line intersection method");
return Vector2.zero;
} else {
float n = (a1.x - a3.x) * (a3.y - a4.y) - (a1.y - a3.y) * (a3.x - a4.x);
float t = n / d;
return a1 + (a2 - a1) * t;
}
}
public static Vector2 ClosestPointOnLineSegment (Vector2 p, Vector2 a, Vector2 b) {
Vector2 aB = b - a;
Vector2 aP = p - a;
float sqrLenAB = aB.sqrMagnitude;
if (sqrLenAB == 0)
return a;
float t = Mathf.Clamp01 (Vector2.Dot (aP, aB) / sqrLenAB);
return a + aB * t;
}
public static Vector3 ClosestPointOnLineSegment (Vector3 p, Vector3 a, Vector3 b) {
Vector3 aB = b - a;
Vector3 aP = p - a;
float sqrLenAB = aB.sqrMagnitude;
if (sqrLenAB == 0)
return a;
float t = Mathf.Clamp01 (Vector3.Dot (aP, aB) / sqrLenAB);
return a + aB * t;
}
public static int SideOfLine (Vector2 a, Vector2 b, Vector2 c) {
return (int) Mathf.Sign ((c.x - a.x) * (-b.y + a.y) + (c.y - a.y) * (b.x - a.x));
}
/// returns the smallest angle between ABC. Never greater than 180
public static float MinAngle (Vector3 a, Vector3 b, Vector3 c) {
return Vector3.Angle ((a - b), (c - b));
}
public static bool PointInTriangle (Vector2 a, Vector2 b, Vector2 c, Vector2 p) {
float area = 0.5f * (-b.y * c.x + a.y * (-b.x + c.x) + a.x * (b.y - c.y) + b.x * c.y);
float s = 1 / (2 * area) * (a.y * c.x - a.x * c.y + (c.y - a.y) * p.x + (a.x - c.x) * p.y);
float t = 1 / (2 * area) * (a.x * b.y - a.y * b.x + (a.y - b.y) * p.x + (b.x - a.x) * p.y);
return s >= 0 && t >= 0 && (s + t) <= 1;
}
public static bool PointsAreClockwise (Vector2[] points) {
float signedArea = 0;
for (int i = 0; i < points.Length; i++) {
int nextIndex = (i + 1) % points.Length;
signedArea += (points[nextIndex].x - points[i].x) * (points[nextIndex].y + points[i].y);
}
return signedArea >= 0;
}
public static Vector2 V3ToXZ (Vector3 v3) {
return new Vector2 (v3.x, v3.z);
}
public static Vector3 V2ToXYZ (Vector2 v2, float yValue) {
return new Vector3 (v2.x, yValue, v2.y);
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 69df6ef4fd0704bd9835a45dbb941451
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,231 @@
using System;
using System.Collections.Generic;
using UnityEngine;
public class PRNG {
public enum Weight { None, Lower, Upper, Centre, Ends }
System.Random prng;
int seed;
public int Seed {
get {
return seed;
}
}
public PRNG (int seed) {
this.seed = seed;
prng = new System.Random (this.seed);
}
public PRNG (string seed) {
this.seed = seed.GetHashCode ();
prng = new System.Random (this.seed);
}
public PRNG () {
prng = new System.Random ();
}
/// Returns a random integer value [min, max)
public int Range (int min, int max) {
return prng.Next (min, max);
}
/// Returns a random float value [min, max)
public float Range (float min, float max) {
return Mathf.Lerp (min, max, (float) prng.NextDouble ());
}
// Returns a vector4 where each component is a random number in range [min, max)
public Vector4 RangeVector4 (float minInclusive, float maxExclusive) {
Vector4 vector = Vector4.zero;
for (int i = 0; i < 4; i++) {
vector[i] = Range (minInclusive, maxExclusive);
}
return vector;
}
/// Random value [0, 1]
public float Value () {
// According to stackoverflow this should technically allow the random value to equal 1
const double maxExclusive = 1.0000000004656612875245796924106;
return (float) (prng.NextDouble () * maxExclusive);
}
/// Random value [0, 1]
/// Output is increasingly biased toward 1 as biasStrength goes from 0 to 1
public float ValueBiasUpper (float biasStrength) {
return 1 - ValueBiasLower (biasStrength);
}
/// Random value [0, 1]
/// Output is increasingly biased toward 0 as biasStrength goes from 0 to 1
public float ValueBiasLower (float biasStrength) {
float t = Value ();
// Avoid possible division by zero
if (biasStrength == 1) {
return 0;
}
// Remap strength for nicer input -> output relationship
float k = Mathf.Clamp01 (1 - biasStrength);
k = k * k * k - 1;
// Thanks to www.shadertoy.com/view/Xd2yRd
return Mathf.Clamp01 ((t + t * k) / (t * k + 1));
}
/// Random value [0, 1]
/// Output is increasingly biased toward the extremes (0 or 1) as biasStrength goes from 0 to 1
public float ValueBiasExtremes (float biasStrength) {
float t = ValueBiasLower (biasStrength);
return (Value () < 0.5f) ? t : 1 - t;
}
/// Random value [0, 1]
/// Output is increasingly biased toward 0.5 as biasStrength goes from 0 to 1
public float ValueBiasCentre (float biasStrength) {
float t = ValueBiasLower (biasStrength);
return 0.5f + t * 0.5f * Sign ();
}
// ---- Signed versions [-1, 1] ---
/// Random value [-1, 1]
public float SignedValue () {
return Value () * 2 - 1;
}
/// Random value [-1, 1]
/// Output is increasingly biased toward the extremes (-1 or 1) as biasStrength goes from 0 to 1
public float SignedValueBiasExtremes (float biasStrength) {
return ValueBiasExtremes (biasStrength) * 2 - 1;
}
/// Random value [-1, 1]
/// Output is increasingly biased toward 0 as biasStrength goes from 0 to 1
public float SignedValueBiasCentre (float biasStrength) {
return ValueBiasCentre (biasStrength) * 2 - 1;
}
// Returns a weighted value in range [min, max)
public float WeightedRange (float min, float max, Weight weight, int weightStrength = 4) {
float value01 = WeightedValue (weight, weightStrength);
return Mathf.Lerp (min, max, value01);
}
// Returns a weighted value in range [-1, 1)
public float WeightedSignedValue (Weight weight, int weightStrength = 4) {
return WeightedValue (weight, weightStrength) * 2 - 1;
}
// Returns a weighted value in range [0, 1)
public float WeightedValue (Weight weight, int weightStrength = 4) {
if (weight == Weight.None) {
return Value ();
}
float smallestValue = Value ();
for (int i = 0; i < weightStrength; i++) {
smallestValue = Mathf.Min (smallestValue, Value ());
}
switch (weight) {
case Weight.Lower: // Bias towards smaller values
return smallestValue;
case Weight.Upper: // Bias towards larger values
return 1 - smallestValue;
case Weight.Centre: // Bias towards middle values
return 0.5f + smallestValue * 0.5f * Sign ();
case Weight.Ends: // Bias towards smaller and larger values
return (Value () < 0.5f) ? smallestValue : 1 - smallestValue;
default:
Debug.LogError ("Missing weight implementation");
return 0;
}
}
// Returns the smallest of n random numbers between 0 and 1
public float SmallestRandom01 (int n) {
float smallest = 1;
for (int i = 0; i < n; i++) {
smallest = Mathf.Min (smallest, Value ());
}
return smallest;
}
// Returns the largest of n random numbers between 0 and 1
public float LargestRandom01 (int n) {
float largest = 0;
for (int i = 0; i < n; i++) {
largest = Mathf.Max (largest, Value ());
}
return largest;
}
// Returns the value closest to 0.5 out of n random numbers between 0 and 1
public float CentredRandom01 (int n) {
float mostCentredValue = 0;
for (int i = 0; i < n; i++) {
float value = Value ();
if (Mathf.Abs (value - 0.5f) < Mathf.Abs (mostCentredValue - 0.5f)) {
mostCentredValue = value;
}
}
return mostCentredValue;
}
public int Sign () {
return (prng.NextDouble () > 0.5) ? 1 : -1;
}
public int NextInt () {
return prng.Next ();
}
public Vector3 JiggleVector3 (float weightX, float weightY, float weightZ) {
return new Vector3 (SignedValue () * weightX, SignedValue () * weightY, SignedValue () * weightZ);
}
// Colours
public Color ColorHSV (float saturationMin, float saturationMax, float valueMin, float valueMax) {
float hue = Value ();
float saturation = Range (saturationMin, saturationMax);
float value = Range (valueMin, valueMax);
return Color.HSVToRGB (hue, saturation, value);
}
public Color ColorGreyscale (float valueMin, float valueMax) {
float value = Range (valueMin, valueMax);
return new Color (value, value, value);
}
// Elements
public T RandomElement<T> (T[] array) {
return array[Range (0, array.Length)];
}
public void Shuffle<T> (T[] array) {
int n = array.Length;
for (int i = 0; i < n - 1; i++) {
int j = prng.Next (i, n);
T temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
public void Shuffle<T> (List<T> list) {
int n = list.Count;
for (int i = 0; i < n - 1; i++) {
int j = prng.Next (i, n);
T temp = list[j];
list[j] = list[i];
list[i] = temp;
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ae686c76044de4891a2c6a36bf7434de
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,25 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class ShaderHelper {
// Set all values from settings object on the shader. Note, variable names must be an exact match in the shader.
// Settings object can be any class/struct containing vectors/ints/floats
public static void SetParams (System.Object settings, Material material, string variableNamePrefix = "") {
var fields = settings.GetType ().GetFields ();
foreach (var field in fields) {
var fieldType = field.FieldType;
string shaderVariableName = variableNamePrefix + field.Name;
if (fieldType == typeof (UnityEngine.Vector4) || fieldType == typeof (Vector3) || fieldType == typeof (Vector2)) {
material.SetVector (shaderVariableName, (Vector4) field.GetValue (settings));
} else if (fieldType == typeof (int)) {
material.SetInt (shaderVariableName, (int) field.GetValue (settings));
} else if (fieldType == typeof (float)) {
material.SetFloat (shaderVariableName, (float) field.GetValue (settings));
} else {
Debug.Log ($"Type {fieldType} not implemented");
}
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7782a7a4791c8426aa102052d42c2541
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,22 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class TextureHelper {
public static void TextureFromGradient (Gradient gradient, int width, ref Texture2D texture) {
if (texture == null || texture.width != width || texture.height != 1) {
texture = new Texture2D (width, 1);
texture.filterMode = FilterMode.Bilinear;
texture.wrapMode = TextureWrapMode.Clamp;
}
Color[] colours = new Color[width];
for (int i = 0; i < width; i++) {
float t = i / (width - 1f);
colours[i] = gradient.Evaluate (t);
}
texture.SetPixels (colours);
texture.Apply ();
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ca4552dbbcdf04006b442ee84e5b2703
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 267a921ab0972416c9c8bd6c2d121654
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 1e03537b7c5244b0882d8e7efc2c0abe
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 375b93914a7154241b14ccf7df35e859
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,87 @@
#pragma kernel CSMain
#include "../../Includes/Math.cginc"
RWTexture2D<float4> Result;
int textureSize;
int numOutScatteringSteps;
float atmosphereRadius;
float avgDensityHeight01;
float densityFalloff;
float4 params;
float densityAtPoint(float2 densitySamplePoint) {
float planetRadius = 1;
float2 planetCentre = 0;
float heightAboveSurface = length(densitySamplePoint - planetCentre) - planetRadius;
float height01 = heightAboveSurface / (atmosphereRadius - planetRadius);
float localDensity = exp(-height01 * densityFalloff) * (1 - height01);
return localDensity;
}
float opticalDepth(float2 rayOrigin, float2 rayDir, float rayLength) {
int numOpticalDepthPoints = numOutScatteringSteps;
float2 densitySamplePoint = rayOrigin;
float stepSize = rayLength / (numOpticalDepthPoints - 1);
float opticalDepth = 0;
for (int i = 0; i < numOpticalDepthPoints; i ++) {
float localDensity = densityAtPoint(densitySamplePoint);
opticalDepth += localDensity * stepSize;
densitySamplePoint += rayDir * stepSize;
}
return opticalDepth;
}
float calculateOutScattering(float2 inPoint, float2 outPoint) {
float planetRadius = 1;
float skinWidth = planetRadius / 1000.0;
float lightTravelDst = length(outPoint - inPoint);
float2 outScatterPoint = inPoint;
float2 rayDir = (outPoint - inPoint) / lightTravelDst;
float stepSize = (lightTravelDst - skinWidth) / (numOutScatteringSteps);
float outScatterAmount = 0;
for (int i = 0; i < numOutScatteringSteps; i ++) {
outScatterPoint += rayDir * stepSize;
// height at planet surface = 0, at furthest extent of atmosphere = 1
float height = length(outScatterPoint - 0) - planetRadius;//
float height01 = saturate(height / (atmosphereRadius - planetRadius));
outScatterAmount += exp(-height01 * densityFalloff) * stepSize;
}
return outScatterAmount;
}
[numthreads(8,8,1)]
void CSMain (uint2 id : SV_DispatchThreadID)
{
const float planetRadius = 1;
float2 uv = id / (float)textureSize;
float height01 = uv.y;
float angle = uv.x * PI;
//angle = (1-cos(angle))/2;
float2 dir = float2(sin(angle), cos(angle));
float y = -2 * uv.x + 1;
float x = sin(acos(y));
dir = float2(x,y);
float2 inPoint = float2(0, lerp(planetRadius, atmosphereRadius, height01));
float dstThroughAtmosphere = raySphere(0, atmosphereRadius, float3(inPoint,0), float3(dir,0)).y;
float2 outPoint = inPoint + dir * raySphere(0, atmosphereRadius, float3(inPoint,0), float3(dir,0)).y;
//float outScattering = calculateOutScattering(inPoint, outPoint);
float outScattering = opticalDepth(inPoint + dir * 0.0001, dir, dstThroughAtmosphere-0.0002);
Result[id.xy] = outScattering;
}

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 463adb4526f5a48bdb8c71df4c6dd88d
ComputeShaderImporter:
externalObjects: {}
currentAPIMask: 65536
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 44fb59fda0e1d49dda281e0401d4dc76
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,57 @@
#pragma kernel CSMain
#include "../../Includes/FractalNoise.cginc"
#include "../../Includes/Craters.cginc"
//
StructuredBuffer<float3> vertices;
RWStructuredBuffer<float> heights;
uint numVertices;
// Continent settings:
float oceanDepthMultiplier;
float oceanFloorDepth;
float oceanFloorSmoothing;
float mountainBlend;
// Old:
float4 noiseParams_continents[3];
float4 noiseParams_mask[3];
float4 noiseParams_mountains[3];
float4 noiseParams_warp[3];
float4 params;
[numthreads(512,1,1)]
void CSMain (uint id : SV_DispatchThreadID)
{
if (id >= numVertices) {
return;
}
float3 pos = vertices[id];
float3 warpNoise = float3(simpleNoise(pos, noiseParams_warp),simpleNoise(pos-100, noiseParams_warp),simpleNoise(pos+100, noiseParams_warp)) * 0.01;
float3 warpedPos = pos + warpNoise;
float craterDepth = calculateCraterDepth(pos);
float continentShape = simpleNoise(pos + warpNoise * params.x, noiseParams_continents);
continentShape = smoothMax(continentShape, -oceanFloorDepth, oceanFloorSmoothing);
if (continentShape < 0) {
continentShape *= 1 + oceanDepthMultiplier;
}
float ridgeNoise = smoothedRidgidNoise(pos + warpNoise * params.y, noiseParams_mountains);
float mask = Blend(0, mountainBlend, simpleNoise(pos + warpNoise * params.z, noiseParams_mask));
// Calculate final height
float finalHeight = 1 + continentShape * 0.01 + ridgeNoise * 0.01 * mask + craterDepth;
//finalHeight = 1 + Blend(0, params.x, simpleNoise(pos, noiseParams_mask)) * 0.05;
// Set terrain data
heights[id] = finalHeight;
}

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: b33d87d0482194cf2a21c78c2cc775f8
ComputeShaderImporter:
externalObjects: {}
currentAPIMask: 65536
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,51 @@
#pragma kernel CSMain
#include "../../Includes/FractalNoise.cginc"
#include "../../Includes/Math.cginc"
//
StructuredBuffer<float3> vertices;
RWStructuredBuffer<float> heights;
uint numVertices;
// Continent settings:
float oceanDepthMultiplier;
float oceanFloorDepth;
float oceanFloorSmoothing;
float mountainBlend;
float4 noiseParams_continents[3];
float4 noiseParams_mask[3];
float4 noiseParams_mountains[3];
float4 params;
[numthreads(512,1,1)]
void CSMain (uint id : SV_DispatchThreadID)
{
if (id >= numVertices) {
return;
}
float3 pos = vertices[id];
float continentShape = simpleNoise(pos, noiseParams_continents);
continentShape = smoothMax(continentShape, -oceanFloorDepth, oceanFloorSmoothing);
if (continentShape < 0) {
continentShape *= 1 + oceanDepthMultiplier;
}
float ridgeNoise = smoothedRidgidNoise(pos, noiseParams_mountains);
float mask = Blend(0, mountainBlend, simpleNoise(pos, noiseParams_mask));
// Calculate final height
float finalHeight = 1 + continentShape * 0.01 + ridgeNoise * 0.01 * mask;
//finalHeight = 1 + Blend(0, params.x, simpleNoise(pos, noiseParams_mask)) * 0.05;
// Set terrain data
heights[id] = finalHeight;
}

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d6df9e6cc324e48a892dd6a9cf741d65
ComputeShaderImporter:
externalObjects: {}
currentAPIMask: 65536
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,69 @@
#pragma kernel CSMain
#include "../../Includes/FractalNoise.cginc"
#include "../../Includes/Craters.cginc"
//
StructuredBuffer<float3> vertices;
RWStructuredBuffer<float> heights;
uint numVertices;
// Continent settings:
float shoreSteepness;
float continentFlatness;
float continentLevel;
float2 maskMinMax;
float mountainBlend;
float4 noiseParams_continents[3];//
float4 noiseParams_mask[3];
// Ridge noise
float4 noiseParams_mountains[3];
float4 params;
float mountainSmoothing;
float calculateMountainNoise(float3 pos) {
float3 sphereNormal = pos;
float3 axisA = cross(sphereNormal, float3(0,1,0));
float3 axisB = cross(sphereNormal, axisA);
// Sample the noise several times at small offsets from the centre and average the result
// This reduces some of the harsh jaggedness that can occur
float offsetDst = mountainSmoothing * 0.01;
float sample0 = ridgidNoise(pos, noiseParams_mountains);
float sample1 = ridgidNoise(pos - axisA * offsetDst, noiseParams_mountains);
float sample2 = ridgidNoise(pos + axisA * offsetDst, noiseParams_mountains);
float sample3 = ridgidNoise(pos - axisB * offsetDst, noiseParams_mountains);
float sample4 = ridgidNoise(pos + axisB * offsetDst, noiseParams_mountains);
return (sample0 + sample1 + sample2 + sample3 + sample4) / 5;
}
[numthreads(512,1,1)]
void CSMain (uint id : SV_DispatchThreadID)
{
if (id >= numVertices) {
return;
}
float3 pos = vertices[id];
float continentShape = simpleNoise(pos, noiseParams_continents);
continentShape = continentShape * (1 + continentShape / continentLevel * shoreSteepness);
if (continentShape < 0) {
continentShape *= 1+mountainSmoothing * abs(continentShape);
}
float craterDepth = calculateCraterDepth(pos);
//float heightAboveShore = max(0, continentShape);
//float k = (1 - saturate(heightAboveShore / continentLevel)) * shoreSteepness;
// continentShape = smoothMin(continentShape, 0, shoreSteepness);
// Calculate final height
float finalHeight = 1 + continentShape * 0.01 + craterDepth;
// Set terrain data
heights[id] = finalHeight;
}

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: e32322f519a614092915aa9cbc4cb7c2
ComputeShaderImporter:
externalObjects: {}
currentAPIMask: 65536
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,41 @@
#pragma kernel CSMain
#include "../../Includes/Craters.cginc"
#include "../../Includes/FractalNoise.cginc"
//
StructuredBuffer<float3> vertices;
RWStructuredBuffer<float> heights;
uint numVertices;
float4 testParams;
// Noise settings
float4 noiseParams_shape[3];
float4 noiseParams_ridge[3];
float4 noiseParams_ridge2[3];
[numthreads(512, 1, 1)]
void CSMain (uint id : SV_DispatchThreadID)
{
if (id >= numVertices) { return; }
static const float elevationMultiplier = 0.01;
float3 pos = vertices[id];
// Craters
float craterDepth = calculateCraterDepth(pos);
// Low-frequency noise to add some slight deformation to the base sphere shape of the moon
float shapeNoise = simpleNoise(pos, noiseParams_shape);
// Ridge noise
float ridgeNoise = smoothedRidgidNoise(pos, noiseParams_ridge);
float ridge2 = smoothedRidgidNoise(pos, noiseParams_ridge2);
float noiseSum = (shapeNoise + ridgeNoise + ridge2) * elevationMultiplier;
float finalHeight = 1 + craterDepth + noiseSum;
heights[id] = finalHeight;
// Debug ridge mask
//terrainHeights[id] = 1 + ridgeMask * .1;
//terrainHeights[id] = 1 + ridgeNoise * elevationMultiplier;
}

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 1c8bff6c5dfd7461f8403bd2cef35625
ComputeShaderImporter:
externalObjects: {}
currentAPIMask: 65536
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,44 @@
#pragma kernel CSMain
#include "../../Includes/FractalNoise.cginc"
#include "../../Includes/Craters.cginc"
//
StructuredBuffer<float3> vertices;
RWStructuredBuffer<float> heights;
uint numVertices;
float plateauHeight;
float plateauSmoothing;
float4 noiseParams_continents[3];
float4 noiseParams_mountains[3];
float4 noiseParams_mountains2[3];
float4 noiseParams_warp[3];
float4 params;
[numthreads(512,1,1)]
void CSMain (uint id : SV_DispatchThreadID)
{
if (id >= numVertices) {
return;
}
float3 pos = vertices[id];
float3 warpNoise = float3(simpleNoise(pos, noiseParams_warp),simpleNoise(pos-100, noiseParams_warp),simpleNoise(pos+100, noiseParams_warp)) * 0.01;
float craterDepth = calculateCraterDepth(pos);
float continentShape = simpleNoise(pos + warpNoise, noiseParams_continents);
continentShape = smoothMin(continentShape, plateauHeight, plateauSmoothing);
float ridgeNoise = smoothedRidgidNoise(pos, noiseParams_mountains);
float ridgeNoise2 = smoothedRidgidNoise(pos, noiseParams_mountains2); //
// Calculate final height
float finalHeight = 1 + (continentShape + ridgeNoise + ridgeNoise2) * 0.01 + craterDepth;
//finalHeight = 1 + Blend(0, params.x, simpleNoise(pos, noiseParams_mask)) * 0.05;
// Set terrain data
heights[id] = finalHeight;
}

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 13008f929df404f2c9c4d64443449aed
ComputeShaderImporter:
externalObjects: {}
currentAPIMask: 65536
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: caff2a8a0d5b640a9a75ebb6a10c3fa8
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,69 @@
Shader "Hidden/OceanMask"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
Cull Off ZWrite Off ZTest Always
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
#include "../../Includes/Math.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
float3 viewVector : TEXCOORD1;
};
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
// Camera space matches OpenGL convention where cam forward is -z. In unity forward is positive z.
// (https://docs.unity3d.com/ScriptReference/Camera-cameraToWorldMatrix.html)
float3 viewVector = mul(unity_CameraInvProjection, float4(v.uv.xy * 2 - 1, 0, -1));
o.viewVector = mul(unity_CameraToWorld, float4(viewVector,0));
return o;
}
sampler2D _MainTex;
static const int maxNumSpheres = 10;
float4 spheres[maxNumSpheres];
int numSpheres;
fixed4 frag (v2f i) : SV_Target
{
float3 rayOrigin = _WorldSpaceCameraPos;
float3 rayDir = normalize(i.viewVector);
//return float4(rayDir,1);
float nearest = 0;
for (int sphereIndex = 0; sphereIndex < numSpheres; sphereIndex ++) {
float2 hitInfo = raySphere(spheres[sphereIndex].xyz, spheres[sphereIndex].w, rayOrigin, rayDir);
if (hitInfo.y > 0) {
return 1;
}
}
return 0;
}
ENDCG
}
}
}

View file

@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 5c954f4bd730d46199b888d542aded55
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,33 @@
#pragma kernel CSMain
#include "../../Includes/FractalNoise.cginc"
RWStructuredBuffer<float3> points;
uint numPoints;
float maxStrength;
float3 perturb(float3 pos) {
float scale = 50;
float fx = simpleNoise(pos * 1, 2, scale, .5, 2, 1);
float fy = simpleNoise(pos * 2, 2, scale, .5, 2, 1);
float fz = simpleNoise(pos * 3, 2, scale, .5, 2, 1);
float3 offset = float3(fx, fy, fz);
offset = smoothstep(-1,1,offset) * 2 -1;
return offset;
}
[numthreads(512,1,1)]
void CSMain (uint id : SV_DispatchThreadID)
{
if (id >= numPoints) {
return;
}
float3 pos = points[id];
float height = length(pos);
float3 offset = perturb(pos);
float3 newPos = pos + offset * maxStrength;
newPos = normalize(newPos) * height;
points[id] = newPos;
}

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: c95c667630d66481daf208e2a7a4d95d
ComputeShaderImporter:
externalObjects: {}
currentAPIMask: 65536
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,29 @@
#pragma kernel CSMain
#include "../../Includes/FractalNoise.cginc"
RWStructuredBuffer<float3> points;
uint numPoints;
float maxStrength;
float3 perturb(float3 pos) {
float3 noise = fractalNoiseGrad(pos, 4, 25, .5, 2).xyz;
noise = smoothstep(-1,1,noise) * 2 -1;
return noise;
}
[numthreads(512,1,1)]
void CSMain (uint id : SV_DispatchThreadID)
{
if (id >= numPoints) {
return;
}
float3 pos = points[id];
float height = length(pos);
float3 offset = perturb(pos);
float3 newPos = pos + offset * maxStrength;
newPos = normalize(newPos) * height;
points[id] = newPos;
}

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 0cc4782d709194aa5a22ed5e9ab8bf09
ComputeShaderImporter:
externalObjects: {}
currentAPIMask: 65536
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,25 @@
#pragma kernel CSMain
StructuredBuffer<float3> vertices;
StructuredBuffer<int> triangles;
RWStructuredBuffer<float> steepness;
int numTriangles;
[numthreads(256,1,1)]
void CSMain (uint id : SV_DispatchThreadID)
{
if ((int)id >= numTriangles) {
return;
}
int triangleIndex = id * 3;
float3 a = vertices[triangles[triangleIndex]];
float3 b = vertices[triangles[triangleIndex+1]];
float3 c = vertices[triangles[triangleIndex+2]];
float3 faceNormal = normalize(cross(a-b, a-c));
float3 sphereNormal = normalize((a+b+c)/3);
steepness[id] = 1 - dot(faceNormal, sphereNormal);
}

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: b65c4a31f112141149dfdfb7d00a93f2
ComputeShaderImporter:
externalObjects: {}
currentAPIMask: 65536
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 1b6ba54c403c749d3935a2e0e7a34e83
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,46 @@
#pragma kernel CSMain
#include "../../Includes/FractalNoise.cginc"
#include "../../Includes/Math.cginc"
StructuredBuffer<float3> vertices;
RWStructuredBuffer<float4> shadingData;
uint numVertices;
// Noise settings
float4 noiseParams_detailWarp[3];
float4 noiseParams_detail[3];
float4 noiseParams_large[3];
float4 noiseParams_small[3];
// Second warp
float4 noiseParams_warp2[3];
float4 noiseParams_noise2[3];
[numthreads(512, 1, 1)]
void CSMain (uint id : SV_DispatchThreadID)
{
if (id >= numVertices) { return; }
float3 pos = vertices[id];
// Large, low frequency noise
float largeNoise = simpleNoise(pos, noiseParams_large);
float smallNoise = simpleNoise(pos, noiseParams_small);
// Warped detail noise
float detailWarp = simpleNoise(pos, noiseParams_detailWarp);
float detailNoise = simpleNoise(pos + detailWarp * 0.1, noiseParams_detail);
// Second warp noise
float3 warpOffset2;
warpOffset2.x = simpleNoise(pos, noiseParams_warp2);
warpOffset2.y = simpleNoise(pos + 99999, noiseParams_warp2);
warpOffset2.z = simpleNoise(pos - 99999, noiseParams_warp2);
float warpedNoise2 = simpleNoise(pos + warpOffset2 * 0.1, noiseParams_noise2);
shadingData[id] = float4(largeNoise, detailNoise, smallNoise, warpedNoise2);
}

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: f3a2904f78271471481822700022a157
ComputeShaderImporter:
externalObjects: {}
currentAPIMask: 65536
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,87 @@
#pragma kernel CSMain
#include "../../Includes/FractalNoise.cginc"
#include "../../Includes/Math.cginc"
//
StructuredBuffer<float3> vertices;
RWStructuredBuffer<float4> shadingData;
uint numVertices;
StructuredBuffer<float4> points;
int numRandomPoints;
float4 noiseParams_biomeWarp[3];
float4 noiseParams_detailWarp[3];
float4 noiseParams_detail[3];
float4 params;
StructuredBuffer<float4> ejectaCraters;
int numEjectaCraters;
float calcSphereNoise(float3 pos) {
float sphereNoise = 1.#INF;
for (int i = 0; i < numRandomPoints; i ++) {
float3 sphereCentre = points[i].xyz;
float sphereRadius = points[i].w;
float dst = length(pos - sphereCentre);
float t = dst / sphereRadius;
sphereNoise = min(sphereNoise, t);
}
return sphereNoise;
}
[numthreads(512,1,1)]
void CSMain (uint id : SV_DispatchThreadID)
{
if (id >= numVertices) { return; }
float3 pos = vertices[id];
float3 domainWarp = 0;
domainWarp.x = simpleNoise(pos, noiseParams_biomeWarp);
domainWarp.y = simpleNoise(pos + 100, noiseParams_biomeWarp);
domainWarp.z = simpleNoise(pos - 100, noiseParams_biomeWarp);
float3 detailWarp = 0;
detailWarp.x = simpleNoise(pos, noiseParams_detailWarp);
detailWarp.y = simpleNoise(pos + 100, noiseParams_detailWarp);
detailWarp.z = simpleNoise(pos - 100, noiseParams_detailWarp);
float domainWarp2 = simpleNoise(pos, noiseParams_detailWarp);
// Sphere noise
float3 warpedPos = pos + (domainWarp) * 0.1;
float sphereNoise = calcSphereNoise(warpedPos);
float detailNoise = simpleNoise(pos + domainWarp2 * 0.1, noiseParams_detail);
// Calculate uv coords for crater 'ejecta ray' texture to be projected onto the surface around select craters
float2 ejectaUV = 1;
float minDst = 999;
for (int craterIndex = 0; craterIndex < numEjectaCraters; craterIndex ++) {
float3 craterCentre = ejectaCraters[craterIndex].xyz;
float dst = length(craterCentre - pos);
float scaledDst = dst / ejectaCraters[craterIndex].w;
if (scaledDst < minDst) {
minDst = scaledDst;
float3 craterUp = craterCentre;
float3 craterForward = normalize(cross(craterUp, float3(0,1,0)));
float3 forward = normalize(cross(pos, craterUp));
float cross_x = forward.y * craterForward.z - forward.z * craterForward.y;
float cross_y = forward.z * craterForward.x - forward.x * craterForward.z;
float cross_z = forward.x * craterForward.y - forward.y * craterForward.x;
float angleSign = sign(craterUp.x * cross_x + craterUp.y * cross_y + craterUp.z * cross_z);
float angle = acos(dot(craterForward, forward)) * angleSign;
//float estBiomeVal = Blend(7 * 0.8, 0.8, calcSphereNoise(craterCentre));
//float biomeSign = (estBiomeVal < 0.5)?-1:1;
ejectaUV = float2 (angle, scaledDst);
}
}
shadingData[id] = float4(ejectaUV.xy, detailNoise, sphereNoise);
}

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 8f6c3d86008df43ca88b9d64cf8e0514
ComputeShaderImporter:
externalObjects: {}
currentAPIMask: 65536
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 717e98688348e475da7adb47d0d1c7ec
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,37 @@
#pragma kernel CSMain
Texture2D<float4> SourceTex;
RWTexture2D<float4> Result;
uint textureSize;
int blurSize;
uint2 Wrap(int x, int y) {
x = (x < 0) ? textureSize + x : x;
x = (x >= (int)textureSize) ? x - textureSize : x;
y = (y < 0) ? textureSize + y : y;
y = (y >= (int)textureSize) ? y - textureSize : y;
return uint2(x, y);
}
[numthreads(8,8,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
if (id.x >= textureSize || id.y >= textureSize) {
return;
}
float4 sum = 0;
for (int offsetX = -blurSize; offsetX <= blurSize; offsetX ++) {
for (int offsetY = -blurSize; offsetY <= blurSize; offsetY ++) {
uint2 sampleCoord = Wrap(id.x + offsetX, id.y + offsetY);
float4 sample = SourceTex[sampleCoord];
sum += sample;
}
}
int numSamples = (blurSize * 2 + 1) * (blurSize * 2 + 1);
float4 result = sum / numSamples;
Result[id.xy] = result;
}

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 3bbb70231abe74a25b57d54568b663d9
ComputeShaderImporter:
externalObjects: {}
currentAPIMask: 65536
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,49 @@
// Each #kernel tells which function to compile; you can have many kernels
#pragma kernel CSMain
#include "../../Includes/Math.cginc"
//
// Create a RenderTexture with enableRandomWrite flag and set it
// with cs.SetTexture
RWTexture2D<float4> Result;
StructuredBuffer<float4> spots;
uint resolution;
int numSpots;
float background;
float4 params;
float smoothing;
[numthreads(8,8,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
if (id.x >= resolution || id.y >= resolution) {
return;
}
float2 pos = id.xy / (float)resolution;
float alpha = 0;
float minDst = 999;
for (int i = 0; i < numSpots; i ++) {
float4 spot = spots[i];
float r = spot.z;
float dst = length(spot.xy - pos);
float minDstOld = minDst;
// minDst = smoothMin(dst, minDst, smoothing * 0.001);
if ( dst <= r) {
//alpha = max(alpha, spot.w);
//float v = 1-dst/r;
//alpha += v*v*spot.w;
alpha = max(alpha,spot.w);
}
}
alpha = 1-saturate(background + alpha);
Result[id.xy] = float4(alpha, alpha, alpha, 1);//
}

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: a06a7dddd79684a96a2169e2128e5f88
ComputeShaderImporter:
externalObjects: {}
currentAPIMask: 65536
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,101 @@
#pragma kernel CSMain
#pragma kernel Normalize
#include "../../Includes/SimplexNoise3.cginc"
static const int minMaxAccuracy = 1000000;
RWTexture2D<float4> Result;
uint resolution;
RWStructuredBuffer<int> minMax;
float4 noiseParams_simple[3];
float4 noiseParams_warp[3];
float valueFloor;
float4 params;
// Remap a value (with a known mininum and maximum) to a value between 0 and 1
float remap01(float v, float minOld, float maxOld) {
return saturate((v-minOld) / (maxOld-minOld));
}
//
float tilingNoise(float2 pos, float4 noiseParams[3], float warp) {
static const int x1 =-1, y1=-1, x2=1, y2=1;
static const float dx = x2 - x1;
static const float dy = y2 - y1;
static const float tau = 3.14159265359 * 2;
// Params
float3 offset = warp;
float3 offset3d = noiseParams[0].xyz;//
int numLayers = int(noiseParams[0].w);
float persistence = noiseParams[1].x;
float lacunarity = noiseParams[1].y;
float scale = noiseParams[1].z;
float multiplier = noiseParams[1].w;
// web.archive.org/web/20160304043608/https://www.gamedev.net/blog/33/entry-2138456-seamless-noise/
float nx = x1 + cos(pos.x * tau) * dx;
float ny = y1 + cos(pos.y * tau) * dy;
float nz = x1 + sin(pos.x * tau) * dx;
float nw = y1 + sin (pos.y * tau) * dy;
float4 pos4D = float4(nx, ny, nz, nw) / tau;
float4 dir = normalize(pos4D);
pos4D += dir * 0.1 * params.x;
//pos4D += snoise(pos4D * params.w * 0.001);
float noise = 0;
float amplitude = 1;
float frequency = scale;
for (int i = 0; i < numLayers; i ++) {
float layerVal = snoise((pos4D + warp) * frequency);//
//layerVal = 1-abs(layerVal);
//layerVal *= layerVal;
noise += layerVal * amplitude;
amplitude *= persistence;
frequency *= lacunarity;
}
return noise * multiplier;
}
[numthreads(8,8,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
if (id.x >= resolution || id.y >= resolution) {
return;
}
float2 pos = id.xy/(float)resolution;
float warpNoise = tilingNoise(pos, noiseParams_warp, 0) * 0.1;
float noise = tilingNoise(pos, noiseParams_simple, warpNoise);
// keep inside range [0,1] as will be clamped in texture
float approxMax = 2;
noise = saturate((noise + approxMax * 0.5) / approxMax);
Result[id.xy] = noise;
// keep track of min max (using int to support atomic operation)
int val = (int)(noise * minMaxAccuracy);
InterlockedMin(minMax[0],val);
InterlockedMax(minMax[1],val);
}
[numthreads(8,8,1)]
void Normalize (uint3 id : SV_DispatchThreadID)
{
if (id.x >= resolution || id.y >= resolution) {
return;
}
float minVal = (float)minMax[0]/minMaxAccuracy;
float maxVal = (float)minMax[1]/minMaxAccuracy;
float4 normalizedValue = (Result[id.xy]-minVal)/(maxVal-minVal);
Result[id.xy] = normalizedValue;
}

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 2821ce0c209074cf9bb487300949b8f6
ComputeShaderImporter:
externalObjects: {}
currentAPIMask: 65536
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 2690ae45068734fcb83c3197e2a33975
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,33 @@
#include "/Math.cginc"
struct Crater {
float3 centre;
float radius;
float floor;
float smoothness;
};
// Crater data and settings
StructuredBuffer<Crater> craters;
int numCraters;
float floorHeight;
float rimSteepness;
float rimWidth;
float smoothFactor;
float calculateCraterDepth(float3 vertexPos) {
float craterHeight = 0;
for (int i = 0; i < numCraters; i ++) {
float x = length(vertexPos - craters[i].centre) / max(craters[i].radius, 0.0001);
float cavity = x * x - 1;
float rimX = min(x - 1 - rimWidth, 0);
float rim = rimSteepness * rimX * rimX;
float craterShape = smoothMax(cavity, craters[i].floor, craters[i].smoothness);
craterShape = smoothMin(craterShape, rim, craters[i].smoothness);
craterHeight += craterShape * craters[i].radius;
}
return craterHeight;
}

View file

@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: de61f86c990f74bca9aff6a6c95ce22d
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,258 @@
#include "/SimplexNoise.cginc"
float simpleNoise(float3 pos, int numLayers, float scale, float persistence, float lacunarity, float multiplier) {
float noiseSum = 0;
float amplitude = 1;
float frequency = scale;
for (int i = 0; i < numLayers; i ++) {
noiseSum += snoise(pos * frequency) * amplitude;
amplitude *= persistence;
frequency *= lacunarity;
}
return noiseSum * multiplier;
}
float simpleNoise(float3 pos, float scale, float multiplier) {
const int numLayers = 4;
const float persistence = .5;
const float lacunarity = 2;
return simpleNoise(pos, numLayers, scale, persistence, lacunarity, multiplier);
}
float simpleNoise(float3 pos) {
const float scale = 1;
const float multiplier = 1;
return simpleNoise(pos, scale, multiplier);
}
float simpleNoise(float3 pos, float4 params[3]) {
// Extract parameters for readability
float3 offset = params[0].xyz;
int numLayers = int(params[0].w);
float persistence = params[1].x;
float lacunarity = params[1].y;
float scale = params[1].z;
float multiplier = params[1].w;
float verticalShift = params[2].x;
// Sum up noise layers
float noiseSum = 0;
float amplitude = 1;
float frequency = scale;
for (int i = 0; i < numLayers; i ++) {
noiseSum += snoise(pos * frequency + offset) * amplitude;
amplitude *= persistence;
frequency *= lacunarity;
}
return noiseSum * multiplier + verticalShift;
}
// Simple noise, but with smaller values dampened
float dampenedSimpleNoise(float3 pos, float4 params[3]) {
// Parameters
float3 offset = params[0].xyz;
int numLayers = int(params[0].w);
float persistence = params[1].x;
float lacunarity = params[1].y;
float scale = params[1].z;
float multiplier = params[1].w;
float gain = 1.2;
// Sum up noise layers
float noiseSum = 0;
float amplitude = 1;
float frequency = scale;
float weight = 1;
for (int i = 0; i < numLayers; i ++) {
float noiseVal = snoise(pos * frequency + offset) * .5 + .5;
noiseVal *= weight;
weight = saturate(noiseVal * gain);
noiseSum += noiseVal * amplitude;
amplitude *= persistence;
frequency *= lacunarity;
}
return noiseSum * multiplier;
}
// Noise very roughly in range 0-1
float continentNoise(float3 pos, float4 params[3]) {
// Parameters
float3 offset = params[0].xyz;
int numLayers = int(params[0].w);
float persistence = params[1].x;
float lacunarity = params[1].y;
float scale = params[1].z;
float multiplier = params[1].w;
float gain = 1;
// Sum up noise layers
float noiseSum = 0;
float amplitude = 1;
float frequency = scale;
float weight = 1;
for (int i = 0; i < numLayers; i ++) {
float noiseVal = snoise(pos * frequency + offset) * .5 + .5;
noiseVal *= weight;
weight = saturate(noiseVal * gain);
noiseSum += noiseVal * amplitude;
amplitude *= persistence;
frequency *= lacunarity;
}
return noiseSum;
}
float simpleNoise2(float3 pos, float4 params[3]) {
// Parameters
float3 offset = params[0].xyz;
int numLayers = int(params[0].w);
float persistence = params[1].x;
float lacunarity = params[1].y;
float scale = params[1].z;
float multiplier = params[1].w;
// Sum up noise layers
float noiseSum = 0;
float amplitude = 1;
float frequency = scale;
for (int i = 0; i < numLayers; i ++) {
float noiseVal = snoise(pos * frequency + offset);
noiseSum += (noiseVal+1)*.5 * amplitude;
amplitude *= persistence;
frequency *= lacunarity;
}
return noiseSum;
}
float simpleNoiseMusgrave(float3 pos, float4 params[3], float o) {
// Parameters
float3 offset = params[0].xyz;
int numLayers = int(params[0].w);
float persistence = params[1].x;
float lacunarity = params[1].y;
float scale = params[1].z;
float multiplier = params[1].w;
// first octave
float result = snoise(pos) + o;
pos *= lacunarity;
// Sum up noise layers
float amplitude = 1;
float frequency = scale * lacunarity;
float weight = result;
for (int i = 1; i < numLayers; i ++) {
weight = min(1, weight);
float signal = (snoise(pos * frequency) + o) * pow (abs(frequency), -persistence);
result += weight * signal;
weight *= signal;
//amplitude *= persistence;
frequency *= lacunarity;
pos *= lacunarity;
}
return result * multiplier;
}
float ridgidNoise(float3 pos, float4 params[3]) {
// Extract parameters for readability
float3 offset = params[0].xyz;
int numLayers = int(params[0].w);
float persistence = params[1].x;
float lacunarity = params[1].y;
float scale = params[1].z;
float multiplier = params[1].w;
float power = params[2].x;
float gain = params[2].y;
float verticalShift = params[2].z;
// Sum up noise layers
float noiseSum = 0;
float amplitude = 1;
float frequency = scale;
float ridgeWeight = 1;
for (int i = 0; i < numLayers; i ++) {
float noiseVal = 1 - abs(snoise(pos * frequency + offset));
noiseVal = pow(abs(noiseVal), power);
noiseVal *= ridgeWeight;
ridgeWeight = saturate(noiseVal * gain);
noiseSum += noiseVal * amplitude;
amplitude *= persistence;
frequency *= lacunarity;
}
return noiseSum * multiplier + verticalShift;
}
// Sample the noise several times at small offsets from the centre and average the result
// This reduces some of the harsh jaggedness that can occur
float smoothedRidgidNoise(float3 pos, float4 params[3]) {
float3 sphereNormal = normalize(pos);
float3 axisA = cross(sphereNormal, float3(0,1,0));
float3 axisB = cross(sphereNormal, axisA);
float offsetDst = params[2].w * 0.01;
float sample0 = ridgidNoise(pos, params);
float sample1 = ridgidNoise(pos - axisA * offsetDst, params);
float sample2 = ridgidNoise(pos + axisA * offsetDst, params);
float sample3 = ridgidNoise(pos - axisB * offsetDst, params);
float sample4 = ridgidNoise(pos + axisB * offsetDst, params);
return (sample0 + sample1 + sample2 + sample3 + sample4) / 5;
}
float ridgidNoise2(float3 pos, float4 params[3]) {
// Parameters
float3 offset = params[0].xyz;
int numLayers = int(params[0].w);
float persistence = params[1].x;
float lacunarity = params[1].y;
float scale = params[1].z;
float multiplier = params[1].w;
float power = params[2].x;
// Sum up noise layers
float noiseSum = 0;
float amplitude = 1;
float frequency = scale;
float ridgeWeight = 1;
for (int i = 0; i < numLayers; i ++) {
float noiseVal = 1 - abs(snoise(pos * frequency + offset));
noiseVal = (noiseVal * .5 + .5);
noiseVal *= ridgeWeight;
ridgeWeight = saturate(noiseVal);
noiseSum += noiseVal * amplitude;
amplitude *= persistence;
frequency *= lacunarity;
}
noiseSum = 1 - abs(noiseSum*2-1);
noiseSum = pow(abs(noiseSum), power);
return noiseSum * multiplier;
}
float4 fractalNoiseGrad(float3 pos, int numLayers, float scale, float persistence, float lacunarity) {
float4 noise = 0;
float amplitude = 1;
float frequency = scale;
for (int i = 0; i < numLayers; i ++) {
noise += snoise_grad(pos * frequency) * amplitude;
amplitude *= persistence;
frequency *= lacunarity;
}
return noise;
}

View file

@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 7a4d381262f094ec1ba9b87c715a7ae9
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,73 @@
static const float PI = 3.14159265359;
static const float TAU = PI * 2;
static const float maxFloat = 3.402823466e+38;
// Remap a value from one range to another
float remap(float v, float minOld, float maxOld, float minNew, float maxNew) {
return saturate(minNew + (v-minOld) * (maxNew - minNew) / (maxOld-minOld));
}
// Remap the components of a vector from one range to another
float4 remap(float4 v, float minOld, float maxOld, float minNew, float maxNew) {
return saturate(minNew + (v-minOld) * (maxNew - minNew) / (maxOld-minOld));//
}
// Remap a float value (with a known mininum and maximum) to a value between 0 and 1
float remap01(float v, float minOld, float maxOld) {
return saturate((v-minOld) / (maxOld-minOld));
}
// Remap a float2 value (with a known mininum and maximum) to a value between 0 and 1
float2 remap01(float2 v, float2 minOld, float2 maxOld) {
return saturate((v-minOld) / (maxOld-minOld));
}
// Smooth minimum of two values, controlled by smoothing factor k
// When k = 0, this behaves identically to min(a, b)
float smoothMin(float a, float b, float k) {
k = max(0, k);
// https://www.iquilezles.org/www/articles/smin/smin.htm
float h = max(0, min(1, (b - a + k) / (2 * k)));
return a * h + b * (1 - h) - k * h * (1 - h);
}
// Smooth maximum of two values, controlled by smoothing factor k
// When k = 0, this behaves identically to max(a, b)
float smoothMax(float a, float b, float k) {
k = min(0, -k);
float h = max(0, min(1, (b - a + k) / (2 * k)));
return a * h + b * (1 - h) - k * h * (1 - h);
}
float Blend(float startHeight, float blendDst, float height) {
return smoothstep(startHeight - blendDst / 2, startHeight + blendDst / 2, height);
}
// Returns vector (dstToSphere, dstThroughSphere)
// If ray origin is inside sphere, dstToSphere = 0
// If ray misses sphere, dstToSphere = maxValue; dstThroughSphere = 0
float2 raySphere(float3 sphereCentre, float sphereRadius, float3 rayOrigin, float3 rayDir) {
float3 offset = rayOrigin - sphereCentre;
float a = 1; // Set to dot(rayDir, rayDir) if rayDir might not be normalized
float b = 2 * dot(offset, rayDir);
float c = dot (offset, offset) - sphereRadius * sphereRadius;
float d = b * b - 4 * a * c; // Discriminant from quadratic formula
// Number of intersections: 0 when d < 0; 1 when d = 0; 2 when d > 0
if (d > 0) {
float s = sqrt(d);
float dstToSphereNear = max(0, (-b - s) / (2 * a));
float dstToSphereFar = (-b + s) / (2 * a);
// Ignore intersections that occur behind the ray
if (dstToSphereFar >= 0) {
return float2(dstToSphereNear, dstToSphereFar - dstToSphereNear);
}
}
// Ray did not intersect sphere
return float2(maxFloat, 0);
}

View file

@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 8dc954e584876428396a17a9271bc3f1
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,191 @@
// Noise Shader Library for Unity - https://github.com/keijiro/NoiseShader
//
// Original work (webgl-noise) Copyright (C) 2011 Ashima Arts.
// Translation and modification was made by Keijiro Takahashi.
//
// This shader is based on the webgl-noise GLSL shader. For further details
// of the original shader, please see the following description from the
// original source code.
//
//
// Description : Array and textureless GLSL 2D/3D/4D simplex
// noise functions.
// Author : Ian McEwan, Ashima Arts.
// Maintainer : ijm
// Lastmod : 20110822 (ijm)
// License : Copyright (C) 2011 Ashima Arts. All rights reserved.
// Distributed under the MIT License. See LICENSE file.
// https://github.com/ashima/webgl-noise
//
float3 mod289(float3 x)
{
return x - floor(x / 289.0) * 289.0;
}
float4 mod289(float4 x)
{
return x - floor(x / 289.0) * 289.0;
}
float4 permute(float4 x)
{
return mod289((x * 34.0 + 1.0) * x);
}
float4 taylorInvSqrt(float4 r)
{
return 1.79284291400159 - r * 0.85373472095314;
}
float snoise(float3 v)
{
const float2 C = float2(1.0 / 6.0, 1.0 / 3.0);
// First corner
float3 i = floor(v + dot(v, C.yyy));
float3 x0 = v - i + dot(i, C.xxx);
// Other corners
float3 g = step(x0.yzx, x0.xyz);
float3 l = 1.0 - g;
float3 i1 = min(g.xyz, l.zxy);
float3 i2 = max(g.xyz, l.zxy);
// x1 = x0 - i1 + 1.0 * C.xxx;
// x2 = x0 - i2 + 2.0 * C.xxx;
// x3 = x0 - 1.0 + 3.0 * C.xxx;
float3 x1 = x0 - i1 + C.xxx;
float3 x2 = x0 - i2 + C.yyy;
float3 x3 = x0 - 0.5;
// Permutations
i = mod289(i); // Avoid truncation effects in permutation
float4 p =
permute(permute(permute(i.z + float4(0.0, i1.z, i2.z, 1.0))
+ i.y + float4(0.0, i1.y, i2.y, 1.0))
+ i.x + float4(0.0, i1.x, i2.x, 1.0));
// Gradients: 7x7 points over a square, mapped onto an octahedron.
// The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294)
float4 j = p - 49.0 * floor(p / 49.0); // mod(p,7*7)
float4 x_ = floor(j / 7.0);
float4 y_ = floor(j - 7.0 * x_); // mod(j,N)
float4 x = (x_ * 2.0 + 0.5) / 7.0 - 1.0;
float4 y = (y_ * 2.0 + 0.5) / 7.0 - 1.0;
float4 h = 1.0 - abs(x) - abs(y);
float4 b0 = float4(x.xy, y.xy);
float4 b1 = float4(x.zw, y.zw);
//float4 s0 = float4(lessThan(b0, 0.0)) * 2.0 - 1.0;
//float4 s1 = float4(lessThan(b1, 0.0)) * 2.0 - 1.0;
float4 s0 = floor(b0) * 2.0 + 1.0;
float4 s1 = floor(b1) * 2.0 + 1.0;
float4 sh = -step(h, 0.0);
float4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;
float4 a1 = b1.xzyw + s1.xzyw * sh.zzww;
float3 g0 = float3(a0.xy, h.x);
float3 g1 = float3(a0.zw, h.y);
float3 g2 = float3(a1.xy, h.z);
float3 g3 = float3(a1.zw, h.w);
// Normalise gradients
float4 norm = taylorInvSqrt(float4(dot(g0, g0), dot(g1, g1), dot(g2, g2), dot(g3, g3)));
g0 *= norm.x;
g1 *= norm.y;
g2 *= norm.z;
g3 *= norm.w;
// Mix final noise value
float4 m = max(0.6 - float4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0);
m = m * m;
m = m * m;
float4 px = float4(dot(x0, g0), dot(x1, g1), dot(x2, g2), dot(x3, g3));
return 42.0 * dot(m, px);
}
float4 snoise_grad(float3 v)
{
const float2 C = float2(1.0 / 6.0, 1.0 / 3.0);
// First corner
float3 i = floor(v + dot(v, C.yyy));
float3 x0 = v - i + dot(i, C.xxx);
// Other corners
float3 g = step(x0.yzx, x0.xyz);
float3 l = 1.0 - g;
float3 i1 = min(g.xyz, l.zxy);
float3 i2 = max(g.xyz, l.zxy);
// x1 = x0 - i1 + 1.0 * C.xxx;
// x2 = x0 - i2 + 2.0 * C.xxx;
// x3 = x0 - 1.0 + 3.0 * C.xxx;
float3 x1 = x0 - i1 + C.xxx;
float3 x2 = x0 - i2 + C.yyy;
float3 x3 = x0 - 0.5;
// Permutations
i = mod289(i); // Avoid truncation effects in permutation
float4 p =
permute(permute(permute(i.z + float4(0.0, i1.z, i2.z, 1.0))
+ i.y + float4(0.0, i1.y, i2.y, 1.0))
+ i.x + float4(0.0, i1.x, i2.x, 1.0));
// Gradients: 7x7 points over a square, mapped onto an octahedron.
// The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294)
float4 j = p - 49.0 * floor(p / 49.0); // mod(p,7*7)
float4 x_ = floor(j / 7.0);
float4 y_ = floor(j - 7.0 * x_); // mod(j,N)
float4 x = (x_ * 2.0 + 0.5) / 7.0 - 1.0;
float4 y = (y_ * 2.0 + 0.5) / 7.0 - 1.0;
float4 h = 1.0 - abs(x) - abs(y);
float4 b0 = float4(x.xy, y.xy);
float4 b1 = float4(x.zw, y.zw);
//float4 s0 = float4(lessThan(b0, 0.0)) * 2.0 - 1.0;
//float4 s1 = float4(lessThan(b1, 0.0)) * 2.0 - 1.0;
float4 s0 = floor(b0) * 2.0 + 1.0;
float4 s1 = floor(b1) * 2.0 + 1.0;
float4 sh = -step(h, 0.0);
float4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;
float4 a1 = b1.xzyw + s1.xzyw * sh.zzww;
float3 g0 = float3(a0.xy, h.x);
float3 g1 = float3(a0.zw, h.y);
float3 g2 = float3(a1.xy, h.z);
float3 g3 = float3(a1.zw, h.w);
// Normalise gradients
float4 norm = taylorInvSqrt(float4(dot(g0, g0), dot(g1, g1), dot(g2, g2), dot(g3, g3)));
g0 *= norm.x;
g1 *= norm.y;
g2 *= norm.z;
g3 *= norm.w;
// Compute noise and gradient at P
float4 m = max(0.6 - float4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0);
float4 m2 = m * m;
float4 m3 = m2 * m;
float4 m4 = m2 * m2;
float3 grad =
-6.0 * m3.x * x0 * dot(x0, g0) + m4.x * g0 +
-6.0 * m3.y * x1 * dot(x1, g1) + m4.y * g1 +
-6.0 * m3.z * x2 * dot(x2, g2) + m4.z * g2 +
-6.0 * m3.w * x3 * dot(x3, g3) + m4.w * g3;
float4 px = float4(dot(x0, g0), dot(x1, g1), dot(x2, g2), dot(x3, g3));
return 42.0 * float4(grad, dot(m4, px));
}

View file

@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 7ab50d4af95614b3c9e1f4b079a25ec7
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,440 @@
#ifndef NOISE_SIMPLEX_FUNC
#define NOISE_SIMPLEX_FUNC
/*
Description:
Array- and textureless CgFx/HLSL 2D, 3D and 4D simplex noise functions.
a.k.a. simplified and optimized Perlin noise.
The functions have very good performance
and no dependencies on external data.
2D - Very fast, very compact code.
3D - Fast, compact code.
4D - Reasonably fast, reasonably compact code.
------------------------------------------------------------------
Ported by:
Lex-DRL
I've ported the code from GLSL to CgFx/HLSL for Unity,
added a couple more optimisations (to speed it up even further)
and slightly reformatted the code to make it more readable.
Original GLSL functions:
https://github.com/ashima/webgl-noise
Credits from original glsl file are at the end of this cginc.
------------------------------------------------------------------
Usage:
float ns = snoise(v);
// v is any of: float2, float3, float4
Return type is float.
To generate 2 or more components of noise (colorful noise),
call these functions several times with different
constant offsets for the arguments.
E.g.:
float3 colorNs = float3(
snoise(v),
snoise(v + 17.0),
snoise(v - 43.0),
);
Remark about those offsets from the original author:
People have different opinions on whether these offsets should be integers
for the classic noise functions to match the spacing of the zeroes,
so we have left that for you to decide for yourself.
For most applications, the exact offsets don't really matter as long
as they are not too small or too close to the noise lattice period
(289 in this implementation).
*/
// 1 / 289
#define NOISE_SIMPLEX_1_DIV_289 0.00346020761245674740484429065744f
float mod289(float x) {
return x - floor(x * NOISE_SIMPLEX_1_DIV_289) * 289.0;
}
float2 mod289(float2 x) {
return x - floor(x * NOISE_SIMPLEX_1_DIV_289) * 289.0;
}
float3 mod289(float3 x) {
return x - floor(x * NOISE_SIMPLEX_1_DIV_289) * 289.0;
}
float4 mod289(float4 x) {
return x - floor(x * NOISE_SIMPLEX_1_DIV_289) * 289.0;
}
// ( x*34.0 + 1.0 )*x =
// x*x*34.0 + x
float permute(float x) {
return mod289(
x*x*34.0 + x
);
}
float3 permute(float3 x) {
return mod289(
x*x*34.0 + x
);
}
float4 permute(float4 x) {
return mod289(
x*x*34.0 + x
);
}
float4 grad4(float j, float4 ip)
{
const float4 ones = float4(1.0, 1.0, 1.0, -1.0);
float4 p, s;
p.xyz = floor( frac(j * ip.xyz) * 7.0) * ip.z - 1.0;
p.w = 1.5 - dot( abs(p.xyz), ones.xyz );
// GLSL: lessThan(x, y) = x < y
// HLSL: 1 - step(y, x) = x < y
p.xyz -= sign(p.xyz) * (p.w < 0);
return p;
}
// ----------------------------------- 2D -------------------------------------
float snoise(float2 v)
{
const float4 C = float4(
0.211324865405187, // (3.0-sqrt(3.0))/6.0
0.366025403784439, // 0.5*(sqrt(3.0)-1.0)
-0.577350269189626, // -1.0 + 2.0 * C.x
0.024390243902439 // 1.0 / 41.0
);
// First corner
float2 i = floor( v + dot(v, C.yy) );
float2 x0 = v - i + dot(i, C.xx);
// Other corners
// float2 i1 = (x0.x > x0.y) ? float2(1.0, 0.0) : float2(0.0, 1.0);
// Lex-DRL: afaik, step() in GPU is faster than if(), so:
// step(x, y) = x <= y
// Actually, a simple conditional without branching is faster than that madness :)
int2 i1 = (x0.x > x0.y) ? float2(1.0, 0.0) : float2(0.0, 1.0);
float4 x12 = x0.xyxy + C.xxzz;
x12.xy -= i1;
// Permutations
i = mod289(i); // Avoid truncation effects in permutation
float3 p = permute(
permute(
i.y + float3(0.0, i1.y, 1.0 )
) + i.x + float3(0.0, i1.x, 1.0 )
);
float3 m = max(
0.5 - float3(
dot(x0, x0),
dot(x12.xy, x12.xy),
dot(x12.zw, x12.zw)
),
0.0
);
m = m*m ;
m = m*m ;
// Gradients: 41 points uniformly over a line, mapped onto a diamond.
// The ring size 17*17 = 289 is close to a multiple of 41 (41*7 = 287)
float3 x = 2.0 * frac(p * C.www) - 1.0;
float3 h = abs(x) - 0.5;
float3 ox = floor(x + 0.5);
float3 a0 = x - ox;
// Normalise gradients implicitly by scaling m
// Approximation of: m *= inversesqrt( a0*a0 + h*h );
m *= 1.79284291400159 - 0.85373472095314 * ( a0*a0 + h*h );
// Compute final noise value at P
float3 g;
g.x = a0.x * x0.x + h.x * x0.y;
g.yz = a0.yz * x12.xz + h.yz * x12.yw;
return 130.0 * dot(m, g);
}
// ----------------------------------- 3D -------------------------------------
float snoise(float3 v)
{
const float2 C = float2(
0.166666666666666667, // 1/6
0.333333333333333333 // 1/3
);
const float4 D = float4(0.0, 0.5, 1.0, 2.0);
// First corner
float3 i = floor( v + dot(v, C.yyy) );
float3 x0 = v - i + dot(i, C.xxx);
// Other corners
float3 g = step(x0.yzx, x0.xyz);
float3 l = 1 - g;
float3 i1 = min(g.xyz, l.zxy);
float3 i2 = max(g.xyz, l.zxy);
float3 x1 = x0 - i1 + C.xxx;
float3 x2 = x0 - i2 + C.yyy; // 2.0*C.x = 1/3 = C.y
float3 x3 = x0 - D.yyy; // -1.0+3.0*C.x = -0.5 = -D.y
// Permutations
i = mod289(i);
float4 p = permute(
permute(
permute(
i.z + float4(0.0, i1.z, i2.z, 1.0 )
) + i.y + float4(0.0, i1.y, i2.y, 1.0 )
) + i.x + float4(0.0, i1.x, i2.x, 1.0 )
);
// Gradients: 7x7 points over a square, mapped onto an octahedron.
// The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294)
float n_ = 0.142857142857; // 1/7
float3 ns = n_ * D.wyz - D.xzx;
float4 j = p - 49.0 * floor(p * ns.z * ns.z); // mod(p,7*7)
float4 x_ = floor(j * ns.z);
float4 y_ = floor(j - 7.0 * x_ ); // mod(j,N)
float4 x = x_ *ns.x + ns.yyyy;
float4 y = y_ *ns.x + ns.yyyy;
float4 h = 1.0 - abs(x) - abs(y);
float4 b0 = float4( x.xy, y.xy );
float4 b1 = float4( x.zw, y.zw );
//float4 s0 = float4(lessThan(b0,0.0))*2.0 - 1.0;
//float4 s1 = float4(lessThan(b1,0.0))*2.0 - 1.0;
float4 s0 = floor(b0)*2.0 + 1.0;
float4 s1 = floor(b1)*2.0 + 1.0;
float4 sh = -step(h, 0.0);
float4 a0 = b0.xzyw + s0.xzyw*sh.xxyy ;
float4 a1 = b1.xzyw + s1.xzyw*sh.zzww ;
float3 p0 = float3(a0.xy,h.x);
float3 p1 = float3(a0.zw,h.y);
float3 p2 = float3(a1.xy,h.z);
float3 p3 = float3(a1.zw,h.w);
//Normalise gradients
float4 norm = rsqrt(float4(
dot(p0, p0),
dot(p1, p1),
dot(p2, p2),
dot(p3, p3)
));
p0 *= norm.x;
p1 *= norm.y;
p2 *= norm.z;
p3 *= norm.w;
// Mix final noise value
float4 m = max(
0.6 - float4(
dot(x0, x0),
dot(x1, x1),
dot(x2, x2),
dot(x3, x3)
),
0.0
);
m = m * m;
return 42.0 * dot(
m*m,
float4(
dot(p0, x0),
dot(p1, x1),
dot(p2, x2),
dot(p3, x3)
)
);
}
// ----------------------------------- 4D -------------------------------------
float snoise(float4 v)
{
const float4 C = float4(
0.138196601125011, // (5 - sqrt(5))/20 G4
0.276393202250021, // 2 * G4
0.414589803375032, // 3 * G4
-0.447213595499958 // -1 + 4 * G4
);
// First corner
float4 i = floor(
v +
dot(
v,
0.309016994374947451 // (sqrt(5) - 1) / 4
)
);
float4 x0 = v - i + dot(i, C.xxxx);
// Other corners
// Rank sorting originally contributed by Bill Licea-Kane, AMD (formerly ATI)
float4 i0;
float3 isX = step( x0.yzw, x0.xxx );
float3 isYZ = step( x0.zww, x0.yyz );
i0.x = isX.x + isX.y + isX.z;
i0.yzw = 1.0 - isX;
i0.y += isYZ.x + isYZ.y;
i0.zw += 1.0 - isYZ.xy;
i0.z += isYZ.z;
i0.w += 1.0 - isYZ.z;
// i0 now contains the unique values 0,1,2,3 in each channel
float4 i3 = saturate(i0);
float4 i2 = saturate(i0-1.0);
float4 i1 = saturate(i0-2.0);
// x0 = x0 - 0.0 + 0.0 * C.xxxx
// x1 = x0 - i1 + 1.0 * C.xxxx
// x2 = x0 - i2 + 2.0 * C.xxxx
// x3 = x0 - i3 + 3.0 * C.xxxx
// x4 = x0 - 1.0 + 4.0 * C.xxxx
float4 x1 = x0 - i1 + C.xxxx;
float4 x2 = x0 - i2 + C.yyyy;
float4 x3 = x0 - i3 + C.zzzz;
float4 x4 = x0 + C.wwww;
// Permutations
i = mod289(i);
float j0 = permute(
permute(
permute(
permute(i.w) + i.z
) + i.y
) + i.x
);
float4 j1 = permute(
permute(
permute(
permute (
i.w + float4(i1.w, i2.w, i3.w, 1.0 )
) + i.z + float4(i1.z, i2.z, i3.z, 1.0 )
) + i.y + float4(i1.y, i2.y, i3.y, 1.0 )
) + i.x + float4(i1.x, i2.x, i3.x, 1.0 )
);
// Gradients: 7x7x6 points over a cube, mapped onto a 4-cross polytope
// 7*7*6 = 294, which is close to the ring size 17*17 = 289.
const float4 ip = float4(
0.003401360544217687075, // 1/294
0.020408163265306122449, // 1/49
0.142857142857142857143, // 1/7
0.0
);
float4 p0 = grad4(j0, ip);
float4 p1 = grad4(j1.x, ip);
float4 p2 = grad4(j1.y, ip);
float4 p3 = grad4(j1.z, ip);
float4 p4 = grad4(j1.w, ip);
// Normalise gradients
float4 norm = rsqrt(float4(
dot(p0, p0),
dot(p1, p1),
dot(p2, p2),
dot(p3, p3)
));
p0 *= norm.x;
p1 *= norm.y;
p2 *= norm.z;
p3 *= norm.w;
p4 *= rsqrt( dot(p4, p4) );
// Mix contributions from the five corners
float3 m0 = max(
0.6 - float3(
dot(x0, x0),
dot(x1, x1),
dot(x2, x2)
),
0.0
);
float2 m1 = max(
0.6 - float2(
dot(x3, x3),
dot(x4, x4)
),
0.0
);
m0 = m0 * m0;
m1 = m1 * m1;
return 49.0 * (
dot(
m0*m0,
float3(
dot(p0, x0),
dot(p1, x1),
dot(p2, x2)
)
) + dot(
m1*m1,
float2(
dot(p3, x3),
dot(p4, x4)
)
)
);
}
// Credits from source glsl file:
//
// Description : Array and textureless GLSL 2D/3D/4D simplex
// noise functions.
// Author : Ian McEwan, Ashima Arts.
// Maintainer : ijm
// Lastmod : 20110822 (ijm)
// License : Copyright (C) 2011 Ashima Arts. All rights reserved.
// Distributed under the MIT License. See LICENSE file.
// https://github.com/ashima/webgl-noise
//
//
// The text from LICENSE file:
//
//
// Copyright (C) 2011 by Ashima Arts (Simplex noise)
// Copyright (C) 2011 by Stefan Gustavson (Classic noise)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endif

View file

@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 61fdef2195a524f9fab29698a024c2f7
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,130 @@
// Description : Array and textureless GLSL 2D/3D/4D simplex
// noise functions.
// Author : Ian McEwan, Ashima Arts.
// Maintainer : stegu
// Lastmod : 20110822 (ijm)
// License : Copyright (C) 2011 Ashima Arts. All rights reserved.
// Distributed under the MIT License. See LICENSE file.
// https://github.com/ashima/webgl-noise
// https://github.com/stegu/webgl-noise
//
// Translated to HLSL
float4 mod289(float4 x) {
return x - floor(x * (1.0 / 289.0)) * 289.0; }
float mod289(float x) {
return x - floor(x * (1.0 / 289.0)) * 289.0; }
float4 permute(float4 x) {
return mod289(((x*34.0)+1.0)*x);
}
float permute(float x) {
return mod289(((x*34.0)+1.0)*x);
}
float4 taylorInvSqrt(float4 r)
{
return 1.79284291400159 - 0.85373472095314 * r;
}
float taylorInvSqrt(float r)
{
return 1.79284291400159 - 0.85373472095314 * r;
}
float4 grad4(float j, float4 ip)
{
const float4 ones = float4(1.0, 1.0, 1.0, -1.0);
float4 p,s;
p.xyz = floor( frac (j* ip.xyz) * 7.0) * ip.z - 1.0;
p.w = 1.5 - dot(abs(p.xyz), ones.xyz);
s = float4(p < 0);
p.xyz = p.xyz + (s.xyz*2.0 - 1.0) * s.www;
return p;
}
// (sqrt(5) - 1)/4 = F4, used once below
#define F4 0.309016994374947451
float snoise(float4 v)
{
const float4 C = float4( 0.138196601125011, // (5 - sqrt(5))/20 G4
0.276393202250021, // 2 * G4
0.414589803375032, // 3 * G4
-0.447213595499958); // -1 + 4 * G4
// First corner
float4 i = floor(v + dot(v, F4) );
float4 x0 = v - i + dot(i, C.xxxx);
// Other corners
// Rank sorting originally contributed by Bill Licea-Kane, AMD (formerly ATI)
float4 i0;
float3 isX = step( x0.yzw, x0.xxx );
float3 isYZ = step( x0.zww, x0.yyz );
// i0.x = dot( isX, float3( 1.0 ) );
i0.x = isX.x + isX.y + isX.z;
i0.yzw = 1.0 - isX;
// i0.y += dot( isYZ.xy, float2( 1.0 ) );
i0.y += isYZ.x + isYZ.y;
i0.zw += 1.0 - isYZ.xy;
i0.z += isYZ.z;
i0.w += 1.0 - isYZ.z;
// i0 now contains the unique values 0,1,2,3 in each channel
float4 i3 = saturate(i0);
float4 i2 = saturate(i0-1.0);
float4 i1 = saturate(i0-2.0);
// x0 = x0 - 0.0 + 0.0 * C.xxxx
// x1 = x0 - i1 + 1.0 * C.xxxx
// x2 = x0 - i2 + 2.0 * C.xxxx
// x3 = x0 - i3 + 3.0 * C.xxxx
// x4 = x0 - 1.0 + 4.0 * C.xxxx
float4 x1 = x0 - i1 + C.xxxx;
float4 x2 = x0 - i2 + C.yyyy;
float4 x3 = x0 - i3 + C.zzzz;
float4 x4 = x0 + C.wwww;
// Permutations
i = mod289(i);
float j0 = permute( permute( permute( permute(i.w) + i.z) + i.y) + i.x);
float4 j1 = permute( permute( permute( permute (
i.w + float4(i1.w, i2.w, i3.w, 1.0 ))
+ i.z + float4(i1.z, i2.z, i3.z, 1.0 ))
+ i.y + float4(i1.y, i2.y, i3.y, 1.0 ))
+ i.x + float4(i1.x, i2.x, i3.x, 1.0 ));
// Gradients: 7x7x6 points over a cube, mapped onto a 4-cross polytope
// 7*7*6 = 294, which is close to the ring size 17*17 = 289.
float4 ip = float4(1.0/294.0, 1.0/49.0, 1.0/7.0, 0.0) ;
float4 p0 = grad4(j0, ip);
float4 p1 = grad4(j1.x, ip);
float4 p2 = grad4(j1.y, ip);
float4 p3 = grad4(j1.z, ip);
float4 p4 = grad4(j1.w, ip);
// Normalise gradients
float4 norm = taylorInvSqrt(float4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)));
p0 *= norm.x;
p1 *= norm.y;
p2 *= norm.z;
p3 *= norm.w;
p4 *= taylorInvSqrt(dot(p4,p4));
// Mix contributions from the five corners
float3 m0 = max(0.6 - float3(dot(x0,x0), dot(x1,x1), dot(x2,x2)), 0.0);
float2 m1 = max(0.6 - float2(dot(x3,x3), dot(x4,x4) ), 0.0);
m0 = m0 * m0;
m1 = m1 * m1;
return 49.0 * ( dot(m0*m0, float3( dot( p0, x0 ), dot( p1, x1 ), dot( p2, x2 )))
+ dot(m1*m1, float2( dot( p3, x3 ), dot( p4, x4 ) ) ) ) ;
}

View file

@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: cd3204f7427fd4bd09c91ba886f63cec
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,100 @@
float4 triplanar(float3 vertPos, float3 normal, float scale, sampler2D tex) {
// Calculate triplanar coordinates
float2 uvX = vertPos.zy * scale;
float2 uvY = vertPos.xz * scale;
float2 uvZ = vertPos.xy * scale;
float4 colX = tex2D (tex, uvX);
float4 colY = tex2D (tex, uvY);
float4 colZ = tex2D (tex, uvZ);
// Square normal to make all values positive + increase blend sharpness
float3 blendWeight = normal * normal;
// Divide blend weight by the sum of its components. This will make x + y + z = 1
blendWeight /= dot(blendWeight, 1);
return colX * blendWeight.x + colY * blendWeight.y + colZ * blendWeight.z;
}
float4 triplanarOffset(float3 vertPos, float3 normal, float3 scale, sampler2D tex, float2 offset) {
float3 scaledPos = vertPos / scale;
float4 colX = tex2D (tex, scaledPos.zy + offset);
float4 colY = tex2D(tex, scaledPos.xz + offset);
float4 colZ = tex2D (tex,scaledPos.xy + offset);
// Square normal to make all values positive + increase blend sharpness
float3 blendWeight = normal * normal;
// Divide blend weight by the sum of its components. This will make x + y + z = 1
blendWeight /= dot(blendWeight, 1);
return colX * blendWeight.x + colY * blendWeight.y + colZ * blendWeight.z;
}
float3 ObjectToTangentVector(float4 tangent, float3 normal, float3 objectSpaceVector) {
float3 normalizedTangent = normalize(tangent.xyz);
float3 binormal = cross(normal, normalizedTangent) * tangent.w;
float3x3 rot = float3x3 (normalizedTangent, binormal, normal);
return mul(rot, objectSpaceVector);
}
// Reoriented Normal Mapping
// http://blog.selfshadow.com/publications/blending-in-detail/
// Altered to take normals (-1 to 1 ranges) rather than unsigned normal maps (0 to 1 ranges)
float3 blend_rnm(float3 n1, float3 n2)
{
n1.z += 1;
n2.xy = -n2.xy;
return n1 * dot(n1, n2) / n1.z - n2;
}
// Sample normal map with triplanar coordinates
// Returned normal will be in obj/world space (depending whether pos/normal are given in obj or world space)
// Based on: medium.com/@bgolus/normal-mapping-for-a-triplanar-shader-10bf39dca05a
float3 triplanarNormal(float3 vertPos, float3 normal, float3 scale, float2 offset, sampler2D normalMap) {
float3 absNormal = abs(normal);
// Calculate triplanar blend
float3 blendWeight = saturate(pow(normal, 4));
// Divide blend weight by the sum of its components. This will make x + y + z = 1
blendWeight /= dot(blendWeight, 1);
// Calculate triplanar coordinates
float2 uvX = vertPos.zy * scale + offset;
float2 uvY = vertPos.xz * scale + offset;
float2 uvZ = vertPos.xy * scale + offset;
// Sample tangent space normal maps
// UnpackNormal puts values in range [-1, 1] (and accounts for DXT5nm compression)
float3 tangentNormalX = UnpackNormal(tex2D(normalMap, uvX));
float3 tangentNormalY = UnpackNormal(tex2D(normalMap, uvY));
float3 tangentNormalZ = UnpackNormal(tex2D(normalMap, uvZ));
// Swizzle normals to match tangent space and apply reoriented normal mapping blend
tangentNormalX = blend_rnm(half3(normal.zy, absNormal.x), tangentNormalX);
tangentNormalY = blend_rnm(half3(normal.xz, absNormal.y), tangentNormalY);
tangentNormalZ = blend_rnm(half3(normal.xy, absNormal.z), tangentNormalZ);
// Apply input normal sign to tangent space Z
float3 axisSign = sign(normal);
tangentNormalX.z *= axisSign.x;
tangentNormalY.z *= axisSign.y;
tangentNormalZ.z *= axisSign.z;
// Swizzle tangent normals to match input normal and blend together
float3 outputNormal = normalize(
tangentNormalX.zyx * blendWeight.x +
tangentNormalY.xzy * blendWeight.y +
tangentNormalZ.xyz * blendWeight.z
);
return outputNormal;
}
float3 triplanarNormalTangentSpace(float3 vertPos, float3 normal, float3 scale, float4 tangent, sampler2D normalMap) {
float3 textureNormal = triplanarNormal(vertPos, normal, scale, 0, normalMap);
return ObjectToTangentVector(tangent, normal, textureNormal);
}
float3 triplanarNormalTangentSpace(float3 vertPos, float3 normal, float3 scale, float2 offset, float4 tangent, sampler2D normalMap) {
float3 textureNormal = triplanarNormal(vertPos, normal, scale, offset, normalMap);
return ObjectToTangentVector(tangent, normal, textureNormal);
}

View file

@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 31f13bf4eeb1a49068672a85ab42adad
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d612c10deee194fbca8cd7456da1e532
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

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