Esempio n. 1
0
        public IEnumerator RefreshTilesLayers()
        {
            //Clear
            terrainLayers.Clear();

            //Create Layers
            for (int i = 0; i < layers.Count; i++)
            {
                TerrainLayer terrainLayer = new TerrainLayer();
                System.Guid  g            = System.Guid.NewGuid();
                string       GuidString   = System.Convert.ToBase64String(g.ToByteArray());
                GuidString = GuidString.Replace("=", "");
                GuidString = GuidString.Replace("+", "");
                UnityEditor.AssetDatabase.CreateAsset(terrainLayer, "Assets/MWS/TerrainLayers/terrainLayer" + GuidString + ".terrainlayer");
                terrainLayers.Add(terrainLayer);
            }


            //Apply Layers
            TerrainLayer[] terrainLayerArray = terrainLayers.ToArray();
            for (int i = 0; i < tiles.Count; i++)
            {
                tiles[i].terrainData.terrainLayers = terrainLayerArray;
                Debug.Log(tiles[i].terrainData.terrainLayers.Length);
            }
            yield return(null);
        }
Esempio n. 2
0
        /// <summary>
        /// Executes the modifiers in order and generates the necessary splatmaps
        /// </summary>
        /// <param name="layer"></param>
        /// <param name="modifiers"></param>
        /// <param name="output"></param>
        public static void Execute(Terrain terrain, TerrainLayer layer, List <Modifier> modifiers)
        {
            Graphics.ClearRandomWriteTargets();
            Graphics.SetRenderTarget(alphaMap);

            //Start with a full white base
            Graphics.Blit(Texture2D.whiteTexture, alphaMap);

            //Reverse order
            for (int i = modifiers.Count - 1; i >= 0; i--)
            {
                modifiers[i].Configure(filterMat);
                modifiers[i].Execute(alphaMap);
            }

            //Scale splatmap to fit in terrain
            Vector2 scaledSplatmapSize = new Vector2((terrain.terrainData.size.x / m_resolution) * m_resolution, (terrain.terrainData.size.z / m_resolution) * m_resolution);

            //PaintContext handles creation of splatmaps. Subtracting the weights of a splatmap, from the ones before it.
            //A single pixels of all combined alpha maps must not exceed a value of one. The 2nd pass of Hidden/TerrainEngine/TerrainLayerUtils is used internally to do this
            //Note: Paintcontext must use a serialized terrain reference, otherwise breaks when executing "ApplyDelayedActions" when the project is saved!
            PaintContext c = TerrainPaintUtility.BeginPaintTexture(terrain, new Rect(0, 0, scaledSplatmapSize.x, scaledSplatmapSize.y), layer);

            Graphics.Blit(alphaMap, c.destinationRenderTexture);

            TerrainPaintUtility.EndPaintTexture(c, "Painted terrain");
        }
Esempio n. 3
0
        public static TerrainLayer createTerrainLayer(Material mat, float tiling)
        {
            TerrainLayer terrainLayer = new TerrainLayer();
            string       path         = AssetDatabase.GetAssetPath(mat);

            path = path.Replace(".mat", ".terrainlayer");
            AssetDatabase.CreateAsset(terrainLayer, path);
            AssetDatabase.Refresh();
            terrainLayer.diffuseTexture = (Texture2D)mat.mainTexture;

            //attempt to auto-detect a settings file for Lightweight or HD pipelines
            switch (MegascansUtilities.getCurrentPipeline())
            {
            case Pipeline.HDRP:
                terrainLayer.normalMapTexture = (Texture2D)mat.GetTexture("_NormalMap");
                if (mat.GetFloat("_MaterialID") == 4)
                {
                    terrainLayer.maskMapTexture = (Texture2D)mat.GetTexture("_SpecularColorMap");
                    terrainLayer.metallic       = 1.0f;
                }
                else if (mat.GetFloat("_MaterialID") == 1)
                {
                    terrainLayer.maskMapTexture = (Texture2D)mat.GetTexture("_MaskMap");
                    terrainLayer.specular       = new Color(1.0f, 1.0f, 1.0f);
                }
                break;

            case Pipeline.LWRP:

                terrainLayer.normalMapTexture = (Texture2D)mat.GetTexture("_BumpMap");
                if (mat.GetFloat("_WorkflowMode") == 1)
                {
                    terrainLayer.maskMapTexture = (Texture2D)mat.GetTexture("_MetallicGlossMap");
                    terrainLayer.specular       = new Color(1.0f, 1.0f, 1.0f);
                }
                else
                {
                    terrainLayer.maskMapTexture = (Texture2D)mat.GetTexture("_SpecGlossMap");
                    terrainLayer.metallic       = 1.0f;
                }
                break;

            case Pipeline.Standard:
                terrainLayer.normalMapTexture = (Texture2D)mat.GetTexture("_BumpMap");
                if (mat.shader.ToString() == "Standard (Specular setup)")
                {
                    terrainLayer.maskMapTexture = (Texture2D)mat.GetTexture("_SpecGlossMap");
                    terrainLayer.metallic       = 1.0f;
                }
                else
                {
                    terrainLayer.maskMapTexture = (Texture2D)mat.GetTexture("_MetallicGlossMap");
                    terrainLayer.specular       = new Color(1.0f, 1.0f, 1.0f);
                }
                break;
            }

            terrainLayer.tileSize = new Vector2(tiling, tiling);
            return(terrainLayer);
        }
