Example #1
0
        public override void updateRenderState(Graphics.Material m, RenderState state)
        {
            if (myLightVisualizer == null)
            {
                myLightVisualizer = Renderer.visualizers["light"] as LightVisualizer;
            }

            //material properties
            PerPixelUniformData matData = new PerPixelUniformData
            {
                ambientReflectivity  = m.ambient,
                diffuseReflectivity  = m.diffuse,
                specularReflectivity = m.spec,
                emmission            = m.emission,
                shininess            = m.shininess,
                alpha = m.alpha
            };

            //setup diffuse map, it should exists
            ArrayTexture tex = (m.findAttribute("texArray") as TextureAttribute).value() as ArrayTexture;

            state.setTexture((int)tex.id(), 0, TextureTarget.Texture2DArray);
            state.setUniform(new UniformData(20, Uniform.UniformType.Int, 0));

            //setup the lights that influence this terrain
            byte[] data = matData.toBytes();
            state.setUniformUpload(myMaterialUniform, data);
            state.setUniformBuffer(myMaterialUniform.id, 3);
            state.setUniformBuffer(myLightVisualizer.myLightUniforBuffer.id, 1);
        }
Example #2
0
 public TextureCache(
     GraphicsDevice graphicsDevice,
     uint initialLayerCount = 8,
     uint maxTextureLayers  = 32)
 {
     _entries          = new FreeList <CacheEntry>();
     _strongHandles    = new List <FreeListHandle>();
     _maxTextureLayers = maxTextureLayers;
     _now         = FrameStamp.Invalid;
     _rgbaTexture = new ArrayTexture(
         graphicsDevice,
         PixelFormat.R8_G8_B8_A8_UNorm,
         initialLayerCount
         );
     _r8Texture = new ArrayTexture(
         graphicsDevice,
         PixelFormat.R8_UNorm,
         initialLayerCount
         );
     _uvRectCache = new GpuCache <TextureLocation>(
         graphicsDevice,
         TextureLocation.SizeInGpuBlocks,
         dimension: 256
         );
 }
Example #3
0
        public static bool button(ArrayTexture t, int idx, Vector2 size)
        {
            Window win = currentWindow;

            if (win.skipItems)
            {
                return(false);
            }

            string name = t.ToString() + "-" + idx.ToString();
            UInt32 id   = win.getChildId(name);
            Rect   r    = Rect.fromPosSize(win.cursorScreenPosition + style.framePadding, size);

            bool hovered;
            bool held;
            bool pressed = buttonBehavior(r, id, out hovered, out held);

            //draw the thing (need to convert to screen space)
            Vector2 min = new Vector2(r.left, ImGui.displaySize.Y - r.top);
            Vector2 max = new Vector2(r.right, ImGui.displaySize.Y - r.bottom);
            RenderTexture2dCommand cmd = new RenderTexture2dCommand(min, max, t, idx, pressed ? .25f : 1.0f);

            win.canvas.addCustomRenderCommand(cmd);
            win.canvas.addRect(r, style.colors[(int)ElementColor.Border], style.frameRounding);

            //update the window cursor
            win.addItem(size);

            return(pressed);
        }
Example #4
0
        private void CreateTextureArray(DeviceContext context, List <Texture2D> textureArray)
        {
            //Create the Icon texture Array
            ArrayTexture.CreateTexture2D(context, textureArray.ToArray(), "Icon's ArrayTexture", out _iconsTextureArray);

            // indexes into array corresponds textures with modifier +1 (Air)
            _iconTextureArray = new SpriteTexture(IconSize, IconSize, _iconsTextureArray, new Vector2());
        }
 /// <summary>
 /// Release all the managed resources
 /// </summary>
 public void Release()
 {
     if (ArrayTexture != null)
     {
         ArrayTexture.Destroy();
         ArrayTexture = null;
     }
 }
Example #6
0
 public static void createTextureArray()
 {
     if (myGenerateTextures)
     {
         ArrayTextureDescriptor td = new ArrayTextureDescriptor(myTextureFilenames.ToArray(), true);
         myMaterialTextureArray = Renderer.resourceManager.getResource(td) as ArrayTexture;
         visualMaterial.addAttribute(new TextureAttribute("texArray", myMaterialTextureArray));
     }
 }
