Exemplo n.º 1
0
 /// <summary>
 /// Override this to process the pixel in the second pass of the algorithm
 /// </summary>
 /// <param name="pixel">The pixel to quantize</param>
 /// <param name="destinationPixel"></param>
 /// <returns>The quantized value</returns>
 protected override void QuantizePixel(Color32* pixel, Color32* destinationPixel)
 {
     destinationPixel->Red = pixel->Alpha;
     destinationPixel->Blue = pixel->Alpha;
     destinationPixel->Green = pixel->Alpha;
     destinationPixel->Alpha = 255;
 }
		public static void Quantize(Bitmap bitmap, Color32[] colorsTable)
		{
			var bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
			var colorsDictionary = new Dictionary<Color, Color32>();

			unsafe
			{
				var p = (int*)bitmapData.Scan0.ToPointer();
				for (var i = 0; i < bitmap.Height * bitmap.Width; i++)
				{
					var color = Color.FromArgb(p[i]);

					Color32 closestColor;
					if (!colorsDictionary.TryGetValue(color, out closestColor))
					{
						closestColor = FindClosestColor(color, colorsTable);
						colorsDictionary[color] = closestColor;
					}

					p[i] = closestColor.ARGB;
				}
			}

			bitmap.UnlockBits(bitmapData);
		}
Exemplo n.º 3
0
            public override void drawOnImage(ref Image image, ref Image normalMap, BoundingBox boundingBox)
            {
                drawOnImage(ref image, boundingBox);

                if (_normalOption == NormalOption.USE_BACKGROUND) return;

                Image textImage = new Image(image.width, image.height);
                Color32 backgroudColor = new Color32(127, 127, 127, 0);
                textImage.fill(backgroudColor);

                Color32 color = Global.Gray32;
                if (_normalOption == NormalOption.RAISE_TEXT) color = Global.White32;
                if (_normalOption == NormalOption.LOWER_TEXT) color = Global.Black32;

                textImage.drawText(_text, _fontName, _fontSize, _position, _rotation, color, _mirror, AlphaOption.OVERWRITE, 255, BlendMethod.PIXEL);

                BoundingBox bBox = new BoundingBox(boundingBox);
                if (image.width != normalMap.width || image.height != normalMap.height)
                {
                    textImage.rescale(normalMap.width, normalMap.height);
                    bBox.x = (int)((float)bBox.x * (float)normalMap.width / (float)image.width);
                    bBox.w = (int)((float)bBox.w * (float)normalMap.width / (float)image.width);
                    bBox.y = (int)((float)bBox.y * (float)normalMap.height / (float)image.height);
                    bBox.h = (int)((float)bBox.h * (float)normalMap.height / (float)image.height);
                }

                Image normalMapImage = textImage.createNormalMap(_normalScale);
                normalMap.overlay(normalMapImage, textImage, 128, bBox);
            }
Exemplo n.º 4
0
        /// <summary>
        /// Override this to process the pixel in the second pass of the algorithm
        /// </summary>
        /// <param name="pixel">The pixel to quantize</param>
        /// <param name="destinationPixel"></param>
        /// <returns>The quantized value</returns>
        protected override void QuantizePixel(Color32* pixel, Color32* destinationPixel)
        {
            if (pixel->Alpha > 127)
            {
                destinationPixel->Red = pixel->Red;
                destinationPixel->Green = pixel->Green;
                destinationPixel->Blue = pixel->Blue;
                destinationPixel->Alpha = 255;
            }
            else
            {
                int maxColor = pixel->Red;
                if (maxColor < pixel->Green)
                    maxColor = pixel->Green;
                if (maxColor < pixel->Blue)
                    maxColor = pixel->Blue;

                int minColor = pixel->Red;
                if (minColor > pixel->Green)
                    minColor = pixel->Green;
                if (minColor > pixel->Blue)
                    minColor = pixel->Blue;

                var luminance = (byte)((minColor + maxColor) / 2.00f);

                destinationPixel->Red = luminance;
                destinationPixel->Green = luminance;
                destinationPixel->Blue = luminance;

                //destinationPixel->Alpha = 0;
                destinationPixel->Alpha = pixel->Alpha;
            }
        }
Exemplo n.º 5
0
        /// <summary> Override this to process the pixel in the second pass of the algorithm. </summary>
        /// <param name="pixel"> The pixel to quantize. </param>
        /// <returns> The quantized value. </returns>
        protected override byte QuantizePixel( Color32* pixel ) {
            byte paletteIndex = (byte)maxColors; // The color at [_maxColors] is set to transparent

            // Get the palette index if this non-transparent
            if( pixel->Alpha > 0 )
                paletteIndex = (byte)octree.GetPaletteIndex( pixel );

            return paletteIndex;
        }
Exemplo n.º 6
0
 public TextMeshRenderer(LWF lwf, UnityRenderer.TextContext context)
     : base(lwf, context)
 {
     m_matrix = new Matrix(0, 0, 0, 0, 0, 0);
     m_matrixForRender = new Matrix4x4();
     m_colorMult = new UnityEngine.Color();
     m_colorAdd = new UnityEngine.Color();
     m_color = new Color32();
     m_z = -1;
 }
Exemplo n.º 7
0
 public TextMeshRenderer(LWF lwf, TextContext context)
     : base(lwf, context)
 {
     m_mesh = new Mesh();
     m_matrix = new Matrix4x4();
     m_renderMatrix = new Matrix4x4();
     m_colorMult = new UnityEngine.Color();
     m_colorAdd = new UnityEngine.Color();
     m_color = new Color32();
 }
        /// <summary>
        /// Override this to process the pixel in the second pass of the algorithm
        /// </summary>
        /// <param name="pixel">The pixel to quantize</param>
        /// <returns>The quantized value</returns>
        protected override byte QuantizePixel( Color32* pixel )
        {
            byte	colorIndex = 0 ;
            int		colorHash = pixel->ARGB ;

            // Check if the color is in the lookup table
            if ( _colorMap.ContainsKey ( colorHash ) )
                colorIndex = (byte)_colorMap[colorHash] ;
            else
            {
                // Not found - loop through the palette and find the nearest match.
                // Firstly check the alpha value - if < 128, set the transparent color
                if ( pixel->Alpha < 128 )
                    colorIndex = 0; // color 0 is transparent for Freebox
                else
                {
                    // Not transparent...
                    int	leastDistance = int.MaxValue ;
                    int red = pixel->Red ;
                    int green = pixel->Green;
                    int blue = pixel->Blue;

                    // Loop through the freebox palette visible colors, looking for the closest color match
                    for ( int index = 1 ; index < 192 ; index++ )
                    {
                        Color	paletteColor = _colors[index];

                        int	redDistance = paletteColor.R - red ;
                        int	greenDistance = paletteColor.G - green ;
                        int	blueDistance = paletteColor.B - blue ;

                        int		distance = ( redDistance * redDistance ) +
                                           ( greenDistance * greenDistance ) +
                                           ( blueDistance * blueDistance ) ;

                        if ( distance < leastDistance )
                        {
                            colorIndex = (byte)index ;
                            leastDistance = distance ;

                            // And if it's an exact match, exit the loop
                            if ( 0 == distance )
                                break ;
                        }
                    }
                }

                // Now I have the color, pop it into the hashtable for next time
                _colorMap.Add ( colorHash , colorIndex ) ;
            }

            return colorIndex ;
        }
            public override void drawOnImage(ref Image image, BoundingBox boundingBox)
            {
                BitmapDecal decal;
                if (!BitmapDecalCache.Instance.decals.TryGetValue(_url, out decal)) return;

                Image decalImage = new Image(decal.image);
                Color32 color = new Color32(_red, _green, _blue, _alpha);
                decalImage.recolor(Global.Black32, color, false, true);
                decalImage.rotateImage(_rotation);
                if (_mirror) decalImage.flipHorizontally();

                image.blendImage(decalImage, _blendMethod, _position, _alphaOption, _textureAlpha, boundingBox);
            }
Exemplo n.º 10
0
        /// <summary>
        /// Override this to process the pixel in the second pass of the algorithm
        /// </summary>
        /// <param name="pixel">The pixel to quantize</param>
        /// <returns>The quantized value</returns>
        protected override byte QuantizePixel(Color32 pixel)
        {
            double luminance = (pixel.Red * 0.299) + (pixel.Green * 0.587) + (pixel.Blue * 0.114);

            // Gray scale is an intensity map from black to white.
            // Compute the index to the grayscale entry that
            // approximates the luminance, and then round the index.
            // Also, constrain the index choices by the number of
            // colors to do, and then set that pixel's index to the
            // byte value.
            byte colorIndex = (byte)(luminance + 0.5);

            return colorIndex;
        }
		/// <summary>
		/// Override this to process the pixel in the second pass of the algorithm
		/// -- overriden here to limit distance analysis to 216 web-safe colors
		/// </summary>
		/// <param name="pixel">The pixel to quantize</param>
		/// <returns>The quantized value</returns>
		protected override byte QuantizePixel ( Color32* pixel )
		{
			// indexes of the B/W and grey area of the websafe palette:
			int[] indexes = new int[] { 0x00, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF, 0xE0, 0xE1 };

			byte	colorIndex = 0 ;
			int		colorHash = pixel->ARGB ;	

			// Check if the color is in the lookup table
			if ( _colorMap.ContainsKey ( colorHash ) )
				colorIndex = (byte)_colorMap[colorHash] ;
			else
			{
				// Not found - loop through the palette and find the nearest match.
				int	leastDistance = int.MaxValue ;
				int red = pixel->Red ;
				int green = pixel->Green;
				int blue = pixel->Blue;

				// Loop through the entire palette, looking for the closest color match
				foreach ( int index in indexes )
				{
					Color	paletteColor = _colors[index];
					
					int	redDistance = paletteColor.R - red ;
					int	greenDistance = paletteColor.G - green ;
					int	blueDistance = paletteColor.B - blue ;

					int		distance = ( redDistance * redDistance ) + 
						( greenDistance * greenDistance ) + 
						( blueDistance * blueDistance ) ;

					if ( distance < leastDistance )
					{
						colorIndex = (byte)index ;
						leastDistance = distance ;

						// And if it's an exact match, exit the loop
						if ( 0 == distance )
							break ;
					}
				}

				// Now I have the color, pop it into the hashtable for next time
				_colorMap.Add ( colorHash , colorIndex ) ;
			}

			return colorIndex ;
		}