Esempio n. 4
0
        internal static void ReplaceTerrainLayer(Terrain terrain, int index, TerrainLayer inputLayer)
        {
            if (inputLayer == null)
            {
                RemoveTerrainLayer(terrain, index);
                return;
            }

            var layers = terrain.terrainData.terrainLayers;

            // Make sure the selection is legit
            if (index < 0 || index > layers.Length)
            {
                return;
            }
            // See if they're already using this layer
            for (var idx = 0; idx < layers.Length; ++idx)
            {
                if (layers[idx] == inputLayer)
                {
                    return;
                }
            }

            layers[index] = inputLayer;
            terrain.terrainData.SetTerrainLayersRegisterUndo(layers, "Replace terrain layer");
        }
 public override void LoadContent()
 {
     base.LoadContent();
     _grid         = BlackBoard.GetEntry <Grid>("Grid");
     _terrainLayer = BlackBoard.GetEntry <TerrainLayer>("TerrainLayer");
     _counters[0]  = _grid.Size;
 }
Esempio n. 6
0
    private TerrainLayer createLayer(Biome name, Texture2D texture)
    {
        var layer = new TerrainLayer();

        layer.diffuseTexture = texture;
        return(layer);
    }
Esempio n. 7
0
        internal static void AddTerrainLayer(Terrain terrain, TerrainLayer inputLayer)
        {
            if (inputLayer == null)
            {
                return;
            }

            var terrainData = terrain.terrainData;
            var layers      = terrainData.terrainLayers;

            for (var idx = 0; idx < layers.Length; ++idx)
            {
                if (layers[idx] == inputLayer)
                {
                    return;
                }
            }

            int newIndex = layers.Length;
            var newarray = new TerrainLayer[newIndex + 1];

            Array.Copy(layers, 0, newarray, 0, newIndex);
            newarray[newIndex] = inputLayer;
            terrainData.SetTerrainLayersRegisterUndo(newarray, "Add terrain layer");
        }
Esempio n. 8
0
        // add a list of terrain layers to terrain, and have an option of clear existing ones
        public static void AddLayersToTerrain(TerrainData terrainData, List <TerrainLayer> layers, bool clearExisting)
        {
            if (terrainData == null || layers == null)
            {
                return;
            }

            Undo.RegisterCompleteObjectUndo(terrainData, "Add terrain layer");

            if (clearExisting)
            {
                terrainData.terrainLayers = layers.ToArray();
            }
            else
            {
                // check and remove existing layers
                var filteredLayers = layers.Where(l => !terrainData.terrainLayers.Contains(l)).ToArray();
                int oldLength      = terrainData.terrainLayers.Length;
                int newLength      = oldLength + filteredLayers.Length;
                var newArray       = new TerrainLayer[newLength];
                terrainData.terrainLayers.CopyTo(newArray, 0);
                filteredLayers.CopyTo(newArray, oldLength);
                terrainData.terrainLayers = newArray;
            }
        }
Esempio n. 9
0
        // add layer to terrain
        public static void AddLayerToTerrain(TerrainData terrainData, TerrainLayer inputLayer)
        {
            if (inputLayer == null)
            {
                return;
            }

            Undo.RegisterCompleteObjectUndo(terrainData, "Add terrain layer");

            var layers = terrainData.terrainLayers;

            for (var idx = 0; idx < layers.Length; ++idx)
            {
                if (layers[idx] == inputLayer)
                {
                    return;
                }
            }

            int newIndex = layers.Length;
            var newarray = new TerrainLayer[newIndex + 1];

            Array.Copy(layers, 0, newarray, 0, newIndex);
            newarray[newIndex]        = inputLayer;
            terrainData.terrainLayers = newarray;
        }
