alien_fx_fiend

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

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