Example #7
0
        private void CreateTextureArray(string directoryName, string path, string fileFilters, SharpDX.DXGI.Format ArrayTextureCompressionMode)
        {
            //Get File names from Directory
            Texture2D textureArray = ArrayTexture.CreateImageArrayFromFiles(_engine.ImmediateContext, Directory.GetFiles(path, fileFilters), FilterFlags.Point, ArrayTextureCompressionMode);

            Texture2D.ToFile(_engine.ImmediateContext, textureArray, ImageFileFormat.Dds, path + @"\Array" + directoryName + ".dds");

            textureArray.Dispose();
        }
        public override void LoadContent(DeviceContext context)
        {
            ArrayTexture.CreateTexture2DFromFiles(_d3dEngine.Device, context, ClientSettings.TexturePack + @"Particules/", @"*.png", FilterFlags.Point, "ArrayTexture_Particules", out _particulesSpritesResource);
            ToDispose(_particulesSpritesResource);

            _staticEntityEmitter = new SpriteStaticEmitter(this, DXStates.Samplers.UVWrap_MinMagMipLinear, _particulesSpritesResource, DXStates.Rasters.Default, DXStates.Blenders.Enabled, DXStates.DepthStencils.DepthReadEnabled, _weather);
            AddEmitter(context, _staticEntityEmitter);

            base.LoadContent(context);
        }
Example #9
0
            static async UniTask BackToMainThread(ArrayTexture arrayTexture, Vector3i size, ValueTypeRentMemory <ColorByte> buffer, FrameTimingPoint timingPoint, CancellationToken ct)
            {
                try {
                    await timingPoint.Next(ct);

                    arrayTexture.Load(new(size.X, size.Y), size.Z, buffer.AsSpan());
                }
                finally {
                    buffer.Dispose();
                }
            }
Example #10
0
        public CommonColors()
        {
            var texture = new ArrayTexture <byte>(
                AssetId.None,
                "CommonColors",
                1, 1, Palette.Count,
                Palette.OrderBy(x => x.Value).Select(x => (byte)x.Key).ToArray());

            foreach (var entry in Palette.OrderBy(x => x.Value))
            {
                texture.AddRegion(0, 0, 1, 1, (int)entry.Value);
            }

            BorderTexture = texture;
        }
        public override void updateRenderState(Graphics.Material m, RenderState state)
        {
            if (myLightVisualizer == null)
            {
                myLightVisualizer = Renderer.visualizers["light"] as LightVisualizer;
            }

            //setup diffuse map, it should exists
            ArrayTexture tex = (m.findAttribute("texArray") as TextureAttribute).value() as ArrayTexture;

            state.setTexture((int)tex.id(), 0, TextureTarget.Texture2DArray);
            state.setUniform(new UniformData(20, Uniform.UniformType.Int, 0));

            //setup the lights that influence this terrain
            state.setUniformBuffer(myLightVisualizer.myLightUniforBuffer.id, 1);
        }
