Exemple #1
0
    /**
     * Initializing the terrain with:
     * + Procedural Terrain Heightmap
     * + Splat Map based on Terrain Elevation and Steepness
     **/
    void initTerrain()
    {
        m_terrainSize = Mathf.ClosestPowerOfTwo(Random.Range(1024, 1024));

        Terrain terrain = this.GetComponent <Terrain>();

        generateMap(terrain, Random.Range(3f, 7f));
        paintMap(terrain);
        fillTreeInstances(terrain);
        fillDetailMap(terrain);

        // Place Player ontop of Terrain
        GameObject player = ((GameObject)GameObject.Find("Player"));
        Vector3    temp   = player.transform.position;

        temp.x = Random.Range(100, terrain.terrainData.size.x - 100);
        temp.z = Random.Range(100, terrain.terrainData.size.z - 100);
        temp.y = terrain.SampleHeight(temp) + 2f;
        player.transform.position = temp;
    }
Exemple #2
0
        public Deque(int minCapacity = 8)
        {
            if (minCapacity <= 0)
            {
                throw new ArgumentException("Capacity must be positive and nonzero.");
            }

            //Find next highest power of two
            int capacity = Mathf.ClosestPowerOfTwo(minCapacity);

            if (capacity < minCapacity)
            {
                capacity *= 2;
            }

            _array = new T[capacity];
            recalculateIndexMask();
            _front = 0;
            _count = 0;
        }
Exemple #3
0
    const float kfAnimationDuration = 1.0F / 10.0F; //x fps
    // Update is called once per frame
    void Update()
    {
        fAnimationTime += Time.deltaTime;

        bool bDoAnimation = false;

        if (animate && fAnimationTime >= kfAnimationDuration)
        {
            fAnimationTime = 0.0F;
            bDoAnimation   = true;
        }
        resolution = Mathf.ClosestPowerOfTwo(resolution);
        if (_eCurrentMode != _mode || _currentResolution != resolution || _currentScale != scale || bDoAnimation)
        {
            MakeTexture();
            FillTexture();
            _eCurrentMode      = _mode;
            _currentResolution = resolution;
            _currentScale      = scale;
        }
    }
    bool CheckSplatmap()
    {
        if (Splatmap == null)
        {
            return(false);
        }
        FixFormat(Splatmap);

        if (Splatmap.height != Splatmap.width)
        {
            EditorUtility.DisplayDialog("Wrong size", "Splatmap must be square (width and height must be the same)", "Cancel");
            return(false);
        }
        if (Mathf.ClosestPowerOfTwo(Splatmap.width) != Splatmap.width)
        {
            EditorUtility.DisplayDialog("Wrong size", "Splatmap width and height must be a power of two", "Cancel");
            return(false);
        }

        return(true);
    }
Exemple #5
0
    public void RefreshAll(bool resetTextures = true)
    {
        if (resetTextures)
        {
            ResetTextures();
        }

        int xPowOf2 = Mathf.ClosestPowerOfTwo(Screen.width), yPowOf2 = Mathf.ClosestPowerOfTwo(Screen.height);

        if (colors == null || colors.Length != xPowOf2 * yPowOf2)
        {
            colors = new Color[xPowOf2 * yPowOf2];
        }


        //if (!baseNoise)
        CreateNoise(xPowOf2, yPowOf2);

        //if (!parasites || parasites.name.Contains(autoParasiteName))
        CreateTexture(xPowOf2, yPowOf2);
    }
