Esempio n. 1
0
        private void GenerateTexture(Rgba32[] data, int width, int height)
        {
            _isLoaded = false;

            TextureOptions opts = new TextureOptions(TextureFormat.Rgba8888);

            // Premultiply alpha
            byte[] pmaData = new byte[data.Length * 4];
            for (int i = 0; i < data.Length; i++)
            {
                var   aPixel = data[i];
                float alpha  = (float)aPixel.A / 255;
                pmaData[4 * i + 0] = (byte)(aPixel.R * alpha);
                pmaData[4 * i + 1] = (byte)(aPixel.G * alpha);
                pmaData[4 * i + 2] = (byte)(aPixel.B * alpha);
                pmaData[4 * i + 3] = (byte)(alpha * 255);
            }

            _glTexture = Texture.FromData(pmaData, opts, width, height);

            _isLoaded = true;
            // Make a temporary copy of the event to avoid possibility of
            // a race condition if the last subscriber unsubscribes
            // immediately after the null check and before the event is raised.
            EventHandler <Texture> handler = ResourceLoaded;

            handler?.Invoke(this, _glTexture);
        }
Esempio n. 2
0
 private static void WriteBackgrounds(IList <KeyValuePair <string, GMBackground> > _data, Stream _s, IFF _iff)
 {
     WriteDataKVP(_data, _s, _iff, delegate(KeyValuePair <string, GMBackground> _kvp, Stream __s, IFF __iff, long __index)
     {
         __s.PatchOffset(__index);
         __iff.AddString(__s, _kvp.Key);
         GMBackground value = _kvp.Value;
         __s.WriteBoolean(value.Transparent);
         __s.WriteBoolean(value.Smooth);
         __s.WriteBoolean(value.Preload);
         if (value.Bitmap != null && value.Bitmap.Width * value.Bitmap.Height > 0)
         {
             ms_tpageSprites.BeginGroup(_kvp.Key);
             TexturePageEntry texturePageEntry = ms_tpageSprites.AddImage(value.Bitmap.Bitmap, true, false);
             ms_tpageSprites.EndGroup();
             texturePageEntry.OriginalRepeatBorder = true;
             texturePageEntry.RepeatX = 2;
             texturePageEntry.RepeatY = 2;
             TextureOptions.SetTextureOptions(_kvp.Key, texturePageEntry);
             __iff.AddPatch(__s, texturePageEntry);
         }
         else
         {
             __s.WriteInteger(0);
         }
     });
 }
Esempio n. 3
0
        public TextureProvider(TextureOptions textureOptions)
        {
            _textureOptions = textureOptions;

            LoadBlockColorFile();
            LoadBiomeColorFile();
        }
