Esempio n. 1
0
        public void ExtractBlue(ScriptThread thread)
        {
            int r = 0, g = 0, b = 0, a = 0;

            ColorMethods.SplitColor(ColorFormats.A8R8G8B8, thread.GetIntegerParameter(0), out r, out g, out b, out a);
            thread.SetReturnValue(b);
        }
 /// <summary>
 ///     Initializes a new instance of this class.
 /// </summary>
 public EntityFadeProcess(EntityNode node, int fromColor, int toColor, int duration)
 {
     _entity = node;
     ColorMethods.SplitColor(ColorFormats.A8R8G8B8, fromColor, out _fromColorRed, out _fromColorGreen, out _fromColorBlue, out _fromColorAlpha);
     ColorMethods.SplitColor(ColorFormats.A8R8G8B8, toColor, out _toColorRed, out _toColorGreen, out _toColorBlue, out _toColorAlpha);
     _duration = duration;
     _timer.Restart();
 }
        /// <summary>
        ///     Invoked when the alpha track bar's value is changed.
        /// </summary>
        /// <param name="sender">Object that caused this event to be triggered.</param>
        /// <param name="e">Arguments explaining why this event occured.</param>
        private void alphaTrackBar_Scroll(object sender, EventArgs e)
        {
            int r, g, b, a;

            ColorMethods.SplitColor(ColorFormats.A8R8G8B8, _color, out r, out g, out b, out a);
            _color = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, r, g, b, alphaTrackBar.Value);
            if (SelectionChanged != null)
            {
                SelectionChanged(this, new EventArgs());
            }
        }
Esempio n. 4
0
 private static ColorData[,] GetColorData(Color[,] data)
 {
     ColorData[,] colorData = new ColorData[data.GetLength(0), data.GetLength(1)];
     for (int i = 0; i < data.GetLength(0); i++)
     {
         for (int j = 0; j < data.GetLength(1); j++)
         {
             colorData[i, j] = new ColorData()
             {
                 color = data[i, j], colorName = ColorMethods.GetResistorColorCode(data[i, j])
             };
         }
     }
     return(colorData);
 }
Esempio n. 5
0
    private static ColorMethods.ColorName GetColor(Color[,] data, int i)
    {
        float r = 0f, g = 0f, b = 0f;

        for (int j = 0; j < data.GetLength(0); j++)
        {
            r += data[j, i].r;
            g += data[j, i].g;
            b += data[j, i].b;
        }
        r /= data.GetLength(0);
        g /= data.GetLength(0);
        b /= data.GetLength(0);

        return(ColorMethods.GetResistorColorCode(new Color(r, g, b)));
    }
        /// <summary>
        ///     Invoked when the color panel is clicked.
        /// </summary>
        /// <param name="sender">Object that caused this event to be triggered.</param>
        /// <param name="e">Arguments explaining why this event occured.</param>
        private void colorPanel_Click(object sender, EventArgs e)
        {
            ColorDialog colorDialog = new ColorDialog();

            colorDialog.Color = System.Drawing.Color.FromArgb(_color);
            if (colorDialog.ShowDialog() == DialogResult.OK)
            {
                int r, g, b, a;
                ColorMethods.SplitColor(ColorFormats.A8R8G8B8, _color, out r, out g, out b, out a);
                _color = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, colorDialog.Color.R, colorDialog.Color.G, colorDialog.Color.B, a);
                colorPanel.BackColor = System.Drawing.Color.FromArgb(_color);
                if (SelectionChanged != null)
                {
                    SelectionChanged(this, new EventArgs());
                }
            }
        }
Esempio n. 7
0
        public static void testColorConversions()
        {
            Clog("Testing Color Value Conversion Methods...");
            // RGB to Hex
            if (ColorMethods.RGBToHex(new RGBColor(255, 0, 255)) == "FF00FF")
            {
                Clog("    RGB To Hex Conversion Passed");
            }
            else
            {
                addFailedTest("RGB To Hex Conversion");
            }

            // Integer Array to RGB Object
            int[] intArr = new int[] { 255, 0, 255 };
            if (ColorMethods.ArrToRGB(intArr).Equals(new RGBColor(255, 0, 255)))
            {
                Clog("    Integer Array to RGB Object Conversion Passed");
            }
            else
            {
                addFailedTest("Int Array to RGB");
            }

            // Hex String to RGB Object without #
            if (ColorMethods.HexToRGB("FF00FF").Equals(new RGBColor(255, 0, 255)))
            {
                Clog("    Hex to RGB Object ( w/o # ) Conversion Passed");
            }
            else
            {
                addFailedTest("Hex to RGB Object ( w/o # )");
            }

            // Hex String to RGB Object with #
            if (ColorMethods.HexToRGB("#FF00FF").Equals(new RGBColor(255, 0, 255)))
            {
                Clog("    Hex to RGB Object ( w/ # ) Conversion Passed");
            }
            else
            {
                addFailedTest("Hex to RGB Object ( w/ # )");
            }

            // TODO : Implement HSLToRGB test.
        }
        /// <summary>
        ///		Updates the animation of the entity associated with this process.
        /// </summary>
        /// <param name="deltaTime">Elapsed time since last frame.</param>
        public override void Run(float deltaTime)
        {
            // if (_entity.IsEnabled == false)
            //     return;

            // Couple of useful variables.
            float expired  = (int)_timer.DurationMillisecond;
            float duration = (float)_duration;

            if (expired > _duration)
            {
                _entity.Color = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, _toColorRed, _toColorGreen, _toColorBlue, _toColorAlpha);
                Finish(ProcessResult.Success);
                return;
            }

            // Set the color
            int r = (int)(_fromColorRed + (((_toColorRed - _fromColorRed) / duration) * expired));
            int g = (int)(_fromColorGreen + (((_toColorGreen - _fromColorGreen) / duration) * expired));
            int b = (int)(_fromColorBlue + (((_toColorBlue - _fromColorBlue) / duration) * expired));
            int a = (int)(_fromColorAlpha + (((_toColorAlpha - _fromColorAlpha) / duration) * expired));

            _entity.Color = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, r, g, b, a);
        }