Exemple #6
0
        public Texture2D WrapTexture(Texture2D inputTexture)
        {
            UniformsPack uniforms = new UniformsPack();

            uniforms.SetUniform("_Margin", _configuration.Margin);
            uniforms.SetTexture("_InputTex", inputTexture);

            var outSize = (new Vector2(inputTexture.width, inputTexture.height) / (1 + 2 * _configuration.Margin)).ToIntVector2();

            outSize = new IntVector2(Mathf.ClosestPowerOfTwo(outSize.X), Mathf.ClosestPowerOfTwo(outSize.Y));

            return((Texture2D)_textureRenderer.AddOrder(new TextureRenderingTemplate()
            {
                CanMultistep = false,
                Coords = new MyRectangle(0, 0, 1, 1),
                CreateTexture2D = true,
                OutTextureInfo = new ConventionalTextureInfo(outSize.X, outSize.Y, inputTexture.format, false),
                UniformPack = uniforms,
                ShaderName = "Custom/NPR/ArtMapWrapping"
            }).Result); //todo async
        }
        static BitmapsAtlasInfo PackBitmapsAtlas(
            Texture2D[] textures, SwfSettingsData settings)
        {
            var atlas_padding  = Mathf.Max(0, settings.AtlasPadding);
            var max_atlas_size = Mathf.Max(32, settings.AtlasPowerOfTwo
                                ? Mathf.ClosestPowerOfTwo(settings.MaxAtlasSize)
                                : settings.MaxAtlasSize);
            var atlas = new Texture2D(0, 0);
            var rects = atlas.PackTextures(textures, atlas_padding, max_atlas_size);

            while (rects == null)
            {
                max_atlas_size = Mathf.NextPowerOfTwo(max_atlas_size + 1);
                rects          = atlas.PackTextures(textures, atlas_padding, max_atlas_size);
            }
            return(settings.AtlasForceSquare && atlas.width != atlas.height
                                ? BitmapsAtlasToSquare(atlas, rects)
                                : new BitmapsAtlasInfo {
                Atlas = atlas, Rects = rects
            });
        }
    // this function creates a texture3d from an array of texture2Ds
    public Texture3D Create3DTexture(Texture2D[] textures)
    {
        int width  = Mathf.ClosestPowerOfTwo(textures[0].width);
        int height = Mathf.ClosestPowerOfTwo(textures[0].height);
        int depth  = Mathf.ClosestPowerOfTwo(textures.Length);

        Color c = Color.white;

        Texture2D tex2D = new Texture2D(textures[0].width, textures[0].height);
        Texture3D tex3D = new Texture3D(width, height, depth, TextureFormat.RGB24, false);

        tex3D.wrapMode   = TextureWrapMode.Repeat;
        tex3D.filterMode = FilterMode.Point;
        tex3D.anisoLevel = 0;

        Color[] cols = new Color[width * height * depth];

        int ix = 0;

        for (int z = 0; z < depth; z++)
        {
            tex2D = textures[z];

            for (int x = 0; x < width; x++)
            {
                int xindex = (int)((float)x / (float)width) * tex2D.width;

                for (int y = 0; y < height; y++)
                {
                    int yindex = (int)((float)y / (float)height) * tex2D.height;
                    c          = tex2D.GetPixel(xindex, yindex);
                    cols[ix++] = c;
                }
            }
        }

        tex3D.SetPixels(cols);
        tex3D.Apply();
        return(tex3D);
    }
        private void Start()
        {
            volume_renderer = GetComponent <Renderer>();

            x = Mathf.ClosestPowerOfTwo((int)size.x);
            y = Mathf.ClosestPowerOfTwo((int)size.y);
            z = Mathf.ClosestPowerOfTwo((int)size.z);

            texture = new RenderTexture(x, y, z)
            {
                dimension         = UnityEngine.Rendering.TextureDimension.Tex3D,
                volumeDepth       = z,
                wrapMode          = TextureWrapMode.Clamp,
                enableRandomWrite = true
            };

            // Must be set before creation
            texture.Create();

            texture_manipulator.SetTexture(0, "Result", texture);
            texture_manipulator.Dispatch(0, (int)(x / 8), (int)(y / 8), (int)(z / 8));
        }
    // Update is called once per frame
    void Update()
    {
        //Debug.Log(m_masterTimer + " | " + m_currentSamples);
        if (IsPlaying())
        {
            // add audio delta to master timer
            if (metronomeAudioSource.time - m_prevAudioTime < 0)
            {
                m_masterTimer += (metronomeAudioSource.clip.length - m_prevAudioTime) + metronomeAudioSource.time;
            }
            else
            {
                m_masterTimer += (metronomeAudioSource.time - m_prevAudioTime);
            }


            // beat calculation
            m_subBeatTimer = (((metronomeAudioSource.timeSamples + m_timeSampleOffset) * (m_bpm * m_timeSignatureLower / 240.0f * m_timeSignatureUpper)) % (float)m_audioSourceFrequency) / 100000;
            if (m_subBeatTimer < m_prevSubBeatTimer)
            {
                SubBeat();
            }

            // set memory variables
            m_prevSubBeatTimer = m_subBeatTimer;
            m_prevAudioTime    = metronomeAudioSource.time;

//			SyncToAudioSource();
        }
        else
        {
            // clamp lower time signature
            m_timeSignatureLower = Mathf.ClosestPowerOfTwo(m_timeSignatureLower);

            // calculate new units per beat
            //m_unitsPerBeat = (int)Mathf.Pow(Constants.UNITS_PER_BEAT, 2.0f) / m_timeSignatureLower;
            m_unitsPerBeat = Constants.UNITS_PER_BEAT;
        }
    }
    private static void BuildMipFilterTex(int size)
    {
        size = Mathf.ClosestPowerOfTwo(size);
        Texture2D mipFilterTex;

        mipFilterTex            = new Texture2D(size, size, TextureFormat.Alpha8, true);
        mipFilterTex.anisoLevel = 3;
        mipFilterTex.filterMode = FilterMode.Trilinear;
        mipFilterTex.mipMapBias = 0;
        for (int mip = 0; mip < mipFilterTex.mipmapCount; mip++)
        {
            int     len  = size * size;
            Color[] cols = new Color[len];
            float   cval = 1.0f * mip / (mipFilterTex.mipmapCount - 1);
            Color   col  = new Color(cval, cval, cval, cval);
            for (int i = 0; i < len; i++)
            {
                cols[i] = col;
            }
            mipFilterTex.SetPixels(cols, mip);
        }
        mipFilterTex.Apply(false, true);
        switch (size)
        {
        case 64: mipFilterTex64 = mipFilterTex; break;

        case 128: mipFilterTex128 = mipFilterTex; break;

        case 256: mipFilterTex256 = mipFilterTex; break;

        case 512: mipFilterTex512 = mipFilterTex; break;

        case 1024: mipFilterTex1024 = mipFilterTex; break;

        case 2048: mipFilterTex2048 = mipFilterTex; break;

        default: mipFilterTex512 = mipFilterTex; break;
        }
    }