Esempio n. 10
0
        public static TerrainTextureData[] GetTerrainTextureDatas(TerrainData data)
        {
#if UNITY_2018_3_OR_NEWER
            var arr = new TerrainTextureData[data.terrainLayers.Length];
            for (var i = 0; i < data.terrainLayers.Length; i++)
            {
                TerrainLayer layer = data.terrainLayers[i];
                arr[i] = new TerrainTextureData
                         (
                    layer.normalMapTexture,
                    layer.maskMapTexture,
                    layer.diffuseTexture
                         );
            }

            return(arr);
#else
            var arr = new TerrainTextureData[data.splatPrototypes.Length];
            for (int i = 0; i < data.splatPrototypes.Length; i++)
            {
                var layer = data.splatPrototypes[i];
                arr[i] = new TerrainTextureData
                         (
                    layer.normalMap,
                    layer.texture
                         );
            }
            return(arr);
#endif
        }
        private void drawTerrainLayerMaterial(int index)
        {
            EditorGUILayout.BeginHorizontal();

            TerrainLayer layer = terrainLayers[index];

            if (layer != null)
            {
                GUILayout.Box(layer.diffuseTexture, GUILayout.Height(40), GUILayout.Width(40));
            }
            else
            {
                GUILayout.Box(new GUIContent(), GUILayout.Height(40), GUILayout.Width(40));
            }

            EditorGUILayout.BeginVertical();

            if (layer != null)
            {
                EditorGUILayout.LabelField(layer.diffuseTexture.name);
            }
            else
            {
                EditorGUILayout.LabelField("Missing Terrain Layer");
            }

            terrain.TerrainMaterials[index] = EditorGUILayout.ObjectField("", terrain.TerrainMaterials[index], typeof(ImpactMaterialBase), false) as ImpactMaterialBase;

            EditorGUILayout.EndVertical();

            EditorGUILayout.EndHorizontal();
        }
Esempio n. 12
0
        public override void ApplicationDidFinishLaunching(CCApplication application, CCWindow mainWindow)
        {
            application.ContentRootDirectory = "Content";

            var screen = new ScreenDetails(application, mainWindow);

            var      logger   = new ConsoleLogger(GridGame.Library.Enums.LogLevel.debug);
            GameData gameData = new GameData(logger)
            {
                Screen = screen,
                Input  = new EnvironmentInputs(),
                Player = new PlayerPosition(),
            };


            screen.SetDefaultDesignResolution();


            var scene       = new CCScene(mainWindow);
            var introLayer  = new TerrainLayer(gameData);
            var playerLayer = new PlayerLayer(gameData);

            scene.AddChild(introLayer);
            scene.AddChild(playerLayer);

            mainWindow.RunWithScene(scene);
        }
Esempio n. 13
0
 void OnValidate()
 {
     if (Width < 1)
     {
         Width = 1;
     }
     if (Height < 1)
     {
         Height = 1;
     }
     if (Lacunarity < 1)
     {
         Lacunarity = 1;
     }
     if (Layers.Length == 0)
     {
         Layers    = new TerrainLayer[2];
         Layers[0] = new TerrainLayer()
         {
             Color = Color.blue, Height = 0.4f, Name = "Water"
         };
         Layers[1] = new TerrainLayer()
         {
             Color = Color.green, Height = 1.0f, Name = "Land"
         };
     }
 }
        /// <summary>
        /// Applies an array of Gaia Splat prototypes to a terrain. Uses the correct terrain API for pre and post Unity 2018.3.
        /// </summary>
        /// <param name="terrain">The terrain to assign the splat prototypes to.</param>
        /// <param name="splats">Array of GaiaSplatPrototypes to assign to the terrain.</param>
        /// <param name="terrainName">The current Gaia profile. Used for terrain layer asset filenames.</param>
        public static void SetGaiaSplatPrototypes(Terrain terrain, GaiaSplatPrototype[] splats, string terrainName)
        {
            if (terrain != null && splats != null)
            {
#if UNITY_2018_3_OR_NEWER
                TerrainLayer[] terrainLayers = new TerrainLayer[splats.Length];

                for (int i = 0; i < splats.Length; i++)
                {
                    terrainLayers[i] = splats[i].Convert();
                }

                //completely remove all old splat prototypes first to prevent build-up of abandoned files
                RemoveTerrainLayerAssetFiles(terrainName);

                //Permanently save the new layers as asset files & get a reference, else they will not work properly in the terrain
                for (int i = 0; i < terrainLayers.Length; i++)
                {
                    terrainLayers[i] = SaveTerrainLayerAsAsset(terrainName, i.ToString(), terrainLayers[i]);
                }
                terrain.terrainData.terrainLayers = terrainLayers;
#else
                SplatPrototype[] splatPrototypes = new SplatPrototype[splats.Length];

                for (int i = 0; i < splats.Length; i++)
                {
                    splatPrototypes[i] = splats[i].Convert();
                }
                terrain.terrainData.splatPrototypes = splatPrototypes;
#endif
            }
        }
