// Update is called once per frame
    void Update()
    {
        if (webCamTexture.width > 100)
        {
            if (init == false)
            {
                Init();
                init = true;
            }

            try
            {
                smallTex = TextureScaler.scaled(webCamTexture, width, height);

                for (int i = 0; i < texArray.depth - 1; i++)
                {
                    texArray.SetPixels32(texArray.GetPixels32(i + 1), i);
                }

                texArray.SetPixels32(smallTex.GetPixels32(), texArray.depth - 1);
                texArray.Apply();

                Destroy(smallTex);
            }
            catch (System.Exception e)
            {
            }
        }
    }
Beispiel #2
0
    public void SetUpTexture2DArrays()
    {
        if (customTerrainMaterial)
        {
            int _resolution = splats[0].terrainLayer.diffuseTexture.width;
            int _layerCount = splats.Length;

            texture2DArray_diffuse = new Texture2DArray(_resolution, _resolution, _layerCount, TextureFormat.RGBA32, true);
            texture2DArray_normal  = new Texture2DArray(_resolution, _resolution, _layerCount, TextureFormat.RGBA32, true);
            texture2DArray_height  = new Texture2DArray(_resolution, _resolution, _layerCount, TextureFormat.RGBA32, true);

            for (int i = 0; i < _layerCount; i++)
            {
                texture2DArray_diffuse.SetPixels32(splats[i].terrainLayer.diffuseTexture.GetPixels32(), i, 0);
                texture2DArray_normal.SetPixels32(splats[i].terrainLayer.normalMapTexture.GetPixels32(), i, 0);
                texture2DArray_height.SetPixels32(splats[i].terrainLayer.maskMapTexture.GetPixels32(), i, 0);
            }

            texture2DArray_diffuse.Apply();
            texture2DArray_normal.Apply();
            texture2DArray_height.Apply();


            customTerrainMaterial.SetTexture(NameIDs._TextureArrayDiffuse, texture2DArray_diffuse);
            customTerrainMaterial.SetTexture(NameIDs._TextureArrayNormal, texture2DArray_normal);
            customTerrainMaterial.SetTexture(NameIDs._TextureArrayMOHS, texture2DArray_height);
        }
    }
Beispiel #3
0
    public void UpdateTerrainMaterialProperty()
    {
        if (manager.customTerrainMaterial)
        {
            if (texture2DArray_splat == null)
            {
                texture2DArray_splat = new Texture2DArray(am_x, am_y, terrain.terrainData.alphamapTextures.Length, TextureFormat.RGBA32, true);
                texture2DArray_splat.Apply();
            }

            for (int i = 0; i < terrain.terrainData.alphamapTextures.Length; i++)
            {
                texture2DArray_splat.SetPixels32(GetPixels32FromRenderTexture(splatMapsArray[i]), i, 0);
            }

            texture2DArray_splat.Apply();


            customTerrainMaterial.SetTexture(NameIDs._TextureArraySplatmap, texture2DArray_splat);
            customTerrainMaterial.SetTexture(NameIDs._ColorMapDiffuse, colorMapDiffuse);
            customTerrainMaterial.SetTexture(NameIDs._ColorMapNormal, colorMapNormal);
            customTerrainMaterial.SetTexture(NameIDs._ColorMapMOHS, colorMapMOHS);

            UpdateTerrainMaterialManualPaintedArea();
        }
    }
        public GeocellSparseTextureArray(byte[] inventory, int dimension)
        {
            MapTexture          = new Texture2D(360, 180, TextureFormat.R16, false);
            MapTexture.wrapMode = TextureWrapMode.Clamp;
            MapPixels           = MapTexture.GetRawTextureData <ushort>();

            ushort texture_count = 0;

            for (int i = 0, c = 360 * 180; i < c; ++i)
            {
                MapPixels[i] = 0;
                if (inventory[i] == 0)
                {
                    continue;
                }
                ++texture_count;
                MapPixels[i] = texture_count;
            }
            MapTexture.Apply();

            TextureArray          = new Texture2DArray(dimension, dimension, texture_count + 1, TextureFormat.RGBA32, false);
            TextureArray.wrapMode = TextureWrapMode.Clamp;
            var texture_pixels = new Color32[dimension * dimension];

            for (int i = 0, c = dimension * dimension; i < c; ++i)
            {
                texture_pixels[i] = Color.clear;
            }
            for (int texture_index = 0; texture_index <= texture_count; ++texture_index)
            {
                TextureArray.SetPixels32(texture_pixels, texture_index);
            }
        }
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        if (GUILayout.Button("Generate"))
        {
            Texture2DArrayData component      = (Texture2DArrayData)target;
            Texture2D[]        textures       = component.textures;
            Texture2DArray     texture2DArray = new Texture2DArray(
                textures[0].width, textures[0].height, textures.Length, TextureFormat.RGBA32, true);

            for (int i = 0; i < textures.Length; i++)
            {
                texture2DArray.SetPixels32(textures[i].GetPixels32(), i);
            }
            texture2DArray.Apply();

            AssetDatabase.CreateAsset(texture2DArray, "Assets/Textures/" + component.name + ".asset");

            GameObject exampleMesh = GameObject.Find("ExampleTerrainMesh");
            Shader     texturedDynamicTerrainShader = exampleMesh.GetComponent <Shader>();

            component.NotifyOfUpdatedValues();
            EditorUtility.SetDirty(target);
        }
    }
Beispiel #6
0
        public Texture2DArray Generate(TamIdSoleImagesPack pack, List <TAMTone> tones, List <TAMMipmapLevel> levels, int layersCount)
        {
            var mipmapLevelsCount = levels.Count;
            var tonesCount        = tones.Count;
            var maxResolution     = new IntVector2(
                pack.Columns[tones[0]][levels[mipmapLevelsCount - 1]][0].width,
                pack.Columns[tones[0]][levels[mipmapLevelsCount - 1]][0].height);

            var slicesCount  = tonesCount * layersCount;
            var tamIdTexture = new Texture2DArray(maxResolution.X, maxResolution.Y, slicesCount, TextureFormat.RGBA32, true, true)
            {
                filterMode = FilterMode.Point, wrapMode = TextureWrapMode.Clamp
            };
            var currentResolution = maxResolution;

            for (var mipmapLevelIndex = 0; mipmapLevelIndex < mipmapLevelsCount; mipmapLevelIndex++)
            {
                for (int toneIndex = 0; toneIndex < tonesCount; toneIndex++)
                {
                    for (int layerIndex = 0; layerIndex < layersCount; layerIndex++)
                    {
                        var array = new Color[currentResolution.X * currentResolution.Y];
                        for (int x = 0; x < currentResolution.X; x++)
                        {
                            for (int y = 0; y < currentResolution.Y; y++)
                            {
                                Color newColor = pack.Columns[tones[toneIndex]][levels[mipmapLevelsCount - 1 - mipmapLevelIndex]][layerIndex].GetPixel(x, y);
                                array[x + (y * currentResolution.X)] = newColor;
                            }
                        }

                        tamIdTexture.SetPixels(array, toneIndex * layersCount + layerIndex, mipmapLevelIndex);
                    }
                }

                currentResolution = new IntVector2(currentResolution.X / 2, currentResolution.Y / 2);
            }

            var neededMipLevelsCount = (int)Mathf.Log(currentResolution.X, 2);

            for (int toneIndex = 0; toneIndex < tonesCount; toneIndex++)
            {
                for (int layerIndex = 0; layerIndex < layersCount; layerIndex++)
                {
                    var depthIndex              = toneIndex * layersCount + layerIndex;
                    var lastSetMipmapIndex      = mipmapLevelsCount - 1;
                    var lowerLevelMipmapTexture =
                        CreateAutomaticGeneratedLowerMipmaps(currentResolution * 2, tamIdTexture.GetPixels(depthIndex, lastSetMipmapIndex));

                    for (var mipmapLevelIndex = 0; mipmapLevelIndex < neededMipLevelsCount; mipmapLevelIndex++)
                    {
                        tamIdTexture.SetPixels32(lowerLevelMipmapTexture.GetPixels32(mipmapLevelIndex + 1), depthIndex, mipmapLevelIndex + mipmapLevelsCount);
                    }
                }
            }

            tamIdTexture.Apply(false);
            return(tamIdTexture);
        }
 void CopyData(Texture2D src, Texture2DArray dst, int index)
 {
     for (int m = 0; m < src.mipmapCount; m++)
     {
         var pixels = src.GetPixels32(m);
         dst.SetPixels32(pixels, index, m);
     }
 }
    public void MakeArray()
    {
        // Debug.Log("make it");

        foreach (Texture tex in CookieList)
        {
            if (tex == null)
            {
                Debug.LogError("Cookie list can not have empty texture slots");
                return;
            }
        }

        if (CookieList.Length <= 0)
        {
            Debug.LogError("Cookie texture list is empty");
            return;
        }
        //Make Cookie Texture Array :: Is linear for color blending, input textures should keep sRGB color enabled

        CookieArray = new Texture2DArray(MasterCookieResolution, MasterCookieResolution, CookieList.Length, TextureFormat.ARGB32, true, true);
        Texture2D     tempTex = new Texture2D(MasterCookieResolution, MasterCookieResolution, TextureFormat.ARGB32, false, true);
        RenderTexture TempRT  = new RenderTexture(MasterCookieResolution, MasterCookieResolution, 32, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear);


        TempRT.Create();


        //Casting Array to RT to normalize texture sizes and avoid setting restrictions


        for (int i = 0; i < CookieList.Length; i++)
        {
            Graphics.Blit(CookieList[i], TempRT);

            //Move RT to tex2D to get pixels
            RenderTexture.active = TempRT;
            tempTex.ReadPixels(new Rect(0, 0, TempRT.width, TempRT.height), 0, 0);

            tempTex.Apply();

            //Set Pixels to array
            CookieArray.SetPixels32(tempTex.GetPixels32(0), i, 0);
        }

        CookieArray.Apply(true);

        //clear from memory

        RenderTexture.active = null;
        TempRT.Release();
        TempRT.DiscardContents();
        DestroyImmediate(TempRT);
        DestroyImmediate(tempTex);

        ApplyArray();
    }