Exemple #12
0
        public void SetMaskResolution(float scale = 1)
        {
            Renderer renderer = this.GetComponent <Renderer>();

            if (renderer != null)
            {
                Material mat = renderer.sharedMaterial;
                if (mat != null)
                {
                    Texture baseMap = mat.GetTexture("_BaseMap");
                    if (baseMap != null)
                    {
                        maskWidth  = (RevealMaskResolution)Mathf.ClosestPowerOfTwo((int)(baseMap.width * scale));
                        maskHeight = (RevealMaskResolution)Mathf.ClosestPowerOfTwo((int)(baseMap.height * scale));
                        if (maskWidth != maskHeight)
                        {
                            Debug.Log(this.gameObject.name);
                        }
                    }
                }
            }
        }
    public static void ValidateTextureMap(Texture2D splatmap)
    {
        if (splatmap == null)
        {
            throw new ArgumentException("The specified splat texture is null");
        }

        if (splatmap.format != TextureFormat.ARGB32)
        {
            throw new ArgumentException("Splatmap should be of type ARGB32. Use the TerrainImporter to fix this.");
        }

        if (splatmap.height != splatmap.width)
        {
            throw new ArgumentException("Splatmap should be square");
        }

        if (Mathf.ClosestPowerOfTwo(splatmap.width) != splatmap.width)
        {
            throw new ArgumentException("Splatmap size should be a power of two");
        }
    }
Exemple #14
0
        public void WriteInThread(IApplyData applyData)
        {
            if (!(applyData is GrassOutput200.ApplyData applyGrassData))
            {
                return;
            }

            if (lockLayers == null || lockPrototypes == null)
            {
                return;                                                           // Don't perform lock if nothing is stored
            }
            if (Mathf.ClosestPowerOfTwo(applyGrassData.Resolution) != resolution)
            {
                return;                                                                               //Don't perform lock if resolution changed
            }
            UnifyPrototypes(ref applyGrassData.detailPrototypes, ref applyGrassData.detailLayers, ref lockPrototypes, ref lockLayers);

            for (int c = 0; c < lockPrototypes.Length; c++)
            {
                Stamp(applyGrassData.detailLayers[c], lockLayers[c], circle.rect.offset, circle.center, circle.fullRadius);
            }
        }
    private void GenerateSkinnedAnimationForGPUBuffer()
    {
        BoidSMR   = TargetBoidToGPUSkin.GetComponentInChildren <SkinnedMeshRenderer>();
        _Animator = TargetBoidToGPUSkin.GetComponentInChildren <Animator>();
        int iLayer = 0;
        AnimatorStateInfo aniStateInfo = _Animator.GetCurrentAnimatorStateInfo(iLayer);

        Mesh  bakedMesh    = new Mesh();
        float sampleTime   = 0;
        float perFrameTime = 0;

        NbFrames     = Mathf.ClosestPowerOfTwo((int)(_AnimationClip.frameRate * _AnimationClip.length));
        perFrameTime = _AnimationClip.length / NbFrames;

        var vertexCount = BoidSMR.sharedMesh.vertexCount;

        VertexAnimationBuffer = new ComputeBuffer(vertexCount * NbFrames, 16);
        Vector4[] vertexAnimationData = new Vector4[vertexCount * NbFrames];
        for (int i = 0; i < NbFrames; i++)
        {
            _Animator.Play(aniStateInfo.shortNameHash, iLayer, sampleTime);
            _Animator.Update(0f);

            BoidSMR.BakeMesh(bakedMesh);

            for (int j = 0; j < vertexCount; j++)
            {
                Vector3 vertex = bakedMesh.vertices[j];
                vertexAnimationData[(j * NbFrames) + i] = vertex;
            }

            sampleTime += perFrameTime;
        }

        VertexAnimationBuffer.SetData(vertexAnimationData);
        BoidMaterial.SetBuffer("vertexAnimation", VertexAnimationBuffer);

        TargetBoidToGPUSkin.SetActive(false);
    }
