Advertisement
alien_fx_fiend

Alt# Pool Modfiication By ChatGPT4o (MAY BE BROKEN)

Jun 27th, 2025 (edited)
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 191.22 KB | Source Code | 0 0
  1. #define WIN32_LEAN_AND_MEAN
  2. #define NOMINMAX
  3. #include <windows.h>
  4. #include <d2d1.h>
  5. #include <dwrite.h>
  6. #include <fstream> // For file I/O
  7. #include <iostream> // For some basic I/O, though not strictly necessary for just file ops
  8. #include <vector>
  9. #include <cmath>
  10. #include <string>
  11. #include <sstream> // Required for wostringstream
  12. #include <algorithm> // Required for std::max, std::min
  13. #include <ctime>    // Required for srand, time
  14. #include <cstdlib> // Required for srand, rand (often included by others, but good practice)
  15. #include <commctrl.h> // Needed for radio buttons etc. in dialog (if using native controls)
  16. #include <mmsystem.h> // For PlaySound
  17. #include <tchar.h> //midi func
  18. #include <thread>
  19. #include <atomic>
  20. #include "resource.h"
  21.  
  22. #pragma comment(lib, "Comctl32.lib") // Link against common controls library
  23. #pragma comment(lib, "d2d1.lib")
  24. #pragma comment(lib, "dwrite.lib")
  25. #pragma comment(lib, "Winmm.lib") // Link against Windows Multimedia library
  26.  
  27. // --- Constants ---
  28. const float PI = 3.1415926535f;
  29. const float BALL_RADIUS = 10.0f;
  30. const float TABLE_LEFT = 100.0f;
  31. const float TABLE_TOP = 100.0f;
  32. const float TABLE_WIDTH = 700.0f;
  33. const float TABLE_HEIGHT = 350.0f;
  34. const float TABLE_RIGHT = TABLE_LEFT + TABLE_WIDTH;
  35. const float TABLE_BOTTOM = TABLE_TOP + TABLE_HEIGHT;
  36. const float CUSHION_THICKNESS = 20.0f;
  37. const float HOLE_VISUAL_RADIUS = 22.0f; // Visual size of the hole
  38. const float POCKET_RADIUS = HOLE_VISUAL_RADIUS * 1.05f; // Make detection radius slightly larger // Make detection radius match visual size (or slightly larger)
  39. const float MAX_SHOT_POWER = 15.0f;
  40. const float FRICTION = 0.985f; // Friction factor per frame
  41. const float MIN_VELOCITY_SQ = 0.01f * 0.01f; // Stop balls below this squared velocity
  42. const float HEADSTRING_X = TABLE_LEFT + TABLE_WIDTH * 0.30f; // 30% line
  43. const float RACK_POS_X = TABLE_LEFT + TABLE_WIDTH * 0.65f; // 65% line for rack apex
  44. const float RACK_POS_Y = TABLE_TOP + TABLE_HEIGHT / 2.0f;
  45. const UINT ID_TIMER = 1;
  46. const int TARGET_FPS = 60; // Target frames per second for timer
  47.  
  48. // --- Enums ---
  49. // --- MODIFIED/NEW Enums ---
  50. enum GameState {
  51.     SHOWING_DIALOG,     // NEW: Game is waiting for initial dialog input
  52.     PRE_BREAK_PLACEMENT,// Player placing cue ball for break
  53.     BREAKING,           // Player is aiming/shooting the break shot
  54.     AIMING,             // Player is aiming
  55.     AI_THINKING,        // NEW: AI is calculating its move
  56.     SHOT_IN_PROGRESS,   // Balls are moving
  57.     ASSIGNING_BALLS,    // Turn after break where ball types are assigned
  58.     PLAYER1_TURN,
  59.     PLAYER2_TURN,
  60.     BALL_IN_HAND_P1,
  61.     BALL_IN_HAND_P2,
  62.     SELECT_EIGHT_POCKET_P1,  // NEW: human must choose pocket for 8-Ball
  63.     SELECT_EIGHT_POCKET_P2,  // NEW: CPU must choose pocket for 8-Ball
  64.     GAME_OVER
  65. };
  66.  
  67. enum BallType {
  68.     NONE,
  69.     SOLID,  // Yellow (1-7)
  70.     STRIPE, // Red (9-15)
  71.     EIGHT_BALL, // Black (8)
  72.     CUE_BALL // White (0)
  73. };
  74.  
  75. // NEW Enums for Game Mode and AI Difficulty
  76. enum GameMode {
  77.     HUMAN_VS_HUMAN,
  78.     HUMAN_VS_AI
  79. };
  80.  
  81. enum AIDifficulty {
  82.     EASY,
  83.     MEDIUM,
  84.     HARD
  85. };
  86.  
  87. enum OpeningBreakMode {
  88.     CPU_BREAK,
  89.     P1_BREAK,
  90.     FLIP_COIN_BREAK
  91. };
  92.  
  93. // --- Structs ---
  94. struct Ball {
  95.     int id;             // 0=Cue, 1-7=Solid, 8=Eight, 9-15=Stripe
  96.     BallType type;
  97.     float x, y;
  98.     float vx, vy;
  99.     D2D1_COLOR_F color;
  100.     bool isPocketed;
  101. };
  102.  
  103. struct PlayerInfo {
  104.     BallType assignedType;
  105.     int ballsPocketedCount;
  106.     std::wstring name;
  107. };
  108.  
  109. // --- Global Variables ---
  110.  
  111. // Direct2D & DirectWrite
  112. ID2D1Factory* pFactory = nullptr;
  113. //ID2D1Factory* g_pD2DFactory = nullptr;
  114. ID2D1HwndRenderTarget* pRenderTarget = nullptr;
  115. IDWriteFactory* pDWriteFactory = nullptr;
  116. IDWriteTextFormat* pTextFormat = nullptr;
  117. IDWriteTextFormat* pLargeTextFormat = nullptr; // For "Foul!"
  118.  
  119. // Game State
  120. HWND hwndMain = nullptr;
  121. GameState currentGameState = SHOWING_DIALOG; // Start by showing dialog
  122. std::vector<Ball> balls;
  123. int currentPlayer = 1; // 1 or 2
  124. PlayerInfo player1Info = { BallType::NONE, 0, L"Player 1" };
  125. PlayerInfo player2Info = { BallType::NONE, 0, L"CPU" }; // Default P2 name
  126. bool foulCommitted = false;
  127. std::wstring gameOverMessage = L"";
  128. int selectedPocketIndex = 2;      // Default Top-Right pocket
  129. bool eightPocketSelected = false; // Has the pocket been chosen this turn?
  130. bool eightBallPocketed = false;
  131. bool firstBallPocketedAfterBreak = false;
  132. std::vector<int> pocketedThisTurn;
  133. // --- NEW: Foul Tracking Globals ---
  134. int firstHitBallIdThisShot = -1;      // ID of the first object ball hit by cue ball (-1 if none)
  135. bool cueHitObjectBallThisShot = false; // Did cue ball hit an object ball this shot?
  136. bool railHitAfterContact = false;     // Did any ball hit a rail AFTER cue hit an object ball?
  137. // --- End New Foul Tracking Globals ---
  138.  
  139. // NEW Game Mode/AI Globals
  140. GameMode gameMode = HUMAN_VS_HUMAN; // Default mode
  141. AIDifficulty aiDifficulty = MEDIUM; // Default difficulty
  142. OpeningBreakMode openingBreakMode = CPU_BREAK; // Default opening break mode
  143. bool isPlayer2AI = false;           // Is Player 2 controlled by AI?
  144. bool aiTurnPending = false;         // Flag: AI needs to take its turn when possible
  145. // bool aiIsThinking = false;       // Replaced by AI_THINKING game state
  146. // NEW: Flag to indicate if the current shot is the opening break of the game
  147. bool isOpeningBreakShot = false;
  148.  
  149. // NEW: For AI shot planning and visualization
  150. struct AIPlannedShot {
  151.     float angle;
  152.     float power;
  153.     float spinX;
  154.     float spinY;
  155.     bool isValid; // Is there a valid shot planned?
  156. };
  157. AIPlannedShot aiPlannedShotDetails; // Stores the AI's next shot
  158. bool aiIsDisplayingAim = false;    // True when AI has decided a shot and is in "display aim" mode
  159. int aiAimDisplayFramesLeft = 0;  // How many frames left to display AI aim
  160. const int AI_AIM_DISPLAY_DURATION_FRAMES = 45; // Approx 0.75 seconds at 60 FPS, adjust as needed
  161.  
  162. // Input & Aiming
  163. POINT ptMouse = { 0, 0 };
  164. bool isAiming = false;
  165. bool isDraggingCueBall = false;
  166. // --- ENSURE THIS LINE EXISTS HERE ---
  167. bool isDraggingStick = false; // True specifically when drag initiated on the stick graphic
  168. // --- End Ensure ---
  169. bool isSettingEnglish = false;
  170. D2D1_POINT_2F aimStartPoint = { 0, 0 };
  171. float cueAngle = 0.0f;
  172. float shotPower = 0.0f;
  173. float cueSpinX = 0.0f; // Range -1 to 1
  174. float cueSpinY = 0.0f; // Range -1 to 1
  175. float pocketFlashTimer = 0.0f;
  176. bool cheatModeEnabled = false; // Cheat Mode toggle (G key)
  177. int draggingBallId = -1;
  178. bool keyboardAimingActive = false; // NEW FLAG: true when arrow keys modify aim/power
  179. MCIDEVICEID midiDeviceID = 0; //midi func
  180. std::atomic<bool> isMusicPlaying(false); //midi func
  181. std::thread musicThread; //midi func
  182. void StartMidi(HWND hwnd, const TCHAR* midiPath);
  183. void StopMidi();
  184.  
  185. // UI Element Positions
  186. D2D1_RECT_F powerMeterRect = { TABLE_RIGHT + CUSHION_THICKNESS + 10, TABLE_TOP, TABLE_RIGHT + CUSHION_THICKNESS + 40, TABLE_BOTTOM };
  187. D2D1_RECT_F spinIndicatorRect = { TABLE_LEFT - CUSHION_THICKNESS - 60, TABLE_TOP + 20, TABLE_LEFT - CUSHION_THICKNESS - 20, TABLE_TOP + 60 }; // Circle area
  188. D2D1_POINT_2F spinIndicatorCenter = { spinIndicatorRect.left + (spinIndicatorRect.right - spinIndicatorRect.left) / 2.0f, spinIndicatorRect.top + (spinIndicatorRect.bottom - spinIndicatorRect.top) / 2.0f };
  189. float spinIndicatorRadius = (spinIndicatorRect.right - spinIndicatorRect.left) / 2.0f;
  190. D2D1_RECT_F pocketedBallsBarRect = { TABLE_LEFT, TABLE_BOTTOM + CUSHION_THICKNESS + 30, TABLE_RIGHT, TABLE_BOTTOM + CUSHION_THICKNESS + 70 };
  191.  
  192. // Corrected Pocket Center Positions (aligned with table corners/edges)
  193. const D2D1_POINT_2F pocketPositions[6] = {
  194.     {TABLE_LEFT, TABLE_TOP},                           // Top-Left
  195.     {TABLE_LEFT + TABLE_WIDTH / 2.0f, TABLE_TOP},      // Top-Middle
  196.     {TABLE_RIGHT, TABLE_TOP},                          // Top-Right
  197.     {TABLE_LEFT, TABLE_BOTTOM},                        // Bottom-Left
  198.     {TABLE_LEFT + TABLE_WIDTH / 2.0f, TABLE_BOTTOM},   // Bottom-Middle
  199.     {TABLE_RIGHT, TABLE_BOTTOM}                        // Bottom-Right
  200. };
  201.  
  202. // Colors
  203. const D2D1_COLOR_F TABLE_COLOR = D2D1::ColorF(0.1608f, 0.4000f, 0.1765f); // Darker Green NEWCOLOR (0.0f, 0.5f, 0.1f) => (0.1608f, 0.4000f, 0.1765f)
  204. //const D2D1_COLOR_F TABLE_COLOR = D2D1::ColorF(0.0f, 0.5f, 0.1f); // Darker Green NEWCOLOR (0.0f, 0.5f, 0.1f) => (0.1608f, 0.4000f, 0.1765f)
  205. const D2D1_COLOR_F CUSHION_COLOR = D2D1::ColorF(D2D1::ColorF(0.3608f, 0.0275f, 0.0078f)); // NEWCOLOR ::Red => (0.3608f, 0.0275f, 0.0078f)
  206. //const D2D1_COLOR_F CUSHION_COLOR = D2D1::ColorF(D2D1::ColorF::Red); // NEWCOLOR ::Red => (0.3608f, 0.0275f, 0.0078f)
  207. const D2D1_COLOR_F POCKET_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
  208. const D2D1_COLOR_F CUE_BALL_COLOR = D2D1::ColorF(D2D1::ColorF::White);
  209. const D2D1_COLOR_F EIGHT_BALL_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
  210. const D2D1_COLOR_F SOLID_COLOR = D2D1::ColorF(D2D1::ColorF::Yellow); // Solids = Yellow
  211. const D2D1_COLOR_F STRIPE_COLOR = D2D1::ColorF(D2D1::ColorF::Red);   // Stripes = Red
  212. const D2D1_COLOR_F AIM_LINE_COLOR = D2D1::ColorF(D2D1::ColorF::White, 0.7f); // Semi-transparent white
  213. const D2D1_COLOR_F FOUL_TEXT_COLOR = D2D1::ColorF(D2D1::ColorF::Red);
  214. const D2D1_COLOR_F TURN_ARROW_COLOR = D2D1::ColorF(0.1333f, 0.7294f, 0.7490f); //NEWCOLOR 0.1333f, 0.7294f, 0.7490f => ::Blue
  215. //const D2D1_COLOR_F TURN_ARROW_COLOR = D2D1::ColorF(D2D1::ColorF::Blue);
  216. const D2D1_COLOR_F ENGLISH_DOT_COLOR = D2D1::ColorF(D2D1::ColorF::Red);
  217. const D2D1_COLOR_F UI_TEXT_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
  218.  
  219. // --- Forward Declarations ---
  220. HRESULT CreateDeviceResources();
  221. void DiscardDeviceResources();
  222. void OnPaint();
  223. void OnResize(UINT width, UINT height);
  224. void InitGame();
  225. void GameUpdate();
  226. void UpdatePhysics();
  227. void CheckCollisions();
  228. bool CheckPockets(); // Returns true if any ball was pocketed
  229. void ProcessShotResults();
  230. void ApplyShot(float power, float angle, float spinX, float spinY);
  231. void RespawnCueBall(bool behindHeadstring);
  232. bool AreBallsMoving();
  233. void SwitchTurns();
  234. void AssignPlayerBallTypes(BallType firstPocketedType);
  235. void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed);
  236. Ball* GetBallById(int id);
  237. Ball* GetCueBall();
  238. //void PlayGameMusic(HWND hwnd); //midi func
  239. void AIBreakShot();
  240.  
  241. // Drawing Functions
  242. void DrawScene(ID2D1RenderTarget* pRT);
  243. void DrawTable(ID2D1RenderTarget* pRT, ID2D1Factory* pFactory);
  244. void DrawBalls(ID2D1RenderTarget* pRT);
  245. void DrawCueStick(ID2D1RenderTarget* pRT);
  246. void DrawAimingAids(ID2D1RenderTarget* pRT);
  247. void DrawUI(ID2D1RenderTarget* pRT);
  248. void DrawPowerMeter(ID2D1RenderTarget* pRT);
  249. void DrawSpinIndicator(ID2D1RenderTarget* pRT);
  250. void DrawPocketedBallsIndicator(ID2D1RenderTarget* pRT);
  251. void DrawBallInHandIndicator(ID2D1RenderTarget* pRT);
  252.  
  253. // Helper Functions
  254. float GetDistance(float x1, float y1, float x2, float y2);
  255. float GetDistanceSq(float x1, float y1, float x2, float y2);
  256. bool IsValidCueBallPosition(float x, float y, bool checkHeadstring);
  257. template <typename T> void SafeRelease(T** ppT);
  258. // --- ADD FORWARD DECLARATION FOR NEW HELPER HERE ---
  259. float PointToLineSegmentDistanceSq(D2D1_POINT_2F p, D2D1_POINT_2F a, D2D1_POINT_2F b);
  260. // --- End Forward Declaration ---
  261. bool LineSegmentIntersection(D2D1_POINT_2F p1, D2D1_POINT_2F p2, D2D1_POINT_2F p3, D2D1_POINT_2F p4, D2D1_POINT_2F& intersection); // Keep this if present
  262.  
  263. // --- NEW Forward Declarations ---
  264.  
  265. // AI Related
  266. struct AIShotInfo; // Define below
  267. void TriggerAIMove();
  268. void AIMakeDecision();
  269. void AIPlaceCueBall();
  270. AIShotInfo AIFindBestShot();
  271. AIShotInfo EvaluateShot(Ball* targetBall, int pocketIndex);
  272. bool IsPathClear(D2D1_POINT_2F start, D2D1_POINT_2F end, int ignoredBallId1, int ignoredBallId2);
  273. Ball* FindFirstHitBall(D2D1_POINT_2F start, float angle, float& hitDistSq); // Added hitDistSq output
  274. float CalculateShotPower(float cueToGhostDist, float targetToPocketDist);
  275. D2D1_POINT_2F CalculateGhostBallPos(Ball* targetBall, int pocketIndex);
  276. bool IsValidAIAimAngle(float angle); // Basic check
  277.  
  278. // Dialog Related
  279. INT_PTR CALLBACK NewGameDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam);
  280. void ShowNewGameDialog(HINSTANCE hInstance);
  281. void LoadSettings(); // For deserialization
  282. void SaveSettings(); // For serialization
  283. const std::wstring SETTINGS_FILE_NAME = L"Pool-Settings.txt";
  284. void ResetGame(HINSTANCE hInstance); // Function to handle F2 reset
  285.  
  286. // --- Forward Declaration for Window Procedure --- <<< Add this line HERE
  287. LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
  288.  
  289. // --- NEW Struct for AI Shot Evaluation ---
  290. struct AIShotInfo {
  291.     bool possible = false;          // Is this shot considered viable?
  292.     Ball* targetBall = nullptr;     // Which ball to hit
  293.     int pocketIndex = -1;           // Which pocket to aim for (0-5)
  294.     D2D1_POINT_2F ghostBallPos = { 0,0 }; // Where cue ball needs to hit target ball
  295.     float angle = 0.0f;             // Calculated shot angle
  296.     float power = 0.0f;             // Calculated shot power
  297.     float score = -1.0f;            // Score for this shot (higher is better)
  298.     bool involves8Ball = false;     // Is the target the 8-ball?
  299. };
  300.  
  301. /*
  302. table = TABLE_COLOR new: #29662d (0.1608, 0.4000, 0.1765) => old: (0.0f, 0.5f, 0.1f)
  303. rail CUSHION_COLOR = #5c0702 (0.3608, 0.0275, 0.0078) => ::Red
  304. gap = #e99d33 (0.9157, 0.6157, 0.2000) => ::Orange
  305. winbg = #5e8863 (0.3686, 0.5333, 0.3882) => 1.0f, 1.0f, 0.803f
  306. headstring = #47742f (0.2784, 0.4549, 0.1843) => ::White
  307. bluearrow = #08b0a5 (0.0314, 0.6902, 0.6471) *#22babf (0.1333,0.7294,0.7490) => ::Blue
  308. */
  309.  
  310. // --- NEW Settings Serialization Functions ---
  311. void SaveSettings() {
  312.     std::ofstream outFile(SETTINGS_FILE_NAME);
  313.     if (outFile.is_open()) {
  314.         outFile << static_cast<int>(gameMode) << std::endl;
  315.         outFile << static_cast<int>(aiDifficulty) << std::endl;
  316.         outFile << static_cast<int>(openingBreakMode) << std::endl;
  317.         outFile.close();
  318.     }
  319.     // else: Handle error, e.g., log or silently fail
  320. }
  321.  
  322. void LoadSettings() {
  323.     std::ifstream inFile(SETTINGS_FILE_NAME);
  324.     if (inFile.is_open()) {
  325.         int gm, aid, obm;
  326.         if (inFile >> gm) {
  327.             gameMode = static_cast<GameMode>(gm);
  328.         }
  329.         if (inFile >> aid) {
  330.             aiDifficulty = static_cast<AIDifficulty>(aid);
  331.         }
  332.         if (inFile >> obm) {
  333.             openingBreakMode = static_cast<OpeningBreakMode>(obm);
  334.         }
  335.         inFile.close();
  336.  
  337.         // Validate loaded settings (optional, but good practice)
  338.         if (gameMode < HUMAN_VS_HUMAN || gameMode > HUMAN_VS_AI) gameMode = HUMAN_VS_HUMAN; // Default
  339.         if (aiDifficulty < EASY || aiDifficulty > HARD) aiDifficulty = MEDIUM; // Default
  340.         if (openingBreakMode < CPU_BREAK || openingBreakMode > FLIP_COIN_BREAK) openingBreakMode = CPU_BREAK; // Default
  341.     }
  342.     // else: File doesn't exist or couldn't be opened, use defaults (already set in global vars)
  343. }
  344. // --- End Settings Serialization Functions ---
  345.  
  346. // --- NEW Dialog Procedure ---
  347. INT_PTR CALLBACK NewGameDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {
  348.     switch (message) {
  349.     case WM_INITDIALOG:
  350.     {
  351.         // --- ACTION 4: Center Dialog Box ---
  352. // Optional: Force centering if default isn't working
  353.         RECT rcDlg, rcOwner, rcScreen;
  354.         HWND hwndOwner = GetParent(hDlg); // GetParent(hDlg) might be better if hwndMain is passed
  355.         if (hwndOwner == NULL) hwndOwner = GetDesktopWindow();
  356.  
  357.         GetWindowRect(hwndOwner, &rcOwner);
  358.         GetWindowRect(hDlg, &rcDlg);
  359.         CopyRect(&rcScreen, &rcOwner); // Use owner rect as reference bounds
  360.  
  361.         // Offset the owner rect relative to the screen if it's not the desktop
  362.         if (GetParent(hDlg) != NULL) { // If parented to main window (passed to DialogBoxParam)
  363.             OffsetRect(&rcOwner, -rcScreen.left, -rcScreen.top);
  364.             OffsetRect(&rcDlg, -rcScreen.left, -rcScreen.top);
  365.             OffsetRect(&rcScreen, -rcScreen.left, -rcScreen.top);
  366.         }
  367.  
  368.  
  369.         // Calculate centered position
  370.         int x = rcOwner.left + (rcOwner.right - rcOwner.left - (rcDlg.right - rcDlg.left)) / 2;
  371.         int y = rcOwner.top + (rcOwner.bottom - rcOwner.top - (rcDlg.bottom - rcDlg.top)) / 2;
  372.  
  373.         // Ensure it stays within screen bounds (optional safety)
  374.         x = std::max(static_cast<int>(rcScreen.left), x);
  375.         y = std::max(static_cast<int>(rcScreen.top), y);
  376.         if (x + (rcDlg.right - rcDlg.left) > rcScreen.right)
  377.             x = rcScreen.right - (rcDlg.right - rcDlg.left);
  378.         if (y + (rcDlg.bottom - rcDlg.top) > rcScreen.bottom)
  379.             y = rcScreen.bottom - (rcDlg.bottom - rcDlg.top);
  380.  
  381.  
  382.         // Set the dialog position
  383.         SetWindowPos(hDlg, HWND_TOP, x, y, 0, 0, SWP_NOSIZE);
  384.  
  385.         // --- End Centering Code ---
  386.  
  387.         // Set initial state based on current global settings (or defaults)
  388.         CheckRadioButton(hDlg, IDC_RADIO_2P, IDC_RADIO_CPU, (gameMode == HUMAN_VS_HUMAN) ? IDC_RADIO_2P : IDC_RADIO_CPU);
  389.  
  390.         CheckRadioButton(hDlg, IDC_RADIO_EASY, IDC_RADIO_HARD,
  391.             (aiDifficulty == EASY) ? IDC_RADIO_EASY : ((aiDifficulty == MEDIUM) ? IDC_RADIO_MEDIUM : IDC_RADIO_HARD));
  392.  
  393.         // Enable/Disable AI group based on initial mode
  394.         EnableWindow(GetDlgItem(hDlg, IDC_GROUP_AI), gameMode == HUMAN_VS_AI);
  395.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_EASY), gameMode == HUMAN_VS_AI);
  396.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_MEDIUM), gameMode == HUMAN_VS_AI);
  397.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_HARD), gameMode == HUMAN_VS_AI);
  398.         // Set initial state for Opening Break Mode
  399.         CheckRadioButton(hDlg, IDC_RADIO_CPU_BREAK, IDC_RADIO_FLIP_BREAK,
  400.             (openingBreakMode == CPU_BREAK) ? IDC_RADIO_CPU_BREAK : ((openingBreakMode == P1_BREAK) ? IDC_RADIO_P1_BREAK : IDC_RADIO_FLIP_BREAK));
  401.         // Enable/Disable Opening Break group based on initial mode
  402.         EnableWindow(GetDlgItem(hDlg, IDC_GROUP_BREAK_MODE), gameMode == HUMAN_VS_AI);
  403.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_CPU_BREAK), gameMode == HUMAN_VS_AI);
  404.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_P1_BREAK), gameMode == HUMAN_VS_AI);
  405.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_FLIP_BREAK), gameMode == HUMAN_VS_AI);
  406.     }
  407.     return (INT_PTR)TRUE;
  408.  
  409.     case WM_COMMAND:
  410.         switch (LOWORD(wParam)) {
  411.         case IDC_RADIO_2P:
  412.         case IDC_RADIO_CPU:
  413.         {
  414.             bool isCPU = IsDlgButtonChecked(hDlg, IDC_RADIO_CPU) == BST_CHECKED;
  415.             // Enable/Disable AI group controls based on selection
  416.             EnableWindow(GetDlgItem(hDlg, IDC_GROUP_AI), isCPU);
  417.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_EASY), isCPU);
  418.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_MEDIUM), isCPU);
  419.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_HARD), isCPU);
  420.             // Also enable/disable Opening Break Mode group
  421.             EnableWindow(GetDlgItem(hDlg, IDC_GROUP_BREAK_MODE), isCPU);
  422.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_CPU_BREAK), isCPU);
  423.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_P1_BREAK), isCPU);
  424.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_FLIP_BREAK), isCPU);
  425.         }
  426.         return (INT_PTR)TRUE;
  427.  
  428.         case IDOK:
  429.             // Retrieve selected options and store in global variables
  430.             if (IsDlgButtonChecked(hDlg, IDC_RADIO_CPU) == BST_CHECKED) {
  431.                 gameMode = HUMAN_VS_AI;
  432.                 if (IsDlgButtonChecked(hDlg, IDC_RADIO_EASY) == BST_CHECKED) aiDifficulty = EASY;
  433.                 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_MEDIUM) == BST_CHECKED) aiDifficulty = MEDIUM;
  434.                 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_HARD) == BST_CHECKED) aiDifficulty = HARD;
  435.  
  436.                 if (IsDlgButtonChecked(hDlg, IDC_RADIO_CPU_BREAK) == BST_CHECKED) openingBreakMode = CPU_BREAK;
  437.                 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_P1_BREAK) == BST_CHECKED) openingBreakMode = P1_BREAK;
  438.                 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_FLIP_BREAK) == BST_CHECKED) openingBreakMode = FLIP_COIN_BREAK;
  439.             }
  440.             else {
  441.                 gameMode = HUMAN_VS_HUMAN;
  442.                 // openingBreakMode doesn't apply to HvsH, can leave as is or reset
  443.             }
  444.             SaveSettings(); // Save settings when OK is pressed
  445.             EndDialog(hDlg, IDOK); // Close dialog, return IDOK
  446.             return (INT_PTR)TRUE;
  447.  
  448.         case IDCANCEL: // Handle Cancel or closing the dialog
  449.             // Optionally, could reload settings here if you want cancel to revert to previously saved state
  450.             EndDialog(hDlg, IDCANCEL);
  451.             return (INT_PTR)TRUE;
  452.         }
  453.         break; // End WM_COMMAND
  454.     }
  455.     return (INT_PTR)FALSE; // Default processing
  456. }
  457.  
  458. // --- NEW Helper to Show Dialog ---
  459. void ShowNewGameDialog(HINSTANCE hInstance) {
  460.     if (DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_NEWGAMEDLG), hwndMain, NewGameDialogProc, 0) == IDOK) {
  461.         // User clicked Start, reset game with new settings
  462.         isPlayer2AI = (gameMode == HUMAN_VS_AI); // Update AI flag
  463.         if (isPlayer2AI) {
  464.             switch (aiDifficulty) {
  465.             case EASY: player2Info.name = L"CPU (Easy)"; break;
  466.             case MEDIUM: player2Info.name = L"CPU (Medium)"; break;
  467.             case HARD: player2Info.name = L"CPU (Hard)"; break;
  468.             }
  469.         }
  470.         else {
  471.             player2Info.name = L"Player 2";
  472.         }
  473.         // Update window title
  474.         std::wstring windowTitle = L"Direct2D 8-Ball Pool";
  475.         if (gameMode == HUMAN_VS_HUMAN) windowTitle += L" (Human vs Human)";
  476.         else windowTitle += L" (Human vs " + player2Info.name + L")";
  477.         SetWindowText(hwndMain, windowTitle.c_str());
  478.  
  479.         InitGame(); // Re-initialize game logic & board
  480.         InvalidateRect(hwndMain, NULL, TRUE); // Force redraw
  481.     }
  482.     else {
  483.         // User cancelled dialog - maybe just resume game? Or exit?
  484.         // For simplicity, we do nothing, game continues as it was.
  485.         // To exit on cancel from F2, would need more complex state management.
  486.     }
  487. }
  488.  
  489. // --- NEW Reset Game Function ---
  490. void ResetGame(HINSTANCE hInstance) {
  491.     // Call the helper function to show the dialog and re-init if OK clicked
  492.     ShowNewGameDialog(hInstance);
  493. }
  494.  
  495. // --- WinMain ---
  496. int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR, int nCmdShow) {
  497.     if (FAILED(CoInitialize(NULL))) {
  498.         MessageBox(NULL, L"COM Initialization Failed.", L"Error", MB_OK | MB_ICONERROR);
  499.         return -1;
  500.     }
  501.  
  502.     // --- NEW: Load settings at startup ---
  503.     LoadSettings();
  504.  
  505.     // --- NEW: Show configuration dialog FIRST ---
  506.     if (DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_NEWGAMEDLG), NULL, NewGameDialogProc, 0) != IDOK) {
  507.         // User cancelled the dialog
  508.         CoUninitialize();
  509.         return 0; // Exit gracefully if dialog cancelled
  510.     }
  511.     // Global gameMode and aiDifficulty are now set by the DialogProc
  512.  
  513.     // Set AI flag based on game mode
  514.     isPlayer2AI = (gameMode == HUMAN_VS_AI);
  515.     if (isPlayer2AI) {
  516.         switch (aiDifficulty) {
  517.         case EASY: player2Info.name = L"CPU (Easy)"; break;
  518.         case MEDIUM: player2Info.name = L"CPU (Medium)"; break;
  519.         case HARD: player2Info.name = L"CPU (Hard)"; break;
  520.         }
  521.     }
  522.     else {
  523.         player2Info.name = L"Player 2";
  524.     }
  525.     // --- End of Dialog Logic ---
  526.  
  527.  
  528.     WNDCLASS wc = { };
  529.     wc.lpfnWndProc = WndProc;
  530.     wc.hInstance = hInstance;
  531.     wc.lpszClassName = L"Direct2D_8BallPool";
  532.     wc.hCursor = LoadCursor(NULL, IDC_ARROW);
  533.     wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
  534.     wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1)); // Use your actual icon ID here
  535.  
  536.     if (!RegisterClass(&wc)) {
  537.         MessageBox(NULL, L"Window Registration Failed.", L"Error", MB_OK | MB_ICONERROR);
  538.         CoUninitialize();
  539.         return -1;
  540.     }
  541.  
  542.     // --- ACTION 4: Calculate Centered Window Position ---
  543.     const int WINDOW_WIDTH = 1000; // Define desired width
  544.     const int WINDOW_HEIGHT = 700; // Define desired height
  545.     int screenWidth = GetSystemMetrics(SM_CXSCREEN);
  546.     int screenHeight = GetSystemMetrics(SM_CYSCREEN);
  547.     int windowX = (screenWidth - WINDOW_WIDTH) / 2;
  548.     int windowY = (screenHeight - WINDOW_HEIGHT) / 2;
  549.  
  550.     // --- Change Window Title based on mode ---
  551.     std::wstring windowTitle = L"Direct2D 8-Ball Pool";
  552.     if (gameMode == HUMAN_VS_HUMAN) windowTitle += L" (Human vs Human)";
  553.     else windowTitle += L" (Human vs " + player2Info.name + L")";
  554.  
  555.     DWORD dwStyle = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX; // No WS_THICKFRAME, No WS_MAXIMIZEBOX
  556.  
  557.     hwndMain = CreateWindowEx(
  558.         0, L"Direct2D_8BallPool", windowTitle.c_str(), dwStyle,
  559.         windowX, windowY, WINDOW_WIDTH, WINDOW_HEIGHT,
  560.         NULL, NULL, hInstance, NULL
  561.     );
  562.  
  563.     if (!hwndMain) {
  564.         MessageBox(NULL, L"Window Creation Failed.", L"Error", MB_OK | MB_ICONERROR);
  565.         CoUninitialize();
  566.         return -1;
  567.     }
  568.  
  569.     // Initialize Direct2D Resources AFTER window creation
  570.     if (FAILED(CreateDeviceResources())) {
  571.         MessageBox(NULL, L"Failed to create Direct2D resources.", L"Error", MB_OK | MB_ICONERROR);
  572.         DestroyWindow(hwndMain);
  573.         CoUninitialize();
  574.         return -1;
  575.     }
  576.  
  577.     InitGame(); // Initialize game state AFTER resources are ready & mode is set
  578.     Sleep(500); // Allow window to fully initialize before starting the countdown //midi func
  579.     StartMidi(hwndMain, TEXT("BSQ.MID")); // Replace with your MIDI filename
  580.     //PlayGameMusic(hwndMain); //midi func
  581.  
  582.     ShowWindow(hwndMain, nCmdShow);
  583.     UpdateWindow(hwndMain);
  584.  
  585.     if (!SetTimer(hwndMain, ID_TIMER, 1000 / TARGET_FPS, NULL)) {
  586.         MessageBox(NULL, L"Could not SetTimer().", L"Error", MB_OK | MB_ICONERROR);
  587.         DestroyWindow(hwndMain);
  588.         CoUninitialize();
  589.         return -1;
  590.     }
  591.  
  592.     MSG msg = { };
  593.     // --- Modified Main Loop ---
  594.     // Handles the case where the game starts in SHOWING_DIALOG state (handled now before loop)
  595.     // or gets reset to it via F2. The main loop runs normally once game starts.
  596.     while (GetMessage(&msg, NULL, 0, 0)) {
  597.         // We might need modeless dialog handling here if F2 shows dialog
  598.         // while window is active, but DialogBoxParam is modal.
  599.         // Let's assume F2 hides main window, shows dialog, then restarts game loop.
  600.         // Simpler: F2 calls ResetGame which calls DialogBoxParam (modal) then InitGame.
  601.         TranslateMessage(&msg);
  602.         DispatchMessage(&msg);
  603.     }
  604.  
  605.  
  606.     KillTimer(hwndMain, ID_TIMER);
  607.     DiscardDeviceResources();
  608.     SaveSettings(); // Save settings on exit
  609.     CoUninitialize();
  610.  
  611.     return (int)msg.wParam;
  612. }
  613.  
  614. // --- WndProc ---
  615. LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
  616.     // Declare cueBall pointer once at the top, used in multiple cases
  617.     // For clarity, often better to declare within each case where needed.
  618.     Ball* cueBall = nullptr; // Initialize to nullptr
  619.     switch (msg) {
  620.     case WM_CREATE:
  621.         // Resources are now created in WinMain after CreateWindowEx
  622.         return 0;
  623.  
  624.     case WM_PAINT:
  625.         OnPaint();
  626.         // Validate the entire window region after painting
  627.         ValidateRect(hwnd, NULL);
  628.         return 0;
  629.  
  630.     case WM_SIZE: {
  631.         UINT width = LOWORD(lParam);
  632.         UINT height = HIWORD(lParam);
  633.         OnResize(width, height);
  634.         return 0;
  635.     }
  636.  
  637.     case WM_TIMER:
  638.         if (wParam == ID_TIMER) {
  639.             GameUpdate(); // Update game logic and physics
  640.             InvalidateRect(hwnd, NULL, FALSE); // Request redraw
  641.         }
  642.         return 0;
  643.  
  644.         // --- NEW: Handle F2 Key for Reset ---
  645.         // --- MODIFIED: Handle More Keys ---
  646.     case WM_KEYDOWN:
  647.     { // Add scope for variable declarations
  648.  
  649.         // --- FIX: Get Cue Ball pointer for this scope ---
  650.         cueBall = GetCueBall();
  651.         // We might allow some keys even if cue ball is gone (like F1/F2), but actions need it
  652.         // --- End Fix ---
  653.  
  654.         // Check which player can interact via keyboard (Humans only)
  655.         bool canPlayerControl = ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == AIMING || currentGameState == BREAKING || currentGameState == BALL_IN_HAND_P1 || currentGameState == PRE_BREAK_PLACEMENT)) ||
  656.             (currentPlayer == 2 && !isPlayer2AI && (currentGameState == PLAYER2_TURN || currentGameState == AIMING || currentGameState == BREAKING || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT)));
  657.  
  658.         // --- F1 / F2 Keys (Always available) ---
  659.         if (wParam == VK_F2) {
  660.             HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE);
  661.             ResetGame(hInstance); // Call reset function
  662.             return 0; // Indicate key was processed
  663.         }
  664.         else if (wParam == VK_F1) {
  665.             MessageBox(hwnd,
  666.                 L"Direct2D-based StickPool game made in C++ from scratch (2764+ lines of code)\n" // Update line count if needed
  667.                 L"First successful Clone in C++ (no other sites or projects were there to glean from.) Made /w AI assist\n"
  668.                 L"(others were in JS/ non-8-Ball in C# etc.) w/o OOP and Graphics Frameworks all in a Single file.\n"
  669.                 L"Copyright (C) 2025 Evans Thorpemorton, Entisoft Solutions.\n"
  670.                 L"Includes AI Difficulty Modes, Aim-Trajectory For Table Rails + Hard Angles TipShots. || F2=New Game",
  671.                 L"About This Game", MB_OK | MB_ICONINFORMATION);
  672.             return 0; // Indicate key was processed
  673.         }
  674.  
  675.         // Check for 'M' key (uppercase or lowercase)
  676.             // Toggle music with "M"
  677.         if (wParam == 'M' || wParam == 'm') {
  678.             //static bool isMusicPlaying = false;
  679.             if (isMusicPlaying) {
  680.                 // Stop the music
  681.                 StopMidi();
  682.                 isMusicPlaying = false;
  683.             }
  684.             else {
  685.                 // Build the MIDI file path
  686.                 TCHAR midiPath[MAX_PATH];
  687.                 GetModuleFileName(NULL, midiPath, MAX_PATH);
  688.                 // Keep only the directory part
  689.                 TCHAR* lastBackslash = _tcsrchr(midiPath, '\\');
  690.                 if (lastBackslash != NULL) {
  691.                     *(lastBackslash + 1) = '\0';
  692.                 }
  693.                 // Append the MIDI filename
  694.                 _tcscat_s(midiPath, MAX_PATH, TEXT("BSQ.MID")); // Adjust filename if needed
  695.  
  696.                 // Start playing MIDI
  697.                 StartMidi(hwndMain, midiPath);
  698.                 isMusicPlaying = true;
  699.             }
  700.         }
  701.  
  702.  
  703.         // --- Player Interaction Keys (Only if allowed) ---
  704.         if (canPlayerControl) {
  705.             // --- Get Shift Key State ---
  706.             bool shiftPressed = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
  707.             float angleStep = shiftPressed ? 0.05f : 0.01f; // Base step / Faster step (Adjust as needed) // Multiplier was 5x
  708.             float powerStep = 0.2f; // Power step (Adjust as needed)
  709.  
  710.             switch (wParam) {
  711.             case VK_LEFT: // Rotate Cue Stick Counter-Clockwise
  712.                 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  713.                     cueAngle -= angleStep;
  714.                     // Normalize angle (keep between 0 and 2*PI)
  715.                     if (cueAngle < 0) cueAngle += 2 * PI;
  716.                     // Ensure state shows aiming visuals if turn just started
  717.                     if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
  718.                     isAiming = false; // Keyboard adjust doesn't use mouse aiming state
  719.                     isDraggingStick = false;
  720.                     keyboardAimingActive = true;
  721.                 }
  722.                 break;
  723.  
  724.             case VK_RIGHT: // Rotate Cue Stick Clockwise
  725.                 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  726.                     cueAngle += angleStep;
  727.                     // Normalize angle (keep between 0 and 2*PI)
  728.                     if (cueAngle >= 2 * PI) cueAngle -= 2 * PI;
  729.                     // Ensure state shows aiming visuals if turn just started
  730.                     if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
  731.                     isAiming = false;
  732.                     isDraggingStick = false;
  733.                     keyboardAimingActive = true;
  734.                 }
  735.                 break;
  736.  
  737.             case VK_UP: // Decrease Shot Power
  738.                 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  739.                     shotPower -= powerStep;
  740.                     if (shotPower < 0.0f) shotPower = 0.0f;
  741.                     // Ensure state shows aiming visuals if turn just started
  742.                     if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
  743.                     isAiming = true; // Keyboard adjust doesn't use mouse aiming state
  744.                     isDraggingStick = false;
  745.                     keyboardAimingActive = true;
  746.                 }
  747.                 break;
  748.  
  749.             case VK_DOWN: // Increase Shot Power
  750.                 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  751.                     shotPower += powerStep;
  752.                     if (shotPower > MAX_SHOT_POWER) shotPower = MAX_SHOT_POWER;
  753.                     // Ensure state shows aiming visuals if turn just started
  754.                     if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
  755.                     isAiming = true;
  756.                     isDraggingStick = false;
  757.                     keyboardAimingActive = true;
  758.                 }
  759.                 break;
  760.  
  761.             case VK_SPACE: // Trigger Shot
  762.                 if ((currentGameState == AIMING || currentGameState == BREAKING || currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN)
  763.                     && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING)
  764.                 {
  765.                     if (shotPower > 0.15f) { // Use same threshold as mouse
  766.                        // Reset foul flags BEFORE applying shot
  767.                         firstHitBallIdThisShot = -1;
  768.                         cueHitObjectBallThisShot = false;
  769.                         railHitAfterContact = false;
  770.  
  771.                         // Play sound & Apply Shot
  772.                         std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
  773.                         ApplyShot(shotPower, cueAngle, cueSpinX, cueSpinY);
  774.  
  775.                         // Update State
  776.                         currentGameState = SHOT_IN_PROGRESS;
  777.                         foulCommitted = false;
  778.                         pocketedThisTurn.clear();
  779.                         shotPower = 0; // Reset power after shooting
  780.                         isAiming = false; isDraggingStick = false; // Reset aiming flags
  781.                         keyboardAimingActive = false;
  782.                     }
  783.                 }
  784.                 break;
  785.  
  786.             case VK_ESCAPE: // Cancel Aim/Shot Setup
  787.                 if ((currentGameState == AIMING || currentGameState == BREAKING) || shotPower > 0)
  788.                 {
  789.                     shotPower = 0.0f;
  790.                     isAiming = false;
  791.                     isDraggingStick = false;
  792.                     keyboardAimingActive = false;
  793.                     // Revert to basic turn state if not breaking
  794.                     if (currentGameState != BREAKING) {
  795.                         currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  796.                     }
  797.                 }
  798.                 break;
  799.  
  800.             case 'G': // Toggle Cheat Mode
  801.                 cheatModeEnabled = !cheatModeEnabled;
  802.                 if (cheatModeEnabled)
  803.                     MessageBeep(MB_ICONEXCLAMATION); // Play a beep when enabling
  804.                 else
  805.                     MessageBeep(MB_OK); // Play a different beep when disabling
  806.                 break;
  807.  
  808.             default:
  809.                 // Allow default processing for other keys if needed
  810.                 // return DefWindowProc(hwnd, msg, wParam, lParam); // Usually not needed for WM_KEYDOWN
  811.                 break;
  812.             } // End switch(wParam) for player controls
  813.             return 0; // Indicate player control key was processed
  814.         } // End if(canPlayerControl)
  815.     } // End scope for WM_KEYDOWN case
  816.     // If key wasn't F1/F2 and player couldn't control, maybe allow default processing?
  817.     // return DefWindowProc(hwnd, msg, wParam, lParam); // Or just return 0
  818.     return 0;
  819.  
  820.     case WM_MOUSEMOVE: {
  821.         ptMouse.x = LOWORD(lParam);
  822.         ptMouse.y = HIWORD(lParam);
  823.  
  824.         cueBall = GetCueBall(); // Declare and get cueBall pointer
  825.  
  826.         if (isDraggingCueBall && cheatModeEnabled && draggingBallId != -1) {
  827.             Ball* ball = GetBallById(draggingBallId);
  828.             if (ball) {
  829.                 ball->x = (float)ptMouse.x;
  830.                 ball->y = (float)ptMouse.y;
  831.                 ball->vx = ball->vy = 0.0f;
  832.             }
  833.             return 0;
  834.         }
  835.  
  836.         if (!cueBall) return 0;
  837.  
  838.         // Update Aiming Logic (Check player turn)
  839.         if (isDraggingCueBall &&
  840.             ((currentPlayer == 1 && currentGameState == BALL_IN_HAND_P1) ||
  841.                 (!isPlayer2AI && currentPlayer == 2 && currentGameState == BALL_IN_HAND_P2) ||
  842.                 currentGameState == PRE_BREAK_PLACEMENT))
  843.         {
  844.             bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  845.             // Tentative position update
  846.             cueBall->x = (float)ptMouse.x;
  847.             cueBall->y = (float)ptMouse.y;
  848.             cueBall->vx = cueBall->vy = 0;
  849.         }
  850.         else if ((isAiming || isDraggingStick) &&
  851.             ((currentPlayer == 1 && (currentGameState == AIMING || currentGameState == BREAKING)) ||
  852.                 (!isPlayer2AI && currentPlayer == 2 && (currentGameState == AIMING || currentGameState == BREAKING))))
  853.         {
  854.             //NEW2 MOUSEBOUND CODE = START
  855.                 /*// Clamp mouse inside table bounds during aiming
  856.                 if (ptMouse.x < TABLE_LEFT) ptMouse.x = TABLE_LEFT;
  857.             if (ptMouse.x > TABLE_RIGHT) ptMouse.x = TABLE_RIGHT;
  858.             if (ptMouse.y < TABLE_TOP) ptMouse.y = TABLE_TOP;
  859.             if (ptMouse.y > TABLE_BOTTOM) ptMouse.y = TABLE_BOTTOM;*/
  860.             //NEW2 MOUSEBOUND CODE = END
  861.             // Aiming drag updates angle and power
  862.             float dx = (float)ptMouse.x - cueBall->x;
  863.             float dy = (float)ptMouse.y - cueBall->y;
  864.             if (dx != 0 || dy != 0) cueAngle = atan2f(dy, dx);
  865.             //float pullDist = GetDistance((float)ptMouse.x, (float)ptMouse.y, aimStartPoint.x, aimStartPoint.y);
  866.             //shotPower = std::min(pullDist / 10.0f, MAX_SHOT_POWER);
  867.             if (!keyboardAimingActive) { // Only update shotPower if NOT keyboard aiming
  868.                 float pullDist = GetDistance((float)ptMouse.x, (float)ptMouse.y, aimStartPoint.x, aimStartPoint.y);
  869.                 shotPower = std::min(pullDist / 10.0f, MAX_SHOT_POWER);
  870.             }
  871.         }
  872.         else if (isSettingEnglish &&
  873.             ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == AIMING || currentGameState == BREAKING)) ||
  874.                 (!isPlayer2AI && currentPlayer == 2 && (currentGameState == PLAYER2_TURN || currentGameState == AIMING || currentGameState == BREAKING))))
  875.         {
  876.             // Setting English
  877.             float dx = (float)ptMouse.x - spinIndicatorCenter.x;
  878.             float dy = (float)ptMouse.y - spinIndicatorCenter.y;
  879.             float dist = GetDistance(dx, dy, 0, 0);
  880.             if (dist > spinIndicatorRadius) { dx *= spinIndicatorRadius / dist; dy *= spinIndicatorRadius / dist; }
  881.             cueSpinX = dx / spinIndicatorRadius;
  882.             cueSpinY = dy / spinIndicatorRadius;
  883.         }
  884.         else {
  885.             //DISABLE PERM AIMING = START
  886.             /*// Update visual angle even when not aiming/dragging (Check player turn)
  887.             bool canUpdateVisualAngle = ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == BALL_IN_HAND_P1)) ||
  888.                 (currentPlayer == 2 && !isPlayer2AI && (currentGameState == PLAYER2_TURN || currentGameState == BALL_IN_HAND_P2)) ||
  889.                 currentGameState == PRE_BREAK_PLACEMENT || currentGameState == BREAKING || currentGameState == AIMING);
  890.  
  891.             if (canUpdateVisualAngle && !isDraggingCueBall && !isAiming && !isDraggingStick && !keyboardAimingActive) // NEW: Prevent mouse override if keyboard aiming
  892.             {
  893.                 // NEW MOUSEBOUND CODE = START
  894.                     // Only update cue angle if mouse is inside the playable table area
  895.                 if (ptMouse.x >= TABLE_LEFT && ptMouse.x <= TABLE_RIGHT &&
  896.                     ptMouse.y >= TABLE_TOP && ptMouse.y <= TABLE_BOTTOM)
  897.                 {
  898.                     // NEW MOUSEBOUND CODE = END
  899.                     Ball* cb = cueBall; // Use function-scope cueBall // Already got cueBall above
  900.                     if (cb) {
  901.                         float dx = (float)ptMouse.x - cb->x;
  902.                         float dy = (float)ptMouse.y - cb->y;
  903.                         if (dx != 0 || dy != 0) cueAngle = atan2f(dy, dx);
  904.                     }
  905.                 } //NEW MOUSEBOUND CODE LINE = DISABLE
  906.             }*/
  907.             //DISABLE PERM AIMING = END
  908.         }
  909.         return 0;
  910.     } // End WM_MOUSEMOVE
  911.  
  912.     case WM_LBUTTONDOWN: {
  913.         ptMouse.x = LOWORD(lParam);
  914.         ptMouse.y = HIWORD(lParam);
  915.  
  916.  
  917.         // --- Handle pocket selection clicks ---
  918.         if (currentGameState == SELECT_EIGHT_POCKET_P1 || currentGameState == SELECT_EIGHT_POCKET_P2) {
  919.             for (int i = 0; i < 6; i++) {
  920.                 float dx = ptMouse.x - pocketPositions[i].x, dy = ptMouse.y - pocketPositions[i].y;
  921.                 if (dx * dx + dy * dy <= HOLE_VISUAL_RADIUS * HOLE_VISUAL_RADIUS) {
  922.                     selectedPocketIndex = i;
  923.                     eightPocketSelected = true;
  924.                     // return to normal turn: human aims or CPU thinks
  925.                     currentGameState = (currentGameState == SELECT_EIGHT_POCKET_P1) ? PLAYER1_TURN : PLAYER2_TURN;
  926.                     return 0;
  927.                 }
  928.             }
  929.             return 0;
  930.         }
  931.  
  932.         if (cheatModeEnabled) {
  933.             // Allow dragging any ball freely
  934.             for (Ball& ball : balls) {
  935.                 float distSq = GetDistanceSq(ball.x, ball.y, (float)ptMouse.x, (float)ptMouse.y);
  936.                 if (distSq <= BALL_RADIUS * BALL_RADIUS * 4) { // Click near ball
  937.                     isDraggingCueBall = true;
  938.                     draggingBallId = ball.id;
  939.                     if (ball.id == 0) {
  940.                         // If dragging cue ball manually, ensure we stay in Ball-In-Hand state
  941.                         if (currentPlayer == 1)
  942.                             currentGameState = BALL_IN_HAND_P1;
  943.                         else if (currentPlayer == 2 && !isPlayer2AI)
  944.                             currentGameState = BALL_IN_HAND_P2;
  945.                     }
  946.                     return 0;
  947.                 }
  948.             }
  949.         }
  950.  
  951.         Ball* cueBall = GetCueBall(); // Declare and get cueBall pointer            
  952.  
  953.         // Check which player is allowed to interact via mouse click
  954.         bool canPlayerClickInteract = ((currentPlayer == 1) || (currentPlayer == 2 && !isPlayer2AI));
  955.         // Define states where interaction is generally allowed
  956.         bool canInteractState = (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN ||
  957.             currentGameState == AIMING || currentGameState == BREAKING ||
  958.             currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 ||
  959.             currentGameState == PRE_BREAK_PLACEMENT);
  960.  
  961.         // Check Spin Indicator first (Allow if player's turn/aim phase)
  962.         if (canPlayerClickInteract && canInteractState) {
  963.             float spinDistSq = GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, spinIndicatorCenter.x, spinIndicatorCenter.y);
  964.             if (spinDistSq < spinIndicatorRadius * spinIndicatorRadius * 1.2f) {
  965.                 isSettingEnglish = true;
  966.                 float dx = (float)ptMouse.x - spinIndicatorCenter.x;
  967.                 float dy = (float)ptMouse.y - spinIndicatorCenter.y;
  968.                 float dist = GetDistance(dx, dy, 0, 0);
  969.                 if (dist > spinIndicatorRadius) { dx *= spinIndicatorRadius / dist; dy *= spinIndicatorRadius / dist; }
  970.                 cueSpinX = dx / spinIndicatorRadius;
  971.                 cueSpinY = dy / spinIndicatorRadius;
  972.                 isAiming = false; isDraggingStick = false; isDraggingCueBall = false;
  973.                 return 0;
  974.             }
  975.         }
  976.  
  977.         if (!cueBall) return 0;
  978.  
  979.         // Check Ball-in-Hand placement/drag
  980.         bool isPlacingBall = (currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT);
  981.         bool isPlayerAllowedToPlace = (isPlacingBall &&
  982.             ((currentPlayer == 1 && currentGameState == BALL_IN_HAND_P1) ||
  983.                 (currentPlayer == 2 && !isPlayer2AI && currentGameState == BALL_IN_HAND_P2) ||
  984.                 (currentGameState == PRE_BREAK_PLACEMENT))); // Allow current player in break setup
  985.  
  986.         if (isPlayerAllowedToPlace) {
  987.             float distSq = GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y);
  988.             if (distSq < BALL_RADIUS * BALL_RADIUS * 9.0f) {
  989.                 isDraggingCueBall = true;
  990.                 isAiming = false; isDraggingStick = false;
  991.             }
  992.             else {
  993.                 bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  994.                 if (IsValidCueBallPosition((float)ptMouse.x, (float)ptMouse.y, behindHeadstring)) {
  995.                     cueBall->x = (float)ptMouse.x; cueBall->y = (float)ptMouse.y;
  996.                     cueBall->vx = 0; cueBall->vy = 0;
  997.                     isDraggingCueBall = false;
  998.                     // Transition state
  999.                     if (currentGameState == PRE_BREAK_PLACEMENT) currentGameState = BREAKING;
  1000.                     else if (currentGameState == BALL_IN_HAND_P1) currentGameState = PLAYER1_TURN;
  1001.                     else if (currentGameState == BALL_IN_HAND_P2) currentGameState = PLAYER2_TURN;
  1002.                     cueAngle = 0.0f;
  1003.                 }
  1004.             }
  1005.             return 0;
  1006.         }
  1007.  
  1008.         // Check for starting Aim (Cue Ball OR Stick)
  1009.         bool canAim = ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == BREAKING)) ||
  1010.             (currentPlayer == 2 && !isPlayer2AI && (currentGameState == PLAYER2_TURN || currentGameState == BREAKING)));
  1011.  
  1012.         if (canAim) {
  1013.             const float stickDrawLength = 150.0f * 1.4f;
  1014.             float currentStickAngle = cueAngle + PI;
  1015.             D2D1_POINT_2F currentStickEnd = D2D1::Point2F(cueBall->x + cosf(currentStickAngle) * stickDrawLength, cueBall->y + sinf(currentStickAngle) * stickDrawLength);
  1016.             D2D1_POINT_2F currentStickTip = D2D1::Point2F(cueBall->x + cosf(currentStickAngle) * 5.0f, cueBall->y + sinf(currentStickAngle) * 5.0f);
  1017.             float distToStickSq = PointToLineSegmentDistanceSq(D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y), currentStickTip, currentStickEnd);
  1018.             float stickClickThresholdSq = 36.0f;
  1019.             float distToCueBallSq = GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y);
  1020.             float cueBallClickRadiusSq = BALL_RADIUS * BALL_RADIUS * 25;
  1021.  
  1022.             bool clickedStick = (distToStickSq < stickClickThresholdSq);
  1023.             bool clickedCueArea = (distToCueBallSq < cueBallClickRadiusSq);
  1024.  
  1025.             if (clickedStick || clickedCueArea) {
  1026.                 isDraggingStick = clickedStick && !clickedCueArea;
  1027.                 isAiming = clickedCueArea;
  1028.                 aimStartPoint = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y);
  1029.                 shotPower = 0;
  1030.                 float dx = (float)ptMouse.x - cueBall->x;
  1031.                 float dy = (float)ptMouse.y - cueBall->y;
  1032.                 if (dx != 0 || dy != 0) cueAngle = atan2f(dy, dx);
  1033.                 if (currentGameState != BREAKING) currentGameState = AIMING;
  1034.             }
  1035.         }
  1036.         return 0;
  1037.     } // End WM_LBUTTONDOWN
  1038.  
  1039.  
  1040.     case WM_LBUTTONUP: {
  1041.         if (cheatModeEnabled && isDraggingCueBall) {
  1042.             isDraggingCueBall = false;
  1043.             if (draggingBallId == 0) {
  1044.                 // After dropping CueBall, stay Ball-In-Hand mode if needed
  1045.                 if (currentPlayer == 1)
  1046.                     currentGameState = BALL_IN_HAND_P1;
  1047.                 else if (currentPlayer == 2 && !isPlayer2AI)
  1048.                     currentGameState = BALL_IN_HAND_P2;
  1049.             }
  1050.             draggingBallId = -1;
  1051.             return 0;
  1052.         }
  1053.  
  1054.         ptMouse.x = LOWORD(lParam);
  1055.         ptMouse.y = HIWORD(lParam);
  1056.  
  1057.         Ball* cueBall = GetCueBall(); // Get cueBall pointer
  1058.  
  1059.         // Check for releasing aim drag (Stick OR Cue Ball)
  1060.         if ((isAiming || isDraggingStick) &&
  1061.             ((currentPlayer == 1 && (currentGameState == AIMING || currentGameState == BREAKING)) ||
  1062.                 (!isPlayer2AI && currentPlayer == 2 && (currentGameState == AIMING || currentGameState == BREAKING))))
  1063.         {
  1064.             bool wasAiming = isAiming;
  1065.             bool wasDraggingStick = isDraggingStick;
  1066.             isAiming = false; isDraggingStick = false;
  1067.  
  1068.             if (shotPower > 0.15f) { // Check power threshold
  1069.                 if (currentGameState != AI_THINKING) {
  1070.                     firstHitBallIdThisShot = -1; cueHitObjectBallThisShot = false; railHitAfterContact = false; // Reset foul flags
  1071.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
  1072.                     ApplyShot(shotPower, cueAngle, cueSpinX, cueSpinY);
  1073.                     currentGameState = SHOT_IN_PROGRESS;
  1074.                     foulCommitted = false; pocketedThisTurn.clear();
  1075.                 }
  1076.             }
  1077.             else if (currentGameState != AI_THINKING) { // Revert state if power too low
  1078.                 if (currentGameState == BREAKING) { /* Still breaking */ }
  1079.                 else {
  1080.                     currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  1081.                     if (currentPlayer == 2 && isPlayer2AI) aiTurnPending = false;
  1082.                 }
  1083.             }
  1084.             shotPower = 0; // Reset power indicator regardless
  1085.         }
  1086.  
  1087.         // Handle releasing cue ball drag (placement)
  1088.         if (isDraggingCueBall) {
  1089.             isDraggingCueBall = false;
  1090.             // Check player allowed to place
  1091.             bool isPlacingState = (currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT);
  1092.             bool isPlayerAllowed = (isPlacingState &&
  1093.                 ((currentPlayer == 1 && currentGameState == BALL_IN_HAND_P1) ||
  1094.                     (currentPlayer == 2 && !isPlayer2AI && currentGameState == BALL_IN_HAND_P2) ||
  1095.                     (currentGameState == PRE_BREAK_PLACEMENT)));
  1096.  
  1097.             if (isPlayerAllowed && cueBall) {
  1098.                 bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  1099.                 if (IsValidCueBallPosition(cueBall->x, cueBall->y, behindHeadstring)) {
  1100.                     // Finalize position already set by mouse move
  1101.                     // Transition state
  1102.                     if (currentGameState == PRE_BREAK_PLACEMENT) currentGameState = BREAKING;
  1103.                     else if (currentGameState == BALL_IN_HAND_P1) currentGameState = PLAYER1_TURN;
  1104.                     else if (currentGameState == BALL_IN_HAND_P2) currentGameState = PLAYER2_TURN;
  1105.                     cueAngle = 0.0f;
  1106.                 }
  1107.                 else { /* Stay in BALL_IN_HAND state if final pos invalid */ }
  1108.             }
  1109.         }
  1110.  
  1111.         // Handle releasing english setting
  1112.         if (isSettingEnglish) {
  1113.             isSettingEnglish = false;
  1114.         }
  1115.         return 0;
  1116.     } // End WM_LBUTTONUP
  1117.  
  1118.     case WM_DESTROY:
  1119.         isMusicPlaying = false;
  1120.         if (midiDeviceID != 0) {
  1121.             mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
  1122.             midiDeviceID = 0;
  1123.             SaveSettings(); // Save settings on exit
  1124.         }
  1125.         PostQuitMessage(0);
  1126.         return 0;
  1127.  
  1128.     default:
  1129.         return DefWindowProc(hwnd, msg, wParam, lParam);
  1130.     }
  1131.     return 0;
  1132. }
  1133.  
  1134. // --- Direct2D Resource Management ---
  1135.  
  1136. HRESULT CreateDeviceResources() {
  1137.     HRESULT hr = S_OK;
  1138.  
  1139.     // Create Direct2D Factory
  1140.     if (!pFactory) {
  1141.         hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &pFactory);
  1142.         if (FAILED(hr)) return hr;
  1143.     }
  1144.  
  1145.     // Create DirectWrite Factory
  1146.     if (!pDWriteFactory) {
  1147.         hr = DWriteCreateFactory(
  1148.             DWRITE_FACTORY_TYPE_SHARED,
  1149.             __uuidof(IDWriteFactory),
  1150.             reinterpret_cast<IUnknown**>(&pDWriteFactory)
  1151.         );
  1152.         if (FAILED(hr)) return hr;
  1153.     }
  1154.  
  1155.     // Create Text Formats
  1156.     if (!pTextFormat && pDWriteFactory) {
  1157.         hr = pDWriteFactory->CreateTextFormat(
  1158.             L"Segoe UI", NULL, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
  1159.             16.0f, L"en-us", &pTextFormat
  1160.         );
  1161.         if (FAILED(hr)) return hr;
  1162.         // Center align text
  1163.         pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  1164.         pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  1165.     }
  1166.     if (!pLargeTextFormat && pDWriteFactory) {
  1167.         hr = pDWriteFactory->CreateTextFormat(
  1168.             L"Impact", NULL, DWRITE_FONT_WEIGHT_BOLD, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
  1169.             48.0f, L"en-us", &pLargeTextFormat
  1170.         );
  1171.         if (FAILED(hr)) return hr;
  1172.         pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING); // Align left
  1173.         pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  1174.     }
  1175.  
  1176.  
  1177.     // Create Render Target (needs valid hwnd)
  1178.     if (!pRenderTarget && hwndMain) {
  1179.         RECT rc;
  1180.         GetClientRect(hwndMain, &rc);
  1181.         D2D1_SIZE_U size = D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top);
  1182.  
  1183.         hr = pFactory->CreateHwndRenderTarget(
  1184.             D2D1::RenderTargetProperties(),
  1185.             D2D1::HwndRenderTargetProperties(hwndMain, size),
  1186.             &pRenderTarget
  1187.         );
  1188.         if (FAILED(hr)) {
  1189.             // If failed, release factories if they were created in this call
  1190.             SafeRelease(&pTextFormat);
  1191.             SafeRelease(&pLargeTextFormat);
  1192.             SafeRelease(&pDWriteFactory);
  1193.             SafeRelease(&pFactory);
  1194.             pRenderTarget = nullptr; // Ensure it's null on failure
  1195.             return hr;
  1196.         }
  1197.     }
  1198.  
  1199.     return hr;
  1200. }
  1201.  
  1202. void DiscardDeviceResources() {
  1203.     SafeRelease(&pRenderTarget);
  1204.     SafeRelease(&pTextFormat);
  1205.     SafeRelease(&pLargeTextFormat);
  1206.     SafeRelease(&pDWriteFactory);
  1207.     // Keep pFactory until application exit? Or release here too? Let's release.
  1208.     SafeRelease(&pFactory);
  1209. }
  1210.  
  1211. void OnResize(UINT width, UINT height) {
  1212.     if (pRenderTarget) {
  1213.         D2D1_SIZE_U size = D2D1::SizeU(width, height);
  1214.         pRenderTarget->Resize(size); // Ignore HRESULT for simplicity here
  1215.     }
  1216. }
  1217.  
  1218. // --- Game Initialization ---
  1219. void InitGame() {
  1220.     srand((unsigned int)time(NULL)); // Seed random number generator
  1221.     isOpeningBreakShot = true; // This is the start of a new game, so the next shot is an opening break.
  1222.     aiPlannedShotDetails.isValid = false; // Reset AI planned shot
  1223.     aiIsDisplayingAim = false;
  1224.     aiAimDisplayFramesLeft = 0;
  1225.     // ... (rest of InitGame())
  1226.  
  1227.     // --- Ensure pocketed list is clear from the absolute start ---
  1228.     pocketedThisTurn.clear();
  1229.  
  1230.     balls.clear(); // Clear existing balls
  1231.  
  1232.     // Reset Player Info (Names should be set by Dialog/wWinMain/ResetGame)
  1233.     player1Info.assignedType = BallType::NONE;
  1234.     player1Info.ballsPocketedCount = 0;
  1235.     // Player 1 Name usually remains "Player 1"
  1236.     player2Info.assignedType = BallType::NONE;
  1237.     player2Info.ballsPocketedCount = 0;
  1238.     // Player 2 Name is set based on gameMode in ShowNewGameDialog
  1239.  
  1240.     // If player just sank their 7th object (next is 8-Ball), force pocket selection
  1241.     PlayerInfo& cp = (currentPlayer == 1 ? player1Info : player2Info);
  1242.     if (!eightPocketSelected && !eightBallPocketed && cp.ballsPocketedCount >= 7) {
  1243.         // go into pocket-selection mode
  1244.         currentGameState = (currentPlayer == 1) ? SELECT_EIGHT_POCKET_P1 : SELECT_EIGHT_POCKET_P2;
  1245.         // display “Choose a pocket…” instead of normal UI
  1246.         return;
  1247.     }
  1248.  
  1249.     // Create Cue Ball (ID 0)
  1250.     // Initial position will be set during PRE_BREAK_PLACEMENT state
  1251.     balls.push_back({ 0, BallType::CUE_BALL, TABLE_LEFT + TABLE_WIDTH * 0.15f, RACK_POS_Y, 0, 0, CUE_BALL_COLOR, false });
  1252.  
  1253.     // --- Create Object Balls (Temporary List) ---
  1254.     std::vector<Ball> objectBalls;
  1255.     // Solids (1-7, Yellow)
  1256.     for (int i = 1; i <= 7; ++i) {
  1257.         objectBalls.push_back({ i, BallType::SOLID, 0, 0, 0, 0, SOLID_COLOR, false });
  1258.     }
  1259.     // Stripes (9-15, Red)
  1260.     for (int i = 9; i <= 15; ++i) {
  1261.         objectBalls.push_back({ i, BallType::STRIPE, 0, 0, 0, 0, STRIPE_COLOR, false });
  1262.     }
  1263.     // 8-Ball (ID 8) - Add it to the list to be placed
  1264.     objectBalls.push_back({ 8, BallType::EIGHT_BALL, 0, 0, 0, 0, EIGHT_BALL_COLOR, false });
  1265.  
  1266.  
  1267.     // --- Racking Logic (Improved) ---
  1268.     float spacingX = BALL_RADIUS * 2.0f * 0.866f; // cos(30) for horizontal spacing
  1269.     float spacingY = BALL_RADIUS * 2.0f * 1.0f;   // Vertical spacing
  1270.  
  1271.     // Define rack positions (0-14 indices corresponding to triangle spots)
  1272.     D2D1_POINT_2F rackPositions[15];
  1273.     int rackIndex = 0;
  1274.     for (int row = 0; row < 5; ++row) {
  1275.         for (int col = 0; col <= row; ++col) {
  1276.             if (rackIndex >= 15) break;
  1277.             float x = RACK_POS_X + row * spacingX;
  1278.             float y = RACK_POS_Y + (col - row / 2.0f) * spacingY;
  1279.             rackPositions[rackIndex++] = D2D1::Point2F(x, y);
  1280.         }
  1281.     }
  1282.  
  1283.     // Separate 8-ball
  1284.     Ball eightBall;
  1285.     std::vector<Ball> otherBalls; // Solids and Stripes
  1286.     bool eightBallFound = false;
  1287.     for (const auto& ball : objectBalls) {
  1288.         if (ball.id == 8) {
  1289.             eightBall = ball;
  1290.             eightBallFound = true;
  1291.         }
  1292.         else {
  1293.             otherBalls.push_back(ball);
  1294.         }
  1295.     }
  1296.     // Ensure 8 ball was actually created (should always be true)
  1297.     if (!eightBallFound) {
  1298.         // Handle error - perhaps recreate it? For now, proceed.
  1299.         eightBall = { 8, BallType::EIGHT_BALL, 0, 0, 0, 0, EIGHT_BALL_COLOR, false };
  1300.     }
  1301.  
  1302.  
  1303.     // Shuffle the other 14 balls
  1304.     // Use std::shuffle if available (C++11 and later) for better randomness
  1305.     // std::random_device rd;
  1306.     // std::mt19937 g(rd());
  1307.     // std::shuffle(otherBalls.begin(), otherBalls.end(), g);
  1308.     std::random_shuffle(otherBalls.begin(), otherBalls.end()); // Using deprecated for now
  1309.  
  1310.     // --- Place balls into the main 'balls' vector in rack order ---
  1311.     // Important: Add the cue ball (already created) first.
  1312.     // (Cue ball added at the start of the function now)
  1313.  
  1314.     // 1. Place the 8-ball in its fixed position (index 4 for the 3rd row center)
  1315.     int eightBallRackIndex = 4;
  1316.     eightBall.x = rackPositions[eightBallRackIndex].x;
  1317.     eightBall.y = rackPositions[eightBallRackIndex].y;
  1318.     eightBall.vx = 0;
  1319.     eightBall.vy = 0;
  1320.     eightBall.isPocketed = false;
  1321.     balls.push_back(eightBall); // Add 8 ball to the main vector
  1322.  
  1323.     // 2. Place the shuffled Solids and Stripes in the remaining spots
  1324.     size_t otherBallIdx = 0;
  1325.     //int otherBallIdx = 0;
  1326.     for (int i = 0; i < 15; ++i) {
  1327.         if (i == eightBallRackIndex) continue; // Skip the 8-ball spot
  1328.  
  1329.         if (otherBallIdx < otherBalls.size()) {
  1330.             Ball& ballToPlace = otherBalls[otherBallIdx++];
  1331.             ballToPlace.x = rackPositions[i].x;
  1332.             ballToPlace.y = rackPositions[i].y;
  1333.             ballToPlace.vx = 0;
  1334.             ballToPlace.vy = 0;
  1335.             ballToPlace.isPocketed = false;
  1336.             balls.push_back(ballToPlace); // Add to the main game vector
  1337.         }
  1338.     }
  1339.     // --- End Racking Logic ---
  1340.  
  1341.  
  1342.     // --- Determine Who Breaks and Initial State ---
  1343.     if (isPlayer2AI) {
  1344.         /*// AI Mode: Randomly decide who breaks
  1345.         if ((rand() % 2) == 0) {
  1346.             // AI (Player 2) breaks
  1347.             currentPlayer = 2;
  1348.             currentGameState = PRE_BREAK_PLACEMENT; // AI needs to place ball first
  1349.             aiTurnPending = true; // Trigger AI logic
  1350.         }
  1351.         else {
  1352.             // Player 1 (Human) breaks
  1353.             currentPlayer = 1;
  1354.             currentGameState = PRE_BREAK_PLACEMENT; // Human places cue ball
  1355.             aiTurnPending = false;*/
  1356.         switch (openingBreakMode) {
  1357.         case CPU_BREAK:
  1358.             currentPlayer = 2; // AI breaks
  1359.             currentGameState = PRE_BREAK_PLACEMENT;
  1360.             aiTurnPending = true;
  1361.             break;
  1362.         case P1_BREAK:
  1363.             currentPlayer = 1; // Player 1 breaks
  1364.             currentGameState = PRE_BREAK_PLACEMENT;
  1365.             aiTurnPending = false;
  1366.             break;
  1367.         case FLIP_COIN_BREAK:
  1368.             if ((rand() % 2) == 0) { // 0 for AI, 1 for Player 1
  1369.                 currentPlayer = 2; // AI breaks
  1370.                 currentGameState = PRE_BREAK_PLACEMENT;
  1371.                 aiTurnPending = true;
  1372.             }
  1373.             else {
  1374.                 currentPlayer = 1; // Player 1 breaks
  1375.                 currentGameState = PRE_BREAK_PLACEMENT;
  1376.                 aiTurnPending = false;
  1377.             }
  1378.             break;
  1379.         default: // Fallback to CPU break
  1380.             currentPlayer = 2;
  1381.             currentGameState = PRE_BREAK_PLACEMENT;
  1382.             aiTurnPending = true;
  1383.             break;
  1384.         }
  1385.     }
  1386.     else {
  1387.         // Human vs Human, Player 1 always breaks (or could add a flip coin for HvsH too if desired)
  1388.         currentPlayer = 1;
  1389.         currentGameState = PRE_BREAK_PLACEMENT;
  1390.         aiTurnPending = false; // No AI involved
  1391.     }
  1392.  
  1393.     // Reset other relevant game state variables
  1394.     foulCommitted = false;
  1395.     gameOverMessage = L"";
  1396.     firstBallPocketedAfterBreak = false;
  1397.     // pocketedThisTurn cleared at start
  1398.     // Reset shot parameters and input flags
  1399.     shotPower = 0.0f;
  1400.     cueSpinX = 0.0f;
  1401.     cueSpinY = 0.0f;
  1402.     isAiming = false;
  1403.     isDraggingCueBall = false;
  1404.     isSettingEnglish = false;
  1405.     cueAngle = 0.0f; // Reset aim angle
  1406. }
  1407.  
  1408.  
  1409. // --- Game Loop ---
  1410. void GameUpdate() {
  1411.     if (currentGameState == SHOT_IN_PROGRESS) {
  1412.         UpdatePhysics();
  1413.         CheckCollisions();
  1414.  
  1415.         if (AreBallsMoving()) {
  1416.             // When all balls stop, clear aiming flags
  1417.             isAiming = false;
  1418.             aiIsDisplayingAim = false;
  1419.             //ProcessShotResults();
  1420.         }
  1421.  
  1422.         bool pocketed = CheckPockets(); // Store if any ball was pocketed
  1423.  
  1424.         // --- Update pocket flash animation timer ---
  1425.         if (pocketFlashTimer > 0.0f) {
  1426.             pocketFlashTimer -= 0.02f;
  1427.             if (pocketFlashTimer < 0.0f) pocketFlashTimer = 0.0f;
  1428.         }
  1429.  
  1430.         if (!AreBallsMoving()) {
  1431.             ProcessShotResults(); // Determine next state based on what happened
  1432.         }
  1433.     }
  1434.  
  1435.     // --- Check if AI needs to act ---
  1436.     else if (isPlayer2AI && currentPlayer == 2 && !AreBallsMoving()) {
  1437.         // For CPU, force pocket selection first if needed
  1438.         if (!eightPocketSelected && player2Info.ballsPocketedCount >= 7) {
  1439.             currentGameState = SELECT_EIGHT_POCKET_P2;
  1440.             return;
  1441.         }
  1442.         if (aiIsDisplayingAim) { // AI has decided a shot and is displaying aim
  1443.             aiAimDisplayFramesLeft--;
  1444.             if (aiAimDisplayFramesLeft <= 0) {
  1445.                 aiIsDisplayingAim = false; // Done displaying
  1446.                 if (aiPlannedShotDetails.isValid) {
  1447.                     // Execute the planned shot
  1448.                     firstHitBallIdThisShot = -1;
  1449.                     cueHitObjectBallThisShot = false;
  1450.                     railHitAfterContact = false;
  1451.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
  1452.                     ApplyShot(aiPlannedShotDetails.power, aiPlannedShotDetails.angle, aiPlannedShotDetails.spinX, aiPlannedShotDetails.spinY);
  1453.                     aiPlannedShotDetails.isValid = false; // Clear the planned shot
  1454.                 }
  1455.                 currentGameState = SHOT_IN_PROGRESS;
  1456.                 foulCommitted = false;
  1457.                 pocketedThisTurn.clear();
  1458.             }
  1459.             // Else, continue displaying aim
  1460.         }
  1461.         else if (aiTurnPending) { // AI needs to start its decision process
  1462.             // Valid states for AI to start thinking
  1463.             /*/if (currentGameState == PRE_BREAK_PLACEMENT && isOpeningBreakShot) {*/
  1464.             //newcode 1 commented out
  1465.             /*if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT && currentPlayer == 2 && isPlayer2AI) {
  1466.                 // Handle the break shot
  1467.                 AIBreakShot();
  1468.             }*/ //new code 1 end  
  1469.             /*else if (currentGameState == PRE_BREAK_PLACEMENT || currentGameState == BREAKING ||
  1470.                 currentGameState == PLAYER2_TURN || currentGameState == BALL_IN_HAND_P2) {*/
  1471.  
  1472.                 // aiTurnPending might be consumed by AIBreakShot or remain for next cycle if needed
  1473.         /* } //new code 2 commented out
  1474.         else if (currentGameState == BALL_IN_HAND_P2 && currentPlayer == 2 && isPlayer2AI) {
  1475.             AIPlaceCueBall(); // AI places the ball first
  1476.             // After placement, AI needs to decide its shot.
  1477.             // Transition to a state where AIMakeDecision will be called for shot selection.
  1478.             currentGameState = PLAYER2_TURN; // Or a specific AI_AIMING_AFTER_PLACEMENT state
  1479.                                              // aiTurnPending remains true to trigger AIMakeDecision next.
  1480.         }
  1481.         else if (currentGameState == PLAYER2_TURN && currentPlayer == 2 && isPlayer2AI) {
  1482.             // This is for a normal turn (not break, not immediately after ball-in-hand placement)
  1483.  
  1484.                 currentGameState = AI_THINKING; // Set state to indicate AI is processing
  1485.                 aiTurnPending = false;         // Consume the pending turn flag
  1486.                 AIMakeDecision();              // For normal shots (non-break)
  1487.             }
  1488.             else {
  1489.                 // Not a state where AI should act
  1490.                 aiTurnPending = false;
  1491.             }*/
  1492.             // 2b) AI is ready to think (pending flag)
  1493.             // **1) Ball-in-Hand** let AI place the cue ball first
  1494.             if (currentGameState == BALL_IN_HAND_P2) {
  1495.                 // Step 1: AI places the cue ball.
  1496.                 AIPlaceCueBall();
  1497.                 // Step 2: Transition to thinking state for shot decision.
  1498.                 currentGameState = AI_THINKING; //newcode5
  1499.                 // Step 3: Consume the pending flag for the placement phase.
  1500.                 //         AIMakeDecision will handle shot planning now.
  1501.                 aiTurnPending = false; //newcode5
  1502.                 // Step 4: AI immediately decides the shot from the new position.
  1503.                 AIMakeDecision(); //newcode5
  1504.             }
  1505.             // **2) Opening break** special break shot logic
  1506.             else if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT) {
  1507.                 AIBreakShot();
  1508.             }
  1509.             else if (currentGameState == PLAYER2_TURN || currentGameState == BREAKING) { //newcode5
  1510.                 // General turn for AI to think (not ball-in-hand, not initial break placement)
  1511.                 currentGameState = AI_THINKING; //newcode5
  1512.                 aiTurnPending = false; // Consume the flag //newcode5
  1513.                 AIMakeDecision(); //newcode5
  1514.             }
  1515.             // **3) Otherwise** normal shot planning
  1516.             /*else { //orig uncommented oldcode5
  1517.                 currentGameState = AI_THINKING;
  1518.                 aiTurnPending = false;
  1519.                 AIMakeDecision();
  1520.             }*/
  1521.         }
  1522.  
  1523.         //} //bracefix
  1524.         // If current state is AI_THINKING but not displaying aim, then AI decision has already been made
  1525.     }
  1526. }
  1527.  
  1528. // --- Physics and Collision ---
  1529. void UpdatePhysics() {
  1530.     for (size_t i = 0; i < balls.size(); ++i) {
  1531.         Ball& b = balls[i];
  1532.         if (!b.isPocketed) {
  1533.             b.x += b.vx;
  1534.             b.y += b.vy;
  1535.  
  1536.             // Apply friction
  1537.             b.vx *= FRICTION;
  1538.             b.vy *= FRICTION;
  1539.  
  1540.             // Stop balls if velocity is very low
  1541.             if (GetDistanceSq(b.vx, b.vy, 0, 0) < MIN_VELOCITY_SQ) {
  1542.                 b.vx = 0;
  1543.                 b.vy = 0;
  1544.             }
  1545.         }
  1546.     }
  1547. }
  1548.  
  1549. void CheckCollisions() {
  1550.     float left = TABLE_LEFT;
  1551.     float right = TABLE_RIGHT;
  1552.     float top = TABLE_TOP;
  1553.     float bottom = TABLE_BOTTOM;
  1554.     const float pocketMouthCheckRadiusSq = (POCKET_RADIUS + BALL_RADIUS) * (POCKET_RADIUS + BALL_RADIUS) * 1.1f;
  1555.  
  1556.     // --- Reset Per-Frame Sound Flags ---
  1557.     bool playedWallSoundThisFrame = false;
  1558.     bool playedCollideSoundThisFrame = false;
  1559.     // ---
  1560.  
  1561.     for (size_t i = 0; i < balls.size(); ++i) {
  1562.         Ball& b1 = balls[i];
  1563.         if (b1.isPocketed) continue;
  1564.  
  1565.         bool nearPocket[6];
  1566.         for (int p = 0; p < 6; ++p) {
  1567.             nearPocket[p] = GetDistanceSq(b1.x, b1.y, pocketPositions[p].x, pocketPositions[p].y) < pocketMouthCheckRadiusSq;
  1568.         }
  1569.         bool nearTopLeftPocket = nearPocket[0];
  1570.         bool nearTopMidPocket = nearPocket[1];
  1571.         bool nearTopRightPocket = nearPocket[2];
  1572.         bool nearBottomLeftPocket = nearPocket[3];
  1573.         bool nearBottomMidPocket = nearPocket[4];
  1574.         bool nearBottomRightPocket = nearPocket[5];
  1575.  
  1576.         bool collidedWallThisBall = false;
  1577.  
  1578.         // --- Ball-Wall Collisions ---
  1579.         // (Check logic unchanged, added sound calls and railHitAfterContact update)
  1580.         // Left Wall
  1581.         if (b1.x - BALL_RADIUS < left) {
  1582.             if (!nearTopLeftPocket && !nearBottomLeftPocket) {
  1583.                 b1.x = left + BALL_RADIUS; b1.vx *= -1.0f; collidedWallThisBall = true;
  1584.                 if (!playedWallSoundThisFrame) {
  1585.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  1586.                     playedWallSoundThisFrame = true;
  1587.                 }
  1588.                 if (cueHitObjectBallThisShot) railHitAfterContact = true; // Track rail hit after contact
  1589.             }
  1590.         }
  1591.         // Right Wall
  1592.         if (b1.x + BALL_RADIUS > right) {
  1593.             if (!nearTopRightPocket && !nearBottomRightPocket) {
  1594.                 b1.x = right - BALL_RADIUS; b1.vx *= -1.0f; collidedWallThisBall = true;
  1595.                 if (!playedWallSoundThisFrame) {
  1596.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  1597.                     playedWallSoundThisFrame = true;
  1598.                 }
  1599.                 if (cueHitObjectBallThisShot) railHitAfterContact = true; // Track rail hit after contact
  1600.             }
  1601.         }
  1602.         // Top Wall
  1603.         if (b1.y - BALL_RADIUS < top) {
  1604.             if (!nearTopLeftPocket && !nearTopMidPocket && !nearTopRightPocket) {
  1605.                 b1.y = top + BALL_RADIUS; b1.vy *= -1.0f; collidedWallThisBall = true;
  1606.                 if (!playedWallSoundThisFrame) {
  1607.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  1608.                     playedWallSoundThisFrame = true;
  1609.                 }
  1610.                 if (cueHitObjectBallThisShot) railHitAfterContact = true; // Track rail hit after contact
  1611.             }
  1612.         }
  1613.         // Bottom Wall
  1614.         if (b1.y + BALL_RADIUS > bottom) {
  1615.             if (!nearBottomLeftPocket && !nearBottomMidPocket && !nearBottomRightPocket) {
  1616.                 b1.y = bottom - BALL_RADIUS; b1.vy *= -1.0f; collidedWallThisBall = true;
  1617.                 if (!playedWallSoundThisFrame) {
  1618.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  1619.                     playedWallSoundThisFrame = true;
  1620.                 }
  1621.                 if (cueHitObjectBallThisShot) railHitAfterContact = true; // Track rail hit after contact
  1622.             }
  1623.         }
  1624.  
  1625.         // Spin effect (Unchanged)
  1626.         if (collidedWallThisBall) {
  1627.             if (b1.x <= left + BALL_RADIUS || b1.x >= right - BALL_RADIUS) { b1.vy += cueSpinX * b1.vx * 0.05f; }
  1628.             if (b1.y <= top + BALL_RADIUS || b1.y >= bottom - BALL_RADIUS) { b1.vx -= cueSpinY * b1.vy * 0.05f; }
  1629.             cueSpinX *= 0.7f; cueSpinY *= 0.7f;
  1630.         }
  1631.  
  1632.  
  1633.         // --- Ball-Ball Collisions ---
  1634.         for (size_t j = i + 1; j < balls.size(); ++j) {
  1635.             Ball& b2 = balls[j];
  1636.             if (b2.isPocketed) continue;
  1637.  
  1638.             float dx = b2.x - b1.x; float dy = b2.y - b1.y;
  1639.             float distSq = dx * dx + dy * dy;
  1640.             float minDist = BALL_RADIUS * 2.0f;
  1641.  
  1642.             if (distSq > 1e-6 && distSq < minDist * minDist) {
  1643.                 float dist = sqrtf(distSq);
  1644.                 float overlap = minDist - dist;
  1645.                 float nx = dx / dist; float ny = dy / dist;
  1646.  
  1647.                 // Separation (Unchanged)
  1648.                 b1.x -= overlap * 0.5f * nx; b1.y -= overlap * 0.5f * ny;
  1649.                 b2.x += overlap * 0.5f * nx; b2.y += overlap * 0.5f * ny;
  1650.  
  1651.                 float rvx = b1.vx - b2.vx; float rvy = b1.vy - b2.vy;
  1652.                 float velAlongNormal = rvx * nx + rvy * ny;
  1653.  
  1654.                 if (velAlongNormal > 0) { // Colliding
  1655.                     // --- Play Ball Collision Sound ---
  1656.                     if (!playedCollideSoundThisFrame) {
  1657.                         std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("poolballhit.wav")).detach();
  1658.                         playedCollideSoundThisFrame = true; // Set flag
  1659.                     }
  1660.                     // --- End Sound ---
  1661.  
  1662.                     // --- NEW: Track First Hit and Cue/Object Collision ---
  1663.                     if (firstHitBallIdThisShot == -1) { // If first hit hasn't been recorded yet
  1664.                         if (b1.id == 0) { // Cue ball hit b2 first
  1665.                             firstHitBallIdThisShot = b2.id;
  1666.                             cueHitObjectBallThisShot = true;
  1667.                         }
  1668.                         else if (b2.id == 0) { // Cue ball hit b1 first
  1669.                             firstHitBallIdThisShot = b1.id;
  1670.                             cueHitObjectBallThisShot = true;
  1671.                         }
  1672.                         // If neither is cue ball, doesn't count as first hit for foul purposes
  1673.                     }
  1674.                     else if (b1.id == 0 || b2.id == 0) {
  1675.                         // Track subsequent cue ball collisions with object balls
  1676.                         cueHitObjectBallThisShot = true;
  1677.                     }
  1678.                     // --- End First Hit Tracking ---
  1679.  
  1680.  
  1681.                     // Impulse (Unchanged)
  1682.                     float impulse = velAlongNormal;
  1683.                     b1.vx -= impulse * nx; b1.vy -= impulse * ny;
  1684.                     b2.vx += impulse * nx; b2.vy += impulse * ny;
  1685.  
  1686.                     // Spin Transfer (Unchanged)
  1687.                     if (b1.id == 0 || b2.id == 0) {
  1688.                         float spinEffectFactor = 0.08f;
  1689.                         b1.vx += (cueSpinY * ny - cueSpinX * nx) * spinEffectFactor;
  1690.                         b1.vy += (cueSpinY * nx + cueSpinX * ny) * spinEffectFactor;
  1691.                         b2.vx -= (cueSpinY * ny - cueSpinX * nx) * spinEffectFactor;
  1692.                         b2.vy -= (cueSpinY * nx + cueSpinX * ny) * spinEffectFactor;
  1693.                         cueSpinX *= 0.85f; cueSpinY *= 0.85f;
  1694.                     }
  1695.                 }
  1696.             }
  1697.         } // End ball-ball loop
  1698.     } // End ball loop
  1699. } // End CheckCollisions
  1700.  
  1701.  
  1702. bool CheckPockets() {
  1703.     bool ballPocketedThisCheck = false; // Local flag for this specific check run
  1704.     for (size_t i = 0; i < balls.size(); ++i) {
  1705.         Ball& b = balls[i];
  1706.         if (!b.isPocketed) { // Only check balls that aren't already flagged as pocketed
  1707.             for (int p = 0; p < 6; ++p) {
  1708.                 float distSq = GetDistanceSq(b.x, b.y, pocketPositions[p].x, pocketPositions[p].y);
  1709.                 // --- Use updated POCKET_RADIUS ---
  1710.                 if (distSq < POCKET_RADIUS * POCKET_RADIUS) {
  1711.                     b.isPocketed = true;
  1712.                     b.vx = b.vy = 0;
  1713.                     pocketedThisTurn.push_back(b.id);
  1714.  
  1715.                     // --- Play Pocket Sound (Threaded) ---
  1716.                     if (!ballPocketedThisCheck) {
  1717.                         std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("pocket.wav")).detach();
  1718.                         ballPocketedThisCheck = true;
  1719.                     }
  1720.                     // --- End Sound ---
  1721.  
  1722.                     break; // Ball is pocketed
  1723.                 }
  1724.             }
  1725.         }
  1726.     }
  1727.     return ballPocketedThisCheck;
  1728. }
  1729.  
  1730. bool AreBallsMoving() {
  1731.     for (size_t i = 0; i < balls.size(); ++i) {
  1732.         if (!balls[i].isPocketed && (balls[i].vx != 0 || balls[i].vy != 0)) {
  1733.             return true;
  1734.         }
  1735.     }
  1736.     return false;
  1737. }
  1738.  
  1739. void RespawnCueBall(bool behindHeadstring) { // 'behindHeadstring' only relevant for initial break placement
  1740.     Ball* cueBall = GetCueBall();
  1741.     if (cueBall) {
  1742.         // Reset position to a default
  1743.         //disabled for behind headstring (now move anywhere)
  1744.         /*cueBall->x = HEADSTRING_X * 0.5f;
  1745.         cueBall->y = TABLE_TOP + TABLE_HEIGHT / 2.0f;*/
  1746.         // Reset position to a default:
  1747.         if (behindHeadstring) {
  1748.             // Opening break: kitchen center
  1749.             cueBall->x = HEADSTRING_X * 0.5f;
  1750.             cueBall->y = TABLE_TOP + TABLE_HEIGHT / 2.0f;
  1751.         }
  1752.         else {
  1753.             // Ball-in-hand (foul): center of full table
  1754.             cueBall->x = TABLE_LEFT + TABLE_WIDTH / 2.0f;
  1755.             cueBall->y = TABLE_TOP + TABLE_HEIGHT / 2.0f;
  1756.         }
  1757.         cueBall->vx = 0;
  1758.         cueBall->vy = 0;
  1759.         cueBall->isPocketed = false;
  1760.  
  1761.         // Set state based on who gets ball-in-hand
  1762.         /*// 'currentPlayer' already reflects who's turn it is NOW (switched before calling this)*/
  1763.         // 'currentPlayer' has already been switched to the player whose turn it will be.
  1764.         // The 'behindHeadstring' parameter to RespawnCueBall is mostly for historical reasons / initial setup.
  1765.         if (currentPlayer == 1) { // Player 2 (AI/Human) fouled, Player 1 (Human) gets ball-in-hand
  1766.             currentGameState = BALL_IN_HAND_P1;
  1767.             aiTurnPending = false; // Ensure AI flag off
  1768.         }
  1769.         else { // Player 1 (Human) fouled, Player 2 gets ball-in-hand
  1770.             if (isPlayer2AI) {
  1771.                 // --- CONFIRMED FIX: Set correct state for AI Ball-in-Hand ---
  1772.                 currentGameState = BALL_IN_HAND_P2; // AI now needs to place the ball
  1773.                 aiTurnPending = true; // Trigger AI logic (will call AIPlaceCueBall first)
  1774.             }
  1775.             else { // Human Player 2
  1776.                 currentGameState = BALL_IN_HAND_P2;
  1777.                 aiTurnPending = false; // Ensure AI flag off
  1778.             }
  1779.         }
  1780.         // Handle initial placement state correctly if called from InitGame
  1781.         /*if (behindHeadstring && currentGameState != PRE_BREAK_PLACEMENT) {
  1782.             // This case might need review depending on exact initial setup flow,
  1783.             // but the foul logic above should now be correct.
  1784.             // Let's ensure initial state is PRE_BREAK_PLACEMENT if behindHeadstring is true.*/
  1785.             //currentGameState = PRE_BREAK_PLACEMENT;
  1786.     }
  1787. }
  1788. //}
  1789.  
  1790.  
  1791. // --- Game Logic ---
  1792.  
  1793. void ApplyShot(float power, float angle, float spinX, float spinY) {
  1794.     Ball* cueBall = GetCueBall();
  1795.     if (cueBall) {
  1796.  
  1797.         // --- Play Cue Strike Sound (Threaded) ---
  1798.         if (power > 0.1f) { // Only play if it's an audible shot
  1799.             std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
  1800.         }
  1801.         // --- End Sound ---
  1802.  
  1803.         cueBall->vx = cosf(angle) * power;
  1804.         cueBall->vy = sinf(angle) * power;
  1805.  
  1806.         // Apply English (Spin) - Simplified effect (Unchanged)
  1807.         cueBall->vx += sinf(angle) * spinY * 0.5f;
  1808.         cueBall->vy -= cosf(angle) * spinY * 0.5f;
  1809.         cueBall->vx -= cosf(angle) * spinX * 0.5f;
  1810.         cueBall->vy -= sinf(angle) * spinX * 0.5f;
  1811.  
  1812.         // Store spin (Unchanged)
  1813.         cueSpinX = spinX;
  1814.         cueSpinY = spinY;
  1815.  
  1816.         // --- Reset Foul Tracking flags for the new shot ---
  1817.         // (Also reset in LBUTTONUP, but good to ensure here too)
  1818.         firstHitBallIdThisShot = -1;      // No ball hit yet
  1819.         cueHitObjectBallThisShot = false; // Cue hasn't hit anything yet
  1820.         railHitAfterContact = false;     // No rail hit after contact yet
  1821.         // --- End Reset ---
  1822.  
  1823.                 // If this was the opening break shot, clear the flag
  1824.         if (isOpeningBreakShot) {
  1825.             isOpeningBreakShot = false; // Mark opening break as taken
  1826.         }
  1827.     }
  1828. }
  1829.  
  1830.  
  1831. void ProcessShotResults() {
  1832.     bool cueBallPocketed = false;
  1833.     bool eightBallPocketed = false;
  1834.     bool legalBallPocketed = false;
  1835.     bool opponentBallPocketed = false;
  1836.     bool anyNonCueBallPocketed = false; // Includes opponent balls
  1837.     BallType firstPocketedType = BallType::NONE;
  1838.     int firstPocketedId = -1;
  1839.  
  1840.     PlayerInfo& currentPlayerInfo = (currentPlayer == 1) ? player1Info : player2Info;
  1841.     PlayerInfo& opponentPlayerInfo = (currentPlayer == 1) ? player2Info : player1Info;
  1842.  
  1843.     // Analyze pocketed balls (Unchanged logic)
  1844.     for (int pocketedId : pocketedThisTurn) {
  1845.         Ball* b = GetBallById(pocketedId);
  1846.         if (!b) continue;
  1847.         if (!pocketedThisTurn.empty()) {
  1848.             pocketFlashTimer = 1.0f; // Flash boost when any ball is pocketed
  1849.         }
  1850.         if (b->id == 0) { cueBallPocketed = true; }
  1851.         else if (b->id == 8) { eightBallPocketed = true; }
  1852.         else {
  1853.             anyNonCueBallPocketed = true;
  1854.             if (firstPocketedId == -1) { firstPocketedId = b->id; firstPocketedType = b->type; }
  1855.             if (currentPlayerInfo.assignedType != BallType::NONE) {
  1856.                 if (b->type == currentPlayerInfo.assignedType) legalBallPocketed = true;
  1857.                 else if (b->type == opponentPlayerInfo.assignedType) opponentBallPocketed = true;
  1858.             }
  1859.         }
  1860.     }
  1861.  
  1862.     // --- Game Over Checks --- (Unchanged logic)
  1863.     if (eightBallPocketed) {
  1864.         CheckGameOverConditions(eightBallPocketed, cueBallPocketed);
  1865.         if (currentGameState == GAME_OVER) return;
  1866.     }
  1867.  
  1868.     // --- MODIFIED: Enhanced Foul Checks ---
  1869.     bool turnFoul = false;
  1870.  
  1871.     // Foul 1: Scratch (Cue ball pocketed)
  1872.     if (cueBallPocketed) {
  1873.         foulCommitted = true; turnFoul = true;
  1874.     }
  1875.  
  1876.     // Foul 2: Hit Nothing (Only if not already a scratch)
  1877.     // Condition: Cue ball didn't hit *any* object ball during the shot.
  1878.     if (!turnFoul && !cueHitObjectBallThisShot) {
  1879.         // Check if the cue ball actually moved significantly to constitute a shot attempt
  1880.         Ball* cue = GetCueBall();
  1881.         // Use a small threshold to avoid foul on accidental tiny nudge if needed
  1882.         // For now, any shot attempt that doesn't hit an object ball is a foul.
  1883.         // (Could add velocity check from ApplyShot if needed)
  1884.         if (cue) { // Ensure cue ball exists
  1885.             foulCommitted = true; turnFoul = true;
  1886.         }
  1887.     }
  1888.  
  1889.     // Foul 3: Wrong Ball First (Check only if not already foul and *something* was hit)
  1890.     if (!turnFoul && firstHitBallIdThisShot != -1) {
  1891.         Ball* firstHitBall = GetBallById(firstHitBallIdThisShot);
  1892.         if (firstHitBall) {
  1893.             bool isBreakShot = (player1Info.assignedType == BallType::NONE && player2Info.assignedType == BallType::NONE);
  1894.             bool mustTarget8Ball = (!isBreakShot && currentPlayerInfo.assignedType != BallType::NONE && currentPlayerInfo.ballsPocketedCount >= 7);
  1895.  
  1896.             if (!isBreakShot) { // Standard play rules
  1897.                 if (mustTarget8Ball) {
  1898.                     if (firstHitBall->id != 8) { foulCommitted = true; turnFoul = true; }
  1899.                 }
  1900.                 else if (currentPlayerInfo.assignedType != BallType::NONE) { // Colors assigned
  1901.                   // Illegal to hit opponent ball OR 8-ball first
  1902.                     if (firstHitBall->type == opponentPlayerInfo.assignedType || firstHitBall->id == 8) {
  1903.                         foulCommitted = true; turnFoul = true;
  1904.                     }
  1905.                 }
  1906.                 // If colors NOT assigned yet (e.g. shot immediately after break), hitting any ball is legal first.
  1907.             }
  1908.             // No specific first-hit foul rules applied for the break itself here.
  1909.         }
  1910.     }
  1911.  
  1912.     // Foul 4: No Rail After Contact (Check only if not already foul)
  1913.     // Condition: Cue hit an object ball, BUT after that first contact,
  1914.     //            NO ball hit a rail AND NO object ball was pocketed (excluding cue/8-ball).
  1915.     if (!turnFoul && cueHitObjectBallThisShot && !railHitAfterContact && !anyNonCueBallPocketed) {
  1916.         foulCommitted = true;
  1917.         turnFoul = true;
  1918.     }
  1919.  
  1920.     // Foul 5: Pocketing Opponent's Ball (Optional stricter rule - can uncomment if desired)
  1921.     // if (!turnFoul && opponentBallPocketed) {
  1922.     //     foulCommitted = true; turnFoul = true;
  1923.     // }
  1924.     // --- End Enhanced Foul Checks ---
  1925.  
  1926.  
  1927.     // --- State Transitions ---
  1928.     if (turnFoul) {
  1929.         SwitchTurns();
  1930.         RespawnCueBall(false); // Ball in hand for opponent (state set in Respawn)
  1931.     }
  1932.     // --- Assign Ball Types only AFTER checking for fouls on the break/first shot ---
  1933.     else if (player1Info.assignedType == BallType::NONE && anyNonCueBallPocketed) {
  1934.         // (Assign types logic - unchanged)
  1935.         bool firstTypeVerified = false;
  1936.         for (int id : pocketedThisTurn) { if (id == firstPocketedId) { firstTypeVerified = true; break; } }
  1937.  
  1938.         if (firstTypeVerified && (firstPocketedType == BallType::SOLID || firstPocketedType == BallType::STRIPE)) {
  1939.             AssignPlayerBallTypes(firstPocketedType);
  1940.             legalBallPocketed = true;
  1941.         }
  1942.         // After assignment (or if types already assigned), check if turn continues
  1943.         if (legalBallPocketed) { // Player legally pocketed their assigned type (newly or existing)
  1944.             currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  1945.             if (currentPlayer == 2 && isPlayer2AI) aiTurnPending = true;
  1946.         }
  1947.         else { // Pocketed wrong ball, or only opponent ball, or missed (but no foul committed)
  1948.             SwitchTurns();
  1949.         }
  1950.     }
  1951.     // --- Normal Play Results (Types Assigned) ---
  1952.     else if (player1Info.assignedType != BallType::NONE) { // Ensure types assigned before this block
  1953.         if (legalBallPocketed) { // Legally pocketed own ball
  1954.             currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  1955.             if (currentPlayer == 2 && isPlayer2AI) aiTurnPending = true; // AI continues turn
  1956.         }
  1957.         else { // No legal ball pocketed (or no ball pocketed at all) and no foul
  1958.             SwitchTurns();
  1959.         }
  1960.     }
  1961.     // --- Handle case where shot occurred but no balls pocketed and no foul ---
  1962.     else if (!anyNonCueBallPocketed && !turnFoul) {
  1963.         SwitchTurns();
  1964.     }
  1965.  
  1966.  
  1967.     // Update pocketed counts AFTER handling turns/fouls/assignment
  1968.     int p1NewlyPocketed = 0;
  1969.     int p2NewlyPocketed = 0;
  1970.     for (int id : pocketedThisTurn) {
  1971.         if (id == 0 || id == 8) continue; // Skip cue ball and 8-ball
  1972.         Ball* b = GetBallById(id);
  1973.         if (!b) continue; // extra safety
  1974.         if (b->type == player1Info.assignedType) p1NewlyPocketed++;
  1975.         else if (b->type == player2Info.assignedType) p2NewlyPocketed++;
  1976.     }
  1977.     if (currentGameState != GAME_OVER) {
  1978.         player1Info.ballsPocketedCount += p1NewlyPocketed;
  1979.         player2Info.ballsPocketedCount += p2NewlyPocketed;
  1980.     }
  1981.  
  1982.  
  1983.     // --- Cleanup for next actual shot attempt ---
  1984.     pocketedThisTurn.clear();
  1985.     // Reset foul tracking flags (done before next shot applied)
  1986.     // firstHitBallIdThisShot = -1; // Reset these before next shot call
  1987.     // cueHitObjectBallThisShot = false;
  1988.     // railHitAfterContact = false;
  1989. }
  1990.  
  1991. void AssignPlayerBallTypes(BallType firstPocketedType) {
  1992.     if (firstPocketedType == BallType::SOLID || firstPocketedType == BallType::STRIPE) {
  1993.         if (currentPlayer == 1) {
  1994.             player1Info.assignedType = firstPocketedType;
  1995.             player2Info.assignedType = (firstPocketedType == BallType::SOLID) ? BallType::STRIPE : BallType::SOLID;
  1996.         }
  1997.         else {
  1998.             player2Info.assignedType = firstPocketedType;
  1999.             player1Info.assignedType = (firstPocketedType == BallType::SOLID) ? BallType::STRIPE : BallType::SOLID;
  2000.         }
  2001.     }
  2002.     // If 8-ball was first (illegal on break generally), rules vary.
  2003.     // Here, we might ignore assignment until a solid/stripe is pocketed legally.
  2004.     // Or assign based on what *else* was pocketed, if anything.
  2005.     // Simplification: Assignment only happens on SOLID or STRIPE first pocket.
  2006. }
  2007.  
  2008. void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed) {
  2009.     if (!eightBallPocketed) return; // Only proceed if 8-ball was pocketed
  2010.  
  2011.     PlayerInfo& currentPlayerInfo = (currentPlayer == 1) ? player1Info : player2Info;
  2012.     bool playerClearedBalls = (currentPlayerInfo.assignedType != BallType::NONE && currentPlayerInfo.ballsPocketedCount >= 7);
  2013.  
  2014.     // Loss Conditions:
  2015.     // 1. Pocket 8-ball AND scratch (pocket cue ball)
  2016.     // 2. Pocket 8-ball before clearing own color group
  2017.     if (cueBallPocketed || (!playerClearedBalls && currentPlayerInfo.assignedType != BallType::NONE)) {
  2018.         gameOverMessage = (currentPlayer == 1) ? L"Player 2 Wins! (Player 1 fouled on 8-ball)" : L"Player 1 Wins! (Player 2 fouled on 8-ball)";
  2019.         currentGameState = GAME_OVER;
  2020.     }
  2021.     // Win Condition:
  2022.     // 1. Pocket 8-ball legally after clearing own color group
  2023.     else if (playerClearedBalls) {
  2024.         gameOverMessage = (currentPlayer == 1) ? L"Player 1 Wins!" : L"Player 2 Wins!";
  2025.         currentGameState = GAME_OVER;
  2026.     }
  2027.     // Special case: 8 ball pocketed on break. Usually re-spot or re-rack.
  2028.     // Simple: If it happens during assignment phase, treat as foul, respawn 8ball.
  2029.     else if (player1Info.assignedType == BallType::NONE) {
  2030.         Ball* eightBall = GetBallById(8);
  2031.         if (eightBall) {
  2032.             eightBall->isPocketed = false;
  2033.             // Place 8-ball on foot spot (approx RACK_POS_X) or center if occupied
  2034.             eightBall->x = RACK_POS_X;
  2035.             eightBall->y = RACK_POS_Y;
  2036.             eightBall->vx = eightBall->vy = 0;
  2037.             // Check overlap and nudge if necessary (simplified)
  2038.         }
  2039.         // Apply foul rules if cue ball was also pocketed
  2040.         if (cueBallPocketed) {
  2041.             foulCommitted = true;
  2042.             // Don't switch turns on break scratch + 8ball pocket? Rules vary.
  2043.             // Let's make it a foul, switch turns, ball in hand.
  2044.             SwitchTurns();
  2045.             RespawnCueBall(false); // Ball in hand for opponent
  2046.         }
  2047.         else {
  2048.             // Just respawned 8ball, continue turn or switch based on other balls pocketed.
  2049.             // Let ProcessShotResults handle turn logic based on other pocketed balls.
  2050.         }
  2051.         // Prevent immediate game over message by returning here
  2052.         return;
  2053.     }
  2054.  
  2055.  
  2056. }
  2057.  
  2058.  
  2059. void SwitchTurns() {
  2060.     currentPlayer = (currentPlayer == 1) ? 2 : 1;
  2061.     // Reset aiming state for the new player
  2062.     isAiming = false;
  2063.     shotPower = 0;
  2064.     // Reset foul flag before new turn *really* starts (AI might take over)
  2065.     // Foul flag is mainly for display, gets cleared before human/AI shot
  2066.     // foulCommitted = false; // Probably better to clear before ApplyShot
  2067.  
  2068.     // Set the correct state based on who's turn it is
  2069.     if (currentPlayer == 1) {
  2070.         currentGameState = PLAYER1_TURN;
  2071.         aiTurnPending = false; // Ensure AI flag is off for P1
  2072.     }
  2073.     else { // Player 2's turn
  2074.         if (isPlayer2AI) {
  2075.             currentGameState = PLAYER2_TURN; // State indicates it's P2's turn
  2076.             aiTurnPending = true;           // Set flag for GameUpdate to trigger AI
  2077.             // AI will handle Ball-in-Hand logic if necessary within its decision making
  2078.         }
  2079.         else {
  2080.             currentGameState = PLAYER2_TURN; // Human P2
  2081.             aiTurnPending = false;
  2082.         }
  2083.     }
  2084. }
  2085.  
  2086. void AIBreakShot() {
  2087.     Ball* cueBall = GetCueBall();
  2088.     if (!cueBall) return;
  2089.  
  2090.     // This function is called when it's AI's turn for the opening break and state is PRE_BREAK_PLACEMENT.
  2091.     // AI will place the cue ball and then plan the shot.
  2092.     if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT) {
  2093.         // Place cue ball in the kitchen randomly
  2094.         /*float kitchenMinX = TABLE_LEFT + BALL_RADIUS; // [cite: 1071, 1072, 1587]
  2095.         float kitchenMaxX = HEADSTRING_X - BALL_RADIUS; // [cite: 1072, 1078, 1588]
  2096.         float kitchenMinY = TABLE_TOP + BALL_RADIUS; // [cite: 1071, 1072, 1588]
  2097.         float kitchenMaxY = TABLE_BOTTOM - BALL_RADIUS; // [cite: 1072, 1073, 1589]*/
  2098.  
  2099.         // --- AI Places Cue Ball for Break ---
  2100. // Decide if placing center or side. For simplicity, let's try placing slightly off-center
  2101. // towards one side for a more angled break, or center for direct apex hit.
  2102. // A common strategy is to hit the second ball of the rack.
  2103.  
  2104.         float placementY = RACK_POS_Y; // Align vertically with the rack center
  2105.         float placementX;
  2106.  
  2107.         // Randomly choose a side or center-ish placement for variation.
  2108.         int placementChoice = rand() % 3; // 0: Left-ish, 1: Center-ish, 2: Right-ish in kitchen
  2109.  
  2110.         if (placementChoice == 0) { // Left-ish
  2111.             placementX = HEADSTRING_X - (TABLE_WIDTH * 0.05f) - (BALL_RADIUS * (1 + (rand() % 3))); // Place slightly to the left within kitchen
  2112.         }
  2113.         else if (placementChoice == 2) { // Right-ish
  2114.             placementX = HEADSTRING_X - (TABLE_WIDTH * 0.05f) + (BALL_RADIUS * (1 + (rand() % 3))); // Place slightly to the right within kitchen
  2115.         }
  2116.         else { // Center-ish
  2117.             placementX = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f; // Roughly center of kitchen
  2118.         }
  2119.         placementX = std::max(TABLE_LEFT + BALL_RADIUS + 1.0f, std::min(placementX, HEADSTRING_X - BALL_RADIUS - 1.0f)); // Clamp within kitchen X
  2120.  
  2121.         bool validPos = false;
  2122.         int attempts = 0;
  2123.         while (!validPos && attempts < 100) {
  2124.             /*cueBall->x = kitchenMinX + static_cast<float>(rand()) / (static_cast<float>(RAND_MAX) / (kitchenMaxX - kitchenMinX)); // [cite: 1589]
  2125.             cueBall->y = kitchenMinY + static_cast<float>(rand()) / (static_cast<float>(RAND_MAX) / (kitchenMaxY - kitchenMinY)); // [cite: 1590]
  2126.             if (IsValidCueBallPosition(cueBall->x, cueBall->y, true)) { // [cite: 1591]
  2127.                 validPos = true; // [cite: 1591]*/
  2128.                 // Try the chosen X, but vary Y slightly to find a clear spot
  2129.             cueBall->x = placementX;
  2130.             cueBall->y = placementY + (static_cast<float>(rand() % 100 - 50) / 100.0f) * BALL_RADIUS * 2.0f; // Vary Y a bit
  2131.             cueBall->y = std::max(TABLE_TOP + BALL_RADIUS + 1.0f, std::min(cueBall->y, TABLE_BOTTOM - BALL_RADIUS - 1.0f)); // Clamp Y
  2132.  
  2133.             if (IsValidCueBallPosition(cueBall->x, cueBall->y, true /* behind headstring */)) {
  2134.                 validPos = true;
  2135.             }
  2136.             attempts++; // [cite: 1592]
  2137.         }
  2138.         if (!validPos) {
  2139.             // Fallback position
  2140.             /*cueBall->x = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f; // [cite: 1071, 1078, 1593]
  2141.             cueBall->y = (TABLE_TOP + TABLE_BOTTOM) * 0.5f; // [cite: 1071, 1073, 1594]
  2142.             if (!IsValidCueBallPosition(cueBall->x, cueBall->y, true)) { // [cite: 1594]
  2143.                 cueBall->x = HEADSTRING_X - BALL_RADIUS * 2; // [cite: 1072, 1078, 1594]
  2144.                 cueBall->y = RACK_POS_Y; // [cite: 1080, 1595]
  2145.             }
  2146.         }
  2147.         cueBall->vx = 0; // [cite: 1595]
  2148.         cueBall->vy = 0; // [cite: 1596]
  2149.  
  2150.         // Plan a break shot: aim at the center of the rack (apex ball)
  2151.         float targetX = RACK_POS_X; // [cite: 1079] Aim for the apex ball X-coordinate
  2152.         float targetY = RACK_POS_Y; // [cite: 1080] Aim for the apex ball Y-coordinate
  2153.  
  2154.         float dx = targetX - cueBall->x; // [cite: 1599]
  2155.         float dy = targetY - cueBall->y; // [cite: 1600]
  2156.         float shotAngle = atan2f(dy, dx); // [cite: 1600]
  2157.         float shotPowerValue = MAX_SHOT_POWER; // [cite: 1076, 1600] Use MAX_SHOT_POWER*/
  2158.  
  2159.             cueBall->x = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.75f; // A default safe spot in kitchen
  2160.             cueBall->y = RACK_POS_Y;
  2161.         }
  2162.         cueBall->vx = 0; cueBall->vy = 0;
  2163.  
  2164.         // --- AI Plans the Break Shot ---
  2165.         float targetX, targetY;
  2166.         // If cue ball is near center of kitchen width, aim for apex.
  2167.         // Otherwise, aim for the second ball on the side the cue ball is on (for a cut break).
  2168.         float kitchenCenterRegion = (HEADSTRING_X - TABLE_LEFT) * 0.3f; // Define a "center" region
  2169.         if (std::abs(cueBall->x - (TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) / 2.0f)) < kitchenCenterRegion / 2.0f) {
  2170.             // Center-ish placement: Aim for the apex ball (ball ID 1 or first ball in rack)
  2171.             targetX = RACK_POS_X; // Apex ball X
  2172.             targetY = RACK_POS_Y; // Apex ball Y
  2173.         }
  2174.         else {
  2175.             // Side placement: Aim to hit the "second" ball of the rack for a wider spread.
  2176.             // This is a simplification. A more robust way is to find the actual second ball.
  2177.             // For now, aim slightly off the apex towards the side the cue ball is on.
  2178.             targetX = RACK_POS_X + BALL_RADIUS * 2.0f * 0.866f; // X of the second row of balls
  2179.             targetY = RACK_POS_Y + ((cueBall->y > RACK_POS_Y) ? -BALL_RADIUS : BALL_RADIUS); // Aim at the upper or lower of the two second-row balls
  2180.         }
  2181.  
  2182.         float dx = targetX - cueBall->x;
  2183.         float dy = targetY - cueBall->y;
  2184.         float shotAngle = atan2f(dy, dx);
  2185.         float shotPowerValue = MAX_SHOT_POWER * (0.9f + (rand() % 11) / 100.0f); // Slightly vary max power
  2186.  
  2187.         // Store planned shot details for the AI
  2188.         /*aiPlannedShotDetails.angle = shotAngle; // [cite: 1102, 1601]
  2189.         aiPlannedShotDetails.power = shotPowerValue; // [cite: 1102, 1601]
  2190.         aiPlannedShotDetails.spinX = 0.0f; // [cite: 1102, 1601] No spin for a standard power break
  2191.         aiPlannedShotDetails.spinY = 0.0f; // [cite: 1103, 1602]
  2192.         aiPlannedShotDetails.isValid = true; // [cite: 1103, 1602]*/
  2193.  
  2194.         aiPlannedShotDetails.angle = shotAngle;
  2195.         aiPlannedShotDetails.power = shotPowerValue;
  2196.         aiPlannedShotDetails.spinX = 0.0f; // No spin for break usually
  2197.         aiPlannedShotDetails.spinY = 0.0f;
  2198.         aiPlannedShotDetails.isValid = true;
  2199.  
  2200.         // Update global cue parameters for immediate visual feedback if DrawAimingAids uses them
  2201.         /*::cueAngle = aiPlannedShotDetails.angle;      // [cite: 1109, 1603] Update global cueAngle
  2202.         ::shotPower = aiPlannedShotDetails.power;     // [cite: 1109, 1604] Update global shotPower
  2203.         ::cueSpinX = aiPlannedShotDetails.spinX;    // [cite: 1109]
  2204.         ::cueSpinY = aiPlannedShotDetails.spinY;    // [cite: 1110]*/
  2205.  
  2206.         ::cueAngle = aiPlannedShotDetails.angle;
  2207.         ::shotPower = aiPlannedShotDetails.power;
  2208.         ::cueSpinX = aiPlannedShotDetails.spinX;
  2209.         ::cueSpinY = aiPlannedShotDetails.spinY;
  2210.  
  2211.         // Set up for AI display via GameUpdate
  2212.         /*aiIsDisplayingAim = true;                   // [cite: 1104] Enable AI aiming visualization
  2213.         aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES; // [cite: 1105] Set duration for display
  2214.  
  2215.         currentGameState = AI_THINKING; // [cite: 1081] Transition to AI_THINKING state.
  2216.                                         // GameUpdate will handle the aiAimDisplayFramesLeft countdown
  2217.                                         // and then execute the shot using aiPlannedShotDetails.
  2218.                                         // isOpeningBreakShot will be set to false within ApplyShot.
  2219.  
  2220.         // No immediate ApplyShot or sound here; GameUpdate's AI execution logic will handle it.*/
  2221.  
  2222.         aiIsDisplayingAim = true;
  2223.         aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES;
  2224.         currentGameState = AI_THINKING; // State changes to AI_THINKING, GameUpdate will handle shot execution after display
  2225.  
  2226.         return; // The break shot is now planned and will be executed by GameUpdate
  2227.     }
  2228.  
  2229.     // 2. If not in PRE_BREAK_PLACEMENT (e.g., if this function were called at other times,
  2230.     //    though current game logic only calls it for PRE_BREAK_PLACEMENT)
  2231.     //    This part can be extended if AIBreakShot needs to handle other scenarios.
  2232.     //    For now, the primary logic is above.
  2233. }
  2234.  
  2235. // --- Helper Functions ---
  2236.  
  2237. Ball* GetBallById(int id) {
  2238.     for (size_t i = 0; i < balls.size(); ++i) {
  2239.         if (balls[i].id == id) {
  2240.             return &balls[i];
  2241.         }
  2242.     }
  2243.     return nullptr;
  2244. }
  2245.  
  2246. Ball* GetCueBall() {
  2247.     return GetBallById(0);
  2248. }
  2249.  
  2250. float GetDistance(float x1, float y1, float x2, float y2) {
  2251.     return sqrtf(GetDistanceSq(x1, y1, x2, y2));
  2252. }
  2253.  
  2254. float GetDistanceSq(float x1, float y1, float x2, float y2) {
  2255.     float dx = x2 - x1;
  2256.     float dy = y2 - y1;
  2257.     return dx * dx + dy * dy;
  2258. }
  2259.  
  2260. bool IsValidCueBallPosition(float x, float y, bool checkHeadstring) {
  2261.     // Basic bounds check (inside cushions)
  2262.     float left = TABLE_LEFT + CUSHION_THICKNESS + BALL_RADIUS;
  2263.     float right = TABLE_RIGHT - CUSHION_THICKNESS - BALL_RADIUS;
  2264.     float top = TABLE_TOP + CUSHION_THICKNESS + BALL_RADIUS;
  2265.     float bottom = TABLE_BOTTOM - CUSHION_THICKNESS - BALL_RADIUS;
  2266.  
  2267.     if (x < left || x > right || y < top || y > bottom) {
  2268.         return false;
  2269.     }
  2270.  
  2271.     // Check headstring restriction if needed
  2272.     if (checkHeadstring && x >= HEADSTRING_X) {
  2273.         return false;
  2274.     }
  2275.  
  2276.     // Check overlap with other balls
  2277.     for (size_t i = 0; i < balls.size(); ++i) {
  2278.         if (balls[i].id != 0 && !balls[i].isPocketed) { // Don't check against itself or pocketed balls
  2279.             if (GetDistanceSq(x, y, balls[i].x, balls[i].y) < (BALL_RADIUS * 2.0f) * (BALL_RADIUS * 2.0f)) {
  2280.                 return false; // Overlapping another ball
  2281.             }
  2282.         }
  2283.     }
  2284.  
  2285.     return true;
  2286. }
  2287.  
  2288.  
  2289. template <typename T>
  2290. void SafeRelease(T** ppT) {
  2291.     if (*ppT) {
  2292.         (*ppT)->Release();
  2293.         *ppT = nullptr;
  2294.     }
  2295. }
  2296.  
  2297. // --- Helper Function for Line Segment Intersection ---
  2298. // Finds intersection point of line segment P1->P2 and line segment P3->P4
  2299. // Returns true if they intersect, false otherwise. Stores intersection point in 'intersection'.
  2300. bool LineSegmentIntersection(D2D1_POINT_2F p1, D2D1_POINT_2F p2, D2D1_POINT_2F p3, D2D1_POINT_2F p4, D2D1_POINT_2F& intersection)
  2301. {
  2302.     float denominator = (p4.y - p3.y) * (p2.x - p1.x) - (p4.x - p3.x) * (p2.y - p1.y);
  2303.  
  2304.     // Check if lines are parallel or collinear
  2305.     if (fabs(denominator) < 1e-6) {
  2306.         return false;
  2307.     }
  2308.  
  2309.     float ua = ((p4.x - p3.x) * (p1.y - p3.y) - (p4.y - p3.y) * (p1.x - p3.x)) / denominator;
  2310.     float ub = ((p2.x - p1.x) * (p1.y - p3.y) - (p2.y - p1.y) * (p1.x - p3.x)) / denominator;
  2311.  
  2312.     // Check if intersection point lies on both segments
  2313.     if (ua >= 0.0f && ua <= 1.0f && ub >= 0.0f && ub <= 1.0f) {
  2314.         intersection.x = p1.x + ua * (p2.x - p1.x);
  2315.         intersection.y = p1.y + ua * (p2.y - p1.y);
  2316.         return true;
  2317.     }
  2318.  
  2319.     return false;
  2320. }
  2321.  
  2322. // --- INSERT NEW HELPER FUNCTION HERE ---
  2323. // Calculates the squared distance from point P to the line segment AB.
  2324. float PointToLineSegmentDistanceSq(D2D1_POINT_2F p, D2D1_POINT_2F a, D2D1_POINT_2F b) {
  2325.     float l2 = GetDistanceSq(a.x, a.y, b.x, b.y);
  2326.     if (l2 == 0.0f) return GetDistanceSq(p.x, p.y, a.x, a.y); // Segment is a point
  2327.     // Consider P projecting onto the line AB infinite line
  2328.     // t = [(P-A) . (B-A)] / |B-A|^2
  2329.     float t = ((p.x - a.x) * (b.x - a.x) + (p.y - a.y) * (b.y - a.y)) / l2;
  2330.     t = std::max(0.0f, std::min(1.0f, t)); // Clamp t to the segment [0, 1]
  2331.     // Projection falls on the segment
  2332.     D2D1_POINT_2F projection = D2D1::Point2F(a.x + t * (b.x - a.x), a.y + t * (b.y - a.y));
  2333.     return GetDistanceSq(p.x, p.y, projection.x, projection.y);
  2334. }
  2335. // --- End New Helper ---
  2336.  
  2337. // --- NEW AI Implementation Functions ---
  2338.  
  2339. // Main entry point for AI turn
  2340. void AIMakeDecision() {
  2341.     //AIShotInfo bestShot = { false }; // Declare here
  2342.     // This function is called when currentGameState is AI_THINKING (for a normal shot decision)
  2343.     Ball* cueBall = GetCueBall();
  2344.     if (!cueBall || !isPlayer2AI || currentPlayer != 2) {
  2345.         aiPlannedShotDetails.isValid = false; // Ensure no shot if conditions not met
  2346.         return;
  2347.     }
  2348.  
  2349.     // Phase 1: Placement if needed (Ball-in-Hand or Initial Break)
  2350.     /*if ((isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT) || currentGameState == BALL_IN_HAND_P2) {
  2351.         AIPlaceCueBall(); // Handles kitchen placement for break or regular ball-in-hand
  2352.         if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT) {
  2353.             currentGameState = BREAKING; // Now AI needs to decide the break shot parameters
  2354.         }
  2355.         // For regular BALL_IN_HAND_P2, after placement, it will proceed to find a shot.
  2356.     }*/
  2357.  
  2358.     aiPlannedShotDetails.isValid = false; // Default to no valid shot found yet for this decision cycle
  2359.     // Note: isOpeningBreakShot is false here because AIBreakShot handles the break.
  2360.  
  2361.      // Phase 2: Decide shot parameters (Break or Normal play)
  2362.     /*if (isOpeningBreakShot && currentGameState == BREAKING) {
  2363.         // Force cue ball into center of kitchen
  2364.         cueBall->x = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f;
  2365.         cueBall->y = (TABLE_TOP + TABLE_BOTTOM) * 0.5f;
  2366.         cueBall->vx = cueBall->vy = 0.0f;
  2367.  
  2368.         float rackCenterX = RACK_POS_X + BALL_RADIUS * 2.0f * 0.866f * 2.0f;
  2369.         float rackCenterY = RACK_POS_Y;
  2370.         float dx = rackCenterX - cueBall->x;
  2371.         float dy = rackCenterY - cueBall->y;
  2372.  
  2373.         aiPlannedShotDetails.angle = atan2f(dy, dx);
  2374.         aiPlannedShotDetails.power = MAX_SHOT_POWER;
  2375.         aiPlannedShotDetails.spinX = 0.0f;
  2376.         aiPlannedShotDetails.spinY = 0.0f;
  2377.         aiPlannedShotDetails.isValid = true;
  2378.  
  2379.         // Apply shot immediately
  2380.         cueAngle = aiPlannedShotDetails.angle;
  2381.         shotPower = aiPlannedShotDetails.power;
  2382.         cueSpinX = aiPlannedShotDetails.spinX;
  2383.         cueSpinY = aiPlannedShotDetails.spinY;
  2384.  
  2385.         firstHitBallIdThisShot = -1;
  2386.         cueHitObjectBallThisShot = false;
  2387.         railHitAfterContact = false;
  2388.         isAiming = false;
  2389.         aiIsDisplayingAim = false;
  2390.         aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES;
  2391.         //bool aiIsDisplayingAim = true;
  2392.  
  2393.         std::thread([](const TCHAR* soundName) {
  2394.             PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT);
  2395.             }, TEXT("cue.wav")).detach();
  2396.  
  2397.             ApplyShot(shotPower, cueAngle, cueSpinX, cueSpinY);
  2398.             currentGameState = SHOT_IN_PROGRESS;
  2399.             isOpeningBreakShot = false;
  2400.             aiTurnPending = false;
  2401.             pocketedThisTurn.clear();
  2402.             return;
  2403.     }
  2404.     else {*/
  2405.     // --- Normal AI Shot Decision (using AIFindBestShot) ---
  2406.     AIShotInfo bestShot = AIFindBestShot(); // bugtraq
  2407.     //bestShot = AIFindBestShot(); // bugtraq
  2408.     if (bestShot.possible) {
  2409.         aiPlannedShotDetails.angle = bestShot.angle;
  2410.         aiPlannedShotDetails.power = bestShot.power;
  2411.         aiPlannedShotDetails.spinX = 0.0f; // AI doesn't use spin yet
  2412.         aiPlannedShotDetails.spinY = 0.0f;
  2413.         aiPlannedShotDetails.isValid = true;
  2414.     }
  2415.     else {
  2416.         // Safety tap if no better shot found
  2417.         // Try to hit the closest 'own' ball gently or any ball if types not assigned
  2418.         Ball* ballToNudge = nullptr;
  2419.         float minDistSq = -1.0f;
  2420.         BallType aiTargetType = player2Info.assignedType;
  2421.         bool mustHit8Ball = (aiTargetType != BallType::NONE && player2Info.ballsPocketedCount >= 7);
  2422.  
  2423.         for (auto& b : balls) {
  2424.             if (b.isPocketed || b.id == 0) continue;
  2425.             bool canHitThis = false;
  2426.             if (mustHit8Ball) canHitThis = (b.id == 8);
  2427.             else if (aiTargetType != BallType::NONE) canHitThis = (b.type == aiTargetType);
  2428.             else canHitThis = (b.id != 8); // Can hit any non-8-ball if types not assigned
  2429.  
  2430.             if (canHitThis) {
  2431.                 float dSq = GetDistanceSq(cueBall->x, cueBall->y, b.x, b.y);
  2432.                 if (ballToNudge == nullptr || dSq < minDistSq) {
  2433.                     ballToNudge = &b;
  2434.                     minDistSq = dSq;
  2435.                 }
  2436.             }
  2437.         }
  2438.         if (ballToNudge) { // Found a ball to nudge
  2439.             aiPlannedShotDetails.angle = atan2f(ballToNudge->y - cueBall->y, ballToNudge->x - cueBall->x);
  2440.             aiPlannedShotDetails.power = MAX_SHOT_POWER * 0.15f; // Gentle tap
  2441.         }
  2442.         else { // Absolute fallback: small tap forward
  2443.             aiPlannedShotDetails.angle = cueAngle; // Keep last angle or default
  2444.             //aiPlannedShotDetails.power = MAX_SHOT_POWER * 0.1f;
  2445.             aiPlannedShotDetails.power = MAX_SHOT_POWER * 0.1f;
  2446.         }
  2447.         aiPlannedShotDetails.spinX = 0.0f;
  2448.         aiPlannedShotDetails.spinY = 0.0f;
  2449.         aiPlannedShotDetails.isValid = true; // Safety shot is a "valid" plan
  2450.     }
  2451.     //} //bracefix
  2452.  
  2453.     // Phase 3: Setup for Aim Display (if a valid shot was decided)
  2454.     if (aiPlannedShotDetails.isValid) {
  2455.         cueAngle = aiPlannedShotDetails.angle;   // Update global for drawing
  2456.         shotPower = aiPlannedShotDetails.power;  // Update global for drawing
  2457.         // cueSpinX and cueSpinY could also be set here if AI used them
  2458.         cueSpinX = aiPlannedShotDetails.spinX; // Also set these for drawing consistency
  2459.         cueSpinY = aiPlannedShotDetails.spinY; //
  2460.  
  2461.         aiIsDisplayingAim = true;
  2462.         aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES;
  2463.         // currentGameState remains AI_THINKING, GameUpdate will handle the display countdown and shot execution.
  2464.             // FIRE THE BREAK SHOT NOW
  2465.             // Immediately execute the break shot after setting parameters
  2466.         /*ApplyShot(aiPlannedShotDetails.power, aiPlannedShotDetails.angle, aiPlannedShotDetails.spinX, aiPlannedShotDetails.spinY);
  2467.         currentGameState = SHOT_IN_PROGRESS;
  2468.         aiTurnPending = false;
  2469.         isOpeningBreakShot = false;*/
  2470.     }
  2471.     else {
  2472.         // Should not happen if safety shot is always planned, but as a fallback:
  2473.         aiIsDisplayingAim = false;
  2474.         // If AI truly can't decide anything, maybe switch turn or log error. For now, it will do nothing this frame.
  2475.         // Or force a minimal safety tap without display.
  2476.         // To ensure game progresses, let's plan a minimal tap if nothing else.
  2477.         if (!aiPlannedShotDetails.isValid) { // Double check
  2478.             aiPlannedShotDetails.angle = 0.0f;
  2479.             aiPlannedShotDetails.power = MAX_SHOT_POWER * 0.05f; // Very small tap
  2480.             aiPlannedShotDetails.spinX = 0.0f; aiPlannedShotDetails.spinY = 0.0f;
  2481.             aiPlannedShotDetails.isValid = true;
  2482.             //cueAngle = aiPlannedShotDetails.angle; shotPower = aiPlannedShotDetails.power;
  2483.             cueAngle = aiPlannedShotDetails.angle;
  2484.             shotPower = aiPlannedShotDetails.power;
  2485.             cueSpinX = aiPlannedShotDetails.spinX;
  2486.             cueSpinY = aiPlannedShotDetails.spinY;
  2487.             aiIsDisplayingAim = true; // Allow display for this minimal tap too
  2488.             aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES / 2; // Shorter display for fallback
  2489.         }
  2490.     }
  2491.     // aiTurnPending was set to false by GameUpdate before calling AIMakeDecision.
  2492.     // AIMakeDecision's job is to populate aiPlannedShotDetails and trigger display.
  2493. }
  2494.  
  2495. // AI logic for placing cue ball during ball-in-hand
  2496. void AIPlaceCueBall() {
  2497.     Ball* cueBall = GetCueBall();
  2498.     if (!cueBall) return;
  2499.  
  2500.     // --- CPU AI Opening Break: Kitchen Placement ---
  2501.     /*if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT && currentPlayer == 2 && isPlayer2AI) {
  2502.         float kitchenMinX = TABLE_LEFT + BALL_RADIUS;
  2503.         float kitchenMaxX = HEADSTRING_X - BALL_RADIUS;
  2504.         float kitchenMinY = TABLE_TOP + BALL_RADIUS;
  2505.         float kitchenMaxY = TABLE_BOTTOM - BALL_RADIUS;
  2506.         bool validPositionFound = false;
  2507.         int attempts = 0;
  2508.         while (!validPositionFound && attempts < 100) {
  2509.             cueBall->x = kitchenMinX + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (kitchenMaxX - kitchenMinX)));
  2510.             cueBall->y = kitchenMinY + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (kitchenMaxY - kitchenMinY)));
  2511.             if (IsValidCueBallPosition(cueBall->x, cueBall->y, true)) {
  2512.                 validPositionFound = true;
  2513.             }
  2514.             attempts++;
  2515.         }
  2516.         if (!validPositionFound) {
  2517.             cueBall->x = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f;
  2518.             cueBall->y = TABLE_TOP + TABLE_HEIGHT / 2.0f;
  2519.             if (!IsValidCueBallPosition(cueBall->x, cueBall->y, true)) {
  2520.                 cueBall->x = HEADSTRING_X - BALL_RADIUS * 2.0f;
  2521.                 cueBall->y = RACK_POS_Y;
  2522.             }
  2523.         }
  2524.         cueBall->vx = 0; cueBall->vy = 0;
  2525.         return;
  2526.     }*/
  2527.     // --- End CPU AI Opening Break Placement ---
  2528.  
  2529.     // This function is now SOLELY for Ball-In-Hand placement for the AI (anywhere on the table).
  2530.     // Break placement is handled by AIBreakShot().
  2531.  
  2532.     // Simple Strategy: Find the easiest possible shot for the AI's ball type
  2533.     // Place the cue ball directly behind that target ball, aiming straight at a pocket.
  2534.     // (More advanced: find spot offering multiple options or safety)
  2535.  
  2536.     AIShotInfo bestPlacementShot = { false };
  2537.     D2D1_POINT_2F bestPlacePos = D2D1::Point2F(HEADSTRING_X * 0.5f, RACK_POS_Y); // Default placement
  2538.  
  2539.     // A better default for ball-in-hand (anywhere) might be center table if no shot found.
  2540.     bestPlacePos = D2D1::Point2F(TABLE_LEFT + TABLE_WIDTH / 2.0f, TABLE_TOP + TABLE_HEIGHT / 2.0f);
  2541.     float bestPlacementScore = -1.0f; // Keep track of the score for the best placement found
  2542.  
  2543.     BallType targetType = player2Info.assignedType;
  2544.     bool canTargetAnyPlacement = false; // Local scope variable for placement logic
  2545.     if (targetType == BallType::NONE) {
  2546.         canTargetAnyPlacement = true;
  2547.     }
  2548.     bool target8Ball = (!canTargetAnyPlacement && targetType != BallType::NONE && player2Info.ballsPocketedCount >= 7);
  2549.     if (target8Ball) targetType = BallType::EIGHT_BALL;
  2550.  
  2551.  
  2552.     for (auto& targetBall : balls) {
  2553.         if (targetBall.isPocketed || targetBall.id == 0) continue;
  2554.  
  2555.         // Determine if current ball is a valid target for placement consideration
  2556.         bool currentBallIsValidTarget = false;
  2557.         if (target8Ball && targetBall.id == 8) currentBallIsValidTarget = true;
  2558.         else if (canTargetAnyPlacement && targetBall.id != 8) currentBallIsValidTarget = true;
  2559.         else if (!canTargetAnyPlacement && !target8Ball && targetBall.type == targetType) currentBallIsValidTarget = true;
  2560.  
  2561.         if (!currentBallIsValidTarget) continue; // Skip if not a valid target
  2562.  
  2563.         for (int p = 0; p < 6; ++p) {
  2564.             // Calculate ideal cue ball position: straight line behind target ball aiming at pocket p
  2565.             float targetToPocketX = pocketPositions[p].x - targetBall.x;
  2566.             float targetToPocketY = pocketPositions[p].y - targetBall.y;
  2567.             float dist = sqrtf(targetToPocketX * targetToPocketX + targetToPocketY * targetToPocketY);
  2568.             if (dist < 1.0f) continue; // Avoid division by zero
  2569.  
  2570.             float idealAngle = atan2f(targetToPocketY, targetToPocketX);
  2571.             // Place cue ball slightly behind target ball along this line
  2572.             float placeDist = BALL_RADIUS * 3.0f; // Place a bit behind
  2573.             D2D1_POINT_2F potentialPlacePos = D2D1::Point2F( // Use factory function
  2574.                 targetBall.x - cosf(idealAngle) * placeDist,
  2575.                 targetBall.y - sinf(idealAngle) * placeDist
  2576.             );
  2577.  
  2578.             // Check if this placement is valid (on table, behind headstring if break, not overlapping)
  2579.             /*bool behindHeadstringRule = (currentGameState == PRE_BREAK_PLACEMENT);*/
  2580.             // For ball-in-hand (NOT break), behindHeadstringRule is false.
  2581.             // The currentGameState should be BALL_IN_HAND_P2 when this is called for a foul.
  2582.             bool behindHeadstringRule = false; // Player can place anywhere after a foul
  2583.             if (IsValidCueBallPosition(potentialPlacePos.x, potentialPlacePos.y, behindHeadstringRule)) {
  2584.                 // Is path from potentialPlacePos to targetBall clear?
  2585.                 // Use D2D1::Point2F() factory function here
  2586.                 if (IsPathClear(potentialPlacePos, D2D1::Point2F(targetBall.x, targetBall.y), 0, targetBall.id)) {
  2587.                     // Is path from targetBall to pocket clear?
  2588.                     // Use D2D1::Point2F() factory function here
  2589.                     if (IsPathClear(D2D1::Point2F(targetBall.x, targetBall.y), pocketPositions[p], targetBall.id, -1)) {
  2590.                         // This seems like a good potential placement. Score it?
  2591.                         // Easy AI: Just take the first valid one found.
  2592.                         /*bestPlacePos = potentialPlacePos;
  2593.                         goto placement_found;*/ // Use goto for simplicity in non-OOP structure
  2594.                         // This is a possible shot. Score this placement.
  2595. // A simple score: distance to target ball (shorter is better for placement).
  2596. // More advanced: consider angle to pocket, difficulty of the shot from this placement.
  2597.                         AIShotInfo tempShotInfo;
  2598.                         tempShotInfo.possible = true;
  2599.                         tempShotInfo.targetBall = &targetBall;
  2600.                         tempShotInfo.pocketIndex = p;
  2601.                         tempShotInfo.ghostBallPos = CalculateGhostBallPos(&targetBall, p); // Not strictly needed for placement score but good for consistency
  2602.                         tempShotInfo.angle = idealAngle; // The angle from the placed ball to target
  2603.                         // Use EvaluateShot's scoring mechanism if possible, or a simpler one here.
  2604.                         float currentScore = 1000.0f / (1.0f + GetDistance(potentialPlacePos.x, potentialPlacePos.y, targetBall.x, targetBall.y)); // Inverse distance
  2605.  
  2606.                         if (currentScore > bestPlacementScore) {
  2607.                             bestPlacementScore = currentScore;
  2608.                             bestPlacePos = potentialPlacePos;
  2609.                         }
  2610.                     }
  2611.                 }
  2612.             }
  2613.         }
  2614.     }
  2615.  
  2616. placement_found:
  2617.     // Place the cue ball at the best found position (or default if no good spot found)
  2618.     cueBall->x = bestPlacePos.x;
  2619.     cueBall->y = bestPlacePos.y;
  2620.     cueBall->vx = 0;
  2621.     cueBall->vy = 0;
  2622. }
  2623.  
  2624.  
  2625. // AI finds the best shot available on the table
  2626. AIShotInfo AIFindBestShot() {
  2627.     AIShotInfo bestShotOverall = { false };
  2628.     Ball* cueBall = GetCueBall();
  2629.     if (!cueBall) return bestShotOverall;
  2630.     // Ensure cue ball position is up-to-date if AI just placed it
  2631.     // (AIPlaceCueBall should have already set cueBall->x, cueBall->y)
  2632.  
  2633.     // Determine target ball type for AI (Player 2)
  2634.     BallType targetType = player2Info.assignedType;
  2635.     bool canTargetAny = false; // Can AI hit any ball (e.g., after break, before assignment)?
  2636.     if (targetType == BallType::NONE) {
  2637.         // If colors not assigned, AI aims to pocket *something* (usually lowest numbered ball legally)
  2638.         // Or, more simply, treat any ball as a potential target to make *a* pocket
  2639.         canTargetAny = true; // Simplification: allow targeting any non-8 ball.
  2640.         // A better rule is hit lowest numbered ball first on break follow-up.
  2641.     }
  2642.  
  2643.     // Check if AI needs to shoot the 8-ball
  2644.     bool target8Ball = (!canTargetAny && targetType != BallType::NONE && player2Info.ballsPocketedCount >= 7);
  2645.  
  2646.  
  2647.     // Iterate through all potential target balls
  2648.     for (auto& potentialTarget : balls) {
  2649.         if (potentialTarget.isPocketed || potentialTarget.id == 0) continue; // Skip pocketed and cue ball
  2650.  
  2651.         // Check if this ball is a valid target
  2652.         bool isValidTarget = false;
  2653.         if (target8Ball) {
  2654.             isValidTarget = (potentialTarget.id == 8);
  2655.         }
  2656.         else if (canTargetAny) {
  2657.             isValidTarget = (potentialTarget.id != 8); // Can hit any non-8 ball
  2658.         }
  2659.         else { // Colors assigned, not yet shooting 8-ball
  2660.             isValidTarget = (potentialTarget.type == targetType);
  2661.         }
  2662.  
  2663.         if (!isValidTarget) continue; // Skip if not a valid target for this turn
  2664.  
  2665.         // Now, check all pockets for this target ball
  2666.         for (int p = 0; p < 6; ++p) {
  2667.             AIShotInfo currentShot = EvaluateShot(&potentialTarget, p);
  2668.             currentShot.involves8Ball = (potentialTarget.id == 8);
  2669.  
  2670.             if (currentShot.possible) {
  2671.                 // Compare scores to find the best shot
  2672.                 if (!bestShotOverall.possible || currentShot.score > bestShotOverall.score) {
  2673.                     bestShotOverall = currentShot;
  2674.                 }
  2675.             }
  2676.         }
  2677.     } // End loop through potential target balls
  2678.  
  2679.     // If targeting 8-ball and no shot found, or targeting own balls and no shot found,
  2680.     // need a safety strategy. Current simple AI just takes best found or taps cue ball.
  2681.  
  2682.     return bestShotOverall;
  2683. }
  2684.  
  2685.  
  2686. // Evaluate a potential shot at a specific target ball towards a specific pocket
  2687. AIShotInfo EvaluateShot(Ball* targetBall, int pocketIndex) {
  2688.     AIShotInfo shotInfo;
  2689.     shotInfo.possible = false; // Assume not possible initially
  2690.     shotInfo.targetBall = targetBall;
  2691.     shotInfo.pocketIndex = pocketIndex;
  2692.  
  2693.     Ball* cueBall = GetCueBall();
  2694.     if (!cueBall || !targetBall) return shotInfo;
  2695.  
  2696.     // --- Define local state variables needed for legality checks ---
  2697.     BallType aiAssignedType = player2Info.assignedType;
  2698.     bool canTargetAny = (aiAssignedType == BallType::NONE); // Can AI hit any ball?
  2699.     bool mustTarget8Ball = (!canTargetAny && aiAssignedType != BallType::NONE && player2Info.ballsPocketedCount >= 7);
  2700.     // ---
  2701.  
  2702.     // 1. Calculate Ghost Ball position
  2703.     shotInfo.ghostBallPos = CalculateGhostBallPos(targetBall, pocketIndex);
  2704.  
  2705.     // 2. Calculate Angle from Cue Ball to Ghost Ball
  2706.     float dx = shotInfo.ghostBallPos.x - cueBall->x;
  2707.     float dy = shotInfo.ghostBallPos.y - cueBall->y;
  2708.     if (fabs(dx) < 0.01f && fabs(dy) < 0.01f) return shotInfo; // Avoid aiming at same spot
  2709.     shotInfo.angle = atan2f(dy, dx);
  2710.  
  2711.     // Basic angle validity check (optional)
  2712.     if (!IsValidAIAimAngle(shotInfo.angle)) {
  2713.         // Maybe log this or handle edge cases
  2714.     }
  2715.  
  2716.     // 3. Check Path: Cue Ball -> Ghost Ball Position
  2717.     // Use D2D1::Point2F() factory function here
  2718.     if (!IsPathClear(D2D1::Point2F(cueBall->x, cueBall->y), shotInfo.ghostBallPos, cueBall->id, targetBall->id)) {
  2719.         return shotInfo; // Path blocked
  2720.     }
  2721.  
  2722.     // 4. Check Path: Target Ball -> Pocket
  2723.     // Use D2D1::Point2F() factory function here
  2724.     if (!IsPathClear(D2D1::Point2F(targetBall->x, targetBall->y), pocketPositions[pocketIndex], targetBall->id, -1)) {
  2725.         return shotInfo; // Path blocked
  2726.     }
  2727.  
  2728.     // 5. Check First Ball Hit Legality
  2729.     float firstHitDistSq = -1.0f;
  2730.     // Use D2D1::Point2F() factory function here
  2731.     Ball* firstHit = FindFirstHitBall(D2D1::Point2F(cueBall->x, cueBall->y), shotInfo.angle, firstHitDistSq);
  2732.  
  2733.     if (!firstHit) {
  2734.         return shotInfo; // AI aims but doesn't hit anything? Impossible shot.
  2735.     }
  2736.  
  2737.     // Check if the first ball hit is the intended target ball
  2738.     if (firstHit->id != targetBall->id) {
  2739.         // Allow hitting slightly off target if it's very close to ghost ball pos
  2740.         float ghostDistSq = GetDistanceSq(shotInfo.ghostBallPos.x, shotInfo.ghostBallPos.y, firstHit->x, firstHit->y);
  2741.         // Allow a tolerance roughly half the ball radius squared
  2742.         if (ghostDistSq > (BALL_RADIUS * 0.7f) * (BALL_RADIUS * 0.7f)) {
  2743.             // First hit is significantly different from the target point.
  2744.             // This shot path leads to hitting the wrong ball first.
  2745.             return shotInfo; // Foul or unintended shot
  2746.         }
  2747.         // If first hit is not target, but very close, allow it for now (might still be foul based on type).
  2748.     }
  2749.  
  2750.     // Check legality of the *first ball actually hit* based on game rules
  2751.     if (!canTargetAny) { // Colors are assigned (or should be)
  2752.         if (mustTarget8Ball) { // Must hit 8-ball first
  2753.             if (firstHit->id != 8) {
  2754.                 // return shotInfo; // FOUL - Hitting wrong ball when aiming for 8-ball
  2755.                 // Keep shot possible for now, rely on AIFindBestShot to prioritize legal ones
  2756.             }
  2757.         }
  2758.         else { // Must hit own ball type first
  2759.             if (firstHit->type != aiAssignedType && firstHit->id != 8) { // Allow hitting 8-ball if own type blocked? No, standard rules usually require hitting own first.
  2760.                 // return shotInfo; // FOUL - Hitting opponent ball or 8-ball when shouldn't
  2761.                 // Keep shot possible for now, rely on AIFindBestShot to prioritize legal ones
  2762.             }
  2763.             else if (firstHit->id == 8) {
  2764.                 // return shotInfo; // FOUL - Hitting 8-ball when shouldn't
  2765.                 // Keep shot possible for now
  2766.             }
  2767.         }
  2768.     }
  2769.     // (If canTargetAny is true, hitting any ball except 8 first is legal - assuming not scratching)
  2770.  
  2771.  
  2772.     // 6. Calculate Score & Power (Difficulty affects this)
  2773.     shotInfo.possible = true; // If we got here, the shot is geometrically possible and likely legal enough for AI to consider
  2774.  
  2775.     float cueToGhostDist = GetDistance(cueBall->x, cueBall->y, shotInfo.ghostBallPos.x, shotInfo.ghostBallPos.y);
  2776.     float targetToPocketDist = GetDistance(targetBall->x, targetBall->y, pocketPositions[pocketIndex].x, pocketPositions[pocketIndex].y);
  2777.  
  2778.     // Simple Score: Shorter shots are better, straighter shots are slightly better.
  2779.     float distanceScore = 1000.0f / (1.0f + cueToGhostDist + targetToPocketDist);
  2780.  
  2781.     // Angle Score: Calculate cut angle
  2782.     // Vector Cue -> Ghost
  2783.     float v1x = shotInfo.ghostBallPos.x - cueBall->x;
  2784.     float v1y = shotInfo.ghostBallPos.y - cueBall->y;
  2785.     // Vector Target -> Pocket
  2786.     float v2x = pocketPositions[pocketIndex].x - targetBall->x;
  2787.     float v2y = pocketPositions[pocketIndex].y - targetBall->y;
  2788.     // Normalize vectors
  2789.     float mag1 = sqrtf(v1x * v1x + v1y * v1y);
  2790.     float mag2 = sqrtf(v2x * v2x + v2y * v2y);
  2791.     float angleScoreFactor = 0.5f; // Default if vectors are zero len
  2792.     if (mag1 > 0.1f && mag2 > 0.1f) {
  2793.         v1x /= mag1; v1y /= mag1;
  2794.         v2x /= mag2; v2y /= mag2;
  2795.         // Dot product gives cosine of angle between cue ball path and target ball path
  2796.         float dotProduct = v1x * v2x + v1y * v2y;
  2797.         // Straighter shot (dot product closer to 1) gets higher score
  2798.         angleScoreFactor = (1.0f + dotProduct) / 2.0f; // Map [-1, 1] to [0, 1]
  2799.     }
  2800.     angleScoreFactor = std::max(0.1f, angleScoreFactor); // Ensure some minimum score factor
  2801.  
  2802.     shotInfo.score = distanceScore * angleScoreFactor;
  2803.  
  2804.     // Bonus for pocketing 8-ball legally
  2805.     if (mustTarget8Ball && targetBall->id == 8) {
  2806.         shotInfo.score *= 10.0; // Strongly prefer the winning shot
  2807.     }
  2808.  
  2809.     // Penalty for difficult cuts? Already partially handled by angleScoreFactor.
  2810.  
  2811.     // 7. Calculate Power
  2812.     shotInfo.power = CalculateShotPower(cueToGhostDist, targetToPocketDist);
  2813.  
  2814.     // 8. Add Inaccuracy based on Difficulty (same as before)
  2815.     float angleError = 0.0f;
  2816.     float powerErrorFactor = 1.0f;
  2817.  
  2818.     switch (aiDifficulty) {
  2819.     case EASY:
  2820.         angleError = (float)(rand() % 100 - 50) / 1000.0f; // +/- ~3 deg
  2821.         powerErrorFactor = 0.8f + (float)(rand() % 40) / 100.0f; // 80-120%
  2822.         shotInfo.power *= 0.8f;
  2823.         break;
  2824.     case MEDIUM:
  2825.         angleError = (float)(rand() % 60 - 30) / 1000.0f; // +/- ~1.7 deg
  2826.         powerErrorFactor = 0.9f + (float)(rand() % 20) / 100.0f; // 90-110%
  2827.         break;
  2828.     case HARD:
  2829.         angleError = (float)(rand() % 10 - 5) / 1000.0f; // +/- ~0.3 deg
  2830.         powerErrorFactor = 0.98f + (float)(rand() % 4) / 100.0f; // 98-102%
  2831.         break;
  2832.     }
  2833.     shotInfo.angle += angleError;
  2834.     shotInfo.power *= powerErrorFactor;
  2835.     shotInfo.power = std::max(1.0f, std::min(shotInfo.power, MAX_SHOT_POWER)); // Clamp power
  2836.  
  2837.     return shotInfo;
  2838. }
  2839.  
  2840.  
  2841. // Calculates required power (simplified)
  2842. float CalculateShotPower(float cueToGhostDist, float targetToPocketDist) {
  2843.     // Basic model: Power needed increases with total distance the balls need to travel.
  2844.     // Need enough power for cue ball to reach target AND target to reach pocket.
  2845.     float totalDist = cueToGhostDist + targetToPocketDist;
  2846.  
  2847.     // Map distance to power (needs tuning)
  2848.     // Let's say max power is needed for longest possible shot (e.g., corner to corner ~ 1000 units)
  2849.     float powerRatio = std::min(1.0f, totalDist / 800.0f); // Normalize based on estimated max distance
  2850.  
  2851.     float basePower = MAX_SHOT_POWER * 0.2f; // Minimum power to move balls reliably
  2852.     float variablePower = (MAX_SHOT_POWER * 0.8f) * powerRatio; // Scale remaining power range
  2853.  
  2854.     // Harder AI could adjust based on desired cue ball travel (more power for draw/follow)
  2855.     return std::min(MAX_SHOT_POWER, basePower + variablePower);
  2856. }
  2857.  
  2858. // Calculate the position the cue ball needs to hit for the target ball to go towards the pocket
  2859. D2D1_POINT_2F CalculateGhostBallPos(Ball* targetBall, int pocketIndex) {
  2860.     float targetToPocketX = pocketPositions[pocketIndex].x - targetBall->x;
  2861.     float targetToPocketY = pocketPositions[pocketIndex].y - targetBall->y;
  2862.     float dist = sqrtf(targetToPocketX * targetToPocketX + targetToPocketY * targetToPocketY);
  2863.  
  2864.     if (dist < 1.0f) { // Target is basically in the pocket
  2865.         // Aim slightly off-center to avoid weird physics? Or directly at center?
  2866.         // For simplicity, return a point slightly behind center along the reverse line.
  2867.         return D2D1::Point2F(targetBall->x - targetToPocketX * 0.1f, targetBall->y - targetToPocketY * 0.1f);
  2868.     }
  2869.  
  2870.     // Normalize direction vector from target to pocket
  2871.     float nx = targetToPocketX / dist;
  2872.     float ny = targetToPocketY / dist;
  2873.  
  2874.     // Ghost ball position is diameter distance *behind* the target ball along this line
  2875.     float ghostX = targetBall->x - nx * (BALL_RADIUS * 2.0f);
  2876.     float ghostY = targetBall->y - ny * (BALL_RADIUS * 2.0f);
  2877.  
  2878.     return D2D1::Point2F(ghostX, ghostY);
  2879. }
  2880.  
  2881. // Checks if line segment is clear of obstructing balls
  2882. bool IsPathClear(D2D1_POINT_2F start, D2D1_POINT_2F end, int ignoredBallId1, int ignoredBallId2) {
  2883.     float dx = end.x - start.x;
  2884.     float dy = end.y - start.y;
  2885.     float segmentLenSq = dx * dx + dy * dy;
  2886.  
  2887.     if (segmentLenSq < 0.01f) return true; // Start and end are same point
  2888.  
  2889.     for (const auto& ball : balls) {
  2890.         if (ball.isPocketed) continue;
  2891.         if (ball.id == ignoredBallId1) continue;
  2892.         if (ball.id == ignoredBallId2) continue;
  2893.  
  2894.         // Check distance from ball center to the line segment
  2895.         float ballToStartX = ball.x - start.x;
  2896.         float ballToStartY = ball.y - start.y;
  2897.  
  2898.         // Project ball center onto the line defined by the segment
  2899.         float dot = (ballToStartX * dx + ballToStartY * dy) / segmentLenSq;
  2900.  
  2901.         D2D1_POINT_2F closestPointOnLine;
  2902.         if (dot < 0) { // Closest point is start point
  2903.             closestPointOnLine = start;
  2904.         }
  2905.         else if (dot > 1) { // Closest point is end point
  2906.             closestPointOnLine = end;
  2907.         }
  2908.         else { // Closest point is along the segment
  2909.             closestPointOnLine = D2D1::Point2F(start.x + dot * dx, start.y + dot * dy);
  2910.         }
  2911.  
  2912.         // Check if the closest point is within collision distance (ball radius + path radius)
  2913.         if (GetDistanceSq(ball.x, ball.y, closestPointOnLine.x, closestPointOnLine.y) < (BALL_RADIUS * BALL_RADIUS)) {
  2914.             // Consider slightly wider path check? Maybe BALL_RADIUS * 1.1f?
  2915.             // if (GetDistanceSq(ball.x, ball.y, closestPointOnLine.x, closestPointOnLine.y) < (BALL_RADIUS * 1.1f)*(BALL_RADIUS*1.1f)) {
  2916.             return false; // Path is blocked
  2917.         }
  2918.     }
  2919.     return true; // No obstructions found
  2920. }
  2921.  
  2922. // Finds the first ball hit along a path (simplified)
  2923. Ball* FindFirstHitBall(D2D1_POINT_2F start, float angle, float& hitDistSq) {
  2924.     Ball* hitBall = nullptr;
  2925.     hitDistSq = -1.0f; // Initialize hit distance squared
  2926.     float minCollisionDistSq = -1.0f;
  2927.  
  2928.     float cosA = cosf(angle);
  2929.     float sinA = sinf(angle);
  2930.  
  2931.     for (auto& ball : balls) {
  2932.         if (ball.isPocketed || ball.id == 0) continue; // Skip cue ball and pocketed
  2933.  
  2934.         float dx = ball.x - start.x;
  2935.         float dy = ball.y - start.y;
  2936.  
  2937.         // Project vector from start->ball onto the aim direction vector
  2938.         float dot = dx * cosA + dy * sinA;
  2939.  
  2940.         if (dot > 0) { // Ball is generally in front
  2941.             // Find closest point on aim line to the ball's center
  2942.             float closestPointX = start.x + dot * cosA;
  2943.             float closestPointY = start.y + dot * sinA;
  2944.             float distSq = GetDistanceSq(ball.x, ball.y, closestPointX, closestPointY);
  2945.  
  2946.             // Check if the aim line passes within the ball's radius
  2947.             if (distSq < (BALL_RADIUS * BALL_RADIUS)) {
  2948.                 // Calculate distance from start to the collision point on the ball's circumference
  2949.                 float backDist = sqrtf(std::max(0.f, BALL_RADIUS * BALL_RADIUS - distSq));
  2950.                 float collisionDist = dot - backDist; // Distance along aim line to collision
  2951.  
  2952.                 if (collisionDist > 0) { // Ensure collision is in front
  2953.                     float collisionDistSq = collisionDist * collisionDist;
  2954.                     if (hitBall == nullptr || collisionDistSq < minCollisionDistSq) {
  2955.                         minCollisionDistSq = collisionDistSq;
  2956.                         hitBall = &ball; // Found a closer hit ball
  2957.                     }
  2958.                 }
  2959.             }
  2960.         }
  2961.     }
  2962.     hitDistSq = minCollisionDistSq; // Return distance squared to the first hit
  2963.     return hitBall;
  2964. }
  2965.  
  2966. // Basic check for reasonable AI aim angles (optional)
  2967. bool IsValidAIAimAngle(float angle) {
  2968.     // Placeholder - could check for NaN or infinity if calculations go wrong
  2969.     return isfinite(angle);
  2970. }
  2971.  
  2972. //midi func = start
  2973. void PlayMidiInBackground(HWND hwnd, const TCHAR* midiPath) {
  2974.     while (isMusicPlaying) {
  2975.         MCI_OPEN_PARMS mciOpen = { 0 };
  2976.         mciOpen.lpstrDeviceType = TEXT("sequencer");
  2977.         mciOpen.lpstrElementName = midiPath;
  2978.  
  2979.         if (mciSendCommand(0, MCI_OPEN, MCI_OPEN_TYPE | MCI_OPEN_ELEMENT, (DWORD_PTR)&mciOpen) == 0) {
  2980.             midiDeviceID = mciOpen.wDeviceID;
  2981.  
  2982.             MCI_PLAY_PARMS mciPlay = { 0 };
  2983.             mciSendCommand(midiDeviceID, MCI_PLAY, 0, (DWORD_PTR)&mciPlay);
  2984.  
  2985.             // Wait for playback to complete
  2986.             MCI_STATUS_PARMS mciStatus = { 0 };
  2987.             mciStatus.dwItem = MCI_STATUS_MODE;
  2988.  
  2989.             do {
  2990.                 mciSendCommand(midiDeviceID, MCI_STATUS, MCI_STATUS_ITEM, (DWORD_PTR)&mciStatus);
  2991.                 Sleep(100); // adjust as needed
  2992.             } while (mciStatus.dwReturn == MCI_MODE_PLAY && isMusicPlaying);
  2993.  
  2994.             mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
  2995.             midiDeviceID = 0;
  2996.         }
  2997.     }
  2998. }
  2999.  
  3000. void StartMidi(HWND hwnd, const TCHAR* midiPath) {
  3001.     if (isMusicPlaying) {
  3002.         StopMidi();
  3003.     }
  3004.     isMusicPlaying = true;
  3005.     musicThread = std::thread(PlayMidiInBackground, hwnd, midiPath);
  3006. }
  3007.  
  3008. void StopMidi() {
  3009.     if (isMusicPlaying) {
  3010.         isMusicPlaying = false;
  3011.         if (musicThread.joinable()) musicThread.join();
  3012.         if (midiDeviceID != 0) {
  3013.             mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
  3014.             midiDeviceID = 0;
  3015.         }
  3016.     }
  3017. }
  3018.  
  3019. /*void PlayGameMusic(HWND hwnd) {
  3020.     // Stop any existing playback
  3021.     if (isMusicPlaying) {
  3022.         isMusicPlaying = false;
  3023.         if (musicThread.joinable()) {
  3024.             musicThread.join();
  3025.         }
  3026.         if (midiDeviceID != 0) {
  3027.             mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
  3028.             midiDeviceID = 0;
  3029.         }
  3030.     }
  3031.  
  3032.     // Get the path of the executable
  3033.     TCHAR exePath[MAX_PATH];
  3034.     GetModuleFileName(NULL, exePath, MAX_PATH);
  3035.  
  3036.     // Extract the directory path
  3037.     TCHAR* lastBackslash = _tcsrchr(exePath, '\\');
  3038.     if (lastBackslash != NULL) {
  3039.         *(lastBackslash + 1) = '\0';
  3040.     }
  3041.  
  3042.     // Construct the full path to the MIDI file
  3043.     static TCHAR midiPath[MAX_PATH];
  3044.     _tcscpy_s(midiPath, MAX_PATH, exePath);
  3045.     _tcscat_s(midiPath, MAX_PATH, TEXT("BSQ.MID"));
  3046.  
  3047.     // Start the background playback
  3048.     isMusicPlaying = true;
  3049.     musicThread = std::thread(PlayMidiInBackground, hwnd, midiPath);
  3050. }*/
  3051. //midi func = end
  3052.  
  3053. // --- Drawing Functions ---
  3054.  
  3055. void OnPaint() {
  3056.     HRESULT hr = CreateDeviceResources(); // Ensure resources are valid
  3057.  
  3058.     if (SUCCEEDED(hr)) {
  3059.         pRenderTarget->BeginDraw();
  3060.         DrawScene(pRenderTarget); // Pass render target
  3061.         hr = pRenderTarget->EndDraw();
  3062.  
  3063.         if (hr == D2DERR_RECREATE_TARGET) {
  3064.             DiscardDeviceResources();
  3065.             // Optionally request another paint message: InvalidateRect(hwndMain, NULL, FALSE);
  3066.             // But the timer loop will trigger redraw anyway.
  3067.         }
  3068.     }
  3069.     // If CreateDeviceResources failed, EndDraw might not be called.
  3070.     // Consider handling this more robustly if needed.
  3071. }
  3072.  
  3073. void DrawScene(ID2D1RenderTarget* pRT) {
  3074.     if (!pRT) return;
  3075.  
  3076.     //pRT->Clear(D2D1::ColorF(D2D1::ColorF::LightGray)); // Background color
  3077.     // Set background color to #ffffcd (RGB: 255, 255, 205)
  3078.     pRT->Clear(D2D1::ColorF(0.3686f, 0.5333f, 0.3882f)); // Clear with light yellow background NEWCOLOR 1.0f, 1.0f, 0.803f => (0.3686f, 0.5333f, 0.3882f)
  3079.     //pRT->Clear(D2D1::ColorF(1.0f, 1.0f, 0.803f)); // Clear with light yellow background NEWCOLOR 1.0f, 1.0f, 0.803f => (0.3686f, 0.5333f, 0.3882f)
  3080.  
  3081.     DrawTable(pRT, pFactory);
  3082.     DrawBalls(pRT);
  3083.     DrawAimingAids(pRT); // Includes cue stick if aiming
  3084.     DrawUI(pRT);
  3085.     DrawPowerMeter(pRT);
  3086.     DrawSpinIndicator(pRT);
  3087.     DrawPocketedBallsIndicator(pRT);
  3088.     DrawBallInHandIndicator(pRT); // Draw cue ball ghost if placing
  3089.  
  3090.      // Draw Game Over Message
  3091.     if (currentGameState == GAME_OVER && pTextFormat) {
  3092.         ID2D1SolidColorBrush* pBrush = nullptr;
  3093.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pBrush);
  3094.         if (pBrush) {
  3095.             D2D1_RECT_F layoutRect = D2D1::RectF(TABLE_LEFT, TABLE_TOP + TABLE_HEIGHT / 2 - 30, TABLE_RIGHT, TABLE_TOP + TABLE_HEIGHT / 2 + 30);
  3096.             pRT->DrawText(
  3097.                 gameOverMessage.c_str(),
  3098.                 (UINT32)gameOverMessage.length(),
  3099.                 pTextFormat, // Use large format maybe?
  3100.                 &layoutRect,
  3101.                 pBrush
  3102.             );
  3103.             SafeRelease(&pBrush);
  3104.         }
  3105.     }
  3106.  
  3107. }
  3108.  
  3109. void DrawTable(ID2D1RenderTarget* pRT, ID2D1Factory* pFactory) {
  3110.     ID2D1SolidColorBrush* pBrush = nullptr;
  3111.  
  3112.     // === Draw Full Orange Frame (Table Border) ===
  3113.     ID2D1SolidColorBrush* pFrameBrush = nullptr;
  3114.     pRT->CreateSolidColorBrush(D2D1::ColorF(0.9157f, 0.6157f, 0.2000f), &pFrameBrush); //NEWCOLOR ::Orange (no brackets) => (0.9157, 0.6157, 0.2000)
  3115.     //pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Orange), &pFrameBrush); //NEWCOLOR ::Orange (no brackets) => (0.9157, 0.6157, 0.2000)
  3116.     if (pFrameBrush) {
  3117.         D2D1_RECT_F outerRect = D2D1::RectF(
  3118.             TABLE_LEFT - CUSHION_THICKNESS,
  3119.             TABLE_TOP - CUSHION_THICKNESS,
  3120.             TABLE_RIGHT + CUSHION_THICKNESS,
  3121.             TABLE_BOTTOM + CUSHION_THICKNESS
  3122.         );
  3123.         pRT->FillRectangle(&outerRect, pFrameBrush);
  3124.         SafeRelease(&pFrameBrush);
  3125.     }
  3126.  
  3127.     // Draw Table Bed (Green Felt)
  3128.     pRT->CreateSolidColorBrush(TABLE_COLOR, &pBrush);
  3129.     if (!pBrush) return;
  3130.     D2D1_RECT_F tableRect = D2D1::RectF(TABLE_LEFT, TABLE_TOP, TABLE_RIGHT, TABLE_BOTTOM);
  3131.     pRT->FillRectangle(&tableRect, pBrush);
  3132.     SafeRelease(&pBrush);
  3133.  
  3134.     // Draw Cushions (Red Border)
  3135.     pRT->CreateSolidColorBrush(CUSHION_COLOR, &pBrush);
  3136.     if (!pBrush) return;
  3137.     // Top Cushion (split by middle pocket)
  3138.     pRT->FillRectangle(D2D1::RectF(TABLE_LEFT + HOLE_VISUAL_RADIUS, TABLE_TOP - CUSHION_THICKNESS, TABLE_LEFT + TABLE_WIDTH / 2.f - HOLE_VISUAL_RADIUS, TABLE_TOP), pBrush);
  3139.     pRT->FillRectangle(D2D1::RectF(TABLE_LEFT + TABLE_WIDTH / 2.f + HOLE_VISUAL_RADIUS, TABLE_TOP - CUSHION_THICKNESS, TABLE_RIGHT - HOLE_VISUAL_RADIUS, TABLE_TOP), pBrush);
  3140.     // Bottom Cushion (split by middle pocket)
  3141.     pRT->FillRectangle(D2D1::RectF(TABLE_LEFT + HOLE_VISUAL_RADIUS, TABLE_BOTTOM, TABLE_LEFT + TABLE_WIDTH / 2.f - HOLE_VISUAL_RADIUS, TABLE_BOTTOM + CUSHION_THICKNESS), pBrush);
  3142.     pRT->FillRectangle(D2D1::RectF(TABLE_LEFT + TABLE_WIDTH / 2.f + HOLE_VISUAL_RADIUS, TABLE_BOTTOM, TABLE_RIGHT - HOLE_VISUAL_RADIUS, TABLE_BOTTOM + CUSHION_THICKNESS), pBrush);
  3143.     // Left Cushion
  3144.     pRT->FillRectangle(D2D1::RectF(TABLE_LEFT - CUSHION_THICKNESS, TABLE_TOP + HOLE_VISUAL_RADIUS, TABLE_LEFT, TABLE_BOTTOM - HOLE_VISUAL_RADIUS), pBrush);
  3145.     // Right Cushion
  3146.     pRT->FillRectangle(D2D1::RectF(TABLE_RIGHT, TABLE_TOP + HOLE_VISUAL_RADIUS, TABLE_RIGHT + CUSHION_THICKNESS, TABLE_BOTTOM - HOLE_VISUAL_RADIUS), pBrush);
  3147.     SafeRelease(&pBrush);
  3148.  
  3149.  
  3150.     // Draw Pockets (Black Circles)
  3151.     pRT->CreateSolidColorBrush(POCKET_COLOR, &pBrush);
  3152.     if (!pBrush) return;
  3153.     for (int i = 0; i < 6; ++i) {
  3154.         D2D1_ELLIPSE ellipse = D2D1::Ellipse(pocketPositions[i], HOLE_VISUAL_RADIUS, HOLE_VISUAL_RADIUS);
  3155.         pRT->FillEllipse(&ellipse, pBrush);
  3156.     }
  3157.     SafeRelease(&pBrush);
  3158.  
  3159.     // Draw Headstring Line (White)
  3160.     pRT->CreateSolidColorBrush(D2D1::ColorF(0.4235f, 0.5647f, 0.1765f, 1.0f), &pBrush); // NEWCOLOR ::White => (0.2784, 0.4549, 0.1843)
  3161.     //pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.5f), &pBrush); // NEWCOLOR ::White => (0.2784, 0.4549, 0.1843)
  3162.     if (!pBrush) return;
  3163.     pRT->DrawLine(
  3164.         D2D1::Point2F(HEADSTRING_X, TABLE_TOP),
  3165.         D2D1::Point2F(HEADSTRING_X, TABLE_BOTTOM),
  3166.         pBrush,
  3167.         1.0f // Line thickness
  3168.     );
  3169.     SafeRelease(&pBrush);
  3170.  
  3171.     // Draw Semicircle facing West (flat side East)
  3172.     // Draw Semicircle facing East (curved side on the East, flat side on the West)
  3173.     ID2D1PathGeometry* pGeometry = nullptr;
  3174.     HRESULT hr = pFactory->CreatePathGeometry(&pGeometry);
  3175.     if (SUCCEEDED(hr) && pGeometry)
  3176.     {
  3177.         ID2D1GeometrySink* pSink = nullptr;
  3178.         hr = pGeometry->Open(&pSink);
  3179.         if (SUCCEEDED(hr) && pSink)
  3180.         {
  3181.             float radius = 60.0f; // Radius for the semicircle
  3182.             D2D1_POINT_2F center = D2D1::Point2F(HEADSTRING_X, (TABLE_TOP + TABLE_BOTTOM) / 2.0f);
  3183.  
  3184.             // For a semicircle facing East (curved side on the East), use the top and bottom points.
  3185.             D2D1_POINT_2F startPoint = D2D1::Point2F(center.x, center.y - radius); // Top point
  3186.  
  3187.             pSink->BeginFigure(startPoint, D2D1_FIGURE_BEGIN_HOLLOW);
  3188.  
  3189.             D2D1_ARC_SEGMENT arc = {};
  3190.             arc.point = D2D1::Point2F(center.x, center.y + radius); // Bottom point
  3191.             arc.size = D2D1::SizeF(radius, radius);
  3192.             arc.rotationAngle = 0.0f;
  3193.             // Use the correct identifier with the extra underscore:
  3194.             arc.sweepDirection = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  3195.             arc.arcSize = D2D1_ARC_SIZE_SMALL;
  3196.  
  3197.             pSink->AddArc(&arc);
  3198.             pSink->EndFigure(D2D1_FIGURE_END_OPEN);
  3199.             pSink->Close();
  3200.             SafeRelease(&pSink);
  3201.  
  3202.             ID2D1SolidColorBrush* pArcBrush = nullptr;
  3203.             //pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.3f), &pArcBrush);
  3204.             pRT->CreateSolidColorBrush(D2D1::ColorF(0.4235f, 0.5647f, 0.1765f, 1.0f), &pArcBrush);
  3205.             if (pArcBrush)
  3206.             {
  3207.                 pRT->DrawGeometry(pGeometry, pArcBrush, 1.5f);
  3208.                 SafeRelease(&pArcBrush);
  3209.             }
  3210.         }
  3211.         SafeRelease(&pGeometry);
  3212.     }
  3213.  
  3214.  
  3215.  
  3216.  
  3217. }
  3218.  
  3219.  
  3220. void DrawBalls(ID2D1RenderTarget* pRT) {
  3221.     ID2D1SolidColorBrush* pBrush = nullptr;
  3222.     ID2D1SolidColorBrush* pStripeBrush = nullptr; // For stripe pattern
  3223.  
  3224.     pRT->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0), &pBrush); // Placeholder
  3225.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
  3226.  
  3227.     if (!pBrush || !pStripeBrush) {
  3228.         SafeRelease(&pBrush);
  3229.         SafeRelease(&pStripeBrush);
  3230.         return;
  3231.     }
  3232.  
  3233.  
  3234.     for (size_t i = 0; i < balls.size(); ++i) {
  3235.         const Ball& b = balls[i];
  3236.         if (!b.isPocketed) {
  3237.             D2D1_ELLIPSE ellipse = D2D1::Ellipse(D2D1::Point2F(b.x, b.y), BALL_RADIUS, BALL_RADIUS);
  3238.  
  3239.             // Set main ball color
  3240.             pBrush->SetColor(b.color);
  3241.             pRT->FillEllipse(&ellipse, pBrush);
  3242.  
  3243.             // Draw Stripe if applicable
  3244.             if (b.type == BallType::STRIPE) {
  3245.                 // Draw a white band across the middle (simplified stripe)
  3246.                 D2D1_RECT_F stripeRect = D2D1::RectF(b.x - BALL_RADIUS, b.y - BALL_RADIUS * 0.4f, b.x + BALL_RADIUS, b.y + BALL_RADIUS * 0.4f);
  3247.                 // Need to clip this rectangle to the ellipse bounds - complex!
  3248.                 // Alternative: Draw two colored arcs leaving a white band.
  3249.                 // Simplest: Draw a white circle inside, slightly smaller.
  3250.                 D2D1_ELLIPSE innerEllipse = D2D1::Ellipse(D2D1::Point2F(b.x, b.y), BALL_RADIUS * 0.6f, BALL_RADIUS * 0.6f);
  3251.                 pRT->FillEllipse(innerEllipse, pStripeBrush); // White center part
  3252.                 pBrush->SetColor(b.color); // Set back to stripe color
  3253.                 pRT->FillEllipse(innerEllipse, pBrush); // Fill again, leaving a ring - No, this isn't right.
  3254.  
  3255.                 // Let's try drawing a thick white line across
  3256.                 // This doesn't look great. Just drawing solid red for stripes for now.
  3257.             }
  3258.  
  3259.             // Draw Number (Optional - requires more complex text layout or pre-rendered textures)
  3260.             // if (b.id != 0 && pTextFormat) {
  3261.             //     std::wstring numStr = std::to_wstring(b.id);
  3262.             //     D2D1_RECT_F textRect = D2D1::RectF(b.x - BALL_RADIUS, b.y - BALL_RADIUS, b.x + BALL_RADIUS, b.y + BALL_RADIUS);
  3263.             //     ID2D1SolidColorBrush* pNumBrush = nullptr;
  3264.             //     D2D1_COLOR_F numCol = (b.type == BallType::SOLID || b.id == 8) ? D2D1::ColorF(D2D1::ColorF::Black) : D2D1::ColorF(D2D1::ColorF::White);
  3265.             //     pRT->CreateSolidColorBrush(numCol, &pNumBrush);
  3266.             //     // Create a smaller text format...
  3267.             //     // pRT->DrawText(numStr.c_str(), numStr.length(), pSmallTextFormat, &textRect, pNumBrush);
  3268.             //     SafeRelease(&pNumBrush);
  3269.             // }
  3270.         }
  3271.     }
  3272.  
  3273.     SafeRelease(&pBrush);
  3274.     SafeRelease(&pStripeBrush);
  3275. }
  3276.  
  3277.  
  3278. void DrawAimingAids(ID2D1RenderTarget* pRT) {
  3279.     // Condition check at start (Unchanged)
  3280.     //if (currentGameState != PLAYER1_TURN && currentGameState != PLAYER2_TURN &&
  3281.         //currentGameState != BREAKING && currentGameState != AIMING)
  3282.     //{
  3283.         //return;
  3284.     //}
  3285.         // NEW Condition: Allow drawing if it's a human player's active turn/aiming/breaking,
  3286.     // OR if it's AI's turn and it's in AI_THINKING state (calculating) or BREAKING (aiming break).
  3287.     bool isHumanInteracting = (!isPlayer2AI || currentPlayer == 1) &&
  3288.         (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN ||
  3289.             currentGameState == BREAKING || currentGameState == AIMING);
  3290.     // AI_THINKING state is when AI calculates shot. AIMakeDecision sets cueAngle/shotPower.
  3291.     // Also include BREAKING state if it's AI's turn and isOpeningBreakShot for break aim visualization.
  3292.         // NEW Condition: AI is displaying its aim
  3293.     bool isAiVisualizingShot = (isPlayer2AI && currentPlayer == 2 &&
  3294.         currentGameState == AI_THINKING && aiIsDisplayingAim);
  3295.  
  3296.     if (!isHumanInteracting && !(isAiVisualizingShot || (currentGameState == AI_THINKING && aiIsDisplayingAim))) {
  3297.         return;
  3298.     }
  3299.  
  3300.     Ball* cueBall = GetCueBall();
  3301.     if (!cueBall || cueBall->isPocketed) return; // Don't draw if cue ball is gone
  3302.  
  3303.     ID2D1SolidColorBrush* pBrush = nullptr;
  3304.     ID2D1SolidColorBrush* pGhostBrush = nullptr;
  3305.     ID2D1StrokeStyle* pDashedStyle = nullptr;
  3306.     ID2D1SolidColorBrush* pCueBrush = nullptr;
  3307.     ID2D1SolidColorBrush* pReflectBrush = nullptr; // Brush for reflection line
  3308.  
  3309.     // Ensure render target is valid
  3310.     if (!pRT) return;
  3311.  
  3312.     // Create Brushes and Styles (check for failures)
  3313.     HRESULT hr;
  3314.     hr = pRT->CreateSolidColorBrush(AIM_LINE_COLOR, &pBrush);
  3315.     if FAILED(hr) { SafeRelease(&pBrush); return; }
  3316.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.5f), &pGhostBrush);
  3317.     if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); return; }
  3318.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(0.6f, 0.4f, 0.2f), &pCueBrush);
  3319.     if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); SafeRelease(&pCueBrush); return; }
  3320.     // Create reflection brush (e.g., lighter shade or different color)
  3321.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::LightCyan, 0.6f), &pReflectBrush);
  3322.     if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); SafeRelease(&pCueBrush); SafeRelease(&pReflectBrush); return; }
  3323.     // Create a Cyan brush for primary and secondary lines //orig(75.0f / 255.0f, 0.0f, 130.0f / 255.0f);indigoColor
  3324.     D2D1::ColorF cyanColor(0.0, 255.0, 255.0, 255.0f);
  3325.     ID2D1SolidColorBrush* pCyanBrush = nullptr;
  3326.     hr = pRT->CreateSolidColorBrush(cyanColor, &pCyanBrush);
  3327.     if (FAILED(hr)) {
  3328.         SafeRelease(&pCyanBrush);
  3329.         // handle error if needed
  3330.     }
  3331.     // Create a Purple brush for primary and secondary lines
  3332.     D2D1::ColorF purpleColor(255.0f, 0.0f, 255.0f, 255.0f);
  3333.     ID2D1SolidColorBrush* pPurpleBrush = nullptr;
  3334.     hr = pRT->CreateSolidColorBrush(purpleColor, &pPurpleBrush);
  3335.     if (FAILED(hr)) {
  3336.         SafeRelease(&pPurpleBrush);
  3337.         // handle error if needed
  3338.     }
  3339.  
  3340.     if (pFactory) {
  3341.         D2D1_STROKE_STYLE_PROPERTIES strokeProps = D2D1::StrokeStyleProperties();
  3342.         strokeProps.dashStyle = D2D1_DASH_STYLE_DASH;
  3343.         hr = pFactory->CreateStrokeStyle(&strokeProps, nullptr, 0, &pDashedStyle);
  3344.         if FAILED(hr) { pDashedStyle = nullptr; }
  3345.     }
  3346.  
  3347.  
  3348.     // --- Cue Stick Drawing (Unchanged from previous fix) ---
  3349.     const float baseStickLength = 150.0f;
  3350.     const float baseStickThickness = 4.0f;
  3351.     float stickLength = baseStickLength * 1.4f;
  3352.     float stickThickness = baseStickThickness * 1.5f;
  3353.     float stickAngle = cueAngle + PI;
  3354.     float powerOffset = 0.0f;
  3355.     //if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
  3356.         // Show power offset if human is aiming/dragging, or if AI is preparing its shot (AI_THINKING or AI Break)
  3357.     if ((isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) || isAiVisualizingShot) { // Use the new condition
  3358.         powerOffset = shotPower * 5.0f;
  3359.     }
  3360.     D2D1_POINT_2F cueStickEnd = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (stickLength + powerOffset), cueBall->y + sinf(stickAngle) * (stickLength + powerOffset));
  3361.     D2D1_POINT_2F cueStickTip = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (powerOffset + 5.0f), cueBall->y + sinf(stickAngle) * (powerOffset + 5.0f));
  3362.     pRT->DrawLine(cueStickTip, cueStickEnd, pCueBrush, stickThickness);
  3363.  
  3364.  
  3365.     // --- Projection Line Calculation ---
  3366.     float cosA = cosf(cueAngle);
  3367.     float sinA = sinf(cueAngle);
  3368.     float rayLength = TABLE_WIDTH + TABLE_HEIGHT; // Ensure ray is long enough
  3369.     D2D1_POINT_2F rayStart = D2D1::Point2F(cueBall->x, cueBall->y);
  3370.     D2D1_POINT_2F rayEnd = D2D1::Point2F(rayStart.x + cosA * rayLength, rayStart.y + sinA * rayLength);
  3371.  
  3372.     // Find the first ball hit by the aiming ray
  3373.     Ball* hitBall = nullptr;
  3374.     float firstHitDistSq = -1.0f;
  3375.     D2D1_POINT_2F ballCollisionPoint = { 0, 0 }; // Point on target ball circumference
  3376.     D2D1_POINT_2F ghostBallPosForHit = { 0, 0 }; // Ghost ball pos for the hit ball
  3377.  
  3378.     hitBall = FindFirstHitBall(rayStart, cueAngle, firstHitDistSq);
  3379.     if (hitBall) {
  3380.         // Calculate the point on the target ball's circumference
  3381.         float collisionDist = sqrtf(firstHitDistSq);
  3382.         ballCollisionPoint = D2D1::Point2F(rayStart.x + cosA * collisionDist, rayStart.y + sinA * collisionDist);
  3383.         // Calculate ghost ball position for this specific hit (used for projection consistency)
  3384.         ghostBallPosForHit = D2D1::Point2F(hitBall->x - cosA * BALL_RADIUS, hitBall->y - sinA * BALL_RADIUS); // Approx.
  3385.     }
  3386.  
  3387.     // Find the first rail hit by the aiming ray
  3388.     D2D1_POINT_2F railHitPoint = rayEnd; // Default to far end if no rail hit
  3389.     float minRailDistSq = rayLength * rayLength;
  3390.     int hitRailIndex = -1; // 0:Left, 1:Right, 2:Top, 3:Bottom
  3391.  
  3392.     // Define table edge segments for intersection checks
  3393.     D2D1_POINT_2F topLeft = D2D1::Point2F(TABLE_LEFT, TABLE_TOP);
  3394.     D2D1_POINT_2F topRight = D2D1::Point2F(TABLE_RIGHT, TABLE_TOP);
  3395.     D2D1_POINT_2F bottomLeft = D2D1::Point2F(TABLE_LEFT, TABLE_BOTTOM);
  3396.     D2D1_POINT_2F bottomRight = D2D1::Point2F(TABLE_RIGHT, TABLE_BOTTOM);
  3397.  
  3398.     D2D1_POINT_2F currentIntersection;
  3399.  
  3400.     // Check Left Rail
  3401.     if (LineSegmentIntersection(rayStart, rayEnd, topLeft, bottomLeft, currentIntersection)) {
  3402.         float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  3403.         if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 0; }
  3404.     }
  3405.     // Check Right Rail
  3406.     if (LineSegmentIntersection(rayStart, rayEnd, topRight, bottomRight, currentIntersection)) {
  3407.         float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  3408.         if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 1; }
  3409.     }
  3410.     // Check Top Rail
  3411.     if (LineSegmentIntersection(rayStart, rayEnd, topLeft, topRight, currentIntersection)) {
  3412.         float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  3413.         if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 2; }
  3414.     }
  3415.     // Check Bottom Rail
  3416.     if (LineSegmentIntersection(rayStart, rayEnd, bottomLeft, bottomRight, currentIntersection)) {
  3417.         float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  3418.         if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 3; }
  3419.     }
  3420.  
  3421.  
  3422.     // --- Determine final aim line end point ---
  3423.     D2D1_POINT_2F finalLineEnd = railHitPoint; // Assume rail hit first
  3424.     bool aimingAtRail = true;
  3425.  
  3426.     if (hitBall && firstHitDistSq < minRailDistSq) {
  3427.         // Ball collision is closer than rail collision
  3428.         finalLineEnd = ballCollisionPoint; // End line at the point of contact on the ball
  3429.         aimingAtRail = false;
  3430.     }
  3431.  
  3432.     // --- Draw Primary Aiming Line ---
  3433.     pRT->DrawLine(rayStart, finalLineEnd, pBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  3434.  
  3435.     // --- Draw Target Circle/Indicator ---
  3436.     D2D1_ELLIPSE targetCircle = D2D1::Ellipse(finalLineEnd, BALL_RADIUS / 2.0f, BALL_RADIUS / 2.0f);
  3437.     pRT->DrawEllipse(&targetCircle, pBrush, 1.0f);
  3438.  
  3439.     // --- Draw Projection/Reflection Lines ---
  3440.     if (!aimingAtRail && hitBall) {
  3441.         // Aiming at a ball: Draw Ghost Cue Ball and Target Ball Projection
  3442.         D2D1_ELLIPSE ghostCue = D2D1::Ellipse(ballCollisionPoint, BALL_RADIUS, BALL_RADIUS); // Ghost ball at contact point
  3443.         pRT->DrawEllipse(ghostCue, pGhostBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  3444.  
  3445.         // Calculate target ball projection based on impact line (cue collision point -> target center)
  3446.         float targetProjectionAngle = atan2f(hitBall->y - ballCollisionPoint.y, hitBall->x - ballCollisionPoint.x);
  3447.         // Clamp angle calculation if distance is tiny
  3448.         if (GetDistanceSq(hitBall->x, hitBall->y, ballCollisionPoint.x, ballCollisionPoint.y) < 1.0f) {
  3449.             targetProjectionAngle = cueAngle; // Fallback if overlapping
  3450.         }
  3451.  
  3452.         D2D1_POINT_2F targetStartPoint = D2D1::Point2F(hitBall->x, hitBall->y);
  3453.         D2D1_POINT_2F targetProjectionEnd = D2D1::Point2F(
  3454.             hitBall->x + cosf(targetProjectionAngle) * 50.0f, // Projection length 50 units
  3455.             hitBall->y + sinf(targetProjectionAngle) * 50.0f
  3456.         );
  3457.         // Draw solid line for target projection
  3458.         //pRT->DrawLine(targetStartPoint, targetProjectionEnd, pBrush, 1.0f);
  3459.  
  3460.     //new code start
  3461.  
  3462.                 // Dual trajectory with edge-aware contact simulation
  3463.         D2D1_POINT_2F dir = {
  3464.             targetProjectionEnd.x - targetStartPoint.x,
  3465.             targetProjectionEnd.y - targetStartPoint.y
  3466.         };
  3467.         float dirLen = sqrtf(dir.x * dir.x + dir.y * dir.y);
  3468.         dir.x /= dirLen;
  3469.         dir.y /= dirLen;
  3470.  
  3471.         D2D1_POINT_2F perp = { -dir.y, dir.x };
  3472.  
  3473.         // Approximate cue ball center by reversing from tip
  3474.         D2D1_POINT_2F cueBallCenterForGhostHit = { // Renamed for clarity if you use it elsewhere
  3475.             targetStartPoint.x - dir.x * BALL_RADIUS,
  3476.             targetStartPoint.y - dir.y * BALL_RADIUS
  3477.         };
  3478.  
  3479.         // REAL contact-ball center - use your physics object's center:
  3480.         // (replace 'objectBallPos' with whatever you actually call it)
  3481.         // (targetStartPoint is already hitBall->x, hitBall->y)
  3482.         D2D1_POINT_2F contactBallCenter = targetStartPoint; // Corrected: Use the object ball's actual center
  3483.         //D2D1_POINT_2F contactBallCenter = D2D1::Point2F(hitBall->x, hitBall->y);
  3484.  
  3485.        // The 'offset' calculation below uses 'cueBallCenterForGhostHit' (originally 'cueBallCenter').
  3486.        // This will result in 'offset' being 0 because 'cueBallCenterForGhostHit' is defined
  3487.        // such that (targetStartPoint - cueBallCenterForGhostHit) is parallel to 'dir',
  3488.        // and 'perp' is perpendicular to 'dir'.
  3489.        // Consider Change 2 if this 'offset' is not behaving as intended for the secondary line.
  3490.         /*float offset = ((targetStartPoint.x - cueBallCenterForGhostHit.x) * perp.x +
  3491.             (targetStartPoint.y - cueBallCenterForGhostHit.y) * perp.y);*/
  3492.             /*float offset = ((targetStartPoint.x - cueBallCenter.x) * perp.x +
  3493.                 (targetStartPoint.y - cueBallCenter.y) * perp.y);
  3494.             float absOffset = fabsf(offset);
  3495.             float side = (offset >= 0 ? 1.0f : -1.0f);*/
  3496.  
  3497.             // Use actual cue ball center for offset calculation if 'offset' is meant to quantify the cut
  3498.         D2D1_POINT_2F actualCueBallPhysicalCenter = D2D1::Point2F(cueBall->x, cueBall->y); // This is also rayStart
  3499.  
  3500.         // Offset calculation based on actual cue ball position relative to the 'dir' line through targetStartPoint
  3501.         float offset = ((targetStartPoint.x - actualCueBallPhysicalCenter.x) * perp.x +
  3502.             (targetStartPoint.y - actualCueBallPhysicalCenter.y) * perp.y);
  3503.         float absOffset = fabsf(offset);
  3504.         float side = (offset >= 0 ? 1.0f : -1.0f);
  3505.  
  3506.  
  3507.         // Actual contact point on target ball edge
  3508.         D2D1_POINT_2F contactPoint = {
  3509.         contactBallCenter.x + perp.x * BALL_RADIUS * side,
  3510.         contactBallCenter.y + perp.y * BALL_RADIUS * side
  3511.         };
  3512.  
  3513.         // Tangent (cut shot) path from contact point
  3514.             // Tangent (cut shot) path: from contact point to contact ball center
  3515.         D2D1_POINT_2F objectBallDir = {
  3516.             contactBallCenter.x - contactPoint.x,
  3517.             contactBallCenter.y - contactPoint.y
  3518.         };
  3519.         float oLen = sqrtf(objectBallDir.x * objectBallDir.x + objectBallDir.y * objectBallDir.y);
  3520.         if (oLen != 0.0f) {
  3521.             objectBallDir.x /= oLen;
  3522.             objectBallDir.y /= oLen;
  3523.         }
  3524.  
  3525.         const float PRIMARY_LEN = 150.0f; //default=150.0f
  3526.         const float SECONDARY_LEN = 150.0f; //default=150.0f
  3527.         const float STRAIGHT_EPSILON = BALL_RADIUS * 0.05f;
  3528.  
  3529.         D2D1_POINT_2F primaryEnd = {
  3530.             targetStartPoint.x + dir.x * PRIMARY_LEN,
  3531.             targetStartPoint.y + dir.y * PRIMARY_LEN
  3532.         };
  3533.  
  3534.         // Secondary line starts from the contact ball's center
  3535.         D2D1_POINT_2F secondaryStart = contactBallCenter;
  3536.         D2D1_POINT_2F secondaryEnd = {
  3537.             secondaryStart.x + objectBallDir.x * SECONDARY_LEN,
  3538.             secondaryStart.y + objectBallDir.y * SECONDARY_LEN
  3539.         };
  3540.  
  3541.         if (absOffset < STRAIGHT_EPSILON)  // straight shot?
  3542.         {
  3543.             // Straight: secondary behind primary
  3544.                     // secondary behind primary {pDashedStyle param at end}
  3545.             pRT->DrawLine(secondaryStart, secondaryEnd, pPurpleBrush, 2.0f);
  3546.             //pRT->DrawLine(secondaryStart, secondaryEnd, pGhostBrush, 1.0f);
  3547.             pRT->DrawLine(targetStartPoint, primaryEnd, pCyanBrush, 2.0f);
  3548.             //pRT->DrawLine(targetStartPoint, primaryEnd, pBrush, 1.0f);
  3549.         }
  3550.         else
  3551.         {
  3552.             // Cut shot: both visible
  3553.                     // both visible for cut shot
  3554.             pRT->DrawLine(secondaryStart, secondaryEnd, pPurpleBrush, 2.0f);
  3555.             //pRT->DrawLine(secondaryStart, secondaryEnd, pGhostBrush, 1.0f);
  3556.             pRT->DrawLine(targetStartPoint, primaryEnd, pCyanBrush, 2.0f);
  3557.             //pRT->DrawLine(targetStartPoint, primaryEnd, pBrush, 1.0f);
  3558.         }
  3559.         // End improved trajectory logic
  3560.  
  3561.     //new code end
  3562.  
  3563.         // -- Cue Ball Path after collision (Optional, requires physics) --
  3564.         // Very simplified: Assume cue deflects, angle depends on cut angle.
  3565.         // float cutAngle = acosf(cosf(cueAngle - targetProjectionAngle)); // Angle between paths
  3566.         // float cueDeflectionAngle = ? // Depends on cutAngle, spin, etc. Hard to predict accurately.
  3567.         // D2D1_POINT_2F cueProjectionEnd = ...
  3568.         // pRT->DrawLine(ballCollisionPoint, cueProjectionEnd, pGhostBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  3569.  
  3570.         // --- Accuracy Comment ---
  3571.         // Note: The visual accuracy of this projection, especially for cut shots (hitting the ball off-center)
  3572.         // or shots with spin, is limited by the simplified physics model. Real pool physics involves
  3573.         // collision-induced throw, spin transfer, and cue ball deflection not fully simulated here.
  3574.         // The ghost ball method shows the *ideal* line for a center-cue hit without spin.
  3575.  
  3576.     }
  3577.     else if (aimingAtRail && hitRailIndex != -1) {
  3578.         // Aiming at a rail: Draw reflection line
  3579.         float reflectAngle = cueAngle;
  3580.         // Reflect angle based on which rail was hit
  3581.         if (hitRailIndex == 0 || hitRailIndex == 1) { // Left or Right rail
  3582.             reflectAngle = PI - cueAngle; // Reflect horizontal component
  3583.         }
  3584.         else { // Top or Bottom rail
  3585.             reflectAngle = -cueAngle; // Reflect vertical component
  3586.         }
  3587.         // Normalize angle if needed (atan2 usually handles this)
  3588.         while (reflectAngle > PI) reflectAngle -= 2 * PI;
  3589.         while (reflectAngle <= -PI) reflectAngle += 2 * PI;
  3590.  
  3591.  
  3592.         float reflectionLength = 60.0f; // Length of the reflection line
  3593.         D2D1_POINT_2F reflectionEnd = D2D1::Point2F(
  3594.             finalLineEnd.x + cosf(reflectAngle) * reflectionLength,
  3595.             finalLineEnd.y + sinf(reflectAngle) * reflectionLength
  3596.         );
  3597.  
  3598.         // Draw the reflection line (e.g., using a different color/style)
  3599.         pRT->DrawLine(finalLineEnd, reflectionEnd, pReflectBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  3600.     }
  3601.  
  3602.     // Release resources
  3603.     SafeRelease(&pBrush);
  3604.     SafeRelease(&pGhostBrush);
  3605.     SafeRelease(&pCueBrush);
  3606.     SafeRelease(&pReflectBrush); // Release new brush
  3607.     SafeRelease(&pCyanBrush);
  3608.     SafeRelease(&pPurpleBrush);
  3609.     SafeRelease(&pDashedStyle);
  3610. }
  3611.  
  3612.  
  3613. void DrawUI(ID2D1RenderTarget* pRT) {
  3614.     if (!pTextFormat || !pLargeTextFormat) return;
  3615.  
  3616.     ID2D1SolidColorBrush* pBrush = nullptr;
  3617.     pRT->CreateSolidColorBrush(UI_TEXT_COLOR, &pBrush);
  3618.     if (!pBrush) return;
  3619.  
  3620.     // --- Player Info Area (Top Left/Right) --- (Unchanged)
  3621.     float uiTop = TABLE_TOP - 80;
  3622.     float uiHeight = 60;
  3623.     float p1Left = TABLE_LEFT;
  3624.     float p1Width = 150;
  3625.     float p2Left = TABLE_RIGHT - p1Width;
  3626.     D2D1_RECT_F p1Rect = D2D1::RectF(p1Left, uiTop, p1Left + p1Width, uiTop + uiHeight);
  3627.     D2D1_RECT_F p2Rect = D2D1::RectF(p2Left, uiTop, p2Left + p1Width, uiTop + uiHeight);
  3628.  
  3629.     // Player 1 Info Text (Unchanged)
  3630.     std::wostringstream oss1;
  3631.     oss1 << player1Info.name.c_str() << L"\n";
  3632.     if (player1Info.assignedType != BallType::NONE) {
  3633.         oss1 << ((player1Info.assignedType == BallType::SOLID) ? L"Solids (Yellow)" : L"Stripes (Red)");
  3634.         oss1 << L" [" << player1Info.ballsPocketedCount << L"/7]";
  3635.     }
  3636.     else {
  3637.         oss1 << L"(Undecided)";
  3638.     }
  3639.     pRT->DrawText(oss1.str().c_str(), (UINT32)oss1.str().length(), pTextFormat, &p1Rect, pBrush);
  3640.     // Draw Player 1 Side Ball
  3641.     if (player1Info.assignedType != BallType::NONE)
  3642.     {
  3643.         ID2D1SolidColorBrush* pBallBrush = nullptr;
  3644.         D2D1_COLOR_F ballColor = (player1Info.assignedType == BallType::SOLID) ?
  3645.             D2D1::ColorF(1.0f, 1.0f, 0.0f) : D2D1::ColorF(1.0f, 0.0f, 0.0f);
  3646.         pRT->CreateSolidColorBrush(ballColor, &pBallBrush);
  3647.         if (pBallBrush)
  3648.         {
  3649.             D2D1_POINT_2F ballCenter = D2D1::Point2F(p1Rect.right + 10.0f, p1Rect.top + 20.0f);
  3650.             float radius = 10.0f;
  3651.             D2D1_ELLIPSE ball = D2D1::Ellipse(ballCenter, radius, radius);
  3652.             pRT->FillEllipse(&ball, pBallBrush);
  3653.             SafeRelease(&pBallBrush);
  3654.             // Draw border around the ball
  3655.             ID2D1SolidColorBrush* pBorderBrush = nullptr;
  3656.             pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
  3657.             if (pBorderBrush)
  3658.             {
  3659.                 pRT->DrawEllipse(&ball, pBorderBrush, 1.5f); // thin border
  3660.                 SafeRelease(&pBorderBrush);
  3661.             }
  3662.  
  3663.             // If stripes, draw a stripe band
  3664.             if (player1Info.assignedType == BallType::STRIPE)
  3665.             {
  3666.                 ID2D1SolidColorBrush* pStripeBrush = nullptr;
  3667.                 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
  3668.                 if (pStripeBrush)
  3669.                 {
  3670.                     D2D1_RECT_F stripeRect = D2D1::RectF(
  3671.                         ballCenter.x - radius,
  3672.                         ballCenter.y - 3.0f,
  3673.                         ballCenter.x + radius,
  3674.                         ballCenter.y + 3.0f
  3675.                     );
  3676.                     pRT->FillRectangle(&stripeRect, pStripeBrush);
  3677.                     SafeRelease(&pStripeBrush);
  3678.                 }
  3679.             }
  3680.         }
  3681.     }
  3682.  
  3683.  
  3684.     // Player 2 Info Text (Unchanged)
  3685.     std::wostringstream oss2;
  3686.     oss2 << player2Info.name.c_str() << L"\n";
  3687.     if (player2Info.assignedType != BallType::NONE) {
  3688.         oss2 << ((player2Info.assignedType == BallType::SOLID) ? L"Solids (Yellow)" : L"Stripes (Red)");
  3689.         oss2 << L" [" << player2Info.ballsPocketedCount << L"/7]";
  3690.     }
  3691.     else {
  3692.         oss2 << L"(Undecided)";
  3693.     }
  3694.     pRT->DrawText(oss2.str().c_str(), (UINT32)oss2.str().length(), pTextFormat, &p2Rect, pBrush);
  3695.     // Draw Player 2 Side Ball
  3696.     if (player2Info.assignedType != BallType::NONE)
  3697.     {
  3698.         ID2D1SolidColorBrush* pBallBrush = nullptr;
  3699.         D2D1_COLOR_F ballColor = (player2Info.assignedType == BallType::SOLID) ?
  3700.             D2D1::ColorF(1.0f, 1.0f, 0.0f) : D2D1::ColorF(1.0f, 0.0f, 0.0f);
  3701.         pRT->CreateSolidColorBrush(ballColor, &pBallBrush);
  3702.         if (pBallBrush)
  3703.         {
  3704.             D2D1_POINT_2F ballCenter = D2D1::Point2F(p2Rect.right + 10.0f, p2Rect.top + 20.0f);
  3705.             float radius = 10.0f;
  3706.             D2D1_ELLIPSE ball = D2D1::Ellipse(ballCenter, radius, radius);
  3707.             pRT->FillEllipse(&ball, pBallBrush);
  3708.             SafeRelease(&pBallBrush);
  3709.             // Draw border around the ball
  3710.             ID2D1SolidColorBrush* pBorderBrush = nullptr;
  3711.             pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
  3712.             if (pBorderBrush)
  3713.             {
  3714.                 pRT->DrawEllipse(&ball, pBorderBrush, 1.5f); // thin border
  3715.                 SafeRelease(&pBorderBrush);
  3716.             }
  3717.  
  3718.             // If stripes, draw a stripe band
  3719.             if (player2Info.assignedType == BallType::STRIPE)
  3720.             {
  3721.                 ID2D1SolidColorBrush* pStripeBrush = nullptr;
  3722.                 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
  3723.                 if (pStripeBrush)
  3724.                 {
  3725.                     D2D1_RECT_F stripeRect = D2D1::RectF(
  3726.                         ballCenter.x - radius,
  3727.                         ballCenter.y - 3.0f,
  3728.                         ballCenter.x + radius,
  3729.                         ballCenter.y + 3.0f
  3730.                     );
  3731.                     pRT->FillRectangle(&stripeRect, pStripeBrush);
  3732.                     SafeRelease(&pStripeBrush);
  3733.                 }
  3734.             }
  3735.         }
  3736.     }
  3737.  
  3738.  
  3739.     // --- MODIFIED: Current Turn Arrow (Blue, Bigger, Beside Name) ---
  3740.     ID2D1SolidColorBrush* pArrowBrush = nullptr;
  3741.     pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrowBrush);
  3742.     if (pArrowBrush && currentGameState != GAME_OVER && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  3743.         float arrowSizeBase = 32.0f; // Base size for width/height offsets (4x original ~8)
  3744.         float arrowCenterY = p1Rect.top + uiHeight / 2.0f; // Center vertically with text box
  3745.         float arrowTipX, arrowBackX;
  3746.  
  3747.         D2D1_RECT_F playerBox = (currentPlayer == 1) ? p1Rect : p2Rect;
  3748.         arrowBackX = playerBox.left - 25.0f;
  3749.         arrowTipX = arrowBackX + arrowSizeBase * 0.75f;
  3750.  
  3751.         float notchDepth = 12.0f;  // Increased from 6.0f to make the rectangle longer
  3752.         float notchWidth = 10.0f;
  3753.  
  3754.         float cx = arrowBackX;
  3755.         float cy = arrowCenterY;
  3756.  
  3757.         // Define triangle + rectangle tail shape
  3758.         D2D1_POINT_2F tip = D2D1::Point2F(arrowTipX, cy);                           // tip
  3759.         D2D1_POINT_2F baseTop = D2D1::Point2F(cx, cy - arrowSizeBase / 2.0f);          // triangle top
  3760.         D2D1_POINT_2F baseBot = D2D1::Point2F(cx, cy + arrowSizeBase / 2.0f);          // triangle bottom
  3761.  
  3762.         // Rectangle coordinates for the tail portion:
  3763.         D2D1_POINT_2F r1 = D2D1::Point2F(cx - notchDepth, cy - notchWidth / 2.0f);   // rect top-left
  3764.         D2D1_POINT_2F r2 = D2D1::Point2F(cx, cy - notchWidth / 2.0f);                 // rect top-right
  3765.         D2D1_POINT_2F r3 = D2D1::Point2F(cx, cy + notchWidth / 2.0f);                 // rect bottom-right
  3766.         D2D1_POINT_2F r4 = D2D1::Point2F(cx - notchDepth, cy + notchWidth / 2.0f);    // rect bottom-left
  3767.  
  3768.         ID2D1PathGeometry* pPath = nullptr;
  3769.         if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  3770.             ID2D1GeometrySink* pSink = nullptr;
  3771.             if (SUCCEEDED(pPath->Open(&pSink))) {
  3772.                 pSink->BeginFigure(tip, D2D1_FIGURE_BEGIN_FILLED);
  3773.                 pSink->AddLine(baseTop);
  3774.                 pSink->AddLine(r2); // transition from triangle into rectangle
  3775.                 pSink->AddLine(r1);
  3776.                 pSink->AddLine(r4);
  3777.                 pSink->AddLine(r3);
  3778.                 pSink->AddLine(baseBot);
  3779.                 pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  3780.                 pSink->Close();
  3781.                 SafeRelease(&pSink);
  3782.                 pRT->FillGeometry(pPath, pArrowBrush);
  3783.             }
  3784.             SafeRelease(&pPath);
  3785.         }
  3786.  
  3787.  
  3788.         SafeRelease(&pArrowBrush);
  3789.     }
  3790.  
  3791.     //original
  3792. /*
  3793.     // --- MODIFIED: Current Turn Arrow (Blue, Bigger, Beside Name) ---
  3794.     ID2D1SolidColorBrush* pArrowBrush = nullptr;
  3795.     pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrowBrush);
  3796.     if (pArrowBrush && currentGameState != GAME_OVER && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  3797.         float arrowSizeBase = 32.0f; // Base size for width/height offsets (4x original ~8)
  3798.         float arrowCenterY = p1Rect.top + uiHeight / 2.0f; // Center vertically with text box
  3799.         float arrowTipX, arrowBackX;
  3800.  
  3801.         if (currentPlayer == 1) {
  3802. arrowBackX = p1Rect.left - 25.0f; // Position left of the box
  3803.             arrowTipX = arrowBackX + arrowSizeBase * 0.75f; // Pointy end extends right
  3804.             // Define points for right-pointing arrow
  3805.             //D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
  3806.             //D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
  3807.             //D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
  3808.             // Enhanced arrow with base rectangle intersection
  3809.     float notchDepth = 6.0f; // Depth of square base "stem"
  3810.     float notchWidth = 4.0f; // Thickness of square part
  3811.  
  3812.     D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
  3813.     D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
  3814.     D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX - notchDepth, arrowCenterY - notchWidth / 2.0f); // Square Left-Top
  3815.     D2D1_POINT_2F pt4 = D2D1::Point2F(arrowBackX - notchDepth, arrowCenterY + notchWidth / 2.0f); // Square Left-Bottom
  3816.     D2D1_POINT_2F pt5 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
  3817.  
  3818.  
  3819.     ID2D1PathGeometry* pPath = nullptr;
  3820.     if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  3821.         ID2D1GeometrySink* pSink = nullptr;
  3822.         if (SUCCEEDED(pPath->Open(&pSink))) {
  3823.             pSink->BeginFigure(pt1, D2D1_FIGURE_BEGIN_FILLED);
  3824.             pSink->AddLine(pt2);
  3825.             pSink->AddLine(pt3);
  3826.             pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  3827.             pSink->Close();
  3828.             SafeRelease(&pSink);
  3829.             pRT->FillGeometry(pPath, pArrowBrush);
  3830.         }
  3831.         SafeRelease(&pPath);
  3832.     }
  3833.         }
  3834.  
  3835.  
  3836.         //==================else player 2
  3837.         else { // Player 2
  3838.          // Player 2: Arrow left of P2 box, pointing right (or right of P2 box pointing left?)
  3839.          // Let's keep it consistent: Arrow left of the active player's box, pointing right.
  3840. // Let's keep it consistent: Arrow left of the active player's box, pointing right.
  3841. arrowBackX = p2Rect.left - 25.0f; // Position left of the box
  3842. arrowTipX = arrowBackX + arrowSizeBase * 0.75f; // Pointy end extends right
  3843. // Define points for right-pointing arrow
  3844. D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
  3845. D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
  3846. D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
  3847.  
  3848. ID2D1PathGeometry* pPath = nullptr;
  3849. if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  3850.     ID2D1GeometrySink* pSink = nullptr;
  3851.     if (SUCCEEDED(pPath->Open(&pSink))) {
  3852.         pSink->BeginFigure(pt1, D2D1_FIGURE_BEGIN_FILLED);
  3853.         pSink->AddLine(pt2);
  3854.         pSink->AddLine(pt3);
  3855.         pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  3856.         pSink->Close();
  3857.         SafeRelease(&pSink);
  3858.         pRT->FillGeometry(pPath, pArrowBrush);
  3859.     }
  3860.     SafeRelease(&pPath);
  3861. }
  3862.         }
  3863.         */
  3864.  
  3865.         // --- MODIFIED: Foul Text (Large Red, Bottom Center) ---
  3866.     // --- 8-Ball Pocket Selection Indicator ---
  3867.     if (currentGameState == SELECT_EIGHT_POCKET_P1
  3868.         || currentGameState == SELECT_EIGHT_POCKET_P2) {
  3869.         // Draw down-pointing arrow at chosen pocket
  3870.         ID2D1SolidColorBrush* pArrowBrush = nullptr;
  3871.         pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrowBrush);
  3872.         if (pArrowBrush) {
  3873.             auto P = pocketPositions[selectedPocketIndex];
  3874.             // Triangle points
  3875.             D2D1_POINT_2F tri[3] = {
  3876.                 {P.x - 10, P.y - 30},
  3877.                 {P.x + 10, P.y - 30},
  3878.                 {P.x,     P.y - 10}
  3879.             };
  3880.             // Build and fill geometry
  3881.             ID2D1PathGeometry* geom = nullptr;
  3882.             pFactory->CreatePathGeometry(&geom);
  3883.             ID2D1GeometrySink* sink = nullptr;
  3884.             geom->Open(&sink);
  3885.             sink->BeginFigure(tri[0], D2D1_FIGURE_BEGIN_FILLED);
  3886.             sink->AddLines(&tri[1], 2);
  3887.             sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  3888.             sink->Close();
  3889.             pRT->FillGeometry(geom, pArrowBrush);
  3890.             SafeRelease(&sink);
  3891.             SafeRelease(&geom);
  3892.             SafeRelease(&pArrowBrush);
  3893.         }
  3894.         // Prompt text below table
  3895.         D2D1_RECT_F promptRect = D2D1::RectF(
  3896.             TABLE_LEFT,
  3897.             TABLE_BOTTOM + CUSHION_THICKNESS + 5,
  3898.             TABLE_RIGHT,
  3899.             TABLE_BOTTOM + CUSHION_THICKNESS + 30
  3900.         );
  3901.         pRT->DrawText(
  3902.             L"Choose a pocket...",
  3903.             (UINT32)wcslen(L"Choose a pocket..."),
  3904.             pTextFormat,
  3905.             &promptRect,
  3906.             pBrush
  3907.         );
  3908.         // Stop here so turn/foul text does not draw underneath
  3909.         SafeRelease(&pBrush);
  3910.         return;
  3911.     }
  3912.  
  3913.     // --- Foul / Turn Indicator ---
  3914.     if (foulCommitted) {
  3915.         ID2D1SolidColorBrush* pFoulBrush = nullptr;
  3916.         pRT->CreateSolidColorBrush(FOUL_TEXT_COLOR, &pFoulBrush);
  3917.         if (pFoulBrush) {
  3918.             D2D1_RECT_F foulRect = D2D1::RectF(p1Rect.left, p1Rect.bottom + 10,
  3919.                 p2Rect.right, p1Rect.bottom + 50);
  3920.             pRT->DrawText(gameOverMessage.c_str(),
  3921.                 (UINT32)gameOverMessage.length(),
  3922.                 pLargeTextFormat,
  3923.                 &foulRect,
  3924.                 pFoulBrush);
  3925.             SafeRelease(&pFoulBrush);
  3926.         }
  3927.     }
  3928.  
  3929.     // Show AI Thinking State (Unchanged from previous step)
  3930.     if (currentGameState == AI_THINKING && pTextFormat) {
  3931.         ID2D1SolidColorBrush* pThinkingBrush = nullptr;
  3932.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Orange), &pThinkingBrush);
  3933.         if (pThinkingBrush) {
  3934.             D2D1_RECT_F thinkingRect = p2Rect;
  3935.             thinkingRect.top += 20; // Offset within P2 box
  3936.             // Ensure default text alignment for this
  3937.             pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  3938.             pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  3939.             pRT->DrawText(L"Thinking...", 11, pTextFormat, &thinkingRect, pThinkingBrush);
  3940.             SafeRelease(&pThinkingBrush);
  3941.         }
  3942.     }
  3943.  
  3944.     SafeRelease(&pBrush);
  3945.  
  3946.     // --- Draw CHEAT MODE label if active ---
  3947.     if (cheatModeEnabled) {
  3948.         ID2D1SolidColorBrush* pCheatBrush = nullptr;
  3949.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Red), &pCheatBrush);
  3950.         if (pCheatBrush && pTextFormat) {
  3951.             D2D1_RECT_F cheatTextRect = D2D1::RectF(
  3952.                 TABLE_LEFT + 10.0f,
  3953.                 TABLE_TOP + 10.0f,
  3954.                 TABLE_LEFT + 200.0f,
  3955.                 TABLE_TOP + 40.0f
  3956.             );
  3957.             pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
  3958.             pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
  3959.             pRT->DrawText(L"CHEAT MODE ON", wcslen(L"CHEAT MODE ON"), pTextFormat, &cheatTextRect, pCheatBrush);
  3960.         }
  3961.         SafeRelease(&pCheatBrush);
  3962.     }
  3963. }
  3964.  
  3965. void DrawPowerMeter(ID2D1RenderTarget* pRT) {
  3966.     // Draw Border
  3967.     ID2D1SolidColorBrush* pBorderBrush = nullptr;
  3968.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
  3969.     if (!pBorderBrush) return;
  3970.     pRT->DrawRectangle(&powerMeterRect, pBorderBrush, 2.0f);
  3971.     SafeRelease(&pBorderBrush);
  3972.  
  3973.     // Create Gradient Fill
  3974.     ID2D1GradientStopCollection* pGradientStops = nullptr;
  3975.     ID2D1LinearGradientBrush* pGradientBrush = nullptr;
  3976.     D2D1_GRADIENT_STOP gradientStops[4];
  3977.     gradientStops[0].position = 0.0f;
  3978.     gradientStops[0].color = D2D1::ColorF(D2D1::ColorF::Green);
  3979.     gradientStops[1].position = 0.45f;
  3980.     gradientStops[1].color = D2D1::ColorF(D2D1::ColorF::Yellow);
  3981.     gradientStops[2].position = 0.7f;
  3982.     gradientStops[2].color = D2D1::ColorF(D2D1::ColorF::Orange);
  3983.     gradientStops[3].position = 1.0f;
  3984.     gradientStops[3].color = D2D1::ColorF(D2D1::ColorF::Red);
  3985.  
  3986.     pRT->CreateGradientStopCollection(gradientStops, 4, &pGradientStops);
  3987.     if (pGradientStops) {
  3988.         D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props = {};
  3989.         props.startPoint = D2D1::Point2F(powerMeterRect.left, powerMeterRect.bottom);
  3990.         props.endPoint = D2D1::Point2F(powerMeterRect.left, powerMeterRect.top);
  3991.         pRT->CreateLinearGradientBrush(props, pGradientStops, &pGradientBrush);
  3992.         SafeRelease(&pGradientStops);
  3993.     }
  3994.  
  3995.     // Calculate Fill Height
  3996.     float fillRatio = 0;
  3997.     //if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
  3998.         // Determine if power meter should reflect shot power (human aiming or AI preparing)
  3999.     bool humanIsAimingPower = isAiming && (currentGameState == AIMING || currentGameState == BREAKING);
  4000.     // NEW Condition: AI is displaying its aim, so show its chosen power
  4001.     bool aiIsVisualizingPower = (isPlayer2AI && currentPlayer == 2 &&
  4002.         currentGameState == AI_THINKING && aiIsDisplayingAim);
  4003.  
  4004.     if (humanIsAimingPower || aiIsVisualizingPower) { // Use the new condition
  4005.         fillRatio = shotPower / MAX_SHOT_POWER;
  4006.     }
  4007.     float fillHeight = (powerMeterRect.bottom - powerMeterRect.top) * fillRatio;
  4008.     D2D1_RECT_F fillRect = D2D1::RectF(
  4009.         powerMeterRect.left,
  4010.         powerMeterRect.bottom - fillHeight,
  4011.         powerMeterRect.right,
  4012.         powerMeterRect.bottom
  4013.     );
  4014.  
  4015.     if (pGradientBrush) {
  4016.         pRT->FillRectangle(&fillRect, pGradientBrush);
  4017.         SafeRelease(&pGradientBrush);
  4018.     }
  4019.  
  4020.     // Draw scale notches
  4021.     ID2D1SolidColorBrush* pNotchBrush = nullptr;
  4022.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pNotchBrush);
  4023.     if (pNotchBrush) {
  4024.         for (int i = 0; i <= 8; ++i) {
  4025.             float y = powerMeterRect.top + (powerMeterRect.bottom - powerMeterRect.top) * (i / 8.0f);
  4026.             pRT->DrawLine(
  4027.                 D2D1::Point2F(powerMeterRect.right + 2.0f, y),
  4028.                 D2D1::Point2F(powerMeterRect.right + 8.0f, y),
  4029.                 pNotchBrush,
  4030.                 1.5f
  4031.             );
  4032.         }
  4033.         SafeRelease(&pNotchBrush);
  4034.     }
  4035.  
  4036.     // Draw "Power" Label Below Meter
  4037.     if (pTextFormat) {
  4038.         ID2D1SolidColorBrush* pTextBrush = nullptr;
  4039.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pTextBrush);
  4040.         if (pTextBrush) {
  4041.             D2D1_RECT_F textRect = D2D1::RectF(
  4042.                 powerMeterRect.left - 20.0f,
  4043.                 powerMeterRect.bottom + 8.0f,
  4044.                 powerMeterRect.right + 20.0f,
  4045.                 powerMeterRect.bottom + 38.0f
  4046.             );
  4047.             pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  4048.             pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
  4049.             pRT->DrawText(L"Power", 5, pTextFormat, &textRect, pTextBrush);
  4050.             SafeRelease(&pTextBrush);
  4051.         }
  4052.     }
  4053.  
  4054.     // Draw Glow Effect if fully charged or fading out
  4055.     static float glowPulse = 0.0f;
  4056.     static bool glowIncreasing = true;
  4057.     static float glowFadeOut = 0.0f; // NEW: tracks fading out
  4058.  
  4059.     if (shotPower >= MAX_SHOT_POWER * 0.99f) {
  4060.         // While fully charged, keep pulsing normally
  4061.         if (glowIncreasing) {
  4062.             glowPulse += 0.02f;
  4063.             if (glowPulse >= 1.0f) glowIncreasing = false;
  4064.         }
  4065.         else {
  4066.             glowPulse -= 0.02f;
  4067.             if (glowPulse <= 0.0f) glowIncreasing = true;
  4068.         }
  4069.         glowFadeOut = 1.0f; // Reset fade out to full
  4070.     }
  4071.     else if (glowFadeOut > 0.0f) {
  4072.         // If shot fired, gradually fade out
  4073.         glowFadeOut -= 0.02f;
  4074.         if (glowFadeOut < 0.0f) glowFadeOut = 0.0f;
  4075.     }
  4076.  
  4077.     if (glowFadeOut > 0.0f) {
  4078.         ID2D1SolidColorBrush* pGlowBrush = nullptr;
  4079.         float effectiveOpacity = (0.3f + 0.7f * glowPulse) * glowFadeOut;
  4080.         pRT->CreateSolidColorBrush(
  4081.             D2D1::ColorF(D2D1::ColorF::Red, effectiveOpacity),
  4082.             &pGlowBrush
  4083.         );
  4084.         if (pGlowBrush) {
  4085.             float glowCenterX = (powerMeterRect.left + powerMeterRect.right) / 2.0f;
  4086.             float glowCenterY = powerMeterRect.top;
  4087.             D2D1_ELLIPSE glowEllipse = D2D1::Ellipse(
  4088.                 D2D1::Point2F(glowCenterX, glowCenterY - 10.0f),
  4089.                 12.0f + 3.0f * glowPulse,
  4090.                 6.0f + 2.0f * glowPulse
  4091.             );
  4092.             pRT->FillEllipse(&glowEllipse, pGlowBrush);
  4093.             SafeRelease(&pGlowBrush);
  4094.         }
  4095.     }
  4096. }
  4097.  
  4098. void DrawSpinIndicator(ID2D1RenderTarget* pRT) {
  4099.     ID2D1SolidColorBrush* pWhiteBrush = nullptr;
  4100.     ID2D1SolidColorBrush* pRedBrush = nullptr;
  4101.  
  4102.     pRT->CreateSolidColorBrush(CUE_BALL_COLOR, &pWhiteBrush);
  4103.     pRT->CreateSolidColorBrush(ENGLISH_DOT_COLOR, &pRedBrush);
  4104.  
  4105.     if (!pWhiteBrush || !pRedBrush) {
  4106.         SafeRelease(&pWhiteBrush);
  4107.         SafeRelease(&pRedBrush);
  4108.         return;
  4109.     }
  4110.  
  4111.     // Draw White Ball Background
  4112.     D2D1_ELLIPSE bgEllipse = D2D1::Ellipse(spinIndicatorCenter, spinIndicatorRadius, spinIndicatorRadius);
  4113.     pRT->FillEllipse(&bgEllipse, pWhiteBrush);
  4114.     pRT->DrawEllipse(&bgEllipse, pRedBrush, 0.5f); // Thin red border
  4115.  
  4116.  
  4117.     // Draw Red Dot for Spin Position
  4118.     float dotRadius = 4.0f;
  4119.     float dotX = spinIndicatorCenter.x + cueSpinX * (spinIndicatorRadius - dotRadius); // Keep dot inside edge
  4120.     float dotY = spinIndicatorCenter.y + cueSpinY * (spinIndicatorRadius - dotRadius);
  4121.     D2D1_ELLIPSE dotEllipse = D2D1::Ellipse(D2D1::Point2F(dotX, dotY), dotRadius, dotRadius);
  4122.     pRT->FillEllipse(&dotEllipse, pRedBrush);
  4123.  
  4124.     SafeRelease(&pWhiteBrush);
  4125.     SafeRelease(&pRedBrush);
  4126. }
  4127.  
  4128.  
  4129. void DrawPocketedBallsIndicator(ID2D1RenderTarget* pRT) {
  4130.     ID2D1SolidColorBrush* pBgBrush = nullptr;
  4131.     ID2D1SolidColorBrush* pBallBrush = nullptr;
  4132.  
  4133.     // Ensure render target is valid before proceeding
  4134.     if (!pRT) return;
  4135.  
  4136.     HRESULT hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black, 0.8f), &pBgBrush); // Semi-transparent black
  4137.     if (FAILED(hr)) { SafeRelease(&pBgBrush); return; } // Exit if brush creation fails
  4138.  
  4139.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0), &pBallBrush); // Placeholder, color will be set per ball
  4140.     if (FAILED(hr)) {
  4141.         SafeRelease(&pBgBrush);
  4142.         SafeRelease(&pBallBrush);
  4143.         return; // Exit if brush creation fails
  4144.     }
  4145.  
  4146.     // Draw the background bar (rounded rect)
  4147.     D2D1_ROUNDED_RECT roundedRect = D2D1::RoundedRect(pocketedBallsBarRect, 10.0f, 10.0f); // Corner radius 10
  4148.     float baseAlpha = 0.8f;
  4149.     float flashBoost = pocketFlashTimer * 0.5f; // Make flash effect boost alpha slightly
  4150.     float finalAlpha = std::min(1.0f, baseAlpha + flashBoost);
  4151.     pBgBrush->SetOpacity(finalAlpha);
  4152.     pRT->FillRoundedRectangle(&roundedRect, pBgBrush);
  4153.     pBgBrush->SetOpacity(1.0f); // Reset opacity after drawing
  4154.  
  4155.     // --- Draw small circles for pocketed balls inside the bar ---
  4156.  
  4157.     // Calculate dimensions based on the bar's height for better scaling
  4158.     float barHeight = pocketedBallsBarRect.bottom - pocketedBallsBarRect.top;
  4159.     float ballDisplayRadius = barHeight * 0.30f; // Make balls slightly smaller relative to bar height
  4160.     float spacing = ballDisplayRadius * 2.2f; // Adjust spacing slightly
  4161.     float padding = spacing * 0.75f; // Add padding from the edges
  4162.     float center_Y = pocketedBallsBarRect.top + barHeight / 2.0f; // Vertical center
  4163.  
  4164.     // Starting X positions with padding
  4165.     float currentX_P1 = pocketedBallsBarRect.left + padding;
  4166.     float currentX_P2 = pocketedBallsBarRect.right - padding; // Start from right edge minus padding
  4167.  
  4168.     int p1DrawnCount = 0;
  4169.     int p2DrawnCount = 0;
  4170.     const int maxBallsToShow = 7; // Max balls per player in the bar
  4171.  
  4172.     for (const auto& b : balls) {
  4173.         if (b.isPocketed) {
  4174.             // Skip cue ball and 8-ball in this indicator
  4175.             if (b.id == 0 || b.id == 8) continue;
  4176.  
  4177.             bool isPlayer1Ball = (player1Info.assignedType != BallType::NONE && b.type == player1Info.assignedType);
  4178.             bool isPlayer2Ball = (player2Info.assignedType != BallType::NONE && b.type == player2Info.assignedType);
  4179.  
  4180.             if (isPlayer1Ball && p1DrawnCount < maxBallsToShow) {
  4181.                 pBallBrush->SetColor(b.color);
  4182.                 // Draw P1 balls from left to right
  4183.                 D2D1_ELLIPSE ballEllipse = D2D1::Ellipse(D2D1::Point2F(currentX_P1 + p1DrawnCount * spacing, center_Y), ballDisplayRadius, ballDisplayRadius);
  4184.                 pRT->FillEllipse(&ballEllipse, pBallBrush);
  4185.                 p1DrawnCount++;
  4186.             }
  4187.             else if (isPlayer2Ball && p2DrawnCount < maxBallsToShow) {
  4188.                 pBallBrush->SetColor(b.color);
  4189.                 // Draw P2 balls from right to left
  4190.                 D2D1_ELLIPSE ballEllipse = D2D1::Ellipse(D2D1::Point2F(currentX_P2 - p2DrawnCount * spacing, center_Y), ballDisplayRadius, ballDisplayRadius);
  4191.                 pRT->FillEllipse(&ballEllipse, pBallBrush);
  4192.                 p2DrawnCount++;
  4193.             }
  4194.             // Note: Balls pocketed before assignment or opponent balls are intentionally not shown here.
  4195.             // You could add logic here to display them differently if needed (e.g., smaller, grayed out).
  4196.         }
  4197.     }
  4198.  
  4199.     SafeRelease(&pBgBrush);
  4200.     SafeRelease(&pBallBrush);
  4201. }
  4202.  
  4203. void DrawBallInHandIndicator(ID2D1RenderTarget* pRT) {
  4204.     if (!isDraggingCueBall && (currentGameState != BALL_IN_HAND_P1 && currentGameState != BALL_IN_HAND_P2 && currentGameState != PRE_BREAK_PLACEMENT)) {
  4205.         return; // Only show when placing/dragging
  4206.     }
  4207.  
  4208.     Ball* cueBall = GetCueBall();
  4209.     if (!cueBall) return;
  4210.  
  4211.     ID2D1SolidColorBrush* pGhostBrush = nullptr;
  4212.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.6f), &pGhostBrush); // Semi-transparent white
  4213.  
  4214.     if (pGhostBrush) {
  4215.         D2D1_POINT_2F drawPos;
  4216.         if (isDraggingCueBall) {
  4217.             drawPos = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y);
  4218.         }
  4219.         else {
  4220.             // If not dragging but in placement state, show at current ball pos
  4221.             drawPos = D2D1::Point2F(cueBall->x, cueBall->y);
  4222.         }
  4223.  
  4224.         // Check if the placement is valid before drawing differently?
  4225.         bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  4226.         bool isValid = IsValidCueBallPosition(drawPos.x, drawPos.y, behindHeadstring);
  4227.  
  4228.         if (!isValid) {
  4229.             // Maybe draw red outline if invalid placement?
  4230.             pGhostBrush->SetColor(D2D1::ColorF(D2D1::ColorF::Red, 0.6f));
  4231.         }
  4232.  
  4233.  
  4234.         D2D1_ELLIPSE ghostEllipse = D2D1::Ellipse(drawPos, BALL_RADIUS, BALL_RADIUS);
  4235.         pRT->FillEllipse(&ghostEllipse, pGhostBrush);
  4236.         pRT->DrawEllipse(&ghostEllipse, pGhostBrush, 1.0f); // Outline
  4237.  
  4238.         SafeRelease(&pGhostBrush);
  4239.     }
  4240. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement