alien_fx_fiend

LongBow WireFrame Animation D2D-Win32 (Bkp b4 Tweaking Arrow Top Enter Position)

May 30th, 2025
545
0
Never
8
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 16.09 KB | Source Code | 0 0
  1. ==++ Here's the full code for "BowAndArrow.cpp"::: ++==
  2. //  BowAndArrow.cpp
  3. //  Simple Win32 / Direct2D demo - "wireframe longbow"
  4. //  Build: cl /EHsc /DUNICODE /D_UNICODE BowAndArrow.cpp d2d1.lib user32.lib gdi32.lib
  5.  
  6. #include <windows.h>
  7. #include <d2d1.h>
  8. #include <chrono>
  9. #include <cmath>
  10. #include <algorithm>
  11. #pragma comment(lib, "d2d1")
  12.  
  13. // -------------------------------------------------
  14. // Small RAII helper to release COM objects
  15. // -------------------------------------------------
  16. template<class T> void SafeRelease(T** pp)
  17. {
  18.    if (*pp) { (*pp)->Release(); *pp = nullptr; }
  19. }
  20.  
  21. // -------------------------------------------------
  22. // Animation constants
  23. // -------------------------------------------------
  24. constexpr float  COCK_TIME = 1.0f;   // seconds
  25. constexpr float  HOLD_TIME = 0.5f;   // seconds
  26. constexpr float  FIRE_TIME = 1.0f;   // seconds
  27. constexpr UINT   TIMER_ID = 1;
  28. constexpr UINT   TIMER_MS = 16;     // ~60 FPS
  29.  
  30. enum class AnimStage { Cocking, Hold, Firing, Done };
  31. constexpr float ARROW_REST_OFFSET = 500.0f;   // pixels in-front of bow ( > 0 )
  32.  
  33. // String pull distance (pixels) and bow X center
  34. constexpr float STRING_MAX_PULL = 180.0f;
  35. constexpr float CX_BOW = 220.0f;
  36.  
  37. // -------------------------------------------------
  38. // Global state (kept simple for a demo)
  39. // -------------------------------------------------
  40. HWND                    g_hWnd = nullptr;
  41. ID2D1Factory* g_pFactory = nullptr;
  42. ID2D1HwndRenderTarget* g_pRenderTarget = nullptr;
  43. ID2D1SolidColorBrush* g_pBrush = nullptr;
  44.  
  45. float g_windowW = 1280.0f;
  46. float g_windowH = 720.0f;
  47. // Modify g_arrowPosX initialization to start off-screen at the top
  48. float g_arrowPosX = CX_BOW;   // Will be properly positioned in animation update
  49. // Add these with other global variables
  50. float g_arrowPosY = 0.0f;       // Variable for arrow's vertical position
  51. float g_arrowRotation = 0.0f;   // Rotation angle in radians
  52.  
  53. // Geometry helpers (depend on window height, so they are updated in WM_SIZE)
  54. float cx = CX_BOW;
  55. float topY = 120.0f;
  56. float bottomY = 600.0f;   // will be overwritten in WM_SIZE
  57. float midY = 360.0f;
  58. float halfHeight = 240.0f;
  59.  
  60. // Animation variables
  61. AnimStage   g_stage = AnimStage::Cocking;
  62. float       g_timeInStage = 0.0f;        // seconds
  63. auto        g_prevTick = std::chrono::high_resolution_clock::now();
  64. float       g_stringOffset = 0.0f;        // 0 = relaxed, 1 = fully drawn
  65. //float       g_arrowPosX = 0.0f;        // head position
  66.  
  67. // -------------------------------------------------
  68. // Helpers
  69. // -------------------------------------------------
  70. float Lerp(float a, float b, float t) { return a + (b - a) * t; }
  71.  
  72. // Create or re-create render target
  73. HRESULT CreateDeviceResources()
  74. {
  75.     if (g_pRenderTarget) return S_OK;
  76.  
  77.     RECT rc; GetClientRect(g_hWnd, &rc);
  78.  
  79.     D2D1_SIZE_U size = D2D1::SizeU(rc.right - rc.left,
  80.         rc.bottom - rc.top);
  81.  
  82.     HRESULT hr = g_pFactory->CreateHwndRenderTarget(
  83.         D2D1::RenderTargetProperties(),
  84.         D2D1::HwndRenderTargetProperties(g_hWnd, size),
  85.         &g_pRenderTarget);
  86.  
  87.     if (SUCCEEDED(hr))
  88.         hr = g_pRenderTarget->CreateSolidColorBrush(
  89.             D2D1::ColorF(D2D1::ColorF::White), &g_pBrush);
  90.  
  91.     return hr;
  92. }
  93.  
  94. void DiscardDeviceResources()
  95. {
  96.     SafeRelease(&g_pBrush);
  97.     SafeRelease(&g_pRenderTarget);
  98. }
  99.  
  100. // -------------------------------------------------
  101. // Core rendering
  102. // -------------------------------------------------
  103. void OnRender()
  104. {
  105.     if (FAILED(CreateDeviceResources()))
  106.         return;
  107.  
  108.     g_pRenderTarget->BeginDraw();
  109.     g_pRenderTarget->Clear(D2D1::ColorF(0x202020)); // dark bg
  110.  
  111.     // -------------------------------------------------
  112.     // 1. Draw Bow limbs (two quadratic curves)
  113.     // -------------------------------------------------
  114.     ID2D1PathGeometry* pGeom = nullptr;
  115.     ID2D1GeometrySink* pSink = nullptr;
  116.     if (SUCCEEDED(g_pFactory->CreatePathGeometry(&pGeom)))
  117.     {
  118.         pGeom->Open(&pSink);
  119.  
  120.         //--------------------------------------------------------------
  121.         //  One continuous ")"-shaped limb with a slightly pointy tip.
  122.         //  End-points stay on the string ( (cx, topY) & (cx, bottomY) )
  123.         //--------------------------------------------------------------
  124.         constexpr float NOSE = 35.0f;               // how far the tips stick out
  125.         const     float BULGE = halfHeight * 0.5f;  // max belly distance (x)
  126.  
  127.         pSink->BeginFigure(D2D1::Point2F(cx, topY), D2D1_FIGURE_BEGIN_HOLLOW);
  128.  
  129.         // Draw semicircle bow with pointy tip at middle
  130.         // First quarter - top to middle-top
  131.         pSink->AddBezier(
  132.             D2D1::BezierSegment(
  133.                 D2D1::Point2F(cx + NOSE, topY + halfHeight * 0.1f),      // slight curve at top
  134.                 D2D1::Point2F(cx + BULGE, topY + halfHeight * 0.5f),     // first quarter curve
  135.                 D2D1::Point2F(cx + BULGE + NOSE, midY - NOSE)));         // approaching tip
  136.  
  137.         // Middle part with pointy tip
  138.         pSink->AddBezier(
  139.             D2D1::BezierSegment(
  140.                 D2D1::Point2F(cx + BULGE + NOSE * 1.2f, midY - NOSE * 0.5f),  // curve to tip
  141.                 D2D1::Point2F(cx + BULGE + NOSE * 1.5f, midY),               // pointy tip
  142.                 D2D1::Point2F(cx + BULGE + NOSE * 1.2f, midY + NOSE * 0.5f)));  // curve from tip
  143.  
  144.         // Last quarter - middle-bottom to bottom
  145.         pSink->AddBezier(
  146.             D2D1::BezierSegment(
  147.                 D2D1::Point2F(cx + BULGE + NOSE, midY + NOSE),            // after tip
  148.                 D2D1::Point2F(cx + BULGE, bottomY - halfHeight * 0.5f),   // last quarter curve
  149.                 D2D1::Point2F(cx + NOSE, bottomY - halfHeight * 0.1f)));  // approaching bottom
  150.  
  151.         // Connect back to string
  152.         pSink->AddBezier(
  153.             D2D1::BezierSegment(
  154.                 D2D1::Point2F(cx + NOSE * 0.5f, bottomY - NOSE * 0.25f),  // curve to bottom
  155.                 D2D1::Point2F(cx, bottomY),                              // bottom endpoint
  156.                 D2D1::Point2F(cx, bottomY)));                            // dummy point (required)
  157.  
  158.         pSink->EndFigure(D2D1_FIGURE_END_OPEN);
  159.  
  160.         pSink->Close();
  161.         g_pRenderTarget->DrawGeometry(pGeom, g_pBrush, 2.0f);
  162.  
  163.         SafeRelease(&pSink);
  164.         SafeRelease(&pGeom);
  165.     }
  166.  
  167.     // -------------------------------------------------
  168.     // 2. Draw Bow string
  169.     // -------------------------------------------------
  170.     float pull = g_stringOffset * STRING_MAX_PULL;
  171.     D2D1_POINT_2F p1 = D2D1::Point2F(cx, topY);
  172.     D2D1_POINT_2F pm = D2D1::Point2F(cx - pull, midY);
  173.     D2D1_POINT_2F p2 = D2D1::Point2F(cx, bottomY);
  174.  
  175.     g_pRenderTarget->DrawLine(p1, pm, g_pBrush, 2.0f);
  176.     g_pRenderTarget->DrawLine(pm, p2, g_pBrush, 2.0f);
  177.  
  178.     // Replace the OnRender arrow drawing section with this to use variable Y position
  179. // Replace the OnRender arrow drawing section with this to use variable Y position and rotation
  180. // Replace the OnRender arrow drawing section with this to use variable Y position and rotation
  181. // -------------------------------------------------
  182. // 3. Draw Arrow (simple shaft + head + tail)
  183. // -------------------------------------------------
  184.     float arrowLen = 240.0f;
  185.     float arrowHead = 18.0f;
  186.  
  187.     // Apply rotation to the arrow
  188.     g_pRenderTarget->SetTransform(
  189.         D2D1::Matrix3x2F::Rotation(
  190.             g_arrowRotation * (180.0f / 3.14159f), // Convert radians to degrees
  191.             D2D1::Point2F(g_arrowPosX, g_arrowPosY)
  192.         )
  193.     );
  194.  
  195.     // Shaft
  196.     g_pRenderTarget->DrawLine(
  197.         D2D1::Point2F(g_arrowPosX, g_arrowPosY),
  198.         D2D1::Point2F(g_arrowPosX - arrowLen, g_arrowPosY),
  199.         g_pBrush, 2.0f);
  200.  
  201.     // Arrow head (small triangle)
  202.     D2D1_POINT_2F headPts[3] = {
  203.         D2D1::Point2F(g_arrowPosX,                 g_arrowPosY),
  204.         D2D1::Point2F(g_arrowPosX - arrowHead,     g_arrowPosY - arrowHead * 0.5f),
  205.         D2D1::Point2F(g_arrowPosX - arrowHead,     g_arrowPosY + arrowHead * 0.5f)
  206.     };
  207.     g_pRenderTarget->DrawLine(headPts[0], headPts[1], g_pBrush, 2.0f);
  208.     g_pRenderTarget->DrawLine(headPts[0], headPts[2], g_pBrush, 2.0f);
  209.  
  210.     // Fletching (3 short diagonal lines)
  211.     const float fletch = 20.0f;
  212.     const float step = 5.0f;
  213.     // Top fletching
  214.     for (int i = 0; i < 6; ++i)
  215.     {
  216.         float x = g_arrowPosX - arrowLen + i * step;
  217.         g_pRenderTarget->DrawLine(
  218.             D2D1::Point2F(x, g_arrowPosY),
  219.             D2D1::Point2F(x - fletch, g_arrowPosY - fletch * 0.4f + i * 3.0f),
  220.             g_pBrush, 2.0f);
  221.     }
  222.     // Bottom fletching
  223.     for (int i = 0; i < 6; ++i)
  224.     {
  225.         float x = g_arrowPosX - arrowLen + i * step;
  226.         g_pRenderTarget->DrawLine(
  227.             D2D1::Point2F(x, g_arrowPosY),
  228.             D2D1::Point2F(x - fletch, g_arrowPosY + fletch * 0.4f - i * 3.0f),
  229.             g_pBrush, 2.0f);
  230.     }
  231.  
  232.     // Reset transform for other drawing operations
  233.     g_pRenderTarget->SetTransform(D2D1::Matrix3x2F::Identity());
  234.  
  235.     // Present
  236.     HRESULT hr = g_pRenderTarget->EndDraw();
  237.     if (hr == D2DERR_RECREATE_TARGET)
  238.         DiscardDeviceResources();
  239. }
  240.  
  241. // -------------------------------------------------
  242. // Animation tick (called from WM_TIMER)
  243. // -------------------------------------------------
  244. // Replace the UpdateAnimation function with this updated version
  245. // Replace the UpdateAnimation function with this updated version
  246. void UpdateAnimation()
  247. {
  248.     // Compute delta time
  249.     auto  now = std::chrono::high_resolution_clock::now();
  250.     float dt = std::chrono::duration<float>(now - g_prevTick).count();
  251.     g_prevTick = now;
  252.     g_timeInStage += dt;
  253.  
  254.     switch (g_stage)
  255.     {
  256.     case AnimStage::Cocking:
  257.     {
  258.         float t = min(g_timeInStage / COCK_TIME, 1.0f);
  259.  
  260.         if (t < 0.6f) {
  261.             // First part: arrow dropping from top with tail pointing down
  262.             float arcT = t / 0.6f;  // Normalize to 0-1 for just this part
  263.  
  264.             // Starting position at top, end at bow position
  265.             float startX = cx + 100.0f;    // Start slightly right of bow
  266.             float startY = 0.0f;           // Start at top of screen
  267.             float endX = cx + 50.0f;       // End to the right of bow
  268.             float endY = midY - 50.0f;     // End slightly above midpoint
  269.  
  270.             // Calculate curved path
  271.             g_arrowPosX = Lerp(startX, endX, arcT);
  272.             g_arrowPosY = Lerp(startY, endY, arcT * arcT); // Accelerate down
  273.  
  274.             // Arrow has tail pointing down (pointing up = -90 degrees = -PI/2)
  275.             g_arrowRotation = -1.57079f + arcT * 1.07079f; // -PI/2 to close to 0
  276.         }
  277.         else if (t < 0.8f) {
  278.             // Second part: arrow rotates to horizontal and moves into position
  279.             float alignT = (t - 0.6f) / 0.2f;  // Normalize to 0-1 for just this part
  280.  
  281.             // Move arrow into position horizontally
  282.             float startX = cx + 50.0f;
  283.             float startY = midY - 50.0f;
  284.             float endX = cx + 50.0f;  // Position just right of the bow
  285.             float endY = midY;        // At the midpoint height
  286.  
  287.             g_arrowPosX = Lerp(startX, endX, alignT);
  288.             g_arrowPosY = Lerp(startY, endY, alignT);
  289.  
  290.             // Complete the rotation to horizontal
  291.             g_arrowRotation = Lerp(-0.5f, 0.0f, alignT); // Finish rotating to horizontal
  292.         }
  293.         else {
  294.             // Third part: arrow attaches to string and string gets pulled
  295.             float stringT = (t - 0.8f) / 0.2f;  // Normalize to 0-1 for just this part
  296.  
  297.             // Move arrow with string as it's drawn back
  298.             float startX = cx + 50.0f;
  299.             float endX = cx - STRING_MAX_PULL + 50.0f;
  300.  
  301.             g_arrowPosX = Lerp(startX, endX, stringT);
  302.             g_arrowPosY = midY;
  303.             g_arrowRotation = 0.0f;  // Keep horizontal
  304.  
  305.             // Pull string back gradually
  306.             g_stringOffset = stringT;
  307.         }
  308.  
  309.         if (t >= 1.0f) { g_stage = AnimStage::Hold; g_timeInStage = 0.f; }
  310.     } break;
  311.  
  312.     case AnimStage::Hold:
  313.         // Arrow is now at the correct position
  314.         g_arrowPosY = midY;
  315.         g_arrowRotation = 0.0f;  // Ensure arrow is horizontal
  316.  
  317.         if (g_timeInStage >= HOLD_TIME)
  318.         {
  319.             g_stage = AnimStage::Firing; g_timeInStage = 0.f;
  320.         }
  321.         break;
  322.  
  323.     case AnimStage::Firing:
  324.     {
  325.         float t = min(g_timeInStage / FIRE_TIME, 1.0f);
  326.         g_stringOffset = 1.0f - t;             // 1 -> 0  (same)
  327.  
  328.         float startX = cx - STRING_MAX_PULL + 50.0f;
  329.         float endX = g_windowW + 100.0f;
  330.         g_arrowPosX = Lerp(startX, endX, t);
  331.         g_arrowPosY = midY; // Keep arrow on straight horizontal path
  332.         g_arrowRotation = 0.0f;  // Keep arrow horizontal
  333.  
  334.         if (t >= 1.0f)
  335.         {
  336.             g_stage = AnimStage::Cocking; g_timeInStage = 0.f;
  337.             // Reset arrow to starting position for next animation cycle
  338.             g_arrowPosX = cx + 100.0f;
  339.             g_arrowPosY = 0.0f;
  340.             g_arrowRotation = -1.57079f;  // Start with tail pointing down (arrow pointing up)
  341.         }
  342.     } break;
  343.  
  344.     case AnimStage::Done:
  345.         // Not used anymore, but kept for completeness
  346.         break;
  347.     }
  348.  
  349.     // Request redraw
  350.     InvalidateRect(g_hWnd, nullptr, FALSE);
  351. }
  352.  
  353. // -------------------------------------------------
  354. // Window procedure
  355. // -------------------------------------------------
  356. LRESULT CALLBACK WndProc(HWND hWnd, UINT msg,
  357.     WPARAM wParam, LPARAM lParam)
  358. {
  359.     switch (msg)
  360.     {
  361.         // Add this initialization in WM_CREATE or before animation starts
  362.     // Add to WM_CREATE case or main initialization
  363.     // Add this initialization in WM_CREATE case
  364.     case WM_CREATE:
  365.         if (FAILED(D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED,
  366.             &g_pFactory)))
  367.             return -1; // abort window creation
  368.         SetTimer(hWnd, TIMER_ID, TIMER_MS, nullptr);
  369.         g_prevTick = std::chrono::high_resolution_clock::now();
  370.         g_arrowPosX = cx + 100.0f;   // Initialize right of bow
  371.         g_arrowPosY = 0.0f;          // Initialize at top of screen
  372.         g_arrowRotation = -1.57079f; // Start with tail pointing down (arrow pointing up)
  373.         return 0;
  374.  
  375.     case WM_SIZE:
  376.     {
  377.         g_windowW = static_cast<float>(LOWORD(lParam));
  378.         g_windowH = static_cast<float>(HIWORD(lParam));
  379.  
  380.         // Update dependent geometry values
  381.         topY = 120.0f;
  382.         bottomY = g_windowH - 120.0f;
  383.         midY = (topY + bottomY) * 0.5f;
  384.         halfHeight = (bottomY - topY) * 0.5f;
  385.  
  386.         if (g_pRenderTarget)
  387.             g_pRenderTarget->Resize(
  388.                 D2D1::SizeU(static_cast<UINT>(g_windowW),
  389.                     static_cast<UINT>(g_windowH)));
  390.     }
  391.     return 0;
  392.  
  393.     case WM_TIMER:
  394.         if (wParam == TIMER_ID)
  395.             UpdateAnimation();
  396.         return 0;
  397.  
  398.     case WM_PAINT:
  399.     {
  400.         PAINTSTRUCT ps;
  401.         BeginPaint(hWnd, &ps);
  402.         OnRender();
  403.         EndPaint(hWnd, &ps);
  404.     } return 0;
  405.  
  406.     case WM_DESTROY:
  407.         KillTimer(hWnd, TIMER_ID);
  408.         DiscardDeviceResources();
  409.         SafeRelease(&g_pFactory);
  410.         PostQuitMessage(0);
  411.         return 0;
  412.     }
  413.     return DefWindowProc(hWnd, msg, wParam, lParam);
  414. }
  415.  
  416. // -------------------------------------------------
  417. // WinMain - entry point
  418. // -------------------------------------------------
  419. int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, PWSTR, int nCmdShow)
  420. {
  421.     const wchar_t CLASS_NAME[] = L"BowWindow";
  422.  
  423.     WNDCLASS wc = {};
  424.     wc.lpfnWndProc = WndProc;
  425.     wc.hInstance = hInst;
  426.     wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
  427.     wc.lpszClassName = CLASS_NAME;
  428.     RegisterClass(&wc);
  429.  
  430.     g_hWnd = CreateWindowEx(0, CLASS_NAME, L"Direct2D - Longbow Demo",
  431.         WS_OVERLAPPEDWINDOW,
  432.         CW_USEDEFAULT, CW_USEDEFAULT,
  433.         static_cast<int>(g_windowW),
  434.         static_cast<int>(g_windowH),
  435.         nullptr, nullptr, hInst, nullptr);
  436.  
  437.     ShowWindow(g_hWnd, nCmdShow);
  438.  
  439.     // Main message loop
  440.     MSG msg;
  441.     while (GetMessage(&msg, nullptr, 0, 0))
  442.     {
  443.         TranslateMessage(&msg);
  444.         DispatchMessage(&msg);
  445.     }
  446.     return 0;
  447. }
  448. ```
Advertisement
Comments
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
Add Comment
Please, Sign In to add comment