Exemple #16
0
        /// <summary>
        /// Gets the size of the down sampling.
        /// </summary>
        private static void GetDownSamplingSize(DownSamplingRate rate, out int w, out int h)
        {
#if UNITY_EDITOR
            if (!Application.isPlaying)
            {
                var res = UnityEditor.UnityStats.screenRes.Split('x');
                w = Mathf.Max(64, int.Parse(res[0]));
                h = Mathf.Max(64, int.Parse(res[1]));
            }
            else
#endif
            if (Screen.fullScreenMode == FullScreenMode.Windowed)
            {
                w = Screen.width;
                h = Screen.height;
            }
            else
            {
                w = Screen.currentResolution.width;
                h = Screen.currentResolution.height;
            }

            if (rate == DownSamplingRate.None)
            {
                return;
            }

            var aspect = (float)w / h;
            if (w < h)
            {
                h = Mathf.ClosestPowerOfTwo(h / (int)rate);
                w = Mathf.CeilToInt(h * aspect);
            }
            else
            {
                w = Mathf.ClosestPowerOfTwo(w / (int)rate);
                h = Mathf.CeilToInt(w / aspect);
            }
        }
        private void Blit(Texture2D texture)
        {
            if (renderTexture != null)
            {
                return;
            }

            Texture textureToDownsample;

            // To get a good result from when downsampling the image, the source image must have mip maps.
            // If the source doesn't have mip maps, blit it to a render texture to generate them.
            if (texture.mipmapCount == 1)
            {
                // Can't generate mip maps unless the render texture is a power of two.
                int widthPowerOfTwo  = Mathf.ClosestPowerOfTwo(texture.width);
                int heightPowerOfTwo = Mathf.ClosestPowerOfTwo(texture.height);
                mipRenderTexture           = RenderTexture.GetTemporary(widthPowerOfTwo, heightPowerOfTwo);
                mipRenderTexture.useMipMap = true;
                Graphics.Blit(texture, mipRenderTexture);
                textureToDownsample = mipRenderTexture;
            }
            else
            {
                textureToDownsample = texture;
            }

            int   width       = texture.width;
            int   height      = texture.height;
            float aspectRatio = (float)width / (float)height;

            width  = (int)(IMAGE_HEIGHT * aspectRatio);
            height = IMAGE_HEIGHT;

            renderTexture = RenderTexture.GetTemporary(width, height);
            Graphics.Blit(textureToDownsample, renderTexture);

            // If it exists, dispose the Mip render texture.
            DisposeMipRenderTexture();
        }
Exemple #18
0
    void OnWizardUpdate()
    {
        if (!terrain)
        {
            helpString = "Select a terrain object!";
            isValid    = false;
        }
        else
        {
            if (targetResolution == 0)
            {
                helpString = "Type in your target resolution. Needs to be Power of two";
            }
        }

        if (targetResolution > 0)
        {
            targetResolution = Mathf.ClosestPowerOfTwo(targetResolution);
        }

        if (terrain && targetResolution >= 512)
        {
            if (terrain.terrainData.detailResolution != targetResolution)
            {
                helpString = "Go on and click that button!!!";
                isValid    = true;
            }
            else
            {
                helpString = "Your target resolution is the same as the existing \r\n resolution!";
                isValid    = false;
            }
        }
        else if (targetResolution > 0 && targetResolution < 512)
        {
            helpString = "Your target resolution should be at least 512,\r\n as lower values are not supported by terrain objects!";
            isValid    = false;
        }
    }
Exemple #19
0
 static void ValidateProperty(SerializedProperty property, bool need_pow2, int min_pow2, int max_pow2)
 {
     if (!property.hasMultipleDifferentValues)
     {
         if (property.propertyType == SerializedPropertyType.Integer)
         {
             var last_value = property.intValue;
             if (need_pow2 && !Mathf.IsPowerOfTwo(property.intValue))
             {
                 property.intValue = Mathf.ClosestPowerOfTwo(property.intValue);
             }
             property.intValue = Mathf.Clamp(
                 property.intValue,
                 GetPowerOfTwo(min_pow2),
                 GetPowerOfTwo(max_pow2));
             if (last_value != property.intValue)
             {
                 property.serializedObject.ApplyModifiedProperties();
             }
         }
     }
 }