Beispiel #9
0
    Texture2DArray CreateTextureArray()
    {
        Texture2DArray texArray = new Texture2DArray(textures[0].width, textures[0].height, textures.Length, textures[0].format, true);

        for (int i = 0; i < textures.Length; i++)
        {
            texArray.SetPixels32(textures[i].GetPixels32(), i);
        }
        texArray.Apply();
        return(texArray);
    }
    void Start()
    {
        // Find kernel.
        kernel = compute.FindKernel("ReadTex2DArray");
        // Find define reference to the texture.
        int propResultTex2DArray = Shader.PropertyToID("ResultTexture");

        // Create a 3-dimensional RenderTexture. Note - don't confuse depth with .volumeDepth parameter! It's depth buffer format here!
        rtArr = new RenderTexture(width, height, 0, RenderTextureFormat.ARGB32);
        // Allow compute program to write into this texture.
        rtArr.enableRandomWrite = true;
        // Init the rendertexture as a Tex2DArray.
        rtArr.dimension = UnityEngine.Rendering.TextureDimension.Tex2DArray;
        // Set the slice count.
        rtArr.volumeDepth = layerCount;
        // Create the texture.
        rtArr.Create();

        // Set texture to the compute program.
        compute.SetTexture(kernel, propResultTex2DArray, rtArr);

        // Calculate dispatch dimensions.
        int xDim = Mathf.Max(8, rtArr.width / 8);
        int yDim = Mathf.Max(8, rtArr.height / 8);
        int zDim = Mathf.Max(8, rtArr.volumeDepth / 8);

        // For layer visualization.
        compute.SetInt("_LayerCount", layerCount);

        // Dispatch compute program.
        compute.Dispatch(kernel, xDim, yDim, zDim);

        // Create a request and pass in a method to capture the callback.
        AsyncGPUReadback.Request(rtArr, 0, 0, width, 0, height, 0, layerCount, new Action <AsyncGPUReadbackRequest>
                                 (
                                     (AsyncGPUReadbackRequest request) =>
        {
            if (!request.hasError)
            {
                // Create CPU-side texture array.
                tex2DArrRead = new Texture2DArray(width, height, request.layerCount, TextureFormat.ARGB32, false);

                // Copy the data.
                for (var i = 0; i < request.layerCount; i++)
                {
                    tex2DArrRead.SetPixels32(request.GetData <Color32>(i).ToArray(), i);
                }

                // Save.
                tex2DArrRead.Apply();
            }
        }
                                 ));
    }
Beispiel #11
0
    public static void ConvertBlueNoiseTexturesToArray()
    {
        Texture2DArray bt = new Texture2DArray(64, 64, 16, TextureFormat.R8, false);

        for (int i = 0; i < 16; i++)
        {
            var t = AssetDatabase.LoadAssetAtPath <Texture2D>("Assets/Vts/Resources/Textures/BlueNoise/" + i + ".png");
            bt.SetPixels32(t.GetPixels32(), i);
        }
        bt.wrapMode = TextureWrapMode.Repeat;
        AssetDatabase.CreateAsset(bt, "Assets/Vts/Resources/Textures/BlueNoise.asset");
    }
Beispiel #12
0
 public void EndUpdate()
 {
     if (m_updateRequired)
     {
         m_fgTexture.SetPixels32(m_fgColors);
         m_fgTexture.Apply();
         for (int i = 0; i < m_fogOfWarTextures.depth; ++i)
         {
             m_fogOfWarTextures.SetPixels32(m_fogOfWarColors[i], i);
         }
         m_fogOfWarTextures.Apply();
         m_updateRequired = false;
     }
 }
        public void Initialize()
        {
            var properties      = ConfigManager.Properties;
            var textures        = new Dictionary <string, Texture2D>();
            var textureIndexMap = new Dictionary <string, int>();
            var nextIndex       = 0;

            foreach (var typeString in properties.BlockTypeMap)
            {
                var type          = typeString.Key;
                var blockNameList = typeString.Value;
                _blockTypeMap[type] = new List <int>();
                foreach (var blockName in blockNameList)
                {
                    var blockData = ConfigManager.Load <BlockData>(blockName);
                    _blockTypeMap[type].Add(blockData.BlockId);
                    _dict.Add(blockData.BlockId, blockData);
                    _blockNameMap.Add(blockName, blockData.BlockId);
                    if (blockData.TextureNames == null || blockData.TextureNames.Count <= 0)
                    {
                        continue;
                    }
                    for (var faceIndex = 0; faceIndex < 6; faceIndex++)
                    {
                        var textureName  = blockData.TextureNames[faceIndex % blockData.TextureNames.Count];
                        var textureIndex = (blockData.BlockId << 3) + faceIndex;
                        if (!textures.ContainsKey(textureName))
                        {
                            textures[textureName]        = AssetManager.Load <Texture2D>(textureName);
                            textureIndexMap[textureName] = nextIndex++;
                        }
                        _blockTextureMappings.Add(textureIndex, textureIndexMap[textureName]);
                    }
                }
            }
            BlockTextures = new Texture2DArray(properties.BlockTextureWidth, properties.BlockTextureHeight,
                                               textures.Count, properties.BlockTextureFormat, true)
            {
                wrapModeU = TextureWrapMode.Repeat,
                wrapModeV = TextureWrapMode.Repeat,
                wrapModeW = TextureWrapMode.Repeat
            };
            foreach (var texture in textures)
            {
                BlockTextures.SetPixels32(texture.Value.GetPixels32(), textureIndexMap[texture.Key]);
            }
            BlockTextures.Apply();
            IsInitialized = true;
        }