Esempio n. 9
0
        /// <summary>
        ///     This method is called when PixelMap load is requested, if you return a PixelMap
        ///     it will return it from the user else it will keep trying all the other PixelMapLoaders
        ///     until it does get one
        /// </summary>
        /// <param name="file">File path of the image to load.</param>
        /// <returns>A PixelMap or NULL if this factory can't load the given image file.</returns>
        protected override PixelMap RequestLoad(object path)
        {
            Stream stream = StreamFactory.RequestStream(path, StreamMode.Open);

            if (stream == null)
            {
                return(null);
            }
            BinaryReader reader = new BinaryReader(stream);

            #region Header Parsing

            // Cheak the 8 byte identifier header at the start to make
            // sure this really is a PNG file.
            byte[] correctHeader = new byte[8] {
                137, 80, 78, 71, 13, 10, 26, 10
            };
            byte[] header = reader.ReadBytes(8);

            for (int i = 0; i < correctHeader.Length; i++)
            {
                if (correctHeader[i] != header[i])
                {
                    reader.Close();
                    return(null);
                }
            }

            #endregion

            // Declare chunk releated local variables
            #region Local variables

            int      chunkIndex = 0;
            int      width = 0, height = 0;
            byte     bitDepth = 0, colorType = 0, compressionMethod = 0;
            byte     filterMethod = 0, interlaceMethod = 0;
            bool     readingChunks = true;
            byte[]   pixelData = null;
            int      bytesPerPixel = 0, bitsPerPixel = 0;
            int      dataSize = 0;
            PixelMap pixelMap = null;

            #endregion

            // Read in every chunk till we find the end of file chunk or
            // we read past the end of the stream.
            #region Chunk reading
            while (readingChunks)
            {
                // Read in chunk's data
                int    chunkLength    = EndianSwapMethods.SwapEndian(reader.ReadInt32());
                byte[] chunkTypeChars = reader.ReadBytes(4);
                string chunkType      = ((char)chunkTypeChars[0]).ToString() + ((char)chunkTypeChars[1]).ToString() +
                                        ((char)chunkTypeChars[2]).ToString() + ((char)chunkTypeChars[3]).ToString();

                #region Chunk parsing
                switch (chunkType)
                {
                // Image header chunk, it MUST come first.
                case "IHDR":

                    if (chunkIndex != 0)
                    {
                        throw new Exception("Found out of sequence IHDR chunk while loading PNG file.");
                    }
                    width             = EndianSwapMethods.SwapEndian(reader.ReadInt32());
                    height            = EndianSwapMethods.SwapEndian(reader.ReadInt32());
                    bitDepth          = reader.ReadByte();
                    colorType         = reader.ReadByte();
                    compressionMethod = reader.ReadByte();
                    filterMethod      = reader.ReadByte();
                    interlaceMethod   = reader.ReadByte();

                    pixelMap = new PixelMap(width, height);

                    break;

                // Pallete chunk.

                /*
                 * case "PLTE":
                 *
                 * if (gotPallete == true || (colorType == 0 && gotData == false) || (colorType == 4 && gotData == false))
                 *      throw new Exception("Found out of sequence or unexpected PLTE pallete chunk while loading PNG image.");
                 *
                 * for (int i = 0; i < chunkLength / 3; i++)
                 * {
                 *      pallete[(i * 3)]	 = reader.ReadByte();
                 *      pallete[(i * 3) + 1] = reader.ReadByte();
                 *      pallete[(i * 3) + 2] = reader.ReadByte();
                 * }
                 *
                 * gotPallete = true;
                 *
                 * break;
                 */

                // Image data chunk.
                case "IDAT":

                    // Read in the new data and append it to the compressed
                    // data array for future use.
                    int index = pixelData == null ? 0 : pixelData.Length;

                    if (pixelData != null)
                    {
                        Array.Resize(ref pixelData, pixelData.Length + chunkLength);
                    }
                    else
                    {
                        pixelData = new byte[chunkLength];
                    }

                    stream.Read(pixelData, index, chunkLength);
                    dataSize += chunkLength;

                    break;

                // End of chunks chunk.
                case "IEND":

                    readingChunks = false;

                    break;

                /*
                 * // Transparencry chunk.
                 * case "tRNS":
                 *
                 *      break;
                 *
                 * // Image gamma chunk.
                 * case "gAMA":
                 *
                 *      gamma = EndianSwapMethods.SwapEndian(reader.ReadInt32());
                 *
                 *      break;
                 *
                 * ///Primary chromaticities chunk.
                 * case "cHRM":
                 *
                 *      whitePointX = EndianSwapMethods.SwapEndian(reader.ReadInt32());
                 *      whitePointY = EndianSwapMethods.SwapEndian(reader.ReadInt32());
                 *      redX	    = EndianSwapMethods.SwapEndian(reader.ReadInt32());
                 *      redY		= EndianSwapMethods.SwapEndian(reader.ReadInt32());
                 *      greenX		= EndianSwapMethods.SwapEndian(reader.ReadInt32());
                 *      greenY		= EndianSwapMethods.SwapEndian(reader.ReadInt32());
                 *      blueX		= EndianSwapMethods.SwapEndian(reader.ReadInt32());
                 *      blueY		= EndianSwapMethods.SwapEndian(reader.ReadInt32());
                 *
                 *      break;
                 *
                 * // Standard RGB color space chunk.
                 * case "sRGB":
                 *
                 *      renderingIntent = reader.ReadByte();
                 *
                 *      break;
                 *
                 * // Embedded ICCP chunk.
                 * case "iCCP":
                 *
                 *      break;
                 *
                 *
                 * // Internation textural infomation chunk
                 * case "iTXt":
                 *
                 *      break;
                 *
                 * // Textural infomation chunk.
                 * case "tEXt":
                 *
                 *      // Get the keyword
                 *      string keyword = "";
                 *      int	   keyAsc = 0;
                 *      while(true)
                 *      {
                 *              keyAsc = reader.ReadByte();
                 *              if (keyAsc == 0) break;
                 *              keyword += ((char)keyAsc).ToString();
                 *      }
                 *
                 *      // Read the text
                 *      string text = "";
                 *      int	   textLength = chunkLength - keyword.Length - 1;
                 *      for (int i = 0; i < textLength; i++)
                 *              text += ((char)reader.ReadByte()).ToString();
                 *
                 *      break;
                 *
                 * // Compressed textural infomation chunk.
                 * case "zTXt":
                 *
                 *      break;
                 *
                 * // Default background color chunk.
                 * case "bKGD":
                 *
                 *      break;
                 *
                 * // Physical pixel dimensions chunk.
                 * case "pHYs":
                 *
                 *      break;
                 *
                 * // Bit chunk.
                 * case "sBit":
                 *
                 *      break;
                 *
                 * // Suggested pallete chunk.
                 * case "sPLT":
                 *
                 *      break;
                 *
                 * // Pallete histogram chunk.
                 * case "hIST":
                 *
                 *      break;
                 *
                 * // Last modification time chunk.
                 * case "tIME":
                 */

                default:

                    // Check the chunk is not critical if it is, this file
                    // is probably corrupt or the chunk is not implemented in this
                    // loader so throw up an exception.
                    if ((((byte)chunkTypeChars[0]) & 32) == 0)
                    {
                        throw new Exception("Found unknown or unsupported but critical chunk while reading PNG file.");
                    }

                    stream.Position += chunkLength;

                    break;
                }
                #endregion

                // We shall just ignore the CRC for now :)
                int CRC = EndianSwapMethods.SwapEndian(reader.ReadInt32());

                chunkIndex++;
            }
            #endregion

            // Check the expect size is the same as the actual size.
            if (dataSize != pixelData.Length)
            {
                throw new Exception("An error occured while reading in pixel data, data size is not the same as expect size.");
            }

            // Work out how many bytes are used by each pixel
            #region Pixel size calculations
            switch (colorType)
            {
            case 0: bitsPerPixel = bitDepth;         break;                 // Grey

            case 2: bitsPerPixel = bitDepth * 3; break;                     // RGB

            case 3: bitsPerPixel = bitDepth;         break;                 // Pallete indexed

            case 4: bitsPerPixel = bitDepth * 2; break;                     // Grey and alpha.

            case 6: bitsPerPixel = bitDepth * 4; break;                     // RGB and alpha.
            }
            bytesPerPixel = (int)Math.Round(bitsPerPixel / 8.0, MidpointRounding.AwayFromZero);
            #endregion

            // Decompress data array.
            #region Decompression

            byte[] pixelDataWithoutHeader = new byte[pixelData.Length - 2];
            Array.Copy(pixelData, 2, pixelDataWithoutHeader, 0, pixelData.Length - 2);
            pixelData = DataMethods.Inflate(pixelDataWithoutHeader);

            #endregion

            // Remove filter.
            #region Filter removal

            switch (filterMethod)
            {
            case 0:                     // No filter.

                byte[] filteredData  = new byte[pixelData.Length - height];
                int    scanlineWidth = (width * bytesPerPixel);

                byte[] scanlineData = null;
                for (int scanline = 0; scanline < height; scanline++)
                {
                    int    priorScanlineIndex = ((scanlineWidth + 1) * (scanline - 1)) + 1;
                    int    scanlineIndex      = ((scanlineWidth + 1) * scanline) + 1;
                    byte   slFilterMethod     = pixelData[scanlineIndex - 1];
                    byte[] priorScanlineData  = scanline == 0 ? new byte[scanlineWidth] : scanlineData;
                    scanlineData = new byte[scanlineWidth];
                    Array.Copy(pixelData, scanlineIndex, scanlineData, 0, scanlineWidth);

                    // Check what kind of filter is attached to this scanline.
                    switch (slFilterMethod)
                    {
                    case 0:                                     // None
                        break;

                    case 1:                                     // Left
                        for (int pixel = 0; pixel < scanlineData.Length; pixel++)
                        {
                            int left = pixel - bytesPerPixel < 0 ? (byte)0 : scanlineData[pixel - bytesPerPixel];
                            scanlineData[pixel] = (byte)((scanlineData[pixel] + left) % 256);
                        }
                        break;

                    case 2:                                     // Up
                        for (int pixel = 0; pixel < scanlineData.Length; pixel++)
                        {
                            byte prior = priorScanlineData[pixel];
                            scanlineData[pixel] = (byte)((scanlineData[pixel] + prior) % 256);
                        }
                        break;

                    case 3:                                     // Average
                        for (int pixel = 0; pixel < scanlineData.Length; pixel++)
                        {
                            float p     = pixel - bytesPerPixel < 0 ? (byte)0 : scanlineData[pixel - bytesPerPixel];
                            float prior = priorScanlineData[pixel];
                            scanlineData[pixel] = (byte)(scanlineData[pixel] + Math.Floor((p + prior) / 2));
                        }
                        break;

                    case 4:                                     // Paeth
                        for (int pixel = 0; pixel < scanlineData.Length; pixel++)
                        {
                            int l  = pixel - bytesPerPixel < 0 ? (byte)0 : scanlineData[pixel - bytesPerPixel];
                            int u  = priorScanlineData[pixel];
                            int ul = pixel - bytesPerPixel < 0 ? (byte)0 : priorScanlineData[pixel - bytesPerPixel];
                            scanlineData[pixel] = (byte)((scanlineData[pixel] + PaethPredictor((byte)l, (byte)u, (byte)ul)) % 256);
                        }
                        break;

                    default:
                        throw new Exception("PNG Factory encountered file with invalid or unsupported scanline filter while reading file.");
                    }

                    // Place the scanline data into the filtered data.
                    Array.Copy(scanlineData, 0, filteredData, scanline * scanlineWidth, scanlineWidth);
                }

                pixelData = filteredData;

                break;

            default:

                stream.Close();
                throw new Exception("PNG Factory encountered file with invalid or unsupported filter method while reading file.");
            }

            #endregion

            // Remove interlacing.
            #region Interlace removal
            switch (interlaceMethod)
            {
            case 0:                     // No interlace.

                // *whistles* may as well ignore this, sorter pointless it even
                // being here.

                break;

            default:

                stream.Close();
                throw new Exception("PNG Factory encountered file with invalid or unsupported interlace method while reading file.");
            }
            #endregion

            // Store decompressed data in pixelmap.
            #region PixelMap building
            switch (colorType)
            {
            case 2:                     // RGB

                for (int i = 0; i < (width * height); i++)
                {
                    int pixelIndex = i * bytesPerPixel;
                    pixelMap[i] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, pixelData[pixelIndex], pixelData[pixelIndex + 1], pixelData[pixelIndex + 2], 255);
                }

                break;

            case 6:                     // RGB with alpha.

                for (int i = 0; i < (width * height); i++)
                {
                    int pixelIndex = i * bytesPerPixel;
                    pixelMap[i] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, pixelData[pixelIndex], pixelData[pixelIndex + 1], pixelData[pixelIndex + 2], pixelData[pixelIndex + 3]);
                }

                break;

            // Sherlock, somethings amiss!
            default:

                stream.Close();
                throw new Exception("PNG Factory encountered an invalid or unsupported image type while loading an image.");
            }
            #endregion

            // Return pixelmap and close stream
            stream.Close();
            return(pixelMap);
        }
