internal void InitializeDefaults(Terrain terrain, int index) { this.m_Terrain = terrain; this.m_PrototypeIndex = index; DetailPrototype detailPrototype = this.m_PrototypeIndex != -1 ? this.m_Terrain.terrainData.detailPrototypes[this.m_PrototypeIndex] : new DetailPrototype(); this.m_Detail = detailPrototype.prototype; this.m_NoiseSpread = detailPrototype.noiseSpread; this.m_MinWidth = detailPrototype.minWidth; this.m_MaxWidth = detailPrototype.maxWidth; this.m_MinHeight = detailPrototype.minHeight; this.m_MaxHeight = detailPrototype.maxHeight; this.m_HealthyColor = detailPrototype.healthyColor; this.m_DryColor = detailPrototype.dryColor; switch (detailPrototype.renderMode) { case DetailRenderMode.GrassBillboard: Debug.LogError((object) "Detail meshes can't be rendered as billboards"); this.m_RenderMode = DetailMeshRenderMode.Grass; break; case DetailRenderMode.VertexLit: this.m_RenderMode = DetailMeshRenderMode.VertexLit; break; case DetailRenderMode.Grass: this.m_RenderMode = DetailMeshRenderMode.Grass; break; } this.OnWizardUpdate(); }
void OnWizardUpdate() { this.helpString = "This tool exports the splatmap (layer weight texture) of a terrain to a PNG image.\n"+ "Optionally, the alpha channel is saved to a separate image.\n"; if( Selection.activeGameObject != null ) this.terrain = Selection.activeGameObject.GetComponent<Terrain>(); if(this.terrain == null) this.terrain = GameObject.FindObjectOfType(typeof(Terrain)) as Terrain; this.isValid = this.terrain != null && this.terrain.terrainData != null; }
internal void InitializeDefaults(Terrain terrain, int index) { this.m_Terrain = terrain; this.m_PrototypeIndex = index; DetailPrototype detailPrototype; if (this.m_PrototypeIndex == -1) { detailPrototype = new DetailPrototype(); detailPrototype.renderMode = DetailRenderMode.GrassBillboard; } else { detailPrototype = this.m_Terrain.terrainData.detailPrototypes[this.m_PrototypeIndex]; } this.m_DetailTexture = detailPrototype.prototypeTexture; this.m_MinWidth = detailPrototype.minWidth; this.m_MaxWidth = detailPrototype.maxWidth; this.m_MinHeight = detailPrototype.minHeight; this.m_MaxHeight = detailPrototype.maxHeight; this.m_NoiseSpread = detailPrototype.noiseSpread; this.m_HealthyColor = detailPrototype.healthyColor; this.m_DryColor = detailPrototype.dryColor; this.m_Billboard = (detailPrototype.renderMode == DetailRenderMode.GrassBillboard); this.OnWizardUpdate(); }
private void InitializeDefaults(Terrain terrain) { base.m_Terrain = terrain; object[] objArray1 = new object[] { "Width ", terrain.terrainData.heightmapWidth, " Height ", terrain.terrainData.heightmapHeight }; base.helpString = string.Concat(objArray1); this.OnWizardUpdate(); }
public static void SplitTerrainIntoWorldCells( OpenWorldSettings openWorldSettings, UnityEngine.Terrain terrainToSplit, int heightMapResolution, int alphaMapResolution, int detailMapResolution ) { int splits = UnityTools.TerrainTools.CalculateChunksInTerrain(terrainToSplit, openWorldSettings.cellSize); int maxGrids = openWorldSettings.gridResolution; if (splits > maxGrids) { Debug.LogError("Splitting would require: " + splits + "x" + splits + " cell resolution..., current max is: " + maxGrids + "x" + maxGrids + ". Try increasing cell size or cell resolution..."); return; } GameSettingsList.disableRefresh = true; Dictionary <Vector2Int, UnityEngine.Terrain> splitTerrains = UnityTools.TerrainTools.SplitTerrainIntoChunks( terrainToSplit, openWorldSettings.cellSize, heightMapResolution, alphaMapResolution, detailMapResolution ); if (splitTerrains != null) { SplitTerrainsIntoScenes(openWorldSettings, splitTerrains); } GameSettingsList.disableRefresh = false; }
public static Vector3 DeriveScale(Terrain terrain, float resolution , out int widthCount, out int depthCount) { widthCount = 0; depthCount = 0; if (terrain == null || terrain.terrainData == null || resolution <= 0) return Vector3.zero; Vector3 scale = terrain.terrainData.heightmapScale; widthCount = terrain.terrainData.heightmapWidth; depthCount = terrain.terrainData.heightmapHeight; if (resolution > 0 && resolution < 1) { Vector3 size = terrain.terrainData.size; widthCount = Mathf.FloorToInt(size.x / scale.x * resolution); depthCount = Mathf.FloorToInt(size.z / scale.z * resolution); scale.x = size.x / (float)widthCount; scale.z = size.z / (float)depthCount; // For the vertices along the maximum bounds... widthCount++; depthCount++; } return scale; }
private void Start() { Terrain = GetComponent <UnityEngine.Terrain>(); Terrain.SetNeighbors(_left, _top, _right, _bottom); TerrainManager.Instance.RegisterTerrain(this); }
public void setNeighbors(TerrainEntity left, TerrainEntity top, TerrainEntity right, TerrainEntity bottom) { UnityTerrain left_terrain = null; UnityTerrain top_terrain = null; UnityTerrain right_terrain = null; UnityTerrain bottom_terrain = null; if (left != null) { left_terrain = left.terrain; } if (top != null) { top_terrain = top.terrain; } if (right != null) { right_terrain = right.terrain; } if (bottom != null) { bottom_terrain = bottom.terrain; } this.terrain.SetNeighbors(left_terrain, top_terrain, right_terrain, bottom_terrain); }
/// <summary> /// Computes positions for this Tile and caches /// them. /// </summary> public void ComputePositions() { Positions = new PositionsContainer[Pool._placer.ObjectsToPlace.Count]; UnityEngine.Terrain t = Tile.MeshManager.ActiveTerrain; float amp = TerraConfig.Instance.Generator.Amplitude; for (int i = 0; i < Positions.Length; i++) { ObjectDetailNode objectPlacementData = Pool._placer.ObjectsToPlace[i]; Vector2[] samples = objectPlacementData.SamplePositions(Tile.Random); List <Vector3> worldPositions = new List <Vector3>((int)(Positions.Length * 0.66f)); for (var j = 0; j < samples.Length; j++) { Vector2 pos = samples[j]; float height = t.terrainData.GetInterpolatedHeight(pos.x, pos.y); float angle = Vector3.Angle(Vector3.up, t.terrainData.GetInterpolatedNormal(pos.x, pos.y)) / 90; Vector2 world = MathUtil.NormalToWorld(Tile.GridPosition, pos); if (objectPlacementData.ShouldPlaceAt(world.x, world.y, height / amp, angle)) { worldPositions.Add(new Vector3(world.x, height, world.y)); } } Positions[i] = new PositionsContainer(worldPositions.ToArray(), objectPlacementData); } }
public static void CacheTextures() { Debug.Log("Caching Terrain splatmap lookups, please wait..."); UnityEngine.Terrain activeTerrain = UnityEngine.Terrain.activeTerrain; TerrainData terrainData = activeTerrain.terrainData; Vector3 position = activeTerrain.transform.position; float[,,] numArray = terrainData.GetAlphamaps(0, 0, terrainData.alphamapWidth, terrainData.alphamapHeight); textures = new byte[numArray.GetUpperBound(0) + 1, numArray.GetUpperBound(1) + 1]; for (int i = 0; i < terrainData.alphamapWidth; i++) { for (int j = 0; j < terrainData.alphamapHeight; j++) { float num3 = 0f; int num4 = 0; for (int k = 0; k < (numArray.GetUpperBound(2) + 1); k++) { if (numArray[i, j, k] >= num3) { num4 = k; num3 = numArray[i, j, k]; } } textures[i, j] = (byte)num4; } } GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); }
/// <summary> /// Adds a <see cref="UnityEngine.Terrain"/> component to this <see cref="Tile"/>'s /// gameobject and sets it up according to <see cref="TerraConfig"/>. /// Overwrites <see cref="ActiveTerrain"/> if it already exists. /// </summary> public void AddTerrainComponent() { //Destory current Terrain instance if it exists if (ActiveTerrain != null) { #if UNITY_EDITOR UnityEngine.Object.DestroyImmediate(ActiveTerrain); #else UnityEngine.Object.Destroy(ActiveTerrain); #endif } TerraConfig conf = TerraConfig.Instance; int length = conf.Generator.Length; UnityEngine.Terrain t = _tile.gameObject.AddComponent <UnityEngine.Terrain>(); t.terrainData = new TerrainData(); t.terrainData.size = new Vector3(length, conf.Generator.Amplitude, length); t.allowAutoConnect = true; t.drawInstanced = true; TerrainCollider tc = _tile.gameObject.AddComponent <TerrainCollider>(); tc.terrainData = t.terrainData; t.materialTemplate = conf.Generator.TerrainMaterial != null ? conf.Generator.TerrainMaterial : GetDefaultTerrainMaterial(); }
public static void Apply(TextAsset heightmap, UnityEngine.Terrain terrain, AnimationCurve curve) { float[,] array = null; int resolution = 0; #pragma warning disable 219 float sealevel; #pragma warning restore using (System.IO.StreamReader file = new System.IO.StreamReader(AssetDatabase.GetAssetPath(heightmap))) { resolution = System.Convert.ToInt32(file.ReadLine()); sealevel = float.Parse(file.ReadLine()); array = new float[resolution, resolution]; Debug.Log(resolution); long i = 0; while (file.Peek() >= 0) { float v = System.Convert.ToSingle(file.ReadLine()); array[(resolution - 1) - (i / resolution), i % resolution] = curve.Evaluate(v); i++; } } TerrainData data = terrain.terrainData; data.heightmapResolution = resolution; data.baseMapResolution = resolution; data.SetHeights(0, 0, array); EditorUtility.SetDirty(data); EditorUtility.SetDirty(terrain); }
private void Stitch() { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { UnityEngine.Terrain terrain = this.FindTerrain(i, j); if (terrain != null) { Debug.Log("found terrain"); UnityEngine.Terrain left = this.FindTerrain(i - 1, j); UnityEngine.Terrain right = this.FindTerrain(i + 1, j); UnityEngine.Terrain top = this.FindTerrain(i, j + 1); UnityEngine.Terrain bottom = this.FindTerrain(i, j - 1); terrain.SetNeighbors(left, top, right, bottom); if (left == null) { } } else { Debug.Log(string.Concat(new object[] { "couldnt find terrain :", this.name_base, "_x", i, "_y", j })); } } } }
public static void Apply(Texture2D heightmap, UnityEngine.Terrain terrain, AnimationCurve curve) { TerrainData data = terrain.terrainData; data.heightmapResolution = heightmap.width + 1; data.baseMapResolution = heightmap.width; Color32[] pixels = heightmap.GetPixels32(); float[,] heightmapData = new float[heightmap.width, heightmap.height]; for (int y = 0; y < heightmapData.GetLength(1); y++) { for (int x = 0; x < heightmapData.GetLength(0); x++) { float sample = SampleHeightMap(pixels[x * heightmap.width + y], (float)data.heightmapResolution); heightmapData[x, y] = curve.Evaluate(sample); } } for (int y = 0; y < heightmapData.GetLength(1); y++) { for (int x = 0; x < heightmapData.GetLength(0); x++) { heightmapData[x, y] = GetBlurred(x, y, heightmapData); } } data.SetHeights(0, 0, heightmapData); EditorUtility.SetDirty(data); EditorUtility.SetDirty(terrain); }
public override void OnInspectorGUI() { ApplyHeightmap obj = target as ApplyHeightmap; obj.maxHeight = EditorGUILayout.CurveField("height curve", obj.maxHeight, GUILayout.Height(50)); mTerrain = obj.GetComponent <Terrain>(); if (mTerrain == null) { GUILayout.Label("Select a Terrain to apply the heightmap."); } GUILayout.Space(5); GUILayout.Label("Import from Texture", "boldLabel"); obj.mHeightmap = EditorGUILayout.ObjectField("heightmap", obj.mHeightmap, typeof(Texture2D), false) as Texture2D; GUI.enabled = mTerrain != null && obj.mHeightmap != null; if (GUILayout.Button("Height To Terrain")) { Apply(obj.mHeightmap, mTerrain, obj.maxHeight); } GUILayout.Space(5); GUI.enabled = true; GUILayout.Label("Import from Text Asset", "boldLabel"); obj.mHeightmapText = EditorGUILayout.ObjectField("heightmap text", obj.mHeightmapText, typeof(TextAsset), false) as TextAsset; GUI.enabled = mTerrain != null && obj.mHeightmapText != null; if (GUILayout.Button("Height To Terrain")) { Apply(obj.mHeightmapText, mTerrain, obj.maxHeight); } }
public static void RefreshTreeTextures(UnityEngine.Terrain terrain) { if (terrain == null) { throw new NullReferenceException(); } if (!RanOnce) { RanOnce = true; if (AbleToLocateOnTerrainChanged) { try { OnTerrainChanged.Invoke(terrain, TriggerTreeChangeValues); Working = true; return; } catch (Exception exception) { Debug.LogException(exception); Working = false; } } } if (Working) { OnTerrainChanged.Invoke(terrain, TriggerTreeChangeValues); } else { terrain.Flush(); } }
/// <summary> /// Apply height map onto unity terrain. Keep in mind that this will write in the terrain data so make a backup before calling this method /// </summary> /// <param name="terrain">Terrain to apply height map onto</param> /// <param name="heights">Heights to apply</param> public static void ApplyHeightMap(this UnityEngine.Terrain terrain, float[] heights) { int resolution = (int)Mathf.Sqrt(heights.Length); float[,] unityHeights = new float[resolution, resolution]; Vector2 pos = Vector2.zero; for (int i = 0; i < heights.Length; i++) { unityHeights[(int)pos.x, (int)pos.y] = heights[i]; if (pos.x < resolution - 1) { pos.x += 1; } else { pos.x = 0; pos.y += 1; } } terrain.terrainData.SetHeights(0, 0, unityHeights); }
IEnumerator DrawRoads() { yield return(new WaitForSeconds(3f)); UnityEngine.Terrain t = GetComponent <UnityEngine.Terrain>(); Texture2D texture = t.terrainData.splatPrototypes[0].texture; while (true) { for (int x = 0; x < GameManager.WIDTH; x++) { for (int y = 0; y < GameManager.LENGTH; y++) { // texture.SetPixel(y, x, texture.GetPixel(y, x) + (Color.black * Roads[x, y])); if (Roads[x, y] > 0) { float h, s, v; Color.RGBToHSV(texture.GetPixel(x, y), out h, out s, out v); Color c = Color.HSVToRGB(h, s, 1.0f - Roads[x, y]); texture.SetPixel(x, y, c); } } } SplatPrototype splat = new SplatPrototype(); splat.texture = texture; splat.tileOffset = new Vector2(0, 0); splat.tileSize = new Vector2(GameManager.WIDTH, GameManager.LENGTH); splat.texture.Apply(true); t.terrainData.splatPrototypes = new SplatPrototype[] { splat }; yield return(new WaitForSeconds(1f)); } }
internal void InitializeImportRaw(Terrain terrain, string path) { base.m_Terrain = terrain; this.m_Path = path; this.PickRawDefaults(this.m_Path); base.helpString = "Raw files must use a single channel and be either 8 or 16 bit."; this.OnWizardUpdate(); }
/// <summary> /// <para>Schedules an update of the albedo and emissive textures of a system that contains the renderer or the terrain.</para> /// </summary> /// <param name="renderer">The Renderer to use when searching for a system to update.</param> /// <param name="terrain">The Terrain to use when searching for systems to update.</param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="width"></param> /// <param name="height"></param> public static void UpdateMaterials(Terrain terrain) { if ((Object) terrain == (Object) null) throw new ArgumentNullException("terrain"); if ((Object) terrain.terrainData == (Object) null) throw new ArgumentException("Invalid terrainData."); DynamicGI.UpdateMaterialsForTerrain(terrain, new Rect(0.0f, 0.0f, 1f, 1f)); }
internal static void RemoveDetail(Terrain terrain, int index) { TerrainData terrainData = terrain.terrainData; if ((Object) terrainData == (Object) null) return; Undo.RegisterCompleteObjectUndo((Object) terrainData, "Remove detail object"); terrainData.RemoveDetailPrototype(index); }
// Use this for initialization void Start() { ProcedTerrain = GetComponent <UnityEngine.Terrain> (); HeightList = new float[512, 512]; seed = -1; Current = TerrainType.None; PerlinChange = false; }
public static void EnsureInit() { if (cachedTerrain != UnityEngine.Terrain.activeTerrain) { CacheTextures(); cachedTerrain = UnityEngine.Terrain.activeTerrain; } }
public void ProcessSplats(UnityEngine.Terrain t, Vector3 center) { TerrainData data = t.terrainData; var terrainLayers = this.terrainLayers; Vector3 a = center - tileSize; Vector3 b = center + tileSize; data.alphamapResolution = splatSamples; int splatmapKernel = shader.FindKernel(splatmapKernelName); PipeData(shader, splatmapKernel, "Perms"); PipeData(shader, splatmapKernel, "Noises"); PipeData(shader, splatmapKernel, "Ubers"); PipeData(shader, craterData); int size = splatSamples; int layers = terrainLayers.Length; var splatsBuffer = Buffer("Splats", size * size * layers, sizeof(float)); var splats = shader.GetSplats3d(splatsBuffer, a, b, splatSamples, layers, splatmapKernel); for (int xx = 0; xx < size; xx++) { for (int yy = 0; yy < size; yy++) { float sum = 0; for (int layer = 0; layer < layers; layer++) { float val = splats[xx, yy, layer]; sum += val * val; } float nX = xx * 1.0f / (size - 1.0f); float nY = yy * 1.0f / (size - 1.0f); float angle = data.GetSteepness(nY, nX); float slope = Clamp01(angle / slopeAngle); slope = slope * slope * slope; splats[xx, yy, 0] = slope; // Apply normalization and slope for (int layer = 1; layer < layers; layer++) { float val = splats[xx, yy, layer]; val *= val; splats[xx, yy, layer] = (val * (1 - slope)) / sum; } } } data.terrainLayers = terrainLayers; data.RefreshPrototypes(); data.SetAlphamaps(0, 0, splats); data.RefreshPrototypes(); }
private void InitialOneScene(UnityEngine.SceneManagement.Scene scene) { GameObject[] roots = scene.GetRootGameObjects(); int c1 = 0; int c2 = 0; int c3 = 0; int total = 0; for (int i = 0; i < roots.Length; i++) { GameObject obj = roots[i]; UnityEngine.Terrain t = obj.GetComponent <UnityEngine.Terrain>(); if (t == null) { Transform[] trans = obj.GetComponentsInChildren <Transform>(true); for (int j = 0; j < trans.Length; j++) { GameObject child = trans[j].gameObject; Vector2 pos = new Vector2(trans[j].position.x, trans[j].position.z); if (Math.Abs(pos.x) < 4000 && Math.Abs(pos.y) < 4000 && pos.magnitude > 1) { try { if (child.name.StartsWith("Prop") || child.name.ToLower().StartsWith("stone") || child.name.StartsWith("prop")) { if (child.layer == UnityLayerManager.GetLayerIndex(EUnityLayerName.SmallthingNear)) { smallMap.Insert(child, pos); c1++; } else { MidMap.Insert(child, pos); c2++; } } else { map.Insert(child, pos); c3++; } //child.SetActive(false); total++; } catch (Exception e) { _logger.ErrorFormat("culling insert error {0}", e.Message); } } } } } _logger.InfoFormat("culling insert t={4}, s={0},m={1},b={2} at scene {3}", c1, c2, c3, scene.name, total); }
public void Init(Terrain _terrain, MapDataGround.Tile[,] tiles, float[,] height, byte[,] zones) { InitGlobal(); InitWorld(); terrain = _terrain; InitTerrain(tiles, height, zones); }
public override void Setup(Renderer render, IFPV_Object parent) { terrain = GetComponent<Terrain>(); _parent = parent; _render = render; _originalLayer = gameObject.layer; isVisible = true; viewChanged = false; }
internal static void RemoveDetail(Terrain terrain, int index) { TerrainData terrainData = terrain.terrainData; if (terrainData != null) { Undo.RegisterCompleteObjectUndo(terrainData, "Remove detail object"); terrainData.RemoveDetailPrototype(index); } }
internal static void RemoveTree(Terrain terrain, int index) { TerrainData terrainData = terrain.terrainData; if (terrainData == null) { return; } Undo.RegisterCompleteObjectUndo(terrainData, "Remove tree"); terrainData.RemoveTreePrototype(index); }
/// <summary> /// <para>Schedules an update of the albedo and emissive textures of a system that contains the renderer or the terrain.</para> /// </summary> /// <param name="renderer">The Renderer to use when searching for a system to update.</param> /// <param name="terrain">The Terrain to use when searching for systems to update.</param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="width"></param> /// <param name="height"></param> public static void UpdateMaterials(Terrain terrain, int x, int y, int width, int height) { if ((Object) terrain == (Object) null) throw new ArgumentNullException("terrain"); if ((Object) terrain.terrainData == (Object) null) throw new ArgumentException("Invalid terrainData."); float alphamapWidth = (float) terrain.terrainData.alphamapWidth; float alphamapHeight = (float) terrain.terrainData.alphamapHeight; DynamicGI.UpdateMaterialsForTerrain(terrain, new Rect((float) x / alphamapWidth, (float) y / alphamapHeight, (float) width / alphamapWidth, (float) height / alphamapHeight)); }
// for world shifting // public float[] Offset { get; private set; } public void InitForDetail(UnityEngine.Terrain terrain, TerrainData data, float detailDistance, Vector3 basePos) { InitCommon(terrain, data, basePos); _detailDensity = terrain.detailObjectDensity; _detailDistance = detailDistance; _detailResolution = data.detailResolution; _detailResolutionPerPatch = data.detailResolutionPerPatch; }
void OnWizardUpdate() { this.helpString = "This tool replaces the selected terrain's splatmap (layer weight texture) with another image.\n\n" + "The texture format must be uncompressed (set to \"Truecolor\" in inspector).\n\n" + "This tool cannot add or remove texture layers. The terrain must have all its layers defined\n" + "before importing. If only 2 layers are present, just the red and green channels are imported.\n"; if( Selection.activeGameObject != null ) this.terrain = Selection.activeGameObject.GetComponent<Terrain>(); if(this.terrain == null) this.terrain = GameObject.FindObjectOfType(typeof(Terrain)) as Terrain; this.isValid = this.newSplatmap != null && this.terrain != null && this.terrain.terrainData != null; }
private void UpdateMapsNow(Vector3 gridPosition) { UnityEngine.Terrain activeTerrain = UnityEngine.Terrain.activeTerrain; if (activeTerrain != null) { this.probabilityGenerator.UpdateMap(activeTerrain.transform.InverseTransformPoint(gridPosition)); this.levelMaterial.SetTexture("_TextureIndexTex", this.probabilityGenerator.probabilityTexture); this.levelMaterial.SetVector("_TerrainPosition", activeTerrain.transform.position); } }
public TerrainEntity(int x, int z, float[,] height_map, float terrain_height, GameObject game_object, UnityTerrain terrain ) { this.pos_x = x; this.pos_z = z; this.height_map = height_map; this.terrain_height = terrain_height; this.game_object = game_object; this.terrain = terrain; }
private void OnValidate() { if (this.terrain == null) { UnityEngine.Terrain terrain = UnityEngine.Object.FindObjectOfType <UnityEngine.Terrain>(); if (terrain != null) { this.terrain = terrain.gameObject; } } }
public static void Initialize() { if (Loaded == false) { LSDatabase database = LSFSettingsManager.GetSettings ().Database; _currentDatabase = database; Loaded = true; LockstepManager.Setup(); } Terrain = GameObject.FindObjectOfType<Terrain> (); }
public static void PlaceTrees(Terrain terrain, float xBase, float yBase) { if (terrain.terrainData.treePrototypes.Length == 0) { return; } TreePainter.selectedTree = Mathf.Min(TerrainInspectorUtil.GetPrototypeCount(terrain.terrainData) - 1, TreePainter.selectedTree); if (!TerrainInspectorUtil.PrototypeIsRenderable(terrain.terrainData, TreePainter.selectedTree)) { return; } int num = 0; TreeInstance instance = default(TreeInstance); instance.position = new Vector3(xBase, 0f, yBase); instance.color = TreePainter.GetTreeColor(); instance.lightmapColor = Color.white; instance.prototypeIndex = TreePainter.selectedTree; instance.heightScale = TreePainter.GetTreeHeight(); instance.widthScale = ((!TreePainter.lockWidthToHeight) ? TreePainter.GetTreeWidth() : instance.heightScale); instance.rotation = TreePainter.GetTreeRotation(); bool flag = Event.current.type == EventType.MouseDrag || TreePainter.brushSize > 1f; if (!flag || TerrainInspectorUtil.CheckTreeDistance(terrain.terrainData, instance.position, instance.prototypeIndex, TreePainter.spacing)) { terrain.AddTreeInstance(instance); num++; } Vector3 prototypeExtent = TerrainInspectorUtil.GetPrototypeExtent(terrain.terrainData, TreePainter.selectedTree); prototypeExtent.y = 0f; float num2 = TreePainter.brushSize / (prototypeExtent.magnitude * TreePainter.spacing * 0.5f); int num3 = (int)(num2 * num2 * 0.5f); num3 = Mathf.Clamp(num3, 0, 100); int num4 = 1; while (num4 < num3 && num < num3) { Vector2 insideUnitCircle = UnityEngine.Random.insideUnitCircle; insideUnitCircle.x *= TreePainter.brushSize / terrain.terrainData.size.x; insideUnitCircle.y *= TreePainter.brushSize / terrain.terrainData.size.z; Vector3 position = new Vector3(xBase + insideUnitCircle.x, 0f, yBase + insideUnitCircle.y); if (position.x >= 0f && position.x <= 1f && position.z >= 0f && position.z <= 1f && TerrainInspectorUtil.CheckTreeDistance(terrain.terrainData, position, TreePainter.selectedTree, TreePainter.spacing * 0.5f)) { instance = default(TreeInstance); instance.position = position; instance.color = TreePainter.GetTreeColor(); instance.lightmapColor = Color.white; instance.prototypeIndex = TreePainter.selectedTree; instance.heightScale = TreePainter.GetTreeHeight(); instance.widthScale = ((!TreePainter.lockWidthToHeight) ? TreePainter.GetTreeWidth() : instance.heightScale); instance.rotation = TreePainter.GetTreeRotation(); terrain.AddTreeInstance(instance); num++; } num4++; } }
void Start() { EthKeyManager = GetComponentInParent <EthKeyManager>(); LandManager = GetComponentInParent <LandManager>(); Text = GetComponentInChildren <TextMesh>(); Terrain = GetComponentInChildren <Terrain>(); Text.gameObject.SetActive(false); Terrain.gameObject.SetActive(false); }
/// <summary> /// <para>Schedules an update of the albedo and emissive textures of a system that contains the renderer or the terrain.</para> /// </summary> /// <param name="renderer">The Renderer to use when searching for a system to update.</param> /// <param name="terrain">The Terrain to use when searching for systems to update.</param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="width"></param> /// <param name="height"></param> public static void UpdateMaterials(Terrain terrain) { if (terrain == null) { throw new ArgumentNullException("terrain"); } if (terrain.terrainData == null) { throw new ArgumentException("Invalid terrainData."); } UpdateMaterialsForTerrain(terrain, new Rect(0f, 0f, 1f, 1f)); }
static bool DynamicGI_UpdateMaterials__Terrain(JSVCall vc, int argc) { int len = argc; if (len == 1) { UnityEngine.Terrain arg0 = (UnityEngine.Terrain)JSMgr.datax.getObject((int)JSApi.GetType.Arg); UnityEngine.DynamicGI.UpdateMaterials(arg0); } return(true); }
private static bool IsValidTree(GameObject tree, int prototypeIndex, Terrain terrain) { if ((Object) tree == (Object) null) return false; TreePrototype[] treePrototypes = terrain.terrainData.treePrototypes; for (int index = 0; index < treePrototypes.Length; ++index) { if (index != prototypeIndex && (Object) treePrototypes[index].m_Prefab == (Object) tree) return false; } return true; }
private void Awake() { Instance = FindObjectOfType <TerrainManager>(); ActiveTerrain = FindObjectOfType <UnityEngine.Terrain>(); Data = ActiveTerrain.terrainData; IsInitialized = true; SaveTerrainData(); }
public void UpdateLevels(Vector3 position) { base.transform.position = Vector3.zero; UnityEngine.Terrain activeTerrain = UnityEngine.Terrain.activeTerrain; if (activeTerrain != null) { foreach (FPGrassLevel level in this.children) { level.UpdateLevel(position, activeTerrain); } } }
/// <summary> /// Creates an array of valid neighboring Terrains that fit the following /// requirements: /// - not null /// - heightmap resolutions match between neighboring tile and this one /// </summary> /// <param name="n">Neighborhood of tiles</param> private UnityEngine.Terrain[] GetValidNeighbors(Neighborhood n) { UnityEngine.Terrain left = n.Left == null || n.Left.MeshManager.HeightmapResolution != HeightmapResolution ? null : n.Left.MeshManager.ActiveTerrain; UnityEngine.Terrain top = n.Up == null || n.Up.MeshManager.HeightmapResolution != HeightmapResolution ? null : n.Up.MeshManager.ActiveTerrain; UnityEngine.Terrain right = n.Right == null || n.Right.MeshManager.HeightmapResolution != HeightmapResolution ? null : n.Right.MeshManager.ActiveTerrain; UnityEngine.Terrain bottom = n.Down == null || n.Down.MeshManager.HeightmapResolution != HeightmapResolution ? null : n.Down.MeshManager.ActiveTerrain; return(new[] { left, top, right, bottom }); }
internal new void InitializeDefaults(Terrain terrain) { this.m_Terrain = terrain; this.m_TerrainWidth = base.terrainData.size.x; this.m_TerrainHeight = base.terrainData.size.y; this.m_TerrainLength = base.terrainData.size.z; this.m_HeightmapResolution = base.terrainData.heightmapResolution; this.m_DetailResolution = base.terrainData.detailResolution; this.m_DetailResolutionPerPatch = base.terrainData.detailResolutionPerPatch; this.m_ControlTextureResolution = base.terrainData.alphamapResolution; this.m_BaseTextureResolution = base.terrainData.baseMapResolution; this.OnWizardUpdate(); }
private void InitializeData(Terrain terrain, int index) { this.m_Terrain = terrain; this.m_Index = index; SplatPrototype splatPrototype = index != -1 ? this.m_Terrain.terrainData.splatPrototypes[index] : new SplatPrototype(); this.m_Texture = splatPrototype.texture; this.m_NormalMap = splatPrototype.normalMap; this.m_TileSize = splatPrototype.tileSize; this.m_TileOffset = splatPrototype.tileOffset; this.m_Specular = splatPrototype.specular; this.m_Metallic = splatPrototype.metallic; this.m_Smoothness = splatPrototype.smoothness; }
public static TriangleMesh TriangulateSurface(Terrain terrain , float xmin, float zmin, float xmax, float zmax , float resolution , float yOffset) { if (terrain == null || terrain.terrainData == null || resolution <= 0 || xmin > xmax || zmin > zmax) { return null; } int xCount; int zCount; Vector3 scale = DeriveScale(terrain, resolution, out xCount, out zCount); Vector3 origin = terrain.transform.position; /* * We are generating part of a larger mesh. The vertices must match that of the larger * mesh. * * Convert input values to local grid space. * Clamp to the heightfield bounds. * Convert back to worldspace. */ xmin = origin.x + Mathf.Max(0, Mathf.Floor((xmin - origin.x) / scale.x)) * scale.x; zmin = origin.z + Mathf.Max(0, Mathf.Floor((zmin - origin.z) / scale.z)) * scale.z; xmax = origin.x + Mathf.Min(xCount, Mathf.Ceil((xmax - origin.x) / scale.x)) * scale.x; zmax = origin.z + Mathf.Min(xCount, Mathf.Ceil((zmax - origin.z) / scale.z)) * scale.z; if (xmin + scale.x > xmax || zmin + scale.z > zmax) // Triangulation zone is too small. return null; // Everyting is already snapped to the grid. But there may be floating point errors. // So round it. xCount = Mathf.RoundToInt((xmax - xmin) / scale.x); zCount = Mathf.RoundToInt((zmax - zmin) / scale.z); TriangleMesh m = new TriangleMesh(xCount * zCount, (xCount - 1) * (zCount - 1) * 2); TriangulateSurface(terrain , new Vector3(xmin, origin.y, zmin) , scale , xCount, zCount , yOffset , m); return m; }
public void CopyTo(UnityEngine.Terrain terrain) { terrain.basemapDistance = this.basemapDistance; terrain.castShadows = this.castShadows; terrain.detailObjectDensity = this.detailObjectDensity; terrain.detailObjectDistance = this.detailObjectDistance; terrain.heightmapMaximumLOD = this.heightmapMaximumLOD; terrain.heightmapPixelError = this.heightmapPixelError; terrain.materialTemplate = this.materialTemplate; terrain.treeBillboardDistance = this.treeBillboardDistance; terrain.treeCrossFadeLength = this.treeCrossFadeLength; terrain.treeDistance = this.treeDistance; terrain.treeMaximumFullLODCount = this.treeMaximumFullLODCount; }
/// <summary> /// <para>Schedules an update of the albedo and emissive textures of a system that contains the renderer or the terrain.</para> /// </summary> /// <param name="renderer">The Renderer to use when searching for a system to update.</param> /// <param name="terrain">The Terrain to use when searching for systems to update.</param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="width"></param> /// <param name="height"></param> public static void UpdateMaterials(Terrain terrain, int x, int y, int width, int height) { if (terrain == null) { throw new ArgumentNullException("terrain"); } if (terrain.terrainData == null) { throw new ArgumentException("Invalid terrainData."); } float alphamapWidth = terrain.terrainData.alphamapWidth; float alphamapHeight = terrain.terrainData.alphamapHeight; UpdateMaterialsForTerrain(terrain, new Rect(((float) x) / alphamapWidth, ((float) y) / alphamapHeight, ((float) width) / alphamapWidth, ((float) height) / alphamapHeight)); }
/// <summary> /// Sets the neighboring <see cref="UnityEngine.Terrain"/> types. /// </summary> /// <param name="neighbors">Neighboring tiles</param> /// <param name="hideTerrain">Should the terrain be hid when setting neighboring tiles?</param> public void SetNeighboringTiles(Neighborhood neighbors, bool hideTerrain) { Neighborhood n = neighbors; UnityEngine.Terrain t = ActiveTerrain; if (t == null) { return; } //WeldNeighbors(neighbors, hideTerrain); UnityEngine.Terrain[] tiles = GetValidNeighbors(n); t.SetNeighbors(tiles[0], tiles[1], tiles[2], tiles[3]); }
public void DrawBrush(Vector3 pos, float radius, Terrain terrain, Color color, float thickness=3f, int numCorners=32) { //incline is the height delta in one unit distance Handles.color = color; Vector3[] corners = new Vector3[numCorners+1]; float step = 360f/numCorners; for (int i=0; i<=corners.Length-1; i++) { corners[i] = new Vector3( Mathf.Sin(step*i*Mathf.Deg2Rad), 0, Mathf.Cos(step*i*Mathf.Deg2Rad) ) * radius + pos; corners[i].y = terrain.SampleHeight(corners[i]); } Handles.DrawAAPolyLine(thickness, corners); }
public static void UpdateMaterials(Terrain terrain, int x, int y, int width, int height) { if (terrain == null) { throw new ArgumentNullException("terrain"); } if (terrain.terrainData == null) { throw new ArgumentException("Invalid terrainData."); } float num = (float)terrain.terrainData.alphamapWidth; float num2 = (float)terrain.terrainData.alphamapHeight; DynamicGI.UpdateMaterialsForTerrain(terrain, new Rect((float)x / num, (float)y / num2, (float)width / num, (float)height / num2)); }
public static void PlaceTrees(Terrain terrain, float xBase, float yBase) { int prototypeCount = TerrainInspectorUtil.GetPrototypeCount(terrain.terrainData); if (((selectedTree != -1) && (selectedTree < prototypeCount)) && TerrainInspectorUtil.PrototypeIsRenderable(terrain.terrainData, selectedTree)) { TreeInstance instance; int num2 = 0; instance = new TreeInstance { position = new Vector3(xBase, 0f, yBase), color = GetTreeColor(), lightmapColor = Color.white, prototypeIndex = selectedTree, heightScale = GetTreeHeight(), widthScale = !lockWidthToHeight ? GetTreeWidth() : instance.heightScale, rotation = GetTreeRotation() }; if (((Event.current.type != EventType.MouseDrag) && (brushSize <= 1f)) || TerrainInspectorUtil.CheckTreeDistance(terrain.terrainData, instance.position, instance.prototypeIndex, spacing)) { terrain.AddTreeInstance(instance); num2++; } Vector3 prototypeExtent = TerrainInspectorUtil.GetPrototypeExtent(terrain.terrainData, selectedTree); prototypeExtent.y = 0f; float num3 = brushSize / ((prototypeExtent.magnitude * spacing) * 0.5f); int num4 = (int) ((num3 * num3) * 0.5f); num4 = Mathf.Clamp(num4, 0, 100); for (int i = 1; (i < num4) && (num2 < num4); i++) { Vector2 insideUnitCircle = UnityEngine.Random.insideUnitCircle; insideUnitCircle.x *= brushSize / terrain.terrainData.size.x; insideUnitCircle.y *= brushSize / terrain.terrainData.size.z; Vector3 position = new Vector3(xBase + insideUnitCircle.x, 0f, yBase + insideUnitCircle.y); if ((((position.x >= 0f) && (position.x <= 1f)) && ((position.z >= 0f) && (position.z <= 1f))) && TerrainInspectorUtil.CheckTreeDistance(terrain.terrainData, position, selectedTree, spacing * 0.5f)) { instance = new TreeInstance { position = position, color = GetTreeColor(), lightmapColor = Color.white, prototypeIndex = selectedTree, heightScale = GetTreeHeight(), widthScale = !lockWidthToHeight ? GetTreeWidth() : instance.heightScale, rotation = GetTreeRotation() }; terrain.AddTreeInstance(instance); num2++; } } } }
public static UnityEngine.Mesh GetMeshFromTerrain(UnityEngine.Terrain terrain) { var resolution = terrain.terrainData.heightmapResolution; var l = resolution; var w = resolution; var width = terrain.terrainData.heightmapResolution * terrain.terrainData.heightmapScale.x; var length = terrain.terrainData.heightmapResolution * terrain.terrainData.heightmapScale.z; //Vector3 terrainPos = terrain.transform.position; var newVertices = new Vector3[l * w]; var newTriangles = new int[l * w * 2 * 3]; var tri = 0; var newUV = new Vector2[l * w]; var uvStepL = 1f / (l - 1); var uvStepW = 1f / (w - 1); var heights = terrain.terrainData.GetHeights(0, 0, w, l); for (var i = 0; i < l; i++) { for (var j = 0; j < w; j++) { var height = heights[i, j];//.SampleHeight(new Vector3(terrainPos.x + width / (w - 1) * j, 0f, terrainPos.z + length / (l - 1) * i)); newVertices[i * w + j] = new Vector3(width / (w - 1) * j, height, length / (l - 1) * i); newUV[i * w + j] = new Vector2(uvStepL * i, uvStepW * j); if (i > 0 && j > 0) { newTriangles[tri + 0] = i * w + j - 1; // 3 newTriangles[tri + 1] = (i - 1) * w + j; // 2 newTriangles[tri + 2] = (i - 1) * w + j - 1; // 1 tri += 3; newTriangles[tri + 0] = i * w + j; // 4 newTriangles[tri + 1] = (i - 1) * w + j; // 2 newTriangles[tri + 2] = i * w + j - 1; // 3 tri += 3; } } } var mesh = new UnityEngine.Mesh(); mesh.vertices = newVertices; mesh.triangles = newTriangles; mesh.uv = newUV; return(mesh); }
private void Reset() { GameObject[] objArray = GameObject.FindGameObjectsWithTag("Main Terrain"); if (objArray.Length > 0) { for (int i = 0; i < objArray.Length; i++) { this._terrain = objArray[i].GetComponent <UnityEngine.Terrain>(); if (this._terrain != null) { break; } } } }
private static bool IsValidTree(GameObject tree, int prototypeIndex, Terrain terrain) { if (tree == null) { return false; } TreePrototype[] treePrototypes = terrain.terrainData.treePrototypes; for (int i = 0; i < treePrototypes.Length; i++) { if ((i != prototypeIndex) && (treePrototypes[i].m_Prefab == tree)) { return false; } } return true; }
public static TriangleMesh TriangulateSurface(Terrain terrain, float resolution) { if (terrain == null || terrain.terrainData == null || resolution <= 0) return null; Vector3 origin = terrain.transform.position; int xCount; int zCount; Vector3 scale = DeriveScale(terrain, resolution, out xCount, out zCount); TriangleMesh m = new TriangleMesh(xCount * zCount, (xCount - 1) * (zCount - 1) * 2); TriangulateSurface(terrain, origin, scale, xCount, zCount, 0, m); return m; }
internal void InitializeDefaults(Terrain terrain, int index) { base.m_Terrain = terrain; this.m_PrototypeIndex = index; if (this.m_PrototypeIndex == -1) { this.m_Tree = null; this.m_BendFactor = 0f; } else { this.m_Tree = base.m_Terrain.terrainData.treePrototypes[this.m_PrototypeIndex].prefab; this.m_BendFactor = base.m_Terrain.terrainData.treePrototypes[this.m_PrototypeIndex].bendFactor; } this.m_IsValidTree = IsValidTree(this.m_Tree, this.m_PrototypeIndex, terrain); this.OnWizardUpdate(); }
public static void PlaceTrees(Terrain terrain, float xBase, float yBase) { int prototypeCount = TerrainInspectorUtil.GetPrototypeCount(terrain.terrainData); if (TreePainter.selectedTree == -1 || TreePainter.selectedTree >= prototypeCount || !TerrainInspectorUtil.PrototypeIsRenderable(terrain.terrainData, TreePainter.selectedTree)) return; int num1 = 0; TreeInstance instance = new TreeInstance(); instance.position = new Vector3(xBase, 0.0f, yBase); instance.color = (Color32) TreePainter.GetTreeColor(); instance.lightmapColor = (Color32) Color.white; instance.prototypeIndex = TreePainter.selectedTree; instance.heightScale = TreePainter.GetTreeHeight(); instance.widthScale = !TreePainter.lockWidthToHeight ? TreePainter.GetTreeWidth() : instance.heightScale; instance.rotation = TreePainter.GetTreeRotation(); if (Event.current.type != EventType.MouseDrag && (double) TreePainter.brushSize <= 1.0 || TerrainInspectorUtil.CheckTreeDistance(terrain.terrainData, instance.position, instance.prototypeIndex, TreePainter.spacing)) { terrain.AddTreeInstance(instance); ++num1; } Vector3 prototypeExtent = TerrainInspectorUtil.GetPrototypeExtent(terrain.terrainData, TreePainter.selectedTree); prototypeExtent.y = 0.0f; float num2 = TreePainter.brushSize / (float) ((double) prototypeExtent.magnitude * (double) TreePainter.spacing * 0.5); int num3 = Mathf.Clamp((int) ((double) num2 * (double) num2 * 0.5), 0, 100); for (int index = 1; index < num3 && num1 < num3; ++index) { Vector2 insideUnitCircle = UnityEngine.Random.insideUnitCircle; insideUnitCircle.x *= TreePainter.brushSize / terrain.terrainData.size.x; insideUnitCircle.y *= TreePainter.brushSize / terrain.terrainData.size.z; Vector3 position = new Vector3(xBase + insideUnitCircle.x, 0.0f, yBase + insideUnitCircle.y); if ((double) position.x >= 0.0 && (double) position.x <= 1.0 && ((double) position.z >= 0.0 && (double) position.z <= 1.0) && TerrainInspectorUtil.CheckTreeDistance(terrain.terrainData, position, TreePainter.selectedTree, TreePainter.spacing * 0.5f)) { instance = new TreeInstance(); instance.position = position; instance.color = (Color32) TreePainter.GetTreeColor(); instance.lightmapColor = (Color32) Color.white; instance.prototypeIndex = TreePainter.selectedTree; instance.heightScale = TreePainter.GetTreeHeight(); instance.widthScale = !TreePainter.lockWidthToHeight ? TreePainter.GetTreeWidth() : instance.heightScale; instance.rotation = TreePainter.GetTreeRotation(); terrain.AddTreeInstance(instance); ++num1; } } }
private void CreateTerrainGrid() { int maxX = 0; int maxZ = 0; foreach (Terrain terrain in Terrain.activeTerrains) { maxX = Mathf.Max(TerrainGridPosition(terrain.transform.position.x), maxX); maxZ = Mathf.Max(TerrainGridPosition(terrain.transform.position.z), maxZ); } _terrains = new Terrain[maxX + 1][]; for (int i = 0; i < maxX + 1; i++) { _terrains[i] = new Terrain[maxZ + 1]; } foreach (Terrain terrain in Terrain.activeTerrains) { _terrains[TerrainGridPosition(terrain.transform.position.x)][TerrainGridPosition(terrain.transform.position.z)] = terrain; } }