alien_fx_fiend

LongBow WireFrame Animation Tweaks= Done Completed!!!

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