Exemple #20
0
        public void InitMeshVoxelizer()
        {
            var mesh = SampleMesh();

            if (mesh == null)
            {
                return;
            }
            //defaultMesh = mesh;
            //defaultMaterial =this.spawnObj.GetComponent<MeshRenderer>().sharedMaterial;

            Bounds fireBounds  = this.mediator.bounds;
            Bounds spawnBounds = this.spawnObj.GetComponent <Renderer>().bounds;

            //Debug.Log("box min: " + this.mediator.bounds.min);
            //Debug.Log("box center: " + this.mediator.bounds.center);
            //Debug.Log("box size: " + this.mediator.bounds.size);
            //Debug.Log("spawn box center: " + spawnBounds.center);
            //Debug.Log("spawn box min: " + spawnBounds.min);
            //Debug.Log("spawn box max: " + spawnBounds.max);
            //Debug.Log("spawn box extends: " + spawnBounds.extents);
            //Debug.Log("spawn box size: " + spawnBounds.size);
            //Debug.Log("spawn mesh box center: " + mesh.bounds.center);
            //Debug.Log("spawn mesh box size: " + mesh.bounds.size);

            this.SetObjectCenter();
            this.SetObjectRadius();

            numOfVoxels = Mathf.ClosestPowerOfTwo(this.mediator.fluidSimulator3D.m_width);

            this.gpuVoxelizer = new GPUVoxelizer();
            this.gpuVoxelizer.InitVoxelization(mesh, this.mediator.bounds, numOfVoxels);
            this.voxelsInBounds = gpuVoxelizer.Voxelize(voxelizer, mesh, this.spawnObj.transform, true);

            this.GetComponent <MeshFilter>().sharedMesh = VoxelMesh.Build(this.voxelsInBounds.GetData(), this.voxelsInBounds.UnitLength, true);

            //Debug.LogFormat("!!!!!!!!!!!!!!!!!!!!! Num of triangles: {0}", mesh.triangles.Length);
        }
    public override void OnInspectorGUI()
    {
        serializedObject.Update();

        EditorGUILayout.LabelField("Bakery lightmap group parameters");
        EditorGUILayout.Space();

        if (ftraceMode.intValue != 2)
        {
            ftraceResolution.intValue = (int)Mathf.ClosestPowerOfTwo(EditorGUILayout.IntSlider("Resolution", ftraceResolution.intValue, 1, 8192));
        }

        EditorGUILayout.PropertyField(ftraceMode, new GUIContent("Packing mode", "Determines how lightmaps are packed. In Simple mode they are not packed, and all objects sharing this group are drawn on top of each other. This is desired in case they were all unwrapped together and do not overlap. If UVs of different objects overlap, choose PackAtlas to arrange their lightmaps together into a single packed atlas."));

        EditorGUILayout.PropertyField(ftraceRenderMode, new GUIContent("Render Mode", ""));

        EditorGUILayout.PropertyField(ftraceRenderDirMode, new GUIContent("Directional mode", ""));

        ftraceBitmask.intValue = EditorGUILayout.MaskField(new GUIContent("Bitmask", "Lights only affect renderers with overlapping bits"), ftraceBitmask.intValue, selStrings);

        EditorGUILayout.LabelField("");
        EditorGUILayout.LabelField("Experimental");

        //EditorGUILayout.PropertyField(ftraceThickness, new GUIContent("Calculate AO as thickness", ""));
        EditorGUILayout.PropertyField(ftraceSSS, new GUIContent("Subsurface scattering", ""));
        if (ftraceSSS.boolValue)
        {
            EditorGUILayout.PropertyField(ftraceSSSSamples, new GUIContent("Samples", ""));
            EditorGUILayout.PropertyField(ftraceSSSDensity, new GUIContent("Density", ""));
            EditorGUILayout.PropertyField(ftraceSSSColor, new GUIContent("Color", ""));
        }

        EditorGUILayout.PropertyField(ftraceFakeShadowBias, new GUIContent("Normal offset", "Fake normal offset for surface samples. Might be useful when applying very strong normal maps."));
        EditorGUILayout.PropertyField(ftraceTransparentSelfShadow, new GUIContent("Transparent selfshadow", "Start rays behind the surface so it doesn't cast shadows on self. Might be useful for translucent foliage."));
        EditorGUILayout.PropertyField(ftraceFlipNormal, new GUIContent("Flip normal", "Treat faces as flipped."));

        serializedObject.ApplyModifiedProperties();
    }
        /// <summary>
        /// Enables the user to choose an omnidirectional camera's resolution.
        /// </summary>
        /// <param name="omnidirectionalPixelResolution"></param> The omnidirectional pixel resolution.
        /// <returns></returns> The omnidirectional pixel resolution.
        private static Vector2Int SubsectionOmnidirectional(Vector2Int omnidirectionalPixelResolution)
        {
            // Rich text is used to hide some parts of the text.
            EditorStyles.label.richText = true;
            // Display a slider for resolution width.
            string label         = "Resolution: width: ";
            string tooltip       = "Sensor width in pixels.";
            int    newPixelWidth = Mathf.Clamp(Mathf.ClosestPowerOfTwo(omnidirectionalPixelResolution.x), _omnidirectionalMinResolutionWidth, _omnidirectionalMaxResolutionWidth);

            newPixelWidth = EditorGUILayout.IntSlider(new GUIContent(label, tooltip), newPixelWidth, _omnidirectionalMinResolutionWidth, _omnidirectionalMaxResolutionWidth);
            newPixelWidth = Mathf.Clamp(Mathf.ClosestPowerOfTwo(newPixelWidth), _omnidirectionalMinResolutionWidth, _omnidirectionalMaxResolutionWidth);
            // Display a disabled slider showing the value of the resolution height.
            int  newPixelHeight = newPixelWidth / 2;
            bool isGUIEnabled   = GUI.enabled;

            GUI.enabled = false;
            label       = "<color=" + GeneralToolkit.backgroundGUIColor + ">Resolution:</color> height: ";
            tooltip     = "Sensor height in pixels.";
            EditorGUILayout.IntSlider(new GUIContent(label, tooltip), newPixelHeight, _omnidirectionalMinResolutionWidth / 2, _omnidirectionalMaxResolutionWidth / 2);
            GUI.enabled = isGUIEnabled;
            // Return the value.
            return(new Vector2Int(newPixelWidth, newPixelHeight));
        }