Beispiel #14
0
        public Texture2DArray Generate(TAMSoleImagesPack pack, List <TAMTone> tones, List <TAMMipmapLevel> levels)
        {
            var levelsCount   = levels.Count;
            var tonesCount    = tones.Count;
            var maxResolution = new IntVector2(
                pack.Columns[tones[0]][levels[levelsCount - 1]].width,
                pack.Columns[tones[0]][levels[levelsCount - 1]].height);

            var tamTexture        = new Texture2DArray(maxResolution.X, maxResolution.Y, tonesCount, TextureFormat.RGBA32, true, true);
            var currentResolution = maxResolution;

            for (var levelIndex = 0; levelIndex < levelsCount; levelIndex++)
            {
                for (int toneIndex = 0; toneIndex < tonesCount; toneIndex++)
                {
                    var array = new Color[currentResolution.X * currentResolution.Y];
                    for (int x = 0; x < currentResolution.X; x++)
                    {
                        for (int y = 0; y < currentResolution.Y; y++)
                        {
                            Color newColor = pack.Columns[tones[toneIndex]][levels[levelsCount - 1 - levelIndex]].GetPixel(x, y);
                            array[x + (y * currentResolution.X)] = newColor;
                        }
                    }
                    tamTexture.SetPixels(array, toneIndex, levelIndex);
                }
                currentResolution = new IntVector2(currentResolution.X / 2, currentResolution.Y / 2);
            }

            var lowerLevelTam = CreateAutomaticGeneratedLowerMipmaps(currentResolution * 2, tones,
                                                                     pack.Columns.ToDictionary(
                                                                         p => p.Key,
                                                                         p => p.Value[levels[0]]
                                                                         ));

            var neededMipLevelsCount = (int)Mathf.Log(currentResolution.X, 2);

            for (var levelIndex = 0; levelIndex < neededMipLevelsCount; levelIndex++)
            {
                for (int toneIndex = 0; toneIndex < tonesCount; toneIndex++)
                {
                    tamTexture.SetPixels32(lowerLevelTam.GetPixels32(toneIndex, levelIndex + 1), toneIndex, levelIndex + levelsCount);
                }
            }

            tamTexture.Apply(false);
            return(tamTexture);
        }
    public static int SetPixels32(IntPtr l)
    {
        int result;

        try
        {
            int num = LuaDLL.lua_gettop(l);
            if (num == 3)
            {
                Texture2DArray texture2DArray = (Texture2DArray)LuaObject.checkSelf(l);
                Color32[]      colors;
                LuaObject.checkArray <Color32>(l, 2, out colors);
                int arrayElement;
                LuaObject.checkType(l, 3, out arrayElement);
                texture2DArray.SetPixels32(colors, arrayElement);
                LuaObject.pushValue(l, true);
                result = 1;
            }
            else if (num == 4)
            {
                Texture2DArray texture2DArray2 = (Texture2DArray)LuaObject.checkSelf(l);
                Color32[]      colors2;
                LuaObject.checkArray <Color32>(l, 2, out colors2);
                int arrayElement2;
                LuaObject.checkType(l, 3, out arrayElement2);
                int miplevel;
                LuaObject.checkType(l, 4, out miplevel);
                texture2DArray2.SetPixels32(colors2, arrayElement2, miplevel);
                LuaObject.pushValue(l, true);
                result = 1;
            }
            else
            {
                LuaObject.pushValue(l, false);
                LuaDLL.lua_pushstring(l, "No matched override function SetPixels32 to call");
                result = 2;
            }
        }
        catch (Exception e)
        {
            result = LuaObject.error(l, e);
        }
        return(result);
    }
        void OnWizardCreate()
        {
            if (string.IsNullOrEmpty(Name) || Textures == null || Textures.Length == 0)
            {
                Debug.LogError("No name or textures assigned to texture array.");
                return;
            }

            if (!SystemInfo.supports2DArrayTextures)
            {
                Debug.LogError("Array textures are not supported!");
                return;
            }

            Texture2D      first        = Textures[0];
            Texture2DArray textureArray = new Texture2DArray(first.width, first.height, Textures.Length, first.format, first.mipmapCount > 1);

            if (!Advanced.ReadWriteEnabled && (SystemInfo.copyTextureSupport & CopyTextureSupport.DifferentTypes) == CopyTextureSupport.DifferentTypes)
            {
                textureArray.Apply(false, true);

                for (int i = 0; i < Textures.Length; i++)
                {
                    Graphics.CopyTexture(Textures[i], 0, textureArray, i);
                }
            }
            else
            {
                for (int i = 0; i < Textures.Length; i++)
                {
                    textureArray.SetPixels32(Textures[i].GetPixels32(), i);
                }

                textureArray.Apply(true, !Advanced.ReadWriteEnabled);
            }

            textureArray.filterMode = Advanced.FilterMode;
            textureArray.anisoLevel = Advanced.AnisoLevel;
            textureArray.wrapMode   = Advanced.WrapMode;

            System.IO.Directory.CreateDirectory(Directory);
            AssetDatabase.CreateAsset(textureArray, Path.Combine(Directory, Name + ".asset"));
        }
Beispiel #17
0
        private Texture2DArray CreateTexture(int size, Color32 fill, int count, out Color32[][] colors)
        {
            Texture2DArray result = new Texture2DArray(size, size, count, TextureFormat.RGBA32, true);

            result.wrapMode   = TextureWrapMode.Clamp;
            result.filterMode = FilterMode.Bilinear;
            colors            = new Color32[count][];
            Color color = fill;

            for (int k = 0; k < count; ++k)
            {
                bool skip = !m_gameState.IsLocalPlayer(k);

#if UNITY_EDITOR
                if (k == 0)
                {
                    skip  = false;
                    color = m_transparentColor;
                }
                else
                {
                    color = fill;
                }
#endif
                if (skip)
                {
                    continue;
                }
                colors[k] = new Color32[size * size];
                for (int i = 0; i < size; ++i)
                {
                    for (int j = 0; j < size; ++j)
                    {
                        colors[k][i * size + j] = color;
                    }
                }

                result.SetPixels32(colors[k], k);
            }

            return(result);
        }
    public void LoadVariableData(APIComm.VariableData data)
    {
        texturArray = new Texture2DArray(data.LongitudeRes, data.LatitudeRes, data.TimeRes, TextureFormat.RGBA32, false, false);
        for (int t = 0; t < data.TimeRes; t++)
        {
            Color32[] colors = new Color32[data.LatitudeRes * data.LongitudeRes];
            for (int lat = 0; lat < data.LatitudeRes; lat++)
            {
                for (int lon = 0; lon < data.LongitudeRes; lon++)
                {
                    colors[lat * data.LongitudeRes + lon] = gradient.Evaluate(data.ValueNorm(t, 0, lat, lon));
                }
            }
            texturArray.SetPixels32(colors, t, 0);
        }
        texturArray.Apply(false);
        var material = GetComponent <Renderer>().material;

        material.SetTexture("Texture2DArray_2FDB4295", texturArray);
    }