Esempio n. 15
0
        public override bool OnPaint(Terrain terrain, IOnPaint editContext)
        {
            BrushTransform targetBrushXform = TerrainPaintUtility.CalculateBrushTransform(terrain, editContext.uv, editContext.brushSize, 1);

            Material mat         = GetPaintMaterial();
            Vector4  brushParams = new Vector4(editContext.brushStrength, 0, 0, 0f);

            mat.SetTexture("_BrushTex", editContext.brushTexture);
            mat.SetVector("_BrushParams", brushParams);

            Rect targetRect             = targetBrushXform.GetBrushXYBounds();
            int  numSampleTerrainLayers = terrain.terrainData.terrainLayers.Length;

            for (int i = 0; i < numSampleTerrainLayers; ++i)
            {
                TerrainLayer layer = terrain.terrainData.terrainLayers[i];
                if (layer == null)
                {
                    continue;
                }

                int          layerIndex    = TerrainPaintUtility.FindTerrainLayerIndex(terrain, layer);
                Texture2D    layerTexture  = TerrainPaintUtility.GetTerrainAlphaMapChecked(terrain, layerIndex >> 2);
                PaintContext targetContext = PaintContext.CreateFromBounds(terrain, targetRect, layerTexture.width, layerTexture.height);
                targetContext.CreateRenderTargets(RenderTextureFormat.R8);
                targetContext.GatherAlphamap(layer, true);
                Graphics.Blit(targetContext.sourceRenderTexture, targetContext.destinationRenderTexture, mat, 0);

                TerrainPaintUtility.EndPaintTexture(targetContext, "Terrain Paint - Smooth Splatmaps");
            }
            return(false);
        }
        public void TerrainToolboxUtilites_WhenApplySplatmaps_DoesNotDividebyZero()
        {
            // Preparation:
            // Collect data, create needed objects
            Texture2D    texture = new Texture2D(512, 512);
            TerrainLayer layer   = new TerrainLayer();

            layer.diffuseTexture = texture;
            TerrainLayer[] terrainLayers = { layer };

            //Add splatmap to terrain in order to import into the Utilities Window
            m_TerrainComponent.terrainData.terrainLayers = terrainLayers;
            Selection.activeGameObject = m_TerrainGO;

            // Execute the repro steps in code
            TerrainToolboxWindow toolboxWindow = EditorWindow.GetWindow(typeof(TerrainToolboxWindow)) as TerrainToolboxWindow;

            toolboxWindow.m_TerrainUtilitiesMode.ImportSplatmapsFromTerrain(true);
            Selection.activeGameObject = null;

            Assert.That(() =>
            {
                toolboxWindow.m_TerrainUtilitiesMode.ExportSplatmapsToTerrain(true);
            }, !Throws.TypeOf <System.DivideByZeroException>());
            toolboxWindow.Close();
        }
Esempio n. 17
0
        public IEnumerator Test_PaintTexture_Playback(string recordingFilePath, string targetTerrainName)
        {
            yield return(null);

            Terrain t = GameObject.Find("Terrain").GetComponent <Terrain>();

            InitTerrainTypesWithReflection("PaintTextureTool");
            onPaintHistory = LoadDataFile(recordingFilePath);
            SetupTerrain(targetTerrainName);

            TerrainLayer tl1 = new TerrainLayer(), tl2 = new TerrainLayer();

            tl1.diffuseTexture = Resources.Load <Texture2D>("testGradientCircle");
            tl2.diffuseTexture = Resources.Load <Texture2D>("testGradientCircle");
            terrainObj.terrainData.terrainLayers = new TerrainLayer[] { tl1, tl2 };

            PaintTextureTool paintTextureTool = terrainToolInstance as PaintTextureTool;
            FieldInfo        selectedTerrainLayerInfo = typeof(PaintTextureTool).GetField("m_SelectedTerrainLayer",
                                                                                          s_bindingFlags);

            selectedTerrainLayerInfo.SetValue(paintTextureTool, tl2);

            // Enables the core brush playback on OnSceneGUI
            SceneView.duringSceneGui -= OnSceneGUI;
            SceneView.duringSceneGui += OnSceneGUI;

            while (onPaintHistory.Count > 0)
            {
                // Force a SceneView update for OnSceneGUI to be triggered
                SceneView.RepaintAll();
                yield return(null);
            }

            Assert.Pass("Matrix stack regression not found!");
        }
Esempio n. 18
0
    /*
     * Generate a Texture2D to apply on the terrain layer.
     * <param name="noiseMap">Noise map that will be used to get data of the terrain</param>
     * <param name="terrainTypes">Data to compare against the noise map</param>
     * <param name="chosenTerrainTypes">Infomation of each vertice in the terrain</param>
     */
    private TerrainLayer BuildTexture(float[,] noiseMap, TerrainType[] terrainTypes, TerrainType[,] chosenTerrainTypes)
    {
        var terrainLayer = new TerrainLayer();

        int tileDepth = noiseMap.GetLength(0);
        int tileWidth = noiseMap.GetLength(1);

        terrainLayer.tileSize = new Vector2(tileDepth, tileWidth);

        var colorMap = new Color[tileDepth * tileWidth];

        for (int zIndex = 0; zIndex < tileDepth; zIndex++)
        {
            for (int xIndex = 0; xIndex < tileWidth; xIndex++)
            {
                int   colorIndex  = zIndex * tileWidth + xIndex;
                float noise       = noiseMap[zIndex, xIndex];
                var   terrainType = ChooseTerrainType(noise, terrainTypes);
                colorMap[colorIndex] = terrainType.color;
                chosenTerrainTypes[zIndex, xIndex] = terrainType;
            }
        }

        var tileTexture = new Texture2D(tileWidth, tileDepth);

        tileTexture.wrapMode = TextureWrapMode.Clamp;
        tileTexture.SetPixels(colorMap);
        tileTexture.Apply();

        terrainLayer.diffuseTexture = tileTexture;

        return(terrainLayer);
    }