Exemplo n.º 12
0
        /// <summary>
        /// Override this to process the pixel in the second pass of the algorithm
        /// </summary>
        /// <param name="pixel">The pixel to quantize</param>
        /// <param name="destinationPixel"></param>
        /// <returns>The quantized value</returns>
        protected override void QuantizePixel(Color32* pixel, Color32* destinationPixel)
        {
            destinationPixel->Red = pixel->Red;
            destinationPixel->Green = pixel->Green;
            destinationPixel->Blue = pixel->Blue;

            if (pixel->Alpha == _alphaEmmissiveValue)
            {
                destinationPixel->Alpha = 255;
            }
            else
            {
                destinationPixel->Alpha = 0;
            }
        }
Exemplo n.º 13
0
		public static Color32[] Get(byte[] table)
		{
			var result = new Color32[table.Length / 3];

			var tableIndex = 0;
			var resultIndex = 0;
			while (tableIndex < table.Length)
			{
				byte r = table[tableIndex++];
				byte g = table[tableIndex++];
				byte b = table[tableIndex++];

				result[resultIndex++] = new Color32(r, g, b);
			}

			return result;
		}
Exemplo n.º 14
0
        public void TestConstruction()
        {
            // Verify construction from an int.
            Color32 color = new Color32(OpaqueBlack);
            Assert.That(color.Abgr, Is.EqualTo(OpaqueBlack));

            // Verify construction from a bunch of RGBA bytes.
            color = new Color32(0xff, 0x00, 0x00, 0xff);
            Assert.That(color.Abgr, Is.EqualTo(OpaqueRed));

            // Verify Clone
            Color32 other = new Color32(OpaqueBlue);
            color = other.Clone();
            Assert.That(color.Abgr, Is.EqualTo(OpaqueBlue));

            // Verify parse from a string using mixed case.
            color = Color32.Parse("ff0000FF");
            Assert.That(color.Abgr, Is.EqualTo(OpaqueRed));

            // Verify correct behaviour with poorly formed string data.
            //
            // Any string supplied that is less than 8 chars is filled from the front
            // with zeros (and will thus be completely transparent).

            // An fully empty string initalizes to all zeroes (transparent black).
            color = Color32.Parse(string.Empty);
            Assert.That(color.ToString(), Is.EqualTo("00000000"));

            color = Color32.Parse("ffffff");
            Assert.That(color.ToString(), Is.EqualTo("00ffffff"));

            color = Color32.Parse("ff");
            Assert.That(color.ToString(), Is.EqualTo("000000ff"));

            // Only the first eight chars are used for construction from string. Extra
            // chars at the end of the input string are ignored.
            color = Color32.Parse("aabbccddee");
            Assert.That(color.ToString(), Is.EqualTo("aabbccdd"));

            // The input string here has two valid hex values in the first eight chars.
            // ( the "a" and "c" in "Not a c") and those are the only chars that
            // won't be replaced with zeroes.
            color = Color32.Parse("Not a color value");
            Assert.That(color.ToString(), Is.EqualTo("0000a0c0"));
        }
Exemplo n.º 15
0
            public override void SetText(string text)
            {
                base.SetText(text);

                if (m_empty)
                return;

                m_color = m_colors32[0];

                var tn = m_vertices.Length / 4 * 6;
                m_triangles = new int[tn];
                for (int i = 0, j = 0; i < tn; i += 6, j += 4) {
                m_triangles[i + 0] = j + 0;
                m_triangles[i + 1] = j + 1;
                m_triangles[i + 2] = j + 2;
                m_triangles[i + 3] = j + 2;
                m_triangles[i + 4] = j + 1;
                m_triangles[i + 5] = j + 3;
                }
            }
Exemplo n.º 16
0
        public void TestGetSet()
        {
            // Verify getters of default state.
            Color32 color = new Color32();
            byte value = 0x00;
            Assert.That(color.Alpha, Is.EqualTo(value));
            Assert.That(color.Blue, Is.EqualTo(value));
            Assert.That(color.Green, Is.EqualTo(value));
            Assert.That(color.Red, Is.EqualTo(value));

            // Verify getters of newly set state.
            value = 0xAB;
            color = new Color32(value, value, value, value);
            Assert.That(color.Alpha, Is.EqualTo(value));
            Assert.That(color.Blue, Is.EqualTo(value));
            Assert.That(color.Green, Is.EqualTo(value));
            Assert.That(color.Red, Is.EqualTo(value));

            // Verify ABGR and ARGB.
            color = new Color32(OpaqueRed);
            Assert.That(color.Abgr, Is.EqualTo(OpaqueRed));
            Assert.That(color.Argb, Is.EqualTo(OpaqueBlue)); // Red and blue have switched?
        }
Exemplo n.º 17
0
        protected void ApplyShadowZeroAlloc(List<UIVertex> verts, Color32 color, int start, int end, float x, float y)
        {
            UIVertex vt;

            var neededCpacity = verts.Count * 2;
            if (verts.Capacity < neededCpacity)
                verts.Capacity = neededCpacity;

            for (int i = start; i < end; ++i)
            {
                vt = verts[i];
                verts.Add(vt);

                Vector3 v = vt.position;
                v.x += x;
                v.y += y;
                vt.position = v;
                var newColor = color;
                if (m_UseGraphicAlpha)
                    newColor.a = (byte)((newColor.a * verts[i].color.a) / 255);
                vt.color = newColor;
                verts[i] = vt;
            }
        }
Exemplo n.º 18
0
            public override void Render(Matrix matrix, ColorTransform colorTransform,
		int renderingIndex, int renderingCount, bool visible)
            {
                if (!visible || m_empty)
                return;

                Factory factory = (Factory)m_context.factory;
                factory.ConvertColorTransform(
                ref m_colorMult, ref m_colorAdd, colorTransform);
                if (m_colorMult.a <= 0)
                return;

                m_color = m_colors32[0] * m_colorMult + m_colorAdd;

                int z = renderingCount - renderingIndex;
                if (m_z != z || m_matrix.SetWithComparing(matrix)) {
                m_z = z;
                factory.ConvertMatrix(
                ref m_matrixForRender, matrix, 1, z, m_context.height);
                }

                factory.Render(this,
                m_vertices.Length / 4, m_context.settings.font.material);
            }
Exemplo n.º 19
0
 /// <summary>
 /// Process the pixel in the first pass of the algorithm
 /// </summary>
 /// <param name="pixel">The pixel to quantize</param>
 /// <remarks>
 /// This function need only be overridden if your quantize algorithm needs two passes,
 /// such as an Octree quantizer.
 /// </remarks>
 protected override void InitialQuantizePixel(Color32 pixel)
 {
     // Add the color to the octree
     _octree.AddColor(pixel);
 }
