예제 #1
0
 public void TestParameterSerialization()
 {
     var decoder = new PackedDecoder();
     var p = new List<Parameter>();
     decoder.WriteParameters(p);
     Assert.AreNotEqual(0, p.Count);
     var c1 = p.Count;
     decoder.WriteParameters(p);
     Assert.AreEqual(c1, p.Count);
     decoder.ColorBPP = 4;
     var cf = new ColorFormat(12, 5, 6, 4, 1, 3, 18, 1);
     decoder.ColorFormat = cf;
     ((IPictureDecoderController)decoder).Width = 13;
     ((IPictureDecoderController)decoder).Height = 21;
     decoder.WriteParameters(p);
     Assert.AreEqual(1.ToString(), p.First(z => z.Name == "ppbyp").Value);
     Assert.AreEqual(cf.ToString(), p.First(z => z.Name == "ColorFormat").Value);
     Assert.AreEqual("13", p.First(z => z.Name == "Width").Value);
     Assert.AreEqual("21", p.First(z => z.Name == "Height").Value);
     var d2 = new PackedDecoder();
     d2.ReadParameters(p);
     Assert.AreEqual(4, d2.ColorBPP);
     Assert.AreEqual(cf, d2.ColorFormat);
     Assert.AreEqual(13, ((IPictureDecoderController)decoder).Width);
     Assert.AreEqual(21, ((IPictureDecoderController)decoder).Height);
 }
예제 #2
0
 public GraphicsMode SelectGraphicsMode(ColorFormat color, int depth, int stencil, int samples, ColorFormat accum, int buffers, bool stereo)
 {
     GraphicsMode gfx = new GraphicsMode((IntPtr)1, color, depth, stencil, samples,
                                          accum, buffers, stereo);
     System.Diagnostics.Debug.Print("Created dummy graphics mode.");
     return gfx;
 }
예제 #3
0
파일: RawData.cs 프로젝트: ShadeDBZ/tinke
 public RawImage(byte[] tiles, TileForm form, ColorFormat format, int width, int height,
     bool editable, string fileName = "")
     : base()
 {
     this.fileName = fileName;
     Set_Tiles(tiles, width, height, format, form, editable);
 }
예제 #4
0
 public LessEngine(Parser.Parser parser, ILogger logger, bool compress, ColorFormat colorFormat)
 {
     Parser = parser;
     Logger = logger;
     Compress = compress;
         ColorFormat = colorFormat;
 }
예제 #5
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="device"></param>
		/// <param name="size"></param>
		/// <param name="count"></param>
		/// <param name="format"></param>
		/// <param name="mips"></param>
		public TextureCubeArray ( GraphicsDevice device, int size, int count, ColorFormat format, bool mips ) : base(device)
		{
			if (count>2048/6) {
				throw new GraphicsException("Too much elements in texture array");
			}

			this.Width		=	size;
			this.Depth		=	1;
			this.Height		=	size;
			this.MipCount	=	mips ? ShaderResource.CalculateMipLevels(Width,Height) : 1;

			var texDesc = new Texture2DDescription();

			texDesc.ArraySize		=	6 * count;
			texDesc.BindFlags		=	BindFlags.ShaderResource;
			texDesc.CpuAccessFlags	=	CpuAccessFlags.None;
			texDesc.Format			=	MakeTypeless( Converter.Convert( format ) );
			texDesc.Height			=	Height;
			texDesc.MipLevels		=	0;
			texDesc.OptionFlags		=	ResourceOptionFlags.TextureCube;
			texDesc.SampleDescription.Count	=	1;
			texDesc.SampleDescription.Quality	=	0;
			texDesc.Usage			=	ResourceUsage.Default;
			texDesc.Width			=	Width;


			texCubeArray	=	new D3D.Texture2D( device.Device, texDesc );
			SRV				=	new ShaderResourceView( device.Device, texCubeArray );
		}
예제 #6
0
파일: VideoTrack.cs 프로젝트: eriser/nsynth
        /// <summary>
        /// 
        /// </summary>
        /// <param name="bitmap"></param>
        public VideoTrack(IBitmap bitmap)
        {
            Contract.Requires(bitmap != null);

            this.dimensions = new Size(bitmap.Width, bitmap.Height);
            this.format = bitmap.Format;
        }
예제 #7
0
		/// <summary>
		/// Creates texture
		/// </summary>
		/// <param name="device"></param>
		public VolumeRWTexture ( GraphicsDevice device, int width, int height, int depth, ColorFormat format, bool mips ) : base( device )
		{
			this.Width		=	width;
			this.Height		=	height;
			this.Depth		=	depth;
			this.format		=	format;
			this.mipCount	=	mips ? ShaderResource.CalculateMipLevels(Width,Height,Depth) : 1;

			var texDesc = new Texture3DDescription();
			texDesc.BindFlags		=	BindFlags.ShaderResource | BindFlags.UnorderedAccess;
			texDesc.CpuAccessFlags	=	CpuAccessFlags.None;
			texDesc.Format			=	Converter.Convert( format );
			texDesc.Height			=	Height;
			texDesc.MipLevels		=	mipCount;
			texDesc.OptionFlags		=	ResourceOptionFlags.None;
			texDesc.Usage			=	ResourceUsage.Default;
			texDesc.Width			=	Width;
			texDesc.Depth			=	Depth;

			var uavDesc = new UnorderedAccessViewDescription();
			uavDesc.Format		=	Converter.Convert( format );
			uavDesc.Dimension	=	UnorderedAccessViewDimension.Texture3D;
			uavDesc.Texture3D.FirstWSlice	=	0;
			uavDesc.Texture3D.MipSlice		=	0;
			uavDesc.Texture3D.WSize			=	depth;

			tex3D	=	new D3D.Texture3D( device.Device, texDesc );
			SRV		=	new D3D.ShaderResourceView( device.Device, tex3D );
			uav		=	new UnorderedAccessView( device.Device, tex3D, uavDesc );
		}
예제 #8
0
파일: VideoTrack.cs 프로젝트: eriser/nsynth
        /// <summary>
        /// Initializes a new instance of the <see cref="VideoTrack"/> class.
        /// </summary>
        /// <param name="width">The width, in pixels, of video frames in the new <see cref="VideoTrack"/>.</param>
        /// <param name="height">The height, in pixels, of video frames in the new <see cref="VideoTrack"/>.</param>
        public VideoTrack(int width, int height)
        {
            Contract.Requires(width >= 0);
            Contract.Requires(height >= 0);

            this.dimensions = new Size(width, height);
            this.format = ColorFormat.Default;
        }
예제 #9
0
파일: Image.cs 프로젝트: pleonex/ninoimager
 public Image()
 {
     this.data     = null;
     this.original = null;
     this.format   = ColorFormat.Unknown;
     this.pixelEnc = PixelEncoding.Unknown;
     this.tileSize = new Size(8, 8);
     this.width    = 0;
     this.height   = 0;
 }
예제 #10
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="rtv"></param>
 internal RenderTargetSurface( RenderTargetView rtv, UnorderedAccessView uav, Resource resource, int subresource, ColorFormat format, int width, int height, int sampleCount )
 {
     Width			=	width;
     Height			=	height;
     Format			=	format;
     SampleCount		=	sampleCount;
     RTV				=	rtv;
     UAV				=	uav;
     Resource		=	resource;
     Subresource		=	subresource;
 }
예제 #11
0
        /// <summary>
        /// Return a Random color.
        /// </summary>
        /// <param name="format"></param>
        /// <param name="casing"></param>
        /// <param name="grayscale"></param>
        /// <example>
        ///   <code language="cs">
        ///     // this will return a string. (ex. "rgba(128, 255, 128, 0.5)")
        ///     var color = _random.Color(ColorFormat.Rgba);
        ///   </code>
        /// </example>
        /// <returns></returns>
        public string Color(ColorFormat format, CasingType casing = CasingType.Lower, bool grayscale = true)
        {
            var colorValue = "";
              switch (format)
              {
            case ColorFormat.Hex:
              colorValue = string.Format("#{0}", grayscale ? Gray(Hash(2)) : Hash(6));
              break;
            case ColorFormat.ShortHex:
              colorValue = string.Format("#{0}", grayscale ? Gray(Hash(1)) : Hash(3));
              break;
            case ColorFormat.Rgb:
              if (grayscale)
              {
            var rgb = Gray(Natural(max: 255).ToString(), ",");
            colorValue = string.Format("rgb({0})", rgb);
              }
              else
              {
            var r = Natural(255);
            var g = Natural(255);
            var b = Natural(255);
            colorValue = string.Format("rgb({0}, {1}, {2})", r, g, b);
              }
              break;
            case ColorFormat.Rgba:
              if (grayscale)
              {
            var rgb = Gray(Natural(max: 255).ToString(), ",");
            var alpha = Float(0, 1);
            colorValue = string.Format("rgba({0}, {1})", rgb, alpha);
              }
              else
              {
            var r = Natural(255);
            var g = Natural(255);
            var b = Natural(255);
            var alpha = Float(0, 1);
            colorValue = string.Format("rgba({0}, {1}, {2}, {3})", r, g, b, alpha);
              }
              break;
            case ColorFormat.ConstantHex:
              colorValue = string.Format("0x{0}", grayscale ? Gray(Hash(2)) : Hash(6));
              break;
            default:
              colorValue = string.Empty;
              break;
              }

              if (casing == CasingType.Upper)
            colorValue = colorValue.ToUpper();

              return colorValue;
        }