Esempio n. 10
0
        /// <summary>
        ///     This method is called when PixelMap load is requested, if you return a PixelMap
        ///     it will return it from the user else it will keep trying all the other PixelMapLoaders
        ///     until it does get one
        /// </summary>
        /// <param name="file">File path of the image to load.</param>
        /// <returns>A PixelMap or NULL if this factory can't load the given image file.</returns>
        protected override PixelMap RequestLoad(object path)
        {
            Stream stream = StreamFactory.RequestStream(path, StreamMode.Open);

            if (stream == null)
            {
                return(null);
            }
            BinaryReader reader = new BinaryReader(stream);

            if (stream.Length < 18)
            {
                reader.Close();
                return(null);
            }

            // Read in TGA header.
            #region Header reading

            byte identSize    = reader.ReadByte();
            byte colorMapType = reader.ReadByte();
            byte imageType    = reader.ReadByte();

            short colorMapStart  = reader.ReadInt16();
            short colorMapLength = reader.ReadInt16();
            byte  colorMapBits   = reader.ReadByte();

            short xStart     = reader.ReadInt16();
            short yStart     = reader.ReadInt16();
            short width      = reader.ReadInt16();
            short height     = reader.ReadInt16();
            byte  bits       = reader.ReadByte();
            byte  descriptor = reader.ReadByte();

            // Check the header is a true tga header.
            if (colorMapType != 0 || width < 1 || width > 4096 ||
                height < 1 || height > 4096 || (imageType != (int)TGAImageType.RGB && imageType != (int)TGAImageType.RLERGB))
            {
                reader.Close();
                return(null);
            }

            for (int identCounter = 0; identCounter < identSize; identCounter++)
            {
                reader.ReadByte();
            }

            int pixelCount = width * height;
            int chunkSize = 0;
            int argbColor = 0, rgbColor = 0;

            #endregion

            // Create pixelmap to store data in
            PixelMap pixelMap = new PixelMap(width, height);

            // Most Image types are unused in this day and age so only the most
            // common will be loaded (RGB, RGBRLE, both with 15,16,24 and 32 bit support).
            switch (imageType)
            {
                #region Uncompressed RGB

            case (int)TGAImageType.RGB:                     // RGB uncompressed color data, the BMP of the TGA world!

                // Read in depending on bit depth
                switch (bits)
                {
                case 15:

                    for (int y = height - 1; y >= 0; y--)
                    {
                        for (int x = 0; x < width; x++)
                        {
                            rgbColor       = reader.ReadInt16();
                            pixelMap[x, y] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, (rgbColor >> 7) & 0xF8, (rgbColor >> 2) & 0xF8, (rgbColor << 3) & 0xF8, 255);
                        }
                    }

                    break;

                case 16:

                    for (int y = height - 1; y >= 0; y--)
                    {
                        for (int x = 0; x < width; x++)
                        {
                            rgbColor       = reader.ReadInt16();
                            pixelMap[x, y] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, (rgbColor >> 7) & 0xF8, (rgbColor >> 2) & 0xF8, (rgbColor << 3) & 0xF8, (rgbColor & 0x8000) != 0 ? 255 : 0);
                        }
                    }

                    break;

                case 24:

                    for (int y = height - 1; y >= 0; y--)
                    {
                        for (int x = 0; x < width; x++)
                        {
                            byte[] color = reader.ReadBytes(3);
                            pixelMap[x, y] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, color[2], color[1], color[0], 255);
                        }
                    }

                    break;

                case 32:

                    for (int y = height - 1; y >= 0; y--)
                    {
                        for (int x = 0; x < width; x++)
                        {
                            byte[] color = reader.ReadBytes(4);
                            pixelMap[x, y] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, color[2], color[1], color[0], color[3]);
                        }
                    }

                    break;

                default:
                    reader.Close();
                    return(null);
                }

                reader.Close();
                return(pixelMap);

                #endregion
                #region Compressed RGB

            case (int)TGAImageType.RLERGB:                     // Run length encoded RGB color data.

                // Read in depending on bit depth
                switch (bits)
                {
                case 15:

                    // Read in each image color packet.
                    for (int counter = 0; counter < pixelCount;)
                    {
                        chunkSize = reader.ReadByte();

                        // Check if color packet is RLE or RAW.
                        if ((chunkSize & 128) != 0)
                        {
                            chunkSize -= 127;
                            rgbColor   = reader.ReadInt16();
                            argbColor  = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, (rgbColor >> 7) & 0xF8, (rgbColor >> 2) & 0xF8, (rgbColor << 3) & 0xF8, 255);
                            for (int i = 0; i < chunkSize; i++)
                            {
                                pixelMap[counter % width, height - 1 - (counter / width)] = argbColor;
                                counter++;
                            }
                        }
                        else
                        {
                            chunkSize++;
                            for (int i = 0; i < chunkSize; i++)
                            {
                                rgbColor = reader.ReadInt16();
                                pixelMap[counter % width, height - 1 - (counter / width)] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, (rgbColor >> 7) & 0xF8, (rgbColor >> 2) & 0xF8, (rgbColor << 3) & 0xF8, 255);
                                counter++;
                            }
                        }
                    }

                    break;

                case 16:

                    // Read in each image color packet.
                    for (int counter = 0; counter < pixelCount;)
                    {
                        chunkSize = reader.ReadByte();

                        // Check if color packet is RLE or RAW.
                        if ((chunkSize & 128) != 0)
                        {
                            chunkSize -= 127;
                            rgbColor   = reader.ReadInt16();
                            argbColor  = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, (rgbColor >> 7) & 0xF8, (rgbColor >> 2) & 0xF8, (rgbColor << 3) & 0xF8, (rgbColor & 0x8000) != 0 ? 255 : 0);
                            for (int i = 0; i < chunkSize; i++)
                            {
                                pixelMap[counter % width, height - 1 - (counter / width)] = argbColor;
                                counter++;
                            }
                        }
                        else
                        {
                            chunkSize++;
                            for (int i = 0; i < chunkSize; i++)
                            {
                                rgbColor = reader.ReadInt16();
                                pixelMap[counter % width, height - 1 - (counter / width)] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, (rgbColor >> 7) & 0xF8, (rgbColor >> 2) & 0xF8, (rgbColor << 3) & 0xF8, (rgbColor & 0x8000) != 0 ? 255 : 0);
                                counter++;
                            }
                        }
                    }

                    break;

                case 24:

                    // Read in each image color packet.
                    for (int counter = 0; counter < pixelCount;)
                    {
                        chunkSize = reader.ReadByte();

                        // Check if color packet is RLE or RAW.
                        if ((chunkSize & 128) != 0)
                        {
                            chunkSize -= 127;
                            byte[] color = reader.ReadBytes(3);
                            argbColor = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, color[2], color[1], color[0], 255);
                            for (int i = 0; i < chunkSize; i++)
                            {
                                pixelMap[counter % width, height - 1 - (counter / width)] = argbColor;
                                counter++;
                            }
                        }
                        else
                        {
                            chunkSize++;
                            for (int i = 0; i < chunkSize; i++)
                            {
                                byte[] color = reader.ReadBytes(3);
                                pixelMap[counter % width, height - 1 - (counter / width)] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, color[2], color[1], color[0], 255);
                                counter++;
                            }
                        }
                    }

                    break;

                case 32:

                    // Read in each image color packet.
                    for (int counter = 0; counter < pixelCount;)
                    {
                        chunkSize = reader.ReadByte();

                        // Read in as RLE packet.
                        if ((chunkSize & 128) != 0)
                        {
                            chunkSize -= 127;
                            byte[] color = reader.ReadBytes(4);
                            argbColor = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, color[2], color[1], color[0], color[3]);
                            for (int i = 0; i < chunkSize; i++)
                            {
                                pixelMap[counter % width, height - 1 - (counter / width)] = argbColor;
                                counter++;
                            }
                        }

                        // Read in as RAW packet.
                        else
                        {
                            chunkSize++;
                            for (int i = 0; i < chunkSize; i++)
                            {
                                byte[] color = reader.ReadBytes(4);
                                pixelMap[counter % width, height - 1 - (counter / width)] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, color[2], color[1], color[0], color[3]);
                                counter++;
                            }
                        }
                    }

                    break;

                default:
                    reader.Close();
                    return(null);
                }

                reader.Close();
                return(pixelMap);

                #endregion
            default:
                stream.Close();
                return(null);
            }
        }
Esempio n. 11
0
        /// <summary>
        ///     This method is called when PixelMap load is requested, if you return a PixelMap
        ///     it will return it from the user else it will keep trying all the other PixelMapLoaders
        ///     until it does get one
        /// </summary>
        /// <param name="file">File path of the image to load.</param>
        /// <returns>A PixelMap or NULL if this factory can't load the given image file.</returns>
        protected override PixelMap RequestLoad(object path)
        {
            Stream stream = StreamFactory.RequestStream(path, StreamMode.Open);

            if (stream == null)
            {
                return(null);
            }
            BinaryReader reader = new BinaryReader(stream);

            if (reader.ReadByte() == 'B' && reader.ReadByte() == 'M')
            {
                // Read in file header.
                int   fileSize        = reader.ReadInt32();
                short reserved1       = reader.ReadInt16();
                short reserved2       = reader.ReadInt16();
                int   pixelDataOffset = reader.ReadInt32();

                // Read in image header
                int   imageHeaderSize        = reader.ReadInt32();
                int   imageWidth             = reader.ReadInt32();
                int   imageHeight            = reader.ReadInt32();
                short imagePlanes            = reader.ReadInt16();
                short imageBitCount          = reader.ReadInt16();
                int   imageCompression       = reader.ReadInt32();
                int   imageSize              = reader.ReadInt32();
                int   imageXPixPerMeter      = reader.ReadInt32();
                int   imageYPixPerMeter      = reader.ReadInt32();
                int   imageColorMapUsed      = reader.ReadInt32();
                int   imageColorMapImportant = reader.ReadInt32();
                if (imageCompression > 0)
                {
                    stream.Close();
                    return(null);
                }

                byte[]   pixels;
                int[]    pallete;
                byte[]   tempPallete;
                PixelMap pixelMap = new PixelMap(imageWidth, imageHeight);

                // Work out the horizontal padding size.
                int paddingWidth = (int)((float)imageWidth * (float)imageBitCount / 8.0);
                while (paddingWidth % 4 != 0)
                {
                    paddingWidth++;
                }

                switch (imageBitCount)
                {
                case 1:     // Monochrome

                    int color1 = ColorMethods.CombineColor(ColorFormats.B8G8R8, ColorFormats.A8R8G8B8, reader.ReadInt32());
                    int color2 = ColorMethods.CombineColor(ColorFormats.B8G8R8, ColorFormats.A8R8G8B8, reader.ReadInt32());

                    for (int y = imageHeight - 1; y >= 0; y--)
                    {
                        pixels = reader.ReadBytes(paddingWidth);
                        for (int x = 0; x < imageWidth; x++)
                        {
                            pixelMap[x, y] = ((pixels[x >> 3] & (128 >> (x & 7))) != 0) ? color2 : color1;
                        }
                    }

                    break;

                case 4:     // 16 colors.

                    pallete     = new int[16];
                    tempPallete = new byte[16 * 4];
                    reader.Read(tempPallete, 0, 16 * 4);
                    for (int i = 0; i < 16; i++)
                    {
                        pallete[i] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, tempPallete[(i * 4) + 2], tempPallete[(i * 4) + 1], tempPallete[(i * 4)], 255);
                    }

                    for (int y = imageHeight - 1; y >= 0; y--)
                    {
                        pixels = reader.ReadBytes(paddingWidth);
                        for (int x = 0; x < imageWidth; x++)
                        {
                            pixelMap[x, y] = pallete[(x % 2 == 0) ? (pixels[x / 2] >> 4) : (pixels[x / 2] & 0x0F)];
                        }
                    }

                    break;

                case 8:     // 256 colors.

                    pallete     = new int[256];
                    tempPallete = new byte[256 * 4];
                    reader.Read(tempPallete, 0, 256 * 4);
                    for (int i = 0; i < 256; i++)
                    {
                        pallete[i] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, tempPallete[(i * 4) + 2], tempPallete[(i * 4) + 1], tempPallete[(i * 4)], 255);
                    }

                    for (int y = imageHeight - 1; y >= 0; y--)
                    {
                        pixels = reader.ReadBytes(paddingWidth);
                        for (int x = 0; x < imageWidth; x++)
                        {
                            pixelMap[x, y] = pallete[pixels[x]];
                        }
                    }

                    break;

                case 24:     // 16,777,216 colors

                    for (int y = imageHeight - 1; y >= 0; y--)
                    {
                        pixels = reader.ReadBytes(paddingWidth);
                        for (int x = 0; x < imageWidth; x++)
                        {
                            pixelMap[x, y] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, pixels[(x * 3) + 2], pixels[(x * 3) + 1], pixels[(x * 3)], 255);
                        }
                    }

                    break;

                case 32:     // 16,777,216 colors with alpha

                    for (int y = imageHeight - 1; y >= 0; y--)
                    {
                        pixels = reader.ReadBytes(paddingWidth);
                        for (int x = 0; x < imageWidth; x++)
                        {
                            pixelMap[x, y] = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, pixels[(x * 4) + 2], pixels[(x * 4) + 1], pixels[(x * 4)], pixels[(x * 4) + 3]);
                        }
                    }

                    break;

                default:

                    // The user has either tried to load an corrupt file, or
                    // a file with an unsupported bit count.
                    throw new Exception("Attempt to load BMP file with an bit format storing the image data.");
                }

                stream.Close();
                return(pixelMap);
            }
            else // Header check
            {
                reader.Close();
                return(null);
            }
        }