Beispiel #19
0
        /// <summary>
        /// Gets terrain metallic gloss map texture array containing each terrain tile in a seperate array slice.
        /// </summary>
        /// <param name="archive">Archive index.</param>
        /// <param name="stayReadable">Texture should stay readable.</param>
        /// <param name="nonAlphaFormat">Non-alpha TextureFormat.</param>
        /// <returns>Texture2DArray or null</returns>
        public Texture2DArray GetTerrainMetallicGlossMapTextureArray(
            int archive,
            bool stayReadable = false,
            SupportedNonAlphaTextureFormats nonAlphaFormat = SupportedNonAlphaTextureFormats.RGB24)
        {
            Color32[] defaultMetallicGlossMap;

            // Load texture file and check count matches terrain tiles
            TextureFile textureFile = new TextureFile(Path.Combine(Arena2Path, TextureFile.IndexToFileName(archive)), FileUsage.UseMemory, true);
            int         numSlices   = 0;

            if (textureFile.RecordCount == 56)
            {
                numSlices = textureFile.RecordCount;
            }
            else
            {
                return(null);
            }

            Texture2DArray textureArray;
            int            width;
            int            height;

            // try to import first replacement texture for tile archive to determine width and height of replacement texture set (must be the same for all replacement textures for Texture2DArray)
            if (TextureReplacement.CustomMetallicGlossExist(archive, 0, 0))
            {
                Texture2D metallicGlossMap = TextureReplacement.LoadCustomMetallicGloss(archive, 0, 0);
                width  = metallicGlossMap.width;
                height = metallicGlossMap.height;
            }
            else
            {
                // create default texture array (1x1 texture)
                width  = 1;
                height = 1;
            }

            textureArray = new Texture2DArray(width, height, numSlices, TextureFormat.ARGB32, MipMaps);

            defaultMetallicGlossMap = new Color32[width * height];
            for (int i = 0; i < width * height; i++)
            {
                defaultMetallicGlossMap[i] = new Color32(0, 0, 0, 255);
            }

            // Rollout tiles into texture array
            for (int record = 0; record < textureFile.RecordCount; record++)
            {
                Texture2D metallicGlossMap;
                // Import custom texture(s)
                if (TextureReplacement.CustomMetallicGlossExist(archive, record, 0))
                {
                    metallicGlossMap = TextureReplacement.LoadCustomMetallicGloss(archive, record, 0);
                }
                else
                {
                    //continue;
                    metallicGlossMap = new Texture2D(width, height, TextureFormat.ARGB32, MipMaps);
                    metallicGlossMap.SetPixels32(defaultMetallicGlossMap);
                }

                // enforce that all custom metallicgloss map textures have the same dimension (requirement of Texture2DArray)
                if ((metallicGlossMap.width != width) || (metallicGlossMap.height != height))
                {
                    Debug.LogErrorFormat("Terrain: failed to inject metallicgloss maps for archive {0}, incorrect size at record {1}.", archive, record);
                    return(null);
                }

                // Insert into texture array
                textureArray.SetPixels32(metallicGlossMap.GetPixels32(), record, 0);
            }
            textureArray.Apply(true, !stayReadable);

            // Change settings for these textures
            textureArray.wrapMode   = TextureWrapMode.Clamp;
            textureArray.anisoLevel = 8;

            return(textureArray);
        }
Beispiel #20
0
        /// <summary>
        /// Gets terrain normal map texture array containing each terrain tile in a seperate array slice.
        /// </summary>
        /// <param name="archive">Archive index.</param>
        /// <param name="stayReadable">Texture should stay readable.</param>
        /// <param name="nonAlphaFormat">Non-alpha TextureFormat.</param>
        /// <returns>Texture2DArray or null</returns>
        public Texture2DArray GetTerrainNormalMapTextureArray(
            int archive,
            bool stayReadable = false,
            SupportedAlphaTextureFormats alphaFormat = SupportedAlphaTextureFormats.RGBA32)
        {
            // Load texture file and check count matches terrain tiles
            TextureFile textureFile = new TextureFile(Path.Combine(Arena2Path, TextureFile.IndexToFileName(archive)), FileUsage.UseMemory, true);
            int         numSlices   = 0;

            if (textureFile.RecordCount == 56)
            {
                numSlices = textureFile.RecordCount;
            }
            else
            {
                return(null);
            }

            Texture2DArray textureArray;
            int            width;
            int            height;

            // try to import first replacement texture for tile archive to determine width and height of replacement texture set (must be the same for all replacement textures for Texture2DArray)
            if (TextureReplacement.CustomNormalExist(archive, 0, 0))
            {
                Texture2D normalMap = TextureReplacement.LoadCustomNormal(archive, 0, 0);
                width  = normalMap.width;
                height = normalMap.height;
            }
            else
            {
                return(null);
            }

            textureArray = new Texture2DArray(width, height, numSlices, TextureFormat.ARGB32, MipMaps);

            // Rollout tiles into texture array
            for (int record = 0; record < textureFile.RecordCount; record++)
            {
                Texture2D normalMap;
                // Import custom texture(s)
                if (TextureReplacement.CustomNormalExist(archive, record, 0))
                {
                    normalMap = TextureReplacement.LoadCustomNormal(archive, record, 0);
                }
                else // if current texture does not exist
                {
                    Debug.LogErrorFormat("Terrain: imported archive {0} does not contain normal for record {1}.", archive, record);
                    return(null);
                }

                // enforce that all custom normal map textures have the same dimension (requirement of Texture2DArray)
                if ((normalMap.width != width) || (normalMap.height != height))
                {
                    Debug.LogErrorFormat("Terrain: failed to inject normal maps for archive {0}, incorrect size at record {1}.", archive, record);
                    return(null);
                }

                // Insert into texture array
                textureArray.SetPixels32(normalMap.GetPixels32(), record, 0);
            }
            textureArray.Apply(true, !stayReadable);

            // Change settings for these textures
            textureArray.wrapMode   = TextureWrapMode.Clamp;
            textureArray.anisoLevel = 8;

            return(textureArray);
        }