Exemplo n.º 20
0
        /// <summary>
        /// Generate a 3D texture from images
        /// </summary>
        /// <param name="inputFolder">Input folder</param>
        /// <param name="outputAssetPath">Output path</param>
        /// <param name="filterMode">Filter mode</param>
        /// <param name="mips">Enable mip maps?</param>
        /// <param name="showConfirm">Show confirm dialog?</param>
        /// <param name="progress">Current progress</param>
        /// <param name="progressMultiplier">Progress multiplier</param>
        /// <param name="clearProgress">Whether to restart progress</param>
        public static void Generate3DTexture(string inputFolder, string outputAssetPath, FilterMode filterMode, bool mips,
                                             bool showConfirm = false, float progress = 0.0f, float progressMultiplier = 1.0f, bool clearProgress = true)
        {
            float currentProgress;

            UnityEditor.EditorUtility.DisplayProgressBar("Progress...", "", progress);
            try
            {
                UnityEditor.EditorPrefs.SetString("WeatherMakerCloudNoiseGeneratorFileName", outputAssetPath);
                Directory.CreateDirectory(inputFolder);
                Texture2D       asset2D    = null;
                Texture3D       asset3D    = null;
                string[]        allFiles   = Directory.GetFiles(inputFolder);
                List <string>   files1     = new List <string>();
                List <string>   files2     = new List <string>();
                List <string>   files3     = new List <string>();
                List <string>   files4     = new List <string>();
                List <string>[] filesArray = new List <string> [0];
                foreach (string file in allFiles.OrderBy(f => f))
                {
                    if (System.IO.Path.GetExtension(file).Equals(".jpg", StringComparison.OrdinalIgnoreCase) || System.IO.Path.GetExtension(file).Equals(".png", StringComparison.OrdinalIgnoreCase))
                    {
                        files1.Add(file);
                    }
                }

                TextureFormat format;

                // if only sub folders, read those...
                if (files1.Count == 0)
                {
                    // try rgba channel approach, 4 folders, one for each channel
                    string[] subFolders = Directory.GetDirectories(inputFolder);
                    for (int i = 0; i < subFolders.Length; i++)
                    {
                        allFiles = Directory.GetFiles(subFolders[i]);
                        Array.Resize(ref filesArray, filesArray.Length + 1);
                        filesArray[filesArray.Length - 1] = (i == 0 ? files1 : (i == 1 ? files2 : (i == 2 ? files3 : files4)));
                        foreach (string file in allFiles.OrderBy(f => f))
                        {
                            if (System.IO.Path.GetExtension(file).Equals(".jpg", StringComparison.OrdinalIgnoreCase) || System.IO.Path.GetExtension(file).Equals(".png", StringComparison.OrdinalIgnoreCase))
                            {
                                filesArray[i].Add(file);
                            }
                        }
                    }
                    switch (subFolders.Length)
                    {
                    case 1:
                        format = TextureFormat.Alpha8;
                        break;

                    case 2:
                        format = TextureFormat.RG16;
                        break;

                    case 3:
                        format = TextureFormat.RGB24;
                        break;

                    default:
                        format = TextureFormat.ARGB32;
                        break;
                    }
                }
                else
                {
                    // files are in the specified folder itself
                    filesArray = new List <string>[] { files1 };
                    format     = TextureFormat.ARGB32;
                }

                if (files1.Count == 0 || (files2.Count != 0 && (files1.Count != files2.Count || files2.Count != files3.Count || files3.Count != files4.Count)))
                {
                    UnityEditor.EditorUtility.DisplayDialog("Unable to create 3D texture", "No files found or mismatching file counts in sub folders", "OK");
                }
                else
                {
                    Color32[] allPixels;
                    Texture2D tex2D = new Texture2D(1, 1, format, false, false);
                    int       idx   = 0;

                    try
                    {
                        tex2D.LoadImage(File.ReadAllBytes(files1[0]));
                        if (files1.Count == 1)
                        {
                            asset2D = UnityEditor.AssetDatabase.LoadAssetAtPath(outputAssetPath, typeof(Texture2D)) as Texture2D;
                        }
                        else
                        {
                            asset3D = UnityEditor.AssetDatabase.LoadAssetAtPath(outputAssetPath, typeof(Texture3D)) as Texture3D;
                        }
                        bool saveAsset = false;
                        if (files1.Count == 1)
                        {
                            if (asset2D == null || asset2D.width != tex2D.width || asset2D.height != tex2D.height ||
                                asset2D.format != format || asset2D.filterMode != filterMode)
                            {
                                saveAsset = true;
                                asset2D   = new Texture2D(tex2D.width, tex2D.height, format, mips)
                                {
                                    filterMode = filterMode,
                                    wrapMode   = TextureWrapMode.Repeat,
                                    name       = "Texture2D (Weather Maker)"
                                };
                            }
                        }
                        else if (asset3D == null || asset3D.width != tex2D.width || asset3D.height != tex2D.height || asset3D.depth != files1.Count ||
                                 asset3D.format != format || asset3D.filterMode != filterMode)
                        {
                            saveAsset = true;
                            asset3D   = new Texture3D(tex2D.width, tex2D.height, files1.Count, format, mips)
                            {
                                filterMode = filterMode,
                                wrapMode   = TextureWrapMode.Repeat,
                                name       = "Texture3D (Weather Maker)"
                            };
                        }
                        allPixels = new Color32[tex2D.width * tex2D.height * files1.Count];
                        if (files2.Count == 0)
                        {
                            for (int fileIndex = 0; fileIndex < files1.Count; fileIndex++)
                            {
                                string file = files1[fileIndex];
                                tex2D.LoadImage(File.ReadAllBytes(file));
                                Color32[] pixels = tex2D.GetPixels32();
                                for (int pixelIndex = 0; pixelIndex < pixels.Length; pixelIndex++)
                                {
                                    Color32 p = pixels[pixelIndex];
                                    if (format == TextureFormat.Alpha8)
                                    {
                                        byte b = Math.Min(p.r, p.a);
                                        allPixels[idx].r = b;
                                        allPixels[idx].g = b;
                                        allPixels[idx].b = b;
                                        allPixels[idx].a = b;
                                    }
                                    else if (asset2D != null)
                                    {
                                        p.r            = p.g = p.b = (byte)Math.Min(255, ((int)p.r + (int)p.g + (int)p.b + (int)p.a));
                                        p.a            = 255;
                                        allPixels[idx] = p;
                                    }
                                    else
                                    {
                                        allPixels[idx] = p;
                                    }
                                    idx++;
                                }
                                currentProgress = (progress + (((float)(fileIndex + 1) / (float)filesArray[0].Count) * progressMultiplier));
                                UnityEditor.EditorUtility.DisplayProgressBar("Progress...", "", currentProgress);
                            }
                        }
                        else
                        {
                            int       lastLength = -1;
                            Color32[] subPixels  = new Color32[tex2D.width * tex2D.height];
                            for (int fileIndex = 0; fileIndex < filesArray[0].Count; fileIndex++)
                            {
                                for (int subFileIndex = 0; subFileIndex < filesArray.Length; subFileIndex++)
                                {
                                    string file = filesArray[subFileIndex][fileIndex];
                                    tex2D.LoadImage(File.ReadAllBytes(file));
                                    Color32[] imgPixels = tex2D.GetPixels32();
                                    if (lastLength != -1 && subPixels.Length != lastLength)
                                    {
                                        UnityEditor.EditorUtility.DisplayDialog("Unable to create 3D texture", "Mismatching image size in " + file, "OK");
                                        throw new InvalidOperationException("Mismatching image size in " + file);
                                    }
                                    lastLength = subPixels.Length;
                                    for (int pixelIndex = 0; pixelIndex < imgPixels.Length; pixelIndex++)
                                    {
                                        switch (subFileIndex)
                                        {
                                        case 0:
                                            subPixels[pixelIndex].r = Math.Min(imgPixels[pixelIndex].r, imgPixels[pixelIndex].a);
                                            break;

                                        case 1:
                                            subPixels[pixelIndex].g = Math.Min(imgPixels[pixelIndex].r, imgPixels[pixelIndex].a);
                                            break;

                                        case 2:
                                            subPixels[pixelIndex].b = Math.Min(imgPixels[pixelIndex].r, imgPixels[pixelIndex].a);
                                            break;

                                        case 3:
                                            subPixels[pixelIndex].a = Math.Min(imgPixels[pixelIndex].r, imgPixels[pixelIndex].a);
                                            break;
                                        }
                                    }
                                }
                                foreach (Color32 pixel in subPixels)
                                {
                                    if (asset2D != null)
                                    {
                                        Color32 p = pixel;
                                        p.r = p.g = p.b = (byte)Math.Min(255, ((int)p.r + (int)p.g + (int)p.b + (int)p.a));
                                        p.a = 255;
                                        allPixels[idx++] = p;
                                    }
                                    else
                                    {
                                        allPixels[idx++] = pixel;
                                    }
                                }
                                currentProgress = (progress + (((float)(fileIndex + 1) / (float)filesArray[0].Count) * progressMultiplier));
                                UnityEditor.EditorUtility.DisplayProgressBar("Progress...", "", currentProgress);
                            }
                        }
                        if (asset2D != null)
                        {
                            asset2D.SetPixels32(allPixels);
                            asset2D.Apply();
                        }
                        else
                        {
                            asset3D.SetPixels32(allPixels);
                            asset3D.Apply(true);
                        }
                        if (saveAsset)
                        {
                            if (asset2D != null)
                            {
                                UnityEditor.AssetDatabase.CreateAsset(asset2D, outputAssetPath);
                            }
                            else
                            {
                                UnityEditor.AssetDatabase.CreateAsset(asset3D, outputAssetPath);
                            }
                        }
                        else
                        {
                            UnityEditor.AssetDatabase.ImportAsset(outputAssetPath);
                        }
                        if (asset2D != null)
                        {
                            byte[] png = asset2D.EncodeToPNG();
                            File.WriteAllBytes(outputAssetPath + ".png", png);
                        }
                        UnityEditor.AssetDatabase.Refresh();
                        if (showConfirm)
                        {
                            if (asset2D != null)
                            {
                                UnityEditor.EditorUtility.DisplayDialog("2D texture saved", "New texture assets created as '" + outputAssetPath + "'", "OK");
                            }
                            else
                            {
                                UnityEditor.EditorUtility.DisplayDialog("3D texture saved", "New texture asset created as '" + outputAssetPath + "'", "OK");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        UnityEditor.EditorUtility.DisplayDialog("Unable to create 3D texture", ex.ToString(), "OK");
                        if (asset2D != null)
                        {
                            GameObject.DestroyImmediate(asset2D);
                        }
                        if (asset3D != null)
                        {
                            GameObject.DestroyImmediate(asset3D);
                        }
                    }
                    finally
                    {
                        GameObject.DestroyImmediate(tex2D);
                    }
                }
            }
            finally
            {
                if (clearProgress)
                {
                    UnityEditor.EditorUtility.ClearProgressBar();
                }
            }
        }
Exemplo n.º 21
0
 /// <summary>
 /// Adds argument.
 /// </summary>
 public OscMessage Add(Color32 value)
 {
     Set(_argInfo.Count, value); return(this);
 }
Exemplo n.º 22
0
    public void SetColor(Color32 color)
    {
        Renderer renderer = GetComponent <Renderer>();

        renderer.material.color = color;
    }
Exemplo n.º 23
0
        private void CreateEvent(DateTime startTime, DateTime endTime, ushort building, Color32 colour)
        {
            double startPercent = startTime.TimeOfDay.TotalHours / 24D;
            double endPercent   = endTime.TimeOfDay.TotalHours / 24D;

            string dateString = "ddd";
            string timeString = Experiments.ExperimentsToggle.NormalClock ? "HH:mm" : "hh:mm tt";

            string startString = startTime.ToString(dateString + " " + timeString, LocaleManager.cultureInfo);
            string endString   = endTime.ToString(dateString + " " + timeString, LocaleManager.cultureInfo);
            string nameString  = Singleton <BuildingManager> .instance.GetBuildingName(building, InstanceID.Empty);

            string tooltip = string.Format(LocalisationStrings.DATETIME_EVENTLOCATION, startString, endString, nameString);

            if (endPercent < startPercent)
            {
                CreateEventBlock(startPercent, 1D, colour, building, tooltip);
                CreateEventBlock(0D, endPercent, colour, building, tooltip);
            }
            else
            {
                CreateEventBlock(startPercent, endPercent, colour, building, tooltip);
            }
        }
Exemplo n.º 24
0
 public WeightedColor(uint weight, Color32 color)
 {
     this.weight = weight;
     this.color  = color;
 }
Exemplo n.º 25
0
 public static extern void fc_get_color32(long L, int i, ref Color32 v);
Exemplo n.º 26
0
    public override void ModifyMesh(VertexHelper helper)
    {
        if (!IsActive() || helper.currentVertCount == 0)
        {
            return;
        }

        List <UIVertex> _vertexList = new List <UIVertex>();

        helper.GetUIVertexStream(_vertexList);

        int nCount = _vertexList.Count;

        switch (GradientType)
        {
        case Type.Vertical:
        {
            float fBottomY = _vertexList[0].position.y;
            float fTopY    = _vertexList[0].position.y;
            float fYPos    = 0f;

            for (int i = nCount - 1; i >= 1; --i)
            {
                fYPos = _vertexList[i].position.y;
                if (fYPos > fTopY)
                {
                    fTopY = fYPos;
                }
                else if (fYPos < fBottomY)
                {
                    fBottomY = fYPos;
                }
            }

            float    fUIElementHeight = 1f / (fTopY - fBottomY);
            UIVertex v = new UIVertex();

            for (int i = 0; i < helper.currentVertCount; i++)
            {
                helper.PopulateUIVertex(ref v, i);
                v.color = Color32.Lerp(EndColor, StartColor, (v.position.y - fBottomY) * fUIElementHeight - Offset);
                helper.SetUIVertex(v, i);
            }
        }
        break;

        case Type.Horizontal:
        {
            float fLeftX  = _vertexList[0].position.x;
            float fRightX = _vertexList[0].position.x;
            float fXPos   = 0f;

            for (int i = nCount - 1; i >= 1; --i)
            {
                fXPos = _vertexList[i].position.x;
                if (fXPos > fRightX)
                {
                    fRightX = fXPos;
                }
                else if (fXPos < fLeftX)
                {
                    fLeftX = fXPos;
                }
            }

            float    fUIElementWidth = 1f / (fRightX - fLeftX);
            UIVertex v = new UIVertex();

            for (int i = 0; i < helper.currentVertCount; i++)
            {
                helper.PopulateUIVertex(ref v, i);
                v.color = Color32.Lerp(EndColor, StartColor, (v.position.x - fLeftX) * fUIElementWidth - Offset);
                helper.SetUIVertex(v, i);
            }
        }
        break;

        default:
            break;
        }
    }
Exemplo n.º 27
0
        /// <summary>
        /// Sets the color.
        /// </summary>
        /// <param name="color">Color.</param>
        public void SetColor(Color32 color)
        {
            currentColorHSV = new ColorHSV(color);

            UpdateView();
        }
Exemplo n.º 28
0
        public void UpdateLine()
        {
            if (this.routeInfo.route.Count <= 1)
            {
                this.DeleteLine();
            }
            else
            {
                bool flag1    = this.line == null;
                int  index1   = 0;
                int  capacity = 0;
                while (index1 < this.listPoint.Count)
                {
                    switch (this.listPoint[index1].connection)
                    {
                    case OIRoutePointInfo.Connection.Line:
                        ++capacity;
                        ++index1;
                        if (index1 >= this.listPoint.Count && this.routeInfo.loop)
                        {
                            ++capacity;
                            continue;
                        }
                        continue;

                    case OIRoutePointInfo.Connection.Curve:
                        if (!this.routeInfo.loop && index1 == this.listPoint.Count - 1)
                        {
                            capacity += (this.routeInfo.loop || index1 != this.listPoint.Count - 1 ? this.segments : 0) + 1;
                            ++index1;
                            continue;
                        }
                        int num1 = 1;
                        for (++index1; index1 < this.listPoint.Count && (this.routeInfo.loop || index1 != this.listPoint.Count - 1) && this.listPoint[index1].isLink; ++index1)
                        {
                            ++num1;
                        }
                        capacity += this.segments * num1 + 1;
                        continue;

                    default:
                        continue;
                    }
                }
                if (!flag1 && this.line.get_points3().Count != capacity)
                {
                    VectorLine.Destroy(ref this.line);
                    flag1 = true;
                }
                if (flag1)
                {
                    this.line    = new VectorLine("Spline", new List <Vector3>(capacity), Studio.Studio.optionSystem.routeLineWidth, (LineType)0);
                    this.objLine = GameObject.Find("Spline");
                    if (Object.op_Implicit((Object)this.objLine))
                    {
                        ((Object)this.objLine).set_name("Spline " + this.routeInfo.name);
                        this.objLine.get_transform().SetParent(Singleton <Scene> .Instance.commonSpace.get_transform());
                    }
                }
                int index2 = 0;
                int index3 = 0;
                while (index2 < this.listPoint.Count)
                {
                    switch (this.listPoint[index2].connection)
                    {
                    case OIRoutePointInfo.Connection.Line:
                        List <Vector3> points3_1 = this.line.get_points3();
                        points3_1[index3] = this.listPoint[index2].position;
                        ++index2;
                        ++index3;
                        if (index2 >= this.listPoint.Count && this.routeInfo.loop)
                        {
                            points3_1[index3] = this.listPoint[0].position;
                        }
                        this.line.set_points3(points3_1);
                        continue;

                    case OIRoutePointInfo.Connection.Curve:
                        if (!this.routeInfo.loop && index2 == this.listPoint.Count - 1)
                        {
                            List <Vector3> points3_2 = this.line.get_points3();
                            points3_2[index3] = this.listPoint[index2].position;
                            ++index2;
                            ++index3;
                            this.line.set_points3(points3_2);
                            continue;
                        }
                        List <Transform> list = ((IEnumerable <Transform>) this.listPoint[index2].transform).ToList <Transform>();
                        int index4            = index2 + 1;
                        int num2 = 1;
                        for (; index4 < this.listPoint.Count && (this.routeInfo.loop || index4 != this.listPoint.Count - 1) && this.listPoint[index4].isLink; ++index4)
                        {
                            list.AddRange((IEnumerable <Transform>) this.listPoint[index4].transform);
                            ++num2;
                        }
                        bool flag2 = index2 == 0 && index4 >= this.listPoint.Count && this.routeInfo.loop;
                        if (index4 >= this.listPoint.Count)
                        {
                            if (!flag2)
                            {
                                list.Add(this.listPoint[0].objectItem.get_transform());
                            }
                        }
                        else
                        {
                            list.Add(this.listPoint[index4].objectItem.get_transform());
                        }
                        this.line.MakeSpline(((IEnumerable <Transform>)list).Select <Transform, Vector3>((Func <Transform, Vector3>)(v => v.get_position())).ToArray <Vector3>(), this.segments * num2, index3, flag2);
                        index2  = index4;
                        index3 += this.segments * num2 + 1;
                        continue;

                    default:
                        continue;
                    }
                }
                this.line.set_joins((Joins)1);
                this.line.set_color(Color32.op_Implicit(this.routeInfo.color));
                this.line.set_continuousTexture(false);
                this.line.set_lineWidth(Studio.Studio.optionSystem.routeLineWidth);
                this.line.Draw3DAuto();
                this.line.set_layer(LayerMask.NameToLayer("Studio/Route"));
                if (!flag1)
                {
                    return;
                }
                this.line.set_active(this.routeInfo.visibleLine);
                Renderer component = (Renderer)this.objLine.GetComponent <Renderer>();
                if (!Object.op_Implicit((Object)component))
                {
                    return;
                }
                component.get_material().set_renderQueue(2900);
            }
        }
Exemplo n.º 29
0
    //--------------------------------------------------------------------------------------------------------------------------------

    static public Mesh CreateSmoothedMesh(Mesh originalMesh, string format, bool vcolors, bool vtangents, bool uv2, bool overwriteMesh)
    {
        if (originalMesh == null)
        {
            Debug.LogWarning("[FunDream_ : Smoothed Mesh] Supplied OriginalMesh is null!\nCan't create smooth normals version.");
            return(null);
        }

        //Create new mesh
        Mesh newMesh = overwriteMesh ? originalMesh : new Mesh();

        if (!overwriteMesh)
        {
//			EditorUtility.CopySerialized(originalMesh, newMesh);
            newMesh.vertices    = originalMesh.vertices;
            newMesh.normals     = originalMesh.normals;
            newMesh.tangents    = originalMesh.tangents;
            newMesh.uv          = originalMesh.uv;
            newMesh.uv2         = originalMesh.uv2;
            newMesh.uv3         = originalMesh.uv3;
            newMesh.uv4         = originalMesh.uv4;
            newMesh.colors32    = originalMesh.colors32;
            newMesh.triangles   = originalMesh.triangles;
            newMesh.bindposes   = originalMesh.bindposes;
            newMesh.boneWeights = originalMesh.boneWeights;

            //Only available from Unity 5.3 onward
            if (originalMesh.blendShapeCount > 0)
            {
                CopyBlendShapes(originalMesh, newMesh);
            }

            newMesh.subMeshCount = originalMesh.subMeshCount;
            if (newMesh.subMeshCount > 1)
            {
                for (int i = 0; i < newMesh.subMeshCount; i++)
                {
                    newMesh.SetTriangles(originalMesh.GetTriangles(i), i);
                }
            }
        }

        //--------------------------------
        // Format

        Vector3 chSign = Vector3.one;

        if (string.IsNullOrEmpty(format))
        {
            format = "xyz";
        }
        format = format.ToLowerInvariant();
        int[] channels   = new int[] { 0, 1, 2 };
        bool  skipFormat = (format == "xyz");
        int   charIndex  = 0;
        int   ch         = 0;

        while (charIndex < format.Length)
        {
            switch (format[charIndex])
            {
            case '-': chSign[ch] = -1; break;

            case 'x': channels[ch] = 0; ch++; break;

            case 'y': channels[ch] = 1; ch++; break;

            case 'z': channels[ch] = 2; ch++; break;

            default: break;
            }
            if (ch > 2)
            {
                break;
            }
            charIndex++;
        }

        //--------------------------------
        //Calculate smoothed normals

        //Iterate, find same-position vertices and calculate averaged values as we go
        Dictionary <Vector3, Vector3> averageNormalsHash = new Dictionary <Vector3, Vector3>();

        for (int i = 0; i < newMesh.vertexCount; i++)
        {
            if (!averageNormalsHash.ContainsKey(newMesh.vertices[i]))
            {
                averageNormalsHash.Add(newMesh.vertices[i], newMesh.normals[i]);
            }
            else
            {
                averageNormalsHash[newMesh.vertices[i]] = (averageNormalsHash[newMesh.vertices[i]] + newMesh.normals[i]).normalized;
            }
        }

        //Convert to Array
        Vector3[] averageNormals = new Vector3[newMesh.vertexCount];
        for (int i = 0; i < newMesh.vertexCount; i++)
        {
            averageNormals[i] = averageNormalsHash[newMesh.vertices[i]];
            if (!skipFormat)
            {
                averageNormals[i] = Vector3.Scale(new Vector3(averageNormals[i][channels[0]], averageNormals[i][channels[1]], averageNormals[i][channels[2]]), chSign);
            }
        }

        #if DONT_ALTER_NORMALS
        //Debug: don't alter normals to see if converting into colors/tangents/uv2 works correctly
        for (int i = 0; i < newMesh.vertexCount; i++)
        {
            averageNormals[i] = newMesh.normals[i];
        }
        #endif

        //--------------------------------
        // Store in Vertex Colors

        if (vcolors)
        {
            //Assign averaged normals to colors
            Color32[] colors = new Color32[newMesh.vertexCount];
            for (int i = 0; i < newMesh.vertexCount; i++)
            {
                byte r = (byte)(((averageNormals[i].x * 0.5f) + 0.5f) * 255);
                byte g = (byte)(((averageNormals[i].y * 0.5f) + 0.5f) * 255);
                byte b = (byte)(((averageNormals[i].z * 0.5f) + 0.5f) * 255);

                colors[i] = new Color32(r, g, b, 255);
            }
            newMesh.colors32 = colors;
        }

        //--------------------------------
        // Store in Tangents

        if (vtangents)
        {
            //Assign averaged normals to tangent
            Vector4[] tangents = new Vector4[newMesh.vertexCount];
            for (int i = 0; i < newMesh.vertexCount; i++)
            {
                tangents[i] = new Vector4(averageNormals[i].x, averageNormals[i].y, averageNormals[i].z, 0f);
            }
            newMesh.tangents = tangents;
        }

        //--------------------------------
        // Store in UV2

        if (uv2)
        {
            //Assign averaged normals to UV2 (x,y to uv2.x and z to uv2.y)
            Vector2[] uvs2 = new Vector2[newMesh.vertexCount];
            for (int i = 0; i < newMesh.vertexCount; i++)
            {
                float x = averageNormals[i].x * 0.5f + 0.5f;
                float y = averageNormals[i].y * 0.5f + 0.5f;
                float z = averageNormals[i].z * 0.5f + 0.5f;

                //pack x,y to uv2.x
                x = Mathf.Round(x * 15);
                y = Mathf.Round(y * 15);
                float packed = Vector2.Dot(new Vector2(x, y), new Vector2((float)(1.0 / (255.0 / 16.0)), (float)(1.0 / 255.0)));

                //store to UV2
                uvs2[i].x = packed;
                uvs2[i].y = z;
            }
            newMesh.uv2 = uvs2;
        }

        return(newMesh);
    }
Exemplo n.º 30
0
 public static extern void fc_get_value_color32(long ptr, ref Color32 v);
Exemplo n.º 31
0
 public static extern void fc_push_color32(ref Color32 v);
Exemplo n.º 32
0
 public static void UnitTest_Type()
 {
     string str = "abcd";
     char ccc = str[0];
     Color32 c = new Color32(2, 2, 3, 5);
     c.TestType(typeof(Color32));
 }
Exemplo n.º 33
0
        /// <summary>
        /// Override this to process the pixel in the second pass of the algorithm
        /// </summary>
        /// <param name="pixel">The pixel to quantize</param>
        /// <returns>The quantized value</returns>
        protected override byte QuantizePixel( Color32 pixel )
        {
            byte	colorIndex = 0 ;
            int		colorHash = pixel.ARGB ;

            // Check if the color is in the lookup table
            if ( _colorMap.ContainsKey ( colorHash ) )
                colorIndex = (byte)_colorMap[colorHash] ;
            else
            {
                // Not found - loop through the palette and find the nearest match.
                // Firstly check the alpha value - if 0, lookup the transparent color
                if ( 0 == pixel.Alpha )
                {
                    // Transparent. Lookup the first color with an alpha value of 0
                    for ( int index = 0 ; index < _colors.Length ; index++ )
                    {
                        if ( 0 == _colors[index].A )
                        {
                            colorIndex = (byte)index ;
                            break ;
                        }
                    }
                }
                else
                {
                    // Not transparent...
                    int	leastDistance = int.MaxValue ;
                    int red = pixel.Red ;
                    int green = pixel.Green;
                    int blue = pixel.Blue;

                    // Loop through the entire palette, looking for the closest color match
                    for ( int index = 0 ; index < _colors.Length ; index++ )
                    {
                        Color	paletteColor = _colors[index];

                        int	redDistance = paletteColor.R - red ;
                        int	greenDistance = paletteColor.G - green ;
                        int	blueDistance = paletteColor.B - blue ;

                        int		distance = ( redDistance * redDistance ) +
                                           ( greenDistance * greenDistance ) +
                                           ( blueDistance * blueDistance ) ;

                        if ( distance < leastDistance )
                        {
                            colorIndex = (byte)index ;
                            leastDistance = distance ;

                            // And if it's an exact match, exit the loop
                            if ( 0 == distance )
                                break ;
                        }
                    }
                }

                // Now I have the color, pop it into the hashtable for next time
                _colorMap.Add ( colorHash , colorIndex ) ;
            }

            return colorIndex ;
        }
Exemplo n.º 34
0
    //在第一次渲染此控件时调用
    public void Init()
    {
        if (initFlag)
        {
            return;
        }
        initFlag = true;

        if (mainViewTexture == null)
        {
            mainViewTexture = new RenderTexture(512, 512, 24);
        }

        if (null == assistantViewTexture)
        {
            assistantViewTexture = new RenderTexture(128, 128, 24);
        }

        if (mainViewRoot == null)
        {
            mainViewRoot      = new GameObject();
            mainViewRoot.name = _GenMainViewRootName();
            //为此视图分配唯一的原点
            mainViewRoot.transform.position = _GenMainViewOrigin();
            if (!EditorHelper.IsDebugMode())
            {
                mainViewRoot.hideFlags = HideFlags.HideAndDontSave;
            }
            mainViewRoot.layer = MainViewCtrl.s_layer;
        }

        if (refModelBindingTarget == null)
        {
            refModelBindingTarget                         = new GameObject();
            refModelBindingTarget.name                    = "_RefModelBindingPoint";
            refModelBindingTarget.transform.parent        = mainViewRoot.transform;
            refModelBindingTarget.transform.localPosition = Vector3.zero;
            if (!EditorHelper.IsDebugMode())
            {
                refModelBindingTarget.hideFlags = HideFlags.HideAndDontSave;
            }
            refModelBindingTarget.layer = MainViewCtrl.s_layer;
        }

        if (editObjBindingTarget == null)
        {
            editObjBindingTarget                         = new GameObject();
            editObjBindingTarget.name                    = "_EditObjBindingPoint";
            editObjBindingTarget.transform.parent        = mainViewRoot.transform;
            editObjBindingTarget.transform.localPosition = Vector3.zero;
            if (!EditorHelper.IsDebugMode())
            {
                editObjBindingTarget.hideFlags = HideFlags.HideAndDontSave;
            }
            editObjBindingTarget.layer = MainViewCtrl.s_layer;
        }

        //非3D视图不创建栅格网格
        if (gridMeshObj == null && !Is2DView)
        {
            gridMeshObj                         = new GameObject();
            gridMeshObj.name                    = "_GridMeshObject";
            gridMeshObj.transform.parent        = mainViewRoot.transform;
            gridMeshObj.transform.localPosition = Vector3.zero;
            if (!EditorHelper.IsDebugMode())
            {
                gridMeshObj.hideFlags = HideFlags.HideAndDontSave;
            }
            gridMeshObj.layer = MainViewCtrl.s_layer;

            MeshRenderer gridMeshRenderer = gridMeshObj.AddComponent <MeshRenderer>();

            gridMeshRenderer.material = new Material(Shader.Find("Diffuse"));
            MeshFilter gridMeshFilter = gridMeshObj.AddComponent <MeshFilter>();
            Mesh       gridMesh       = new Mesh();
            _BuildGridMesh(gridMesh);
            gridMeshFilter.mesh = gridMesh;
        }

        #region MainCamera
        if (mainCam == null)
        {
            camObj                  = new GameObject();
            camObj.name             = "_MainViewCamera";
            camObj.transform.parent = mainViewRoot.transform;

            if (!is2DView)
            {
                camObj.transform.localPosition = new Vector3(0, 0, -5);
            }
            else
            {
                camObj.transform.localPosition = new Vector3(0, 0, -10);
            }

            camObj.layer = MainViewCtrl.s_layer;
            center       = Vector3.zero;
            radius       = 10f;

            if (!EditorHelper.IsDebugMode())
            {
                camObj.hideFlags = HideFlags.HideAndDontSave;
            }

            //若为3D视口
            if (!is2DView)
            {//初始化相机位置
                Transform camTrans               = camObj.transform;
                float     angleRotateAroundUp    = 135.0f;
                float     angleRotateAroundRight = 45.0f;

                Vector3 localPos = (camTrans.localPosition - center).normalized * radius;

                Quaternion q0 = Quaternion.AngleAxis(angleRotateAroundUp, camTrans.up);
                camTrans.localPosition = q0 * localPos;
                camTrans.Rotate(Vector3.up, angleRotateAroundUp, Space.Self);

                Quaternion q1 = Quaternion.AngleAxis(angleRotateAroundRight, camTrans.right);
                camTrans.Rotate(Vector3.right, angleRotateAroundRight, Space.Self);
                camTrans.localPosition = q1 * camTrans.localPosition;

                camTrans.localPosition += center;
            }


            Camera camera = camObj.AddComponent <Camera>();
            camera.clearFlags      = CameraClearFlags.Color;
            camera.backgroundColor = bkColor;


            camera.nearClipPlane = 1f;
            camera.farClipPlane  = 1000f;
            camera.targetTexture = mainViewTexture;

            if (!is2DView)
            {
                camera.orthographic = false;
                camera.aspect       = 1.0f;
            }
            else
            {
                camera.orthographic     = true;
                camera.orthographicSize = 10f;
            }
            camera.cullingMask = ~0;
            mainCam            = camera;
        }
        #endregion

        //if (null == axisMeshObj && !Is2DView)
        //{
        //    float angleRotateAroundUp = 135.0f;
        //    float angleRotateAroundRight = 45.0f;

        //    axisMeshObj = new GameObject();
        //    axisMeshObj.name = "_AxisMeshObjet";
        //    axisMeshObj.transform.parent = camObj.transform;
        //    axisMeshObj.transform.localPosition = new Vector3(0.5f, 0, 2f);
        //    axisMeshObj.transform.Rotate(Vector3.up, angleRotateAroundUp, Space.Self);
        //    //axisMeshObj.transform.Rotate(Vector3.forward, 0f, Space.World);
        //    axisMeshObj.transform.Rotate(Vector3.right, angleRotateAroundRight, Space.Self);

        //    if (!EditorHelper.IsDebugMode())
        //    {
        //        axisMeshObj.hideFlags = HideFlags.HideAndDontSave;
        //    }

        //    axisMeshObj.layer = MainViewCtrl.s_layer;

        //    MeshRenderer axisMeshRenderer = axisMeshObj.AddComponent<MeshRenderer>();

        //    axisMeshRenderer.material = new Material(Shader.Find("Transparent/Diffuse"));
        //    MeshFilter axisMeshFilter = axisMeshObj.AddComponent<MeshFilter>();
        //    //axisMeshRenderer.material.color = Color.green;

        //    Mesh axisMesh = new Mesh();
        //    _BuildTestCubeMesh(axisMesh);
        //    axisMeshFilter.mesh = axisMesh;
        //}

        #region AssistantCamera
        if (
            (null == assistantCam) &&
            isShowAxis
            )
        {
            assCentter = s_assistantViewOrigion;

            assistantCamObj      = new GameObject();
            assistantCamObj.name = "_AssistantCamera";
            assistantCamObj.transform.position = new Vector3(assCentter.x, assCentter.y, assCentter.z - assRadius);

            assistantCamObj.layer = MainViewCtrl.s_layer;

            if (!EditorHelper.IsDebugMode())
            {
                assistantCamObj.hideFlags = HideFlags.HideAndDontSave;
            }

            //若为3D视口
            if (!is2DView)
            {//初始化相机位置
                Transform assistantCamTrans      = assistantCamObj.transform;
                float     angleRotateAroundUp    = 135.0f;
                float     angleRotateAroundRight = 45.0f;

                Vector3 localPos = (assistantCamTrans.localPosition - assCentter).normalized * assRadius;

                Quaternion q0 = Quaternion.AngleAxis(angleRotateAroundUp, assistantCamTrans.up);
                assistantCamTrans.localPosition = q0 * localPos;
                assistantCamTrans.Rotate(Vector3.up, angleRotateAroundUp, Space.Self);

                Quaternion q1 = Quaternion.AngleAxis(angleRotateAroundRight, assistantCamTrans.right);
                assistantCamTrans.Rotate(Vector3.right, angleRotateAroundRight, Space.Self);
                assistantCamTrans.localPosition = q1 * assistantCamTrans.localPosition;

                assistantCamTrans.localPosition += assCentter;
            }

            Camera camera = assistantCamObj.AddComponent <Camera>();
            camera.clearFlags = CameraClearFlags.Color;
            Color32 color = Color.black;
            color.a = 0;
            camera.backgroundColor = color;

            camera.nearClipPlane = 1f;
            camera.farClipPlane  = 10;
            camera.targetTexture = assistantViewTexture;

            camera.orthographic = false;
            camera.aspect       = 1.0f;

            camera.cullingMask = ~0;
            assistantCam       = camera;
        }
        #endregion

        if (mainLight == null)
        {
            //将方向光挂接在相机下
            mainLight                         = new GameObject();
            mainLight.name                    = "_MainDirLight";
            mainLight.transform.parent        = camObj.transform;
            mainLight.transform.localPosition = Vector3.zero;
            mainLight.transform.localRotation = Quaternion.identity;
            if (!EditorHelper.IsDebugMode())
            {
                mainLight.hideFlags = HideFlags.HideAndDontSave;
            }
            Light light = mainLight.AddComponent <Light>();
            light.type      = LightType.Directional;
            light.intensity = 0.2f;
            mainLight.layer = MainViewCtrl.s_layer;
        }

        if (
            (null == assLight) &&
            isShowAxis
            )
        {
            //将方向光挂接在相机下
            assLight                         = new GameObject();
            assLight.name                    = "_AssDirLight";
            assLight.transform.parent        = assistantCamObj.transform;
            assLight.transform.localPosition = Vector3.zero;
            assLight.transform.localRotation = Quaternion.AngleAxis(180f, assLight.transform.up);
            if (!EditorHelper.IsDebugMode())
            {
                assLight.hideFlags = HideFlags.HideAndDontSave;
            }
            Light light = assLight.AddComponent <Light>();
            light.type      = LightType.Directional;
            light.intensity = 1.2f;

            light.cullingMask = unchecked ((int)0x80000000);
            assLight.layer    = MainViewCtrl.s_AssLayer;
        }
    }
Exemplo n.º 35
0
 public static Color32 Mix14To1To1(Color32 c1, Color32 c2, Color32 c3)
 {
     return(MixColours(new WeightedColor(14, c1), new WeightedColor(1, c2), new WeightedColor(1, c3)));
 }
Exemplo n.º 36
0
 /// <summary>
 /// Add a given color value to the octree
 /// </summary>
 /// <param name="pixel"></param>
 public void AddColor(Color32 pixel)
 {
     // Check if this request is for the same color as the last
     if (_previousColor == pixel.ARGB)
     {
         // If so, check if I have a previous node setup. This will only ocurr if the first color in the image
         // happens to be black, with an alpha component of zero.
         if (null == _previousNode)
         {
             _previousColor = pixel.ARGB;
             _root.AddColor(pixel, _maxColorBits, 0, this);
         }
         else
             // Just update the previous node
             _previousNode.Increment(pixel);
     }
     else
     {
         _previousColor = pixel.ARGB;
         _root.AddColor(pixel, _maxColorBits, 0, this);
     }
 }
Exemplo n.º 37
0
        /// <summary>Generates a Texture2D atlas containing the textures and gradients for the vector geometry.</summary>
        /// <param name="geoms">The list of Geometry objects, probably created with TessellateNodeHierarchy</param>
        /// <param name="rasterSize">Maximum size of the generated texture</param>
        /// <returns>The generated texture atlas</returns>
        public static TextureAtlas GenerateAtlas(IEnumerable <Geometry> geoms, uint rasterSize)
        {
            UnityEngine.Profiling.Profiler.BeginSample("GenerateAtlas");

            var fills             = new Dictionary <IFill, AtlasEntry>();
            int texturedGeomCount = 0;

            foreach (var g in geoms)
            {
                RawTexture tex;
                if (g.Fill is GradientFill)
                {
                    tex = new RawTexture()
                    {
                        Width = (int)rasterSize, Height = 1, Rgba = RasterizeGradientStripe((GradientFill)g.Fill, (int)rasterSize)
                    };
                    ++texturedGeomCount;
                }
                else if (g.Fill is TextureFill)
                {
                    var fillTex = ((TextureFill)g.Fill).Texture;
                    tex = new RawTexture()
                    {
                        Rgba = fillTex.GetPixels32(), Width = fillTex.width, Height = fillTex.height
                    };
                    ++texturedGeomCount;
                }
                else
                {
                    continue;
                }
                fills[g.Fill] = new AtlasEntry()
                {
                    Texture = tex
                };
            }

            if (fills.Count == 0)
            {
                return(null);
            }

            Vector2 atlasSize;
            var     rectsToPack = fills.Select(x => new KeyValuePair <IFill, Vector2>(x.Key, new Vector2(x.Value.Texture.Width, x.Value.Texture.Height))).ToList();

            rectsToPack.Add(new KeyValuePair <IFill, Vector2>(null, new Vector2(2, 2))); // White fill
            var pack = PackRects(rectsToPack, out atlasSize);

            // The first row of the atlas is reserved for the gradient settings
            for (int packIndex = 0; packIndex < pack.Count; ++packIndex)
            {
                var item = pack[packIndex];
                item.Position.y += 1;
                pack[packIndex]  = item;
            }
            atlasSize.y += 1;

            // Need enough space on first row for texture settings
            int maxSettingIndex = 0;

            foreach (var item in pack)
            {
                maxSettingIndex = Math.Max(maxSettingIndex, item.SettingIndex);
            }
            int minWidth = (maxSettingIndex + 1) * 3;

            atlasSize.x = Math.Max(minWidth, (int)atlasSize.x);

            int atlasWidth  = NextPOT((int)atlasSize.x);
            int atlasHeight = NextPOT((int)atlasSize.y);
            var atlasColors = new Color32[atlasWidth * atlasHeight];

            for (int k = 0; k < atlasWidth * atlasHeight; ++k)
            {
                atlasColors[k] = Color.black;
            }
            Vector2 atlasInvSize         = new Vector2(1.0f / (float)atlasWidth, 1.0f / (float)atlasHeight);
            Vector2 whiteTexelsScreenPos = pack[pack.Count - 1].Position;

            int        i           = 0;
            RawTexture rawAtlasTex = new RawTexture()
            {
                Rgba = atlasColors, Width = atlasWidth, Height = atlasHeight
            };

            foreach (var entry in fills.Values)
            {
                var packItem = pack[i++];
                entry.AtlasLocation = packItem;
                BlitRawTexture(entry.Texture, rawAtlasTex, (int)packItem.Position.x, (int)packItem.Position.y, packItem.Rotated);
            }

            RawTexture whiteTex = new RawTexture()
            {
                Width = 2, Height = 2, Rgba = new Color32[4]
            };

            for (i = 0; i < whiteTex.Rgba.Length; i++)
            {
                whiteTex.Rgba[i] = new Color32(0xFF, 0xFF, 0xFF, 0xFF);
            }
            BlitRawTexture(whiteTex, rawAtlasTex, (int)whiteTexelsScreenPos.x, (int)whiteTexelsScreenPos.y, false);

            // Setting 0 is reserved for the white texel
            WriteRawFloat4Packed(rawAtlasTex, 0.0f, 0.0f, 0.0f, 0.0f, 0, 0);
            WriteRawInt2Packed(rawAtlasTex, (int)whiteTexelsScreenPos.x + 1, (int)whiteTexelsScreenPos.y + 1, 1, 0);
            WriteRawInt2Packed(rawAtlasTex, 0, 0, 2, 0);

            var writtenSettings = new HashSet <int>();

            writtenSettings.Add(0);

            foreach (var g in geoms)
            {
                AtlasEntry entry;
                int        vertsCount = g.Vertices.Length;
                if ((g.Fill != null) && fills.TryGetValue(g.Fill, out entry))
                {
                    int setting = entry.AtlasLocation.SettingIndex;
                    if (writtenSettings.Contains(setting))
                    {
                        continue;
                    }

                    writtenSettings.Add(setting);

                    // There are 3 consecutive pixels to store the settings
                    int destX = setting * 3;

                    var gradientFill = g.Fill as GradientFill;
                    if (gradientFill != null)
                    {
                        var focus = gradientFill.RadialFocus;
                        focus  += Vector2.one;
                        focus  /= 2.0f;
                        focus.y = 1.0f - focus.y;
                        WriteRawFloat4Packed(rawAtlasTex, ((float)gradientFill.Type) / 255, ((float)gradientFill.Addressing) / 255, focus.x, focus.y, destX++, 0);
                    }

                    var textureFill = g.Fill as TextureFill;
                    if (textureFill != null)
                    {
                        WriteRawFloat4Packed(rawAtlasTex, 0.0f, ((float)textureFill.Addressing) / 255, 0.0f, 0.0f, destX++, 0);
                    }

                    var pos  = entry.AtlasLocation.Position;
                    var size = new Vector2(entry.Texture.Width - 1, entry.Texture.Height - 1);
                    WriteRawInt2Packed(rawAtlasTex, (int)pos.x, (int)pos.y, destX++, 0);
                    WriteRawInt2Packed(rawAtlasTex, (int)size.x, (int)size.y, destX++, 0);
                }
            }

            var atlasTex = new Texture2D(atlasWidth, atlasHeight, TextureFormat.ARGB32, false, true);

            atlasTex.wrapModeU = TextureWrapMode.Clamp;
            atlasTex.wrapModeV = TextureWrapMode.Clamp;
            atlasTex.wrapModeW = TextureWrapMode.Clamp;
            atlasTex.SetPixels32(atlasColors);
            atlasTex.Apply();

            UnityEngine.Profiling.Profiler.EndSample();

            return(new TextureAtlas()
            {
                Texture = atlasTex, Entries = pack
            });
        }
Exemplo n.º 38
0
                /// <summary>
                /// Add a color into the tree
                /// </summary>
                /// <param name="pixel">The color</param>
                /// <param name="colorBits">The number of significant color bits</param>
                /// <param name="level">The level in the tree</param>
                /// <param name="octree">The tree to which this node belongs</param>
                public void AddColor(Color32 pixel, int colorBits, int level, Octree octree)
                {
                    // Update the color information if this is a leaf
                    if (_leaf)
                    {
                        Increment(pixel);
                        // Setup the previous node
                        octree.TrackPrevious(this);
                    }
                    else
                    {
                        // Go to the next level down in the tree
                        int shift = 7 - level;
                        int index = ((pixel.Red & mask[level]) >> (shift - 2)) |
                                    ((pixel.Green & mask[level]) >> (shift - 1)) |
                                    ((pixel.Blue & mask[level]) >> (shift));

                        OctreeNode child = _children[index];

                        if (null == child)
                        {
                            // Create a new child node & store in the array
                            child = new OctreeNode(level + 1, colorBits, octree);
                            _children[index] = child;
                        }

                        // Add the color to the child node
                        child.AddColor(pixel, colorBits, level + 1, octree);
                    }
                }
Exemplo n.º 39
0
 private void CreateEvent(CityEventData eventData, Color32 colour)
 {
     CreateEvent(eventData.m_eventStartTime, eventData.m_eventFinishTime, eventData.m_eventBuilding, colour);
 }
Exemplo n.º 40
0
 /// <summary>
 /// Increment the pixel count and add to the color information
 /// </summary>
 public void Increment(Color32 pixel)
 {
     _pixelCount++;
     _red += pixel.Red;
     _green += pixel.Green;
     _blue += pixel.Blue;
 }
		/// <summary>
		/// Override this to process the pixel in the first pass of the algorithm
		/// </summary>
		/// <param name="pixel">The pixel to quantize</param>
		/// <remarks>
		/// This function need only be overridden if your quantize algorithm needs two passes,
		/// such as an Octree quantizer.
		/// </remarks>
		protected virtual void InitialQuantizePixel ( Color32* pixel )
		{
		}
Exemplo n.º 42
0
        private void Update()
        {
            bool useThisDateBar = true;

            CimTools.CimToolsHandler.CimToolBase.ModPanelOptions.GetOptionValue("CityTimeDateBar", ref useThisDateBar);

            if (useThisDateBar)
            {
                if (_oldDayProgressSprite != null)
                {
                    _oldDayProgressSprite.Hide();
                }

                if (_newDayProgressSprite != null)
                {
                    _newDayProgressSprite.Show();
                }
            }
            else
            {
                if (_oldDayProgressSprite != null)
                {
                    _oldDayProgressSprite.Show();
                }

                if (_newDayProgressSprite != null)
                {
                    _newDayProgressSprite.Hide();
                }
            }

            if (_newDayProgressSprite != null && _newDayProgressLabel != null)
            {
                SimulationManager _simulationManager = Singleton <SimulationManager> .instance;
                DateTime          _date       = CityEventManager.CITY_TIME;
                Color32           _barColour  = new Color32(199, 254, 115, 255);
                double            currentHour = _date.TimeOfDay.TotalHours;

                if (_simulationManager.SimulationPaused || _simulationManager.ForcedSimulationPaused)
                {
                    _barColour = new Color32(255, 115, 115, 255);
                }
                else if (CityEventManager.instance.EventTakingPlace())
                {
                    _barColour = new Color32(255, 230, 115, 255);
                }
                else if (GameEventHelpers.EventTakingPlace())
                {
                    _barColour = new Color32(220, 220, 220, 255);
                }

                _newDayProgressSprite.fillAmount = (float)currentHour / 24F;
                _newDayProgressSprite.color      = _barColour;
                _newDayProgressSprite.tooltip    = _date.ToString(Experiments.ExperimentsToggle.DateFormat, LocaleManager.cultureInfo);

                _newDayProgressLabel.text = _date.ToString(Experiments.ExperimentsToggle.NormalClock ? "dddd HH:mm" : "dddd hh:mm tt", LocaleManager.cultureInfo);

                if (CityEventManager.CITY_TIME - _lastTime >= new TimeSpan(0, 1, 0))
                {
                    UpdateEventBlocks();
                }

                _newDayProgressLabel.BringToFront();
            }
        }
Exemplo n.º 43
0
 private void ChangeColour(Color32 color) => gameObject.GetComponent <Image>().color = color;
Exemplo n.º 44
0
 public static Color32 MixEven(Color32 c1, Color32 c2)
 {
     return(MixColours(new WeightedColor(1, c1), new WeightedColor(1, c2)));
 }
Exemplo n.º 45
0
 /// <summary>
 /// Get the palette index for the passed color
 /// </summary>
 /// <param name="pixel"></param>
 /// <returns></returns>
 public int GetPaletteIndex(Color32 pixel)
 {
     return(_root.GetPaletteIndex(pixel, 0));
 }
Exemplo n.º 46
0
 public static Color32 Mix5To2To1(Color32 c1, Color32 c2, Color32 c3)
 {
     return(MixColours(new WeightedColor(5, c1), new WeightedColor(2, c2), new WeightedColor(1, c3)));
 }
Exemplo n.º 47
0
 /// <summary>
 /// Override this to process the pixel in the second pass of the algorithm
 /// </summary>
 /// <param name="pixel">The pixel to quantize</param>
 /// <returns>The quantized value</returns>
 protected abstract byte QuantizePixel(Color32 pixel);
Exemplo n.º 48
0
 public static Color32 Mix5To3(Color32 c1, Color32 c2)
 {
     return(MixColours(new WeightedColor(5, c1), new WeightedColor(3, c2)));
 }
Exemplo n.º 49
0
        public static void UnitTest_Out()
        {
            EUIPanelID id = EUIPanelID.INT1;
            Color32 c = new Color32(2, 2, 3, 5);
            byte b = 0;
            c.GetA(out b);
            Logger.Log("a=" + b);
            c.GetB(ref b);
            Logger.Log("b=" + b);

        }
Exemplo n.º 50
0
 public static Color32 Mix2To3To3(Color32 c1, Color32 c2, Color32 c3)
 {
     return(MixColours(new WeightedColor(2, c1), new WeightedColor(3, c2), new WeightedColor(3, c3)));
 }
Exemplo n.º 51
0
 /// <summary>
 /// Process the pixel in the first pass of the algorithm
 /// </summary>
 /// <param name="pixel">The pixel to quantize</param>
 /// <remarks>
 /// This function need only be overridden if your quantize algorithm needs two passes,
 /// such as an Octree quantizer.
 /// </remarks>
 protected override void InitialQuantizePixel(Color32 pixel)
 {
     // Add the color to the octree
     _octree.AddColor(pixel);
 }
Exemplo n.º 52
0
 public static extern void fc_test_color32(Color32 c);
Exemplo n.º 53
0
 /// <summary>
 /// Get the palette index for the passed color
 /// </summary>
 /// <param name="pixel"></param>
 /// <returns></returns>
 public int GetPaletteIndex(Color32 pixel)
 {
     return _root.GetPaletteIndex(pixel, 0);
 }
Exemplo n.º 54
0
        public static string ColorToHex(Color32 color)
        {
            string hex = color.r.ToString("X2") + color.g.ToString("X2") + color.b.ToString("X2");

            return(hex);
        }
Exemplo n.º 55
0
                /// <summary>
                /// Return the palette index for the passed color
                /// </summary>
                public int GetPaletteIndex(Color32 pixel, int level)
                {
                    int paletteIndex = _paletteIndex;

                    if (!_leaf)
                    {
                        int shift = 7 - level;
                        int index = ((pixel.Red & mask[level]) >> (shift - 2)) |
                                    ((pixel.Green & mask[level]) >> (shift - 1)) |
                                    ((pixel.Blue & mask[level]) >> (shift));

                        if (null != _children[index])
                            paletteIndex = _children[index].GetPaletteIndex(pixel, level + 1);
                        else
                            throw new Exception("Didn't expect this!");
                    }

                    return paletteIndex;
                }
Exemplo n.º 56
0
        internal static long ColorToInt(Color32 color32)
        {
            long color = (color32.a & 0xff) << 24 | (color32.r & 0xff) << 16 | (color32.g & 0xff) << 8 | (color32.b & 0xff);

            return(color);
        }
Exemplo n.º 57
0
		/// <summary>
		/// Initialize new instance of <seealso cref="PaletteColorLUT"/>
		/// </summary>
		/// <param name="firstEntry">The first entry (minium value)</param>
		/// <param name="lut">The palette color LUT</param>
		public PaletteColorLUT(int firstEntry, Color32[] lut) {
			_first = firstEntry;
			ColorMap = lut;
		}
Exemplo n.º 58
0
        public override void Regenerate()
        {
            if (Current.ProgramState != ProgramState.Playing)
            {
                return;
            }

            if (pawnFog == null)
            {
                pawnFog = base.Map.getMapComponentSeenFog();
            }

            if (pawnFog != null && pawnFog.initialized)
            {
                LayerSubMesh subMesh = base.GetSubMesh(MatBases.FogOfWar);
                bool         firstGeneration;
                if (subMesh.mesh.vertexCount == 0)
                {
                    firstGeneration = true;

                    subMesh.mesh.MarkDynamic();

                    MakeBaseGeometry(this.section, subMesh, AltitudeLayer.FogOfWar);

                    targetAlphas    = new byte[subMesh.mesh.vertexCount];
                    alphaChangeTick = new int[subMesh.mesh.vertexCount];
                    meshColors      = new Color32[subMesh.mesh.vertexCount];
                }
                else
                {
                    firstGeneration = false;
                }

                int colorIdx = 0;

                bool[] fogGrid = base.Map.fogGrid.fogGrid;
                if (this.factionShownGrid == null)
                {
                    this.factionShownGrid = pawnFog.getFactionShownCells(Faction.OfPlayer);
                }
                short[] factionShownGrid = this.factionShownGrid;

                int[]  playerShownCellsTick = pawnFog.playerVisibilityChangeTick;
                bool[] knownGrid            = pawnFog.knownCells;

                int mapSizeX = base.Map.Size.x;

                CellRect cellRect  = this.section.CellRect;
                int      mapHeight = base.Map.Size.z - 1;
                int      mapWidth  = mapSizeX - 1;


                bool hasFoggedVerts = false;

                int cellIdx;
                int cellIdxN;
                int cellIdxS;
                int cellIdxE;
                int cellIdxW;
                int cellIdxSW;
                int cellIdxNW;
                int cellIdxNE;
                int cellIdxSE;

                bool cellKnown;
                bool adjCellKnown;

                byte alpha;

                int cellVisibilityChangeTick;
                for (int x = cellRect.minX; x <= cellRect.maxX; x++)
                {
                    for (int z = cellRect.minZ; z <= cellRect.maxZ; z++)
                    {
                        cellIdx = z * mapSizeX + x;
                        cellVisibilityChangeTick = playerShownCellsTick[cellIdx];
                        if (!fogGrid[cellIdx])
                        {
                            if (factionShownGrid[cellIdx] == 0)
                            {
                                cellKnown = knownGrid[cellIdx];
                                for (int n = 0; n < 9; n++)
                                {
                                    this.vertsNotShown[n] = true;
                                    this.vertsSeen[n]     = cellKnown;
                                }
                                if (cellKnown)
                                {
                                    cellIdxN  = (z + 1) * mapSizeX + x;
                                    cellIdxS  = (z - 1) * mapSizeX + x;
                                    cellIdxE  = z * mapSizeX + (x + 1);
                                    cellIdxW  = z * mapSizeX + (x - 1);
                                    cellIdxSW = (z - 1) * mapSizeX + (x - 1);
                                    cellIdxNW = (z + 1) * mapSizeX + (x - 1);
                                    cellIdxNE = (z + 1) * mapSizeX + (x + 1);
                                    cellIdxSE = (z - 1) * mapSizeX + (x + 1);

                                    if (z < mapHeight && !knownGrid[cellIdxN])
                                    {
                                        this.vertsSeen[2] = false;
                                        this.vertsSeen[3] = false;
                                        this.vertsSeen[4] = false;
                                    }
                                    if (z > 0 && !knownGrid[cellIdxS])
                                    {
                                        this.vertsSeen[6] = false;
                                        this.vertsSeen[7] = false;
                                        this.vertsSeen[0] = false;
                                    }
                                    if (x < mapWidth && !knownGrid[cellIdxE])
                                    {
                                        this.vertsSeen[4] = false;
                                        this.vertsSeen[5] = false;
                                        this.vertsSeen[6] = false;
                                    }
                                    if (x > 0 && !knownGrid[cellIdxW])
                                    {
                                        this.vertsSeen[0] = false;
                                        this.vertsSeen[1] = false;
                                        this.vertsSeen[2] = false;
                                    }
                                    if (z > 0 && x > 0 && !knownGrid[cellIdxSW])
                                    {
                                        this.vertsSeen[0] = false;
                                    }
                                    if (z < mapHeight && x > 0 && !knownGrid[cellIdxNW])
                                    {
                                        this.vertsSeen[2] = false;
                                    }
                                    if (z < mapHeight && x < mapWidth && !knownGrid[cellIdxNE])
                                    {
                                        this.vertsSeen[4] = false;
                                    }
                                    if (z > 0 && x < mapWidth && !knownGrid[cellIdxSE])
                                    {
                                        this.vertsSeen[6] = false;
                                    }
                                }
                            }
                            else
                            {
                                for (int l = 0; l < 9; l++)
                                {
                                    this.vertsNotShown[l] = false;
                                    this.vertsSeen[l]     = false;
                                }

                                cellIdxN  = (z + 1) * mapSizeX + x;
                                cellIdxS  = (z - 1) * mapSizeX + x;
                                cellIdxE  = z * mapSizeX + (x + 1);
                                cellIdxW  = z * mapSizeX + (x - 1);
                                cellIdxSW = (z - 1) * mapSizeX + (x - 1);
                                cellIdxNW = (z + 1) * mapSizeX + (x - 1);
                                cellIdxNE = (z + 1) * mapSizeX + (x + 1);
                                cellIdxSE = (z - 1) * mapSizeX + (x + 1);

                                if (z < mapHeight && factionShownGrid[cellIdxN] == 0)
                                {
                                    adjCellKnown          = knownGrid[cellIdxN];
                                    this.vertsNotShown[2] = true;
                                    this.vertsSeen[2]     = adjCellKnown;
                                    this.vertsNotShown[3] = true;
                                    this.vertsSeen[3]     = adjCellKnown;
                                    this.vertsNotShown[4] = true;
                                    this.vertsSeen[4]     = adjCellKnown;
                                }
                                if (z > 0 && factionShownGrid[cellIdxS] == 0)
                                {
                                    adjCellKnown          = knownGrid[cellIdxS];
                                    this.vertsNotShown[6] = true;
                                    this.vertsSeen[6]     = adjCellKnown;
                                    this.vertsNotShown[7] = true;
                                    this.vertsSeen[7]     = adjCellKnown;
                                    this.vertsNotShown[0] = true;
                                    this.vertsSeen[0]     = adjCellKnown;
                                }
                                if (x < mapWidth && factionShownGrid[cellIdxE] == 0)
                                {
                                    adjCellKnown          = knownGrid[cellIdxE];
                                    this.vertsNotShown[4] = true;
                                    this.vertsSeen[4]     = adjCellKnown;
                                    this.vertsNotShown[5] = true;
                                    this.vertsSeen[5]     = adjCellKnown;
                                    this.vertsNotShown[6] = true;
                                    this.vertsSeen[6]     = adjCellKnown;
                                }
                                if (x > 0 && factionShownGrid[cellIdxW] == 0)
                                {
                                    adjCellKnown          = knownGrid[cellIdxW];
                                    this.vertsNotShown[0] = true;
                                    this.vertsSeen[0]     = adjCellKnown;
                                    this.vertsNotShown[1] = true;
                                    this.vertsSeen[1]     = adjCellKnown;
                                    this.vertsNotShown[2] = true;
                                    this.vertsSeen[2]     = adjCellKnown;
                                }
                                if (z > 0 && x > 0 && factionShownGrid[cellIdxSW] == 0)
                                {
                                    adjCellKnown          = knownGrid[cellIdxSW];
                                    this.vertsNotShown[0] = true;
                                    this.vertsSeen[0]     = adjCellKnown;
                                }
                                if (z < mapHeight && x > 0 && factionShownGrid[cellIdxNW] == 0)
                                {
                                    adjCellKnown          = knownGrid[cellIdxNW];
                                    this.vertsNotShown[2] = true;
                                    this.vertsSeen[2]     = adjCellKnown;
                                }
                                if (z < mapHeight && x < mapWidth && factionShownGrid[cellIdxNE] == 0)
                                {
                                    adjCellKnown          = knownGrid[cellIdxNE];
                                    this.vertsNotShown[4] = true;
                                    this.vertsSeen[4]     = adjCellKnown;
                                }
                                if (z > 0 && x < mapWidth && factionShownGrid[cellIdxSE] == 0)
                                {
                                    adjCellKnown          = knownGrid[cellIdxSE];
                                    this.vertsNotShown[6] = true;
                                    this.vertsSeen[6]     = adjCellKnown;
                                }
                            }
                        }
                        else
                        {
                            for (int k = 0; k < 9; k++)
                            {
                                this.vertsNotShown[k] = true;
                                this.vertsSeen[k]     = false;
                            }
                        }
                        for (int m = 0; m < 9; m++)
                        {
                            if (this.vertsNotShown[m])
                            {
                                if (vertsSeen[m])
                                {
                                    alpha = prefFogAlpha;
                                }
                                else
                                {
                                    alpha = 255;
                                }

                                hasFoggedVerts = true;
                            }
                            else
                            {
                                alpha = 0;
                            }

                            if (!prefEnableFade || firstGeneration)
                            {
                                if (firstGeneration || meshColors[colorIdx].a != alpha)
                                {
                                    meshColors[colorIdx] = new Color32(255, 255, 255, alpha);
                                }
                                if (prefEnableFade)
                                {
                                    activeFogTransitions      = true;
                                    targetAlphas[colorIdx]    = alpha;
                                    alphaChangeTick[colorIdx] = cellVisibilityChangeTick;
                                }
                            }
                            else if (targetAlphas[colorIdx] != alpha)
                            {
                                activeFogTransitions      = true;
                                targetAlphas[colorIdx]    = alpha;
                                alphaChangeTick[colorIdx] = cellVisibilityChangeTick;
                            }

                            colorIdx++;
                        }
                    }
                }

                if (!prefEnableFade || firstGeneration)
                {
                    if (hasFoggedVerts)
                    {
                        subMesh.disabled      = false;
                        subMesh.mesh.colors32 = meshColors;
                    }
                    else
                    {
                        subMesh.disabled = true;
                    }
                }
            }
        }
		/// <summary>
		/// Override this to process the pixel in the second pass of the algorithm
		/// </summary>
		/// <param name="pixel">The pixel to quantize</param>
		/// <returns>The quantized value</returns>
		protected abstract byte QuantizePixel ( Color32* pixel ) ;
Exemplo n.º 60
0
        public override void DrawLayer()
        {
            if (prefEnableFade && this.Visible && activeFogTransitions)
            {
                int fogTransitionTick = Find.TickManager.TicksGame;
                int gameSpeed         = Math.Max((int)Find.TickManager.CurTimeSpeed, 1);

                bool alphaUpdated = false;

                bool hasFoggedVerts = false;

                Color32[] colors = meshColors;

                byte alpha;
                byte targetAlpha;
                for (int i = 0; i < targetAlphas.Length; i++)
                {
                    targetAlpha = targetAlphas[i];
                    alpha       = colors[i].a;
                    if (alpha > targetAlpha)
                    {
                        alphaUpdated = true;
                        if (fogTransitionTick != alphaChangeTick[i])
                        {
                            alpha              = (byte)Math.Max(targetAlpha, alpha - prefFadeSpeedMult / gameSpeed * (fogTransitionTick - alphaChangeTick[i]));
                            colors[i]          = new Color32(255, 255, 255, alpha);
                            alphaChangeTick[i] = fogTransitionTick;
                        }
                    }
                    else if (alpha < targetAlpha)
                    {
                        alphaUpdated = true;
                        if (fogTransitionTick != alphaChangeTick[i])
                        {
                            alpha              = (byte)Math.Min(targetAlpha, alpha + prefFadeSpeedMult / gameSpeed * (fogTransitionTick - alphaChangeTick[i]));
                            colors[i]          = new Color32(255, 255, 255, alpha);
                            alphaChangeTick[i] = fogTransitionTick;
                        }
                    }

                    if (alpha != 0)
                    {
                        hasFoggedVerts = true;
                    }
                }
                if (alphaUpdated)
                {
                    LayerSubMesh subMesh = base.GetSubMesh(MatBases.FogOfWar);

                    if (hasFoggedVerts)
                    {
                        subMesh.disabled      = false;
                        subMesh.mesh.colors32 = colors;
                    }
                    else
                    {
                        subMesh.disabled = true;
                    }
                }
                else
                {
                    activeFogTransitions = false;
                }
            }

            base.DrawLayer();
        }