You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Silk.Net读取纹理颜色数据仅获单行而非全部行的问题排查

Direct3D11读取纹理数据不完整问题

我在测试从纹理读取数据时,发现最终得到的数组数据不完整。

我通过自定义Texture类创建源纹理:

texture = new Texture();

texture.Create(videoManager.Device, new Vector2i(3, 2), [
    new Color(1, 2, 3, 4), new Color(5, 6, 7, 8), new Color(9, 10, 11, 12), 
    new Color(13, 14, 15, 16), new Color(17, 18, 19, 20), new Color(21, 22, 23, 24)
    ]);

随后创建Staging Texture:

var testTexture = Texture.CreateStagged(videoManager.Device, texture.Size);

Texture类的CreateStagged方法实现:

public unsafe static ComPtr<ID3D11Texture2D> CreateStagged(ComPtr<ID3D11Device> device, Vector2i size)
{
    ComPtr<ID3D11Texture2D> texture = default;

    var texture2DDesc = new Texture2DDesc()
    {
        Width = (uint)size.X,
        Height = (uint)size.Y,
        ArraySize = 1,
        BindFlags = (uint)BindFlag.None,
        Usage = Usage.Staging,
        CPUAccessFlags = (uint)CpuAccessFlag.Read,
        Format = Format.FormatR8G8B8A8Unorm,
        MipLevels = 1,
        MiscFlags = (uint)ResourceMiscFlag.None,
        SampleDesc = new SampleDesc(1, 0),
    };

    CrashHandler.CheckForError(device.CreateTexture2D(texture2DDesc, Unsafe.NullRef<SubresourceData>(), ref texture), "Stagged Texture creation error");

    return texture;
}

接着将源纹理复制到testTexture,映射资源并把数据复制到字节数组:

videoManager.DeviceContext.CopyResource(testTexture, texture.texture);

var mappedSubresource = new MappedSubresource();

mappedSubresource.RowPitch = (uint)texture.Size.X * 4; // 不确定是否有必要

videoManager.DeviceContext.Map(testTexture, 0, Map.Read, 0, ref mappedSubresource);

byte[] data = new byte[texture.Size.X * texture.Size.Y * 4];

fixed (byte* pData = data)
{
    System.Buffer.MemoryCopy(mappedSubresource.PData, pData, data.Length, data.Length);
}

videoManager.DeviceContext.Unmap(testTexture, 0);

输出data数组内容时,只得到0-12的数值(预期是0-24):

for (int i = 0; i < data.Length; i++)
{
    Console.WriteLine((int)data[i]);
}

已确认源纹理正确,能正常显示在屏幕上。当把纹理尺寸改为[2,3]时,仅显示0-8的数值,怀疑问题出在两点:

  • 映射资源仅将单维度数据复制到MappedSubresource;
  • 从mappedSubresource.PData复制到pData的过程存在错误。

内容的提问来源于stack exchange,提问作者Kordi3112

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 06:13:22