public static void GenerateTerrainBlendData(MicroSplatTerrain bt) { Terrain t = bt.GetComponent <Terrain>(); int w = t.terrainData.heightmapResolution; int h = t.terrainData.heightmapResolution; Texture2D data = new Texture2D(w, h, TextureFormat.RGBAHalf, true, true); for (int x = 0; x < w; ++x) { for (int y = 0; y < h; ++y) { float height = t.terrainData.GetHeight(x, y); Vector3 normal = t.terrainData.GetInterpolatedNormal((float)x / w, (float)y / h); // When you save a texture to EXR format, either in the saving or import stage, // some type of gamma curve is applied regardless of the fact that the textures is // set to linear. So we pow it here to counteract it, whis is total BS, but works.. normal.x = (normal.x >= 0) ? Mathf.Pow(normal.x, 2.0f) : Mathf.Pow(normal.x, 2) * -1; normal.z = (normal.z >= 0) ? Mathf.Pow(normal.z, 2.0f) : Mathf.Pow(normal.z, 2) * -1; data.SetPixel(x, y, new Color(normal.x, normal.y, normal.z, height)); } } data.Apply(); var path = MicroSplatUtilities.RelativePathFromAsset(t.terrainData); path += "/" + t.name + ".exr"; var bytes = data.EncodeToEXR(Texture2D.EXRFlags.OutputAsFloat); System.IO.File.WriteAllBytes(path, bytes); GameObject.DestroyImmediate(data); AssetDatabase.Refresh(); bt.terrainDesc = AssetDatabase.LoadAssetAtPath <Texture2D>(path); var ai = AssetImporter.GetAtPath(path); var ti = ai as TextureImporter; var ps = ti.GetDefaultPlatformTextureSettings(); if (ti.isReadable == true || ti.wrapMode != TextureWrapMode.Clamp || ps.format != TextureImporterFormat.RGBAHalf || ps.textureCompression != TextureImporterCompression.Uncompressed || ps.overridden != true || ti.filterMode != FilterMode.Bilinear || ti.sRGBTexture != false) { ti.sRGBTexture = false; ti.filterMode = FilterMode.Bilinear; ti.mipmapEnabled = true; ti.wrapMode = TextureWrapMode.Clamp; ti.isReadable = false; ps.format = TextureImporterFormat.RGBAHalf; ps.textureCompression = TextureImporterCompression.Uncompressed; ps.overridden = true; ti.SetPlatformTextureSettings(ps); ti.SaveAndReimport(); } bt.sTerrainDirty = false; EditorUtility.SetDirty(bt); MicroSplatTerrain.SyncAll(); }
public void DoPerPixelNormalGUI() { MicroSplatTerrain bt = target as MicroSplatTerrain; Terrain t = bt.GetComponent <Terrain>(); if (t == null || t.terrainData == null) { EditorGUILayout.HelpBox("No Terrain data found", MessageType.Error); return; } if (t.materialTemplate == null) { return; } if (bt.keywordSO == null) { return; } if (bt.terrain.drawInstanced && bt.perPixelNormal != null && !bt.keywordSO.IsKeywordEnabled("_TERRAINBLENDING")) { EditorGUILayout.HelpBox("Per Pixel Normal is assigned, but shader is using Instance rendering, which automatically provides per-pixel normal. You may turn off per pixel normal if it's on and clear the normal data to save memory.", MessageType.Warning); if (bt.perPixelNormal != null && GUILayout.Button("Clear")) { bt.perPixelNormal = null; EditorUtility.SetDirty(bt); EditorUtility.SetDirty(bt.terrain); } } MicroSplatUtilities.DrawTextureField(bt, CPerPixelNormal, ref bt.perPixelNormal, "_PERPIXNORMAL", "_TERRAINBLENDING", null, null, false); if (bt.perPixelNormal == null && (bt.keywordSO.IsKeywordEnabled("_PERPIXNORMAL") || bt.keywordSO.IsKeywordEnabled("_TERRAINBLENDING"))) { EditorGUILayout.HelpBox("Terrain Normal Data is not present, please generate", MessageType.Warning); } if (bt.keywordSO.IsKeywordEnabled("_PERPIXNORMAL") || bt.keywordSO.IsKeywordEnabled("_TERRAINBLENDING")) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Normal Data"); if (GUILayout.Button(bt.perPixelNormal == null ? "Generate" : "Update")) { GenerateTerrainNormalMap(bt); EditorUtility.SetDirty(bt); EditorUtility.SetDirty(bt.terrain); } if (bt.perPixelNormal != null && GUILayout.Button("Clear")) { bt.perPixelNormal = null; EditorUtility.SetDirty(bt); EditorUtility.SetDirty(bt.terrain); } EditorGUILayout.EndHorizontal(); } }
public void DoTerrainDescGUI() { MicroSplatTerrain bt = target as MicroSplatTerrain; Terrain t = bt.GetComponent <Terrain>(); if (t == null || t.terrainData == null) { return; } if (t.materialTemplate == null) { return; } if (bt.keywordSO == null) { return; } if (!bt.keywordSO.IsKeywordEnabled("_TERRAINBLENDING") && !bt.keywordSO.IsKeywordEnabled("_DYNAMICFLOWS")) { return; } EditorGUILayout.Space(); if (bt.blendMat == null && bt.templateMaterial != null && bt.keywordSO != null && bt.keywordSO.IsKeywordEnabled("_TERRAINBLENDING")) { var path = AssetDatabase.GetAssetPath(bt.templateMaterial); path = path.Replace(".mat", "_TerrainObjectBlend.mat"); bt.blendMat = AssetDatabase.LoadAssetAtPath <Material>(path); if (bt.blendMat == null) { string shaderPath = path.Replace(".mat", ".shader"); Shader shader = AssetDatabase.LoadAssetAtPath <Shader>(shaderPath); if (shader == null) { shaderPath = path.Replace(".shader", ".surfshader"); shader = AssetDatabase.LoadAssetAtPath <Shader>(shaderPath); } if (shader == null) { shaderPath = AssetDatabase.GetAssetPath(bt.templateMaterial.shader); shaderPath = shaderPath.Replace(".shader", "_TerrainObjectBlend.shader"); shaderPath = shaderPath.Replace(".surfshader", "_TerrainObjectBlend.surfshader"); shader = AssetDatabase.LoadAssetAtPath <Shader>(shaderPath); } if (shader != null) { Material mat = new Material(shader); AssetDatabase.CreateAsset(mat, path); AssetDatabase.SaveAssets(); MicroSplatTerrain.SyncAll(); } } } EditorUtility.SetDirty(bt); EditorUtility.SetDirty(bt.terrain); }
public void DoPerPixelNormalGUI() { MicroSplatTerrain bt = target as MicroSplatTerrain; Terrain t = bt.GetComponent <Terrain>(); if (t == null || t.terrainData == null) { EditorGUILayout.HelpBox("No Terrain data found", MessageType.Error); return; } if (t.materialType != Terrain.MaterialType.Custom || t.materialTemplate == null) { return; } if (bt.keywordSO == null) { return; } if (!bt.keywordSO.IsKeywordEnabled("_PERPIXNORMAL")) { bt.perPixelNormal = null; return; } #if UNITY_2018_3_OR_NEWER if (bt.terrain.drawInstanced && bt.perPixelNormal) { EditorGUILayout.HelpBox("Per Pixel Normal is assigned, but shader is using Instance rendering, which automatically provides per-pixel normal. You may turn off per pixel normal and clear the normal data to save memory.", MessageType.Warning); } #endif if (bt.perPixelNormal == null) { EditorGUILayout.HelpBox("Terrain Normal Data is not present, please generate", MessageType.Warning); } if (bt.perPixelNormal != null && bt.sTerrainDirty) { EditorGUILayout.HelpBox("Terrain Normal data is out of date, please update", MessageType.Warning); } EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Normal Data"); if (GUILayout.Button(bt.perPixelNormal == null ? "Generate" : "Update")) { GenerateTerrainNormalMap(bt); } if (bt.perPixelNormal != null && GUILayout.Button("Clear")) { bt.perPixelNormal = null; } EditorGUILayout.EndHorizontal(); }
public static void GenerateTerrainNormalMap(MicroSplatTerrain bt) { Terrain t = bt.GetComponent <Terrain>(); int w = t.terrainData.heightmapResolution; int h = t.terrainData.heightmapResolution; Texture2D data = new Texture2D(w, h, TextureFormat.RGBA32, true, true); for (int x = 0; x < w; ++x) { for (int y = 0; y < h; ++y) { Vector3 normal = t.terrainData.GetInterpolatedNormal((float)x / w, (float)y / h); data.SetPixel(x, y, new Color(normal.x * 0.5f + 0.5f, normal.z * 0.5f + 0.5f, normal.y)); } } data.Apply(); var path = MicroSplatUtilities.RelativePathFromAsset(t.terrainData); path += "/" + t.name + "_normal.png"; var bytes = data.EncodeToPNG(); System.IO.File.WriteAllBytes(path, bytes); GameObject.DestroyImmediate(data); AssetDatabase.Refresh(); bt.perPixelNormal = AssetDatabase.LoadAssetAtPath <Texture2D>(path); var ai = AssetImporter.GetAtPath(path); var ti = ai as TextureImporter; var ps = ti.GetDefaultPlatformTextureSettings(); if (ti.isReadable == true || ti.wrapMode != TextureWrapMode.Clamp || ps.overridden != true || ti.textureType != TextureImporterType.NormalMap) { ti.textureType = TextureImporterType.NormalMap; ti.mipmapEnabled = true; ti.wrapMode = TextureWrapMode.Clamp; ti.isReadable = false; ps.overridden = true; ti.SetPlatformTextureSettings(ps); ti.SaveAndReimport(); } bt.sTerrainDirty = false; EditorUtility.SetDirty(bt); EditorUtility.SetDirty(bt.terrain); MicroSplatTerrain.SyncAll(); AssetDatabase.SaveAssets(); }
public void DoCavityMapGUI() { MicroSplatTerrain bt = target as MicroSplatTerrain; Terrain t = bt.GetComponent <Terrain>(); if (t == null || t.terrainData == null) { EditorGUILayout.HelpBox("No Terrain data found", MessageType.Error); return; } if (t.materialTemplate == null) { return; } if (bt.keywordSO == null) { return; } if (bt.cavityMap == null) { EditorGUILayout.HelpBox("Cavity Map Data is not present, please generate or provide", MessageType.Warning); } bt.cavityMap = (Texture2D)EditorGUILayout.ObjectField("Cavity Map", bt.cavityMap, typeof(Texture2D), false); if (bt.cavityMap != null && bt.sTerrainDirty) { EditorGUILayout.HelpBox("Cavity data may be out of date as terrain has changed", MessageType.Warning); } EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Cavity Data"); if (GUILayout.Button(bt.cavityMap == null ? "Generate" : "Update")) { ComputeCavityFlowMap(bt); } if (bt.cavityMap != null && GUILayout.Button("Clear")) { bt.cavityMap = null; } EditorGUILayout.EndHorizontal(); }
/// <summary> /// Preprocess the terrain to clamp down on the number of splat maps which have weights on each control point. First pass /// limits the number of weights to the specified amount per control point. Since each rendered pixel is a blend of 4 possible /// control points, this still means a given pixel may need up to 4 weights even if the control point is clamped to 1 weight. /// In the second pass, we check all of the neighoring pixels to see if they have different weights- if they do, we clamp /// down to one less weight on this control point. The idea here is to create some extra headroom for the blend, but since /// you can still need 4 blend weights in some cases, there is no perfect solution to this issue when running with less than /// 4 blend weights. It does, however, greatly help when running under those constraints. /// /// </summary> /// <param name="bt">Bt.</param> /// <param name="maxWeights">Max weights.</param> /// <param name="secondPass">If set to <c>true</c> second pass.</param> public static void WeightLimitTerrain(MicroSplatTerrain bt, int maxWeights, bool secondPass = false) { Terrain t = bt.GetComponent <Terrain>(); if (t == null) { return; } UnityEngine.TerrainData td = t.terrainData; if (td == null) { return; } int w = td.alphamapWidth; int h = td.alphamapHeight; int l = td.alphamapLayers; Undo.RegisterCompleteObjectUndo(t, "Weight Limit Terrain"); var splats = td.GetAlphamaps(0, 0, w, h); float[] data = new float[16]; List <WeightPair> sorted = new List <WeightPair>(); List <int> validIndexes = new List <int>(); for (int x = 0; x < w; ++x) { for (int y = 0; y < h; ++y) { // gather all weights for (int i = 0; i < l; ++i) { data[i] = splats[x, y, i]; } sorted.Clear(); for (int i = 0; i < 16; ++i) { var wp = new WeightPair(); wp.index = i; wp.weight = data[i]; sorted.Add(wp); } sorted.Sort((w0, w1) => w1.weight.CompareTo(w0.weight)); // remove lower weights int allowedWeights = maxWeights; while (sorted.Count > allowedWeights) { sorted.RemoveAt(sorted.Count - 1); } // generate valid index list validIndexes.Clear(); for (int i = 0; i < sorted.Count; ++i) { if (sorted[i].weight > 0) { validIndexes.Add(sorted[i].index); } } // figure out if our neighbors have weights which we don't have- if so, clamp down harder to make room for blending.. // if not, allow us to blend fully. We do this in a second pass so that small weights are reduced before we make // this decision.. if (secondPass) { for (int xm = -1; xm < 2; ++xm) { for (int ym = -1; ym < 2; ++ym) { int nx = x + xm; int ny = y + ym; if (nx >= 0 && ny >= 0 && nx < w && ny < y) { for (int layer = 0; layer < l; ++layer) { float weight = splats[nx, ny, layer]; if (weight > 0 && !validIndexes.Contains(layer)) { allowedWeights = maxWeights - 1; } } } } } while (sorted.Count > allowedWeights) { sorted.RemoveAt(sorted.Count - 1); } // generate valid index list validIndexes.Clear(); for (int i = 0; i < sorted.Count; ++i) { if (sorted[i].weight > 0) { validIndexes.Add(sorted[i].index); } } } // clear non-valid indexes for (int j = 0; j < 16; ++j) { if (!validIndexes.Contains(j)) { data[j] = 0; } } // now normalize weights so that they total one on each pixel float total = 0; for (int j = 0; j < 16; ++j) { total += data[j]; } float scale = 1.0f / total; for (int j = 0; j < 16; ++j) { data[j] *= scale; } // now map back to splat data array for (int i = 0; i < l; ++i) { splats[x, y, i] = data[i]; } } } td.SetAlphamaps(0, 0, splats); }
bool DoConvertGUI(MicroSplatTerrain t) { if (t.templateMaterial == null) { InitConvertConfigs(); using (new GUILayout.VerticalScope(GUI.skin.box)) { EditorGUILayout.LabelField("Select any integrations you want to add:"); // integrations for (int i = 0; i < integrationConfigs.Count; ++i) { var ic = integrationConfigs [i]; if (!ic.assetInstalled) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(ic.name, GUILayout.Width(120)); EditorGUILayout.LabelField("Not Installed", GUILayout.Width(120)); if (GUILayout.Button("Link", GUILayout.Width(120))) { Application.OpenURL(ic.assetLink); } EditorGUILayout.EndHorizontal(); } else { EditorGUILayout.BeginHorizontal(); ic.include = EditorGUILayout.Toggle(ic.include, GUILayout.Width(20)); EditorGUILayout.LabelField(ic.name); EditorGUILayout.EndHorizontal(); if (ic.include && ic.missingModules.Count > 0) { using (new GUILayout.VerticalScope(GUI.skin.box)) { EditorGUILayout.HelpBox("Some MicroSplat modules requested by this module are not installed. Some or all features of the integration will not be active.", MessageType.Warning); for (int j = 0; j < ic.missingModules.Count; ++j) { var m = ic.missingModules [j]; DrawMissingModule(m); } } } } } if (GUILayout.Button("Convert to MicroSplat")) { // get all terrains in selection, not just this one, and treat as one giant terrain var objs = Selection.gameObjects; List <Terrain> terrains = new List <Terrain> (); for (int i = 0; i < objs.Length; ++i) { Terrain ter = objs [i].GetComponent <Terrain> (); if (ter != null) { terrains.Add(ter); } Terrain [] trs = objs [i].GetComponentsInChildren <Terrain> (); for (int x = 0; x < trs.Length; ++x) { if (!terrains.Contains(trs [x])) { terrains.Add(trs [x]); } } } Terrain terrain = t.GetComponent <Terrain> (); int texcount = terrain.terrainData.terrainLayers.Length; List <string> keywords = new List <string> (defaultKeywords); // set initial render pipleine var pipeline = MicroSplatUtilities.DetectPipeline(); if (pipeline == MicroSplatUtilities.PipelineType.HDPipeline) { keywords.Add("_MSRENDERLOOP_UNITYHD"); } else if (pipeline == MicroSplatUtilities.PipelineType.UniversalPipeline) { keywords.Add("_MSRENDERLOOP_UNITYLD"); } // Because new users won't read the manual or read settings before they act, we don't clamp the texture count // down for maximum performance. Way to many support requests complaining of black terrain after adding textures because // they didn't realize they needed to up the max texture count. So now, 16 minimum. This is why we can't have nice things. /* * if (texcount <= 4) * { * keywords.Add ("_MAX4TEXTURES"); * } * else if (texcount <= 8) * { * keywords.Add ("_MAX8TEXTURES"); * } * else if (texcount <= 12) * { * keywords.Add ("_MAX12TEXTURES"); * } */ if (texcount > 16 && texcount <= 20) { keywords.Add("_MAX20TEXTURES"); } else if (texcount <= 24) { keywords.Add("_MAX24TEXTURES"); } else if (texcount <= 28) { keywords.Add("_MAX28TEXTURES"); } else if (texcount > 28) { keywords.Add("_MAX32TEXTURES"); } for (int i = 0; i < integrationConfigs.Count; ++i) { var ic = integrationConfigs [i]; if (ic.include) { keywords.AddRange(ic.keywords); } } // setup this terrain t.templateMaterial = MicroSplatShaderGUI.NewShaderAndMaterial(terrain, keywords.ToArray()); var config = TextureArrayConfigEditor.CreateConfig(terrain); t.templateMaterial.SetTexture("_Diffuse", config.diffuseArray); t.templateMaterial.SetTexture("_NormalSAO", config.normalSAOArray); t.propData = MicroSplatShaderGUI.FindOrCreatePropTex(t.templateMaterial); EditorUtility.SetDirty(t); if (terrain.terrainData.terrainLayers != null) { if (terrain.terrainData.terrainLayers.Length > 0) { Vector2 min = new Vector2(99999, 99999); Vector2 max = Vector2.zero; for (int x = 0; x < terrain.terrainData.terrainLayers.Length; ++x) { var uv = terrain.terrainData.terrainLayers [x].tileSize; if (min.x > uv.x) { min.x = uv.x; } if (min.y > uv.y) { min.y = uv.y; } if (max.x < uv.x) { max.x = uv.x; } if (max.y < uv.y) { max.y = uv.y; } } Vector2 average = Vector2.Lerp(min, max, 0.5f); // use per texture UVs instead.. float diff = Vector2.Distance(min, max); if (diff > 0.1) { keywords.Add("_PERTEXUVSCALEOFFSET"); // if the user has widely different UVs, use the LOD sampler. This is because the gradient mode blends between mip levels, // which looks bad with hugely different UVs. I still don't understand why people do this kind of crap though, ideally // your UVs should not differ per texture, and if so, not by much.. if (diff > 10) { Debug.LogWarning("Terrain has wildly varing UV scales, it's best to keep consistent texture resolution. "); } if (!keywords.Contains("_USEGRADMIP")) { keywords.Add("_USEGRADMIP"); } Vector4 scaleOffset = new Vector4(1, 1, 0, 0); t.templateMaterial.SetVector("_UVScale", scaleOffset); var propData = MicroSplatShaderGUI.FindOrCreatePropTex(t.templateMaterial); for (int x = 0; x < terrain.terrainData.terrainLayers.Length; ++x) { var uvScale = terrain.terrainData.terrainLayers [x].tileSize; var uvOffset = terrain.terrainData.terrainLayers [x].tileOffset; uvScale = MicroSplatRuntimeUtil.UnityUVScaleToUVScale(uvScale, terrain); uvScale.x = Mathf.RoundToInt(uvScale.x); uvScale.y = Mathf.RoundToInt(uvScale.y); propData.SetValue(x, MicroSplatPropData.PerTexVector2.SplatUVScale, uvScale); propData.SetValue(x, MicroSplatPropData.PerTexVector2.SplatUVOffset, Vector2.zero); } for (int x = terrain.terrainData.terrainLayers.Length; x < 32; ++x) { propData.SetValue(x, MicroSplatPropData.PerTexVector2.SplatUVScale, average); propData.SetValue(x, MicroSplatPropData.PerTexVector2.SplatUVOffset, Vector2.zero); } // must init the data, or the editor will write over it. propData.SetValue(0, 15, Color.white); EditorUtility.SetDirty(propData); t.templateMaterial.SetVector("_TriplanarUVScale", new Vector4( 10.0f / t.terrain.terrainData.size.x, 10.0f / t.terrain.terrainData.size.x, 0, 0)); } else { var uvScale = terrain.terrainData.terrainLayers [0].tileSize; var uvOffset = terrain.terrainData.terrainLayers [0].tileOffset; uvScale = MicroSplatRuntimeUtil.UnityUVScaleToUVScale(uvScale, terrain); uvOffset.x = uvScale.x / terrain.terrainData.size.x * 0.5f * uvOffset.x; uvOffset.y = uvScale.y / terrain.terrainData.size.x * 0.5f * uvOffset.y; Vector4 scaleOffset = new Vector4(uvScale.x, uvScale.y, uvOffset.x, uvOffset.y); t.templateMaterial.SetVector("_UVScale", scaleOffset); t.templateMaterial.SetVector("_TriplanarUVScale", new Vector4( 10.0f / t.terrain.terrainData.size.x, 10.0f / t.terrain.terrainData.size.x, 0, 0)); } } } // now make sure others all have the same settings as well. for (int i = 0; i < terrains.Count; ++i) { var nt = terrains [i]; var mgr = nt.GetComponent <MicroSplatTerrain> (); if (mgr == null) { mgr = nt.gameObject.AddComponent <MicroSplatTerrain> (); } mgr.templateMaterial = t.templateMaterial; if (mgr.propData == null) { mgr.propData = MicroSplatShaderGUI.FindOrCreatePropTex(mgr.templateMaterial); } } Selection.SetActiveObjectWithContext(config, config); t.keywordSO = MicroSplatUtilities.FindOrCreateKeywords(t.templateMaterial); t.keywordSO.keywords.Clear(); t.keywordSO.keywords = new List <string> (keywords); // force recompile, so that basemap shader name gets reset correctly.. MicroSplatShaderGUI.MicroSplatCompiler comp = new MicroSplatShaderGUI.MicroSplatCompiler(); comp.Compile(t.templateMaterial); // for some reason, often when people create terrains with Gaia but this is unconfirmed, // if instancing is set, the terrain will not draw until a shader feature is toggled. // So for now, turn off instancing when doing conversion. for (int i = 0; i < terrains.Count; ++i) { var nt = terrains [i]; nt.drawInstanced = false; } MicroSplatTerrain.SyncAll(); /* * // turn on draw instanced if enabled and tessellation is disabled, unless render loop is LWRP/URP in which case it does work.. * if (t.keywordSO != null && (!t.keywordSO.IsKeywordEnabled("_TESSDISTANCE") || t.keywordSO.IsKeywordEnabled("_MSRENDERLOOP_UNITYLD"))) * { * for (int i = 0; i < terrains.Count; ++i) * { * var nt = terrains [i]; * var mgr = nt.GetComponent<MicroSplatTerrain> (); * if (mgr != null && mgr.keywordSO != null && !mgr.keywordSO.IsKeywordEnabled("_MSRENDERLOOP_UNITYLD")) * { * nt.drawInstanced = true; * } * } * } */ return(true); } } } return(false); }
public static void GenerateTerrainBlendData(MicroSplatTerrain bt) { Terrain t = bt.GetComponent <Terrain>(); int w = t.terrainData.heightmapResolution; int h = t.terrainData.heightmapResolution; Texture2D data = null; if (SystemInfo.SupportsTextureFormat(TextureFormat.RGBAHalf)) { data = new Texture2D(w, h, TextureFormat.RGBAHalf, true, true); } #if UNITY_2018_3_OR_NEWER else if (SystemInfo.SupportsTextureFormat(TextureFormat.RGBAFloat)) { data = new Texture2D(w, h, TextureFormat.RGBAFloat, true, true); } #endif else { Debug.LogError("System does not support RGBAHalf or RGBAFloat texture formats, Terrain Descriptor cannot be generated."); return; } for (int x = 0; x < w; ++x) { for (int y = 0; y < h; ++y) { float height = t.terrainData.GetHeight(x, y); Vector3 normal = t.terrainData.GetInterpolatedNormal((float)x / w, (float)y / h); // When you save a texture to EXR format, either in the saving or import stage, // some type of gamma curve is applied regardless of the fact that the textures is // set to linear. So we pow it here to counteract it, whis is total BS, but works.. normal.x = (normal.x >= 0) ? Mathf.Pow(normal.x, 2.0f) : Mathf.Pow(normal.x, 2) * -1; normal.z = (normal.z >= 0) ? Mathf.Pow(normal.z, 2.0f) : Mathf.Pow(normal.z, 2) * -1; data.SetPixel(x, y, new Color(normal.x, normal.y, normal.z, height)); } } data.Apply(); var path = MicroSplatUtilities.RelativePathFromAsset(t.terrainData); path += "/" + t.name + ".exr"; var bytes = data.EncodeToEXR(Texture2D.EXRFlags.OutputAsFloat); System.IO.File.WriteAllBytes(path, bytes); GameObject.DestroyImmediate(data); AssetDatabase.Refresh(); bt.terrainDesc = AssetDatabase.LoadAssetAtPath <Texture2D>(path); var ai = AssetImporter.GetAtPath(path); var ti = ai as TextureImporter; // default platform no longer supports RGBA half/float in newer unity, so we override all platforms bool changed = false; var platforms = System.Enum.GetNames(typeof(BuildTarget)); for (int i = 0; i < platforms.Length; ++i) { string platform = platforms [i]; var ps = ti.GetPlatformTextureSettings(platform); if (ti.isReadable == true || ti.wrapMode != TextureWrapMode.Clamp || #if UNITY_2018_3_OR_NEWER (ps.format != TextureImporterFormat.RGBAHalf && ps.format != TextureImporterFormat.RGBAFloat) || #else ps.format != TextureImporterFormat.RGBAHalf || #endif ps.textureCompression != TextureImporterCompression.Uncompressed || ps.overridden != true || ti.filterMode != FilterMode.Bilinear || ti.sRGBTexture != false) { ti.sRGBTexture = false; ti.filterMode = FilterMode.Bilinear; ti.mipmapEnabled = true; ti.wrapMode = TextureWrapMode.Clamp; ti.isReadable = false; #if UNITY_2018_3_OR_NEWER if (SystemInfo.SupportsTextureFormat(TextureFormat.RGBAHalf)) { ps.format = TextureImporterFormat.RGBAHalf; } else { ps.format = TextureImporterFormat.RGBAFloat; } #else ps.format = TextureImporterFormat.RGBAHalf; #endif ps.textureCompression = TextureImporterCompression.Uncompressed; ps.overridden = true; try { ti.SetPlatformTextureSettings(ps); changed = true; } catch { } } } if (changed) { ti.SaveAndReimport(); } bt.sTerrainDirty = false; EditorUtility.SetDirty(bt); EditorUtility.SetDirty(bt.terrain); MicroSplatTerrain.SyncAll(); AssetDatabase.SaveAssets(); }
public void DoTerrainDescGUI() { MicroSplatTerrain bt = target as MicroSplatTerrain; Terrain t = bt.GetComponent <Terrain>(); if (t == null || t.terrainData == null) { EditorGUILayout.HelpBox("No Terrain found, please add this component to your terrain", MessageType.Error); return; } if (t.materialTemplate == null) { return; } if (bt.keywordSO == null) { return; } if (!bt.keywordSO.IsKeywordEnabled("_TERRAINBLENDING") && !bt.keywordSO.IsKeywordEnabled("_DYNAMICFLOWS")) { return; } EditorGUILayout.Space(); if (bt.terrainDesc == null) { EditorGUILayout.HelpBox("Terrain Descriptor Data is not present, please generate", MessageType.Info); } if (bt.terrainDesc != null && bt.sTerrainDirty) { EditorGUILayout.HelpBox("Terrain Descriptor data is out of date, please update", MessageType.Info); } if (GUILayout.Button(bt.terrainDesc == null ? "Generate Terrain Descriptor Data" : "Update Terrain Descriptor Data")) { GenerateTerrainBlendData(bt); } if (bt.terrainDesc != null && GUILayout.Button("Clear Terrain Descriptor Data")) { bt.terrainDesc = null; } if (bt.terrainDesc != null) { EditorGUILayout.BeginHorizontal(); int mem = bt.terrainDesc.width * bt.terrainDesc.height; mem /= 128; EditorGUILayout.LabelField("Terrain Descriptor Data Memory: " + mem.ToString() + "kb"); EditorGUILayout.EndHorizontal(); } if (bt.blendMat == null && bt.templateMaterial != null && bt.keywordSO != null && bt.keywordSO.IsKeywordEnabled("_TERRAINBLENDING")) { var path = AssetDatabase.GetAssetPath(bt.templateMaterial); path = path.Replace(".mat", "_TerrainObjectBlend.mat"); bt.blendMat = AssetDatabase.LoadAssetAtPath <Material>(path); if (bt.blendMat == null) { string shaderPath = path.Replace(".mat", ".shader"); Shader shader = AssetDatabase.LoadAssetAtPath <Shader>(shaderPath); if (shader == null) { shaderPath = AssetDatabase.GetAssetPath(bt.templateMaterial.shader); shaderPath = shaderPath.Replace(".shader", "_TerrainObjectBlend.shader"); shader = AssetDatabase.LoadAssetAtPath <Shader>(shaderPath); } if (shader != null) { Material mat = new Material(shader); AssetDatabase.CreateAsset(mat, path); AssetDatabase.SaveAssets(); MicroSplatTerrain.SyncAll(); } } } EditorUtility.SetDirty(bt); EditorUtility.SetDirty(bt.terrain); }
//static GUIContent AdvDetailControl = new GUIContent("Advanced Detail Control", "Control map for Advanced Details"); public override void OnInspectorGUI() { MicroSplatTerrain t = target as MicroSplatTerrain; if (t == null) { EditorGUILayout.HelpBox("No Terrain Present, please put this component on a terrain", MessageType.Error); return; } EditorGUI.BeginChangeCheck(); t.templateMaterial = EditorGUILayout.ObjectField(CTemplateMaterial, t.templateMaterial, typeof(Material), false) as Material; if (t.templateMaterial == null) { if (GUILayout.Button("Convert to MicroSplat")) { // get all terrains in selection, not just this one, and treat as one giant terrain var objs = Selection.gameObjects; List <Terrain> terrains = new List <Terrain>(); for (int i = 0; i < objs.Length; ++i) { Terrain ter = objs[i].GetComponent <Terrain>(); if (ter != null) { terrains.Add(ter); } Terrain[] trs = objs[i].GetComponentsInChildren <Terrain>(); for (int x = 0; x < trs.Length; ++x) { if (!terrains.Contains(trs[x])) { terrains.Add(trs[x]); } } } // setup this terrain Terrain terrain = t.GetComponent <Terrain>(); t.templateMaterial = MicroSplatShaderGUI.NewShaderAndMaterial(terrain); var config = TextureArrayConfigEditor.CreateConfig(terrain); t.templateMaterial.SetTexture("_Diffuse", config.diffuseArray); t.templateMaterial.SetTexture("_NormalSAO", config.normalSAOArray); t.propData = MicroSplatShaderGUI.FindOrCreatePropTex(t.templateMaterial); if (terrain.terrainData.splatPrototypes.Length > 0) { var uvScale = terrain.terrainData.splatPrototypes[0].tileSize; var uvOffset = terrain.terrainData.splatPrototypes[0].tileOffset; uvScale = MicroSplatRuntimeUtil.UnityUVScaleToUVScale(uvScale, terrain); uvOffset.x = uvScale.x / terrain.terrainData.size.x * 0.5f * uvOffset.x; uvOffset.y = uvScale.y / terrain.terrainData.size.x * 0.5f * uvOffset.y; Vector4 scaleOffset = new Vector4(uvScale.x, uvScale.y, uvOffset.x, uvOffset.y); t.templateMaterial.SetVector("_UVScale", scaleOffset); } // now make sure others all have the same settings as well. for (int i = 0; i < terrains.Count; ++i) { var nt = terrains[i]; var mgr = nt.GetComponent <MicroSplatTerrain>(); if (mgr == null) { mgr = nt.gameObject.AddComponent <MicroSplatTerrain>(); } mgr.templateMaterial = t.templateMaterial; if (mgr.propData == null) { mgr.propData = MicroSplatShaderGUI.FindOrCreatePropTex(mgr.templateMaterial); } } Selection.SetActiveObjectWithContext(config, config); } MicroSplatTerrain.SyncAll(); return; } if (t.propData == null) { t.propData = MicroSplatShaderGUI.FindOrCreatePropTex(t.templateMaterial); } #if __MICROSPLAT_TERRAINBLEND__ || __MICROSPLAT_STREAMS__ DoTerrainDescGUI(); #endif // could move this to some type of interfaced component created by the module if this becomes a thing, // but I think this will be most of the cases? MicroSplatUtilities.DrawTextureField(t, geoTexOverride, ref t.geoTextureOverride, "_GEOMAP"); MicroSplatUtilities.DrawTextureField(t, geoTintOverride, ref t.tintMapOverride, "_GLOBALTINT"); MicroSplatUtilities.DrawTextureField(t, geoNormalOverride, ref t.globalNormalOverride, "_GLOBALNORMALS"); #if __MICROSPLAT_ADVANCED_DETAIL__ DrawAdvancedModuleDetailGUI(t); #endif if (t.templateMaterial.IsKeywordEnabled("_VSGRASSMAP")) { EditorGUI.BeginChangeCheck(); t.vsGrassMap = EditorGUILayout.ObjectField(CVSGrassMap, t.vsGrassMap, typeof(Texture2D), false) as Texture2D; if (EditorGUI.EndChangeCheck()) { EditorUtility.SetDirty(t); } } if (t.templateMaterial.IsKeywordEnabled("_VSSHADOWMAP")) { EditorGUI.BeginChangeCheck(); t.vsShadowMap = EditorGUILayout.ObjectField(CVSShadowMap, t.vsShadowMap, typeof(Texture2D), false) as Texture2D; if (EditorGUI.EndChangeCheck()) { EditorUtility.SetDirty(t); } } EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Sync")) { var mgr = target as MicroSplatTerrain; mgr.Sync(); } if (GUILayout.Button("Sync All")) { MicroSplatTerrain.SyncAll(); } EditorGUILayout.EndHorizontal(); BakingGUI(t); WeightLimitingGUI(t); #if __MICROSPLAT_ADVANCED_DETAIL__ DrawAdvancedModuleDetailTooset(t); #endif if (MicroSplatUtilities.DrawRollup("Debug", false, true)) { EditorGUI.indentLevel += 2; EditorGUILayout.HelpBox("These should not need to be edited unless something funky has happened. They are automatically managed by MicroSplat.", MessageType.Info); t.propData = EditorGUILayout.ObjectField("Per Texture Data", t.propData, typeof(MicroSplatPropData), false) as MicroSplatPropData; t.blendMat = EditorGUILayout.ObjectField(CBlendMat, t.blendMat, typeof(Material), false) as Material; t.terrainDesc = EditorGUILayout.ObjectField("Terrain Descriptor", t.terrainDesc, typeof(Texture2D), false) as Texture2D; t.addPass = EditorGUILayout.ObjectField("Add Pass", t.addPass, typeof(Shader), false) as Shader; EditorGUI.indentLevel -= 2; } if (EditorGUI.EndChangeCheck()) { EditorUtility.SetDirty(t); } }
public override void OnInspectorGUI() { MicroSplatTerrain t = target as MicroSplatTerrain; if (t == null) { EditorGUILayout.HelpBox("No Terrain Present, please put this component on a terrain", MessageType.Error); return; } EditorGUI.BeginChangeCheck(); t.templateMaterial = EditorGUILayout.ObjectField(CTemplateMaterial, t.templateMaterial, typeof(Material), false) as Material; if (t.templateMaterial == null) { if (GUILayout.Button("Convert to MicroSplat")) { // get all terrains in selection, not just this one, and treat as one giant terrain var objs = Selection.gameObjects; List <Terrain> terrains = new List <Terrain>(); for (int i = 0; i < objs.Length; ++i) { Terrain ter = objs[i].GetComponent <Terrain>(); if (ter != null) { terrains.Add(ter); } Terrain[] trs = objs[i].GetComponentsInChildren <Terrain>(); for (int x = 0; x < trs.Length; ++x) { if (!terrains.Contains(trs[x])) { terrains.Add(trs[x]); } } } // setup this terrain Terrain terrain = t.GetComponent <Terrain>(); t.templateMaterial = MicroSplatShaderGUI.NewShaderAndMaterial(terrain); var config = TextureArrayConfigEditor.CreateConfig(terrain); t.templateMaterial.SetTexture("_Diffuse", config.diffuseArray); t.templateMaterial.SetTexture("_NormalSAO", config.normalSAOArray); t.propData = MicroSplatShaderGUI.FindOrCreatePropTex(t.templateMaterial); #if UNITY_2018_3_OR_NEWER if (terrain.terrainData.terrainLayers.Length > 0) { var uvScale = terrain.terrainData.terrainLayers[0].tileSize; var uvOffset = terrain.terrainData.terrainLayers[0].tileOffset; uvScale = MicroSplatRuntimeUtil.UnityUVScaleToUVScale(uvScale, terrain); uvOffset.x = uvScale.x / terrain.terrainData.size.x * 0.5f * uvOffset.x; uvOffset.y = uvScale.y / terrain.terrainData.size.x * 0.5f * uvOffset.y; Vector4 scaleOffset = new Vector4(uvScale.x, uvScale.y, uvOffset.x, uvOffset.y); t.templateMaterial.SetVector("_UVScale", scaleOffset); } #else if (terrain.terrainData.splatPrototypes.Length > 0) { var uvScale = terrain.terrainData.splatPrototypes[0].tileSize; var uvOffset = terrain.terrainData.splatPrototypes[0].tileOffset; uvScale = MicroSplatRuntimeUtil.UnityUVScaleToUVScale(uvScale, terrain); uvOffset.x = uvScale.x / terrain.terrainData.size.x * 0.5f * uvOffset.x; uvOffset.y = uvScale.y / terrain.terrainData.size.x * 0.5f * uvOffset.y; Vector4 scaleOffset = new Vector4(uvScale.x, uvScale.y, uvOffset.x, uvOffset.y); t.templateMaterial.SetVector("_UVScale", scaleOffset); } #endif // now make sure others all have the same settings as well. for (int i = 0; i < terrains.Count; ++i) { var nt = terrains[i]; var mgr = nt.GetComponent <MicroSplatTerrain>(); if (mgr == null) { mgr = nt.gameObject.AddComponent <MicroSplatTerrain>(); } mgr.templateMaterial = t.templateMaterial; if (mgr.propData == null) { mgr.propData = MicroSplatShaderGUI.FindOrCreatePropTex(mgr.templateMaterial); } } Selection.SetActiveObjectWithContext(config, config); } MicroSplatTerrain.SyncAll(); return; } if (t.propData == null) { t.propData = MicroSplatShaderGUI.FindOrCreatePropTex(t.templateMaterial); EditorUtility.SetDirty(t); } if (t.keywordSO == null) { t.keywordSO = MicroSplatUtilities.FindOrCreateKeywords(t.templateMaterial); EditorUtility.SetDirty(t); } EditorGUI.BeginChangeCheck(); #if __MICROSPLAT_PROCTEX__ if (t.keywordSO.IsKeywordEnabled("_PROCEDURALTEXTURE") || t.keywordSO.IsKeywordEnabled("_PCHEIGHTGRADIENT") || t.keywordSO.IsKeywordEnabled("_PCHEIGHTHSV")) { var old = t.procTexCfg; t.procTexCfg = MicroSplatProceduralTexture.FindOrCreateProceduralConfig(t.templateMaterial); if (old != t.procTexCfg) { EditorUtility.SetDirty(t); } } #endif #if __MICROSPLAT_TERRAINBLEND__ || __MICROSPLAT_STREAMS__ DoTerrainDescGUI(); #endif DoPerPixelNormalGUI(); #if __MICROSPLAT_PROCTEX__ if (t.keywordSO.IsKeywordEnabled(MicroSplatProceduralTexture.GetFeatureName(MicroSplatProceduralTexture.DefineFeature._PCCAVITY)) || t.keywordSO.IsKeywordEnabled(MicroSplatProceduralTexture.GetFeatureName(MicroSplatProceduralTexture.DefineFeature._PCFLOW))) { DoCavityMapGUI(); } #endif // could move this to some type of interfaced component created by the module if this becomes a thing, // but I think this will be most of the cases? MicroSplatUtilities.DrawTextureField(t, CCustomSplat0, ref t.customControl0, "_CUSTOMSPLATTEXTURES"); MicroSplatUtilities.DrawTextureField(t, CCustomSplat1, ref t.customControl1, "_CUSTOMSPLATTEXTURES"); MicroSplatUtilities.DrawTextureField(t, CCustomSplat2, ref t.customControl2, "_CUSTOMSPLATTEXTURES"); MicroSplatUtilities.DrawTextureField(t, CCustomSplat3, ref t.customControl3, "_CUSTOMSPLATTEXTURES"); MicroSplatUtilities.DrawTextureField(t, CCustomSplat4, ref t.customControl4, "_CUSTOMSPLATTEXTURES"); MicroSplatUtilities.DrawTextureField(t, CCustomSplat5, ref t.customControl5, "_CUSTOMSPLATTEXTURES"); MicroSplatUtilities.DrawTextureField(t, CCustomSplat6, ref t.customControl6, "_CUSTOMSPLATTEXTURES"); MicroSplatUtilities.DrawTextureField(t, CCustomSplat7, ref t.customControl7, "_CUSTOMSPLATTEXTURES"); // perpixel normal MicroSplatUtilities.DrawTextureField(t, perPixelNormal, ref t.perPixelNormal, "_PERPIXELNORMAL"); // global texture overrides #if __MICROSPLAT_GLOBALTEXTURE__ MicroSplatUtilities.DrawTextureField(t, geoTexOverride, ref t.geoTextureOverride, "_GEOMAP"); MicroSplatUtilities.DrawTextureField(t, geoTintOverride, ref t.tintMapOverride, "_GLOBALTINT"); MicroSplatUtilities.DrawTextureField(t, geoNormalOverride, ref t.globalNormalOverride, "_GLOBALNORMALS"); MicroSplatUtilities.DrawTextureField(t, geoSAOMOverride, ref t.globalSAOMOverride, "_GLOBALSMOOTHAOMETAL"); MicroSplatUtilities.DrawTextureField(t, geoEmisOverride, ref t.globalEmisOverride, "_GLOBALEMIS"); #endif #if __MICROSPLAT_ALPHAHOLE__ // alpha hole override MicroSplatUtilities.DrawTextureField(t, clipMapOverride, ref t.clipMap, "_ALPHAHOLETEXTURE"); #endif #if (VEGETATION_STUDIO || VEGETATION_STUDIO_PRO) // vsstudio overrides MicroSplatUtilities.DrawTextureField(t, CVSGrassMap, ref t.vsGrassMap, "_VSGRASSMAP"); MicroSplatUtilities.DrawTextureField(t, CVSShadowMap, ref t.vsShadowMap, "_VSSHADOWMAP"); #endif #if __MICROSPLAT_PROCTEX__ MicroSplatUtilities.DrawTextureField(t, biomeOverride, ref t.procBiomeMask, "_PROCEDURALTEXTURE"); #endif #if __MICROSPLAT_ADVANCED_DETAIL__ DrawAdvancedModuleDetailGUI(t); #endif if (t.propData == null && t.templateMaterial != null) { t.propData = MicroSplatShaderGUI.FindOrCreatePropTex(t.templateMaterial); if (t.propData == null) { // this should really never happen, but users seem to have issues with unassigned propData's a lot. I think // this is from external tools like MapMagic not creating it, but the above call should create it. EditorGUILayout.HelpBox("PropData is null, please assign", MessageType.Error); t.propData = EditorGUILayout.ObjectField("Per Texture Data", t.propData, typeof(MicroSplatPropData), false) as MicroSplatPropData; } } if (EditorGUI.EndChangeCheck()) { MicroSplatTerrain.SyncAll(); } EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Sync")) { var mgr = target as MicroSplatTerrain; mgr.Sync(); } if (GUILayout.Button("Sync All")) { MicroSplatTerrain.SyncAll(); } EditorGUILayout.EndHorizontal(); BakingGUI(t); WeightLimitingGUI(t); ImportExportGUI(); #if __MICROSPLAT_ADVANCED_DETAIL__ DrawAdvancedModuleDetailTooset(t); #endif if (MicroSplatUtilities.DrawRollup("Debug", false, true)) { EditorGUI.indentLevel += 2; EditorGUILayout.HelpBox("These should not need to be edited unless something funky has happened. They are automatically managed by MicroSplat.", MessageType.Info); t.propData = EditorGUILayout.ObjectField("Per Texture Data", t.propData, typeof(MicroSplatPropData), false) as MicroSplatPropData; #if __MICROSPLAT_PROCTEX__ t.procTexCfg = EditorGUILayout.ObjectField("Procedural Config", t.procTexCfg, typeof(MicroSplatProceduralTextureConfig), false) as MicroSplatProceduralTextureConfig; #endif t.keywordSO = EditorGUILayout.ObjectField("Keywords", t.keywordSO, typeof(MicroSplatKeywords), false) as MicroSplatKeywords; t.blendMat = EditorGUILayout.ObjectField(CBlendMat, t.blendMat, typeof(Material), false) as Material; t.terrainDesc = EditorGUILayout.ObjectField("Terrain Descriptor", t.terrainDesc, typeof(Texture2D), false) as Texture2D; t.perPixelNormal = EditorGUILayout.ObjectField("Normal Data", t.perPixelNormal, typeof(Texture2D), false) as Texture2D; t.addPass = EditorGUILayout.ObjectField("Add Pass", t.addPass, typeof(Shader), false) as Shader; EditorGUI.indentLevel -= 2; } if (EditorGUI.EndChangeCheck()) { EditorUtility.SetDirty(t); } }
bool DoConvertGUI(MicroSplatTerrain t) { if (t.templateMaterial == null) { InitConvertConfigs(); using (new GUILayout.VerticalScope(GUI.skin.box)) { EditorGUILayout.LabelField("Select a Template:"); EditorGUILayout.BeginHorizontal(); for (int i = 0; i < convertConfigs.Count; ++i) { var c = convertConfigs [i]; if (DrawConvertButton(c, i == selectedConvertConfig)) { selectedConvertConfig = i; } } EditorGUILayout.EndHorizontal(); var selectedConfig = convertConfigs [selectedConvertConfig]; if (selectedConfig.missingModules.Count > 0) { EditorGUILayout.HelpBox("You are missing some MicroSplat modules needed by this template. The preset may still be used but some features will not be enabled. Missing modules are listed below:", MessageType.Warning); for (int i = 0; i < selectedConfig.missingModules.Count; ++i) { var m = selectedConfig.missingModules [i]; DrawMissingModule(m); } } EditorGUILayout.LabelField("Select any integrations you want to add:"); // integrations for (int i = 0; i < integrationConfigs.Count; ++i) { var ic = integrationConfigs [i]; if (!ic.assetInstalled) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(ic.name, GUILayout.Width(120)); EditorGUILayout.LabelField("Not Installed", GUILayout.Width(120)); if (GUILayout.Button("Link", GUILayout.Width(120))) { Application.OpenURL(ic.assetLink); } EditorGUILayout.EndHorizontal(); } else { EditorGUILayout.BeginHorizontal(); ic.include = EditorGUILayout.Toggle(ic.include, GUILayout.Width(20)); EditorGUILayout.LabelField(ic.name); EditorGUILayout.EndHorizontal(); if (ic.include && ic.missingModules.Count > 0) { using (new GUILayout.VerticalScope(GUI.skin.box)) { EditorGUILayout.HelpBox("Some MicroSplat modules requested by this module are not installed. Some or all features of the integration will not be active.", MessageType.Warning); for (int j = 0; j < ic.missingModules.Count; ++j) { var m = ic.missingModules [j]; DrawMissingModule(m); } } } } } if (GUILayout.Button("Convert to MicroSplat")) { // get all terrains in selection, not just this one, and treat as one giant terrain var objs = Selection.gameObjects; List <Terrain> terrains = new List <Terrain> (); for (int i = 0; i < objs.Length; ++i) { Terrain ter = objs [i].GetComponent <Terrain> (); if (ter != null) { terrains.Add(ter); } Terrain [] trs = objs [i].GetComponentsInChildren <Terrain> (); for (int x = 0; x < trs.Length; ++x) { if (!terrains.Contains(trs [x])) { terrains.Add(trs [x]); } } } Terrain terrain = t.GetComponent <Terrain> (); int texcount = 16; #if UNITY_2018_3_OR_NEWER texcount = terrain.terrainData.terrainLayers.Length; #else texcount = terrain.terrainData.splatPrototypes.Length; #endif List <string> keywords = new List <string> (selectedConfig.keywords); if (texcount <= 4) { keywords.Add("_MAX4TEXTURES"); } else if (texcount <= 8) { keywords.Add("_MAX8TEXTURES"); } else if (texcount <= 12) { keywords.Add("_MAX12TEXTURES"); } else if (texcount <= 20) { keywords.Add("_MAX20TEXTURES"); } else if (texcount <= 24) { keywords.Add("_MAX24TEXTURES"); } else if (texcount <= 28) { keywords.Add("_MAX28TEXTURES"); } else if (texcount > 28) { keywords.Add("_MAX32TEXTURES"); } for (int i = 0; i < integrationConfigs.Count; ++i) { var ic = integrationConfigs [i]; if (ic.include) { keywords.AddRange(ic.keywords); } } // setup this terrain t.templateMaterial = MicroSplatShaderGUI.NewShaderAndMaterial(terrain, keywords.ToArray()); var config = TextureArrayConfigEditor.CreateConfig(terrain); t.templateMaterial.SetTexture("_Diffuse", config.diffuseArray); t.templateMaterial.SetTexture("_NormalSAO", config.normalSAOArray); t.propData = MicroSplatShaderGUI.FindOrCreatePropTex(t.templateMaterial); #if UNITY_2018_3_OR_NEWER if (terrain.terrainData.terrainLayers.Length > 0) { var uvScale = terrain.terrainData.terrainLayers[0].tileSize; var uvOffset = terrain.terrainData.terrainLayers[0].tileOffset; uvScale = MicroSplatRuntimeUtil.UnityUVScaleToUVScale(uvScale, terrain); uvOffset.x = uvScale.x / terrain.terrainData.size.x * 0.5f * uvOffset.x; uvOffset.y = uvScale.y / terrain.terrainData.size.x * 0.5f * uvOffset.y; Vector4 scaleOffset = new Vector4(uvScale.x, uvScale.y, uvOffset.x, uvOffset.y); t.templateMaterial.SetVector("_UVScale", scaleOffset); } #else if (terrain.terrainData.splatPrototypes.Length > 0) { var uvScale = terrain.terrainData.splatPrototypes [0].tileSize; var uvOffset = terrain.terrainData.splatPrototypes [0].tileOffset; uvScale = MicroSplatRuntimeUtil.UnityUVScaleToUVScale(uvScale, terrain); uvOffset.x = uvScale.x / terrain.terrainData.size.x * 0.5f * uvOffset.x; uvOffset.y = uvScale.y / terrain.terrainData.size.x * 0.5f * uvOffset.y; Vector4 scaleOffset = new Vector4(uvScale.x, uvScale.y, uvOffset.x, uvOffset.y); t.templateMaterial.SetVector("_UVScale", scaleOffset); } #endif // we need to set a few things on the material if certain features are enabled. // Test for property existence as module might not be installed and feature was culled. if (System.Array.Exists(selectedConfig.keywords, x => x == "_TRIPLANAR")) { if (t.templateMaterial.HasProperty("_TriplanarUVScale")) { t.templateMaterial.SetVector("_TriplanarUVScale", new Vector4(0.25f, 0.25f, 0, 0)); } } if (System.Array.Exists(selectedConfig.keywords, x => x == "_NORMALNOISE")) { if (t.templateMaterial.HasProperty("_NormalNoise")) { t.templateMaterial.SetTexture("_NormalNoise", MicroSplatUtilities.GetAutoTexture("microsplat_def_detail_normal_01")); } } // now make sure others all have the same settings as well. for (int i = 0; i < terrains.Count; ++i) { var nt = terrains [i]; var mgr = nt.GetComponent <MicroSplatTerrain> (); if (mgr == null) { mgr = nt.gameObject.AddComponent <MicroSplatTerrain> (); } mgr.templateMaterial = t.templateMaterial; if (mgr.propData == null) { mgr.propData = MicroSplatShaderGUI.FindOrCreatePropTex(mgr.templateMaterial); } } Selection.SetActiveObjectWithContext(config, config); t.keywordSO = MicroSplatUtilities.FindOrCreateKeywords(t.templateMaterial); t.keywordSO.keywords.Clear(); t.keywordSO.keywords = new List <string> (keywords); // force recompile, so that basemap shader name gets reset correctly.. MicroSplatShaderGUI.MicroSplatCompiler comp = new MicroSplatShaderGUI.MicroSplatCompiler(); comp.Compile(t.templateMaterial); MicroSplatTerrain.SyncAll(); // trun on draw instanced if enabled and tessellation is disabled, unless render loop is LWRP/URP in which case it does work.. #if UNITY_2018_3_OR_NEWER if (t.keywordSO != null && (!t.keywordSO.IsKeywordEnabled("_TESSDISTANCE") || t.keywordSO.IsKeywordEnabled("_MSRENDERLOOP_UNITYLD"))) { for (int i = 0; i < terrains.Count; ++i) { var nt = terrains [i]; var mgr = nt.GetComponent <MicroSplatTerrain> (); if (mgr != null && mgr.keywordSO != null && !mgr.keywordSO.IsKeywordEnabled("_MSRENDERLOOP_UNITYLD")) { nt.drawInstanced = true; } } } #endif return(true); } } } return(false); }
public override void OnInspectorGUI() { MicroSplatTerrain t = target as MicroSplatTerrain; if (t == null) { EditorGUILayout.HelpBox("No Terrain Present, please put this component on a terrain", MessageType.Error); return; } EditorGUI.BeginChangeCheck(); t.templateMaterial = EditorGUILayout.ObjectField(CTemplateMaterial, t.templateMaterial, typeof(Material), false) as Material; t.propData = EditorGUILayout.ObjectField("Per Texture Data", t.propData, typeof(MicroSplatPropData), false) as MicroSplatPropData; if (EditorGUI.EndChangeCheck()) { EditorUtility.SetDirty(t); } if (t.templateMaterial == null) { if (GUILayout.Button("Convert to MicroSplat")) { // get all terrains in selection, not just this one, and treat as one giant terrain var objs = Selection.gameObjects; List <Terrain> terrains = new List <Terrain>(); for (int i = 0; i < objs.Length; ++i) { Terrain ter = objs[i].GetComponent <Terrain>(); if (ter != null) { terrains.Add(ter); } Terrain[] trs = objs[i].GetComponentsInChildren <Terrain>(); for (int x = 0; x < trs.Length; ++x) { if (!terrains.Contains(trs[x])) { terrains.Add(trs[x]); } } } // setup this terrain Terrain terrain = t.GetComponent <Terrain>(); t.templateMaterial = MicroSplatShaderGUI.NewShaderAndMaterial(terrain); var config = TextureArrayConfigEditor.CreateConfig(terrain); t.templateMaterial.SetTexture("_Diffuse", config.diffuseArray); t.templateMaterial.SetTexture("_NormalSAO", config.normalSAOArray); t.propData = MicroSplatShaderGUI.FindOrCreatePropTex(t.templateMaterial); bool perTexScaleOffset = false; if (terrain.terrainData.splatPrototypes.Length > 0) { var uvScale = terrain.terrainData.splatPrototypes[0].tileSize; var uvOffset = terrain.terrainData.splatPrototypes[0].tileOffset; for (int i = 1; i < terrain.terrainData.splatPrototypes.Length; ++i) { if (uvScale != terrain.terrainData.splatPrototypes[0].tileSize || uvOffset != terrain.terrainData.splatPrototypes[0].tileOffset) { perTexScaleOffset = true; } } if (!perTexScaleOffset) { uvScale = MicroSplatRuntimeUtil.UnityUVScaleToUVScale(uvScale, terrain); uvOffset.x = uvScale.x / terrain.terrainData.size.x * 0.5f * uvOffset.x; uvOffset.y = uvScale.y / terrain.terrainData.size.x * 0.5f * uvOffset.y; Vector4 scaleOffset = new Vector4(uvScale.x, uvScale.y, uvOffset.x, uvOffset.y); t.templateMaterial.SetVector("_UVScale", scaleOffset); } } if (perTexScaleOffset) { t.templateMaterial.SetVector("_UVScale", new Vector4(1, 1, 0, 0)); t.templateMaterial.EnableKeyword("_PERTEXUVSCALE"); t.templateMaterial.EnableKeyword("_PERTEXUVOFFSET"); var propTex = MicroSplatShaderGUI.FindOrCreatePropTex(t.templateMaterial); // set per tex props for each texture for (int i = 0; i < terrain.terrainData.splatPrototypes.Length; ++i) { var uvScale = terrain.terrainData.splatPrototypes[i].tileSize; var uvOffset = terrain.terrainData.splatPrototypes[i].tileOffset; uvScale = MicroSplatRuntimeUtil.UnityUVScaleToUVScale(uvScale, terrain); uvOffset.x = uvScale.x / terrain.terrainData.size.x * 0.5f * uvOffset.x; uvOffset.y = uvScale.y / terrain.terrainData.size.x * 0.5f * uvOffset.y; Color c = new Color(uvScale.x, uvScale.y, uvOffset.x, uvOffset.y); propTex.SetValue(i, 0, c); } } // now make sure others all have the same settings as well. for (int i = 0; i < terrains.Count; ++i) { var nt = terrains[i]; var mgr = nt.GetComponent <MicroSplatTerrain>(); if (mgr == null) { mgr = nt.gameObject.AddComponent <MicroSplatTerrain>(); } mgr.templateMaterial = t.templateMaterial; if (mgr.propData == null) { mgr.propData = MicroSplatShaderGUI.FindOrCreatePropTex(mgr.templateMaterial); } } Selection.SetActiveObjectWithContext(config, config); } MicroSplatTerrain.SyncAll(); return; } if (t.propData == null) { t.propData = MicroSplatShaderGUI.FindOrCreatePropTex(t.templateMaterial); } #if __MICROSPLAT_TERRAINBLEND__ || __MICROSPLAT_STREAMS__ DoTerrainDescGUI(); #endif // could move this to some type of interfaced component created by the module if this becomes a thing, // but I think this will be most of the cases? MicroSplatUtilities.DrawTextureField(t, geoTexOverride, ref t.geoTextureOverride, "_GEOMAP"); MicroSplatUtilities.DrawTextureField(t, geoTintOverride, ref t.tintMapOverride, "_GLOBALTINT"); MicroSplatUtilities.DrawTextureField(t, geoNormalOverride, ref t.globalNormalOverride, "_GLOBALNORMALS"); MicroSplatUtilities.DrawTextureField(t, AdvDetailControl, ref t.advDetailControl, "_ADVANCED_DETAIL"); if (t.templateMaterial.IsKeywordEnabled("_VSGRASSMAP")) { EditorGUI.BeginChangeCheck(); t.vsGrassMap = EditorGUILayout.ObjectField(CVSGrassMap, t.vsGrassMap, typeof(Texture2D), false) as Texture2D; if (EditorGUI.EndChangeCheck()) { EditorUtility.SetDirty(t); } } if (t.templateMaterial.IsKeywordEnabled("_VSSHADOWMAP")) { EditorGUI.BeginChangeCheck(); t.vsShadowMap = EditorGUILayout.ObjectField(CVSShadowMap, t.vsShadowMap, typeof(Texture2D), false) as Texture2D; if (EditorGUI.EndChangeCheck()) { EditorUtility.SetDirty(t); } } EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Sync")) { var mgr = target as MicroSplatTerrain; mgr.Sync(); } if (GUILayout.Button("Sync All")) { MicroSplatTerrain.SyncAll(); } EditorGUILayout.EndHorizontal(); BakingGUI(t); WeightLimitingGUI(t); }