Esempio n. 19
0
        private void EndRecordLayerProperties()
        {
            IRTE    editor     = IOC.Resolve <IRTE>();
            Terrain terrain    = Terrain;
            int     layerIndex = m_layersList.SelectedIndex;

            Vector2 tileSize   = SelectedLayer.tileSize;
            Vector2 tileOffset = SelectedLayer.tileOffset;

            editor.Undo.CreateRecord(record =>
            {
                TerrainLayer layer = terrain.terrainData.terrainLayers[layerIndex];
                if (layer != null)
                {
                    layer.tileOffset = tileOffset;
                    layer.tileSize   = tileSize;
                }
                return(true);
            },
                                     record =>
            {
                TerrainLayer layer = terrain.terrainData.terrainLayers[layerIndex];
                if (layer != null)
                {
                    layer.tileOffset = m_initialTileOffset;
                    layer.tileSize   = m_initialTileSize;
                }

                return(true);
            });
        }
Esempio n. 20
0
        private void SetNormals()
        {
#if UNITY_2017 || UNITY_2018_1 || UNITY_2018_2
            var splatProtos = new List <SplatPrototype>();
            for (var i = 0; i < albedos.Count; i++)
            {
                var prototype = new SplatPrototype();
                prototype.texture   = albedos[i];
                prototype.normalMap = normals[normalCount[i]];
                splatProtos.Insert(i, prototype);
            }

            Undo.RegisterCompleteObjectUndo(terrain.gameObject, "AddNormalsToSplats");
            terrain.terrainData.splatPrototypes = splatProtos.ToArray();
#endif
#if UNITY_2018_3_OR_NEWER
            var splatProtos = new List <TerrainLayer>();
            for (var i = 0; i < albedos.Count; i++)
            {
                var prototype = new TerrainLayer();
                prototype.diffuseTexture   = albedos[i];
                prototype.normalMapTexture = normals[normalCount[i]];
                splatProtos.Insert(i, prototype);
            }
            Undo.RegisterCompleteObjectUndo(terrain.gameObject, "AddNormalsToSplats");
            terrain.terrainData.terrainLayers = splatProtos.ToArray();
#endif
            terrain.Flush();
            terrain.terrainData.RefreshPrototypes();
            Close();
        }
Esempio n. 21
0
        public static bool ImportTerrainAll(TerrainLayer m)
        {
            using var ofd = new OpenFileDialog
                  {
                      Filter   = "New Horizons Terrain (*.nht)|*.nht|All files (*.*)|*.*",
                      FileName = "terrainAcres.nht",
                  };
            if (ofd.ShowDialog() != DialogResult.OK)
            {
                return(false);
            }

            var path = ofd.FileName;
            var fi   = new FileInfo(path);

            int expect = m.MaxTileCount * TerrainTile.SIZE;

            if (fi.Length != expect)
            {
                WinFormsUtil.Error(string.Format(MessageStrings.MsgDataSizeMismatchImport, fi.Length, expect));
                return(false);
            }

            var data = File.ReadAllBytes(path);

            m.ImportAll(data);
            return(true);
        }
Esempio n. 22
0
        public sealed override Texture2D RenderStaticPreview(string assetPath, UnityEngine.Object[] subAssets, int width, int height)
        {
            TerrainLayer t = AssetDatabase.LoadMainAssetAtPath(assetPath) as TerrainLayer;

            if (t == null || t.diffuseTexture == null)
            {
                return(null);
            }

            int texwidth  = t.diffuseTexture.width;
            int texheight = t.diffuseTexture.height;

            PreviewHelpers.AdjustWidthAndHeightForStaticPreview(texwidth, texheight, ref width, ref height);

            RenderTexture oldRT  = RenderTexture.active;
            RenderTexture tempRT = RenderTexture.GetTemporary(width, height, 0, RenderTextureFormat.ARGB32);

            Graphics.Blit(t.diffuseTexture, tempRT);
            Texture2D previewTexture = new Texture2D(width, height, TextureFormat.ARGB32, false);

            RenderTexture.active = tempRT;
            previewTexture.ReadPixels(new Rect(0, 0, width, height), 0, 0);
            previewTexture.Apply();
            RenderTexture.ReleaseTemporary(tempRT);
            tempRT = null;
            RenderTexture.active = oldRT;
            return(previewTexture);
        }