Beispiel #21
0
    private void RebuildSprites()
    {
        SpriteWasRemoved = false;
        m_camInfo.transform.hasChanged = true;

        m_spriteRts = new List <SpriteRT>();
        foreach (RayTracingSprite sprite in m_Sprites)
        {
            if (sprite == null)
            {
                continue;
            }
            RayTracingSprite.TextureMode texMode = sprite.TexSize;
            Texture2D tex    = sprite.GetTexture();
            Texture2D normal = sprite.GetNormal();
            int       index  = 0;
            switch (texMode)
            {
            case RayTracingSprite.TextureMode.TEX64: break;

            case RayTracingSprite.TextureMode.TEX128:
                if (m_tex128List.Contains(tex))
                {
                    //  Debug.Log("countains!");
                    index = m_tex128List.IndexOf(tex);
                }
                else
                {
                    index = m_tex128List.Count;
                    m_tex128List.Add(tex);
                    m_tex2DArray128.SetPixels32(tex.GetPixels32(), index, 0);
                    m_tex2DArray128_Normal.SetPixels32(normal.GetPixels32(), index, 0);
                }
                break;

            case RayTracingSprite.TextureMode.TEX256:
                if (m_tex256List.Contains(tex))
                {
                    //   Debug.Log("countains!");
                    index = m_tex256List.IndexOf(tex);
                }
                else
                {
                    index = m_tex256List.Count;
                    m_tex256List.Add(tex);
                    m_tex2DArray256.SetPixels32(tex.GetPixels32(), index, 0);
                    m_tex2DArray256_Normal.SetPixels32(tex.GetPixels32(), index, 0);
                }
                break;

            case RayTracingSprite.TextureMode.TEX512:
                if (m_tex512List.Contains(tex))
                {
                    //   Debug.Log("countains!");
                    index = m_tex512List.IndexOf(tex);
                }
                else
                {
                    index = m_tex512List.Count;
                    m_tex512List.Add(tex);
                    m_tex2DArray512.SetPixels32(tex.GetPixels32(), index, 0);
                    m_tex2DArray512_Normal.SetPixels32(tex.GetPixels32(), index, 0);
                }
                break;
            }
            SpriteRT newSprite = sprite.GenSprite();
            newSprite.TextureIndex = index;
            m_spriteRts.Add(newSprite);
        }
        CreateComputeBuffer(ref m_SpriteBuffer, m_spriteRts, 36);
        m_tex2DArray512.Apply();
        m_tex2DArray256.Apply();
        m_tex2DArray128.Apply();
        m_RebuildCompletely = true;
    }
 public void SetTexturePixels(int texture_index, Color32[] pixels) => TextureArray.SetPixels32(pixels, texture_index);
        void LoadWorldTextures()
        {
            requireTextureArrayUpdate = false;

            // Init texture array
            if (worldTextures == null)
            {
                worldTextures = new List <WorldTexture> ();
            }
            else
            {
                worldTextures.Clear();
            }
            if (worldTexturesDict == null)
            {
                worldTexturesDict = new Dictionary <Texture2D, int> ();
            }
            else
            {
                worldTexturesDict.Clear();
            }

            // Clear definitions
            if (voxelDefinitions != null)
            {
                // Voxel Definitions no longer are added to the dictionary, clear the index field.
                for (int k = 0; k < voxelDefinitionsCount; k++)
                {
                    if (voxelDefinitions [k] != null)
                    {
                        voxelDefinitions [k].Reset();
                    }
                }
            }
            else
            {
                voxelDefinitions = new VoxelDefinition [128];
            }
            voxelDefinitionsCount = 0;
            if (voxelDefinitionsDict == null)
            {
                voxelDefinitionsDict = new Dictionary <string, VoxelDefinition> ();
            }
            else
            {
                voxelDefinitionsDict.Clear();
            }
            if (sessionUserVoxels == null)
            {
                sessionUserVoxels = new List <VoxelDefinition> ();
            }

            // The null voxel definition
            VoxelDefinition nullVoxelDefinition = ScriptableObject.CreateInstance <VoxelDefinition> ();

            nullVoxelDefinition.name           = "Null";
            nullVoxelDefinition.hidden         = true;
            nullVoxelDefinition.canBeCollected = false;
            nullVoxelDefinition.ignoresRayCast = true;
            nullVoxelDefinition.renderType     = RenderType.Empty;
            AddVoxelTextures(nullVoxelDefinition);

            // Check default voxel
            if (defaultVoxel == null)
            {
                defaultVoxel = Resources.Load <VoxelDefinition> ("VoxelPlay/Defaults/DefaultVoxel");
            }
            AddVoxelTextures(defaultVoxel);

            // Add all biome textures
            if (world.biomes != null)
            {
                for (int k = 0; k < world.biomes.Length; k++)
                {
                    BiomeDefinition biome = world.biomes [k];
                    if (biome == null)
                    {
                        continue;
                    }
                    if (biome.voxelTop != null)
                    {
                        AddVoxelTextures(biome.voxelTop);
                        if (biome.voxelTop.biomeDirtCounterpart == null)
                        {
                            biome.voxelTop.biomeDirtCounterpart = biome.voxelDirt;
                        }
                    }
                    AddVoxelTextures(biome.voxelDirt);
                    if (biome.vegetation != null)
                    {
                        for (int v = 0; v < biome.vegetation.Length; v++)
                        {
                            AddVoxelTextures(biome.vegetation [v].vegetation);
                        }
                    }
                    if (biome.trees != null)
                    {
                        for (int t = 0; t < biome.trees.Length; t++)
                        {
                            ModelDefinition tree = biome.trees [t].tree;
                            if (tree == null)
                            {
                                continue;
                            }
                            for (int b = 0; b < tree.bits.Length; b++)
                            {
                                AddVoxelTextures(tree.bits [b].voxelDefinition);
                            }
                        }
                    }
                    if (biome.ores != null)
                    {
                        for (int v = 0; v < biome.ores.Length; v++)
                        {
                            // ensure proper size
                            if (biome.ores [v].veinMinSize == biome.ores [v].veinMaxSize && biome.ores [v].veinMaxSize == 0)
                            {
                                biome.ores [v].veinMinSize   = 2;
                                biome.ores [v].veinMaxSize   = 6;
                                biome.ores [v].veinsCountMin = 1;
                                biome.ores [v].veinsCountMax = 2;
                            }
                            AddVoxelTextures(biome.ores [v].ore);
                        }
                    }
                }
            }

            // Special voxels
            if (enableClouds)
            {
                if (world.cloudVoxel == null)
                {
                    world.cloudVoxel = Resources.Load <VoxelDefinition> ("VoxelPlay/Defaults/VoxelCloud");
                }
                AddVoxelTextures(world.cloudVoxel);
            }

            // Add additional world voxels
            if (world.moreVoxels != null)
            {
                for (int k = 0; k < world.moreVoxels.Length; k++)
                {
                    AddVoxelTextures(world.moreVoxels [k]);
                }
            }

            // Add all items' textures are available
            if (world.items != null)
            {
                int itemCount = world.items.Length;
                for (int k = 0; k < itemCount; k++)
                {
                    ItemDefinition item = world.items [k];
                    if (item != null && item.category == ItemCategory.Voxel)
                    {
                        AddVoxelTextures(item.voxelType);
                    }
                }
            }

            // Add any other voxel found inside Defaults
            VoxelDefinition [] vdd = Resources.LoadAll <VoxelDefinition> ("VoxelPlay/Defaults");
            for (int k = 0; k < vdd.Length; k++)
            {
                AddVoxelTextures(vdd [k]);
            }

            // Add any other voxel found inside World directory
            if (!string.IsNullOrEmpty(world.name))
            {
                vdd = Resources.LoadAll <VoxelDefinition> ("Worlds/" + world.name);
                for (int k = 0; k < vdd.Length; k++)
                {
                    AddVoxelTextures(vdd [k]);
                }

                // Add any other voxel found inside a resource directory with same name of world (if not placed into Worlds directory)
                vdd = Resources.LoadAll <VoxelDefinition> (world.name);
                for (int k = 0; k < vdd.Length; k++)
                {
                    AddVoxelTextures(vdd [k]);
                }
            }

            // Add any other voxel found inside a resource directory under the world definition asset
            if (!string.IsNullOrEmpty(world.resourceLocation))
            {
                vdd = Resources.LoadAll <VoxelDefinition> (world.resourceLocation);
                for (int k = 0; k < vdd.Length; k++)
                {
                    AddVoxelTextures(vdd [k]);
                }
            }

            // Add connected textures
            ConnectedTexture [] ctt = Resources.LoadAll <ConnectedTexture> ("");
            for (int k = 0; k < ctt.Length; k++)
            {
                ConnectedTexture ct = ctt [k];
                VoxelDefinition  vd = ctt [k].voxelDefinition;
                if (vd == null || vd.index == 0)
                {
                    continue;
                }
                for (int j = 0; j < ct.config.Length; j++)
                {
                    ct.config [j].textureIndex = AddTexture(ct.config [j].texture, null, null, null);
                }
                ct.Init();
            }

            // Add user provided voxels during playtime
            int count = sessionUserVoxels.Count;

            for (int k = 0; k < count; k++)
            {
                AddVoxelTextures(sessionUserVoxels [k]);
            }
            sessionUserVoxelsLastIndex = voxelDefinitionsCount - 1;

            // Add transparent voxel definitions for the see-through effect
            if (seeThrough)
            {
                int lastOne = voxelDefinitionsCount; // this loop will add voxels so end at the last regular voxel definition (don't process see-through versions)
                for (int k = 0; k < lastOne; k++)
                {
                    VoxelDefinition vd = voxelDefinitions [k];
                    if (vd.renderType == RenderType.CutoutCross)
                    {
                        vd.seeThroughMode = SeeThroughMode.FullyInvisible;
                    }
                    else
                    {
                        if (vd.seeThroughMode == SeeThroughMode.Transparency)
                        {
                            if (vd.renderType.supportsAlphaSeeThrough())
                            {
                                vd.seeThroughVoxelTempTransp = CreateSeeThroughVoxelDefinition(vd);
                            }
                            else
                            {
                                vd.seeThroughMode = SeeThroughMode.FullyInvisible;
                            }
                        }
                    }
                }
            }

            // Create array texture
            int textureCount = worldTextures.Count;

            if (textureCount > 0)
            {
                Texture2DArray pointFilterTextureArray = new Texture2DArray(textureSize, textureSize, textureCount, TextureFormat.ARGB32, hqFiltering);
                if (enableReliefMapping || !enableSmoothLighting)
                {
                    pointFilterTextureArray.wrapMode = TextureWrapMode.Repeat;
                }
                else
                {
                    pointFilterTextureArray.wrapMode = TextureWrapMode.Clamp;
                }
                pointFilterTextureArray.filterMode = hqFiltering ? FilterMode.Bilinear : FilterMode.Point;
                pointFilterTextureArray.mipMapBias = -mipMapBias;
                for (int k = 0; k < textureCount; k++)
                {
                    if (worldTextures [k].colorsAndEmission != null)
                    {
                        pointFilterTextureArray.SetPixels32(worldTextures [k].colorsAndEmission, k);
                    }
                    else if (worldTextures [k].normalsAndElevation != null)
                    {
                        pointFilterTextureArray.SetPixels32(worldTextures [k].normalsAndElevation, k);
                    }
                }
                worldTextures.Clear();

                pointFilterTextureArray.Apply(hqFiltering, true);

                // Assign textures to materials
                if (renderingMaterials != null)
                {
                    for (int k = 0; k < renderingMaterials.Length; k++)
                    {
                        if (renderingMaterials [k].usesTextureArray)
                        {
                            Material mat = renderingMaterials [k].material;
                            if (mat != null && mat.HasProperty("_MainTex"))
                            {
                                mat.SetTexture("_MainTex", pointFilterTextureArray);
                            }
                        }
                    }
                }
                matDynamicOpaque.SetTexture("_MainTex", pointFilterTextureArray);
                matDynamicCutout.SetTexture("_MainTex", pointFilterTextureArray);

                if (modelHighlightMat == null)
                {
                    modelHighlightMat = Instantiate <Material> (Resources.Load <Material> ("VoxelPlay/Materials/VP Highlight Model")) as Material;
                }
                modelHighlightMat.SetTexture("_MainTex", pointFilterTextureArray);
            }
        }
        private void OnGUI()
        {
            GUILayout.Space(verticalWindowPadding);
            using (var c = new EditorGUILayout.HorizontalScope())
            {
                GUILayout.Space(horizontalWindowPadding);
                using (var a = new EditorGUILayout.VerticalScope())
                {
                    // Ramp Collection Field
                    EditorGUI.BeginChangeCheck();
                    rampCollectionRaw = (RampCollectionData)EditorGUILayout.ObjectField(rampCollectionLabel,
                                                                                        rampCollectionRaw, typeof(RampCollectionData), false);
                    if (rampCollectionRaw != null)
                    {
                        // Create serialized asset mirror if missing
                        if (EditorGUI.EndChangeCheck() || rampCollection == null)
                        {
                            rampCollection = new SerializedObject(rampCollectionRaw);
                            resolution     = rampCollection.FindProperty(nameof(RampCollectionData.resolution));
                            height         = rampCollection.FindProperty(nameof(RampCollectionData.height));
                            ramps          = rampCollection.FindProperty(nameof(RampCollectionData.ramps));
                        }
                    }
                    else
                    {
                        EditorGUI.EndChangeCheck();
                        EditorGUILayout.Space(8);
                        using (var b = new EditorGUILayout.HorizontalScope())
                        {
                            rampCollectionName = EditorGUILayout.TextField(rampCollectionNameLabel, rampCollectionName);
                            GUILayout.Space(32);
                            if (GUILayout.Button(createNewCollectionLabel))
                            {
                                rampCollectionPath = "Assets/Toon Shader URP/Ramp Collections";
                                rampCollectionRaw  = CreateInstance <RampCollectionData>();
                                if (rampCollectionName == null || rampCollectionName.Length == 0)
                                {
                                    rampCollectionName     = "New Ramp Collection";
                                    rampCollectionRaw.name = rampCollectionName;
                                }
                                Directory.CreateDirectory($"{Application.dataPath}/Toon Shader URP/Ramp Collections");
                                AssetDatabase.CreateAsset(rampCollectionRaw,
                                                          $"{rampCollectionPath}/{rampCollectionName}.asset");
                                rampCollection = new SerializedObject(rampCollectionRaw);
                                SerializedProperty name = rampCollection.FindProperty(nameof(RampCollectionData.arrayName));
                                resolution = rampCollection.FindProperty(nameof(RampCollectionData.resolution));
                                height     = rampCollection.FindProperty(nameof(RampCollectionData.height));
                                ramps      = rampCollection.FindProperty(nameof(RampCollectionData.ramps));

                                name.stringValue    = rampCollectionName;
                                resolution.intValue = defaultRampResolution;
                                height.intValue     = defaultRowHeight;
                                rampCollection.ApplyModifiedProperties();
                            }
                            else
                            {
                                rampCollection = null;
                                ramps          = null;
                            }
                        }
                        EditorGUILayout.Space(8);
                    }

                    if (rampCollection != null && ramps != null)
                    {
                        rampCollection.UpdateIfRequiredOrScript();
                        resolution.intValue = EditorGUILayout.IntField(rampResolutionLabel, resolution.intValue);
                        height.intValue     = Mathf.Clamp(EditorGUILayout.IntField(rowHeightLabel, height.intValue), 1, int.MaxValue);
                        EditorGUILayout.PropertyField(ramps);
                        rampCollection.ApplyModifiedProperties();

                        if (Event.current.type == EventType.MouseUp ||
                            (Event.current.type == EventType.KeyUp &&
                             Event.current.keyCode == KeyCode.Return))
                        {
                            AssetDatabase.SaveAssets();
                        }

                        using (var d = new EditorGUILayout.HorizontalScope())
                        {
                            if (GUILayout.Button(saveRampTextureArrayLabel))
                            {
                                Texture2DArray rasterizedRampArray = new Texture2DArray(
                                    resolution.intValue, 1, ramps.arraySize, TextureFormat.RGBA32, false)
                                {
                                    wrapMode   = TextureWrapMode.Clamp,
                                    filterMode = FilterMode.Bilinear,
                                    anisoLevel = 0
                                };
                                for (int i = 0; i < ramps.arraySize; ++i)
                                {
                                    Color32[] arrayRamp = new Color32[resolution.intValue];
                                    for (int j = 0; j < resolution.intValue; ++j)
                                    {
                                        arrayRamp[j] = rampCollectionRaw.ramps[i].Evaluate((float)j / resolution.intValue);
                                    }
                                    rasterizedRampArray.SetPixels32(arrayRamp, i);
                                }
                                rasterizedRampArray.Apply();
                                string path = EditorUtility.SaveFilePanelInProject(
                                    "Save Texture Array", defaultRampTextureArrayName, "asset",
                                    "Select a location to save your generated texture array in.");

                                if (path.Length != 0)
                                {
                                    AssetDatabase.CreateAsset(rasterizedRampArray, path);
                                }
                            }
                            else if (GUILayout.Button(saveRampTextureAtlasLabel))
                            {
                                Texture2D rasterizedRampAtlas = new Texture2D(
                                    resolution.intValue, ramps.arraySize * height.intValue, TextureFormat.RGBA32, false)
                                {
                                    wrapMode   = TextureWrapMode.Clamp,
                                    filterMode = FilterMode.Bilinear,
                                    anisoLevel = 0,
                                };
                                for (int i = 0; i < ramps.arraySize; ++i)
                                {
                                    Color32[] rampRow = new Color32[resolution.intValue];
                                    for (int j = 0; j < resolution.intValue; ++j)
                                    {
                                        rampRow[j] = rampCollectionRaw.ramps[i].Evaluate((float)j / resolution.intValue);
                                    }
                                    for (int k = 0; k < height.intValue; ++k)
                                    {
                                        rasterizedRampAtlas.SetPixels32(0, k + (i * height.intValue), resolution.intValue, 1, rampRow);
                                    }
                                }
                                rasterizedRampAtlas.Apply();
                                string path = EditorUtility.SaveFilePanelInProject(
                                    "Save Texture Atlas", defaultRampTextureAtlasName, "png",
                                    "Select a location to save your generated texture atlas in.");

                                if (path.Length != 0)
                                {
                                    string localPath = path.Substring("Assets".Length);
                                    RampAtlasPreprocessor.isRampTexture = true;
                                    File.WriteAllBytes($"{Application.dataPath}/{localPath}", rasterizedRampAtlas.EncodeToPNG());
                                }
                            }
                        }
                    }
                }
                GUILayout.Space(horizontalWindowPadding);
            }
            GUILayout.Space(verticalWindowPadding);
        }
