Advertisement
alien_fx_fiend

Gemini's 4th Attempt - Shows 6 Balls Pocketed When 7 Balls (Fix For This) - Should Fix Everything !!

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