Esempio n. 4
0
        protected void WriteOptions(AssetKey assetGuid, string urhoTextureName, DateTime lastWriteTimeUtc,
                                    TextureOptions options)
        {
            if (options == null)
            {
                return;
            }
            var xmlFileName = ExportUtils.ReplaceExtension(urhoTextureName, ".xml");

            if (xmlFileName == urhoTextureName)
            {
                return;
            }
            using (var writer = _engine.TryCreateXml(assetGuid, xmlFileName, lastWriteTimeUtc))
            {
                if (writer != null)
                {
                    writer.WriteStartElement("texture");
                    writer.WriteWhitespace(Environment.NewLine);
                    switch (options.filterMode)
                    {
                    case FilterMode.Point:
                        writer.WriteElementParameter("filter", "mode", "nearest");
                        break;

                    case FilterMode.Bilinear:
                        writer.WriteElementParameter("filter", "mode", "bilinear");
                        break;

                    case FilterMode.Trilinear:
                        writer.WriteElementParameter("filter", "mode", "trilinear");
                        break;

                    default:
                        writer.WriteElementParameter("filter", "mode", "default");
                        break;
                    }

                    switch (options.wrapMode)
                    {
                    case TextureWrapMode.Repeat:
                        writer.WriteElementParameter("address", "mode", "wrap");
                        break;

                    case TextureWrapMode.Clamp:
                        writer.WriteElementParameter("address", "mode", "clamp");
                        break;

                    case TextureWrapMode.Mirror:
                        writer.WriteElementParameter("address", "mode", "mirror");
                        break;
                    }

                    writer.WriteElementParameter("srgb", "enable", options.sRGBTexture ? "true" : "false");
                    writer.WriteElementParameter("mipmap", "enable", options.mipmapEnabled ? "true" : "false");
                    writer.WriteEndElement();
                }
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="DynamicTexture2D"/> class.
        /// </summary>
        /// <param name="uv">The Ultraviolet context.</param>
        /// <param name="width">The texture's width in pixels.</param>
        /// <param name="height">The texture's height in pixels.</param>
        /// <param name="options">The texture's configuration options.</param>
        /// <param name="state">An arbitrary state object which will be passed to the flush handler.</param>
        /// <param name="flushed">The handler to invoke when the texture is flushed.</param>
        protected DynamicTexture2D(UltravioletContext uv, Int32 width, Int32 height, TextureOptions options, Object state, Action <Texture2D, Object> flushed)
            : base(uv)
        {
            Contract.Require(flushed, nameof(flushed));

            this.state   = state;
            this.flushed = flushed;
        }
Esempio n. 6
0
 private WriteFunc <SerializedType> GetTextureWriter(TextureOptions inTextureOptions)
 {
     if ((inTextureOptions & TextureOptions.JPG) != 0)
     {
         return(Write_Texture2DJPG);
     }
     return(Write_Texture2DPNG);
 }
 private WriteFunc <UnityEngine.Texture2D> GetTextureWriter(TextureOptions inTextureOptions)
 {
     if ((inTextureOptions & TextureOptions.JPG) != 0)
     {
         return(Write_Texture2DJPG_Cached ?? (Write_Texture2DJPG_Cached = Write_Texture2DJPG));
     }
     return(Write_Texture2DPNG_Cached ?? (Write_Texture2DPNG_Cached = Write_Texture2DPNG));
 }
Esempio n. 8
0
        /// <summary>
        /// Creates a new instance of the <see cref="Texture2D"/> class.
        /// </summary>
        /// <param name="width">The texture's width in pixels.</param>
        /// <param name="height">The texture's height in pixels.</param>
        /// <param name="options">The texture's configuration options.</param>
        /// <returns>The instance of <see cref="Texture2D"/> that was created.</returns>
        public static Texture2D CreateTexture(Int32 width, Int32 height, TextureOptions options = TextureOptions.Default)
        {
            Contract.EnsureRange(width > 0, nameof(width));
            Contract.EnsureRange(height > 0, nameof(height));

            var uv = UltravioletContext.DemandCurrent();

            return(uv.GetFactoryMethod <Texture2DFactory>()(uv, width, height, options));
        }
Esempio n. 9
0
        /// <summary>
        /// Creates a new instance of the <see cref="Texture2D"/> class which is designed to be
        /// dynamically updated from data on the CPU.
        /// </summary>
        /// <param name="width">The texture's width in pixels.</param>
        /// <param name="height">The texture's height in pixels.</param>
        /// <param name="options">The texture's configuration options.</param>
        /// <param name="state">An arbitrary state object which will be passed to the flush handler.</param>
        /// <param name="flushed">The handler to invoke when the texture is flushed.</param>
        /// <returns>The instance of <see cref="Texture2D"/> that was created.</returns>
        public static Texture2D CreateDynamicTexture(Int32 width, Int32 height, TextureOptions options, Object state, Action <Texture2D, Object> flushed)
        {
            Contract.EnsureRange(width > 0, nameof(width));
            Contract.EnsureRange(height > 0, nameof(height));
            Contract.Require(flushed, nameof(flushed));

            var uv = UltravioletContext.DemandCurrent();

            return(uv.GetFactoryMethod <DynamicTexture2DFactory>()(uv, width, height, options, state, flushed));
        }
Esempio n. 10
0
 public Texture(string resource, int width, int height, TextureOptions options)
 {
     m_owned = true;
     Handle  = View3D_TextureCreateFromUri(resource, (uint)width, (uint)height, ref options.Data);
     if (Handle == HTexture.Zero)
     {
         throw new Exception($"Failed to create texture from {resource}");
     }
     View3D_TextureGetInfo(Handle, out Info);
     View3D_TextureSetFilterAndAddrMode(Handle, options.Filter, options.AddrU, options.AddrV);
 }
Esempio n. 11
0
            public Texture(int width, int height, IntPtr data, uint data_size, TextureOptions options)
            {
                m_owned = true;
                Handle  = View3D_TextureCreate((uint)width, (uint)height, data, data_size, ref options.Data);
                if (Handle == HTexture.Zero)
                {
                    throw new Exception($"Failed to create {width}x{height} texture");
                }

                View3D_TextureGetInfo(Handle, out Info);
                View3D_TextureSetFilterAndAddrMode(Handle, options.Filter, options.AddrU, options.AddrV);
            }
Esempio n. 12
0
 /// <summary>
 /// Creates a new 2D <see cref="Texture" />.
 /// </summary>
 /// <param name="device">The <see cref="GraphicsDevice" />.</param>
 /// <param name="width">The width.</param>
 /// <param name="height">The height.</param>
 /// <param name="mipCount">Number of mipmaps, set to true to have all mipmaps, set to an int &gt;=1 for a particular mipmap count.</param>
 /// <param name="format">Describes the format to use.</param>
 /// <param name="textureData">Texture datas through an array of <see cref="DataBox" /></param>
 /// <param name="textureFlags">true if the texture needs to support unordered read write.</param>
 /// <param name="arraySize">Size of the texture 2D array, default to 1.</param>
 /// <param name="usage">The usage.</param>
 /// <param name="multisampleCount">The multisample count.</param>
 /// <param name="options">The options, e.g. sharing</param>
 /// <returns>
 /// A new instance of 2D <see cref="Texture" /> class.
 /// </returns>
 public static Texture New2D(
     GraphicsDevice device,
     int width,
     int height,
     MipMapCount mipCount,
     PixelFormat format,
     DataBox[] textureData,
     TextureFlags textureFlags         = TextureFlags.ShaderResource,
     int arraySize                     = 1,
     GraphicsResourceUsage usage       = GraphicsResourceUsage.Default,
     MultisampleCount multisampleCount = MultisampleCount.None,
     TextureOptions options            = TextureOptions.None)
 {
     return(new Texture(device).InitializeFrom(TextureDescription.New2D(width, height, mipCount, format, textureFlags, arraySize, usage, multisampleCount, options), textureData));
 }
Esempio n. 13
0
            /// <summary>Create a render target texture based on a shared Dx9 texture</summary>
            public static Texture Dx9RenderTarget(HWND hwnd, int width, int height, TextureOptions options, out IntPtr shared_handle)
            {
                // Not all of the texture options are used, just format, sampler description, has alpha, and dbg name
                if (hwnd == IntPtr.Zero)
                {
                    throw new Exception("DirectX 9 requires a window handle");
                }

                // Try to create the texture. This can fail if the window handle is 'ready'
                var handle = View3D_CreateDx9RenderTarget(hwnd, (uint)width, (uint)height, ref options.Data, out shared_handle);

                if (handle == IntPtr.Zero)
                {
                    throw new Exception("Failed to create DirectX 9 render target texture");
                }

                return(new Texture(handle, owned: true));
            }
        /// <summary>
        /// Initializes a new instance of the <see cref="OpenGLTexture3D"/> class.
        /// </summary>
        /// <param name="uv">The Ultraviolet context.</param>
        /// <param name="data">A list of pointers to the raw pixel data for each of the texture's layers.</param>
        /// <param name="width">The texture's width in pixels.</param>
        /// <param name="height">The texture's height in pixels.</param>
        /// <param name="bytesPerPixel">The number of bytes which represent each pixel in the raw data.</param>
        /// <param name="options">The texture's configuration options.</param>
        public OpenGLTexture3D(UltravioletContext uv, IList <IntPtr> data, Int32 width, Int32 height, Int32 bytesPerPixel, TextureOptions options)
            : base(uv)
        {
            Contract.Require(data, nameof(data));
            Contract.EnsureRange(width > 0, nameof(width));
            Contract.EnsureRange(height > 0, nameof(height));
            Contract.EnsureRange(bytesPerPixel == 3 || bytesPerPixel == 4, nameof(bytesPerPixel));

            var isLinear = (options & TextureOptions.LinearColor) == TextureOptions.LinearColor;
            var isSrgb   = (options & TextureOptions.SrgbColor) == TextureOptions.SrgbColor;

            if (isLinear && isSrgb)
            {
                throw new ArgumentException(UltravioletStrings.TextureCannotHaveMultipleEncodings);
            }

            var caps        = uv.GetGraphics().Capabilities;
            var srgbEncoded = isLinear ? false : (isSrgb ? true : uv.Properties.SrgbDefaultForSurface3D) && caps.SrgbEncodingEnabled;

            var format         = OpenGLTextureUtil.GetFormatFromBytesPerPixel(bytesPerPixel);
            var internalformat = OpenGLTextureUtil.GetInternalFormatFromBytesPerPixel(bytesPerPixel, srgbEncoded);

            if (format == gl.GL_NONE || internalformat == gl.GL_NONE)
            {
                throw new NotSupportedException(OpenGLStrings.UnsupportedImageType);
            }

            var pixels = IntPtr.Zero;

            try
            {
                pixels = CreateConcatenatedPixelBuffer(data, width * height * bytesPerPixel);
                CreateNativeTexture(uv, internalformat, width, height, data.Count, format,
                                    gl.GL_UNSIGNED_BYTE, (void *)pixels, true);
            }
            finally
            {
                if (pixels != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(pixels);
                }
            }
        }
Esempio n. 15
0
 public void Map(string inKey, ref Dictionary <string, SerializedType> ioMap, TextureOptions inTextureOptions = TextureOptions.Default, FieldOptions inOptions = FieldOptions.None)
 {
     DoMapUnity <SerializedType>(inKey, ref ioMap, inOptions, Read_Texture2D, GetTextureWriter(inTextureOptions));
 }
Esempio n. 16
0
 public void Set(string inKey, ref HashSet <SerializedType> ioSet, TextureOptions inTextureOptions = TextureOptions.Default, FieldOptions inOptions = FieldOptions.None)
 {
     DoSetUnity <SerializedType>(inKey, ref ioSet, inOptions, Read_Texture2D, GetTextureWriter(inTextureOptions));
 }
Esempio n. 17
0
 public void Array(string inKey, ref SerializedType[] ioArray, TextureOptions inTextureOptions = TextureOptions.Default, FieldOptions inOptions = FieldOptions.None)
 {
     DoArrayUnity <SerializedType>(inKey, ref ioArray, inOptions, Read_Texture2D, GetTextureWriter(inTextureOptions));
 }
Esempio n. 18
0
 public void Serialize(string inKey, ref SerializedType ioData, TextureOptions inTextureOptions = TextureOptions.Default, FieldOptions inOptions = FieldOptions.None)
 {
     DoSerializeUnity <SerializedType>(inKey, ref ioData, inOptions, Read_Texture2D, GetTextureWriter(inTextureOptions));
 }
Esempio n. 19
0
 /**
  * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024).
  * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024).
  * @param pTextureOptions the (quality) settings of the Texture.
  */
 public Texture(int pWidth, int pHeight, TextureOptions pTextureOptions) /* throws IllegalArgumentException */ {
     Init(pWidth, pHeight, pTextureOptions, null);
 }
Esempio n. 20
0
            public static IEnumerator UpdateTextures(CelestialBody celestialBody, TextureOptions options)
            {
                // Get time
                DateTime now = DateTime.Now;

                // If the user wants to export normals, we need height too
                if (options.ExportNormal)
                {
                    options.ExportHeight = true;
                }

                // Prepare the PQS
                PQS pqsVersion = celestialBody.pqsController;

                // If the PQS is null, abort
                if (pqsVersion == null)
                {
                    throw new InvalidOperationException();
                }

                // Tell the PQS that we are going to build maps
                pqsVersion.SetupExternalRender();

                // Get the mod building methods from the PQS
                Action <PQS.VertexBuildData> modOnVertexBuildHeight =
                    (Action <PQS.VertexBuildData>)Delegate.CreateDelegate(
                        typeof(Action <PQS.VertexBuildData>),
                        pqsVersion,
                        typeof(PQS).GetMethod("Mod_OnVertexBuildHeight",
                                              BindingFlags.Instance | BindingFlags.NonPublic));
                Action <PQS.VertexBuildData> modOnVertexBuild = (Action <PQS.VertexBuildData>)Delegate.CreateDelegate(
                    typeof(Action <PQS.VertexBuildData>),
                    pqsVersion,
                    typeof(PQS).GetMethod("Mod_OnVertexBuild", BindingFlags.Instance | BindingFlags.NonPublic));

                // Get all mods the PQS is connected to
                PQSMod[] mods = pqsVersion.GetComponentsInChildren <PQSMod>()
                                .Where(m => m.sphere == pqsVersion && m.modEnabled).OrderBy(m => m.order).ToArray();

                // Prevent the PQS from updating
                pqsVersion.enabled = false;

                // Create the Textures
                Texture2D colorMap = new Texture2D(pqsVersion.mapFilesize, pqsVersion.mapFilesize / 2,
                                                   TextureFormat.ARGB32,
                                                   true);
                Texture2D heightMap = new Texture2D(pqsVersion.mapFilesize, pqsVersion.mapFilesize / 2,
                                                    TextureFormat.RGB24,
                                                    true);

                // Arrays
                Color[] colorMapValues  = new Color[pqsVersion.mapFilesize * (pqsVersion.mapFilesize / 2)];
                Color[] heightMapValues = new Color[pqsVersion.mapFilesize * (pqsVersion.mapFilesize / 2)];

                // Create a VertexBuildData
                PQS.VertexBuildData data = new PQS.VertexBuildData();

                // Display
                ScreenMessage message = ScreenMessages.PostScreenMessage("Generating Planet-Maps", Single.MaxValue, ScreenMessageStyle.UPPER_CENTER);

                yield return(null);

                // Loop through the pixels
                for (Int32 y = 0; y < pqsVersion.mapFilesize / 2; y++)
                {
                    for (Int32 x = 0; x < pqsVersion.mapFilesize; x++)
                    {
                        // Update Message
                        Double percent = (Double)(y * pqsVersion.mapFilesize + x) /
                                         (pqsVersion.mapFilesize / 2 * pqsVersion.mapFilesize) * 100;
                        while (CanvasUpdateRegistry.IsRebuildingLayout())
                        {
                            Thread.Sleep(10);
                        }
                        message.textInstance.text.text = "Generating Planet-Maps: " + percent.ToString("0.00") + "%";

                        // Update the VertexBuildData
                        data.directionFromCenter =
                            QuaternionD.AngleAxis(360d / pqsVersion.mapFilesize * x, Vector3d.up) *
                            QuaternionD.AngleAxis(90d - 180d / (pqsVersion.mapFilesize / 2f) * y, Vector3d.right)
                            * Vector3d.forward;
                        data.vertHeight = pqsVersion.radius;

                        // Build from the Mods
                        Double height = Double.MinValue;
                        if (options.ExportHeight)
                        {
                            modOnVertexBuildHeight(data);

                            // Adjust the height
                            height = (data.vertHeight - pqsVersion.radius) * (1d / pqsVersion.mapMaxHeight);
                            if (height < 0)
                            {
                                height = 0;
                            }
                            else if (height > 1)
                            {
                                height = 1;
                            }

                            // Set the Pixels
                            heightMapValues[y * pqsVersion.mapFilesize + x] =
                                new Color((Single)height, (Single)height, (Single)height);
                        }

                        if (options.ExportColor)
                        {
                            modOnVertexBuild(data);

                            // Adjust the Color
                            Color color = data.vertColor;
                            if (!pqsVersion.mapOcean)
                            {
                                color.a = 1f;
                            }
                            else if (height > pqsVersion.mapOceanHeight)
                            {
                                color.a = options.TransparentMaps ? 0f : 1f;
                            }
                            else
                            {
                                color = pqsVersion.mapOceanColor.A(1f);
                            }

                            // Set the Pixels
                            colorMapValues[y * pqsVersion.mapFilesize + x] = color;
                        }
                    }

                    yield return(null);
                }

                // Serialize the maps to disk
                String name = "KittopiaTech/PluginData/" + celestialBody.transform.name + "/";
                String path = KSPUtil.ApplicationRootPath + "/GameData/" + name;

                Directory.CreateDirectory(path);

                // Colormap
                if (options.ExportColor)
                {
                    // Save it
                    colorMap.SetPixels(colorMapValues);
                    yield return(null);

                    if (options.SaveToDisk)
                    {
                        File.WriteAllBytes(path + celestialBody.transform.name + "_Color.png", colorMap.EncodeToPNG());
                        colorMap.name = name + celestialBody.transform.name + "_Color.png";
                        yield return(null);
                    }

                    // Apply it
                    if (options.ApplyToScaled)
                    {
                        colorMap.Apply();
                        celestialBody.scaledBody.GetComponent <MeshRenderer>().material.SetTexture("_MainTex", colorMap);
                    }
                }

                if (options.ExportHeight)
                {
                    heightMap.SetPixels(heightMapValues);
                    yield return(null);

                    if (options.SaveToDisk)
                    {
                        File.WriteAllBytes(path + celestialBody.transform.name + "_Height.png",
                                           heightMap.EncodeToPNG());
                        yield return(null);
                    }

                    if (options.ExportNormal)
                    {
                        // Bump to Normal Map
                        Texture2D normalMap = Utility.BumpToNormalMap(heightMap, pqsVersion.radius, options.NormalStrength);
                        yield return(null);

                        if (options.SaveToDisk)
                        {
                            File.WriteAllBytes(path + celestialBody.transform.name + "_Normal.png",
                                               normalMap.EncodeToPNG());
                            normalMap.name = name + celestialBody.transform.name + "_Normal.png";
                            yield return(null);
                        }

                        // Apply it
                        if (options.ApplyToScaled)
                        {
                            normalMap.Apply();
                            celestialBody.scaledBody.GetComponent <MeshRenderer>().material
                            .SetTexture("_BumpMap", normalMap);
                        }
                    }
                }

                // Close the Renderer
                pqsVersion.enabled = true;
                pqsVersion.CloseExternalRender();

                // Declare that we're done
                ScreenMessages.RemoveMessage(message);
                ScreenMessages.PostScreenMessage("Operation completed in: " + (DateTime.Now - now).TotalMilliseconds + " ms", 2f, ScreenMessageStyle.UPPER_CENTER);
            }
Esempio n. 21
0
        /// <summary>
        /// Initializes a new instance of the OpenGLTexture2D class.
        /// </summary>
        /// <param name="uv">The Ultraviolet context.</param>
        /// <param name="pixels">A pointer to the raw pixel data with which to populate the texture.</param>
        /// <param name="width">The texture's width in pixels.</param>
        /// <param name="height">The texture's height in pixels.</param>
        /// <param name="bytesPerPixel">The number of bytes which represent each pixel in the raw data.</param>
        /// <param name="options">The texture's configuration options.</param>
        public OpenGLTexture2D(UltravioletContext uv, IntPtr pixels, Int32 width, Int32 height, Int32 bytesPerPixel, TextureOptions options)
            : base(uv)
        {
            Contract.EnsureRange(width > 0, nameof(width));
            Contract.EnsureRange(height > 0, nameof(height));
            Contract.EnsureRange(bytesPerPixel >= 3 || bytesPerPixel <= 4, nameof(bytesPerPixel));

            var isSrgb   = (options & TextureOptions.SrgbColor) == TextureOptions.SrgbColor;
            var isLinear = (options & TextureOptions.LinearColor) == TextureOptions.LinearColor;

            if (isSrgb && isLinear)
            {
                throw new ArgumentException(UltravioletStrings.TextureCannotHaveMultipleEncodings);
            }

            var caps        = uv.GetGraphics().Capabilities;
            var srgbEncoded = (isLinear ? false : (isSrgb ? true : uv.Properties.SrgbDefaultForTexture2D)) && caps.SrgbEncodingEnabled;

            var format         = OpenGLTextureUtil.GetFormatFromBytesPerPixel(bytesPerPixel);
            var internalformat = OpenGLTextureUtil.GetInternalFormatFromBytesPerPixel(bytesPerPixel, srgbEncoded);

            if (format == gl.GL_NONE || internalformat == gl.GL_NONE)
            {
                throw new NotSupportedException(OpenGLStrings.UnsupportedImageType);
            }

            CreateNativeTexture(uv, internalformat, width, height, format,
                                gl.GL_UNSIGNED_BYTE, (void *)pixels, (options & TextureOptions.ImmutableStorage) == TextureOptions.ImmutableStorage);
        }
Esempio n. 22
0
 /**
  * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024).
  * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024).
  * @param pTextureOptions the (quality) settings of the Texture.
  * @param pTextureStateListener to be informed when this {@link Texture} is loaded, unloaded or a {@link ITextureSource} failed to load.
  */
 public Texture(int pWidth, int pHeight, TextureOptions pTextureOptions, ITextureStateListener pTextureStateListener) /* throws IllegalArgumentException */ {
     Init(pWidth, pHeight, pTextureOptions, pTextureStateListener);
 }
Esempio n. 23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OpenGLDynamicTexture2D"/> class.
 /// </summary>
 /// <param name="uv">The Ultraviolet context.</param>
 /// <param name="width">The texture's width in pixels.</param>
 /// <param name="height">The texture's height in pixels.</param>
 /// <param name="depth">The texture's depth in pixels.</param>
 /// <param name="options">The texture's configuration options.</param>
 /// <param name="state">An arbitrary state object which will be passed to the flush handler.</param>
 /// <param name="flushed">The handler to invoke when the texture is flushed.</param>
 public OpenGLDynamicTexture3D(UltravioletContext uv, Int32 width, Int32 height, Int32 depth, TextureOptions options, Object state, Action <Texture3D, Object> flushed)
     : base(uv, width, height, depth, options, state, flushed)
 {
     this.texture = new OpenGLTexture3D(uv, width, height, depth, options);
 }
Esempio n. 24
0
        /**
         * @param pWidth must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024).
         * @param pHeight must be a power of 2 (i.e. 32, 64, 128, 256, 512, 1024).
         * @param pTextureOptions the (quality) settings of the Texture.
         * @param pTextureStateListener to be informed when this {@link Texture} is loaded, unloaded or a {@link ITextureSource} failed to load.
         */
        protected void Init(int pWidth, int pHeight, TextureOptions pTextureOptions, ITextureStateListener pTextureStateListener) /* throws IllegalArgumentException */ {
            if (!MathUtils.IsPowerOfTwo(pWidth) || !MathUtils.IsPowerOfTwo(pHeight))
            {
                throw new IllegalArgumentException("Width and Height of a Texture must be a power of 2!");
            }

            this.mWidth = pWidth;
            this.mHeight = pHeight;
            this.mTextureOptions = pTextureOptions;
            this.mTextureStateListener = pTextureStateListener;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="DynamicTextureAtlas"/> class.
        /// </summary>
        /// <param name="uv">The Ultraviolet context.</param>
        /// <param name="width">The width of the texture atlas in pixels.</param>
        /// <param name="height">The height of the texture atlas in pixels.</param>
        /// <param name="spacing">The number of pixels between cells on the texture atlas.</param>
        /// <param name="options">The texture's configuration options.</param>
        private DynamicTextureAtlas(UltravioletContext uv, Int32 width, Int32 height, Int32 spacing, TextureOptions options)
            : base(uv)
        {
            Contract.EnsureRange(width > 0, nameof(width));
            Contract.EnsureRange(height > 0, nameof(height));
            Contract.EnsureRange(spacing >= 0, nameof(spacing));

            var isSrgb   = (options & TextureOptions.SrgbColor) == TextureOptions.SrgbColor;
            var isLinear = (options & TextureOptions.LinearColor) == TextureOptions.LinearColor;

            if (isSrgb && isLinear)
            {
                throw new ArgumentException(UltravioletStrings.TextureCannotHaveMultipleEncodings);
            }

            var caps        = uv.GetGraphics().Capabilities;
            var srgbEncoded = (isLinear ? false : (isSrgb ? true : uv.Properties.SrgbDefaultForTexture2D)) && caps.SrgbEncodingEnabled;
            var surfOptions = (srgbEncoded ? SurfaceOptions.SrgbColor : SurfaceOptions.LinearColor);

            this.IsFlipped = Ultraviolet.GetGraphics().Capabilities.FlippedTextures;

            this.Width   = width;
            this.Height  = height;
            this.Spacing = spacing;
            this.Surface = Surface2D.Create(width, height, surfOptions);
            this.Texture = Texture2D.CreateDynamicTexture(width, height, options, this, (dt2d, state) =>
            {
                ((DynamicTextureAtlas)state).Flush();
            });

            Clear(true);
            Invalidate();
        }
 /// <summary>
 /// Creates a new <see cref="TextureDescription" />.
 /// </summary>
 /// <param name="width">The width.</param>
 /// <param name="height">The height.</param>
 /// <param name="mipCount">Number of mipmaps, set to true to have all mipmaps, set to an int &gt;=1 for a particular mipmap count.</param>
 /// <param name="format">Describes the format to use.</param>
 /// <param name="textureFlags">true if the texture needs to support unordered read write.</param>
 /// <param name="arraySize">Size of the texture 2D array, default to 1.</param>
 /// <param name="usage">The usage.</param>
 /// <param name="multisampleCount">The multisample count.</param>
 /// <returns>A new instance of <see cref="TextureDescription" /> class.</returns>
 public static TextureDescription New2D(int width, int height, MipMapCount mipCount, PixelFormat format, TextureFlags textureFlags = TextureFlags.ShaderResource, int arraySize = 1, GraphicsResourceUsage usage = GraphicsResourceUsage.Default, MultisampleCount multisampleCount = MultisampleCount.None, TextureOptions textureOptions = TextureOptions.None)
 {
     return(New2D(width, height, format, textureFlags, mipCount, arraySize, usage, multisampleCount, textureOptions));
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="OpenGLTexture3D"/> class.
        /// </summary>
        /// <param name="uv">The Ultraviolet context.</param>
        /// <param name="width">The texture's width in pixels.</param>
        /// <param name="height">The texture's height in pixels.</param>
        /// <param name="depth">The texture's depth in layers.</param>
        /// <param name="options">The texture's configuration options.</param>
        public OpenGLTexture3D(UltravioletContext uv, Int32 width, Int32 height, Int32 depth, TextureOptions options)
            : base(uv)
        {
            Contract.EnsureRange(width > 0, nameof(width));
            Contract.EnsureRange(height > 0, nameof(height));
            Contract.EnsureRange(depth > 0, nameof(depth));

            var isLinear = (options & TextureOptions.LinearColor) == TextureOptions.LinearColor;
            var isSrgb   = (options & TextureOptions.SrgbColor) == TextureOptions.SrgbColor;

            if (isLinear && isSrgb)
            {
                throw new ArgumentException(UltravioletStrings.TextureCannotHaveMultipleEncodings);
            }

            var caps        = uv.GetGraphics().Capabilities;
            var srgbEncoded = isLinear ? false : (isSrgb ? true : uv.Properties.SrgbDefaultForSurface3D) && caps.SrgbEncodingEnabled;

            var format         = OpenGLTextureUtil.GetFormatFromBytesPerPixel(4);
            var internalformat = OpenGLTextureUtil.GetInternalFormatFromBytesPerPixel(4, srgbEncoded);

            CreateNativeTexture(uv, internalformat, width, height, depth, format, gl.GL_UNSIGNED_BYTE, null, immutable);
        }
Esempio n. 28
0
        private static int Main(string[] _args)
        {
            Trace.Write("------------ {1} {0} --------------", Assembly.GetExecutingAssembly().GetName().Version.ToString(), Assembly.GetExecutingAssembly().GetName().Name);

            /*if (!Debugger.IsAttached)
             * {
             *      AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
             * }*/
            //Unlike yoyogames. i see NO issue with running a debugger here :D
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            GMLCompile.Test();
            GMLCompile.Code_Init();
            HTMLRunner             = "C:\\source\\GameMaker\\Runner\\HTML5\\scripts";
            Verbose                = false;
            CompileVerbose         = false;
            Out                    = Console.Out;
            SplashOmit             = true;
            TextureType            = new eTexType[2];
            SeparateOpaqueAndAlpha = false;
            DisplaySortedTextures  = false;
            RemoveDND              = true;
            CenterHTML5Game        = false;
            NoCache                = false;
            HTMLRunner             = string.Empty;
            NoIndexHTML            = false;
            TextureGroups          = new Dictionary <string, List <string> >();
            DoObfuscate            = false;
            ObfuscateObfuscate     = true;
            ObfuscatePrettyPrint   = false;
            ObfuscateRemoveUnused  = true;
            ObfuscateEncodeStrings = true;
            LoadingBarName         = null;
            CustomLoadingScreen    = false;
            ExitCode               = 0;
            InhibitErrorOutput     = false;
            string PreObfuscateLib = string.Empty;

            TextureScale = 1;
            Studio       = false;
            m_options    = new OptionSet().Add("?|help", "display help usage", (Action <string>) delegate
            {
                ShowHelp();
            }).Add("m=|machine=", "set machine type (ios, psp, win, droid)", delegate(string m)
            {
                SetMachineType(m);
            }).Add("t=|tex=", "override opaque texture type (dxt,raw,pvr,png)", delegate(string s)
            {
                TextureType[0] = SetTextureType(s);
            })
                           .Add("at=|alphatex=", "override alpha texture type (dxt,raw,pvr,png)", delegate(string s)
            {
                TextureType[1] = SetTextureType(s);
            })
                           .Add("o=|outputDir=", "set output directory", delegate(string d)
            {
                OutputDir = d;
            })
                           .Add("w=|tpageWidth=", "set texture page width", delegate(int w)
            {
                TexturePageWidth = w;
            })
                           .Add("h=|tpageHeight=", "set texture page height", delegate(int h)
            {
                TexturePageHeight = h;
            })
                           .Add("wt|writeTextures", "optionally write textures generated to output directory", (Action <string>) delegate
            {
                WriteTextures = true;
            })
                           .Add("ww|writeWaves", "optionally write audio waves generated to output directory", (Action <string>) delegate
            {
                WriteTextures = true;
            })
                           .Add("so|splashOmit", "optionally disable writing of the Spash screen to output file", (Action <string>) delegate
            {
                SplashOmit = true;
            })
                           .Add("dst|DisplaySortedTextures", "optionally display sorted texture information", (Action <string>) delegate
            {
                DisplaySortedTextures = true;
            })
                           .Add("c|compile", "do not display gui compile only", (Action <string>) delegate
            {
                CompileOnly = true;
            })
                           .Add("s|separate", "separate the alpha and opaque textures (false by default)", (Action <string>) delegate
            {
                SeparateOpaqueAndAlpha = true;
            })
                           .Add("v|verbose", "output verbose debug info", (Action <string>) delegate
            {
                Verbose = true;
            })
                           .Add("nohtml", "do not output index.html", (Action <string>) delegate
            {
                NoIndexHTML = true;
            })
                           .Add("HTMLRunner=", "directory with HTML Runner (will be copied as scripts)", delegate(string d)
            {
                HTMLRunner = d;
            })
                           .Add("tg=|TextureGroup=", "Group resources onto texture pages comma param is a filename, file has format <groupname> : <comma delim list of resourcenames>, use # for comment (NOTE: entries MUST all be on the same line", delegate(string f)
            {
                string[] array4 = File.ReadAllLines(f);
                string[] array5 = array4;
                foreach (string text3 in array5)
                {
                    string text4 = text3.Trim().Replace(" ", "").Replace("\t", "");
                    if (!string.IsNullOrEmpty(text4) && !text4.StartsWith("#"))
                    {
                        string[] array6 = text4.Split(':');
                        if (array6.Length == 2)
                        {
                            string[] collection2 = array6[1].Split(',');
                            string key           = array6[0];
                            List <string> value  = new List <string>(collection2);
                            TextureGroups.Add(key, value);
                        }
                    }
                }
            })
                           .Add("to=|TextureOption=", "Set an option for a set of textures via <option> : <comma delimited list of resourcenames>. Valid options are: " + TextureOptions.ValidTextureOptions() + ")", delegate(string f)
            {
                string[] array  = File.ReadAllLines(f);
                string[] array2 = array;
                foreach (string text in array2)
                {
                    string text2 = text.Trim().Replace(" ", "").Replace("\t", "");
                    if (!string.IsNullOrEmpty(text2) && !text2.StartsWith("#"))
                    {
                        string[] array3 = text2.Split(':');
                        if (array3.Length == 2)
                        {
                            string[] collection     = array3[1].Split(',');
                            string optionName       = array3[0];
                            List <string> resources = new List <string>(collection);
                            TextureOptions.AddResourceOptions(optionName, resources);
                        }
                    }
                }
            })
                           .Add("nodnd", "remove any Drag and Drop (dnd)", (Action <string>) delegate
            {
                RemoveDND = true;
            })
                           .Add("obfuscate|ob", "obfuscate the Javascript output", (Action <string>) delegate
            {
                DoObfuscate = true;
            })
                           .Add("obfuscateDo=|obob=", "Really do the obfuscation (default true)", delegate(bool v)
            {
                ObfuscateObfuscate = v;
            })
                           .Add("obfuscatePrettyPrint=|obpp=", "when obfuscating Pretty Print the output (default false)", delegate(bool v)
            {
                ObfuscatePrettyPrint = v;
            })
                           .Add("obfuscateRemoveUnused=|obru=", "when obfuscating Remove Unused functions from the output (default true)", delegate(bool v)
            {
                ObfuscateRemoveUnused = v;
            })
                           .Add("obfuscateEncodeStrings=|obes=", "when obfuscating Encode strings in the output (default true)", delegate(bool v)
            {
                ObfuscateEncodeStrings = v;
            })
                           .Add("compileVerbose|cv", "switch on verbose mode when compiling the GML (default false)", (Action <string>) delegate
            {
                CompileVerbose = true;
            })
                           .Add("c_html5", "Center the HTML5 game in the browser", (Action <string>) delegate
            {
                CenterHTML5Game = true;
            })
                           .Add("nocache_html5", "Add the \"no cache\" option to the default index.html page", (Action <string>) delegate
            {
                NoCache = true;
            })
                           .Add("preObfuscateLib=|pob=", "Pre-Obfuscate a directory of JS files into a single file - keep GM public interface", delegate(string v)
            {
                PreObfuscateLib = v;
            })
                           .Add("textureScale=|ts=", "scale textures by an integer amount (default 1)", delegate(int v)
            {
                TextureScale = v;
            })
                           .Add("loadingbarcallback=", "Name of the loading bar callback function", delegate(string v)
            {
                LoadingBarName = v;
            })
                           .Add("customloadingimage", "Use the custom screen provided?", (Action <string>) delegate
            {
                CustomLoadingScreen = true;
            })
                           .Add("studio", "Enable Studio use...", (Action <string>) delegate
            {
                Studio = true;
            });
            List <string> list = m_options.Parse(_args);

            if (!string.IsNullOrEmpty(PreObfuscateLib))
            {
                DoPreObfuscateLib(PreObfuscateLib, OutputDir);
                return(ExitCode);
            }
            GMAssets gMAssets = null;

            foreach (string item in list)
            {
                if (File.Exists(item))
                {
                    gMAssets = Loader.Load(item);
                }
            }
            if (MachineType == null)
            {
                SetMachineType("ios");
            }
            if (gMAssets == null)
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Filter           = "Exe files (*.exe, *.ios, *.psp, *.win, *.droid)|*.exe;*.ios;*.psp;*.win;*.droid|All files (*.*)|*.*";
                openFileDialog.FilterIndex      = 1;
                openFileDialog.RestoreDirectory = true;
                if (openFileDialog.ShowDialog() != DialogResult.OK)
                {
                    return(-1);
                }
                gMAssets = Loader.Load(openFileDialog.FileName);
            }
            if (OutputDir == null)
            {
                if (gMAssets != null)
                {
                    OutputDir = Path.GetDirectoryName(gMAssets.FileName);
                }
            }
            Assets = gMAssets;
            if (!CompileOnly)
            {
                Application.Run(new Form1(gMAssets));
            }
            else
            {
                string extension = MachineType.Extension;
                if (Studio)
                {
                    extension = ".zip";
                }
                string name = Path.Combine(OutputDir, Path.ChangeExtension(Path.GetFileName(gMAssets.FileName), extension));
                switch (MachineType.OutputType)
                {
                case eOutputType.eWAD:
                    IFFSaver.Save(gMAssets, name);
                    break;

                case eOutputType.eHTML5:
                    HTML5Saver.Save(gMAssets, name);
                    break;
                }
            }
            return(ExitCode);
        }
Esempio n. 29
0
 /// <summary>
 /// Initializes a new instance of the OpenGLTexture2D class.
 /// </summary>
 /// <param name="uv">The Ultraviolet context.</param>
 /// <param name="width">The texture's width in pixels.</param>
 /// <param name="height">The texture's height in pixels.</param>
 /// <param name="options">The texture's configuration options.</param>
 /// <returns>The instance of Texture2D that was created.</returns>
 public OpenGLTexture2D(UltravioletContext uv, Int32 width, Int32 height, TextureOptions options)
     : this(uv, IntPtr.Zero, width, height, 4, options)
 {
 }
        private static TextureDescription New2D(int width, int height, PixelFormat format, TextureFlags textureFlags, int mipCount, int arraySize, GraphicsResourceUsage usage, MultisampleCount multisampleCount, TextureOptions textureOptions = TextureOptions.None)
        {
            if ((textureFlags & TextureFlags.UnorderedAccess) != 0)
            {
                usage = GraphicsResourceUsage.Default;
            }

            var desc = new TextureDescription
            {
                Dimension        = TextureDimension.Texture2D,
                Width            = width,
                Height           = height,
                Depth            = 1,
                ArraySize        = arraySize,
                MultisampleCount = multisampleCount,
                Flags            = textureFlags,
                Format           = format,
                MipLevels        = Texture.CalculateMipMapCount(mipCount, width, height),
                Usage            = Texture.GetUsageWithFlags(usage, textureFlags),
                Options          = textureOptions
            };

            return(desc);
        }
Esempio n. 31
0
 /// <summary>
 /// Creates a new 2D <see cref="Texture" /> with a single mipmap.
 /// </summary>
 /// <param name="device">The <see cref="GraphicsDevice"/>.</param>
 /// <param name="width">The width.</param>
 /// <param name="height">The height.</param>
 /// <param name="format">Describes the format to use.</param>
 /// <param name="textureFlags">true if the texture needs to support unordered read write.</param>
 /// <param name="arraySize">Size of the texture 2D array, default to 1.</param>
 /// <param name="usage">The usage.</param>
 /// <returns>A new instance of 2D <see cref="Texture" /> class.</returns>
 public static Texture New2D(GraphicsDevice device, int width, int height, PixelFormat format, TextureFlags textureFlags = TextureFlags.ShaderResource, int arraySize = 1, GraphicsResourceUsage usage = GraphicsResourceUsage.Default, TextureOptions options = TextureOptions.None)
 {
     return(New2D(device, width, height, false, format, textureFlags, arraySize, usage, options));
 }
        /// <summary>
        /// Creates a new instance of the <see cref="DynamicTextureAtlas"/> class.
        /// </summary>
        /// <param name="width">The texture's width in pixels.</param>
        /// <param name="height">The texture's height in pixels.</param>
        /// <param name="spacing">The number of pixels between cells on the texture atlas.</param>
        /// <param name="options">The texture's configuration options.</param>
        /// <returns>The instance of <see cref="DynamicTextureAtlas"/> that was created.</returns>
        public static DynamicTextureAtlas Create(Int32 width, Int32 height, Int32 spacing, TextureOptions options = TextureOptions.Default)
        {
            var uv = UltravioletContext.DemandCurrent();

            return(new DynamicTextureAtlas(uv, width, height, spacing, options));
        }
Esempio n. 33
0
 /// <summary>
 /// Creates a new 2D <see cref="Texture" /> with a single level of mipmap.
 /// </summary>
 /// <typeparam name="T">Type of the pixel data to upload to the texture.</typeparam>
 /// <param name="device">The <see cref="GraphicsDevice"/>.</param>
 /// <param name="width">The width.</param>
 /// <param name="height">The height.</param>
 /// <param name="format">Describes the format to use.</param>
 /// <param name="textureData">The texture data for a single mipmap and a single array slice. See remarks</param>
 /// <param name="textureFlags">true if the texture needs to support unordered read write.</param>
 /// <param name="usage">The usage.</param>
 /// <returns>A new instance of 2D <see cref="Texture" /> class.</returns>
 /// <remarks>
 /// Each value in textureData is a pixel in the destination texture.
 /// </remarks>
 public static unsafe Texture New2D <T>(GraphicsDevice device, int width, int height, PixelFormat format, T[] textureData, TextureFlags textureFlags = TextureFlags.ShaderResource, GraphicsResourceUsage usage = GraphicsResourceUsage.Immutable, TextureOptions options = TextureOptions.None) where T : struct
 {
     return(New2D(device, width, height, 1, format, new[] { GetDataBox(format, width, height, 1, textureData, (IntPtr)Interop.Fixed(textureData)) }, textureFlags, 1, usage, MultisampleCount.None, options));
 }