Exemple #23
0
        void PrepareRenderTexture()
        {
            if (overheadDepthTexture == null)
            {
                // Increase rendering performance by lowering the resoluttion of the depth render.
                int halfScreenResolution = Mathf.ClosestPowerOfTwo(Mathf.FloorToInt(textureResolution));

                // Based on what the platform supports we end up with more or less texture precision for depth.
                RenderTextureFormat bestFormat = RenderTextureFormat.ARGB32;

                // // Only Uncomment this if you need higher precision, should be fine without it.
                // if (SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBFloat)) {
                //   bestFormat = RenderTextureFormat.ARGBFloat;
                // } else if (SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGB64)) {
                //   bestFormat = RenderTextureFormat.ARGB64;
                // }

                overheadDepthTexture = new RenderTexture(
                    halfScreenResolution, halfScreenResolution, 24,
                    bestFormat, RenderTextureReadWrite.Linear);

                overheadDepthTexture.useMipMap        = false;
                overheadDepthTexture.autoGenerateMips = false;
                overheadDepthTexture.filterMode       = FilterMode.Point;
                overheadDepthTexture.antiAliasing     = 2;
            }

            if (overheadDepthTexture.IsCreated() == false)
            {
                overheadDepthTexture.Create();
            }

            if (m_DepthCamera.targetTexture != overheadDepthTexture)
            {
                m_DepthCamera.targetTexture = overheadDepthTexture;
            }
        }
Exemple #24
0
    /// <summary>
    /// Returns a logarithmically scaled and proportionate array of spectrum data from the AudioSource. Doesn't work in WebGL.
    /// </summary>
    /// <param name="source">The AudioSource to take data from.</param>
    /// <param name="spectrumSize">The size of the returned array.</param>
    /// <param name="sampleSize">The size of sample to take from the AudioSource. Must be a power of two.</param>
    /// <param name="windowUsed">The FFTWindow to use when sampling.</param>
    /// <param name="channelUsed">The audio channel to use when sampling.</param>
    /// <returns>A logarithmically scaled and proportionate array of spectrum data from the AudioSource.</returns>
    public static float[] GetLogarithmicSpectrumData(AudioSource source, int spectrumSize, int sampleSize, FFTWindow windowUsed = FFTWindow.BlackmanHarris, int channelUsed = 0)
    {
#if UNITY_WEBGL
        Debug.LogError("Error from SimpleSpectrum: Spectrum data cannot be retrieved from a single AudioSource in WebGL!");
        return(null);
#endif
        float[] spectrum = new float[spectrumSize];

        channelUsed = Mathf.Clamp(channelUsed, 0, 1);

        float[] samples = new float[Mathf.ClosestPowerOfTwo(sampleSize)];

        source.GetSpectrumData(samples, channelUsed, windowUsed);

        float highestLogSampleFreq = Mathf.Log(spectrum.Length + 1, 2); //gets the highest possible logged frequency, used to calculate which sample of the spectrum to use for a bar

        float logSampleFreqMultiplier = sampleSize / highestLogSampleFreq;

        for (int i = 0; i < spectrum.Length; i++)                                                                             //for each float in the output
        {
            float trueSampleIndex = (highestLogSampleFreq - Mathf.Log(spectrum.Length + 1 - i, 2)) * logSampleFreqMultiplier; //gets the index equiv of the logified frequency

            //the true sample is usually a decimal, so we need to lerp between the floor and ceiling of it.

            int sampleIndexFloor = Mathf.FloorToInt(trueSampleIndex);
            sampleIndexFloor = Mathf.Clamp(sampleIndexFloor, 0, samples.Length - 2);                                                        //just keeping it within the spectrum array's range

            float value = Mathf.SmoothStep(spectrum[sampleIndexFloor], spectrum[sampleIndexFloor + 1], trueSampleIndex - sampleIndexFloor); //smoothly interpolate between the two samples using the true index's decimal.

            value = value * trueSampleIndex;                                                                                                //multiply value by its position to make it proportionate;

            value = Mathf.Sqrt(value);                                                                                                      //compress the amplitude values by sqrt(x)

            spectrum[i] = value;
        }
        return(spectrum);
    }