Example #12
0
        public override void LoadContent(DeviceContext context)
        {
            ArrayTexture.CreateTexture2DFromFiles(_engine.Device, context, ClientSettings.TexturePack + @"Cracks/", @"ct*.png", TexturePackConfig.Current.Settings.enuSamplingFilter, "ArrayTexture_Cracks", out _cracksArray);
            ToDispose(_cracksArray);

            _cubeVb = ToDispose(new VertexBuffer <VertexMesh>(context.Device, _cubeMeshBluePrint.Vertices.Length, SharpDX.Direct3D.PrimitiveTopology.TriangleList, "Cracks Block VB"));
            _cubeIb = ToDispose(new IndexBuffer <ushort>(context.Device, _cubeMeshBluePrint.Indices.Length, "Cracks Block IB"));

            _cubeVb.SetData(context, _cubeMeshBluePrint.Vertices);
            _cubeIb.SetData(context, _cubeMeshBluePrint.Indices);

            _cubeEffect = ToDispose(new HLSLCracks(context.Device, ClientSettings.EffectPack + @"Terran/Cracks.hlsl", VertexMesh.VertexDeclaration));
            _cubeEffect.DiffuseTexture.Value = _cracksArray;
            _cubeEffect.SamplerDiffuse.Value = RenderStatesRepo.GetSamplerState(DXStates.Samplers.UVClamp_MinMagMipPoint);

            base.LoadContent(context);
        }
        /// <summary>
        /// Launches the Texture2DArray generation (already handles NeedsToUpdateVolumeTexture and alwaysGenerateOnUpdate parameters check)
        /// </summary>
        public void Generate()
        {
            if (NeedsToUpdateTexture || alwaysGenerateOnUpdate)
            {
                if (_texturesList.Count > 0)
                {
                    if (NeedsToUpdateTexture)
                    {
                        if (ArrayTexture != null)
                        {
                            ArrayTexture.Destroy();
                            ArrayTexture = null;
                        }

                        ArrayTexture = new Texture2DArray(RequiredSizeX, RequiredSizeY, _texturesList.Count, _requiredTextureFormat, false, _linear);
                    }

                    for (int i = 0; i < _texturesList.Count; ++i)
                    {
                        Graphics.CopyTexture(_texturesList[i], 0, 0, 0, 0, RequiredSizeX, RequiredSizeY, ArrayTexture, i, 0, 0, 0);
                    }

                    HasTexture = true;
                }
                else
                {
                    if (ArrayTexture != null)
                    {
                        ArrayTexture.Destroy();
                        ArrayTexture = null;
                    }
                    HasTexture = false;
                }

                NeedsToUpdateTexture = false;

                RaiseTextureUpdatedEvent();
            }
        }