Esempio n. 12
0
    private void Update()
    {
        //print(ColorMethods.GetResistorColorCode(new Color(0f, 4f/255f, 13f/255f)).ToString());

        if (Input.GetKeyDown(KeyCode.Space))
        {
            var data = t.EncodeToPNG();
            File.WriteAllBytes("a.png", data);
            print("oldu");
        }

        if (Input.touchCount > 0 && Input.touches[0].phase == TouchPhase.Began && Input.touches[0].position.x > Screen.width / 2)
        {
            Application.CaptureScreenshot("ss" + Time.fixedTime + ".png");
            //StartCoroutine(CaptureScreenshotCoroutine(Screen.width, Screen.height));
            s += "s";
        }

        if (!camAvailable)
        {
            return;
        }

        float ratio = (float)backCam.width / (float)backCam.height;

        fit.aspectRatio = ratio;

        float zoomValue = 2.7f;
        float scaleY    = backCam.videoVerticallyMirrored ? -1f : 1f;

        background.rectTransform.localScale = new Vector3(1f * zoomValue, scaleY * zoomValue, 1f);

        int orient = -backCam.videoRotationAngle;

        background.rectTransform.localEulerAngles = new Vector3(0, 0, orient);

        Color color = backCam.GetPixel(backCam.width / 2, backCam.height / 2);

        ColorMethods.ColorName colorName = ColorMethods.GetResistorColorCode(color);
        colorDisplayer.color = GetPrimitiveColor(colorName);
        //colorText.text = "Color: " + colorName.ToString();

        infoText.text = ColorMethods.GetHSV(color).ToString() + s;

        cursor.anchoredPosition = new Vector3(1080 / 2, 1920 / 2, 0f);
        int width  = 75;
        int heigth = 5;

        Color[] colorBlock = backCam.GetPixels(backCam.width / 2 - width / 2, backCam.height / 2 - (heigth - 1) / 2, width, heigth);
        Color[,] colorBlock2D = ArrayTo2DArray(colorBlock, width, heigth);
        //Color baseColor;
        //List<ColorData> colorData = ResistorOhmFinder.GetLines(colorBlock2D, out baseColor);
        //simulator.Set(colorData, baseColor);

        t = new Texture2D(width, heigth);
        t.SetPixels(0, 0, width, heigth, colorBlock);
        t.Apply();

        var t2 = MedianBlur(t, 5);

        t2.Apply();
        Color[] colorBlockBlurred = t2.GetPixels();
        Color[,] colorBlockBlurred2D = ArrayTo2DArray(colorBlockBlurred, width, heigth);
        //testTexture2D = MedianBlur(testTexture2D);
        testImage.texture  = t;
        testImage2.texture = t2;

        List <ColorMethods.ColorName> colorData = ResistorOhmFinder.GetLines(colorBlockBlurred2D, lineCount);

        simulator.Set(colorData, lineCount);


        redLine.sizeDelta = new Vector2(width * zoomValue / 2 * 1.1f, 3);

        //redLine.sizeDelta = new Vector2(width * ratio / 2 * zoomValue * 1.1f, 3);
    }
Esempio n. 13
0
    private static ColorMethods.ColorName GetColor2(Color[,] data, int i)
    {
        int j = (data.GetLength(0) - 1) / 2;

        ColorMethods.ColorName color = ColorMethods.GetResistorColorCode(data[j, i]);
        if (color != ColorMethods.ColorName.Unknown)
        {
            return(color);
        }

        //If color did not recognized, look left..
        if (i > 0 && (color = ColorMethods.GetResistorColorCode(data[j, i - 1])) != ColorMethods.ColorName.Unknown)
        {
            return(color);
        }

        //If not recognized, look rigth
        if (i < data.GetLength(1) - 1 && (color = ColorMethods.GetResistorColorCode(data[j, i + 1])) != ColorMethods.ColorName.Unknown)
        {
            return(color);
        }

        //If not recognized, look top
        if (j > 0 && (color = ColorMethods.GetResistorColorCode(data[j - 1, i])) != ColorMethods.ColorName.Unknown)
        {
            return(color);
        }

        //If not recognized, look bottom
        if (data.GetLength(0) > 1 && (color = ColorMethods.GetResistorColorCode(data[j + 1, i])) != ColorMethods.ColorName.Unknown)
        {
            return(color);
        }

        //If not recognized, look top left
        if (j > 0 && i > 0 && (color = ColorMethods.GetResistorColorCode(data[j - 1, i - 1])) != ColorMethods.ColorName.Unknown)
        {
            return(color);
        }

        //If not recognized, look top rigth
        if (j > 0 && i < data.GetLength(1) - 1 && (color = ColorMethods.GetResistorColorCode(data[j - 1, i + 1])) != ColorMethods.ColorName.Unknown)
        {
            return(color);
        }

        //If not recognized, look bottom left
        if (data.GetLength(0) > 1 && i > 0 && (color = ColorMethods.GetResistorColorCode(data[j + 1, i - 1])) != ColorMethods.ColorName.Unknown)
        {
            return(color);
        }

        //If not recognized, look bottom right
        if (data.GetLength(0) > 1 && i < data.GetLength(1) - 1 && (color = ColorMethods.GetResistorColorCode(data[j + 1, i + 1])) != ColorMethods.ColorName.Unknown)
        {
            return(color);
        }

        //If never recognized, return null
        return(ColorMethods.ColorName.Unknown);
    }