Beispiel #25
0
        void LoadWorldTextures()
        {
            requireTextureArrayUpdate = false;

            // Init texture array
            if (worldTextures == null)
            {
                worldTextures = new List <WorldTexture> ();
            }
            else
            {
                worldTextures.Clear();
            }
            if (worldTexturesDict == null)
            {
                worldTexturesDict = new Dictionary <Texture2D, int> ();
            }
            else
            {
                worldTexturesDict.Clear();
            }

            // Clear definitions
            if (voxelDefinitions != null)
            {
                // Voxel Definitions no longer are added to the dictionary, clear the index field.
                for (int k = 0; k < voxelDefinitionsCount; k++)
                {
                    if (voxelDefinitions [k] != null)
                    {
                        voxelDefinitions [k].Reset();
                    }
                }
            }
            else
            {
                voxelDefinitions = new VoxelDefinition[128];
            }
            voxelDefinitionsCount = 0;
            if (voxelDefinitionsDict == null)
            {
                voxelDefinitionsDict = new Dictionary <string, VoxelDefinition> ();
            }
            else
            {
                voxelDefinitionsDict.Clear();
            }
            if (sessionUserVoxels == null)
            {
                sessionUserVoxels = new List <VoxelDefinition> ();
            }

            // The null voxel definition
            VoxelDefinition nullVoxelDefinition = ScriptableObject.CreateInstance <VoxelDefinition> ();

            nullVoxelDefinition.hidden         = true;
            nullVoxelDefinition.canBeCollected = false;
            nullVoxelDefinition.name           = "Null";
            AddVoxelTextures(nullVoxelDefinition);

            // Check default voxel
            if (defaultVoxel == null)
            {
                defaultVoxel = Resources.Load <VoxelDefinition> ("VoxelPlay/Defaults/DefaultVoxel");
            }
            AddVoxelTextures(defaultVoxel);

            // Add all biome textures
            if (world.biomes != null)
            {
                for (int k = 0; k < world.biomes.Length; k++)
                {
                    BiomeDefinition biome = world.biomes [k];
                    if (biome == null)
                    {
                        continue;
                    }
                    AddVoxelTextures(biome.voxelTop);
                    if (biome.voxelTop.biomeDirtCounterpart == null)
                    {
                        biome.voxelTop.biomeDirtCounterpart = biome.voxelDirt;
                    }
                    AddVoxelTextures(biome.voxelDirt);
                    if (biome.vegetation != null)
                    {
                        for (int v = 0; v < biome.vegetation.Length; v++)
                        {
                            AddVoxelTextures(biome.vegetation [v].vegetation);
                        }
                    }
                    if (biome.trees != null)
                    {
                        for (int t = 0; t < biome.trees.Length; t++)
                        {
                            ModelDefinition tree = biome.trees [t].tree;
                            if (tree == null)
                            {
                                continue;
                            }
                            for (int b = 0; b < tree.bits.Length; b++)
                            {
                                AddVoxelTextures(tree.bits [b].voxelDefinition);
                            }
                        }
                    }
                    if (biome.ores != null)
                    {
                        for (int v = 0; v < biome.ores.Length; v++)
                        {
                            // ensure proper size
                            if (biome.ores [v].veinMinSize == biome.ores [v].veinMaxSize && biome.ores [v].veinMaxSize == 0)
                            {
                                biome.ores [v].veinMinSize   = 2;
                                biome.ores [v].veinMaxSize   = 6;
                                biome.ores [v].veinsCountMin = 1;
                                biome.ores [v].veinsCountMax = 2;
                            }
                            AddVoxelTextures(biome.ores [v].ore);
                        }
                    }
                }
            }

            // Special voxels
            if (world.cloudVoxel == null)
            {
                world.cloudVoxel = Resources.Load <VoxelDefinition> ("VoxelPlay/Defaults/VoxelCloud");
            }
            AddVoxelTextures(world.cloudVoxel);

            // Add additional world voxels
            if (world.moreVoxels != null)
            {
                for (int k = 0; k < world.moreVoxels.Length; k++)
                {
                    AddVoxelTextures(world.moreVoxels [k]);
                }
            }

            // Add all items' textures are available
            if (world.items != null)
            {
                int itemCount = world.items.Length;
                for (int k = 0; k < itemCount; k++)
                {
                    ItemDefinition item = world.items [k];
                    if (item.category == ItemCategory.Voxel)
                    {
                        AddVoxelTextures(item.voxelType);
                    }
                }
            }


            // Add any other voxel found inside Defaults
            VoxelDefinition[] vdd = Resources.LoadAll <VoxelDefinition> ("VoxelPlay/Defaults");
            for (int k = 0; k < vdd.Length; k++)
            {
                AddVoxelTextures(vdd [k]);
            }

            // Add any other voxel found inside World directory
            vdd = Resources.LoadAll <VoxelDefinition> ("Worlds/" + world.name);
            for (int k = 0; k < vdd.Length; k++)
            {
                AddVoxelTextures(vdd [k]);
            }

            // Add any other voxel found inside a resource directory with same name of world (if not placed into Worlds directory)
            vdd = Resources.LoadAll <VoxelDefinition> (world.name);
            for (int k = 0; k < vdd.Length; k++)
            {
                AddVoxelTextures(vdd [k]);
            }

            // Add user provided voxels during playtime
            int count = sessionUserVoxels.Count;

            for (int k = 0; k < count; k++)
            {
                AddVoxelTextures(sessionUserVoxels [k]);
            }

            // Unload textures (doesn't work at runtime on PC! this commented section should be removed)
//			#if !UNITY_EDITOR
//			for (int k = 0; k < voxelDefinitionsCount; k++) {
//				VoxelDefinition vd = voxelDefinitions [k];
//				if (vd.index == 0)
//					continue;
//				if (vd.textureTop != null)
//					Resources.UnloadAsset (vd.textureTop);
//				if (vd.textureTopEmission != null)
//					Resources.UnloadAsset (vd.textureTopEmission);
//				if (vd.textureTopNRM != null)
//					Resources.UnloadAsset (vd.textureTopNRM);
//				if (vd.textureTopDISP != null)
//					Resources.UnloadAsset (vd.textureTopDISP);
//				if (vd.textureLeft != null)
//					Resources.UnloadAsset (vd.textureLeft);
//				if (vd.textureLeftEmission != null)
//					Resources.UnloadAsset (vd.textureLeftEmission);
//				if (vd.textureLeftNRM != null)
//					Resources.UnloadAsset (vd.textureLeftNRM);
//				if (vd.textureLeftDISP != null)
//					Resources.UnloadAsset (vd.textureLeftDISP);
//				if (vd.textureRight != null)
//					Resources.UnloadAsset (vd.textureRight);
//				if (vd.textureRightEmission != null)
//					Resources.UnloadAsset (vd.textureRightEmission);
//				if (vd.textureRightNRM != null)
//					Resources.UnloadAsset (vd.textureRightNRM);
//				if (vd.textureRightDISP != null)
//					Resources.UnloadAsset (vd.textureRightDISP);
//				if (vd.textureBottom != null)
//					Resources.UnloadAsset (vd.textureBottom);
//				if (vd.textureBottomEmission != null)
//					Resources.UnloadAsset (vd.textureBottomEmission);
//				if (vd.textureBottomNRM != null)
//					Resources.UnloadAsset (vd.textureBottomNRM);
//				if (vd.textureBottomDISP != null)
//					Resources.UnloadAsset (vd.textureBottomDISP);
//				if (vd.textureSide != null)
//					Resources.UnloadAsset (vd.textureSide);
//				if (vd.textureSideEmission != null)
//					Resources.UnloadAsset (vd.textureSideEmission);
//				if (vd.textureSideNRM != null)
//					Resources.UnloadAsset (vd.textureSideNRM);
//				if (vd.textureSideDISP != null)
//					Resources.UnloadAsset (vd.textureSideDISP);
//				if (vd.textureForward != null)
//					Resources.UnloadAsset (vd.textureForward);
//				if (vd.textureForwardEmission != null)
//					Resources.UnloadAsset (vd.textureForwardEmission);
//				if (vd.textureForwardNRM != null)
//					Resources.UnloadAsset (vd.textureForwardNRM);
//				if (vd.textureForwardDISP != null)
//					Resources.UnloadAsset (vd.textureForwardDISP);
//			}
//			#endif

            // Create array texture
            int textureCount = worldTextures.Count;

            if (textureCount > 0)
            {
                Texture2DArray pointFilterTextureArray = new Texture2DArray(textureSize, textureSize, textureCount, TextureFormat.ARGB32, hqFiltering);
                if (enableReliefMapping || !enableSmoothLighting)
                {
                    pointFilterTextureArray.wrapMode = TextureWrapMode.Repeat;
                }
                else
                {
                    pointFilterTextureArray.wrapMode = TextureWrapMode.Clamp;
                }
                pointFilterTextureArray.filterMode = hqFiltering ? FilterMode.Bilinear : FilterMode.Point;
                pointFilterTextureArray.mipMapBias = -mipMapBias;
                for (int k = 0; k < textureCount; k++)
                {
                    if (worldTextures [k].colorsAndEmission != null)
                    {
                        pointFilterTextureArray.SetPixels32(worldTextures [k].colorsAndEmission, k);
                    }
                    else if (worldTextures [k].normalsAndElevation != null)
                    {
                        pointFilterTextureArray.SetPixels32(worldTextures [k].normalsAndElevation, k);
                    }
                }
                worldTextures.Clear();

                pointFilterTextureArray.Apply(hqFiltering, true);

                // Assign textures to materials
                for (int k = 0; k < materials.Length; k++)
                {
                    if (materials[k] != null && materials[k].HasProperty("_MainTex"))
                    {
                        materials[k].SetTexture("_MainTex", pointFilterTextureArray);
                    }
                }

                if (modelHighlightMat == null)
                {
                    modelHighlightMat = Instantiate <Material> (Resources.Load <Material> ("VoxelPlay/Materials/VP Highlight Model")) as Material;
                }
                modelHighlightMat.SetTexture("_MainTex", pointFilterTextureArray);
            }
        }