예제 #12
0
파일: RawData.cs 프로젝트: ShadeDBZ/tinke
        public RawImage(String file, int id, TileForm form, ColorFormat format,
            bool editable, int offset, int size, string fileName = "")
            : base()
        {
            this.id = id;
            if (fileName == "")
                this.fileName = Path.GetFileName(file);
            else
                this.fileName = fileName;

            Read(file, form, format, editable, offset, size);
        }
예제 #13
0
 public static Color FromFormat(uint color, ColorFormat format)
 {
     switch(format)
     {
         case ColorFormat.ARGB:
             return new Color((byte)(color >> 24), (byte)(color >> 16), (byte)(color >> 8), (byte)(color));
         case ColorFormat.RGBA:
             return new Color((byte)(color & 0xFF), (byte)((color & 0xFF000000) >> 24), (byte)((color & 0x00FF0000) >> 16), (byte)((color & 0x0000FF00) >> 8));
         default:
             throw new ArgumentException();
     }
 }
예제 #14
0
파일: Image.cs 프로젝트: pleonex/ninoimager
        private Image(Image img, uint[] data, int width, int height)
        {
            this.original = data;
            this.width  = width;
            this.height = height;
            this.format = img.Format;
            this.pixelEnc = img.PixelEncoding;
            this.tileSize = img.TileSize;

            this.data = new uint[data.Length];
            this.pixelEnc.Codec(this.original, this.data, true, this.width, this.height, this.tileSize);
        }