Esempio n. 14
0
    public static List <ColorData> GetLines(Color[,] data, out Color baseColorInfo)
    {
        //Convert all data to ColorData.
        ColorData[,] colorInfo = GetColorData(data);

        //Find the center of the vertical axis of pixel group.
        int j = colorInfo.GetLength(0) / 2;

        //Set base color info to most left and center pixel.
        baseColorInfo = colorInfo[j, 0].color;

        //Set most left and center pixel as base color of resistor.
        ColorMethods.HSV baseColor = ColorMethods.GetHSV(colorInfo[j, 0].color);

        //Create an empty list to save lines.
        List <ColorData> lines = new List <ColorData>();

        //Set tolerance level to check if a color is same as the base color since base color has no known range.
        float[] tolerance = { 5f, 0.1f, 0.3f };

        //Create a flag to know if last checked pixel was a part of a line.
        ColorData lastPixel = null;

        //Iterate through all pixel from left to right to resolve their colors and find line colors.
        for (int i = 1; i < colorInfo.GetLength(1); i++)
        {
            //Get current pixel.
            ColorData currentPixel = colorInfo[j, i];

            //If current pixel is white, check if it is just a shine effect.
            if (currentPixel.colorName == ColorMethods.ColorName.White)
            {
                currentPixel = CheckShine(i, colorInfo);
            }

            //If color of current pixel couldn't be resolved, continue to next pixel.
            if (currentPixel.colorName == ColorMethods.ColorName.Unknown)
            {
                Debug.LogWarning("Unknown pixel color found: " + currentPixel.color.ToString());
                continue;
            }

            //If current pixel is NOT same as the base color ...
            if (CompareColors(baseColor, ColorMethods.GetHSV(currentPixel.color), tolerance) == false)
            {
                /*If last checked pixel was NOT a line color, that means we found a new line on resistor.
                 * We should add this pixel to lines list and turn on the flag to let next pixel know last
                 * pixel was a line pixel.*/
                if (lastPixel == null)
                {
                    if (lines.Count < 6)
                    {
                        lines.Add(currentPixel);
                        lastPixel = currentPixel;
                    }
                    /*If there are already 6 lines but found a seventh one, that means this object is not a resistor.*/
                    else
                    {
                        return(null);
                    }
                }

                /*If last checked pixel was a line color, but not same as this pixel's color; that means
                 * there are two different lines next to each other without a base color seperating them.
                 * That is not possible on a resistor.*/
                else
                {
                    if (lastPixel.colorName != currentPixel.colorName)
                    {
                        Debug.LogWarning("Two different adjoining lines found: 1)" + currentPixel.colorName.ToString() + " 2)" + lastPixel.colorName.ToString());
                    }
                }
            }
            //If current pixel is same as the base color, turn off the flag of last pixel was a line.
            else
            {
                lastPixel = null;
            }
        }
        return(lines);
    }
        /// <summary>
        ///		Syncronizes the data in property list with that contained in the entity.
        /// </summary>
        public void SyncronizeData()
        {
            // Clear the list view so its ready for some new items.
            propertyListView.Clear();

            // If we have no entity at the moment then just disable this control and return.
            if (_entity == null)
            {
                propertyListView.Enabled = false;
                _categories = null;
                propertyListView.Refresh();
                return;
            }

            // Set the default values of this list view.
            propertyListView.Enabled     = true;
            propertyListView.DefaultItem = "Test";

            // Split up the color of our entity to make the rendering category
            // easier to create.
            int a, r, g, b;

            ColorMethods.SplitColor(ColorFormats.A8R8G8B8, _entity.Color, out r, out g, out b, out a);

            // Create a list of categories and properties to go in them.
            _categories = new object[]
            {
                // This is our general category.
                new object[]
                {
                    new PropertyListViewCategory("General"),
                    new PropertyListViewItem("Name", _entity.Name, "", "Name of this entity. Used by the event system to identify and trigger this entity if neccessary.", typeof(string)),
                    new PropertyListViewItem("Event", _entity.Event, "", "Name of entity to trigger when this entity is triggered.", typeof(string)),
                    new PropertyListViewItem("Enabled", _entity.IsEnabled, true, "Indicates whether this entity is enabled.", typeof(bool)),
                },

                // This is our transformation category.
                new object[]
                {
                    new PropertyListViewCategory("Transformation"),
                    new PropertyListViewItem("Location", new Point((int)_entity.Transformation.X, (int)_entity.Transformation.Y), new Point(), "The location of this entity.", typeof(Point)),
                    new PropertyListViewItem("Z-Offset", _entity.Transformation.Z, 0.0f, "This value is added to this entities resulting depth, you can use it to set a depth origin.", typeof(float)),
                    new PropertyListViewItem("Z-Layer", _entity.DepthLayer, 0, "Determines which depth layer this entity is render one.", typeof(int)),
                    new PropertyListViewItem("Depth Mode", _entity.DepthMode, (int)EntityDepthMode.Normal, "Determines how the depth of this entity is worked out.", typeof(EntityDepthMode)),
                    new PropertyListViewItem("Scale", new Vector(_entity.Transformation.ScaleX, _entity.Transformation.ScaleY, _entity.Transformation.ScaleZ), new Vector(), "The scale of this entity.", typeof(Vector)),
                    new PropertyListViewItem("Angle", new Vector(_entity.Transformation.AngleX, _entity.Transformation.AngleY, _entity.Transformation.AngleZ), new Vector(), "The rotational angle of this entity in degrees.", typeof(Vector)),
                    new PropertyListViewItem("Bounding Rectangle", _entity.BoundingRectangle, new Rectangle(0, 0, 0, 0), "The bounding box of this entity. The bounding box is used for determining how an entity should be culled to save rendering time.", typeof(Rectangle)),
                },
            };

            // See if we can insert the collision group.
            if (_entity.CollisionPolygon != null)
            {
                object[] newCategories = new object[_categories.Length + 1];
                _categories.CopyTo(newCategories, 0);
                _categories = newCategories;
                _categories[_categories.Length - 1] = new object[]
                {
                    new PropertyListViewCategory("Collision"),
                    new PropertyListViewItem("Solid", _entity.IsSolid, true, "Indicates whether this entity can respond to collisions.", typeof(bool)),
                    new PropertyListViewItem("Collision Layers", _entity.CollisionPolygon.Layers, new int[] { 0 }, "Indicates which collision layers this entity can collide with.", typeof(int[])),
                    new PropertyListViewItem("Collision Rectangle", _entity.CollisionRectangle, new Rectangle(0, 0, 0, 0), "Specifies the dimensions of the collision box of this entity.", typeof(Rectangle)),
                };
            }

            // Add the text and rendering categories as well.
            if (!(_entity is TilemapSegmentNode) && !(_entity is EmitterNode))
            {
                object[] newCategories = new object[_categories.Length + 2];
                _categories.CopyTo(newCategories, 0);
                _categories = newCategories;
                _categories[_categories.Length - 1] = new object[]
                {
                    new PropertyListViewCategory("Rendering"),
                    new PropertyListViewItem("Visible", _entity.IsVisible, true, "Indicates whether this entity is visible.", typeof(bool)),
                    new PropertyListViewItem("Color", Color.FromArgb(ColorMethods.CombineColor(ColorFormats.A8R8G8B8, r, g, b, 255)), Color.FromArgb(unchecked ((int)0xFFFFFFFF)), "Indicates the color this entity should be tinted.", typeof(Color)),
                    new PropertyListViewItem("Alpha", a, (byte)255, "Indicates the transparency this entity should be rendered at.", typeof(byte)),
                    new PropertyListViewItem("Blend Mode", _entity.BlendMode, BlendMode.Alpha, "Indicates the blending mode this entity should be rendered with.", typeof(BlendMode)),
                    new PropertyListViewItem("Render Mode", _entity.RenderMode, EntityRenderMode.None, "Indicates how this entity should be rendered.", typeof(EntityRenderMode)),
                    new PropertyListViewItem("Image", _entity.Image, null, "The image that should be rendered if this entitys rendering mode is set to render an image.", typeof(string), typeof(ImageEditor)),
                    new PropertyListViewItem("Frame", _entity.Frame, 0, "The frame of this entitys image that should be rendered when render mode is set to an image mode.", typeof(int)),
                    new PropertyListViewItem("Shader", new FileEditorValue(_entity.Shader == null ? "" : _entity.Shader.URL.ToString(), "Fusion Shader Files|*.xml", Environment.CurrentDirectory + "\\" + Engine.Engine.GlobalInstance.ShaderPath), null, "The shader that this entity should apply to itself when rendering.", typeof(string), typeof(FileEditor)),
                    new PropertyListViewItem("Mesh", new FileEditorValue(_entity.Mesh == null ? "" : _entity.Mesh.URL.ToString(), "Mesh Files|*.raw", Environment.CurrentDirectory + "\\" + Engine.Engine.GlobalInstance.MediaPath), null, "The mesh that this entity should use to render if its render mode is set to MESH.", typeof(string), typeof(FileEditor)),
                };

                // ((PropertyListViewItem)(((object[])_categories[_categories.Length - 1])[6])).Attributes = new Attribute[] { new ReadOnlyAttribute(true) };

                // This is our text category.
                _categories[_categories.Length - 2] = new object[]
                {
                    new PropertyListViewCategory("Text"),
                    new PropertyListViewItem("Text", _entity.Text, "", "The string of text that this entity should render if its render mode is set to Text.", typeof(string)),
                    new PropertyListViewItem("Bitmap Font", _entity.Font, null, "Bitmap font used to render text when this entitys render mode is set to Text.", typeof(string), typeof(BitmapFontEditor)),
                };

                // ((PropertyListViewItem)(((object[])_categories[_categories.Length - 2])[2])).Attributes = new Attribute[] { new ReadOnlyAttribute(true) };
            }
            else if (_entity is TilemapSegmentNode)
            {
                object[] newCategories = new object[_categories.Length + 1];
                _categories.CopyTo(newCategories, 0);
                _categories = newCategories;
                _categories[_categories.Length - 1] = new object[]
                {
                    new PropertyListViewCategory("Rendering"),
                    new PropertyListViewItem("Visible", _entity.IsVisible, true, "Indicates whether this entity is visible.", typeof(bool)),
                    new PropertyListViewItem("Color", Color.FromArgb(ColorMethods.CombineColor(ColorFormats.A8R8G8B8, r, g, b, 255)), Color.FromArgb(unchecked ((int)0xFFFFFFFF)), "Indicates the color this entity should be tinted.", typeof(Color)),
                    new PropertyListViewItem("Alpha", a, (byte)255, "Indicates the transparency this entity should be rendered at.", typeof(byte)),
                    new PropertyListViewItem("Blend Mode", _entity.BlendMode, BlendMode.Alpha, "Indicates the blending mode this entity should be rendered with.", typeof(BlendMode)),
                };
            }
            else if (_entity is EmitterNode)
            {
                object[] newCategories = new object[_categories.Length + 1];
                _categories.CopyTo(newCategories, 0);
                _categories = newCategories;
                _categories[_categories.Length - 1] = new object[]
                {
                    new PropertyListViewCategory("Rendering"),
                    new PropertyListViewItem("Visible", _entity.IsVisible, true, "Indicates whether this entity is visible.", typeof(bool)),
                };
            }

            // Specialist properties.
            if (_entity is ScriptedEntityNode)
            {
                #region Script properties

                // Add the new dynamic category to the category list.
                ArrayList categoryList = new ArrayList();
                categoryList.Add(new PropertyListViewCategory("Script"));
                object[] newCategories = new object[_categories.Length + 1];
                _categories.CopyTo(newCategories, 0);
                _categories = newCategories;

                // Insert all the properties contained in the scripts.
                ScriptedEntityNode scriptedEntity = (ScriptedEntityNode)_entity;
                foreach (Symbol symbol in scriptedEntity.ScriptProcess.GlobalScope.Symbols)
                {
                    if (symbol is VariableSymbol && ((VariableSymbol)symbol).IsProperty == true)
                    {
                        VariableSymbol variableSymbol = ((VariableSymbol)symbol);
                        object         value          = null;

                        if (variableSymbol.DataType.IsArray == false)
                        {
                            switch (variableSymbol.DataType.DataType)
                            {
                            case DataType.Bool: value = scriptedEntity.ScriptProcess[0].GetBooleanGlobal(variableSymbol.Identifier); break;

                            case DataType.Byte: value = scriptedEntity.ScriptProcess[0].GetByteGlobal(variableSymbol.Identifier); break;

                            case DataType.Double: value = scriptedEntity.ScriptProcess[0].GetDoubleGlobal(variableSymbol.Identifier); break;

                            case DataType.Float: value = scriptedEntity.ScriptProcess[0].GetFloatGlobal(variableSymbol.Identifier); break;

                            case DataType.Int: value = scriptedEntity.ScriptProcess[0].GetIntegerGlobal(variableSymbol.Identifier); break;

                            case DataType.Long: value = scriptedEntity.ScriptProcess[0].GetLongGlobal(variableSymbol.Identifier); break;

                            case DataType.Short: value = scriptedEntity.ScriptProcess[0].GetShortGlobal(variableSymbol.Identifier); break;

                            case DataType.String:
                                value = scriptedEntity.ScriptProcess[0].GetStringGlobal(variableSymbol.Identifier);
                                if (value == null)
                                {
                                    value = "";
                                }
                                break;

                            case DataType.Object:
                                value = scriptedEntity.ScriptProcess[0].GetObjectGlobal(variableSymbol.Identifier);
                                if (value is NativeObject)
                                {
                                    value = ((NativeObject)value).Object;
                                }
                                break;
                                //default: continue;
                            }
                        }
                        else
                        {
                            int arrayIndex  = scriptedEntity.ScriptProcess[0].GetArrayGlobal(variableSymbol.Identifier);
                            int arrayLength = 0;
                            if (arrayIndex == 0)
                            {
                                arrayLength = 1;
                            }
                            else
                            {
                                arrayLength = scriptedEntity.ScriptProcess[0].GetArrayLength(arrayIndex);
                            }

                            switch (variableSymbol.DataType.DataType)
                            {
                            case DataType.Bool: value = new bool[arrayLength]; break;

                            case DataType.Byte: value = new byte[arrayLength]; break;

                            case DataType.Double: value = new double[arrayLength]; break;

                            case DataType.Float: value = new float[arrayLength]; break;

                            case DataType.Int: value = new int[arrayLength]; break;

                            case DataType.Long: value = new long[arrayLength]; break;

                            case DataType.Short: value = new short[arrayLength]; break;

                            case DataType.String: value = new string[arrayLength]; break;

                            case DataType.Object: value = new object[arrayLength]; break;
                            }

                            if (arrayIndex != 0)
                            {
                                for (int i = 0; i < arrayLength; i++)
                                {
                                    switch (variableSymbol.DataType.DataType)
                                    {
                                    case DataType.Bool: ((object[])value)[i] = scriptedEntity.ScriptProcess[0].GetBooleanArrayElement(arrayIndex, i); break;

                                    case DataType.Byte: ((object[])value)[i] = scriptedEntity.ScriptProcess[0].GetByteArrayElement(arrayIndex, i); break;

                                    case DataType.Double: ((object[])value)[i] = scriptedEntity.ScriptProcess[0].GetDoubleArrayElement(arrayIndex, i); break;

                                    case DataType.Float: ((object[])value)[i] = scriptedEntity.ScriptProcess[0].GetFloatArrayElement(arrayIndex, i); break;

                                    case DataType.Int: ((object[])value)[i] = scriptedEntity.ScriptProcess[0].GetIntArrayElement(arrayIndex, i); break;

                                    case DataType.Long: ((object[])value)[i] = scriptedEntity.ScriptProcess[0].GetLongArrayElement(arrayIndex, i); break;

                                    case DataType.Short: ((object[])value)[i] = scriptedEntity.ScriptProcess[0].GetShortArrayElement(arrayIndex, i); break;

                                    case DataType.String:
                                        ((object[])value)[i] = scriptedEntity.ScriptProcess[0].GetStringArrayElement(arrayIndex, i);
                                        if (((object[])value)[i] == null)
                                        {
                                            ((object[])value)[i] = "";
                                        }
                                        break;

                                    case DataType.Object:
                                        ((object[])value)[i] = scriptedEntity.ScriptProcess[0].GetObjectArrayElement(arrayIndex, i);
                                        if (((object[])value)[i] is NativeObject)
                                        {
                                            ((object[])value)[i] = ((NativeObject)value).Object;
                                        }
                                        break;
                                        //default: continue;
                                    }
                                }
                            }
                        }

                        // Check to see if there is an editmethod meta-data chunk attached to this property.
                        string editMethod = "", basePath = "", filter = "", description = "", name = variableSymbol.Identifier, enumeration = "";
                        bool   dontCreate = false;
                        Type   type = null, editorType = null;
                        foreach (Symbol subSymbol in symbol.Symbols)
                        {
                            if (subSymbol is MetaDataSymbol)
                            {
                                switch (((MetaDataSymbol)subSymbol).Identifier.ToLower())
                                {
                                case "editmethod": editMethod = ((MetaDataSymbol)subSymbol).Value; break;

                                case "basepath": basePath = Environment.CurrentDirectory + "\\" + ((MetaDataSymbol)subSymbol).Value; break;

                                case "filter": filter = ((MetaDataSymbol)subSymbol).Value; break;

                                case "description": description = ((MetaDataSymbol)subSymbol).Value; break;

                                case "name": name = ((MetaDataSymbol)subSymbol).Value; break;

                                case "enumeration": enumeration = ((MetaDataSymbol)subSymbol).Value; break;

                                case "filtertype":
                                    switch (((MetaDataSymbol)subSymbol).Value.ToLower())
                                    {
                                    case "audio": filter = "Audio Files|*.ogg;*.wav"; break;

                                    case "script": filter = "Script Files|*.fs;*.fso;*.fsl"; break;

                                    case "object": filter = "Object Declaration Files|*.fso"; break;

                                    case "font": filter = "Font Declaration Files|*.xml"; break;

                                    case "map": filter = "Fusion Map Files|*.fmp"; break;

                                    case "graphic": filter = "Graphics Files|*.tga;*.bmp"; break;

                                    case "tileset": filter = "Tileset Declaration Files|*.xml"; break;

                                    case "save": filter = "Fusion Save Files|*.fsv"; break;

                                    case "shader": filter = "Fusion Shader Files|*.xml"; break;
                                    }
                                    break;
                                }
                            }
                        }

                        if (editMethod.ToLower() == "file" && variableSymbol.DataType.DataType == DataType.String)
                        {
                            value      = new FileEditorValue(value.ToString(), filter, basePath);
                            type       = typeof(string);
                            editorType = typeof(FileEditor);
                        }
                        else if (editMethod.ToLower() == "color" && value is int)
                        {
                            value = Color.FromArgb((int)value);
                            type  = typeof(Color);
                        }
                        else if (editMethod.ToLower() == "image" && variableSymbol.DataType.DataType == DataType.Object)
                        {
                            type       = typeof(string);
                            editorType = typeof(ImageEditor);
                        }
                        else if (editMethod.ToLower() == "sound" && variableSymbol.DataType.DataType == DataType.Object)
                        {
                            type       = typeof(string);
                            editorType = typeof(SoundEditor);
                        }
                        else if (editMethod.ToLower() == "enumeration" && variableSymbol.DataType.DataType == DataType.Int)
                        {
                            // Split up the enumeration scope.
                            string[] scopeList    = enumeration.Split(new char[] { '.' });
                            Symbol   currentScope = scriptedEntity.ScriptProcess.GlobalScope;

                            // Lets find the correct enumeration.
                            for (int i = 0; i < scopeList.Length; i++)
                            {
                                if (currentScope == null)
                                {
                                    break;
                                }

                                string scopeName = scopeList[i];
                                currentScope = currentScope.FindSymbol(scopeName);
                            }

                            // Check it exists and is an enumeration.
                            if (currentScope != null && currentScope.Type == SymbolType.Enumeration)
                            {
                                ArrayList list = new ArrayList();
                                PropertyEnumerationEntry currentEntry = null;
                                foreach (Symbol subSymbol in currentScope.Symbols)
                                {
                                    if (subSymbol == null || subSymbol.Type != SymbolType.Variable)
                                    {
                                        continue;
                                    }
                                    PropertyEnumerationEntry entry = new PropertyEnumerationEntry(subSymbol.Identifier, Int32.Parse(((VariableSymbol)subSymbol).ConstToken.Ident));
                                    if (entry.Value == (int)value)
                                    {
                                        currentEntry = entry;
                                    }
                                    list.Add(entry);
                                }

                                int index = (int)value;
                                value = (currentEntry == null) ? "Unknown" : currentEntry.Name;
                                type  = typeof(string);

                                PropertyListViewItem item = new PropertyListViewItem(name, value, value, description, type);
                                item.EnumerationValues = list;
                                item.EnumerationValue  = (currentEntry == null) ? 0 : currentEntry.Value;
                                item.TypeConverter     = typeof(PropertyEnumerationConverter).AssemblyQualifiedName;
                                dontCreate             = true;
                                categoryList.Add(item);
                            }
                        }
                        else
                        {
                            if (variableSymbol.DataType.DataType == DataType.Object)
                            {
                                continue;
                            }
                            type = value.GetType();
                        }

                        // And finally lets create the property item.
                        if (dontCreate == false)
                        {
                            if (editorType == null)
                            {
                                categoryList.Add(new PropertyListViewItem(name, value, value, description, type));
                            }
                            else
                            {
                                categoryList.Add(new PropertyListViewItem(name, value, value, description, type, editorType));
                            }
                        }
                    }
                }

                // Add everything to the category list.
                _categories[_categories.Length - 1] = categoryList.ToArray();
                #endregion
            }

            else if (_entity is EmitterNode)
            {
                // Add the new dynamic category to the category list.
                object[] newCategories = new object[_categories.Length + 1];
                _categories.CopyTo(newCategories, 0);
                _categories = newCategories;
                _categories[_categories.Length - 1] = new object[]
                {
                    new PropertyListViewCategory("Emitter"),
                    new PropertyListViewItem("Effect", _entity, null, "Contains the actual definition of this emitters effect. Editing this will caused the effects editor to be opened.", typeof(string), typeof(EmitterEditor)),
                };

                //((PropertyListViewItem)(((object[])_categories[_categories.Length - 1])[1])).Attributes = new Attribute[] { new ReadOnlyAttribute(true) };
            }

            else if (_entity is TilemapSegmentNode)
            {
                TilemapSegmentNode segmentNode = _entity as TilemapSegmentNode;

                // Add the new dynamic category to the category list.
                object[] newCategories = new object[_categories.Length + 1];
                _categories.CopyTo(newCategories, 0);
                _categories = newCategories;
                _categories[_categories.Length - 1] = new object[]
                {
                    new PropertyListViewCategory("Tilemap"),
                    new PropertyListViewItem("Grid Visible", segmentNode.IsGridVisible, false, "Indicates if a grid should be rendered over this tilemap segment or not.", typeof(bool)),
                    new PropertyListViewItem("Tile Size", new Size(segmentNode.TileWidth, segmentNode.TileHeight), new Size(0, 0), "Indicates if a grid should be rendered over this tilemap segment or not.", typeof(Size)),
                };
            }

            else if (_entity is PathMarkerNode)
            {
                PathMarkerNode markerNode = _entity as PathMarkerNode;

                // Add the new dynamic category to the category list.
                object[] newCategories = new object[_categories.Length + 1];
                _categories.CopyTo(newCategories, 0);
                _categories = newCategories;
                _categories[_categories.Length - 1] = new object[]
                {
                    new PropertyListViewCategory("Path Marker"),
                    new PropertyListViewItem("Speed", markerNode.Speed, new StartFinishF(0, 0), "Indicates the starting and finishing speeds a entity should move along this path.", typeof(StartFinishF)),
                    new PropertyListViewItem("Delay", markerNode.Delay, 0, "If set this indicates the delay before this part of the path starts.", typeof(int)),
                    new PropertyListViewItem("Next Marker Name", markerNode.NextNodeName, "", "This is the name of the next node in the sequence.", typeof(string)),
                };
                ((PropertyListViewItem)((object[])_categories[_categories.Length - 1])[1]).TypeConverter = typeof(ExpandableObjectConverter).AssemblyQualifiedName;
            }

            // Populate the list view.
            foreach (object[] category in _categories)
            {
                // Create the category.
                PropertyListViewCategory listViewCategory = category[0] as PropertyListViewCategory;
                propertyListView.AddCategory(listViewCategory);

                // Add any existing items into the category.
                if (category.Length > 0)
                {
                    for (int i = category.Length - 1; i >= 1; i--) // Add items in reverse otherwise it will appear the wrong way round :D.
                    {
                        listViewCategory.AddProperty((PropertyListViewItem)category[i]);
                    }
                }
            }

            // Refresh the property list view.
            propertyListView.Refresh();
        }