Esempio n. 23
0
        public void GatherAlphamap(TerrainLayer inputLayer, bool addLayerIfDoesntExist = true)
        {
            if (inputLayer == null)
            {
                return;
            }

            Material copyTerrainLayerMaterial = TerrainPaintUtility.GetCopyTerrainLayerMaterial();

            Vector4[] layerMasks = { new Vector4(1, 0, 0, 0), new Vector4(0, 1, 0, 0), new Vector4(0, 0, 1, 0), new Vector4(0, 0, 0, 1) };

            GatherInternal(
                t =>
            {       // return the texture to be gathered from this terrain tile
                SplatmapUserData userData = GetTerrainLayerUserData(t, inputLayer, addLayerIfDoesntExist);
                if (userData != null)
                {
                    return(TerrainPaintUtility.GetTerrainAlphaMapChecked(t.terrain, userData.mapIndex));
                }
                else
                {
                    return(null);
                }
            },

                new Color(0.0f, 0.0f, 0.0f, 0.0f),
                "PaintContext.GatherAlphamap",
                copyTerrainLayerMaterial, 0,
                t =>
            {       // before blit -- setup layer mask in the material
                SplatmapUserData userData = GetTerrainLayerUserData(t);
                copyTerrainLayerMaterial.SetVector("_LayerMask", layerMasks[userData.channelIndex]);
            });
        }
Esempio n. 24
0
 void OnSelectLayerElement(ReorderableList list)
 {
     if (m_SelectedTerrain.terrainData.terrainLayers.Length > list.index)
     {
         m_SelectedTerrainLayer = m_SelectedTerrain.terrainData.terrainLayers[list.index];
     }
 }
Esempio n. 25
0
    public override void Build(World world, Chunk chunk, Vector3Int pos, TerrainLayer layer)
    {
        int noise        = layer.GetNoise(pos.x, pos.y, pos.z, 1f, 3, 1);
        int leavesRange  = noise + 3;
        int leavesRange2 = leavesRange * leavesRange;
        int trunkHeight  = posY - noise;

        float a2inv = 1.0f / leavesRange2;
        float b2inv = 1.0f / ((leavesRange - 1) * (leavesRange - 1));

        for (int y = -leavesRange + 1; y <= leavesRange - 1; y++)
        {
            for (int z = -leavesRange; z <= leavesRange; z++)
            {
                for (int x = -leavesRange; x <= leavesRange; x++)
                {
                    if (x * x * a2inv + z * z * a2inv + y * y * b2inv <= 1.0f) // An ellipsoid flattened on the y axis
                    {
                        blocks.Set(pos.Add(x, y + trunkHeight, z), leaves);
                    }
                }
            }
        }

        blocks.Set(pos, log);
        for (int y = 1; y <= trunkHeight; y++)
        {
            blocks.Set(pos.Add(0, y, 0), log);
        }
    }
Esempio n. 26
0
        private void PaintAlphamap(Terrain sampleTerrain, Terrain targetTerrain, BrushTransform sampleXform, BrushTransform targetXform, Material mat)
        {
            Rect sampleRect             = sampleXform.GetBrushXYBounds();
            Rect targetRect             = targetXform.GetBrushXYBounds();
            int  numSampleTerrainLayers = sampleTerrain.terrainData.terrainLayers.Length;

            for (int i = 0; i < numSampleTerrainLayers; ++i)
            {
                TerrainLayer layer = sampleTerrain.terrainData.terrainLayers[i];

                if (layer == null)
                {
                    continue;                // nothing to paint if the layer is NULL
                }
                PaintContext sampleContext = TerrainPaintUtility.BeginPaintTexture(sampleTerrain, sampleRect, layer);

                // manually create target context since we are possibly applying another terrain's layers and not its own
                int          layerIndex    = TerrainPaintUtility.FindTerrainLayerIndex(sampleTerrain, layer);
                Texture2D    layerTexture  = TerrainPaintUtility.GetTerrainAlphaMapChecked(sampleTerrain, layerIndex >> 2);
                PaintContext targetContext = PaintContext.CreateFromBounds(targetTerrain, targetRect, layerTexture.width, layerTexture.height);
                targetContext.CreateRenderTargets(RenderTextureFormat.R8);
                targetContext.GatherAlphamap(layer, true);
                sampleContext.sourceRenderTexture.filterMode = FilterMode.Point;
                mat.SetTexture("_CloneTex", sampleContext.sourceRenderTexture);
                Graphics.Blit(targetContext.sourceRenderTexture, targetContext.destinationRenderTexture, mat, (int)ShaderPasses.CloneAlphamap);
                // apply texture modifications and perform cleanup. same thing as calling TerrainPaintUtility.EndPaintTexture
                targetContext.ScatterAlphamap("Terrain Paint - Clone Brush (Texture)");
                targetContext.Cleanup();
            }
        }
