【问题标题】:Strange behaviour when adding doubles添加双打时的奇怪行为
【发布时间】:2020-08-06 13:24:26
【问题描述】:

我正在做一个 Direct3D 项目,在我的代码中有一个函数,它接受一个双精度作为参数,这个双精度代表自上一帧以来的时间,我的想法是将这个时间与另一个代表角度的双精度相加立方体的旋转,然后将新值存储为新角度,但在调试后我注意到从零开始的角度(在代码中称为 rot )在第一帧跳到大约 79800 的值,每次它略有不同,但总是 79 作为第一个数字,我真的不明白问题是什么。

这是每帧的运行:

double rot = 0.0f;
double seconds = 0.0;
unsigned int frames = 0;

// this is the function used to render a single frame
void RenderFrame(double time)
{
    // clear the back buffer to a deep blue
    devcon->ClearRenderTargetView(renderTarget, D3DXCOLOR(0.0f, 0.2f, 0.4f, 1.0f));
    devcon->ClearDepthStencilView(stencilView, D3D11_CLEAR_DEPTH, 1.0f, 0);

    //PROBLEM HERE
    //////
    rot += time;
    //////


    VSCBdata.transformation = XMMatrixTranspose(XMMatrixRotationX(rot) * XMMatrixRotationZ(rot) * XMMatrixTranslation(0.0f, 0.0f, 4.0f) * XMMatrixPerspectiveLH(1.0f, 1.0f, 0.5f, 10.0f));

    devcon->UpdateSubresource(VSConstantBuffer, 0, NULL, &VSCBdata, 0, 0);

    // draw the vertex buffer to the back buffer
    devcon->DrawIndexed(ARRAYSIZE(indices), 0, 0);

    VSCBdata.transformation = XMMatrixTranspose(XMMatrixRotationY(rot) * XMMatrixRotationZ(rot) * XMMatrixTranslation(0.0f, 2.0f, 6.0f) * XMMatrixPerspectiveLH(1.0f, 1.0f, 0.5f, 10.0f));

    devcon->UpdateSubresource(VSConstantBuffer, 0, NULL, &VSCBdata, 0, 0);

    // draw the vertex buffer to the back buffer
    devcon->DrawIndexed(ARRAYSIZE(indices), 0, 0);

    // do 3D rendering on the back buffer here

    // switch the back buffer and the front buffer
    swapchain->Present(0, 0);
}

这是计算所经过时间的代码:

double frequency = 0.0;
__int64 start = 0;
__int64 lastFrame = 0;

void StartTimer()
{
    LARGE_INTEGER shish;
    QueryPerformanceFrequency(&shish);
    frequency = double(shish.QuadPart);
    QueryPerformanceCounter(&shish);
    start = shish.QuadPart;
}

double GetTime()
{
    LARGE_INTEGER time;
    QueryPerformanceCounter(&time);
    return (time.QuadPart - start) / frequency;
}

double GetFrameTime()
{
    LARGE_INTEGER time;
    QueryPerformanceCounter(&time);
    __int64 result = time.QuadPart - lastFrame;
    lastFrame = time.QuadPart;
    if (result < 0.0) result = 0.0;
    return double(result)/frequency;
}

【问题讨论】:

  • 时间的单位是什么?
  • 请删除所有不需要的代码以使问题仍然发生。
  • 除非时间以弧度为单位,否则您需要一个转换因子。

标签: c++ visual-studio double


【解决方案1】:

由于lastFrame 被初始化为0,对GetFrameTime 的第一次调用将以秒为单位返回QueryPerformanceCounter 的值。

您应该在程序开始时调用一次GetFrameTime 并丢弃该值或在StartTimer 中初始化lastFrame

【讨论】:

  • 我已将 StartTimer 中的 lastFrame 初始化为 shish.QuadPart,现在它可以完美运行,非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-27
  • 1970-01-01
  • 1970-01-01
  • 2021-02-15
  • 1970-01-01
  • 2017-09-05
  • 1970-01-01
相关资源
最近更新 更多