Esempio n. 16
0
        /// <summary>
        ///     This method is called when PixelMap save is requested, if it returns true
        ///		the calling method will stop illiterating through the PixelMapFactorys and
        ///		return success to the user.
        /// </summary>
        /// <param name="path">File path or object of the image to load.</param>
        /// <param name="pixelMap">PixelMap to save.</param>
        /// <param name="flags">Bitmask of flags defining how the pixel map should be saved.</param>
        /// <returns>True if the save was successfull else false.</returns>
        protected override bool RequestSave(object path, PixelMap pixelMap, PixelMapSaveFlags flags)
        {
            if (path.ToString().ToLower().EndsWith(".bmp") == false &&
                path.ToString().ToLower().EndsWith(".dib") == false)
            {
                return(false);
            }

            Stream stream = StreamFactory.RequestStream(path, StreamMode.Truncate);

            if (stream == null)
            {
                return(false);
            }

            BinaryWriter writer = new BinaryWriter(stream);

            // Work out how to save.
            int bitCount = 24;

            if ((flags & PixelMapSaveFlags.BITDEPTH1) != 0)
            {
                bitCount = 1;
            }
            if ((flags & PixelMapSaveFlags.BITDEPTH4) != 0)
            {
                bitCount = 4;
            }
            if ((flags & PixelMapSaveFlags.BITDEPTH8) != 0)
            {
                bitCount = 8;
            }
            if ((flags & PixelMapSaveFlags.BITDEPTH24) != 0)
            {
                bitCount = 24;
            }
            if ((flags & PixelMapSaveFlags.BITDEPTH32) != 0)
            {
                bitCount = 32;
            }

            // Write in header.
            writer.Write(new char[2] {
                'B', 'M'
            });

            // Write in file header.
            writer.Write((int)0);
            writer.Write((short)0);
            writer.Write((short)0);
            writer.Write((int)54);

            // Write in image header.
            writer.Write((int)40);
            writer.Write((int)pixelMap.Width);
            writer.Write((int)pixelMap.Height);
            writer.Write((short)1);
            writer.Write((short)bitCount);
            writer.Write((int)0);
            writer.Write((int)0);
            writer.Write((int)3780);
            writer.Write((int)3780);
            writer.Write((int)0);
            writer.Write((int)0);

            // Work out the horizontal padding size.
            int paddingWidth = (int)((float)pixelMap.Width * (float)bitCount / 8.0f);

            while (paddingWidth % 4 != 0)
            {
                paddingWidth++;
            }

            // Grab a few usefull details from the pixel map.
            int maskColor = pixelMap.MaskColor, maskRed, maskGreen, maskBlue, maskAlpha;

            ColorMethods.SplitColor(ColorFormats.A8R8G8B8, maskColor, out maskRed, out maskGreen, out maskBlue, out maskAlpha);

            // Write in based of bit count
            switch (bitCount)
            {
            case 1:

                // Write out our lovely monocromatic colors, black and white obviously :).
                writer.Write((int)ColorMethods.CombineColor(ColorFormats.A8R8G8B8, ColorFormats.B8G8R8, unchecked ((int)0xFF000000)));
                writer.Write((int)ColorMethods.CombineColor(ColorFormats.A8R8G8B8, ColorFormats.B8G8R8, unchecked ((int)0xFFFFFFFF)));

                // Write byte here!
                for (int y = pixelMap.Height - 1; y >= 0; y--)
                {
                    int bit     = 128;
                    int bitMask = 0;

                    for (int x = 0; x < pixelMap.Width; x++)
                    {
                        // Mask with bit if pixel should be black.
                        int red, green, blue, alpha;
                        ColorMethods.SplitColor(ColorFormats.A8R8G8B8, pixelMap[x, y], out red, out green, out blue, out alpha);
                        if (red > 128 || green > 128 || blue > 128)
                        {
                            bitMask |= bit;
                        }

                        // Flips horizontal direction at every 8th horizontal pixel.
                        // Update bit mask.
                        bit >>= 1;
                        if (bit < 1)
                        {
                            writer.Write((byte)bitMask);
                            bit     = 128;
                            bitMask = 0;
                        }
                    }

                    // Write in last bit if neccessary.
                    if (bitMask > 0)
                    {
                        writer.Write((byte)bitMask);
                    }

                    // Pad out scan line.
                    for (int i = (pixelMap.Width / 8); i < paddingWidth - 1; i++)
                    {
                        writer.Write((byte)0);
                    }
                }

                break;

            //case 4: // - Can't think when this would be needed? Can you?

            //	break;

            //case 8: // Same as 4bit.

            //	break;

            case 24:

                for (int y = pixelMap.Height - 1; y >= 0; y--)
                {
                    for (int x = 0; x < paddingWidth / (bitCount / 8); x++)
                    {
                        int red = 0, green = 0, blue = 0, alpha = 0;
                        if (x < pixelMap.Width)
                        {
                            // If the pixel map is masked we need to substitute the pixel color
                            // for the correct mask color or we will just end up with an invisible pixel (>_>).
                            if (pixelMap[x, y] != pixelMap.MaskColor)
                            {
                                ColorMethods.SplitColor(ColorFormats.A8R8G8B8, pixelMap[x, y], out red, out green, out blue, out alpha);
                            }
                            else
                            {
                                blue  = maskBlue;
                                green = maskGreen;
                                red   = maskRed;
                            }
                            writer.Write((byte)blue);
                            writer.Write((byte)green);
                            writer.Write((byte)red);
                        }
                        else
                        {
                            writer.Write((byte)0);
                        }
                    }
                }

                break;

            case 32:

                for (int y = pixelMap.Height - 1; y >= 0; y--)
                {
                    for (int x = 0; x < paddingWidth / (bitCount / 8); x++)
                    {
                        int red = 0, green = 0, blue = 0, alpha = 0;
                        if (x < pixelMap.Width)
                        {
                            // If the pixel map is masked we need to substitute the pixel color
                            // for the correct mask color or we will just end up with an invisible pixel (>_>).
                            if (pixelMap[x, y] != pixelMap.MaskColor)
                            {
                                ColorMethods.SplitColor(ColorFormats.A8R8G8B8, pixelMap[x, y], out red, out green, out blue, out alpha);
                            }
                            else
                            {
                                blue  = maskBlue;
                                green = maskGreen;
                                red   = maskRed;
                                alpha = maskAlpha;
                            }
                            writer.Write((byte)blue);
                            writer.Write((byte)green);
                            writer.Write((byte)red);
                            writer.Write((byte)alpha);
                        }
                        else
                        {
                            writer.Write((byte)0);
                        }
                    }
                }

                break;

            default:

                stream.Close();
                throw new Exception(bitCount + "bit bmp saving is not supported");
            }

            // Seek back to start and write in file size
            stream.Flush();
            int fileSize = (int)stream.Length;

            stream.Seek(2, SeekOrigin.Begin);
            writer.Write(fileSize);

            // Seek back to start and write in image size.
            stream.Seek(34, SeekOrigin.Begin);
            writer.Write(fileSize - 54);

            // Cleanup stream and return success.
            stream.Close();
            return(true);
        }
        /// <summary>
        ///     Called when the property list view wishs to set the value of an item.
        /// </summary>
        /// <param name="item">Item to set value of.</param>
        /// <param name="value">Value to set item as.</param>
        private void SetValue(PropertyListViewItem item, object value)
        {
            // If the value is a file editor we need to grab its file URL.
            if (value is FileEditorValue)
            {
                value = ((FileEditorValue)value).FileUrl;
            }

            // If its an enumeration get its enumeration value instead.
            if (item.EnumerationValues != null)
            {
                value = item.EnumerationValue;
            }

            // Go through non-dynamic items.
            switch (item.Name.ToLower())
            {
            // General
            case "name":
                _entity.Name = value as string;
                Engine.Engine.GlobalInstance.Map.SceneGraph.SyncronizeNodes();
                return;

            case "event":
                _entity.Event      = value as string;
                _entity.EventNodes = Engine.Engine.GlobalInstance.Map.SceneGraph.GetNodesByName(_entity.Event);
                return;

            case "enabled":     _entity.IsEnabled = (bool)value; return;

            // Rendering
            case "visible":     _entity.IsVisible = (bool)value; return;

            case "color":
            {
                Color color = (Color)value;
                int   a, r, g, b;
                ColorMethods.SplitColor(ColorFormats.A8R8G8B8, _entity.Color, out r, out g, out b, out a);
                _entity.Color = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, color.R, color.G, color.B, a);
                return;
            }

            case "alpha":
            {
                int a, r, g, b;
                ColorMethods.SplitColor(ColorFormats.A8R8G8B8, _entity.Color, out r, out g, out b, out a);
                _entity.Color = ColorMethods.CombineColor(ColorFormats.A8R8G8B8, r, g, b, (byte)value);
                return;
            }

            case "blend mode":  _entity.BlendMode = (BlendMode)value; return;

            case "render mode": _entity.RenderMode = (EntityRenderMode)value; return;

            case "image":
            {
                _entity.Image = value as Graphics.Image;

                if (_entity.Image != null)
                {
                    _entity.BoundingRectangle  = new Rectangle(0, 0, _entity.Image.Width, _entity.Image.Height);
                    _entity.CollisionRectangle = new Rectangle(0, 0, _entity.Image.Width, _entity.Image.Height);
                }

                return;
            }

            case "mesh": _entity.Mesh = (string)value == "" ? null : new Mesh(Engine.Engine.GlobalInstance.MediaPath + "\\" + value, 0); return;

            case "frame":      _entity.Frame = (int)value; return;

            // Collision
            case "solid":               _entity.IsSolid = (bool)value; return;

            case "collision rectangle": _entity.CollisionRectangle = (Rectangle)value; return;

            case "collision layers":    _entity.CollisionPolygon.Layers = value as int[]; return;

            // Text
            case "text":                _entity.Text = (string)value; return;

            case "bitmap font":         _entity.Font = value as BitmapFont; return;

            case "shader":              _entity.Shader = (string)value == "" ? null : new Shader(Engine.Engine.GlobalInstance.ShaderPath + "\\" + value); return;

            // Transformation
            case "location":            _entity.Position(((Point)value).X, ((Point)value).Y, _entity.Transformation.Z); return;

            case "scale":               _entity.Scale(((Vector)value).X, ((Vector)value).Y, ((Vector)value).Z); return;

            case "angle":               _entity.Rotate(((Vector)value).X, ((Vector)value).Y, ((Vector)value).Z); return;

            case "z-offset":            _entity.Position(_entity.Transformation.X, _entity.Transformation.Y, (float)value); return;

            case "z-layer":             _entity.DepthLayer = (int)value; return;

            case "depth mode":          _entity.DepthMode = (EntityDepthMode)value; return;

            case "bounding rectangle":  _entity.BoundingRectangle = (Rectangle)value; return;
            }

            // Go through dynamic items.
            if (_entity is ScriptedEntityNode)
            {
                ScriptedEntityNode scriptedEntity = (ScriptedEntityNode)_entity;
                foreach (Symbol symbol in scriptedEntity.ScriptProcess.GlobalScope.Symbols)
                {
                    if (!(symbol is VariableSymbol))
                    {
                        continue;
                    }

                    string name       = ((VariableSymbol)symbol).Identifier;
                    string editMethod = "";
                    foreach (Symbol subSymbol in symbol.Symbols)
                    {
                        if (subSymbol is MetaDataSymbol)
                        {
                            if (((MetaDataSymbol)subSymbol).Identifier.ToLower() == "name")
                            {
                                name = ((MetaDataSymbol)subSymbol).Value;
                            }
                            else if (((MetaDataSymbol)subSymbol).Identifier.ToLower() == "editmethod")
                            {
                                editMethod = ((MetaDataSymbol)subSymbol).Value;
                            }
                        }
                    }


                    if (((VariableSymbol)symbol).IsProperty == true && name.ToLower() == item.Name.ToLower())
                    {
                        VariableSymbol variableSymbol = ((VariableSymbol)symbol);
                        if (variableSymbol.DataType.IsArray == false)
                        {
                            switch (variableSymbol.DataType.DataType)
                            {
                            case DataType.Bool: scriptedEntity.ScriptProcess[0].SetGlobalVariable(variableSymbol.Identifier, (bool)value); break;

                            case DataType.Byte: scriptedEntity.ScriptProcess[0].SetGlobalVariable(variableSymbol.Identifier, (byte)value); break;

                            case DataType.Double: scriptedEntity.ScriptProcess[0].SetGlobalVariable(variableSymbol.Identifier, (double)value); break;

                            case DataType.Float: scriptedEntity.ScriptProcess[0].SetGlobalVariable(variableSymbol.Identifier, (float)value); break;

                            case DataType.Int: scriptedEntity.ScriptProcess[0].SetGlobalVariable(variableSymbol.Identifier, (int)value); break;

                            case DataType.Long: scriptedEntity.ScriptProcess[0].SetGlobalVariable(variableSymbol.Identifier, (long)value); break;

                            case DataType.Short: scriptedEntity.ScriptProcess[0].SetGlobalVariable(variableSymbol.Identifier, (short)value); break;

                            case DataType.String: scriptedEntity.ScriptProcess[0].SetGlobalVariable(variableSymbol.Identifier, (string)value); break;

                            case DataType.Object:
                                if (editMethod.ToLower() == "image")
                                {
                                    scriptedEntity.ScriptProcess[0].SetGlobalVariable(variableSymbol.Identifier, value == null ? (RuntimeObject)null : new Engine.ScriptingFunctions.ImageScriptObject(value as Graphics.Image)); break;
                                }
                                else if (editMethod.ToLower() == "sound")
                                {
                                    scriptedEntity.ScriptProcess[0].SetGlobalVariable(variableSymbol.Identifier, value == null ? (RuntimeObject)null : new Engine.ScriptingFunctions.SoundScriptObject(value as Audio.Sound)); break;
                                }
                                break;

                            default: continue;
                            }
                        }
                        else
                        {
                            object[] array      = (object[])value;
                            int      arrayIndex = scriptedEntity.ScriptProcess[0].AllocateArray(variableSymbol.DataType.DataType, array.Length);
                            for (int i = 0; i < array.Length; i++)
                            {
                                switch (variableSymbol.DataType.DataType)
                                {
                                case DataType.Bool: scriptedEntity.ScriptProcess[0].SetArrayElement(arrayIndex, i, (bool)array[i]); break;

                                case DataType.Byte: scriptedEntity.ScriptProcess[0].SetArrayElement(arrayIndex, i, (byte)array[i]); break;

                                case DataType.Double: scriptedEntity.ScriptProcess[0].SetArrayElement(arrayIndex, i, (double)array[i]); break;

                                case DataType.Float: scriptedEntity.ScriptProcess[0].SetArrayElement(arrayIndex, i, (float)array[i]); break;

                                case DataType.Int: scriptedEntity.ScriptProcess[0].SetArrayElement(arrayIndex, i, (int)array[i]); break;

                                case DataType.Long: scriptedEntity.ScriptProcess[0].SetArrayElement(arrayIndex, i, (long)array[i]); break;

                                case DataType.Short: scriptedEntity.ScriptProcess[0].SetArrayElement(arrayIndex, i, (short)array[i]); break;

                                case DataType.String: scriptedEntity.ScriptProcess[0].SetArrayElement(arrayIndex, i, (string)array[i]); break;

                                // Needs fixing - What if we have other items apart from images stored in this variable?
                                case DataType.Object:
                                    if (editMethod.ToLower() == "image")
                                    {
                                        scriptedEntity.ScriptProcess[0].SetArrayElement(arrayIndex, i, array[i] == null ? (RuntimeObject)null : new Engine.ScriptingFunctions.ImageScriptObject(array[i] as Graphics.Image)); break;
                                    }
                                    else if (editMethod.ToLower() == "image")
                                    {
                                        scriptedEntity.ScriptProcess[0].SetArrayElement(arrayIndex, i, array[i] == null ? (RuntimeObject)null : new Engine.ScriptingFunctions.SoundScriptObject(array[i] as Audio.Sound)); break;
                                    }
                                    break;

                                default: continue;
                                }
                            }
                        }
                        scriptedEntity.OnPropertyChange(symbol.Identifier);
                    }
                }
            }

            else if (_entity is EmitterNode)
            {
                // Unneccessary, the emitter editor deals with this.
            }

            else if (_entity is TilemapSegmentNode)
            {
                TilemapSegmentNode segmentNode = _entity as TilemapSegmentNode;

                switch (item.Name.ToLower())
                {
                case "grid visible": segmentNode.IsGridVisible = (bool)value; break;

                case "tile size":    segmentNode.TileWidth = ((Size)value).Width; segmentNode.TileHeight = ((Size)value).Height; break;
                }
            }

            else if (_entity is PathMarkerNode)
            {
                PathMarkerNode markerNode = _entity as PathMarkerNode;

                switch (item.Name.ToLower())
                {
                case "speed": markerNode.Speed = (StartFinishF)value; break;

                case "delay": markerNode.Delay = (int)value; break;

                case "next marker name":
                    markerNode.NextNodeName = (string)value;
                    ArrayList nodes = Engine.Engine.GlobalInstance.Map.SceneGraph.GetNodesByName(markerNode.NextNodeName);
                    markerNode.NextNode = (nodes.Count != 0) ? nodes[0] as PathMarkerNode : null;
                    break;
                }
            }

            // Call property changed delegate.
            _propertyChangedDelegate(this, item.Name, value);
        }
Esempio n. 18
0
 public void CombineColor(ScriptThread thread)
 {
     thread.SetReturnValue(ColorMethods.CombineColor(ColorFormats.A8R8G8B8, thread.GetIntegerParameter(1), thread.GetIntegerParameter(2), thread.GetIntegerParameter(3), thread.GetIntegerParameter(0)));
 }