Exemple #25
0
    private void Update()
    {
        if (!source)
        {
            return;
        }
        sampleCount             = Mathf.ClosestPowerOfTwo(sampleCount);
        FFTSpectrumDataChannel0 = new float[sampleCount];

        if (algorithm == BeatDetectionAlgorithm.FrequencyEnergy) //Only gather second channel data with the CConstant Algorithm
        {
            FFTSpectrumDataChannel1 = new float[sampleCount];
        }

        source.GetSpectrumData(FFTSpectrumDataChannel0, 0, fftType);

        if (algorithm == BeatDetectionAlgorithm.FrequencyEnergy)
        {
            source.GetSpectrumData(FFTSpectrumDataChannel1, 1, fftType);
        }

        FindFrequencyBands();
        SmoothenFrequencyBands();
        //SetVolume(volume);
        if (algorithm == BeatDetectionAlgorithm.FrequencyEnergy)
        {
            UpdateCConstantBeatDetection();
        }
        else
        {
            UpdateSpectralFluxBeatDetection();
        }
        if (endScreen)
        {
            endScreen.SetActive(PlayerDead);
        }
    }
Exemple #26
0
 private bool ValidateMainTexture(Texture2D tex)
 {
     if (tex == null)
     {
         EditorGUILayout.HelpBox("Assign a tiling texture", MessageType.Warning);
         return(false);
     }
     if (tex.wrapMode != TextureWrapMode.Repeat)
     {
         EditorGUILayout.HelpBox("Texture wrap mode must be set to Repeat", MessageType.Warning);
         return(false);
     }
     if ((tex.width != Mathf.ClosestPowerOfTwo(tex.width)) || (tex.height != Mathf.ClosestPowerOfTwo(tex.height)))
     {
         EditorGUILayout.HelpBox("Texture size must be power of two", MessageType.Warning);
         return(false);
     }
     if (tex.mipmapCount <= 1)
     {
         EditorGUILayout.HelpBox("Texture must have mip maps", MessageType.Warning);
         return(false);
     }
     return(true);
 }
        /// <summary>
        /// Gets the size of the desampling.
        /// </summary>
        public void GetDesamplingSize(DesamplingRate rate, out int w, out int h)
        {
            var cam = canvas.worldCamera ?? Camera.main;

            h = cam.pixelHeight;
            w = cam.pixelWidth;
            if (rate == DesamplingRate.None)
            {
                return;
            }

            float aspect = (float)w / h;

            if (w < h)
            {
                h = Mathf.ClosestPowerOfTwo(h / (int)rate);
                w = Mathf.CeilToInt(h * aspect);
            }
            else
            {
                w = Mathf.ClosestPowerOfTwo(w / (int)rate);
                h = Mathf.CeilToInt(w / aspect);
            }
        }
    public void Start()
    {
        if (GetComponent <OnlineMapsAdjustToScreen>() != null)
        {
            return;
        }

        if (width < 256)
        {
            throw new Exception("Width must be greater than or equal to 256.");
        }
        if (height < 256)
        {
            throw new Exception("Height must be greater than or equal to 256.");
        }

        width  = Mathf.ClosestPowerOfTwo(width);
        height = Mathf.ClosestPowerOfTwo(height);

        Texture2D texture = new Texture2D(width, height, TextureFormat.RGB24, false);

        texture.name = "Dynamic Map Texture";
        GetComponent <OnlineMaps>().SetTexture(texture);
    }
        void Start()
        {
            m_mountainNoise = new FractalNoise(new PerlinNoise(m_mountainSeed, m_mountainFrq), 6, 1.0f, 1.0f);

            if (!Mathf.IsPowerOfTwo(m_heightMapSize - 1))
            {
                Debug.Log("height map size must be pow2+1 number");
                m_heightMapSize = Mathf.ClosestPowerOfTwo(m_heightMapSize) + 1;
            }

            if (!Mathf.IsPowerOfTwo(m_alphaMapSize))
            {
                Debug.Log("Alpha map size must be pow2 number");
                m_alphaMapSize = Mathf.ClosestPowerOfTwo(m_alphaMapSize);
            }

            float[,] htmap = new float[m_heightMapSize, m_heightMapSize];

            m_terrain = new Terrain[m_tilesX, m_tilesZ];

            //this will center terrain at origin
            m_offset = new Vector2(-m_terrainSize * m_tilesX * 0.5f, -m_terrainSize * m_tilesZ * 0.5f);

            CreateProtoTypes();

            for (int x = 0; x < m_tilesX; x++)
            {
                for (int z = 0; z < m_tilesZ; z++)
                {
                    FillHeights(htmap, x, z);

                    TerrainData terrainData = new TerrainData();

                    terrainData.heightmapResolution = m_heightMapSize;
                    terrainData.SetHeights(0, 0, htmap);
                    terrainData.size            = new Vector3(m_terrainSize, m_terrainHeight, m_terrainSize);
                    terrainData.splatPrototypes = m_splatPrototypes;

                    FillAlphaMap(terrainData);

                    m_terrain[x, z] = Terrain.CreateTerrainGameObject(terrainData).GetComponent <Terrain>();

                    m_terrain[x, z].transform.parent        = transform;
                    m_terrain[x, z].transform.localPosition = new Vector3(m_terrainSize * x + m_offset.x, 0, m_terrainSize * z + m_offset.y);
                    m_terrain[x, z].heightmapPixelError     = m_pixelMapError;
                    m_terrain[x, z].basemapDistance         = m_baseMapDist;
                }
            }

            //Set the neighbours of terrain to remove seams.
            for (int x = 0; x < m_tilesX; x++)
            {
                for (int z = 0; z < m_tilesZ; z++)
                {
                    Terrain right  = null;
                    Terrain left   = null;
                    Terrain bottom = null;
                    Terrain top    = null;

                    if (x > 0)
                    {
                        left = m_terrain[(x - 1), z];
                    }
                    if (x < m_tilesX - 1)
                    {
                        right = m_terrain[(x + 1), z];
                    }

                    if (z > 0)
                    {
                        bottom = m_terrain[x, (z - 1)];
                    }
                    if (z < m_tilesZ - 1)
                    {
                        top = m_terrain[x, (z + 1)];
                    }

                    m_terrain[x, z].SetNeighbors(left, top, right, bottom);
                }
            }
        }
        //针对每一个动作单独生成纹理
        private void GenerateAnimationTexture(Animation animation, AnimationState state)
        {
            //生成动画纹理的名称
            string assetName = string.Format("{0}_{1}", modelGameObject.name, state.name);

            Debug.LogFormat("正在处理 {0}...", assetName);

            //播放并记录
            Debug.Log("播放动画" + state.name);
            animation.Play(state.name);

            AnimationClip clip = state.clip;

            //连接到材质球
            string keyLen = string.Format("_{0}Len", state.name);

            mainMaterial.SetFloat(keyLen, state.length);

            //原始需要帧数
            int   originFrames   = (int)(state.clip.frameRate * state.length);
            int   generateFrames = Mathf.ClosestPowerOfTwo(originFrames);
            float frameGap       = state.length / generateFrames;

            Debug.LogFormat("{0}的原始帧数为{1},处理后为{2},动画长度为{3:0.00},帧间隔为{4:0.00}",
                            state.name,
                            originFrames,
                            generateFrames,
                            state.length,
                            frameGap);

            //纹理宽度为顶点数量,高度为动作帧数
            int       textureWidth     = Mathf.NextPowerOfTwo(combinedMesh.vertexCount);
            int       textureHeight    = generateFrames;
            Texture2D animationTexture = new Texture2D(textureWidth, textureHeight, TextureFormat.RGBAHalf, false);

            for (int v = 0; v < textureHeight; v++)
            {
                //摆pose
                state.time = v * frameGap;
                //采样!!!
                animation.Sample();

                for (int u = 0; u < combinedMesh.vertexCount; u++)
                {
                    //这里必须按照之前合并网格的顺序来搞...
                    int       relativeU = 0;
                    SmartMesh sm        = null;
                    GetSmartMeshByU(u, ref relativeU, out sm);

                    if (sm == null)
                    {
                        EditorUtility.DisplayDialog("错误", "根据UV坐标获取网格信息失败!", "呃...");
                        return;
                    }
                    Mesh mesh = sm.GetAnimationMesh(modelCenter.worldToLocalMatrix);

                    Vector3 vertexPos = mesh.vertices[relativeU];
                    Color   color     = new Color(vertexPos.x, vertexPos.y, vertexPos.z);
                    //将位置保存为颜色
                    animationTexture.SetPixel(u, v, color);
                }
            }

            animationTexture.Apply();

            //保存
            AssetDatabase.CreateAsset(animationTexture, GetAnimationTextureAssetPath(assetName));
            Debug.Log("生成了动画纹理:" + assetName, animationTexture);

            //连接到材质球
            string keyTex = string.Format("_{0}Tex", state.name);

            mainMaterial.SetTexture(keyTex, animationTexture);

            if (state.name.ToLower().Contains("attack"))
            {
                animationAsset.attackAnimLength = clip.length;
            }
            else if (state.name.ToLower().Contains("death"))
            {
                //别问为什么,经验!
                animationAsset.deathAnimLength = clip.length * 0.95f;
            }
        }