예제 #15
0
파일: ColorHelpers.cs 프로젝트: L1Q/ShareX
 public static string ColorToHex(Color color, ColorFormat format = ColorFormat.RGB)
 {
     switch (format)
     {
         default:
         case ColorFormat.RGB:
             return string.Format("{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);
         case ColorFormat.RGBA:
             return string.Format("{0:X2}{1:X2}{2:X2}{3:X2}", color.R, color.G, color.B, color.A);
         case ColorFormat.ARGB:
             return string.Format("{0:X2}{1:X2}{2:X2}{3:X2}", color.A, color.R, color.G, color.B);
     }
 }
예제 #16
0
 public static int ColorToDecimal(Color color, ColorFormat format = ColorFormat.RGB)
 {
     switch (format)
     {
         default:
         case ColorFormat.RGB:
             return color.R << 16 | color.G << 8 | color.B;
         case ColorFormat.RGBA:
             return color.R << 24 | color.G << 16 | color.B << 8 | color.A;
         case ColorFormat.ARGB:
             return color.A << 24 | color.R << 16 | color.G << 8 | color.B;
     }
 }
        public ColorConverterSmartTagAction(ITrackingSpan span, ParseItem item, ColorModel colorModel, ColorFormat format)
        {
            _span = span;
            _item = item;
            _format = format;
            _colorModel = colorModel;

            if (Icon == null)
            {
                Icon = BitmapFrame.Create(new Uri("pack://application:,,,/WebEssentials2013;component/Resources/palette.png", UriKind.RelativeOrAbsolute));
            }

            SetDisplayText();
        }
예제 #18
0
 public void TestDecode()
 {
     unchecked {
         var cf = new ColorFormat(16, 8, 8, 8, 0, 8, 24, 8);
         var result = cf.Decode((int)0x87654321);
         Assert.AreEqual((int)0x87654321, result);
         Assert.AreEqual((int)0x87, ((result >> 24) & 0xff));
     }
     {
         var cf = new ColorFormat(8, 4, 4, 4, 0, 4, 0, 0);
         var result = cf.Decode(0x0352);
         Assert.AreEqual((uint)0xff335522, (uint)result);
     }
 }
예제 #19
0
        public int AddColor( ref byte[] Bytes, int idx, Color clr, ColorFormat fmt )
        {
            int nc = (int)clr.ToArgb();

            byte a = (byte)((nc&0xFF000000)>>24);
            byte r = (byte)((nc&0x00FF0000)>>16);
            byte g = (byte)((nc&0x0000FF00)>>8);
            byte b = (byte)((nc&0x000000FF));
            switch (fmt)
            {
                case ColorFormat.ARGB4444:
                {
                    byte b1 = (byte)((a&0xF0)|(r>>4));
                    byte b2 = (byte)((g&0xF0)|(b>>4));
                    Bytes[idx] = b2;
                    Bytes[idx + 1] = b1;
                    return 2;
                }
                case ColorFormat.ARGB8888:
                {
                    Bytes[idx] = b;
                    Bytes[idx + 1] = g;
                    Bytes[idx + 2] = r;
                    Bytes[idx + 3] = a;
                    return 4;
                }
                case ColorFormat.RGB565:
                {
                    byte b1 = (byte)((r&0xF8)|((g&0xFC)>>5));
                    byte b2 = (byte)(((g<<3)&0xE0)|((b&0xF8)>>3));
                    Bytes[idx] = b2;
                    Bytes[idx + 1] = b1;
                    return 2;
                }
                case ColorFormat.RGB888:
                {
                    Bytes[idx] = b;
                    Bytes[idx + 1] = g;
                    Bytes[idx + 2] = r;
                    return 3;
                }
                case ColorFormat.A8:
                {
                    Bytes[idx] = a;
                    return 1;
                }
            }
            return 0;
        }
예제 #20
0
        public Sprite( string name, string path, Bitmap bmp, ColorFormat fmt, bool bFiltered )
        {
            Name          = name;
            FilePath      = path;
            Width         = bmp.Width;
            Height        = bmp.Height;
            ClrFormat     = fmt;
            Filtered      = bFiltered;
            PivotX        = 0;
            PivotY        = 0;
            ShiftX        = 0;
            ShiftY        = 0;
            Difference    = false;

            CreatePartition( bmp );
        }
        public ColorConverterSmartTagAction(ITrackingSpan span, ColorModel colorModel, ColorFormat format)
        {
            _span = span;

            if (format == ColorFormat.RgbHex6)
                format = ColorFormat.RgbHex3;

            _format = format;
            _colorModel = colorModel.Clone();
            _colorModel.Format = format;

            if (Icon == null)
            {
                Icon = BitmapFrame.Create(new Uri("pack://application:,,,/WebEssentials2015;component/Resources/Images/palette.png", UriKind.RelativeOrAbsolute));
            }

            _displayText = "Convert to " + GetColorString(_format, _colorModel);
        }
        private static string GetColorString(ColorFormat format, ColorModel model)
        {
            switch (format)
            {
                case ColorFormat.Name:
                    return GetNamedColor(model.Color);

                case ColorFormat.Hsl:
                    return FormatHslColor(model); //ColorFormatter.FormatColorAs(_colorModel, ColorFormat.Hsl);

                case ColorFormat.Rgb:
                case ColorFormat.RgbHex3:
                case ColorFormat.RgbHex6:
                    return ColorFormatter.FormatColor(model, format);

                default:
                    throw new InvalidEnumArgumentException("format", (int)format, typeof(ColorFormat));
            }
        }
예제 #23
0
 public void TestSerialize()
 {
     {
         var cf = new ColorFormat(16, 8, 8, 8, 0, 8, 24, 8);
         Assert.AreEqual("S24:8,16:8,8:8,0:8", cf.ToString());
     }
     {
         var cf = new ColorFormat(0, 4, 4, 4, 8, 4, 0, 0);
         Assert.AreEqual("S0:0,0:4,4:4,8:4", cf.ToString());
     }
     {
         var cf = new ColorFormat(16, 8, 8, 8, 0, 8, 24, 8);
         Assert.AreEqual("S24:8,16:8,8:8,0:8", cf.ToString());
     }
     {
         var cf = new ColorFormat(11, 5, 5, 6, 0, 5, 0, 0);
         Assert.AreEqual("S0:0,11:5,5:6,0:5", cf.ToString());
     }
     {
         var cf = new ColorFormat(10, 5, 5, 5, 0, 5, 15, 1);
         Assert.AreEqual("S15:1,10:5,5:5,0:5", cf.ToString());
     }
 }
예제 #24
0
        public static BitmapSource Dither(BitmapSource source, ColorFormat format)
        {
            if(source.Format == PixelFormats.Indexed8)
            {
                var rgb = new FormatConvertedBitmap();
                rgb.BeginInit();
                rgb.Source = source;
                rgb.DestinationFormat = PixelFormats.Rgb24;
                rgb.EndInit();
                source = rgb;
            }

            var dest = new FormatConvertedBitmap();
            dest.BeginInit();

            dest.Source = source;
            var numColors = (int)Math.Pow(2, (int) format);
            var colors = ColorList.Take(numColors).ToList();
            dest.DestinationPalette = new BitmapPalette(colors);
            dest.DestinationFormat = PixelFormats.Indexed8;
            dest.EndInit();

            return dest;
        }
예제 #25
0
        public static Color HexToColor(string hex, ColorFormat format = ColorFormat.RGB)
        {
            if (string.IsNullOrEmpty(hex))
            {
                return Color.Empty;
            }

            if (hex[0] == '#')
            {
                hex = hex.Remove(0, 1);
            }

            if (((format == ColorFormat.RGBA || format == ColorFormat.ARGB) && hex.Length != 8) ||
                (format == ColorFormat.RGB && hex.Length != 6))
            {
                return Color.Empty;
            }

            int r, g, b, a;

            switch (format)
            {
                default:
                case ColorFormat.RGB:
                    r = HexToDecimal(hex.Substring(0, 2));
                    g = HexToDecimal(hex.Substring(2, 2));
                    b = HexToDecimal(hex.Substring(4, 2));
                    a = 255;
                    break;
                case ColorFormat.RGBA:
                    r = HexToDecimal(hex.Substring(0, 2));
                    g = HexToDecimal(hex.Substring(2, 2));
                    b = HexToDecimal(hex.Substring(4, 2));
                    a = HexToDecimal(hex.Substring(6, 2));
                    break;
                case ColorFormat.ARGB:
                    a = HexToDecimal(hex.Substring(0, 2));
                    r = HexToDecimal(hex.Substring(2, 2));
                    g = HexToDecimal(hex.Substring(4, 2));
                    b = HexToDecimal(hex.Substring(6, 2));
                    break;
            }

            return Color.FromArgb(a, r, g, b);
        }
예제 #26
0
 public void TestStandardConformity()
 {
     var color = Color.FromArgb(0x12, 0x34, 0x56, 0x78);//ARGB
     var cf = new ColorFormat(16, 8, 8, 8, 0, 8, 24, 8);
     Assert.AreEqual(color.ToArgb(), cf.Decode(color.ToArgb()));
     Assert.AreEqual(0x34, (color.ToArgb() >> 16) & 0xff);
     Assert.AreEqual(0x12, (color.ToArgb() >> 24) & 0xff);
 }
예제 #27
0
        public void Read12(string fileIn)
        {
            BinaryReader br = new BinaryReader(File.OpenRead(fileIn));

            // Read header
            ushort bpp         = br.ReadUInt16();
            int    width       = br.ReadByte() * 8;
            int    height      = br.ReadByte() * 8;
            ushort map_offset  = br.ReadUInt16();
            ushort map_size    = br.ReadUInt16();
            ushort data_offset = br.ReadUInt16();
            ushort data_size   = br.ReadUInt16();
            ushort pal_offset  = br.ReadUInt16();
            ushort pal_size    = br.ReadUInt16();

            // Read map
            br.BaseStream.Position = map_offset;
            NTFS[] map = new NTFS[map_size / 2];
            for (int i = 0; i < map.Length; i++)
            {
                map[i] = Actions.MapInfo(br.ReadUInt16());
            }
            Set_Map(map, false, width, height);

            // Read image data
            ColorFormat format = ColorFormat.colors256;

            if (bpp == 0x12 || bpp == 0x1A)
            {
                format = ColorFormat.colors16;
            }
            else if (bpp == 0x10 || bpp == 0x18)
            {
                format = ColorFormat.colors256;
            }

            br.BaseStream.Position = data_offset;
            byte[]     data = br.ReadBytes(data_size);
            Encryption enc  = new Encryption(data);

            data = enc.Decrypt();

            img = new RawImage(data, TileForm.Horizontal, format, width, height, false);

            // Read palette
            if ((bpp == 0x18 || bpp == 0x1A) && pluginHost.Get_Palette().Loaded)
            {
                pal = pluginHost.Get_Palette();
            }
            else
            {
                br.BaseStream.Position = pal_offset;
                Color[] colors = Actions.BGR555ToColor(br.ReadBytes(pal_size));
                pal = new RawPalette(new Color[][] { colors }, false, ColorFormat.colors16);
            }

            br.Close();
            ismap = true;

            Console.WriteLine("Image with bpp: {0}", bpp.ToString("x"));
        }
예제 #28
0
        // Called when the widget needs to be (fully or partially) redrawn.
        protected override bool OnExposeEvent(Gdk.EventExpose eventExpose)
        {
            if (!initialized)
            {
                initialized = true;

                // If this looks uninitialized...  initialize.
                if (ColorBPP == 0)
                {
                    ColorBPP = 32;

                    if (DepthBPP == 0)
                    {
                        DepthBPP = 16;
                    }
                }

                ColorFormat colorBufferColorFormat = new ColorFormat(ColorBPP);

                ColorFormat accumulationColorFormat = new ColorFormat(AccumulatorBPP);

                int buffers = 2;
                if (SingleBuffer)
                {
                    buffers--;
                }

                GraphicsMode graphicsMode = new GraphicsMode(colorBufferColorFormat, DepthBPP, StencilBPP, Samples, accumulationColorFormat, buffers, Stereo);

                // IWindowInfo
                if (Configuration.RunningOnWindows)
                {
                    IntPtr windowHandle = gdk_win32_drawable_get_handle(GdkWindow.Handle);
                    windowInfo = OpenTK.Platform.Utilities.CreateWindowsWindowInfo(windowHandle);
                }
                else if (Configuration.RunningOnMacOS)
                {
                    IntPtr windowHandle = gdk_quartz_window_get_nswindow(GdkWindow.Handle);
                    IntPtr contentView  = gdk_quartz_window_get_nsview(GdkWindow.Handle);

                    // Problem: gdk_window_ensure_native() crashes when used more than once.
                    // For now, just create a NSView in place and use that instead.
                    // Needs some care updating when resizing, hiding, etc, but seems to work.
                    // (I'd guess this is pretty much what gdk_window_ensure_native() does internally.)

                    var customView = Class.AllocateClass("CustomNSView" + uniqueId++, "NSView");
                    //Class.RegisterMethod(windowClass, new WindowKeyDownDelegate(WindowKeyDown), "keyDown:", "v@:@");
                    //Class.RegisterMethod(customView, new OnHitTestDelegate(OnHitTest), "hitTest:", "@@:{NSPoint=ff}");
                    Class.RegisterMethod(customView, new OnMouseDownDelegate(OnMouseDown), "mouseDown:", "v@:@");
                    Class.RegisterMethod(customView, new OnMouseDraggedDelegate(OnMouseDragged), "mouseDragged:", "v@:@");
                    Class.RegisterMethod(customView, new OnMouseUpDelegate(OnMouseUp), "mouseUp:", "v@:@");

                    Class.RegisterClass(customView);

                    nsView = SendIntPtr(SendIntPtr(customView, sel_registerName("alloc")), sel_registerName("initWithFrame:"), new RectangleF(0, 0, 100, 100));
                    SendVoid(contentView, sel_registerName("addSubview:"), nsView);


//					bool native = gdk_window_ensure_native(GdkWindow.Handle);
//					if (!native)
//					{
//						throw new PlatformNotSupportedException("Could not create native view.");
//					}
//
//					nsView = gdk_quartz_window_get_nsview(GdkWindow.Handle);

                    windowInfo = OpenTK.Platform.Utilities.CreateMacOSWindowInfo(windowHandle, nsView);
                    UpdateNSView();
                }
                else if (Configuration.RunningOnX11)
                {
                    IntPtr display      = gdk_x11_display_get_xdisplay(Display.Handle);
                    int    screen       = Screen.Number;
                    IntPtr windowHandle = gdk_x11_drawable_get_xid(GdkWindow.Handle);
                    IntPtr rootWindow   = gdk_x11_drawable_get_xid(RootWindow.Handle);

                    IntPtr visualInfo;
                    if (graphicsMode.Index.HasValue)
                    {
                        XVisualInfo info = new XVisualInfo();
                        info.VisualID = graphicsMode.Index.Value;
                        int dummy;
                        visualInfo = XGetVisualInfo(display, XVisualInfoMask.ID, ref info, out dummy);
                    }
                    else
                    {
                        visualInfo = GetVisualInfo(display);
                    }

                    windowInfo = OpenTK.Platform.Utilities.CreateX11WindowInfo(display, screen, windowHandle, rootWindow, visualInfo);
                    XFree(visualInfo);
                }
                else
                {
                    throw new PlatformNotSupportedException();
                }

                // GraphicsContext
                graphicsContext = new GraphicsContext(graphicsMode, windowInfo, GlVersionMajor, GlVersionMinor, graphicsContextFlags);
                graphicsContext.MakeCurrent(windowInfo);

                if (GraphicsContext.ShareContexts)
                {
                    Interlocked.Increment(ref graphicsContextCount);

                    if (!sharedContextInitialized)
                    {
                        sharedContextInitialized = true;
                        ((IGraphicsContextInternal)graphicsContext).LoadAll();
                        OnGraphicsContextInitialized();
                    }
                }
                else
                {
                    ((IGraphicsContextInternal)graphicsContext).LoadAll();
                    OnGraphicsContextInitialized();
                }

                OnInitialized();
            }
            else
            {
                try                 // Hack: Fix crash when returning from sleep mode on windows, using nvidia drivers. See: http://www.opentk.com/node/2634
                {
                    graphicsContext.MakeCurrent(windowInfo);
                }
                catch
                {
                }
            }

            bool result = base.OnExposeEvent(eventExpose);

            OnRenderFrame();
            eventExpose.Window.Display.Sync();             // Add Sync call to fix resize rendering problem (Jay L. T. Cornwall) - How does this affect VSync?
            graphicsContext.SwapBuffers();
            return(result);
        }
예제 #29
0
 public static string ColorToHex(Color color, ColorFormat format = ColorFormat.RGB)
 {
     return(ColorToHex(color.R, color.G, color.B, color.A, format));
 }
예제 #30
0
 public static void setImage(byte[] buffer, uint width, uint height, ColorFormat colorFormat, bool originIsUpperLeft)
 {
     // Cannot use default parameters in Unity, forces .NET 3.5 syntax
     setImage(buffer, width, height, colorFormat, originIsUpperLeft, -1);
 }
예제 #31
0
파일: VideoTrack.cs 프로젝트: eriser/nsynth
 /// <summary>
 /// Initializes a new instance of the <see cref="VideoTrack"/> class.
 /// </summary>
 public VideoTrack()
 {
     this.dimensions = new Size(1920, 1080);
     this.format = ColorFormat.Default;
 }
예제 #32
0
        /// <summary>
        /// Gets a random aesthetically pleasing color near the base RGB. See [here](http://stackoverflow.com/questions/43044/algorithm-to-randomly-generate-an-aesthetically-pleasing-color-palette).
        /// </summary>
        /// <param name="baseRed">Red base color</param>
        /// <param name="baseGreen">Green base color</param>
        /// <param name="baseBlue">Blue base color</param>
        /// <param name="grayscale">Output a gray scale color</param>
        /// <param name="format">The color format</param>
        /// <returns>A random color.</returns>
        public string Color(byte baseRed = 0, byte baseGreen = 0, byte baseBlue = 0, bool grayscale = false, ColorFormat format = ColorFormat.Hex)
        {
            var red   = Math.Floor((Random.Number(256) + (double)baseRed) / 2);
            var green = Math.Floor((Random.Number(256) + (double)baseGreen) / 2);
            var blue  = Math.Floor((Random.Number(256) + (double)baseBlue) / 2);

            if (grayscale)
            {
                green = red;
                blue  = red;
            }

            var r = (byte)red;
            var g = (byte)green;
            var b = (byte)blue;

            if (format == ColorFormat.Hex)
            {
                return($"#{r:x02}{g:x02}{b:x02}");
            }

            if (format == ColorFormat.Delimited)
            {
                return(DelimitedRgb());
            }

            return($"rgb({DelimitedRgb()})");

            string DelimitedRgb()
            {
                return($"{r},{g},{b}");
            }
        }
예제 #33
0
        public static Color GetTexel(byte[] line, int texelX, ColorFormat format, BitSize bitSize)
        {
            ulong texel;

            switch (bitSize)
            {
            case BitSize._4:
                texel = Get4BitTexel(line, texelX);
                break;

            case BitSize._8:
                texel = line[texelX];
                break;

            case BitSize._16:
                texel = line.ReadUInt16(texelX * 2);
                break;

            case BitSize._32:
                texel = line.ReadUInt32(texelX * 4);
                break;

            default:
                throw new Exception();
            }

            if (format == ColorFormat.I)
            {
                byte i;
                if (bitSize == BitSize._4)
                {
                    i = (byte)(texel | (texel << 4));
                }
                else if (bitSize == BitSize._8)
                {
                    i = (byte)texel;
                }
                else
                {
                    throw new Exception();
                }
                return(Color.FromArgb(i, i, i, i));
            }
            else if (format == ColorFormat.IA)
            {
                byte i;
                byte alpha;
                if (bitSize == BitSize._4)
                {
                    ulong i3 = texel >> 1;
                    i     = (byte)(((i3 << 5) | (i3 << 2) | (i3 >> 1)) & 0xFF);
                    alpha = (byte)(0xFF * (texel & 1));
                }
                else if (bitSize == BitSize._8)
                {
                    ulong i4 = texel >> 4;
                    ulong a4 = texel & 0x0F;
                    i     = (byte)(i4 | (i4 << 4));
                    alpha = (byte)(a4 | (a4 << 4));
                }
                else if (bitSize == BitSize._16)
                {
                    i     = (byte)(texel >> 8);
                    alpha = (byte)(texel & 0xFF);
                }
                else
                {
                    throw new Exception();
                }
                return(Color.FromArgb(alpha, i, i, i));
            }
            else if (format == ColorFormat.RGBA)
            {
                if (bitSize == BitSize._16)
                {
                    return(RGBA16ToColor((ushort)texel));
                }
                else if (bitSize == BitSize._32)
                {
                    int argb = (int)((texel >> 8) | ((texel & 0xFF) << 24));
                    return(Color.FromArgb(argb));
                }
                else
                {
                    throw new Exception();
                }
            }
            else
            {
                throw new Exception();
            }
        }
예제 #34
0
 public DescriptionAttribute(string description, ColorFormat color)
     : this(description)
 {
     this.Color = color;
 }
예제 #35
0
        protected override void CreateFrameBuffer()
        {
            int         requestedDepth       = 0;
            int         requestedStencil     = 0;
            ColorFormat requestedColorFormat = 32;

            switch (RequestedBackBufferFormat)
            {
            case PixelFormat.R8G8B8A8_UNorm:
            case PixelFormat.B8G8R8A8_UNorm:
                requestedColorFormat = 32;
                break;

            case PixelFormat.B8G8R8X8_UNorm:
                requestedColorFormat = 24;
                break;

            case PixelFormat.B5G6R5_UNorm:
                requestedColorFormat = new ColorFormat(5, 6, 5, 0);
                break;

            case PixelFormat.B5G5R5A1_UNorm:
                requestedColorFormat = new ColorFormat(5, 5, 5, 1);
                break;

            default:
                throw new NotSupportedException("RequestedBackBufferFormat");
            }

            switch (RequestedDepthStencilFormat)
            {
            case PixelFormat.D16_UNorm:
                requestedDepth = 16;
                break;

            case PixelFormat.D24_UNorm_S8_UInt:
                requestedDepth   = 24;
                requestedStencil = 8;
                break;

            case PixelFormat.D32_Float:
                requestedDepth = 32;
                break;

            case PixelFormat.D32_Float_S8X24_UInt:
                requestedDepth   = 32;
                requestedStencil = 8;
                break;

            default:
                throw new NotSupportedException("RequestedDepthStencilFormat");
            }

            // Some devices only allow D16_S8, let's try it as well
            // D24 and D32 are supported on OpenGL ES 3 devices
            var requestedDepthFallback = requestedDepth > 16 ? 16 : requestedDepth;

            foreach (var version in OpenGLUtils.GetGLVersions(RequestedGraphicsProfile))
            {
                if (TryCreateFrameBuffer(MajorVersionToGLVersion(version), requestedColorFormat, requestedDepth, requestedStencil) ||
                    TryCreateFrameBuffer(MajorVersionToGLVersion(version), requestedColorFormat, requestedDepthFallback, requestedStencil))
                {
                    return;
                }
            }

            throw new Exception("Unable to create a graphics context on the device. Maybe you should lower the preferred GraphicsProfile.");
        }
예제 #36
0
        public Format Read2(sFile file)
        {
            string ext = "";

            if (file.size >= 4)
            {
                using (BinaryReader br = new BinaryReader(File.OpenRead(file.path)))
                {
                    ext = new String(Encoding.ASCII.GetChars(br.ReadBytes(4)));
                    br.Close();
                }
            }

            // Palette
            if (file.name.ToUpper().EndsWith(".NTFP") || file.name.ToUpper().EndsWith(".PLT"))
            {
                RawPalette palette = new RawPalette(file.path, file.id, true, 0, -1, file.name);
                pluginHost.Set_Palette(palette);
                return(Format.Palette);
            }
            else if (ext == "RLCN")
            {
                PaletteBase palette = new NCLR(file.path, file.id, file.name);
                pluginHost.Set_Palette(palette);
                return(Format.Palette);
            }
            else if (ext == "NCCL")
            {
                NCCL palette = new NCCL(file.path, file.id, file.name);
                pluginHost.Set_Palette(palette);
                return(Format.Palette);
            }
            else if (file.name.ToUpper().EndsWith(".NBFP"))
            {
                RawPalette palette = new RawPalette(file.path, file.id, true, 0, -1, file.name);
                pluginHost.Set_Palette(palette);
                return(Format.Palette);
            }
            else if (file.name.ToUpper().EndsWith(".NCL.L") && ext[0] != '\x10')
            {
                RawPalette palette = new RawPalette(file.path, file.id, true, 0, -1, file.name);
                pluginHost.Set_Palette(palette);
                return(Format.Palette);
            }


            // Tile
            ColorFormat depth = ColorFormat.colors256;

            if (pluginHost.Get_Palette().Loaded)
            {
                depth = pluginHost.Get_Palette().Depth;
            }

            if (file.name.ToUpper().EndsWith(".NTFT"))
            {
                RawImage image = new RawImage(file.path, file.id, TileForm.Lineal, depth, true, 0, -1, file.name);
                pluginHost.Set_Image(image);
                return(Format.Tile);
            }
            else if (ext == "RGCN" || ext == "RBCN")
            {
                NCGR ncgr = new NCGR(file.path, file.id, file.name);
                pluginHost.Set_Image(ncgr);
                return(Format.Tile);
            }
            else if (ext == "NCCG")
            {
                NCCG image = new NCCG(file.path, file.id, file.name);
                pluginHost.Set_Image(image);
                return(Format.Tile);
            }
            else if (file.name.ToUpper().EndsWith(".NBFC") || file.name.ToUpper().EndsWith(".CHAR"))
            {
                RawImage image = new RawImage(file.path, file.id, TileForm.Horizontal, depth, true, 0, -1, file.name);
                pluginHost.Set_Image(image);
                return(Format.Tile);
            }
            else if (file.name.ToUpper().EndsWith(".NCG.L") && ext[0] != '\x10')
            {
                RawImage image = new RawImage(file.path, file.id, TileForm.Horizontal, depth, true, 0, -1, file.name);
                pluginHost.Set_Image(image);
                return(Format.Tile);
            }

            // Map
            if (file.name.ToUpper().EndsWith(".NBFS"))
            {
                RawMap map = new RawMap(file.path, file.id, 0, -1, true, file.name);
                pluginHost.Set_Map(map);
                return(Format.Map);
            }
            else if (ext == "RCSN")
            {
                NSCR nscr = new NSCR(file.path, file.id, file.name);
                pluginHost.Set_Map(nscr);
                return(Format.Map);
            }
            else if (ext == "NCSC")
            {
                NCSC map = new NCSC(file.path, file.id, file.name);
                pluginHost.Set_Map(map);
                return(Format.Map);
            }
            else if (file.name.ToUpper().EndsWith(".NSC.L") && ext[0] != '\x10')
            {
                RawMap map = new RawMap(file.path, file.id, 0, -1, true, file.name);
                pluginHost.Set_Map(map);
                return(Format.Map);
            }

            // Sprite
            if (ext == "NCOB")
            {
                NCOB sprite = new NCOB(file.path, file.id, file.name);
                pluginHost.Set_Sprite(sprite);
                pluginHost.Set_Image(sprite.Image);
                return(Format.Cell);
            }
            else if (ext == "RECN")
            {
                NCER ncer = new NCER(file.path, file.id, file.name);
                pluginHost.Set_Sprite(ncer);
                return(Format.Cell);
            }

            // Animation
            if (ext == "RNAN")
            {
                nanr = new NANR(pluginHost, file.path, file.id);
                return(Format.Animation);
            }

            return(Format.Unknown);
        }
예제 #37
0
 public int ToDecimal(ColorFormat format = ColorFormat.RGB)
 {
     return(ColorHelper.ColorToDecimal(ARGB.R, ARGB.G, ARGB.B, ARGB.A, format));
 }
예제 #38
0
 public string ToHex(ColorFormat format = ColorFormat.RGB)
 {
     return(ColorHelper.ColorToHex(ARGB.R, ARGB.G, ARGB.B, ARGB.A, format));
 }
예제 #39
0
        /// <summary>
        /// Initializes the <see cref="GLWidget"/> with its given values and creates a <see cref="GraphicsContext"/>.
        /// </summary>
        private void Initialize()
        {
            _Initialized = true;

            // If this looks uninitialized...  initialize.
            if (ColorBPP == 0)
            {
                ColorBPP = 32;

                if (DepthBPP == 0)
                {
                    DepthBPP = 16;
                }
            }

            ColorFormat colorBufferColorFormat = new ColorFormat(ColorBPP);

            ColorFormat accumulationColorFormat = new ColorFormat(AccumulatorBPP);

            int buffers = 2;

            if (SingleBuffer)
            {
                buffers--;
            }

            GraphicsMode graphicsMode = new GraphicsMode(colorBufferColorFormat, DepthBPP, StencilBPP, Samples, accumulationColorFormat, buffers, Stereo);

            if (Configuration.RunningOnWindows)
            {
                Console.WriteLine("OpenTK running on windows");
            }
            else if (Configuration.RunningOnMacOS)
            {
                Console.WriteLine("OpenTK running on OSX");
            }
            else
            {
                Console.WriteLine("OpenTK running on X11");
            }

#if GTK3
            IntPtr widgetWindowHandle = this.Window.Handle;
#else
            IntPtr widgetWindowHandle = this.GdkWindow.Handle;
#endif

            // IWindowInfo
            if (Configuration.RunningOnWindows)
            {
                _WindowInfo = WinWindowsInfoInitializer.Initialize(widgetWindowHandle);
            }
            else if (Configuration.RunningOnMacOS)
            {
                _WindowInfo = OSXWindowInfoInitializer.Initialize(widgetWindowHandle);
            }
            else
            {
                _WindowInfo = XWindowInfoInitializer.Initialize(graphicsMode, this.Display.Handle, this.Screen.Number, widgetWindowHandle, this.Screen.RootWindow.Handle);
            }

            // GraphicsContext
            _GraphicsContext = new GraphicsContext(graphicsMode, _WindowInfo, GlVersionMajor, GlVersionMinor, GraphicsContextFlags);
            _GraphicsContext.MakeCurrent(_WindowInfo);

            if (GraphicsContext.ShareContexts)
            {
                Interlocked.Increment(ref _GraphicsContextCount);

                if (!_SharedContextInitialized)
                {
                    _SharedContextInitialized = true;
                    ((IGraphicsContextInternal)_GraphicsContext).LoadAll();
                    OnGraphicsContextInitialized();
                }
            }
            else
            {
                ((IGraphicsContextInternal)_GraphicsContext).LoadAll();
                OnGraphicsContextInitialized();
            }

            OnInitialized();
        }
예제 #40
0
        public static Bitmap ConvertToBitmap(byte[] data, ColorFormat format, BitSize bitSize, int width, int height, int bytesPerLine, bool flipVertically, bool deinterleave, ushort[]?palette)
        {
            if (bytesPerLine % 8 != 0)
            {
                throw new Exception();
            }

            byte[][] lines = new byte[height][];

            for (int l = 0; l < height; l++)
            {
                lines[l] = data.Subsection(l * bytesPerLine, bytesPerLine);
            }

            // Deinterleave odd lines
            if (deinterleave)
            {
                for (int l = 1; l < height; l += 2)
                {
                    byte[] line = lines[l];

                    for (int word = 0; word < bytesPerLine / 8; word++)
                    {
                        int  wordPos = word * 8;
                        byte b1      = line[wordPos];
                        byte b2      = line[wordPos + 1];
                        byte b3      = line[wordPos + 2];
                        byte b4      = line[wordPos + 3];
                        byte b5      = line[wordPos + 4];
                        byte b6      = line[wordPos + 5];
                        byte b7      = line[wordPos + 6];
                        byte b8      = line[wordPos + 7];

                        line[wordPos]     = b5;
                        line[wordPos + 1] = b6;
                        line[wordPos + 2] = b7;
                        line[wordPos + 3] = b8;
                        line[wordPos + 4] = b1;
                        line[wordPos + 5] = b2;
                        line[wordPos + 6] = b3;
                        line[wordPos + 7] = b4;
                    }

                    // might not be necessary but w/e
                    lines[l] = line;
                }
            }

            Bitmap bmp = new Bitmap(width, height);

            for (int l = 0; l < height; l++)
            {
                byte[] line = lines[l];
                for (int x = 0; x < width; x++)
                {
                    Color texelColor;
                    if (format == ColorFormat.CI)
                    {
                        if (bitSize != BitSize._4)
                        {
                            throw new Exception();
                        }

                        if (palette == null)
                        {
                            throw new Exception();
                        }

                        int index = Get4BitTexel(line, x);

                        // We know it's always in RGBA16
                        texelColor = RGBA16ToColor(palette[index]);
                    }
                    else
                    {
                        texelColor = GetTexel(line, x, format, bitSize);
                    }

                    bmp.SetPixel(x, flipVertically ? (height - 1) - l : l, texelColor);
                }
            }
            return(bmp);
        }
예제 #41
0
파일: RGBA.cs 프로젝트: yuhongfang/ShareX
 public string ToHex(ColorFormat format = ColorFormat.RGB)
 {
     return ColorHelpers.ColorToHex(this, format);
 }
예제 #42
0
        public ColorConverterSmartTagAction(ITrackingSpan span, ColorModel colorModel, ColorFormat format)
        {
            _span = span;

            if (format == ColorFormat.RgbHex6)
            {
                format = ColorFormat.RgbHex3;
            }

            _format            = format;
            _colorModel        = colorModel.Clone();
            _colorModel.Format = format;

            if (Icon == null)
            {
                Icon = BitmapFrame.Create(new Uri("pack://application:,,,/WebEssentials2013;component/Resources/Images/palette.png", UriKind.RelativeOrAbsolute));
            }

            _displayText = "Convert to " + GetColorString(_format, _colorModel);
        }
예제 #43
0
파일: Pmo.cs 프로젝트: PlancakeJB/OpenKh
        public static void ReadMeshData(Stream stream, Pmo pmo, int MeshNumber = 0)
        {
            // Go to mesh position.
            if (MeshNumber == 0)
            {
                stream.Seek(pmo.header.MeshOffset0, SeekOrigin.Begin);
            }
            else
            {
                stream.Seek(pmo.header.MeshOffset1, SeekOrigin.Begin);
            }

            UInt16 VertCnt = 0xFFFF;

            while (VertCnt > 0)
            {
                MeshChunks meshChunk = new MeshChunks();
                meshChunk.MeshNumber = MeshNumber;

                meshChunk.SectionInfo = BinaryMapping.ReadObject <MeshSection>(stream);

                // Exit if Vertex Count is zero.
                if (meshChunk.SectionInfo.VertexCount <= 0)
                {
                    break;
                }

                meshChunk.TextureID = meshChunk.SectionInfo.TextureID;
                VertexFlags flags = GetFlags(meshChunk.SectionInfo);

                bool isColorFlagRisen = flags.UniformDiffuseFlag;

                if (pmo.header.SkeletonOffset != 0)
                {
                    meshChunk.SectionInfo_opt1 = BinaryMapping.ReadObject <MeshSectionOptional1>(stream);
                }
                if (isColorFlagRisen)
                {
                    meshChunk.SectionInfo_opt2 = BinaryMapping.ReadObject <MeshSectionOptional2>(stream);
                }
                if (meshChunk.SectionInfo.TriangleStripCount > 0)
                {
                    meshChunk.TriangleStripValues = new UInt16[meshChunk.SectionInfo.TriangleStripCount];
                    for (int i = 0; i < meshChunk.SectionInfo.TriangleStripCount; i++)
                    {
                        meshChunk.TriangleStripValues[i] = stream.ReadUInt16();
                    }
                }

                // Get Formats.
                CoordinateFormat TexCoordFormat       = flags.TextureCoordinateFormat;
                CoordinateFormat VertexPositionFormat = flags.PositionFormat;
                CoordinateFormat WeightFormat         = flags.WeightFormat;
                ColorFormat      ColorFormat          = flags.ColorFormat;
                UInt32           SkinningWeightsCount = flags.SkinningWeightsCount;
                BinaryReader     r = new BinaryReader(stream);
                long             positionAfterHeader = stream.Position;

                if (meshChunk.SectionInfo.TriangleStripCount > 0)
                {
                    int vertInd = 0;
                    for (int p = 0; p < meshChunk.SectionInfo.TriangleStripCount; p++)
                    {
                        for (int s = 0; s < (meshChunk.TriangleStripValues[p] - 2); s++)
                        {
                            if (s % 2 == 0)
                            {
                                meshChunk.Indices.Add(vertInd + s + 0);
                                meshChunk.Indices.Add(vertInd + s + 1);
                                meshChunk.Indices.Add(vertInd + s + 2);
                            }
                            else
                            {
                                meshChunk.Indices.Add(vertInd + s + 0);
                                meshChunk.Indices.Add(vertInd + s + 2);
                                meshChunk.Indices.Add(vertInd + s + 1);
                            }
                        }

                        vertInd += meshChunk.TriangleStripValues[p];
                    }
                }
                else
                {
                    if (flags.Primitive == PrimitiveType.PRIMITIVE_TRIANGLE_STRIP)
                    {
                        for (int s = 0; s < (meshChunk.SectionInfo.VertexCount - 2); s++)
                        {
                            if (s % 2 == 0)
                            {
                                meshChunk.Indices.Add(s + 0);
                                meshChunk.Indices.Add(s + 1);
                                meshChunk.Indices.Add(s + 2);
                            }
                            else
                            {
                                meshChunk.Indices.Add(s + 1);
                                meshChunk.Indices.Add(s + 0);
                                meshChunk.Indices.Add(s + 2);
                            }
                        }
                    }
                }

                for (int v = 0; v < meshChunk.SectionInfo.VertexCount; v++)
                {
                    long vertexStartPos       = stream.Position;
                    int  vertexIncreaseAmount = 0;

                    if (pmo.header.SkeletonOffset != 0 && WeightFormat != CoordinateFormat.NO_VERTEX)
                    {
                        for (int i = 0; i < (SkinningWeightsCount + 1); i++)
                        {
                            switch (WeightFormat)
                            {
                            case CoordinateFormat.NORMALIZED_8_BITS:
                                meshChunk.jointWeights.Add(stream.ReadByte() / 127.0f);
                                break;

                            case CoordinateFormat.NORMALIZED_16_BITS:
                                meshChunk.jointWeights.Add(stream.ReadUInt16() / 32767.0f);
                                break;

                            case CoordinateFormat.FLOAT_32_BITS:
                                meshChunk.jointWeights.Add(stream.ReadFloat());
                                break;

                            case CoordinateFormat.NO_VERTEX:
                                break;
                            }
                        }
                    }

                    Vector2 currentTexCoord;

                    switch (TexCoordFormat)
                    {
                    case CoordinateFormat.NORMALIZED_8_BITS:
                        currentTexCoord.X = stream.ReadByte() / 127.0f;
                        currentTexCoord.Y = stream.ReadByte() / 127.0f;
                        meshChunk.textureCoordinates.Add(currentTexCoord);
                        break;

                    case CoordinateFormat.NORMALIZED_16_BITS:
                        vertexIncreaseAmount = ((0x2 - (Convert.ToInt32(stream.Position - vertexStartPos) & 0x1)) & 0x1);
                        stream.Seek(vertexIncreaseAmount, SeekOrigin.Current);

                        currentTexCoord.X = stream.ReadUInt16() / 32767.0f;
                        currentTexCoord.Y = stream.ReadUInt16() / 32767.0f;
                        meshChunk.textureCoordinates.Add(currentTexCoord);
                        break;

                    case CoordinateFormat.FLOAT_32_BITS:
                        vertexIncreaseAmount = ((0x4 - (Convert.ToInt32(stream.Position - vertexStartPos) & 0x3)) & 0x3);
                        stream.Seek(vertexIncreaseAmount, SeekOrigin.Current);

                        currentTexCoord.X = stream.ReadFloat();
                        currentTexCoord.Y = stream.ReadFloat();
                        meshChunk.textureCoordinates.Add(currentTexCoord);
                        break;
                    }

                    switch (ColorFormat)
                    {
                    case Pmo.ColorFormat.NO_COLOR:
                        meshChunk.colors.Add(new Vector4(0xFF, 0xFF, 0xFF, 0xFF));
                        break;

                    case Pmo.ColorFormat.BGR_5650_16BITS:
                        stream.ReadUInt16();
                        break;

                    case Pmo.ColorFormat.ABGR_5551_16BITS:
                        stream.ReadUInt16();
                        break;

                    case Pmo.ColorFormat.ABGR_4444_16BITS:
                        stream.ReadUInt16();
                        break;

                    case Pmo.ColorFormat.ABGR_8888_32BITS:
                        vertexIncreaseAmount = ((0x4 - (Convert.ToInt32(stream.Position - vertexStartPos) & 0x3)) & 0x3);
                        stream.Seek(vertexIncreaseAmount, SeekOrigin.Current);

                        Vector4 col;
                        col.X = stream.ReadByte();
                        col.Y = stream.ReadByte();
                        col.Z = stream.ReadByte();
                        col.W = stream.ReadByte();
                        meshChunk.colors.Add(col);
                        break;
                    }

                    Vector3 currentVertex;

                    // Handle triangles and triangle strips.
                    switch (VertexPositionFormat)
                    {
                    case CoordinateFormat.NORMALIZED_8_BITS:
                        currentVertex.X = r.ReadSByte() / 127.0f;
                        currentVertex.Y = r.ReadSByte() / 127.0f;
                        currentVertex.Z = r.ReadSByte() / 127.0f;
                        meshChunk.vertices.Add(currentVertex);
                        break;

                    case CoordinateFormat.NORMALIZED_16_BITS:
                        vertexIncreaseAmount = ((0x2 - (Convert.ToInt32(stream.Position - vertexStartPos) & 0x1)) & 0x1);
                        stream.Seek(vertexIncreaseAmount, SeekOrigin.Current);

                        currentVertex.X = (float)stream.ReadInt16() / 32767.0f;
                        currentVertex.Y = (float)stream.ReadInt16() / 32767.0f;
                        currentVertex.Z = (float)stream.ReadInt16() / 32767.0f;
                        meshChunk.vertices.Add(currentVertex);
                        break;

                    case CoordinateFormat.FLOAT_32_BITS:
                        vertexIncreaseAmount = ((0x4 - (Convert.ToInt32(stream.Position - vertexStartPos) & 0x3)) & 0x3);
                        stream.Seek(vertexIncreaseAmount, SeekOrigin.Current);

                        currentVertex.X = stream.ReadFloat();
                        currentVertex.Y = stream.ReadFloat();
                        currentVertex.Z = stream.ReadFloat();
                        meshChunk.vertices.Add(currentVertex);
                        break;
                    }

                    stream.Seek(vertexStartPos + meshChunk.SectionInfo.VertexSize, SeekOrigin.Begin);

                    if (flags.Primitive == PrimitiveType.PRIMITIVE_TRIANGLE)
                    {
                        meshChunk.Indices.Add(v);
                    }
                }

                VertCnt = meshChunk.SectionInfo.VertexCount;
                pmo.Meshes.Add(meshChunk);

                // Find position of next data chunk.
                stream.Seek(positionAfterHeader + (meshChunk.SectionInfo.VertexCount * meshChunk.SectionInfo.VertexSize), SeekOrigin.Begin);
                stream.Seek(stream.Position % 4, SeekOrigin.Current);
            }
        }
예제 #44
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Cell"/> class.
 /// </summary>
 /// <param name="contents">The contents of the cell.</param>
 /// <param name="color">The color of the contents of the cell.</param>
 public Cell(string contents, ColorFormat color)
     : this()
 {
     this.Contents = contents;
     this.Color    = color;
 }
예제 #45
0
파일: Pmo.cs 프로젝트: PlancakeJB/OpenKh
        public static int GetVertexSize(CoordinateFormat TexCoordFormat, CoordinateFormat VertexPositionFormat, CoordinateFormat WeightFormat, ColorFormat ColorFormat, int numWeights = 0)
        {
            int vertexSize = 0;

            switch (TexCoordFormat)
            {
            case CoordinateFormat.NORMALIZED_8_BITS:
                vertexSize += 2;
                break;

            case CoordinateFormat.NORMALIZED_16_BITS:
                vertexSize += 4;
                break;

            case CoordinateFormat.FLOAT_32_BITS:
                vertexSize += 8;
                break;
            }

            switch (VertexPositionFormat)
            {
            case CoordinateFormat.NORMALIZED_8_BITS:
                vertexSize += 3;
                break;

            case CoordinateFormat.NORMALIZED_16_BITS:
                vertexSize += 6;
                break;

            case CoordinateFormat.FLOAT_32_BITS:
                vertexSize += 12;
                break;
            }

            switch (WeightFormat)
            {
            case CoordinateFormat.NORMALIZED_8_BITS:
                vertexSize += (numWeights + 1);
                break;

            case CoordinateFormat.NORMALIZED_16_BITS:
                vertexSize += (numWeights + 1) * 2;
                break;

            case CoordinateFormat.FLOAT_32_BITS:
                vertexSize += (numWeights + 1) * 4;
                break;
            }

            switch (ColorFormat)
            {
            case ColorFormat.BGR_5650_16BITS:
                vertexSize += 2;
                break;

            case ColorFormat.ABGR_5551_16BITS:
                vertexSize += 2;
                break;

            case ColorFormat.ABGR_4444_16BITS:
                vertexSize += 2;
                break;

            case ColorFormat.ABGR_8888_32BITS:
                vertexSize += 4;
                break;
            }

            return(vertexSize);
        }
예제 #46
0
 /// <summary>
 /// Set external camera image to AR engine.(Free, Enterprise license key can activate this interface. Mobile only supported)
 /// </summary>
 /// <param name="data">Native address of camera image</param>
 /// <param name="length">Lenght of data buffer</param>
 /// <param name="width">Width of camera image</param>
 /// <param name="height">Height of camera image</param>
 /// <param name="format">Color format</param>
 /// <returns>True success</returns>
 public bool SetNewFrame(ulong data, int length, int width, int height, ColorFormat format)
 {
     return(NativeAPI.maxst_CameraDevice_setNewFramePtr(data, length, width, height, (int)format));
 }
예제 #47
0
 public static int ColorToDecimal(Color color, ColorFormat format = ColorFormat.RGB)
 {
     return(ColorToDecimal(color.R, color.G, color.B, color.A, format));
 }
예제 #48
0
 /// <summary>
 /// Set external camera image and timestamp to AR engine.(Free, Enterprise license key can activate this interface. Mobile only supported)
 /// </summary>
 /// <param name="data">Native address of camera image</param>
 /// <param name="length">Lenght of data buffer</param>
 /// <param name="width">Width of camera image</param>
 /// <param name="height">Height of camera image</param>
 /// <param name="format">Color format</param>
 /// <param name="timestamp">Timestamp</param>
 /// <returns>True success</returns>
 public bool SetNewFrameAndTimestamp(ulong data, int length, int width, int height, ColorFormat format, ulong timestamp)
 {
     return(NativeAPI.maxst_CameraDevice_setNewFramePtrAndTimestamp(data, length, width, height, (int)format, timestamp));
 }
예제 #49
0
 public int ToDecimal(ColorFormat format = ColorFormat.RGB)
 {
     return(ColorHelper.ColorToDecimal(argb.R, argb.G, argb.B, argb.A, format));
 }
예제 #50
0
        /// \internal
        /// <summary>
        /// Relaxes graphics mode parameters. Use this function to increase compatibility
        /// on systems that do not directly support a requested GraphicsMode. For example:
        /// - user requested stereoscopic rendering, but GPU does not support stereo
        /// - user requseted 16x antialiasing, but GPU only supports 4x
        /// </summary>
        /// <returns><c>true</c>, if a graphics mode parameter was relaxed, <c>false</c> otherwise.</returns>
        /// <param name="color">Color bits.</param>
        /// <param name="depth">Depth bits.</param>
        /// <param name="stencil">Stencil bits.</param>
        /// <param name="samples">Number of antialiasing samples.</param>
        /// <param name="accum">Accumulator buffer bits.</param>
        /// <param name="buffers">Number of rendering buffers (1 for single buffering, 2+ for double buffering, 0 for don't care).</param>
        /// <param name="stereo">Stereoscopic rendering enabled/disabled.</param>
        internal static bool RelaxGraphicsMode(ref ColorFormat color, ref int depth, ref int stencil, ref int samples, ref ColorFormat accum, ref int buffers, ref bool stereo)
        {
            // Parameters are relaxed in order of importance.
            // - Accumulator buffers are way outdated as a concept,
            // so they go first.
            // - Triple+ buffering is generally not supported by the
            // core WGL/GLX/AGL/CGL/EGL specs, so we clamp
            // to double-buffering as a second step. (If this doesn't help
            // we will also fall back to undefined single/double buffering
            // as a last resort).
            // - AA samples are an easy way to increase compatibility
            // so they go next.
            // - Stereoscopic is only supported on very few GPUs
            // (Quadro/FirePro series) so it goes next.
            // - The rest of the parameters then follow.

            if (accum != 0)
            {
                accum = 0;
                return(true);
            }

            if (buffers > 2)
            {
                buffers = 2;
                return(true);
            }

            if (samples > 0)
            {
                samples = Math.Max(samples - 1, 0);
                return(true);
            }

            if (stereo)
            {
                stereo = false;
                return(true);
            }

            if (stencil != 0)
            {
                stencil = 0;
                return(true);
            }

            if (depth != 0)
            {
                depth = 0;
                return(true);
            }

            if (color != 24)
            {
                color = 24;
                return(true);
            }

            if (buffers != 0)
            {
                buffers = 0;
                return(true);
            }

            // no parameters left to relax, fail
            return(false);
        }
예제 #51
0
 public string ToHex(ColorFormat format = ColorFormat.RGB)
 {
     return(ColorHelper.ColorToHex(argb.R, argb.G, argb.B, argb.A, format));
 }
예제 #52
0
 public ColorSpaceEntry(Guid videoSubType, ColorFormat colorFormat)
 {
     this.videoSubType = videoSubType;
     this.colorFormat  = colorFormat;
 }
예제 #53
0
 public static Color DecimalToColor(int dec, ColorFormat format = ColorFormat.RGB)
 {
     switch (format)
     {
         default:
         case ColorFormat.RGB:
             return Color.FromArgb((dec >> 16) & 0xFF, (dec >> 8) & 0xFF, dec & 0xFF);
         case ColorFormat.RGBA:
             return Color.FromArgb(dec & 0xFF, (dec >> 24) & 0xFF, (dec >> 16) & 0xFF, (dec >> 8) & 0xFF);
         case ColorFormat.ARGB:
             return Color.FromArgb((dec >> 24) & 0xFF, (dec >> 16) & 0xFF, (dec >> 8) & 0xFF, dec & 0xFF);
     }
 }
예제 #54
0
        void InitializeContext()
        {
            Toolkit.Init();

            // If this looks uninitialized...  initialize.
            if (ColorBPP == 0)
            {
                ColorBPP = 24;

                if (DepthBPP == 0)
                {
                    DepthBPP = 16;
                }
            }

            ColorFormat colorBufferColorFormat = new ColorFormat(ColorBPP);

            ColorFormat accumulationColorFormat = new ColorFormat(AccumulatorBPP);

            int buffers = 2;

            if (SingleBuffer)
            {
                buffers--;
            }

            var graphicsMode = new GraphicsMode(colorBufferColorFormat, DepthBPP, StencilBPP, Samples, accumulationColorFormat, buffers, Stereo);

            // IWindowInfo
            if (Configuration.RunningOnWindows)
            {
                IntPtr windowHandle = gdk_win32_drawable_get_handle(GdkWindow.Handle);
                windowInfo = Utilities.CreateWindowsWindowInfo(windowHandle);
            }
            else if (Configuration.RunningOnMacOS)
            {
                IntPtr windowHandle = gdk_x11_drawable_get_xid(GdkWindow.Handle);
                bool   ownHandle    = true;
                bool   isControl    = true;
                windowInfo = Utilities.CreateMacOSCarbonWindowInfo(windowHandle, ownHandle, isControl);
            }
            else if (Configuration.RunningOnX11)
            {
                IntPtr display      = gdk_x11_display_get_xdisplay(Display.Handle);
                int    screen       = Screen.Number;
                IntPtr windowHandle = gdk_x11_drawable_get_xid(GdkWindow.Handle);
                IntPtr rootWindow   = gdk_x11_drawable_get_xid(RootWindow.Handle);

                IntPtr visualInfo;
                if (graphicsMode.Index.HasValue)
                {
                    XVisualInfo info = new XVisualInfo();
                    info.VisualID = graphicsMode.Index.Value;
                    int dummy;
                    visualInfo = XGetVisualInfo(display, XVisualInfoMask.ID, ref info, out dummy);
                }
                else
                {
                    visualInfo = GetVisualInfo(display);
                }

                windowInfo = Utilities.CreateX11WindowInfo(display, screen, windowHandle, rootWindow, visualInfo);
                XFree(visualInfo);
            }
            else
            {
                throw new PlatformNotSupportedException();
            }

            // GraphicsContext
            graphicsContext = new GraphicsContext(graphicsMode, windowInfo, GlVersionMajor, GlVersionMinor, graphicsContextFlags);
            graphicsContext.MakeCurrent(windowInfo);

            if (GraphicsContext.ShareContexts)
            {
                Interlocked.Increment(ref graphicsContextCount);

                if (!sharedContextInitialized)
                {
                    sharedContextInitialized = true;
                    ((IGraphicsContextInternal)graphicsContext).LoadAll();
                    OnGraphicsContextInitialized();
                }
            }
            else
            {
                ((IGraphicsContextInternal)graphicsContext).LoadAll();
                OnGraphicsContextInitialized();
            }

            initialized = true;
            OnInitialized();
            //QueueDraw();
        }
예제 #55
0
 public void SetColorMethod(ColorFormat model)
 => ColorFormat = model;
예제 #56
0
 public ColorDescriptor(ColorFormat id, string name, string description)
 {
     Id          = id;
     Name        = name;
     Description = description;
 }
예제 #57
0
파일: RGBA.cs 프로젝트: yuhongfang/ShareX
 public int ToDecimal(ColorFormat format = ColorFormat.RGB)
 {
     return ColorHelpers.ColorToDecimal(this, format);
 }
        /// <summary>
        /// Initializes this instance by coroutine.
        /// </summary>
        protected override IEnumerator _Initialize()
        {
            if (hasInitDone)
            {
                StartCoroutine(_Stop());

                while (isChangeVideoModeWaiting)
                {
                    yield return(null);
                }

                ReleaseResources();

                if (onDisposed != null)
                {
                    onDisposed.Invoke();
                }
            }

            isInitWaiting = true;

            while (isChangeVideoModeWaiting)
            {
                yield return(null);
            }

            isChangeVideoModeWaiting = true;
            if (videoCapture != null)
            {
                videoCapture.StopVideoModeAsync(result1 =>
                {
                    cameraParams = CreateCameraParams(videoCapture);
                    videoCapture.StartVideoModeAsync(cameraParams, result2 =>
                    {
                        if (!result2.success)
                        {
                            isChangeVideoModeWaiting = false;
                            isInitWaiting            = false;
                            CancelInitCoroutine();

                            if (onErrorOccurred != null)
                            {
                                onErrorOccurred.Invoke(ErrorCode.UNKNOWN);
                            }
                        }
                        else
                        {
                            isChangeVideoModeWaiting = false;
                        }
                    });
                });
            }
            else
            {
                //Fetch a pointer to Unity's spatial coordinate system if you need pixel mapping
#if UNITY_2017_2_OR_NEWER
                spatialCoordinateSystemPtr = UnityEngine.XR.WSA.WorldManager.GetNativeISpatialCoordinateSystemPtr();
#else
                spatialCoordinateSystemPtr = UnityEngine.VR.WSA.WorldManager.GetNativeISpatialCoordinateSystemPtr();
#endif

                HoloLensCameraStream.VideoCapture.CreateAync(videoCapture =>
                {
                    if (initCoroutine == null)
                    {
                        return;
                    }

                    if (videoCapture == null)
                    {
                        Debug.LogError("Did not find a video capture object. You may not be using the HoloLens.");

                        isChangeVideoModeWaiting = false;
                        isInitWaiting            = false;
                        CancelInitCoroutine();

                        if (onErrorOccurred != null)
                        {
                            onErrorOccurred.Invoke(ErrorCode.CAMERA_DEVICE_NOT_EXIST);
                        }

                        return;
                    }

                    this.videoCapture = videoCapture;

                    //Request the spatial coordinate ptr if you want fetch the camera and set it if you need to
                    videoCapture.WorldOriginPtr = spatialCoordinateSystemPtr;

                    cameraParams = CreateCameraParams(videoCapture);

                    videoCapture.FrameSampleAcquired -= OnFrameSampleAcquired;
                    videoCapture.FrameSampleAcquired += OnFrameSampleAcquired;
                    videoCapture.StartVideoModeAsync(cameraParams, result =>
                    {
                        if (!result.success)
                        {
                            isChangeVideoModeWaiting = false;
                            isInitWaiting            = false;
                            CancelInitCoroutine();

                            if (onErrorOccurred != null)
                            {
                                onErrorOccurred.Invoke(ErrorCode.UNKNOWN);
                            }
                        }
                        else
                        {
                            isChangeVideoModeWaiting = false;
                        }
                    });
                });
            }

            int  initFrameCount = 0;
            bool isTimeout      = false;

            while (true)
            {
                if (initFrameCount > _timeoutFrameCount)
                {
                    isTimeout = true;
                    break;
                }
                else if (didUpdateThisFrame)
                {
                    Debug.Log("HololensCameraStreamToMatHelper:: " + "name:" + "" + " width:" + cameraParams.cameraResolutionWidth + " height:" + cameraParams.cameraResolutionHeight + " fps:" + cameraParams.frameRate);

                    baseColorFormat = (outputColorFormat == ColorFormat.GRAY) ? ColorFormat.GRAY : ColorFormat.BGRA;

                    baseMat = new Mat(cameraParams.cameraResolutionHeight, cameraParams.cameraResolutionWidth, CvType.CV_8UC(Channels(baseColorFormat)));

                    if (baseColorFormat == outputColorFormat)
                    {
                        frameMat = baseMat;
                    }
                    else
                    {
                        frameMat = new Mat(baseMat.rows(), baseMat.cols(), CvType.CV_8UC(Channels(outputColorFormat)));
                    }

                    if (_rotate90Degree)
                    {
                        rotatedFrameMat = new Mat(frameMat.cols(), frameMat.rows(), CvType.CV_8UC(Channels(outputColorFormat)));
                    }

                    isInitWaiting = false;
                    hasInitDone   = true;
                    initCoroutine = null;

                    if (onInitialized != null)
                    {
                        onInitialized.Invoke();
                    }

                    hasInitEventCompleted = true;

                    break;
                }
                else
                {
                    initFrameCount++;
                    yield return(null);
                }
            }

            if (isTimeout)
            {
                if (videoCapture != null)
                {
                    videoCapture.FrameSampleAcquired -= OnFrameSampleAcquired;

                    isChangeVideoModeWaiting = true;
                    videoCapture.StopVideoModeAsync(result =>
                    {
                        videoCapture.Dispose();
                        videoCapture             = null;
                        isChangeVideoModeWaiting = false;
                    });

                    isInitWaiting = false;
                    initCoroutine = null;

                    if (onErrorOccurred != null)
                    {
                        onErrorOccurred.Invoke(ErrorCode.TIMEOUT);
                    }
                }
                else
                {
                    isInitWaiting = false;
                    initCoroutine = null;

                    if (onErrorOccurred != null)
                    {
                        onErrorOccurred.Invoke(ErrorCode.TIMEOUT);
                    }
                }
            }
        }
예제 #59
0
 public DescriptionAttribute(string description, string detail, ColorFormat color)
     : this(description, color)
 {
     this.Detail = detail;
 }
예제 #60
0
        /// <summary>
        /// Gets a random aesthetically pleasing color near the base RGB. See [here](http://stackoverflow.com/questions/43044/algorithm-to-randomly-generate-an-aesthetically-pleasing-color-palette).
        /// </summary>
        /// <param name="baseRed">Red base color</param>
        /// <param name="baseGreen">Green base color</param>
        /// <param name="baseBlue">Blue base color</param>
        /// <param name="grayscale">Output a gray scale color</param>
        /// <param name="format">The color format</param>
        /// <returns>A random color.</returns>
        public string Color(byte baseRed = 0, byte baseGreen = 0, byte baseBlue = 0, bool grayscale = false, ColorFormat format = ColorFormat.Hex)
        {
            var red   = Math.Floor((Random.Number(256) + (double)baseRed) / 2);
            var green = Math.Floor((Random.Number(256) + (double)baseGreen) / 2);
            var blue  = Math.Floor((Random.Number(256) + (double)baseBlue) / 2);

            if (grayscale)
            {
                green = red;
                blue  = red;
            }

            if (format == ColorFormat.Hex)
            {
                return(string.Format("#{0:x02}{1:x02}{2:x02}", (byte)red, (byte)green, (byte)blue));
            }

            if (format == ColorFormat.Delimited)
            {
                return(DelimitedRgb());
            }

            return($"rgb({DelimitedRgb()})");

            string DelimitedRgb()
            {
                return($"{(byte)red},{(byte)green},{(byte)blue}");
            }
        }