Beispiel #26
0
        public void CollectInfos()
        {
            TerrainData     terrainData = terrain.terrainData;
            Texture2D       baseTexture = TerrainToMeshTool.BakeBaseTexture(terrain.terrainData);
            List <Material> matAdd      = new List <Material>();
            List <Material> matFirst    = new List <Material>();
            Material        matBase     = new Material(shaderBase);

            matBase.SetTexture("_MainTex", baseTexture);
            float[,] heights = terrain.terrainData.GetHeights(0, 0, terrain.terrainData.heightmapWidth, terrain.terrainData.heightmapHeight);
            Texture2DArray texArray        = null;
            Material       terrainMaterial = new Material(Shader.Find("Nature/Terrain/Diffuse"));

            if (layerType == LayerType.SingleMesh_LayerIndexTexture)
            {
                bakedControlTexture = TerrainToMeshTool.BakeTextureIndex(terrain.terrainData);
                {
                    Texture firstTexture = terrainData.splatPrototypes[0].texture;
                    texArray = new Texture2DArray(firstTexture.width, firstTexture.height, terrainData.splatPrototypes.Length, TextureFormat.ARGB32, true, true);
                    for (int i = 0; i < terrainData.splatPrototypes.Length; i++)
                    {
                        texArray.SetPixels32(terrainData.splatPrototypes[i].texture.GetPixels32(), i);
                    }
                    texArray.Apply();
                }
                if (terrainTextureIndexMaterial == null)
                {
                    terrainTextureIndexMaterial = new Material(Shader.Find("Mobile/TerrainTextureIndex"));
                }
                else
                {
                    terrainTextureIndexMaterial.shader = Shader.Find("Mobile/TerrainTextureIndex");
                }
                terrainTextureIndexMaterial.SetTexture("_IndexControl", bakedControlTexture);
                terrainTextureIndexMaterial.SetTexture("_TexArray", texArray);
                terrainTextureIndexMaterial.SetFloat("_TexArrayNum", terrainData.splatPrototypes.Length);

                terrainTextureIndexMaterial.SetVectorArray("_ScaleOffset", GetScaleOffsets(terrainData));
            }
            else if (layerType == LayerType.SingleMesh_Max4Layer)
            {
                bakedControlTexture = TerrainToMeshTool.BakeControlTexture(terrain.terrainData, roots[0], gridSize, 4);
            }
            else
            {
                for (int l = 0; l < terrainData.alphamapLayers; l++)
                {
                    LayerProperty lp = l < layerProperties.Length ? layerProperties[l] : null;
                    matAdd.Add(TerrainToMeshTool.GetMaterial(terrain, l, shaderAdd, lp));
                    matFirst.Add(TerrainToMeshTool.GetMaterial(terrain, l, shaderFirst, lp));
                }
            }

            int w        = terrainData.heightmapWidth - 1;
            int gridNumX = w / gridSize;

            tiles = new TerrainToMeshTile[gridNumX * gridNumX];

            for (int x = 0; x < gridNumX; x++)
            {
                for (int y = 0; y < gridNumX; y++)
                {
                    GameObject objGrid = new GameObject("mesh_" + x + "_" + y);
                    objGrid.transform.SetParent(GetRootTransform(), false);
                    TerrainToMeshTile tile = objGrid.AddComponent <TerrainToMeshTile>();
                    tiles[y * gridNumX + x] = tile;
                    tile.matBase            = matBase;
                    tile.matAdd             = matAdd;
                    tile.matFirst           = matFirst;
                    tile.lodLevel           = -1;
                    tile.terrainData        = terrainData;
                    tile.heights            = heights;
                    tile.roots                       = roots;
                    tile.trees                       = new Node[roots.Length];
                    tile.layerType                   = layerType;
                    tile.lodPower                    = lodPower;
                    tile.terrainMaterial             = terrainMaterial;
                    tile.bakedControlTexture         = bakedControlTexture;
                    tile.terrainTextureIndexMaterial = terrainTextureIndexMaterial;
                    tile.texArray                    = texArray;
                    for (int lod = 0; lod < roots.Length; lod++)
                    {
                        tile.trees[lod] = roots[lod].FindSizeNode(x * gridSize, y * gridSize, gridSize);
                        TerrainToMeshTool.SetNodeSkirts(tile.trees[lod], tile.trees[lod]);
                    }
                }
            }

            for (int x = 0; x < gridNumX; x++)
            {
                for (int y = 0; y < gridNumX; y++)
                {
                    tiles[y * gridNumX + x].CollectMeshInfo(maxLodLevel);
                }
            }
        }