Esempio n. 27
0
 public static Bitmap CreateMap(TerrainLayer mgr, int scale, int x, int y, int[] scale1, int[] scaleX, Bitmap map)
 {
     CreateMap(mgr, scale1);
     ImageUtil.ScalePixelImage(scale1, scaleX, map.Width, map.Height, scale);
     ImageUtil.SetBitmapData(map, scaleX);
     return(DrawReticle(map, mgr, x, y, scale));
 }
Esempio n. 28
0
    private void GenerateGenericJSON() //For testing purposes
    {
        TerrainLayer[] arr = new TerrainLayer[2];

        TerrainLayer terrainLayer1 = new TerrainLayer("Water", 0.0f, 0.3f, Color.blue);
        TerrainLayer terrainLayer2 = new TerrainLayer("Sand", 0.3f, 0.4f, Color.yellow);
        TerrainLayer terrainLayer3 = new TerrainLayer("Grass", 0.4f, 1.0f, Color.green, false);

        string json1 = JsonUtility.ToJson(terrainLayer1);
        string json2 = JsonUtility.ToJson(terrainLayer2);
        string json3 = JsonUtility.ToJson(terrainLayer3);

        List <string> jsonList = new List <string>
        {
            json1,
            json2,
            json3
        };

        Debug.Log("first json: " + json1);

        try
        {
            File.WriteAllLines(PrefPath + "DefaultTerrainLayers.json", jsonList);
        } catch
        {
        }
    }
        public override void OnInspectorGUI(Terrain terrain, IOnInspectorGUI editContext)
        {
            GUILayout.Label("Settings", EditorStyles.boldLabel);

            EditorGUI.BeginChangeCheck();

            EditorGUILayout.Space();
            Editor.DrawFoldoutInspector(terrain.materialTemplate, ref m_TemplateMaterialEditor);

            EditorGUILayout.Space();

            if (m_SelectedTerrainLayerIndex == -1)
            {
                m_SelectedTerrainLayerIndex = TerrainPaintUtility.FindTerrainLayerIndex(terrain, m_SelectedTerrainLayer);
            }

            m_SelectedTerrainLayerIndex = TerrainLayerUtility.ShowTerrainLayersSelectionHelper(terrain, m_SelectedTerrainLayerIndex);
            EditorGUILayout.Space();

            if (EditorGUI.EndChangeCheck())
            {
                m_SelectedTerrainLayer = m_SelectedTerrainLayerIndex != -1 ? terrain.terrainData.terrainLayers[m_SelectedTerrainLayerIndex] : null;
                Save(true);
            }

            terrain.materialTemplate.SetFloat("_NumLayersCount", terrain.terrainData.terrainLayers.Length);
            TerrainLayerUtility.ShowTerrainLayerGUI(terrain, m_SelectedTerrainLayer, ref m_SelectedTerrainLayerInspector,
                                                    (m_TemplateMaterialEditor as MaterialEditor)?.customShaderGUI as ITerrainLayerCustomUI);
            EditorGUILayout.Space();

            int textureRez = terrain.terrainData.alphamapResolution;

            editContext.ShowBrushesGUI(5, BrushGUIEditFlags.All, textureRez);
        }
Esempio n. 30
0
        public override void OnInspectorGUI(Terrain terrain, IOnInspectorGUI editContext)
        {
            GUILayout.Label("Settings", EditorStyles.boldLabel);

            EditorGUI.BeginChangeCheck();

            EditorGUILayout.Space();
            Editor.DrawFoldoutInspector(terrain.materialTemplate, ref m_TemplateMaterialEditor);

            EditorGUILayout.Space();

            int layerIndex = TerrainPaintUtility.FindTerrainLayerIndex(terrain, m_SelectedTerrainLayer);

            layerIndex = TerrainLayerUtility.ShowTerrainLayersSelectionHelper(terrain, layerIndex);
            EditorGUILayout.Space();

            if (EditorGUI.EndChangeCheck())
            {
                m_SelectedTerrainLayer = layerIndex != -1 ? terrain.terrainData.terrainLayers[layerIndex] : null;
                Save(true);
            }

            TerrainLayerUtility.ShowTerrainLayerGUI(terrain, m_SelectedTerrainLayer, ref m_SelectedTerrainLayerInspector,
                                                    (m_TemplateMaterialEditor as MaterialEditor)?.customShaderGUI as ITerrainLayerCustomUI);
            EditorGUILayout.Space();

            editContext.ShowBrushesGUI(5);
        }