Example #14
0
        /// <summary>
        /// Allows to load world effects and textures or to reload textures
        /// </summary>
        /// <param name="context"></param>
        public void InitDrawComponents(DeviceContext context)
        {
            if (this.IsInitialized)
            {
                UnloadDrawComponents();
            }

            //Create Biomes Colors texture Array

            ArrayTexture.CreateTexture2DFromFiles(_d3dEngine.Device, context, ClientSettings.TexturePack + @"BiomesColors/", @"*.png", FilterFlags.Point, "BiomesColors_WorldChunk", out _biomesColors_View, SharpDX.DXGI.Format.BC1_UNorm);

            _terra_View = VisualWorldParameters.CubeTextureManager.CubeArrayTexture;
            //ArrayTexture.CreateTexture2DFromFiles(_d3dEngine.Device, context, ClientSettings.TexturePack + @"Terran/", @"ct*.png", TexturePackConfig.Current.Settings.enuSamplingFilter, "ArrayTexture_WorldChunk", out _terra_View);
            ArrayTexture.CreateTexture2DFromFiles(_d3dEngine.Device, context, ClientSettings.TexturePack + @"AnimatedTextures/", @"*.png", FilterFlags.Point, "ArrayTexture_AnimatedTextures", out _textureAnimation_View, SharpDX.DXGI.Format.BC4_UNorm);


            _terraEffect = new HLSLTerran(_d3dEngine.Device, ClientSettings.EffectPack + @"Terran/Terran.hlsl", VertexCubeSolid.VertexDeclaration, SharedFrameCb.CBPerFrame);
            _terraEffect.TerraTexture.Value      = _terra_View;
            _terraEffect.SamplerDiffuse.Value    = RenderStatesRepo.GetSamplerState(TexturePackConfig.Current.Settings.enuTexMipCreationFilteringId);
            _terraEffect.SamplerBackBuffer.Value = RenderStatesRepo.GetSamplerState(DXStates.Samplers.UVClamp_MinMagMipPoint);
            _terraEffect.BiomesColors.Value      = _biomesColors_View;
            _terraEffect.SkyBackBuffer.Value     = _skyBackBuffer.RenderTextureView;

            _liquidEffect = new HLSLLiquid(_d3dEngine.Device, ClientSettings.EffectPack + @"Terran/Liquid.hlsl", VertexCubeLiquid.VertexDeclaration, SharedFrameCb.CBPerFrame);
            _liquidEffect.TerraTexture.Value      = _terra_View;
            _liquidEffect.SamplerDiffuse.Value    = RenderStatesRepo.GetSamplerState(TexturePackConfig.Current.Settings.enuTexMipCreationFilteringId);
            _liquidEffect.SamplerOverlay.Value    = RenderStatesRepo.GetSamplerState(DXStates.Samplers.UVWrap_MinMagMipLinear);
            _liquidEffect.SamplerBackBuffer.Value = RenderStatesRepo.GetSamplerState(DXStates.Samplers.UVClamp_MinMagMipPoint);
            _liquidEffect.BiomesColors.Value      = _biomesColors_View;
            _liquidEffect.AnimatedTextures.Value  = _textureAnimation_View;
            _liquidEffect.SkyBackBuffer.Value     = _skyBackBuffer.RenderTextureView;

            _voxelModelEffect          = ToDispose(new HLSLVoxelModel(_d3dEngine.Device, ClientSettings.EffectPack + @"Entities\VoxelModel.hlsl", VertexVoxel.VertexDeclaration));
            _voxelModelInstancedEffect = ToDispose(new HLSLVoxelModelInstanced(_d3dEngine.Device, ClientSettings.EffectPack + @"Entities\VoxelModelInstanced.hlsl", VoxelInstanceData.VertexDeclaration));
            _voxelModelInstancedEffect.SamplerBackBuffer.Value = RenderStatesRepo.GetSamplerState(DXStates.Samplers.UVClamp_MinMagMipPoint);
        }
        private void CreateTextureResources(DeviceContext context, FilterFlags MIPfilterFlag)
        {
            if (CubeArrayTexture != null)
            {
                RemoveToDispose(CubeArrayTexture);
                CubeArrayTexture.Dispose();
            }
            CubeArrayTexture = null;

            ImageLoadInformation ImageInfo = new ImageLoadInformation()
            {
                FirstMipLevel  = 0,
                Usage          = ResourceUsage.Staging,
                BindFlags      = BindFlags.None,
                CpuAccessFlags = CpuAccessFlags.Write | CpuAccessFlags.Read,
                OptionFlags    = ResourceOptionFlags.None,
                Format         = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
                Filter         = FilterFlags.None,
                MipFilter      = MIPfilterFlag
            };

            List <Texture2D> cubeTextures = new List <Texture2D>();

            //Get all file and create a list of stream !
            foreach (string file in Directory.GetFiles(ClientSettings.TexturePack + @"Terran/", @"*.png").OrderBy(x => x))
            {
                var meta = CubeTexturesMeta[Path.GetFileNameWithoutExtension(file)];

                if (meta.isAnimated)
                {
                    //Split file into small pieces and create Texture2D from it
                    Bitmap    animatedTex = new Bitmap(file);
                    Bitmap    frameTex    = new Bitmap(meta.Size.Width, meta.Size.Width);
                    Rectangle frameRect   = new Rectangle(0, 0, meta.Size.Width, meta.Size.Width);
                    using (Graphics gr = Graphics.FromImage(frameTex))
                    {
                        int       rows       = meta.Size.Height / meta.Size.Width;
                        Rectangle sourceRect = new Rectangle(0, 0, meta.Size.Width, meta.Size.Width);
                        for (int row = 0; row < rows; row++)
                        {
                            // Copy the frame of the image.
                            gr.DrawImage(animatedTex, frameRect, sourceRect, GraphicsUnit.Pixel);
                            //Save into a memoryStream
                            using (MemoryStream textureMemoryStream = new MemoryStream())
                            {
                                frameTex.Save(textureMemoryStream, System.Drawing.Imaging.ImageFormat.Png);
                                textureMemoryStream.Position = 0;
                                Texture2D newTexture = Texture2D.FromStream <Texture2D>(_engine.Device, textureMemoryStream, (int)textureMemoryStream.Length, ImageInfo);
                                cubeTextures.Add(newTexture);
                            }
                            sourceRect.Y += meta.Size.Width;
                        }
                    }

                    frameTex.Dispose();
                    animatedTex.Dispose();
                }
                else
                {
                    Texture2D newTexture = Texture2D.FromFile <Texture2D>(_engine.Device, file, ImageInfo);
                    cubeTextures.Add(newTexture);
                }
            }

            //2 Creation of the TextureArray resource
            ArrayTexture.CreateTexture2D(context, cubeTextures.ToArray(), "CubeTexturesArray", out CubeArrayTexture, ImageInfo.Format);

            //Disposing resources used to create the texture array
            foreach (Texture2D tex in cubeTextures)
            {
                tex.Dispose();
            }

            ToDispose(CubeArrayTexture);
        }
Example #16
0
        private static UniTask BuildTexture(PMXObject pmx, ResourceFile pmxFile, Model3D model, UnsafeRawArray <SkinnedVertex> vertices, CancellationToken ct)
        {
            var arrayTexture = new ArrayTexture(TextureConfig.BilinearRepeat);

            model.AddComponent(arrayTexture);

            var dir             = ResourcePath.GetDirectoryName(pmxFile.Name);
            var textureNames    = pmx.TextureList.AsSpan();
            var resourcePackage = pmxFile.Package;

            var materials = pmx.MaterialList.AsSpan();

            using var matTexMem = new ValueTypeRentMemory <int>(materials.Length, true);
            var matTex = matTexMem.AsSpan();

            for (int i = 0; i < materials.Length; i++)
            {
                matTex[i] = materials[i].Texture;
            }
            matTex.Sort();
            var texCount = 0;

            if (matTex.Length > 0)
            {
                texCount = 1;
                for (int i = 1; i < matTex.Length; i++)
                {
                    if (matTex[i - 1] != matTex[i])
                    {
                        texCount++;
                    }
                }
            }

            using var textureUsed = new ValueTypeRentMemory <bool>(textureNames.Length, true);

            var size   = new Vector2i(1024, 1024);  // TODO:
            var count  = 0;
            var buffer = new ValueTypeRentMemory <ColorByte>(size.X * size.Y * texCount, false);

            try {
                for (int i = 0; i < textureNames.Length; i++)
                {
                    if (matTex.Contains(i) == false)
                    {
                        continue;
                    }

                    using var _ = GetTexturePath(dir, textureNames[i], out var texturePath, out var ext);
                    var path = texturePath.ToString();

                    // Some pmx have the texture paths that don't exist. (Nobody references them.)
                    // So skip them.
                    if (resourcePackage.TryGetStream(path, out var stream) == false)
                    {
                        continue;
                    }
                    textureUsed[i] = true;
                    var dest = buffer.AsSpan(count * size.X * size.Y);
                    try {
                        using var image = Image.LoadToImageSource(stream, Image.GetTypeFromExt(ext));
                        if (image.Width != size.X || image.Height != size.Y)
                        {
                            using var resized = Image.Resized(image, size);
                            resized.GetPixels().CopyTo(dest);
                        }
                        else
                        {
                            image.GetPixels().CopyTo(dest);
                        }
                        count++;
                    }
                    finally {
                        stream.Dispose();
                    }
                }

                // Calculate texture index of each vertex
                {
                    var indices = pmx.SurfaceList.AsSpan().MarshalCast <Surface, int>();
                    int i       = 0;
                    foreach (var mat in materials)
                    {
                        for (int j = 0; j < mat.VertexCount; j++)
                        {
                            var unusedCount = 0;
                            foreach (var isUsed in textureUsed.AsSpan(0, mat.Texture))
                            {
                                if (isUsed == false)
                                {
                                    unusedCount++;
                                }
                            }
                            vertices[indices[i++]].TextureIndex = mat.Texture - unusedCount;
                        }
                    }
                }
            }
            catch {
                buffer.Dispose();
                throw;
            }
            return(BackToMainThread(arrayTexture, new Vector3i(size.X, size.Y, count), buffer, model.Screen !.TimingPoints.Update, ct));