Esempio n. 31
0
    public override void Build(World world, BlockPos chunkPos, BlockPos pos, TerrainLayer layer)
    {
        int leaves = layer.GetNoise(pos.x, 0, pos.z, 1f, 2, 1) +1;

        for (int x = -leaves; x <= leaves; x++)
        {
            for (int y = 3; y <= 6; y++)
            {
                for (int z = -leaves; z <= leaves; z++)
                {
                    if (Chunk.InRange(pos.x + x - chunkPos.x) && Chunk.InRange(pos.z + z - chunkPos.z))
                    {
                        Block block = "leaves";
                        block.modified = false;
                        world.SetBlock(pos.Add(x, y, z), block, false);
                    }
                }
            }
        }
        for (int y = 0; y <= 5; y++)
        {
            if (y < Config.Env.WorldMaxY)
            {
                Block block = "log";
                block.modified = false;
                world.SetBlock(pos.Add(0, y, 0), block, false);
            }
        }
    }
Esempio n. 32
0
        /// <summary>
        /// Invalidates the specified terrain layer in the data cached by the renderer.
        /// </summary>
        /// <param name="tile">The terrain tile owning the terrain layer.</param>
        /// <param name="layer">The terrain layer which should be invalidated.</param>
        /// <inheritdoc cref="Invalidate()"/>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="tile"/> or <paramref name="layer"/> is <see langword="null"/>.
        /// </exception>
        public void Invalidate(TerrainTile tile, TerrainLayer layer)
        {
            if (tile == null)
            throw new ArgumentNullException("tile");
              if (layer == null)
            throw new ArgumentNullException("layer");

              UpdateAabb();

              Aabb aabb = layer.Aabb ?? tile.Aabb;

              if (layer.Material.Contains(TerrainClipmapRenderer.RenderPassBase)
              && !RegionsContain(InvalidBaseRegions, aabb))
              {
            InvalidBaseRegions.Add(aabb);

            // If there are 2 or more AABBs, then they need clipping.
            AreInvalidBaseRegionsClipped = (InvalidBaseRegions.Count == 1);
              }

              if (layer.Material.Contains(TerrainClipmapRenderer.RenderPassDetail)
              && !RegionsContain(InvalidDetailRegions, aabb))
              {
            InvalidDetailRegions.Add(aabb);

            // If there are 2 or more AABBs, then they need clipping.
            AreInvalidDetailRegionsClipped = (InvalidDetailRegions.Count == 1);
              }
        }
Esempio n. 33
0
 void AddToLayerOrder(TerrainLayer layer)
 {
     List<TerrainLayer> layers = new List<TerrainLayer>();
     layers.AddRange(gen.layerOrder);
     layers.Add(layer);
     gen.layerOrder = layers.ToArray();
     EditorUtility.SetDirty(gen);
 }
Esempio n. 34
0
 public virtual void Build(World world, BlockPos chunkPos, BlockPos pos, TerrainLayer layer) { }
Esempio n. 35
0
 /// <summary>
 /// Invalidates the specified terrain layer in the data cached by the renderer.
 /// </summary>
 /// <param name="layer">The terrain layer which should be invalidated.</param>
 /// <inheritdoc cref="Graphics.Terrain.Invalidate()"/>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="layer"/> is <see langword="null"/>.
 /// </exception>
 public void Invalidate(TerrainLayer layer)
 {
     if (Terrain != null)
     Terrain.Invalidate(this, layer);
 }
Esempio n. 36
0
        /// <summary>
        /// Invalidates the specified terrain layer in the data cached by the renderer.
        /// </summary>
        /// <param name="layer">The terrain layer which should be invalidated.</param>
        /// <inheritdoc cref="Invalidate()"/>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="layer"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="GraphicsException">
        /// <paramref name="layer"/> does not have a valid AABB. This method cannot be used. Use one of
        /// the other method overloads instead.
        /// </exception>
        public void Invalidate(TerrainLayer layer)
        {
            if (layer == null)
            throw new ArgumentNullException("layer");
              if (!layer.Aabb.HasValue)
            throw new GraphicsException("The specified terrain layer does not have a valid AABB.");

              Aabb aabb = layer.Aabb.Value;

              if (layer.Material.Contains(TerrainClipmapRenderer.RenderPassBase)
              && !RegionsContain(InvalidBaseRegions, aabb))
              {
            InvalidBaseRegions.Add(aabb);

            // If there are 2 or more AABBs, then they need clipping.
            AreInvalidBaseRegionsClipped = (InvalidBaseRegions.Count == 1);
              }

              if (layer.Material.Contains(TerrainClipmapRenderer.RenderPassDetail)
              && !RegionsContain(InvalidDetailRegions, aabb))
              {
            InvalidDetailRegions.Add(aabb);

            // If there are 2 or more AABBs, then they need clipping.
            AreInvalidDetailRegionsClipped = (InvalidDetailRegions.Count == 1);
              }
        }