alien_fx_fiend

2D StickPool C++ D2D (Pockets Are Semi-Circles + 8-Ball PlayerInfo Indicator + Realistic CueStick)

Aug 7th, 2025 (edited)
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 240.67 KB | Source Code | 0 0
  1. ==++ Here's the full source code of (File 1/3) "Pool-Game-CloneV18.cpp" ++== cf. Github.com/alienfxfiend/Prelude-in-C/
  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. #ifndef HAS_STD_CLAMP
  25. template <typename T>
  26. T clamp(const T& v, const T& lo, const T& hi)
  27. {
  28.    return (v < lo) ? lo : (v > hi) ? hi : v;
  29. }
  30. namespace std { using ::clamp; }   // inject into std:: for seamless use
  31. #define HAS_STD_CLAMP
  32. #endif
  33.  
  34. #pragma comment(lib, "Comctl32.lib") // Link against common controls library
  35. #pragma comment(lib, "d2d1.lib")
  36. #pragma comment(lib, "dwrite.lib")
  37. #pragma comment(lib, "Winmm.lib") // Link against Windows Multimedia library
  38.  
  39. // --- Constants ---
  40. const float PI = 3.1415926535f;
  41. const float BALL_RADIUS = 10.0f;
  42. const float TABLE_LEFT = 100.0f;
  43. const float TABLE_TOP = 100.0f;
  44. const float TABLE_WIDTH = 700.0f;
  45. const float TABLE_HEIGHT = 350.0f;
  46. const float TABLE_RIGHT = TABLE_LEFT + TABLE_WIDTH;
  47. const float TABLE_BOTTOM = TABLE_TOP + TABLE_HEIGHT;
  48. const float CUSHION_THICKNESS = 20.0f;
  49. const float HOLE_VISUAL_RADIUS = 22.0f; // Visual size of the hole
  50. const float POCKET_RADIUS = HOLE_VISUAL_RADIUS * 1.05f; // Make detection radius slightly larger // Make detection radius match visual size (or slightly larger)
  51. const float MAX_SHOT_POWER = 15.0f;
  52. const float FRICTION = 0.985f; // Friction factor per frame
  53. const float MIN_VELOCITY_SQ = 0.01f * 0.01f; // Stop balls below this squared velocity
  54. const float HEADSTRING_X = TABLE_LEFT + TABLE_WIDTH * 0.30f; // 30% line
  55. const float RACK_POS_X = TABLE_LEFT + TABLE_WIDTH * 0.65f; // 65% line for rack apex
  56. const float RACK_POS_Y = TABLE_TOP + TABLE_HEIGHT / 2.0f;
  57. const UINT ID_TIMER = 1;
  58. const int TARGET_FPS = 60; // Target frames per second for timer
  59.  
  60. // --- Enums ---
  61. // --- MODIFIED/NEW Enums ---
  62. enum GameState {
  63.    SHOWING_DIALOG,     // NEW: Game is waiting for initial dialog input
  64.    PRE_BREAK_PLACEMENT,// Player placing cue ball for break
  65.    BREAKING,           // Player is aiming/shooting the break shot
  66.    CHOOSING_POCKET_P1, // NEW: Player 1 needs to call a pocket for the 8-ball
  67.    CHOOSING_POCKET_P2, // NEW: Player 2 needs to call a pocket for the 8-ball
  68.    AIMING,             // Player is aiming
  69.    AI_THINKING,        // NEW: AI is calculating its move
  70.    SHOT_IN_PROGRESS,   // Balls are moving
  71.    ASSIGNING_BALLS,    // Turn after break where ball types are assigned
  72.    PLAYER1_TURN,
  73.    PLAYER2_TURN,
  74.    BALL_IN_HAND_P1,
  75.    BALL_IN_HAND_P2,
  76.    GAME_OVER
  77. };
  78.  
  79. enum BallType {
  80.    NONE,
  81.    SOLID,  // Yellow (1-7)
  82.    STRIPE, // Red (9-15)
  83.    EIGHT_BALL, // Black (8)
  84.    CUE_BALL // White (0)
  85. };
  86.  
  87. // NEW Enums for Game Mode and AI Difficulty
  88. enum GameMode {
  89.    HUMAN_VS_HUMAN,
  90.    HUMAN_VS_AI
  91. };
  92.  
  93. enum AIDifficulty {
  94.    EASY,
  95.    MEDIUM,
  96.    HARD
  97. };
  98.  
  99. enum OpeningBreakMode {
  100.    CPU_BREAK,
  101.    P1_BREAK,
  102.    FLIP_COIN_BREAK
  103. };
  104.  
  105. // NEW: Enum and arrays for table color options
  106. enum TableColor {
  107.    INDIGO,
  108.    TAN,
  109.    TEAL,
  110.    GREEN,
  111.    RED
  112. };
  113.  
  114. // --- Structs ---
  115. struct Ball {
  116.    int id;             // 0=Cue, 1-7=Solid, 8=Eight, 9-15=Stripe
  117.    BallType type;
  118.    float x, y;
  119.    float vx, vy;
  120.    D2D1_COLOR_F color;
  121.    bool isPocketed;
  122. };
  123.  
  124. struct PlayerInfo {
  125.    BallType assignedType;
  126.    int ballsPocketedCount;
  127.    std::wstring name;
  128. };
  129.  
  130. // --- Global Variables ---
  131.  
  132. // Direct2D & DirectWrite
  133. ID2D1Factory* pFactory = nullptr;
  134. //ID2D1Factory* g_pD2DFactory = nullptr;
  135. ID2D1HwndRenderTarget* pRenderTarget = nullptr;
  136. IDWriteFactory* pDWriteFactory = nullptr;
  137. IDWriteTextFormat* pTextFormat = nullptr;
  138. IDWriteTextFormat* pLargeTextFormat = nullptr; // For "Foul!"
  139. IDWriteTextFormat* pBallNumFormat = nullptr;
  140.  
  141. // Game State
  142. HWND hwndMain = nullptr;
  143. GameState currentGameState = SHOWING_DIALOG; // Start by showing dialog
  144. std::vector<Ball> balls;
  145. int currentPlayer = 1; // 1 or 2
  146. PlayerInfo player1Info = { BallType::NONE, 0, L"Vince Woods"/*"Player 1"*/ };
  147. PlayerInfo player2Info = { BallType::NONE, 0, L"Virtus Pro"/*"CPU"*/ }; // Default P2 name
  148. bool foulCommitted = false;
  149. std::wstring gameOverMessage = L"";
  150. bool firstBallPocketedAfterBreak = false;
  151. std::vector<int> pocketedThisTurn;
  152. // --- NEW: 8-Ball Pocket Call Globals ---
  153. int calledPocketP1 = -1; // Pocket index (0-5) called by Player 1 for the 8-ball. -1 means not called.
  154. int calledPocketP2 = -1; // Pocket index (0-5) called by Player 2 for the 8-ball.
  155. int currentlyHoveredPocket = -1; // For visual feedback on which pocket is being hovered
  156. std::wstring pocketCallMessage = L""; // Message like "Choose a pocket..."
  157.     // --- NEW: Remember which pocket the 8?ball actually went into last shot
  158. int lastEightBallPocketIndex = -1;
  159. //int lastPocketedIndex = -1; // pocket index (0–5) of the last ball pocketed
  160. int called = -1;
  161. bool cueBallPocketed = false;
  162.  
  163. // --- NEW: Foul Tracking Globals ---
  164. int firstHitBallIdThisShot = -1;      // ID of the first object ball hit by cue ball (-1 if none)
  165. bool cueHitObjectBallThisShot = false; // Did cue ball hit an object ball this shot?
  166. bool railHitAfterContact = false;     // Did any ball hit a rail AFTER cue hit an object ball?
  167. // --- End New Foul Tracking Globals ---
  168.  
  169. // NEW Game Mode/AI Globals
  170. GameMode gameMode = HUMAN_VS_HUMAN; // Default mode
  171. AIDifficulty aiDifficulty = MEDIUM; // Default difficulty
  172. OpeningBreakMode openingBreakMode = CPU_BREAK; // Default opening break mode
  173. bool isPlayer2AI = false;           // Is Player 2 controlled by AI?
  174. bool aiTurnPending = false;         // Flag: AI needs to take its turn when possible
  175. // bool aiIsThinking = false;       // Replaced by AI_THINKING game state
  176. // NEW: Flag to indicate if the current shot is the opening break of the game
  177. bool isOpeningBreakShot = false;
  178.  
  179. // NEW: For AI shot planning and visualization
  180. struct AIPlannedShot {
  181.    float angle;
  182.    float power;
  183.    float spinX;
  184.    float spinY;
  185.    bool isValid; // Is there a valid shot planned?
  186. };
  187. AIPlannedShot aiPlannedShotDetails; // Stores the AI's next shot
  188. bool aiIsDisplayingAim = false;    // True when AI has decided a shot and is in "display aim" mode
  189. int aiAimDisplayFramesLeft = 0;  // How many frames left to display AI aim
  190. const int AI_AIM_DISPLAY_DURATION_FRAMES = 45; // Approx 0.75 seconds at 60 FPS, adjust as needed
  191.  
  192. // Input & Aiming
  193. POINT ptMouse = { 0, 0 };
  194. bool isAiming = false;
  195. bool isDraggingCueBall = false;
  196. // --- ENSURE THIS LINE EXISTS HERE ---
  197. bool isDraggingStick = false; // True specifically when drag initiated on the stick graphic
  198. // --- End Ensure ---
  199. bool isSettingEnglish = false;
  200. D2D1_POINT_2F aimStartPoint = { 0, 0 };
  201. float cueAngle = 0.0f;
  202. float shotPower = 0.0f;
  203. float cueSpinX = 0.0f; // Range -1 to 1
  204. float cueSpinY = 0.0f; // Range -1 to 1
  205. float pocketFlashTimer = 0.0f;
  206. bool cheatModeEnabled = false; // Cheat Mode toggle (G key)
  207. int draggingBallId = -1;
  208. bool keyboardAimingActive = false; // NEW FLAG: true when arrow keys modify aim/power
  209. MCIDEVICEID midiDeviceID = 0; //midi func
  210. std::atomic<bool> isMusicPlaying(false); //midi func
  211. std::thread musicThread; //midi func
  212. void StartMidi(HWND hwnd, const TCHAR* midiPath);
  213. void StopMidi();
  214.  
  215. // NEW: Global for selected table color and definitions
  216. TableColor selectedTableColor = INDIGO; // Default color
  217. const WCHAR* tableColorNames[] = { L"Indigo", L"Tan", L"Teal", L"Green", L"Red" };
  218. const D2D1_COLOR_F tableColorValues[] = {
  219. D2D1::ColorF(0.05f, 0.09f, 0.28f),       // Indigo
  220. D2D1::ColorF(0.3529f, 0.3137f, 0.2196f), // Tan
  221. D2D1::ColorF(0.0f, 0.5f, 0.5f)/*(0.0f, 0.4f, 0.4392f)*/,       // Teal
  222. D2D1::ColorF(0.1608f, 0.4000f, 0.1765f), // Green
  223. D2D1::ColorF(0.3882f, 0.1059f, 0.10196f) // Red
  224. };
  225.  
  226. // UI Element Positions
  227. D2D1_RECT_F powerMeterRect = { TABLE_RIGHT + CUSHION_THICKNESS + 10, TABLE_TOP, TABLE_RIGHT + CUSHION_THICKNESS + 40, TABLE_BOTTOM };
  228. D2D1_RECT_F spinIndicatorRect = { TABLE_LEFT - CUSHION_THICKNESS - 60, TABLE_TOP + 20, TABLE_LEFT - CUSHION_THICKNESS - 20, TABLE_TOP + 60 }; // Circle area
  229. D2D1_POINT_2F spinIndicatorCenter = { spinIndicatorRect.left + (spinIndicatorRect.right - spinIndicatorRect.left) / 2.0f, spinIndicatorRect.top + (spinIndicatorRect.bottom - spinIndicatorRect.top) / 2.0f };
  230. float spinIndicatorRadius = (spinIndicatorRect.right - spinIndicatorRect.left) / 2.0f;
  231. D2D1_RECT_F pocketedBallsBarRect = { TABLE_LEFT, TABLE_BOTTOM + CUSHION_THICKNESS + 30, TABLE_RIGHT, TABLE_BOTTOM + CUSHION_THICKNESS + 70 };
  232.  
  233. // Corrected Pocket Center Positions (aligned with table corners/edges)
  234. const D2D1_POINT_2F pocketPositions[6] = {
  235.     {TABLE_LEFT, TABLE_TOP},                           // Top-Left
  236.     {TABLE_LEFT + TABLE_WIDTH / 2.0f, TABLE_TOP},      // Top-Middle
  237.     {TABLE_RIGHT, TABLE_TOP},                          // Top-Right
  238.     {TABLE_LEFT, TABLE_BOTTOM},                        // Bottom-Left
  239.     {TABLE_LEFT + TABLE_WIDTH / 2.0f, TABLE_BOTTOM},   // Bottom-Middle
  240.     {TABLE_RIGHT, TABLE_BOTTOM}                        // Bottom-Right
  241. };
  242.  
  243. // Colors
  244. //const D2D1_COLOR_F TABLE_COLOR = D2D1::ColorF(0.0f, 0.5f, 0.5f); // Darker Green NEWCOLOR (0.0f, 0.5f, 0.1f) => (0.1608f, 0.4000f, 0.1765f) (uncomment this l8r if needbe)
  245. // This is now a variable that can be changed, not a constant.
  246. D2D1_COLOR_F TABLE_COLOR = D2D1::ColorF(0.05f, 0.09f, 0.28f); // Default to Indigo
  247. //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)
  248. /*
  249. MPool: *Darker tan= (0.3529f, 0.3137f, 0.2196f) *Indigo= (0.05f, 0.09f, 0.28f) xPurple= (0.1922f, 0.2941f, 0.4118f); xTan= (0.5333f, 0.4706f, 0.3569f); (Red= (0.3882f, 0.1059f, 0.10196f); *Green(default)= (0.1608f, 0.4000f, 0.1765f); *Teal= (0.0f, 0.4f, 0.4392f) + Teal40%reduction= (0.0f, 0.3333f, 0.4235f);
  250. Hex: Teal=#00abc2 Tan=#7c6d53 Teal2=#03adc2 xPurple=#314b69 ?Tan=#88785b Red=#631b1a
  251. */
  252. const D2D1_COLOR_F CUSHION_COLOR = D2D1::ColorF(D2D1::ColorF(0.3608f, 0.0275f, 0.0078f)); // NEWCOLOR ::Red => (0.3608f, 0.0275f, 0.0078f)
  253. //const D2D1_COLOR_F CUSHION_COLOR = D2D1::ColorF(D2D1::ColorF::Red); // NEWCOLOR ::Red => (0.3608f, 0.0275f, 0.0078f)
  254. const D2D1_COLOR_F POCKET_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
  255. const D2D1_COLOR_F CUE_BALL_COLOR = D2D1::ColorF(D2D1::ColorF::White);
  256. const D2D1_COLOR_F EIGHT_BALL_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
  257. const D2D1_COLOR_F SOLID_COLOR = D2D1::ColorF(D2D1::ColorF::Goldenrod); // Solids = Yellow Goldenrod
  258. const D2D1_COLOR_F STRIPE_COLOR = D2D1::ColorF(D2D1::ColorF::DarkOrchid);   // Stripes = Red DarkOrchid
  259. const D2D1_COLOR_F AIM_LINE_COLOR = D2D1::ColorF(D2D1::ColorF::White, 0.7f); // Semi-transparent white
  260. const D2D1_COLOR_F FOUL_TEXT_COLOR = D2D1::ColorF(D2D1::ColorF::Red);
  261. const D2D1_COLOR_F TURN_ARROW_COLOR = D2D1::ColorF(0.1333f, 0.7294f, 0.7490f); //NEWCOLOR 0.1333f, 0.7294f, 0.7490f => ::Blue
  262. //const D2D1_COLOR_F TURN_ARROW_COLOR = D2D1::ColorF(D2D1::ColorF::Blue);
  263. const D2D1_COLOR_F ENGLISH_DOT_COLOR = D2D1::ColorF(D2D1::ColorF::Red);
  264. const D2D1_COLOR_F UI_TEXT_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
  265.  
  266. // --------------------------------------------------------------------
  267. //  Realistic colours for each id (0-15)
  268. //  0 = cue-ball (white) | 1-7 solids | 8 = eight-ball | 9-15 stripes
  269. // --------------------------------------------------------------------
  270. static const D2D1_COLOR_F BALL_COLORS[16] =
  271. {
  272.     D2D1::ColorF(D2D1::ColorF::White),          // 0  cue
  273.     D2D1::ColorF(1.00f, 0.85f, 0.00f),          // 1  yellow
  274.     D2D1::ColorF(0.05f, 0.30f, 1.00f),          // 2  blue
  275.     D2D1::ColorF(0.90f, 0.10f, 0.10f),          // 3  red
  276.     D2D1::ColorF(0.55f, 0.25f, 0.85f),          // 4  purple
  277.     D2D1::ColorF(1.00f, 0.55f, 0.00f),          // 5  orange
  278.     D2D1::ColorF(0.00f, 0.60f, 0.30f),          // 6  green
  279.     D2D1::ColorF(0.50f, 0.05f, 0.05f),          // 7  maroon / burgundy
  280.     D2D1::ColorF(D2D1::ColorF::Black),          // 8  black
  281.     D2D1::ColorF(1.00f, 0.85f, 0.00f),          // 9  (yellow stripe)
  282.     D2D1::ColorF(0.05f, 0.30f, 1.00f),          // 10 blue stripe
  283.     D2D1::ColorF(0.90f, 0.10f, 0.10f),          // 11 red stripe
  284.     D2D1::ColorF(0.55f, 0.25f, 0.85f),          // 12 purple stripe
  285.     D2D1::ColorF(1.00f, 0.55f, 0.00f),          // 13 orange stripe
  286.     D2D1::ColorF(0.00f, 0.60f, 0.30f),          // 14 green stripe
  287.     D2D1::ColorF(0.50f, 0.05f, 0.05f)           // 15 maroon stripe
  288. };
  289.  
  290. // Quick helper
  291. inline D2D1_COLOR_F GetBallColor(int id)
  292. {
  293.     return (id >= 0 && id < 16) ? BALL_COLORS[id]
  294.         : D2D1::ColorF(D2D1::ColorF::White);
  295. }
  296.  
  297. // --- Forward Declarations ---
  298. HRESULT CreateDeviceResources();
  299. void DiscardDeviceResources();
  300. void OnPaint();
  301. void OnResize(UINT width, UINT height);
  302. void InitGame();
  303. void GameUpdate();
  304. void UpdatePhysics();
  305. void CheckCollisions();
  306. bool CheckPockets(); // Returns true if any ball was pocketed
  307. void ProcessShotResults();
  308. void ApplyShot(float power, float angle, float spinX, float spinY);
  309. void RespawnCueBall(bool behindHeadstring);
  310. bool AreBallsMoving();
  311. void SwitchTurns();
  312. //bool AssignPlayerBallTypes(BallType firstPocketedType);
  313. bool AssignPlayerBallTypes(BallType firstPocketedType,
  314.     bool creditShooter = true);
  315. void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed);
  316. Ball* GetBallById(int id);
  317. Ball* GetCueBall();
  318. //void PlayGameMusic(HWND hwnd); //midi func
  319. void AIBreakShot();
  320.  
  321. // Drawing Functions
  322. void DrawScene(ID2D1RenderTarget* pRT);
  323. void DrawTable(ID2D1RenderTarget* pRT, ID2D1Factory* pFactory);
  324. void DrawBalls(ID2D1RenderTarget* pRT);
  325. void DrawCueStick(ID2D1RenderTarget* pRT);
  326. void DrawAimingAids(ID2D1RenderTarget* pRT);
  327. void DrawUI(ID2D1RenderTarget* pRT);
  328. void DrawPowerMeter(ID2D1RenderTarget* pRT);
  329. void DrawSpinIndicator(ID2D1RenderTarget* pRT);
  330. void DrawPocketedBallsIndicator(ID2D1RenderTarget* pRT);
  331. void DrawBallInHandIndicator(ID2D1RenderTarget* pRT);
  332. // NEW
  333. void DrawPocketSelectionIndicator(ID2D1RenderTarget* pRT);
  334.  
  335. // Helper Functions
  336. float GetDistance(float x1, float y1, float x2, float y2);
  337. float GetDistanceSq(float x1, float y1, float x2, float y2);
  338. bool IsValidCueBallPosition(float x, float y, bool checkHeadstring);
  339. template <typename T> void SafeRelease(T** ppT);
  340. // --- NEW HELPER FORWARD DECLARATIONS ---
  341. bool IsPlayerOnEightBall(int player);
  342. void CheckAndTransitionToPocketChoice(int playerID);
  343. // --- ADD FORWARD DECLARATION FOR NEW HELPER HERE ---
  344. float PointToLineSegmentDistanceSq(D2D1_POINT_2F p, D2D1_POINT_2F a, D2D1_POINT_2F b);
  345. // --- End Forward Declaration ---
  346. 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
  347.  
  348. // --- NEW Forward Declarations ---
  349.  
  350. // AI Related
  351. struct AIShotInfo; // Define below
  352. void TriggerAIMove();
  353. void AIMakeDecision();
  354. void AIPlaceCueBall();
  355. AIShotInfo AIFindBestShot();
  356. AIShotInfo EvaluateShot(Ball* targetBall, int pocketIndex);
  357. bool IsPathClear(D2D1_POINT_2F start, D2D1_POINT_2F end, int ignoredBallId1, int ignoredBallId2);
  358. Ball* FindFirstHitBall(D2D1_POINT_2F start, float angle, float& hitDistSq); // Added hitDistSq output
  359. float CalculateShotPower(float cueToGhostDist, float targetToPocketDist);
  360. D2D1_POINT_2F CalculateGhostBallPos(Ball* targetBall, int pocketIndex);
  361. bool IsValidAIAimAngle(float angle); // Basic check
  362.  
  363. // Dialog Related
  364. INT_PTR CALLBACK NewGameDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam);
  365. void ShowNewGameDialog(HINSTANCE hInstance);
  366. void LoadSettings(); // For deserialization
  367. void SaveSettings(); // For serialization
  368. const std::wstring SETTINGS_FILE_NAME = L"Pool-Settings.txt";
  369. void ResetGame(HINSTANCE hInstance); // Function to handle F2 reset
  370.  
  371. // --- Forward Declaration for Window Procedure --- <<< Add this line HERE
  372. LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
  373.  
  374. // --- NEW Struct for AI Shot Evaluation ---
  375. struct AIShotInfo {
  376.     bool possible = false;          // Is this shot considered viable?
  377.     Ball* targetBall = nullptr;     // Which ball to hit
  378.     int pocketIndex = -1;           // Which pocket to aim for (0-5)
  379.     D2D1_POINT_2F ghostBallPos = { 0,0 }; // Where cue ball needs to hit target ball
  380.     float angle = 0.0f;             // Calculated shot angle
  381.     float power = 0.0f;             // Calculated shot power
  382.     float score = -1.0f;            // Score for this shot (higher is better)
  383.     bool involves8Ball = false;     // Is the target the 8-ball?
  384.     float spinX = 0.0f;
  385.     float spinY = 0.0f;
  386. };
  387.  
  388. /*
  389. table = TABLE_COLOR new: #29662d (0.1608, 0.4000, 0.1765) => old: (0.0f, 0.5f, 0.1f)
  390. rail CUSHION_COLOR = #5c0702 (0.3608, 0.0275, 0.0078) => ::Red
  391. gap = #e99d33 (0.9157, 0.6157, 0.2000) => ::Orange
  392. winbg = #5e8863 (0.3686, 0.5333, 0.3882) => 1.0f, 1.0f, 0.803f
  393. headstring = #47742f (0.2784, 0.4549, 0.1843) => ::White
  394. bluearrow = #08b0a5 (0.0314, 0.6902, 0.6471) *#22babf (0.1333,0.7294,0.7490) => ::Blue
  395. */
  396.  
  397. // --- NEW Settings Serialization Functions ---
  398. void SaveSettings() {
  399.     std::ofstream outFile(SETTINGS_FILE_NAME);
  400.     if (outFile.is_open()) {
  401.         outFile << static_cast<int>(gameMode) << std::endl;
  402.         outFile << static_cast<int>(aiDifficulty) << std::endl;
  403.         outFile << static_cast<int>(openingBreakMode) << std::endl;
  404.         outFile << static_cast<int>(selectedTableColor) << std::endl;
  405.         outFile.close();
  406.     }
  407.     // else: Handle error, e.g., log or silently fail
  408. }
  409.  
  410. void LoadSettings() {
  411.     std::ifstream inFile(SETTINGS_FILE_NAME);
  412.     if (inFile.is_open()) {
  413.         int gm, aid, obm;
  414.         if (inFile >> gm) {
  415.             gameMode = static_cast<GameMode>(gm);
  416.         }
  417.         if (inFile >> aid) {
  418.             aiDifficulty = static_cast<AIDifficulty>(aid);
  419.         }
  420.         if (inFile >> obm) {
  421.             openingBreakMode = static_cast<OpeningBreakMode>(obm);
  422.         }
  423.         int tc;
  424.         if (inFile >> tc) {
  425.             selectedTableColor = static_cast<TableColor>(tc);
  426.         }
  427.         inFile.close();
  428.  
  429.         // Validate loaded settings (optional, but good practice)
  430.         if (gameMode < HUMAN_VS_HUMAN || gameMode > HUMAN_VS_AI) gameMode = HUMAN_VS_HUMAN; // Default
  431.         if (aiDifficulty < EASY || aiDifficulty > HARD) aiDifficulty = MEDIUM; // Default
  432.         if (openingBreakMode < CPU_BREAK || openingBreakMode > FLIP_COIN_BREAK) openingBreakMode = CPU_BREAK; // Default
  433.     }
  434.     // else: File doesn't exist or couldn't be opened, use defaults (already set in global vars)
  435. }
  436. // --- End Settings Serialization Functions ---
  437.  
  438. // --- NEW Dialog Procedure ---
  439. INT_PTR CALLBACK NewGameDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {
  440.     switch (message) {
  441.     case WM_INITDIALOG:
  442.     {
  443.         // --- ACTION 4: Center Dialog Box ---
  444. // Optional: Force centering if default isn't working
  445.         RECT rcDlg, rcOwner, rcScreen;
  446.         HWND hwndOwner = GetParent(hDlg); // GetParent(hDlg) might be better if hwndMain is passed
  447.         if (hwndOwner == NULL) hwndOwner = GetDesktopWindow();
  448.  
  449.         GetWindowRect(hwndOwner, &rcOwner);
  450.         GetWindowRect(hDlg, &rcDlg);
  451.         CopyRect(&rcScreen, &rcOwner); // Use owner rect as reference bounds
  452.  
  453.         // Offset the owner rect relative to the screen if it's not the desktop
  454.         if (GetParent(hDlg) != NULL) { // If parented to main window (passed to DialogBoxParam)
  455.             OffsetRect(&rcOwner, -rcScreen.left, -rcScreen.top);
  456.             OffsetRect(&rcDlg, -rcScreen.left, -rcScreen.top);
  457.             OffsetRect(&rcScreen, -rcScreen.left, -rcScreen.top);
  458.         }
  459.  
  460.  
  461.         // Calculate centered position
  462.         int x = rcOwner.left + (rcOwner.right - rcOwner.left - (rcDlg.right - rcDlg.left)) / 2;
  463.         int y = rcOwner.top + (rcOwner.bottom - rcOwner.top - (rcDlg.bottom - rcDlg.top)) / 2;
  464.  
  465.         // Ensure it stays within screen bounds (optional safety)
  466.         x = std::max(static_cast<int>(rcScreen.left), x);
  467.         y = std::max(static_cast<int>(rcScreen.top), y);
  468.         if (x + (rcDlg.right - rcDlg.left) > rcScreen.right)
  469.             x = rcScreen.right - (rcDlg.right - rcDlg.left);
  470.         if (y + (rcDlg.bottom - rcDlg.top) > rcScreen.bottom)
  471.             y = rcScreen.bottom - (rcDlg.bottom - rcDlg.top);
  472.  
  473.  
  474.         // Set the dialog position
  475.         SetWindowPos(hDlg, HWND_TOP, x, y, 0, 0, SWP_NOSIZE);
  476.  
  477.         // --- End Centering Code ---
  478.  
  479.         // Set initial state based on current global settings (or defaults)
  480.         CheckRadioButton(hDlg, IDC_RADIO_2P, IDC_RADIO_CPU, (gameMode == HUMAN_VS_HUMAN) ? IDC_RADIO_2P : IDC_RADIO_CPU);
  481.  
  482.         CheckRadioButton(hDlg, IDC_RADIO_EASY, IDC_RADIO_HARD,
  483.             (aiDifficulty == EASY) ? IDC_RADIO_EASY : ((aiDifficulty == MEDIUM) ? IDC_RADIO_MEDIUM : IDC_RADIO_HARD));
  484.  
  485.         // Enable/Disable AI group based on initial mode
  486.         EnableWindow(GetDlgItem(hDlg, IDC_GROUP_AI), gameMode == HUMAN_VS_AI);
  487.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_EASY), gameMode == HUMAN_VS_AI);
  488.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_MEDIUM), gameMode == HUMAN_VS_AI);
  489.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_HARD), gameMode == HUMAN_VS_AI);
  490.         // Set initial state for Opening Break Mode
  491.         CheckRadioButton(hDlg, IDC_RADIO_CPU_BREAK, IDC_RADIO_FLIP_BREAK,
  492.             (openingBreakMode == CPU_BREAK) ? IDC_RADIO_CPU_BREAK : ((openingBreakMode == P1_BREAK) ? IDC_RADIO_P1_BREAK : IDC_RADIO_FLIP_BREAK));
  493.         // Enable/Disable Opening Break group based on initial mode
  494.         EnableWindow(GetDlgItem(hDlg, IDC_GROUP_BREAK_MODE), gameMode == HUMAN_VS_AI);
  495.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_CPU_BREAK), gameMode == HUMAN_VS_AI);
  496.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_P1_BREAK), gameMode == HUMAN_VS_AI);
  497.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_FLIP_BREAK), gameMode == HUMAN_VS_AI);
  498.         // --- NEW: Populate the Table Color ComboBox ---
  499.         HWND hCombo = GetDlgItem(hDlg, IDC_COMBO_TABLECOLOR);
  500.         for (int i = 0; i < 5; ++i) {
  501.             SendMessage(hCombo, CB_ADDSTRING, 0, (LPARAM)tableColorNames[i]);
  502.         }
  503.         // Set the initial selection based on the loaded/default setting
  504.         SendMessage(hCombo, CB_SETCURSEL, (WPARAM)selectedTableColor, 0);
  505.     }
  506.     return (INT_PTR)TRUE;
  507.  
  508.     case WM_COMMAND:
  509.     { // Add an opening brace to create a new scope for the entire case.
  510.         HWND hCombo;
  511.         int selectedIndex;
  512.         switch (LOWORD(wParam)) {
  513.         case IDC_RADIO_2P:
  514.         case IDC_RADIO_CPU:
  515.         {
  516.             bool isCPU = IsDlgButtonChecked(hDlg, IDC_RADIO_CPU) == BST_CHECKED;
  517.             // Enable/Disable AI group controls based on selection
  518.             EnableWindow(GetDlgItem(hDlg, IDC_GROUP_AI), isCPU);
  519.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_EASY), isCPU);
  520.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_MEDIUM), isCPU);
  521.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_HARD), isCPU);
  522.             // Also enable/disable Opening Break Mode group
  523.             EnableWindow(GetDlgItem(hDlg, IDC_GROUP_BREAK_MODE), isCPU);
  524.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_CPU_BREAK), isCPU);
  525.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_P1_BREAK), isCPU);
  526.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_FLIP_BREAK), isCPU);
  527.         }
  528.         return (INT_PTR)TRUE;
  529.  
  530.         case IDOK:
  531.             // Retrieve selected options and store in global variables
  532.             if (IsDlgButtonChecked(hDlg, IDC_RADIO_CPU) == BST_CHECKED) {
  533.                 gameMode = HUMAN_VS_AI;
  534.                 if (IsDlgButtonChecked(hDlg, IDC_RADIO_EASY) == BST_CHECKED) aiDifficulty = EASY;
  535.                 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_MEDIUM) == BST_CHECKED) aiDifficulty = MEDIUM;
  536.                 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_HARD) == BST_CHECKED) aiDifficulty = HARD;
  537.  
  538.                 if (IsDlgButtonChecked(hDlg, IDC_RADIO_CPU_BREAK) == BST_CHECKED) openingBreakMode = CPU_BREAK;
  539.                 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_P1_BREAK) == BST_CHECKED) openingBreakMode = P1_BREAK;
  540.                 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_FLIP_BREAK) == BST_CHECKED) openingBreakMode = FLIP_COIN_BREAK;
  541.             }
  542.             else {
  543.                 gameMode = HUMAN_VS_HUMAN;
  544.                 // openingBreakMode doesn't apply to HvsH, can leave as is or reset
  545.             }
  546.  
  547.             // --- NEW: Retrieve selected table color ---
  548.             hCombo = GetDlgItem(hDlg, IDC_COMBO_TABLECOLOR);
  549.             selectedIndex = (int)SendMessage(hCombo, CB_GETCURSEL, 0, 0);
  550.             if (selectedIndex != CB_ERR) {
  551.                 selectedTableColor = static_cast<TableColor>(selectedIndex);
  552.             }
  553.  
  554.             SaveSettings(); // Save settings when OK is pressed
  555.             EndDialog(hDlg, IDOK); // Close dialog, return IDOK
  556.             return (INT_PTR)TRUE;
  557.  
  558.         case IDCANCEL: // Handle Cancel or closing the dialog
  559.             // Optionally, could reload settings here if you want cancel to revert to previously saved state
  560.             EndDialog(hDlg, IDCANCEL);
  561.             return (INT_PTR)TRUE;
  562.         }
  563.     } // Add a closing brace for the new scope.
  564.     break; // End WM_COMMAND
  565.     }
  566.     return (INT_PTR)FALSE; // Default processing
  567. }
  568.  
  569. // --- NEW Helper to Show Dialog ---
  570. void ShowNewGameDialog(HINSTANCE hInstance) {
  571.     if (DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_NEWGAMEDLG), hwndMain, NewGameDialogProc, 0) == IDOK) {
  572.         // User clicked Start, reset game with new settings
  573.         isPlayer2AI = (gameMode == HUMAN_VS_AI); // Update AI flag
  574.         if (isPlayer2AI) {
  575.             switch (aiDifficulty) {
  576.             case EASY: player2Info.name = L"Virtus Pro (Easy)"/*"CPU (Easy)"*/; break;
  577.             case MEDIUM: player2Info.name = L"Virtus Pro (Medium)"/*"CPU (Medium)"*/; break;
  578.             case HARD: player2Info.name = L"Virtus Pro (Hard)"/*"CPU (Hard)"*/; break;
  579.             }
  580.         }
  581.         else {
  582.             player2Info.name = L"Billy Ray Cyrus"/*"Player 2"*/;
  583.         }
  584.         // Update window title
  585.         std::wstring windowTitle = L"Midnight Pool 4"/*"Direct2D 8-Ball Pool"*/;
  586.         if (gameMode == HUMAN_VS_HUMAN) windowTitle += L" (Human vs Human)";
  587.         else windowTitle += L" (Human vs " + player2Info.name + L")";
  588.         SetWindowText(hwndMain, windowTitle.c_str());
  589.  
  590.         // --- NEW: Apply the selected table color ---
  591.         TABLE_COLOR = tableColorValues[selectedTableColor];
  592.  
  593.         InitGame(); // Re-initialize game logic & board
  594.         InvalidateRect(hwndMain, NULL, TRUE); // Force redraw
  595.     }
  596.     else {
  597.         // User cancelled dialog - maybe just resume game? Or exit?
  598.         // For simplicity, we do nothing, game continues as it was.
  599.         // To exit on cancel from F2, would need more complex state management.
  600.     }
  601. }
  602.  
  603. // --- NEW Reset Game Function ---
  604. void ResetGame(HINSTANCE hInstance) {
  605.     // Call the helper function to show the dialog and re-init if OK clicked
  606.     ShowNewGameDialog(hInstance);
  607. }
  608.  
  609. // --- WinMain ---
  610. int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR, int nCmdShow) {
  611.     if (FAILED(CoInitialize(NULL))) {
  612.         MessageBox(NULL, L"COM Initialization Failed.", L"Error", MB_OK | MB_ICONERROR);
  613.         return -1;
  614.     }
  615.  
  616.     // --- NEW: Load settings at startup ---
  617.     LoadSettings();
  618.  
  619.     // --- NEW: Show configuration dialog FIRST ---
  620.     if (DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_NEWGAMEDLG), NULL, NewGameDialogProc, 0) != IDOK) {
  621.         // User cancelled the dialog
  622.         CoUninitialize();
  623.         return 0; // Exit gracefully if dialog cancelled
  624.     }
  625.     // Global gameMode and aiDifficulty are now set by the DialogProc
  626.  
  627.     // --- Apply the selected table color to the global before anything else draws ---
  628.     TABLE_COLOR = tableColorValues[selectedTableColor];
  629.  
  630.     // Set AI flag based on game mode
  631.     isPlayer2AI = (gameMode == HUMAN_VS_AI);
  632.     if (isPlayer2AI) {
  633.         switch (aiDifficulty) {
  634.         case EASY: player2Info.name = L"Virtus Pro (Easy)"/*"CPU (Easy)"*/; break;
  635.         case MEDIUM:player2Info.name = L"Virtus Pro (Medium)"/*"CPU (Medium)"*/; break;
  636.         case HARD: player2Info.name = L"Virtus Pro (Hard)"/*"CPU (Hard)"*/; break;
  637.         }
  638.     }
  639.     else {
  640.         player2Info.name = L"Billy Ray Cyrus"/*"Player 2"*/;
  641.     }
  642.     // --- End of Dialog Logic ---
  643.  
  644.  
  645.     WNDCLASS wc = { };
  646.     wc.lpfnWndProc = WndProc;
  647.     wc.hInstance = hInstance;
  648.     wc.lpszClassName = L"BLISS_GameEngine"/*"Direct2D_8BallPool"*/;
  649.     wc.hCursor = LoadCursor(NULL, IDC_ARROW);
  650.     wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
  651.     wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1)); // Use your actual icon ID here
  652.  
  653.     if (!RegisterClass(&wc)) {
  654.         MessageBox(NULL, L"Window Registration Failed.", L"Error", MB_OK | MB_ICONERROR);
  655.         CoUninitialize();
  656.         return -1;
  657.     }
  658.  
  659.     // --- ACTION 4: Calculate Centered Window Position ---
  660.     const int WINDOW_WIDTH = 1000; // Define desired width
  661.     const int WINDOW_HEIGHT = 700; // Define desired height
  662.     int screenWidth = GetSystemMetrics(SM_CXSCREEN);
  663.     int screenHeight = GetSystemMetrics(SM_CYSCREEN);
  664.     int windowX = (screenWidth - WINDOW_WIDTH) / 2;
  665.     int windowY = (screenHeight - WINDOW_HEIGHT) / 2;
  666.  
  667.     // --- Change Window Title based on mode ---
  668.     std::wstring windowTitle = L"Midnight Pool 4"/*"Direct2D 8-Ball Pool"*/;
  669.     if (gameMode == HUMAN_VS_HUMAN) windowTitle += L" (Human vs Human)";
  670.     else windowTitle += L" (Human vs " + player2Info.name + L")";
  671.  
  672.     DWORD dwStyle = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX; // No WS_THICKFRAME, No WS_MAXIMIZEBOX
  673.  
  674.     hwndMain = CreateWindowEx(
  675.         0, L"BLISS_GameEngine"/*"Direct2D_8BallPool"*/, windowTitle.c_str(), dwStyle,
  676.         windowX, windowY, WINDOW_WIDTH, WINDOW_HEIGHT,
  677.         NULL, NULL, hInstance, NULL
  678.     );
  679.  
  680.     if (!hwndMain) {
  681.         MessageBox(NULL, L"Window Creation Failed.", L"Error", MB_OK | MB_ICONERROR);
  682.         CoUninitialize();
  683.         return -1;
  684.     }
  685.  
  686.     // Initialize Direct2D Resources AFTER window creation
  687.     if (FAILED(CreateDeviceResources())) {
  688.         MessageBox(NULL, L"Failed to create Direct2D resources.", L"Error", MB_OK | MB_ICONERROR);
  689.         DestroyWindow(hwndMain);
  690.         CoUninitialize();
  691.         return -1;
  692.     }
  693.  
  694.     InitGame(); // Initialize game state AFTER resources are ready & mode is set
  695.     Sleep(500); // Allow window to fully initialize before starting the countdown //midi func
  696.     StartMidi(hwndMain, TEXT("BSQ.MID")); // Replace with your MIDI filename
  697.     //PlayGameMusic(hwndMain); //midi func
  698.  
  699.     ShowWindow(hwndMain, nCmdShow);
  700.     UpdateWindow(hwndMain);
  701.  
  702.     if (!SetTimer(hwndMain, ID_TIMER, 1000 / TARGET_FPS, NULL)) {
  703.         MessageBox(NULL, L"Could not SetTimer().", L"Error", MB_OK | MB_ICONERROR);
  704.         DestroyWindow(hwndMain);
  705.         CoUninitialize();
  706.         return -1;
  707.     }
  708.  
  709.     MSG msg = { };
  710.     // --- Modified Main Loop ---
  711.     // Handles the case where the game starts in SHOWING_DIALOG state (handled now before loop)
  712.     // or gets reset to it via F2. The main loop runs normally once game starts.
  713.     while (GetMessage(&msg, NULL, 0, 0)) {
  714.         // We might need modeless dialog handling here if F2 shows dialog
  715.         // while window is active, but DialogBoxParam is modal.
  716.         // Let's assume F2 hides main window, shows dialog, then restarts game loop.
  717.         // Simpler: F2 calls ResetGame which calls DialogBoxParam (modal) then InitGame.
  718.         TranslateMessage(&msg);
  719.         DispatchMessage(&msg);
  720.     }
  721.  
  722.  
  723.     KillTimer(hwndMain, ID_TIMER);
  724.     DiscardDeviceResources();
  725.     SaveSettings(); // Save settings on exit
  726.     CoUninitialize();
  727.  
  728.     return (int)msg.wParam;
  729. }
  730.  
  731. // --- WndProc ---
  732. LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
  733.     // Declare cueBall pointer once at the top, used in multiple cases
  734.     // For clarity, often better to declare within each case where needed.
  735.     Ball* cueBall = nullptr; // Initialize to nullptr
  736.     switch (msg) {
  737.     case WM_CREATE:
  738.         // Resources are now created in WinMain after CreateWindowEx
  739.         return 0;
  740.  
  741.     case WM_PAINT:
  742.         OnPaint();
  743.         // Validate the entire window region after painting
  744.         ValidateRect(hwnd, NULL);
  745.         return 0;
  746.  
  747.     case WM_SIZE: {
  748.         UINT width = LOWORD(lParam);
  749.         UINT height = HIWORD(lParam);
  750.         OnResize(width, height);
  751.         return 0;
  752.     }
  753.  
  754.     case WM_TIMER:
  755.         if (wParam == ID_TIMER) {
  756.             GameUpdate(); // Update game logic and physics
  757.             InvalidateRect(hwnd, NULL, FALSE); // Request redraw
  758.         }
  759.         return 0;
  760.  
  761.         // --- NEW: Handle F2 Key for Reset ---
  762.         // --- MODIFIED: Handle More Keys ---
  763.     case WM_KEYDOWN:
  764.     { // Add scope for variable declarations
  765.  
  766.         // --- FIX: Get Cue Ball pointer for this scope ---
  767.         cueBall = GetCueBall();
  768.         // We might allow some keys even if cue ball is gone (like F1/F2), but actions need it
  769.         // --- End Fix ---
  770.  
  771.         // Check which player can interact via keyboard (Humans only)
  772.         bool canPlayerControl = ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == AIMING || currentGameState == BREAKING || currentGameState == BALL_IN_HAND_P1 || currentGameState == PRE_BREAK_PLACEMENT)) ||
  773.             (currentPlayer == 2 && !isPlayer2AI && (currentGameState == PLAYER2_TURN || currentGameState == AIMING || currentGameState == BREAKING || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT)));
  774.  
  775.         // --- F1 / F2 Keys (Always available) ---
  776.         if (wParam == VK_F2) {
  777.             HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE);
  778.             ResetGame(hInstance); // Call reset function
  779.             return 0; // Indicate key was processed
  780.         }
  781.         else if (wParam == VK_F1) {
  782.             MessageBox(hwnd,
  783.                 L"Direct2D-based StickPool game made in C++ from scratch (4827+ lines of code)\n" // Update line count if needed {2764+ lines}
  784.                 L"First successful Clone in C++ (no other sites or projects were there to glean from.) Made /w AI assist\n"
  785.                 L"(others were in JS/ non-8-Ball in C# etc.) w/o OOP and Graphics Frameworks all in a Single file.\n"
  786.                 L"Copyright (C) 2025 Evans Thorpemorton, Entisoft Solutions. Midnight Pool 4. 'BLISS' Game Engine.\n"
  787.                 L"Includes AI Difficulty Modes, Aim-Trajectory For Table Rails + Hard Angles TipShots. || F2=New Game",
  788.                 L"About This Game", MB_OK | MB_ICONINFORMATION);
  789.             return 0; // Indicate key was processed
  790.         }
  791.  
  792.         // Check for 'M' key (uppercase or lowercase)
  793.             // Toggle music with "M"
  794.         if (wParam == 'M' || wParam == 'm') {
  795.             //static bool isMusicPlaying = false;
  796.             if (isMusicPlaying) {
  797.                 // Stop the music
  798.                 StopMidi();
  799.                 isMusicPlaying = false;
  800.             }
  801.             else {
  802.                 // Build the MIDI file path
  803.                 TCHAR midiPath[MAX_PATH];
  804.                 GetModuleFileName(NULL, midiPath, MAX_PATH);
  805.                 // Keep only the directory part
  806.                 TCHAR* lastBackslash = _tcsrchr(midiPath, '\\');
  807.                 if (lastBackslash != NULL) {
  808.                     *(lastBackslash + 1) = '\0';
  809.                 }
  810.                 // Append the MIDI filename
  811.                 _tcscat_s(midiPath, MAX_PATH, TEXT("BSQ.MID")); // Adjust filename if needed
  812.  
  813.                 // Start playing MIDI
  814.                 StartMidi(hwndMain, midiPath);
  815.                 isMusicPlaying = true;
  816.             }
  817.         }
  818.  
  819.  
  820.         // --- Player Interaction Keys (Only if allowed) ---
  821.         if (canPlayerControl) {
  822.             // --- Get Shift Key State ---
  823.             bool shiftPressed = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
  824.             float angleStep = shiftPressed ? 0.05f : 0.01f; // Base step / Faster step (Adjust as needed) // Multiplier was 5x
  825.             float powerStep = 0.2f; // Power step (Adjust as needed)
  826.  
  827.             switch (wParam) {
  828.             case VK_LEFT: // Rotate Cue Stick Counter-Clockwise
  829.                 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  830.                     cueAngle -= angleStep;
  831.                     // Normalize angle (keep between 0 and 2*PI)
  832.                     if (cueAngle < 0) cueAngle += 2 * PI;
  833.                     // Ensure state shows aiming visuals if turn just started
  834.                     if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
  835.                     isAiming = false; // Keyboard adjust doesn't use mouse aiming state
  836.                     isDraggingStick = false;
  837.                     keyboardAimingActive = true;
  838.                 }
  839.                 break;
  840.  
  841.             case VK_RIGHT: // Rotate Cue Stick Clockwise
  842.                 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  843.                     cueAngle += angleStep;
  844.                     // Normalize angle (keep between 0 and 2*PI)
  845.                     if (cueAngle >= 2 * PI) cueAngle -= 2 * PI;
  846.                     // Ensure state shows aiming visuals if turn just started
  847.                     if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
  848.                     isAiming = false;
  849.                     isDraggingStick = false;
  850.                     keyboardAimingActive = true;
  851.                 }
  852.                 break;
  853.  
  854.             case VK_UP: // Decrease Shot Power
  855.                 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  856.                     shotPower -= powerStep;
  857.                     if (shotPower < 0.0f) shotPower = 0.0f;
  858.                     // Ensure state shows aiming visuals if turn just started
  859.                     if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
  860.                     isAiming = true; // Keyboard adjust doesn't use mouse aiming state
  861.                     isDraggingStick = false;
  862.                     keyboardAimingActive = true;
  863.                 }
  864.                 break;
  865.  
  866.             case VK_DOWN: // Increase Shot Power
  867.                 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  868.                     shotPower += powerStep;
  869.                     if (shotPower > MAX_SHOT_POWER) shotPower = MAX_SHOT_POWER;
  870.                     // Ensure state shows aiming visuals if turn just started
  871.                     if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
  872.                     isAiming = true;
  873.                     isDraggingStick = false;
  874.                     keyboardAimingActive = true;
  875.                 }
  876.                 break;
  877.  
  878.             case VK_SPACE: // Trigger Shot
  879.                 if ((currentGameState == AIMING || currentGameState == BREAKING || currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN)
  880.                     && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING)
  881.                 {
  882.                     if (shotPower > 0.15f) { // Use same threshold as mouse
  883.                        // Reset foul flags BEFORE applying shot
  884.                         firstHitBallIdThisShot = -1;
  885.                         cueHitObjectBallThisShot = false;
  886.                         railHitAfterContact = false;
  887.  
  888.                         // Play sound & Apply Shot
  889.                         std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
  890.                         ApplyShot(shotPower, cueAngle, cueSpinX, cueSpinY);
  891.  
  892.                         // Update State
  893.                         currentGameState = SHOT_IN_PROGRESS;
  894.                         foulCommitted = false;
  895.                         pocketedThisTurn.clear();
  896.                         shotPower = 0; // Reset power after shooting
  897.                         isAiming = false; isDraggingStick = false; // Reset aiming flags
  898.                         keyboardAimingActive = false;
  899.                     }
  900.                 }
  901.                 break;
  902.  
  903.             case VK_ESCAPE: // Cancel Aim/Shot Setup
  904.                 if ((currentGameState == AIMING || currentGameState == BREAKING) || shotPower > 0)
  905.                 {
  906.                     shotPower = 0.0f;
  907.                     isAiming = false;
  908.                     isDraggingStick = false;
  909.                     keyboardAimingActive = false;
  910.                     // Revert to basic turn state if not breaking
  911.                     if (currentGameState != BREAKING) {
  912.                         currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  913.                     }
  914.                     //if (currentPlayer == 1) calledPocketP1 = -1;
  915.                     //else                  calledPocketP2 = -1;
  916.                 }
  917.                 break;
  918.  
  919.             case 'G': // Toggle Cheat Mode
  920.                 cheatModeEnabled = !cheatModeEnabled;
  921.                 if (cheatModeEnabled)
  922.                     MessageBeep(MB_ICONEXCLAMATION); // Play a beep when enabling
  923.                 else
  924.                     MessageBeep(MB_OK); // Play a different beep when disabling
  925.                 break;
  926.  
  927.             default:
  928.                 // Allow default processing for other keys if needed
  929.                 // return DefWindowProc(hwnd, msg, wParam, lParam); // Usually not needed for WM_KEYDOWN
  930.                 break;
  931.             } // End switch(wParam) for player controls
  932.             return 0; // Indicate player control key was processed
  933.         } // End if(canPlayerControl)
  934.     } // End scope for WM_KEYDOWN case
  935.     // If key wasn't F1/F2 and player couldn't control, maybe allow default processing?
  936.     // return DefWindowProc(hwnd, msg, wParam, lParam); // Or just return 0
  937.     return 0;
  938.  
  939.     case WM_MOUSEMOVE: {
  940.         ptMouse.x = LOWORD(lParam);
  941.         ptMouse.y = HIWORD(lParam);
  942.  
  943.         // --- NEW LOGIC: Handle Pocket Hover ---
  944.         if ((currentGameState == CHOOSING_POCKET_P1 && currentPlayer == 1) ||
  945.             (currentGameState == CHOOSING_POCKET_P2 && currentPlayer == 2 && !isPlayer2AI)) {
  946.             int oldHover = currentlyHoveredPocket;
  947.             currentlyHoveredPocket = -1; // Reset
  948.             for (int i = 0; i < 6; ++i) {
  949.                 if (GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, pocketPositions[i].x, pocketPositions[i].y) < HOLE_VISUAL_RADIUS * HOLE_VISUAL_RADIUS * 2.25f) {
  950.                     currentlyHoveredPocket = i;
  951.                     break;
  952.                 }
  953.             }
  954.             if (oldHover != currentlyHoveredPocket) {
  955.                 InvalidateRect(hwnd, NULL, FALSE);
  956.             }
  957.             // Do NOT return 0 here, allow normal mouse angle update to continue
  958.         }
  959.         // --- END NEW LOGIC ---
  960.  
  961.  
  962.         cueBall = GetCueBall(); // Declare and get cueBall pointer
  963.  
  964.         if (isDraggingCueBall && cheatModeEnabled && draggingBallId != -1) {
  965.             Ball* ball = GetBallById(draggingBallId);
  966.             if (ball) {
  967.                 ball->x = (float)ptMouse.x;
  968.                 ball->y = (float)ptMouse.y;
  969.                 ball->vx = ball->vy = 0.0f;
  970.             }
  971.             return 0;
  972.         }
  973.  
  974.         if (!cueBall) return 0;
  975.  
  976.         // Update Aiming Logic (Check player turn)
  977.         if (isDraggingCueBall &&
  978.             ((currentPlayer == 1 && currentGameState == BALL_IN_HAND_P1) ||
  979.                 (!isPlayer2AI && currentPlayer == 2 && currentGameState == BALL_IN_HAND_P2) ||
  980.                 currentGameState == PRE_BREAK_PLACEMENT))
  981.         {
  982.             bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  983.             // Tentative position update
  984.             cueBall->x = (float)ptMouse.x;
  985.             cueBall->y = (float)ptMouse.y;
  986.             cueBall->vx = cueBall->vy = 0;
  987.         }
  988.         else if ((isAiming || isDraggingStick) &&
  989.             ((currentPlayer == 1 && (currentGameState == AIMING || currentGameState == BREAKING)) ||
  990.                 (!isPlayer2AI && currentPlayer == 2 && (currentGameState == AIMING || currentGameState == BREAKING))))
  991.         {
  992.             //NEW2 MOUSEBOUND CODE = START
  993.                 /*// Clamp mouse inside table bounds during aiming
  994.                 if (ptMouse.x < TABLE_LEFT) ptMouse.x = TABLE_LEFT;
  995.             if (ptMouse.x > TABLE_RIGHT) ptMouse.x = TABLE_RIGHT;
  996.             if (ptMouse.y < TABLE_TOP) ptMouse.y = TABLE_TOP;
  997.             if (ptMouse.y > TABLE_BOTTOM) ptMouse.y = TABLE_BOTTOM;*/
  998.             //NEW2 MOUSEBOUND CODE = END
  999.             // Aiming drag updates angle and power
  1000.             float dx = (float)ptMouse.x - cueBall->x;
  1001.             float dy = (float)ptMouse.y - cueBall->y;
  1002.             if (dx != 0 || dy != 0) cueAngle = atan2f(dy, dx);
  1003.             //float pullDist = GetDistance((float)ptMouse.x, (float)ptMouse.y, aimStartPoint.x, aimStartPoint.y);
  1004.             //shotPower = std::min(pullDist / 10.0f, MAX_SHOT_POWER);
  1005.             if (!keyboardAimingActive) { // Only update shotPower if NOT keyboard aiming
  1006.                 float pullDist = GetDistance((float)ptMouse.x, (float)ptMouse.y, aimStartPoint.x, aimStartPoint.y);
  1007.                 shotPower = std::min(pullDist / 10.0f, MAX_SHOT_POWER);
  1008.             }
  1009.         }
  1010.         else if (isSettingEnglish &&
  1011.             ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == AIMING || currentGameState == BREAKING)) ||
  1012.                 (!isPlayer2AI && currentPlayer == 2 && (currentGameState == PLAYER2_TURN || currentGameState == AIMING || currentGameState == BREAKING))))
  1013.         {
  1014.             // Setting English
  1015.             float dx = (float)ptMouse.x - spinIndicatorCenter.x;
  1016.             float dy = (float)ptMouse.y - spinIndicatorCenter.y;
  1017.             float dist = GetDistance(dx, dy, 0, 0);
  1018.             if (dist > spinIndicatorRadius) { dx *= spinIndicatorRadius / dist; dy *= spinIndicatorRadius / dist; }
  1019.             cueSpinX = dx / spinIndicatorRadius;
  1020.             cueSpinY = dy / spinIndicatorRadius;
  1021.         }
  1022.         else {
  1023.             //DISABLE PERM AIMING = START
  1024.             /*// Update visual angle even when not aiming/dragging (Check player turn)
  1025.             bool canUpdateVisualAngle = ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == BALL_IN_HAND_P1)) ||
  1026.                 (currentPlayer == 2 && !isPlayer2AI && (currentGameState == PLAYER2_TURN || currentGameState == BALL_IN_HAND_P2)) ||
  1027.                 currentGameState == PRE_BREAK_PLACEMENT || currentGameState == BREAKING || currentGameState == AIMING);
  1028.  
  1029.             if (canUpdateVisualAngle && !isDraggingCueBall && !isAiming && !isDraggingStick && !keyboardAimingActive) // NEW: Prevent mouse override if keyboard aiming
  1030.             {
  1031.                 // NEW MOUSEBOUND CODE = START
  1032.                     // Only update cue angle if mouse is inside the playable table area
  1033.                 if (ptMouse.x >= TABLE_LEFT && ptMouse.x <= TABLE_RIGHT &&
  1034.                     ptMouse.y >= TABLE_TOP && ptMouse.y <= TABLE_BOTTOM)
  1035.                 {
  1036.                     // NEW MOUSEBOUND CODE = END
  1037.                     Ball* cb = cueBall; // Use function-scope cueBall // Already got cueBall above
  1038.                     if (cb) {
  1039.                         float dx = (float)ptMouse.x - cb->x;
  1040.                         float dy = (float)ptMouse.y - cb->y;
  1041.                         if (dx != 0 || dy != 0) cueAngle = atan2f(dy, dx);
  1042.                     }
  1043.                 } //NEW MOUSEBOUND CODE LINE = DISABLE
  1044.             }*/
  1045.             //DISABLE PERM AIMING = END
  1046.         }
  1047.         return 0;
  1048.     } // End WM_MOUSEMOVE
  1049.  
  1050.     case WM_LBUTTONDOWN: {
  1051.         ptMouse.x = LOWORD(lParam);
  1052.         ptMouse.y = HIWORD(lParam);
  1053.  
  1054.         // --- FOOLPROOF FIX: This block implements the two-stage pocket selection ---
  1055.         if ((currentGameState == CHOOSING_POCKET_P1 && currentPlayer == 1) ||
  1056.             (currentGameState == CHOOSING_POCKET_P2 && currentPlayer == 2 && !isPlayer2AI)) {
  1057.  
  1058.             int clickedPocketIndex = -1;
  1059.             // STAGE 1, STEP 1: Check if the click was on any of the 6 pockets
  1060.             for (int i = 0; i < 6; ++i) {
  1061.                 if (GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, pocketPositions[i].x, pocketPositions[i].y) < HOLE_VISUAL_RADIUS * HOLE_VISUAL_RADIUS * 2.25f) {
  1062.                     clickedPocketIndex = i;
  1063.                     break;
  1064.                 }
  1065.             }
  1066.  
  1067.             if (clickedPocketIndex != -1) {
  1068.                 // STAGE 1, STEP 2: Player clicked on a pocket. Update the choice.
  1069.                 // We DO NOT change the game state here. This allows re-selection.
  1070.                 if (currentPlayer == 1) calledPocketP1 = clickedPocketIndex;
  1071.                 else calledPocketP2 = clickedPocketIndex;
  1072.                 InvalidateRect(hwnd, NULL, FALSE); // Redraw to show the arrow has moved.
  1073.                 return 0; // Consume the click and stay in CHOOSING_POCKET state.
  1074.             }
  1075.  
  1076.             // STAGE 2, STEP 1: Check if the player is clicking the cue ball to confirm.
  1077.             Ball* cueBall = GetCueBall();
  1078.             int calledPocket = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  1079.             if (cueBall && calledPocket != -1 && GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y) < BALL_RADIUS * BALL_RADIUS * 25) {
  1080.                 // STAGE 2, STEP 2: A pocket has been selected, and the player now clicks the cue ball.
  1081.                 // NOW we transition to the normal aiming state.
  1082.                 currentGameState = AIMING; // Go to a generic aiming state.
  1083.                 pocketCallMessage = L""; // Clear the "Choose a pocket..." message.
  1084.                 isAiming = true; // Prepare for aiming.
  1085.                 aimStartPoint = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y); // Use your existing aim start variable.
  1086.                 return 0;
  1087.             }
  1088.  
  1089.             // If they click anywhere else (not a pocket, not the cue ball), do nothing.
  1090.             return 0;
  1091.         }
  1092.  
  1093.         /*// --- FOOLPROOF FIX: This block handles re-selectable pocket choice ---
  1094.         if ((currentGameState == CHOOSING_POCKET_P1 && currentPlayer == 1) ||
  1095.             (currentGameState == CHOOSING_POCKET_P2 && currentPlayer == 2 && !isPlayer2AI)) {
  1096.  
  1097.             int clickedPocketIndex = -1;
  1098.             // Check if the click was on any of the 6 pockets
  1099.             for (int i = 0; i < 6; ++i) {
  1100.                 if (GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, pocketPositions[i].x, pocketPositions[i].y) < HOLE_VISUAL_RADIUS * HOLE_VISUAL_RADIUS * 2.25f) {
  1101.                     clickedPocketIndex = i;
  1102.                     break;
  1103.                 }
  1104.             }
  1105.  
  1106.             if (clickedPocketIndex != -1) { // Player clicked on a pocket
  1107.                 // FIX: Update the called pocket, but DO NOT change the game state.
  1108.                 // This allows the player to click another pocket to change their mind.
  1109.                 if (currentPlayer == 1) calledPocketP1 = clickedPocketIndex;
  1110.                 else calledPocketP2 = clickedPocketIndex;
  1111.                 InvalidateRect(hwnd, NULL, FALSE); // Redraw to show updated arrow
  1112.                 return 0; // Consume the click and stay in CHOOSING_POCKET state
  1113.             }
  1114.  
  1115.             // FIX: Add new logic to CONFIRM the choice by clicking the cue ball.
  1116.             Ball* cueBall = GetCueBall();
  1117.             int calledPocket = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  1118.             if (cueBall && calledPocket != -1 && GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y) < BALL_RADIUS * BALL_RADIUS * 25) {
  1119.                 // A pocket has been selected, and the player now clicks the cue ball.
  1120.                 // NOW we transition to the normal aiming state.
  1121.                 currentGameState = AIMING; // Go to aiming, not PLAYER1_TURN
  1122.                 pocketCallMessage = L""; // Clear the "Choose a pocket..." message
  1123.                 isAiming = true; // Prepare for aiming
  1124.                 aimStartPoint = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y);
  1125.                 return 0;
  1126.             }
  1127.  
  1128.             // If they click anywhere else (not a pocket, not the cue ball), do nothing.
  1129.             return 0;
  1130.         }*/
  1131.  
  1132.         /*// --- handle pocket re-selection when choosing 8-ball pocket ---
  1133.         if ((currentGameState == CHOOSING_POCKET_P1 && currentPlayer == 1)
  1134.             || (currentGameState == CHOOSING_POCKET_P2 && currentPlayer == 2 && !isPlayer2AI))
  1135.         {
  1136.             POINT pt = { LOWORD(lParam), HIWORD(lParam) };
  1137.             for (int i = 0; i < 6; ++i) {
  1138.                 float dx = pt.x - pocketPositions[i].x;
  1139.                 float dy = pt.y - pocketPositions[i].y;
  1140.                 if (dx * dx + dy * dy <= POCKET_RADIUS * POCKET_RADIUS) {
  1141.                     // 1) Record the call
  1142.                     if (currentPlayer == 1) calledPocketP1 = i;
  1143.                     else                  calledPocketP2 = i;
  1144.                     // 2) Clear any prompt text
  1145.                     pocketCallMessage.clear();
  1146.                     // 3) Return to normal aiming state
  1147.                     currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  1148.                     // 4) Redraw (arrow stays because calledPocketP* >= 0)
  1149.                     InvalidateRect(hwnd, NULL, FALSE);
  1150.                     return 0; // consume click
  1151.                 }
  1152.             }
  1153.             return 0; // clicked outside ? stay in pocket?call until a valid pocket is chosen
  1154.         }*/
  1155.  
  1156.         // … rest of your click?to?aim logic …
  1157.  
  1158.         //replaced /w new code
  1159.         /*
  1160.         // --- FIX: Add this entire block at the top of WM_LBUTTONDOWN ---
  1161. // This handles input specifically for the pocket selection state.
  1162.         if ((currentGameState == CHOOSING_POCKET_P1 && currentPlayer == 1) ||
  1163.             (currentGameState == CHOOSING_POCKET_P2 && currentPlayer == 2 && !isPlayer2AI)) {
  1164.  
  1165.             int clickedPocketIndex = -1;
  1166.             // Check if the click was on any of the 6 pockets
  1167.             for (int i = 0; i < 6; ++i) {
  1168.                 if (GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, pocketPositions[i].x, pocketPositions[i].y) < HOLE_VISUAL_RADIUS * HOLE_VISUAL_RADIUS * 2.25f) {
  1169.                     clickedPocketIndex = i;
  1170.                     break;
  1171.                 }
  1172.             }
  1173.  
  1174.             if (clickedPocketIndex != -1) {
  1175.                 // A pocket was clicked. Update the selection but STAY in the choosing state.
  1176.                 // This allows the player to click another pocket to change their mind.
  1177.                 if (currentPlayer == 1) calledPocketP1 = clickedPocketIndex;
  1178.                 else calledPocketP2 = clickedPocketIndex;
  1179.                 InvalidateRect(hwnd, NULL, FALSE); // Redraw to show the arrow has moved.
  1180.                 return 0; // Consume the click and wait for the next action.
  1181.             }
  1182.  
  1183.             // If the player clicks the CUE BALL, that confirms their pocket selection.
  1184.             Ball* cueBall = GetCueBall();
  1185.             int calledPocket = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  1186.             if (cueBall && calledPocket != -1 && GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y) < BALL_RADIUS * BALL_RADIUS * 25) {
  1187.                 // A pocket has been selected, and the player now clicks the cue ball.
  1188.                 // NOW we transition to the normal aiming state.
  1189.                 currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  1190.                 pocketCallMessage = L""; // Clear the "Choose a pocket..." message
  1191.                 isAiming = true; // Prepare for aiming
  1192.                 aimStartPoint = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y); // Use your existing aim start variable
  1193.                 return 0;
  1194.             }
  1195.  
  1196.             // If they click anywhere else (not a pocket, not the cue ball), do nothing.
  1197.             return 0;
  1198.         }
  1199.         // --- END OF THE NEW BLOCK ---
  1200.         */
  1201.         //new code ends here
  1202.  
  1203.         if (cheatModeEnabled) {
  1204.             // Allow dragging any ball freely
  1205.             for (Ball& ball : balls) {
  1206.                 float distSq = GetDistanceSq(ball.x, ball.y, (float)ptMouse.x, (float)ptMouse.y);
  1207.                 if (distSq <= BALL_RADIUS * BALL_RADIUS * 4) { // Click near ball
  1208.                     isDraggingCueBall = true;
  1209.                     draggingBallId = ball.id;
  1210.                     if (ball.id == 0) {
  1211.                         // If dragging cue ball manually, ensure we stay in Ball-In-Hand state
  1212.                         if (currentPlayer == 1)
  1213.                             currentGameState = BALL_IN_HAND_P1;
  1214.                         else if (currentPlayer == 2 && !isPlayer2AI)
  1215.                             currentGameState = BALL_IN_HAND_P2;
  1216.                     }
  1217.                     return 0;
  1218.                 }
  1219.             }
  1220.         }
  1221.  
  1222.         Ball* cueBall = GetCueBall(); // Declare and get cueBall pointer            
  1223.  
  1224.         // Check which player is allowed to interact via mouse click
  1225.         bool canPlayerClickInteract = ((currentPlayer == 1) || (currentPlayer == 2 && !isPlayer2AI));
  1226.         // Define states where interaction is generally allowed
  1227.         bool canInteractState = (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN ||
  1228.             currentGameState == AIMING || currentGameState == BREAKING ||
  1229.             currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 ||
  1230.             currentGameState == PRE_BREAK_PLACEMENT);
  1231.  
  1232.         // Check Spin Indicator first (Allow if player's turn/aim phase)
  1233.         if (canPlayerClickInteract && canInteractState) {
  1234.             float spinDistSq = GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, spinIndicatorCenter.x, spinIndicatorCenter.y);
  1235.             if (spinDistSq < spinIndicatorRadius * spinIndicatorRadius * 1.2f) {
  1236.                 isSettingEnglish = true;
  1237.                 float dx = (float)ptMouse.x - spinIndicatorCenter.x;
  1238.                 float dy = (float)ptMouse.y - spinIndicatorCenter.y;
  1239.                 float dist = GetDistance(dx, dy, 0, 0);
  1240.                 if (dist > spinIndicatorRadius) { dx *= spinIndicatorRadius / dist; dy *= spinIndicatorRadius / dist; }
  1241.                 cueSpinX = dx / spinIndicatorRadius;
  1242.                 cueSpinY = dy / spinIndicatorRadius;
  1243.                 isAiming = false; isDraggingStick = false; isDraggingCueBall = false;
  1244.                 return 0;
  1245.             }
  1246.         }
  1247.  
  1248.         if (!cueBall) return 0;
  1249.  
  1250.         // Check Ball-in-Hand placement/drag
  1251.         bool isPlacingBall = (currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT);
  1252.         bool isPlayerAllowedToPlace = (isPlacingBall &&
  1253.             ((currentPlayer == 1 && currentGameState == BALL_IN_HAND_P1) ||
  1254.                 (currentPlayer == 2 && !isPlayer2AI && currentGameState == BALL_IN_HAND_P2) ||
  1255.                 (currentGameState == PRE_BREAK_PLACEMENT))); // Allow current player in break setup
  1256.  
  1257.         if (isPlayerAllowedToPlace) {
  1258.             float distSq = GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y);
  1259.             if (distSq < BALL_RADIUS * BALL_RADIUS * 9.0f) {
  1260.                 isDraggingCueBall = true;
  1261.                 isAiming = false; isDraggingStick = false;
  1262.             }
  1263.             else {
  1264.                 bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  1265.                 if (IsValidCueBallPosition((float)ptMouse.x, (float)ptMouse.y, behindHeadstring)) {
  1266.                     cueBall->x = (float)ptMouse.x; cueBall->y = (float)ptMouse.y;
  1267.                     cueBall->vx = 0; cueBall->vy = 0;
  1268.                     isDraggingCueBall = false;
  1269.                     // Transition state
  1270.                     if (currentGameState == PRE_BREAK_PLACEMENT) currentGameState = BREAKING;
  1271.                     else if (currentGameState == BALL_IN_HAND_P1) currentGameState = PLAYER1_TURN;
  1272.                     else if (currentGameState == BALL_IN_HAND_P2) currentGameState = PLAYER2_TURN;
  1273.                     cueAngle = 0.0f;
  1274.                 }
  1275.             }
  1276.             return 0;
  1277.         }
  1278.  
  1279.         // Check for starting Aim (Cue Ball OR Stick)
  1280.         bool canAim = ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == BREAKING)) ||
  1281.             (currentPlayer == 2 && !isPlayer2AI && (currentGameState == PLAYER2_TURN || currentGameState == BREAKING)));
  1282.  
  1283.         if (canAim) {
  1284.             const float stickDrawLength = 150.0f * 1.4f;
  1285.             float currentStickAngle = cueAngle + PI;
  1286.             D2D1_POINT_2F currentStickEnd = D2D1::Point2F(cueBall->x + cosf(currentStickAngle) * stickDrawLength, cueBall->y + sinf(currentStickAngle) * stickDrawLength);
  1287.             D2D1_POINT_2F currentStickTip = D2D1::Point2F(cueBall->x + cosf(currentStickAngle) * 5.0f, cueBall->y + sinf(currentStickAngle) * 5.0f);
  1288.             float distToStickSq = PointToLineSegmentDistanceSq(D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y), currentStickTip, currentStickEnd);
  1289.             float stickClickThresholdSq = 36.0f;
  1290.             float distToCueBallSq = GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y);
  1291.             float cueBallClickRadiusSq = BALL_RADIUS * BALL_RADIUS * 25;
  1292.  
  1293.             bool clickedStick = (distToStickSq < stickClickThresholdSq);
  1294.             bool clickedCueArea = (distToCueBallSq < cueBallClickRadiusSq);
  1295.  
  1296.             if (clickedStick || clickedCueArea) {
  1297.                 isDraggingStick = clickedStick && !clickedCueArea;
  1298.                 isAiming = clickedCueArea;
  1299.                 aimStartPoint = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y);
  1300.                 shotPower = 0;
  1301.                 float dx = (float)ptMouse.x - cueBall->x;
  1302.                 float dy = (float)ptMouse.y - cueBall->y;
  1303.                 if (dx != 0 || dy != 0) cueAngle = atan2f(dy, dx);
  1304.                 if (currentGameState != BREAKING) currentGameState = AIMING;
  1305.             }
  1306.         }
  1307.         return 0;
  1308.     } // End WM_LBUTTONDOWN
  1309.  
  1310.  
  1311.     case WM_LBUTTONUP: {
  1312.         // --- FOOLPROOF FIX for Cheat Mode Scoring ---
  1313.         if (cheatModeEnabled && draggingBallId != -1) {
  1314.             Ball* b = GetBallById(draggingBallId);
  1315.             if (b) {
  1316.                 for (int p = 0; p < 6; ++p) {
  1317.                     float dx = b->x - pocketPositions[p].x;
  1318.                     float dy = b->y - pocketPositions[p].y;
  1319.                     if (dx * dx + dy * dy <= POCKET_RADIUS * POCKET_RADIUS) {
  1320.                         // --- This is the new, "smarter" logic ---
  1321.                         b->isPocketed = true; // Pocket the ball visually.
  1322.  
  1323.                         // If the table is open, assign types based on this cheated ball.
  1324.                         if (player1Info.assignedType == BallType::NONE && b->id != 0 && b->id != 8) {
  1325.                             AssignPlayerBallTypes(b->type, false);
  1326.                         }
  1327.  
  1328.                         // Now, correctly update the score for the right player.
  1329.                         if (b->id != 0 && b->id != 8) {
  1330.                             if (b->type == player1Info.assignedType) {
  1331.                                 player1Info.ballsPocketedCount++;
  1332.                             }
  1333.                             else if (b->type == player2Info.assignedType) {
  1334.                                 player2Info.ballsPocketedCount++;
  1335.                             }
  1336.                         }
  1337.                         break; // Stop checking pockets.
  1338.                     }
  1339.                 }
  1340.             }
  1341.         }
  1342.  
  1343.         /*if (cheatModeEnabled && draggingBallId != -1) {
  1344.             Ball* b = GetBallById(draggingBallId);
  1345.             if (b) {
  1346.                 for (int p = 0; p < 6; ++p) {
  1347.                     float dx = b->x - pocketPositions[p].x;
  1348.                     float dy = b->y - pocketPositions[p].y;
  1349.                     if (dx * dx + dy * dy <= POCKET_RADIUS * POCKET_RADIUS) {
  1350.                         // --- Assign ball type on first cheat-pocket if table still open ---
  1351.                         if (player1Info.assignedType == BallType::NONE
  1352.                             && player2Info.assignedType == BallType::NONE
  1353.                             && (b->type == BallType::SOLID || b->type == BallType::STRIPE))
  1354.                         {
  1355.                             // In cheat mode, let's just assign to the current player
  1356.                             AssignPlayerBallTypes(b->type);
  1357.                         }
  1358.                         b->isPocketed = true;
  1359.                         pocketedThisTurn.push_back(b->id);
  1360.  
  1361.                         // --- FIX FOR CHEAT MODE SCORING ---
  1362.                         // Immediately increment the correct player's count based on ball type,
  1363.                         // not whose turn it is.
  1364.                         if (b->id != 0 && b->id != 8) {
  1365.                             if (b->type == player1Info.assignedType) {
  1366.                                 player1Info.ballsPocketedCount++;
  1367.                             }
  1368.                             else if (b->type == player2Info.assignedType) {
  1369.                                 player2Info.ballsPocketedCount++;
  1370.                             }
  1371.                         }
  1372.                         // --- END FIX ---
  1373.                         // --- NEW: If this was the 7th ball, trigger the arrow call UI ---
  1374.                         if (b->id != 8) {
  1375.                             PlayerInfo& shooter = (currentPlayer == 1 ? player1Info : player2Info);
  1376.                             if (shooter.ballsPocketedCount >= 7
  1377.                                 && calledPocketP1 < 0
  1378.                                 && calledPocketP2 < 0)
  1379.                             {
  1380.                                 currentGameState = (currentPlayer == 1)
  1381.                                     ? CHOOSING_POCKET_P1
  1382.                                     : CHOOSING_POCKET_P2;
  1383.                             }
  1384.                             else {
  1385.                                 // For any other cheat?pocket, keep the turn so you can continue aiming
  1386.                                 currentGameState = (currentPlayer == 1)
  1387.                                     ? PLAYER1_TURN
  1388.                                     : PLAYER2_TURN;
  1389.                             }
  1390.                         }
  1391.                         // --- NEW: If it was the 8-Ball, award instant victory ---
  1392.                         else {
  1393.                             currentGameState = GAME_OVER;
  1394.                             gameOverMessage = (currentPlayer == 1 ? player1Info.name : player2Info.name)
  1395.                                 + std::wstring(L" Wins!");
  1396.                         }
  1397.                         break;
  1398.                     }
  1399.                 }
  1400.             }
  1401.         }*/
  1402.  
  1403.         ptMouse.x = LOWORD(lParam);
  1404.         ptMouse.y = HIWORD(lParam);
  1405.  
  1406.         Ball* cueBall = GetCueBall(); // Get cueBall pointer
  1407.  
  1408.         // Check for releasing aim drag (Stick OR Cue Ball)
  1409.         if ((isAiming || isDraggingStick) &&
  1410.             ((currentPlayer == 1 && (currentGameState == AIMING || currentGameState == BREAKING)) ||
  1411.                 (!isPlayer2AI && currentPlayer == 2 && (currentGameState == AIMING || currentGameState == BREAKING))))
  1412.         {
  1413.             bool wasAiming = isAiming;
  1414.             bool wasDraggingStick = isDraggingStick;
  1415.             isAiming = false; isDraggingStick = false;
  1416.  
  1417.             if (shotPower > 0.15f) { // Check power threshold
  1418.                 if (currentGameState != AI_THINKING) {
  1419.                     firstHitBallIdThisShot = -1; cueHitObjectBallThisShot = false; railHitAfterContact = false; // Reset foul flags
  1420.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
  1421.                     ApplyShot(shotPower, cueAngle, cueSpinX, cueSpinY);
  1422.                     currentGameState = SHOT_IN_PROGRESS;
  1423.                     foulCommitted = false; pocketedThisTurn.clear();
  1424.                 }
  1425.             }
  1426.             else if (currentGameState != AI_THINKING) { // Revert state if power too low
  1427.                 if (currentGameState == BREAKING) { /* Still breaking */ }
  1428.                 else {
  1429.                     currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  1430.                     if (currentPlayer == 2 && isPlayer2AI) aiTurnPending = false;
  1431.                 }
  1432.             }
  1433.             shotPower = 0; // Reset power indicator regardless
  1434.         }
  1435.  
  1436.         // Handle releasing cue ball drag (placement)
  1437.         if (isDraggingCueBall) {
  1438.             isDraggingCueBall = false;
  1439.             // Check player allowed to place
  1440.             bool isPlacingState = (currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT);
  1441.             bool isPlayerAllowed = (isPlacingState &&
  1442.                 ((currentPlayer == 1 && currentGameState == BALL_IN_HAND_P1) ||
  1443.                     (currentPlayer == 2 && !isPlayer2AI && currentGameState == BALL_IN_HAND_P2) ||
  1444.                     (currentGameState == PRE_BREAK_PLACEMENT)));
  1445.  
  1446.             if (isPlayerAllowed && cueBall) {
  1447.                 bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  1448.                 if (IsValidCueBallPosition(cueBall->x, cueBall->y, behindHeadstring)) {
  1449.                     // Finalize position already set by mouse move
  1450.                     // Transition state
  1451.                     if (currentGameState == PRE_BREAK_PLACEMENT) currentGameState = BREAKING;
  1452.                     else if (currentGameState == BALL_IN_HAND_P1) currentGameState = PLAYER1_TURN;
  1453.                     else if (currentGameState == BALL_IN_HAND_P2) currentGameState = PLAYER2_TURN;
  1454.                     cueAngle = 0.0f;
  1455.                     /* ----------------------------------------------------
  1456.                     If the player who now has the turn is already on the
  1457.                     8-ball, immediately switch to pocket-selection state.
  1458.                     ---------------------------------------------------- */
  1459.                     if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN)
  1460.                     {
  1461.                         CheckAndTransitionToPocketChoice(currentPlayer);
  1462.                     }
  1463.                 }
  1464.                 else { /* Stay in BALL_IN_HAND state if final pos invalid */ }
  1465.             }
  1466.         }
  1467.  
  1468.         // Handle releasing english setting
  1469.         if (isSettingEnglish) {
  1470.             isSettingEnglish = false;
  1471.         }
  1472.         return 0;
  1473.     } // End WM_LBUTTONUP
  1474.  
  1475.     case WM_DESTROY:
  1476.         isMusicPlaying = false;
  1477.         if (midiDeviceID != 0) {
  1478.             mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
  1479.             midiDeviceID = 0;
  1480.             SaveSettings(); // Save settings on exit
  1481.         }
  1482.         PostQuitMessage(0);
  1483.         return 0;
  1484.  
  1485.     default:
  1486.         return DefWindowProc(hwnd, msg, wParam, lParam);
  1487.     }
  1488.     return 0;
  1489. }
  1490.  
  1491. // --- Direct2D Resource Management ---
  1492.  
  1493. HRESULT CreateDeviceResources() {
  1494.     HRESULT hr = S_OK;
  1495.  
  1496.     // Create Direct2D Factory
  1497.     if (!pFactory) {
  1498.         hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &pFactory);
  1499.         if (FAILED(hr)) return hr;
  1500.     }
  1501.  
  1502.     // Create DirectWrite Factory
  1503.     if (!pDWriteFactory) {
  1504.         hr = DWriteCreateFactory(
  1505.             DWRITE_FACTORY_TYPE_SHARED,
  1506.             __uuidof(IDWriteFactory),
  1507.             reinterpret_cast<IUnknown**>(&pDWriteFactory)
  1508.         );
  1509.         if (FAILED(hr)) return hr;
  1510.     }
  1511.  
  1512.     // Create Text Formats
  1513.     if (!pTextFormat && pDWriteFactory) {
  1514.         hr = pDWriteFactory->CreateTextFormat(
  1515.             L"Segoe UI", NULL, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
  1516.             16.0f, L"en-us", &pTextFormat
  1517.         );
  1518.         if (FAILED(hr)) return hr;
  1519.         // Center align text
  1520.         pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  1521.         pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  1522.     }
  1523.     if (!pLargeTextFormat && pDWriteFactory) {
  1524.         hr = pDWriteFactory->CreateTextFormat(
  1525.             L"Impact", NULL, DWRITE_FONT_WEIGHT_BOLD, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
  1526.             48.0f, L"en-us", &pLargeTextFormat
  1527.         );
  1528.         if (FAILED(hr)) return hr;
  1529.         pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING); // Align left
  1530.         pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  1531.     }
  1532.  
  1533.     if (!pBallNumFormat && pDWriteFactory)
  1534.     {
  1535.         hr = pDWriteFactory->CreateTextFormat(
  1536.             L"Segoe UI", nullptr,
  1537.             DWRITE_FONT_WEIGHT_BOLD, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
  1538.             10.0f,                       // << small size for ball decals
  1539.             L"en-us",
  1540.             &pBallNumFormat);
  1541.         if (SUCCEEDED(hr))
  1542.         {
  1543.             pBallNumFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  1544.             pBallNumFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  1545.         }
  1546.     }
  1547.  
  1548.  
  1549.     // Create Render Target (needs valid hwnd)
  1550.     if (!pRenderTarget && hwndMain) {
  1551.         RECT rc;
  1552.         GetClientRect(hwndMain, &rc);
  1553.         D2D1_SIZE_U size = D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top);
  1554.  
  1555.         hr = pFactory->CreateHwndRenderTarget(
  1556.             D2D1::RenderTargetProperties(),
  1557.             D2D1::HwndRenderTargetProperties(hwndMain, size),
  1558.             &pRenderTarget
  1559.         );
  1560.         if (FAILED(hr)) {
  1561.             // If failed, release factories if they were created in this call
  1562.             SafeRelease(&pTextFormat);
  1563.             SafeRelease(&pLargeTextFormat);
  1564.             SafeRelease(&pDWriteFactory);
  1565.             SafeRelease(&pFactory);
  1566.             pRenderTarget = nullptr; // Ensure it's null on failure
  1567.             return hr;
  1568.         }
  1569.     }
  1570.  
  1571.     return hr;
  1572. }
  1573.  
  1574. void DiscardDeviceResources() {
  1575.     SafeRelease(&pRenderTarget);
  1576.     SafeRelease(&pTextFormat);
  1577.     SafeRelease(&pLargeTextFormat);
  1578.     SafeRelease(&pBallNumFormat);            // NEW
  1579.     SafeRelease(&pDWriteFactory);
  1580.     // Keep pFactory until application exit? Or release here too? Let's release.
  1581.     SafeRelease(&pFactory);
  1582. }
  1583.  
  1584. void OnResize(UINT width, UINT height) {
  1585.     if (pRenderTarget) {
  1586.         D2D1_SIZE_U size = D2D1::SizeU(width, height);
  1587.         pRenderTarget->Resize(size); // Ignore HRESULT for simplicity here
  1588.     }
  1589. }
  1590.  
  1591. // --- Game Initialization ---
  1592. void InitGame() {
  1593.     srand((unsigned int)time(NULL)); // Seed random number generator
  1594.     isOpeningBreakShot = true; // This is the start of a new game, so the next shot is an opening break.
  1595.     aiPlannedShotDetails.isValid = false; // Reset AI planned shot
  1596.     aiIsDisplayingAim = false;
  1597.     aiAimDisplayFramesLeft = 0;
  1598.     // ... (rest of InitGame())
  1599.  
  1600.     // --- Ensure pocketed list is clear from the absolute start ---
  1601.     pocketedThisTurn.clear();
  1602.  
  1603.     balls.clear(); // Clear existing balls
  1604.  
  1605.     // Reset Player Info (Names should be set by Dialog/wWinMain/ResetGame)
  1606.     player1Info.assignedType = BallType::NONE;
  1607.     player1Info.ballsPocketedCount = 0;
  1608.     // Player 1 Name usually remains "Player 1"
  1609.     player2Info.assignedType = BallType::NONE;
  1610.     player2Info.ballsPocketedCount = 0;
  1611.     // Player 2 Name is set based on gameMode in ShowNewGameDialog
  1612.         // --- Reset any 8?Ball call state on new game ---
  1613.     lastEightBallPocketIndex = -1;
  1614.     calledPocketP1 = -1;
  1615.     calledPocketP2 = -1;
  1616.     pocketCallMessage = L"";
  1617.     aiPlannedShotDetails.isValid = false; // THIS IS THE CRITICAL FIX: Reset the AI's plan.
  1618.  
  1619.     // Create Cue Ball (ID 0)
  1620.     // Initial position will be set during PRE_BREAK_PLACEMENT state
  1621.     balls.push_back({ 0, BallType::CUE_BALL, TABLE_LEFT + TABLE_WIDTH * 0.15f, RACK_POS_Y, 0, 0, CUE_BALL_COLOR, false });
  1622.  
  1623.     // --- Create Object Balls (Temporary List) ---
  1624.     std::vector<Ball> objectBalls;
  1625.     // Solids (1-7, Yellow)
  1626.     for (int i = 1; i <= 7; ++i) {
  1627.         //objectBalls.push_back({ i, BallType::SOLID, 0, 0, 0, 0, SOLID_COLOR, false });
  1628.         objectBalls.push_back({ i, BallType::SOLID, 0,0,0,0,
  1629.                     GetBallColor(i), false });
  1630.     }
  1631.     // Stripes (9-15, Red)
  1632.     for (int i = 9; i <= 15; ++i) {
  1633.         //objectBalls.push_back({ i, BallType::STRIPE, 0, 0, 0, 0, STRIPE_COLOR, false });
  1634.         objectBalls.push_back({ i, BallType::STRIPE, 0,0,0,0,
  1635.                     GetBallColor(i), false });
  1636.     }
  1637.     // 8-Ball (ID 8) - Add it to the list to be placed
  1638.     //objectBalls.push_back({ 8, BallType::EIGHT_BALL, 0, 0, 0, 0, EIGHT_BALL_COLOR, false });
  1639.     objectBalls.push_back({ 8, BallType::EIGHT_BALL, 0,0,0,0,
  1640.           GetBallColor(8), false });
  1641.  
  1642.  
  1643.     // --- Racking Logic (Improved) ---
  1644.     float spacingX = BALL_RADIUS * 2.0f * 0.866f; // cos(30) for horizontal spacing
  1645.     float spacingY = BALL_RADIUS * 2.0f * 1.0f;   // Vertical spacing
  1646.  
  1647.     // Define rack positions (0-14 indices corresponding to triangle spots)
  1648.     D2D1_POINT_2F rackPositions[15];
  1649.     int rackIndex = 0;
  1650.     for (int row = 0; row < 5; ++row) {
  1651.         for (int col = 0; col <= row; ++col) {
  1652.             if (rackIndex >= 15) break;
  1653.             float x = RACK_POS_X + row * spacingX;
  1654.             float y = RACK_POS_Y + (col - row / 2.0f) * spacingY;
  1655.             rackPositions[rackIndex++] = D2D1::Point2F(x, y);
  1656.         }
  1657.     }
  1658.  
  1659.     // Separate 8-ball
  1660.     Ball eightBall;
  1661.     std::vector<Ball> otherBalls; // Solids and Stripes
  1662.     bool eightBallFound = false;
  1663.     for (const auto& ball : objectBalls) {
  1664.         if (ball.id == 8) {
  1665.             eightBall = ball;
  1666.             eightBallFound = true;
  1667.         }
  1668.         else {
  1669.             otherBalls.push_back(ball);
  1670.         }
  1671.     }
  1672.     // Ensure 8 ball was actually created (should always be true)
  1673.     if (!eightBallFound) {
  1674.         // Handle error - perhaps recreate it? For now, proceed.
  1675.         eightBall = { 8, BallType::EIGHT_BALL, 0, 0, 0, 0, EIGHT_BALL_COLOR, false };
  1676.     }
  1677.  
  1678.  
  1679.     // Shuffle the other 14 balls
  1680.     // Use std::shuffle if available (C++11 and later) for better randomness
  1681.     // std::random_device rd;
  1682.     // std::mt19937 g(rd());
  1683.     // std::shuffle(otherBalls.begin(), otherBalls.end(), g);
  1684.     std::random_shuffle(otherBalls.begin(), otherBalls.end()); // Using deprecated for now
  1685.  
  1686.     // --- Place balls into the main 'balls' vector in rack order ---
  1687.     // Important: Add the cue ball (already created) first.
  1688.     // (Cue ball added at the start of the function now)
  1689.  
  1690.     // 1. Place the 8-ball in its fixed position (index 4 for the 3rd row center)
  1691.     int eightBallRackIndex = 4;
  1692.     eightBall.x = rackPositions[eightBallRackIndex].x;
  1693.     eightBall.y = rackPositions[eightBallRackIndex].y;
  1694.     eightBall.vx = 0;
  1695.     eightBall.vy = 0;
  1696.     eightBall.isPocketed = false;
  1697.     balls.push_back(eightBall); // Add 8 ball to the main vector
  1698.  
  1699.     // 2. Place the shuffled Solids and Stripes in the remaining spots
  1700.     size_t otherBallIdx = 0;
  1701.     //int otherBallIdx = 0;
  1702.     for (int i = 0; i < 15; ++i) {
  1703.         if (i == eightBallRackIndex) continue; // Skip the 8-ball spot
  1704.  
  1705.         if (otherBallIdx < otherBalls.size()) {
  1706.             Ball& ballToPlace = otherBalls[otherBallIdx++];
  1707.             ballToPlace.x = rackPositions[i].x;
  1708.             ballToPlace.y = rackPositions[i].y;
  1709.             ballToPlace.vx = 0;
  1710.             ballToPlace.vy = 0;
  1711.             ballToPlace.isPocketed = false;
  1712.             balls.push_back(ballToPlace); // Add to the main game vector
  1713.         }
  1714.     }
  1715.     // --- End Racking Logic ---
  1716.  
  1717.  
  1718.     // --- Determine Who Breaks and Initial State ---
  1719.     if (isPlayer2AI) {
  1720.         /*// AI Mode: Randomly decide who breaks
  1721.         if ((rand() % 2) == 0) {
  1722.             // AI (Player 2) breaks
  1723.             currentPlayer = 2;
  1724.             currentGameState = PRE_BREAK_PLACEMENT; // AI needs to place ball first
  1725.             aiTurnPending = true; // Trigger AI logic
  1726.         }
  1727.         else {
  1728.             // Player 1 (Human) breaks
  1729.             currentPlayer = 1;
  1730.             currentGameState = PRE_BREAK_PLACEMENT; // Human places cue ball
  1731.             aiTurnPending = false;*/
  1732.         switch (openingBreakMode) {
  1733.         case CPU_BREAK:
  1734.             currentPlayer = 2; // AI breaks
  1735.             currentGameState = PRE_BREAK_PLACEMENT;
  1736.             aiTurnPending = true;
  1737.             break;
  1738.         case P1_BREAK:
  1739.             currentPlayer = 1; // Player 1 breaks
  1740.             currentGameState = PRE_BREAK_PLACEMENT;
  1741.             aiTurnPending = false;
  1742.             break;
  1743.         case FLIP_COIN_BREAK:
  1744.             if ((rand() % 2) == 0) { // 0 for AI, 1 for Player 1
  1745.                 currentPlayer = 2; // AI breaks
  1746.                 currentGameState = PRE_BREAK_PLACEMENT;
  1747.                 aiTurnPending = true;
  1748.             }
  1749.             else {
  1750.                 currentPlayer = 1; // Player 1 breaks
  1751.                 currentGameState = PRE_BREAK_PLACEMENT;
  1752.                 aiTurnPending = false;
  1753.             }
  1754.             break;
  1755.         default: // Fallback to CPU break
  1756.             currentPlayer = 2;
  1757.             currentGameState = PRE_BREAK_PLACEMENT;
  1758.             aiTurnPending = true;
  1759.             break;
  1760.         }
  1761.     }
  1762.     else {
  1763.         // Human vs Human, Player 1 always breaks (or could add a flip coin for HvsH too if desired)
  1764.         currentPlayer = 1;
  1765.         currentGameState = PRE_BREAK_PLACEMENT;
  1766.         aiTurnPending = false; // No AI involved
  1767.     }
  1768.  
  1769.     // Reset other relevant game state variables
  1770.     foulCommitted = false;
  1771.     gameOverMessage = L"";
  1772.     firstBallPocketedAfterBreak = false;
  1773.     // pocketedThisTurn cleared at start
  1774.     // Reset shot parameters and input flags
  1775.     shotPower = 0.0f;
  1776.     cueSpinX = 0.0f;
  1777.     cueSpinY = 0.0f;
  1778.     isAiming = false;
  1779.     isDraggingCueBall = false;
  1780.     isSettingEnglish = false;
  1781.     cueAngle = 0.0f; // Reset aim angle
  1782. }
  1783.  
  1784.  
  1785. // --------------------------------------------------------------------------------
  1786. // Full GameUpdate(): integrates AI call?pocket ? aim ? shoot (no omissions)
  1787. // --------------------------------------------------------------------------------
  1788. void GameUpdate() {
  1789.     // --- 1) Handle an in?flight shot ---
  1790.     if (currentGameState == SHOT_IN_PROGRESS) {
  1791.         UpdatePhysics();
  1792.         // ? clear old 8?ball pocket info before any new pocket checks
  1793.         //lastEightBallPocketIndex = -1;
  1794.         CheckCollisions();
  1795.         CheckPockets(); // FIX: This line was missing. It's essential to check for pocketed balls every frame.
  1796.  
  1797.         if (AreBallsMoving()) {
  1798.             isAiming = false;
  1799.             aiIsDisplayingAim = false;
  1800.         }
  1801.  
  1802.         if (!AreBallsMoving()) {
  1803.             ProcessShotResults();
  1804.         }
  1805.         return;
  1806.     }
  1807.  
  1808.     // --- 2) CPU’s turn (table is static) ---
  1809.     if (isPlayer2AI && currentPlayer == 2 && !AreBallsMoving()) {
  1810.         // ??? If we've just auto?entered AI_THINKING for the 8?ball call, actually make the decision ???
  1811.         if (currentGameState == AI_THINKING && aiTurnPending) {
  1812.             aiTurnPending = false;        // consume the pending flag
  1813.             AIMakeDecision();             // CPU calls its pocket or plans its shot
  1814.             return;                       // done this tick
  1815.         }
  1816.  
  1817.         // ??? Automate the AI pocket?selection click ???
  1818.         if (currentGameState == CHOOSING_POCKET_P2) {
  1819.             // AI immediately confirms its call and moves to thinking/shooting
  1820.             currentGameState = AI_THINKING;
  1821.             aiTurnPending = true;
  1822.             return; // process on next tick
  1823.         }
  1824.         // 2A) If AI is displaying its aim line, count down then shoot
  1825.         if (aiIsDisplayingAim) {
  1826.             aiAimDisplayFramesLeft--;
  1827.             if (aiAimDisplayFramesLeft <= 0) {
  1828.                 aiIsDisplayingAim = false;
  1829.                 if (aiPlannedShotDetails.isValid) {
  1830.                     firstHitBallIdThisShot = -1;
  1831.                     cueHitObjectBallThisShot = false;
  1832.                     railHitAfterContact = false;
  1833.                     std::thread([](const TCHAR* soundName) {
  1834.                         PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT);
  1835.                         }, TEXT("cue.wav")).detach();
  1836.  
  1837.                         ApplyShot(
  1838.                             aiPlannedShotDetails.power,
  1839.                             aiPlannedShotDetails.angle,
  1840.                             aiPlannedShotDetails.spinX,
  1841.                             aiPlannedShotDetails.spinY
  1842.                         );
  1843.                         aiPlannedShotDetails.isValid = false;
  1844.                 }
  1845.                 currentGameState = SHOT_IN_PROGRESS;
  1846.                 foulCommitted = false;
  1847.                 pocketedThisTurn.clear();
  1848.             }
  1849.             return;
  1850.         }
  1851.  
  1852.         // 2B) Immediately after calling pocket, transition into AI_THINKING
  1853.         if (currentGameState == CHOOSING_POCKET_P2 && aiTurnPending) {
  1854.             // Start thinking/shooting right away—no human click required
  1855.             currentGameState = AI_THINKING;
  1856.             aiTurnPending = false;
  1857.             AIMakeDecision();
  1858.             return;
  1859.         }
  1860.  
  1861.         // 2C) If AI has pending actions (break, ball?in?hand, or normal turn)
  1862.         if (aiTurnPending) {
  1863.             if (currentGameState == BALL_IN_HAND_P2) {
  1864.                 AIPlaceCueBall();
  1865.                 currentGameState = AI_THINKING;
  1866.                 aiTurnPending = false;
  1867.                 AIMakeDecision();
  1868.             }
  1869.             else if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT) {
  1870.                 AIBreakShot();
  1871.             }
  1872.             else if (currentGameState == PLAYER2_TURN || currentGameState == BREAKING) {
  1873.                 currentGameState = AI_THINKING;
  1874.                 aiTurnPending = false;
  1875.                 AIMakeDecision();
  1876.             }
  1877.             return;
  1878.         }
  1879.     }
  1880. }
  1881.  
  1882.  
  1883. // --- Physics and Collision ---
  1884. void UpdatePhysics() {
  1885.     for (size_t i = 0; i < balls.size(); ++i) {
  1886.         Ball& b = balls[i];
  1887.         if (!b.isPocketed) {
  1888.             b.x += b.vx;
  1889.             b.y += b.vy;
  1890.  
  1891.             // Apply friction
  1892.             b.vx *= FRICTION;
  1893.             b.vy *= FRICTION;
  1894.  
  1895.             // Stop balls if velocity is very low
  1896.             if (GetDistanceSq(b.vx, b.vy, 0, 0) < MIN_VELOCITY_SQ) {
  1897.                 b.vx = 0;
  1898.                 b.vy = 0;
  1899.             }
  1900.  
  1901.             /* -----------------------------------------------------------------
  1902.    Additional clamp to guarantee the ball never escapes the table.
  1903.    The existing wall–collision code can momentarily disable the
  1904.    reflection test while the ball is close to a pocket mouth;
  1905.    that rare case allowed it to ‘slide’ through the cushion and
  1906.    leave the board.  We therefore enforce a final boundary check
  1907.    after the normal physics step.
  1908.    ----------------------------------------------------------------- */
  1909.             const float leftBound = TABLE_LEFT + BALL_RADIUS;
  1910.             const float rightBound = TABLE_RIGHT - BALL_RADIUS;
  1911.             const float topBound = TABLE_TOP + BALL_RADIUS;
  1912.             const float bottomBound = TABLE_BOTTOM - BALL_RADIUS;
  1913.  
  1914.             if (b.x < leftBound) { b.x = leftBound;   b.vx = fabsf(b.vx); }
  1915.             if (b.x > rightBound) { b.x = rightBound;  b.vx = -fabsf(b.vx); }
  1916.             if (b.y < topBound) { b.y = topBound;    b.vy = fabsf(b.vy); }
  1917.             if (b.y > bottomBound) { b.y = bottomBound; b.vy = -fabsf(b.vy); }
  1918.         }
  1919.     }
  1920. }
  1921.  
  1922. void CheckCollisions() {
  1923.     float left = TABLE_LEFT;
  1924.     float right = TABLE_RIGHT;
  1925.     float top = TABLE_TOP;
  1926.     float bottom = TABLE_BOTTOM;
  1927.     const float pocketMouthCheckRadiusSq = (POCKET_RADIUS + BALL_RADIUS) * (POCKET_RADIUS + BALL_RADIUS) * 1.1f;
  1928.  
  1929.     // --- Reset Per-Frame Sound Flags ---
  1930.     bool playedWallSoundThisFrame = false;
  1931.     bool playedCollideSoundThisFrame = false;
  1932.     // ---
  1933.  
  1934.     for (size_t i = 0; i < balls.size(); ++i) {
  1935.         Ball& b1 = balls[i];
  1936.         if (b1.isPocketed) continue;
  1937.  
  1938.         bool nearPocket[6];
  1939.         for (int p = 0; p < 6; ++p) {
  1940.             nearPocket[p] = GetDistanceSq(b1.x, b1.y, pocketPositions[p].x, pocketPositions[p].y) < pocketMouthCheckRadiusSq;
  1941.         }
  1942.         bool nearTopLeftPocket = nearPocket[0];
  1943.         bool nearTopMidPocket = nearPocket[1];
  1944.         bool nearTopRightPocket = nearPocket[2];
  1945.         bool nearBottomLeftPocket = nearPocket[3];
  1946.         bool nearBottomMidPocket = nearPocket[4];
  1947.         bool nearBottomRightPocket = nearPocket[5];
  1948.  
  1949.         bool collidedWallThisBall = false;
  1950.  
  1951.         // --- Ball-Wall Collisions ---
  1952.         // (Check logic unchanged, added sound calls and railHitAfterContact update)
  1953.         // Left Wall
  1954.         if (b1.x - BALL_RADIUS < left) {
  1955.             if (!nearTopLeftPocket && !nearBottomLeftPocket) {
  1956.                 b1.x = left + BALL_RADIUS; b1.vx *= -1.0f; collidedWallThisBall = true;
  1957.                 if (!playedWallSoundThisFrame) {
  1958.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  1959.                     playedWallSoundThisFrame = true;
  1960.                 }
  1961.                 if (cueHitObjectBallThisShot) railHitAfterContact = true; // Track rail hit after contact
  1962.             }
  1963.         }
  1964.         // Right Wall
  1965.         if (b1.x + BALL_RADIUS > right) {
  1966.             if (!nearTopRightPocket && !nearBottomRightPocket) {
  1967.                 b1.x = right - BALL_RADIUS; b1.vx *= -1.0f; collidedWallThisBall = true;
  1968.                 if (!playedWallSoundThisFrame) {
  1969.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  1970.                     playedWallSoundThisFrame = true;
  1971.                 }
  1972.                 if (cueHitObjectBallThisShot) railHitAfterContact = true; // Track rail hit after contact
  1973.             }
  1974.         }
  1975.         // Top Wall
  1976.         if (b1.y - BALL_RADIUS < top) {
  1977.             if (!nearTopLeftPocket && !nearTopMidPocket && !nearTopRightPocket) {
  1978.                 b1.y = top + BALL_RADIUS; b1.vy *= -1.0f; collidedWallThisBall = true;
  1979.                 if (!playedWallSoundThisFrame) {
  1980.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  1981.                     playedWallSoundThisFrame = true;
  1982.                 }
  1983.                 if (cueHitObjectBallThisShot) railHitAfterContact = true; // Track rail hit after contact
  1984.             }
  1985.         }
  1986.         // Bottom Wall
  1987.         if (b1.y + BALL_RADIUS > bottom) {
  1988.             if (!nearBottomLeftPocket && !nearBottomMidPocket && !nearBottomRightPocket) {
  1989.                 b1.y = bottom - BALL_RADIUS; b1.vy *= -1.0f; collidedWallThisBall = true;
  1990.                 if (!playedWallSoundThisFrame) {
  1991.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  1992.                     playedWallSoundThisFrame = true;
  1993.                 }
  1994.                 if (cueHitObjectBallThisShot) railHitAfterContact = true; // Track rail hit after contact
  1995.             }
  1996.         }
  1997.  
  1998.         // Spin effect (Unchanged)
  1999.         if (collidedWallThisBall) {
  2000.             if (b1.x <= left + BALL_RADIUS || b1.x >= right - BALL_RADIUS) { b1.vy += cueSpinX * b1.vx * 0.05f; }
  2001.             if (b1.y <= top + BALL_RADIUS || b1.y >= bottom - BALL_RADIUS) { b1.vx -= cueSpinY * b1.vy * 0.05f; }
  2002.             cueSpinX *= 0.7f; cueSpinY *= 0.7f;
  2003.         }
  2004.  
  2005.  
  2006.         // --- Ball-Ball Collisions ---
  2007.         for (size_t j = i + 1; j < balls.size(); ++j) {
  2008.             Ball& b2 = balls[j];
  2009.             if (b2.isPocketed) continue;
  2010.  
  2011.             float dx = b2.x - b1.x; float dy = b2.y - b1.y;
  2012.             float distSq = dx * dx + dy * dy;
  2013.             float minDist = BALL_RADIUS * 2.0f;
  2014.  
  2015.             if (distSq > 1e-6 && distSq < minDist * minDist) {
  2016.                 float dist = sqrtf(distSq);
  2017.                 float overlap = minDist - dist;
  2018.                 float nx = dx / dist; float ny = dy / dist;
  2019.  
  2020.                 // Separation (Unchanged)
  2021.                 b1.x -= overlap * 0.5f * nx; b1.y -= overlap * 0.5f * ny;
  2022.                 b2.x += overlap * 0.5f * nx; b2.y += overlap * 0.5f * ny;
  2023.  
  2024.                 float rvx = b1.vx - b2.vx; float rvy = b1.vy - b2.vy;
  2025.                 float velAlongNormal = rvx * nx + rvy * ny;
  2026.  
  2027.                 if (velAlongNormal > 0) { // Colliding
  2028.                     // --- Play Ball Collision Sound ---
  2029.                     if (!playedCollideSoundThisFrame) {
  2030.                         std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("poolballhit.wav")).detach();
  2031.                         playedCollideSoundThisFrame = true; // Set flag
  2032.                     }
  2033.                     // --- End Sound ---
  2034.  
  2035.                     // --- NEW: Track First Hit and Cue/Object Collision ---
  2036.                     if (firstHitBallIdThisShot == -1) { // If first hit hasn't been recorded yet
  2037.                         if (b1.id == 0) { // Cue ball hit b2 first
  2038.                             firstHitBallIdThisShot = b2.id;
  2039.                             cueHitObjectBallThisShot = true;
  2040.                         }
  2041.                         else if (b2.id == 0) { // Cue ball hit b1 first
  2042.                             firstHitBallIdThisShot = b1.id;
  2043.                             cueHitObjectBallThisShot = true;
  2044.                         }
  2045.                         // If neither is cue ball, doesn't count as first hit for foul purposes
  2046.                     }
  2047.                     else if (b1.id == 0 || b2.id == 0) {
  2048.                         // Track subsequent cue ball collisions with object balls
  2049.                         cueHitObjectBallThisShot = true;
  2050.                     }
  2051.                     // --- End First Hit Tracking ---
  2052.  
  2053.  
  2054.                     // Impulse (Unchanged)
  2055.                     float impulse = velAlongNormal;
  2056.                     b1.vx -= impulse * nx; b1.vy -= impulse * ny;
  2057.                     b2.vx += impulse * nx; b2.vy += impulse * ny;
  2058.  
  2059.                     // Spin Transfer (Unchanged)
  2060.                     if (b1.id == 0 || b2.id == 0) {
  2061.                         float spinEffectFactor = 0.08f;
  2062.                         b1.vx += (cueSpinY * ny - cueSpinX * nx) * spinEffectFactor;
  2063.                         b1.vy += (cueSpinY * nx + cueSpinX * ny) * spinEffectFactor;
  2064.                         b2.vx -= (cueSpinY * ny - cueSpinX * nx) * spinEffectFactor;
  2065.                         b2.vy -= (cueSpinY * nx + cueSpinX * ny) * spinEffectFactor;
  2066.                         cueSpinX *= 0.85f; cueSpinY *= 0.85f;
  2067.                     }
  2068.                 }
  2069.             }
  2070.         } // End ball-ball loop
  2071.     } // End ball loop
  2072. } // End CheckCollisions
  2073.  
  2074.  
  2075. bool CheckPockets() {
  2076.     bool anyPocketed = false;
  2077.     bool ballPocketedThisCheck = false;
  2078.  
  2079.     // For each ball not already pocketed:
  2080.     for (auto& b : balls) {
  2081.         if (b.isPocketed) continue;
  2082.  
  2083.         // Test against each of the 6 pockets
  2084.         for (int p = 0; p < 6; ++p) {
  2085.             // Half‐circle check for true black‐hole sink
  2086.             D2D1_POINT_2F center = pocketPositions[p];
  2087.             float dx = b.x - center.x;
  2088.             float dy = b.y - center.y;
  2089.             bool isInPocket = false;
  2090.  
  2091.             if (p == 1) {
  2092.                 // Top‐middle: only the half of the circle _inside_ the table (y >= center.y)
  2093.                 if (dy >= 0 && dx * dx + dy * dy <= HOLE_VISUAL_RADIUS * HOLE_VISUAL_RADIUS)
  2094.                     isInPocket = true;
  2095.             }
  2096.             else if (p == 4) {
  2097.                 // Bottom‐middle: only the half _inside_ the table (y <= center.y)
  2098.                 if (dy <= 0 && dx * dx + dy * dy <= HOLE_VISUAL_RADIUS * HOLE_VISUAL_RADIUS)
  2099.                     isInPocket = true;
  2100.             }
  2101.             else {
  2102.                 // Corner pockets: full circles
  2103.                 if (dx * dx + dy * dy <= HOLE_VISUAL_RADIUS * HOLE_VISUAL_RADIUS)
  2104.                     isInPocket = true;
  2105.             }
  2106.  
  2107.             // 3) If it qualifies, sink it
  2108.             if (isInPocket) {
  2109.                 if (b.id == 8) {
  2110.                     lastEightBallPocketIndex = p;   // remember 8-ball’s pocket
  2111.                 }
  2112.                 b.isPocketed = true;
  2113.                 b.vx = b.vy = 0.0f;
  2114.                 pocketedThisTurn.push_back(b.id);
  2115.                 anyPocketed = true;
  2116.  
  2117.                 // play sound just once per check
  2118.                 if (!ballPocketedThisCheck) {
  2119.                     std::thread([](const TCHAR* soundName) {
  2120.                         PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT);
  2121.                         }, TEXT("pocket.wav")).detach();
  2122.                         ballPocketedThisCheck = true;
  2123.                 }
  2124.                 break;  // drop this ball and move on to the next
  2125.             }
  2126.         }
  2127.     }
  2128.  
  2129.     return anyPocketed;
  2130. }
  2131.  
  2132.  
  2133. bool AreBallsMoving() {
  2134.     for (size_t i = 0; i < balls.size(); ++i) {
  2135.         if (!balls[i].isPocketed && (balls[i].vx != 0 || balls[i].vy != 0)) {
  2136.             return true;
  2137.         }
  2138.     }
  2139.     return false;
  2140. }
  2141.  
  2142. void RespawnCueBall(bool behindHeadstring) {
  2143.     Ball* cueBall = GetCueBall();
  2144.     if (cueBall) {
  2145.         // Determine the initial target position
  2146.         float targetX, targetY;
  2147.         if (behindHeadstring) {
  2148.             targetX = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f;
  2149.             targetY = TABLE_TOP + TABLE_HEIGHT / 2.0f;
  2150.         }
  2151.         else {
  2152.             targetX = TABLE_LEFT + TABLE_WIDTH / 2.0f;
  2153.             targetY = TABLE_TOP + TABLE_HEIGHT / 2.0f;
  2154.         }
  2155.  
  2156.         // FOOLPROOF FIX: Check if the target spot is valid. If not, nudge it until it is.
  2157.         int attempts = 0;
  2158.         while (!IsValidCueBallPosition(targetX, targetY, behindHeadstring) && attempts < 100) {
  2159.             // If the spot is occupied, try nudging the ball slightly.
  2160.             targetX += (static_cast<float>(rand() % 100 - 50) / 50.0f) * BALL_RADIUS;
  2161.             targetY += (static_cast<float>(rand() % 100 - 50) / 50.0f) * BALL_RADIUS;
  2162.             // Clamp to stay within reasonable bounds
  2163.             targetX = std::max(TABLE_LEFT + BALL_RADIUS, std::min(targetX, TABLE_RIGHT - BALL_RADIUS));
  2164.             targetY = std::max(TABLE_TOP + BALL_RADIUS, std::min(targetY, TABLE_BOTTOM - BALL_RADIUS));
  2165.             attempts++;
  2166.         }
  2167.  
  2168.         // Set the final, valid position.
  2169.         cueBall->x = targetX;
  2170.         cueBall->y = targetY;
  2171.         cueBall->vx = 0;
  2172.         cueBall->vy = 0;
  2173.         cueBall->isPocketed = false;
  2174.  
  2175.         // Set the correct game state for ball-in-hand.
  2176.         if (currentPlayer == 1) {
  2177.             currentGameState = BALL_IN_HAND_P1;
  2178.             aiTurnPending = false;
  2179.         }
  2180.         else {
  2181.             currentGameState = BALL_IN_HAND_P2;
  2182.             if (isPlayer2AI) {
  2183.                 aiTurnPending = true;
  2184.             }
  2185.         }
  2186.     }
  2187. }
  2188.  
  2189.  
  2190. // --- Game Logic ---
  2191.  
  2192. void ApplyShot(float power, float angle, float spinX, float spinY) {
  2193.     Ball* cueBall = GetCueBall();
  2194.     if (cueBall) {
  2195.  
  2196.         // --- Play Cue Strike Sound (Threaded) ---
  2197.         if (power > 0.1f) { // Only play if it's an audible shot
  2198.             std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
  2199.         }
  2200.         // --- End Sound ---
  2201.  
  2202.         cueBall->vx = cosf(angle) * power;
  2203.         cueBall->vy = sinf(angle) * power;
  2204.  
  2205.         // Apply English (Spin) - Simplified effect (Unchanged)
  2206.         cueBall->vx += sinf(angle) * spinY * 0.5f;
  2207.         cueBall->vy -= cosf(angle) * spinY * 0.5f;
  2208.         cueBall->vx -= cosf(angle) * spinX * 0.5f;
  2209.         cueBall->vy -= sinf(angle) * spinX * 0.5f;
  2210.  
  2211.         // Store spin (Unchanged)
  2212.         cueSpinX = spinX;
  2213.         cueSpinY = spinY;
  2214.  
  2215.         // --- Reset Foul Tracking flags for the new shot ---
  2216.         // (Also reset in LBUTTONUP, but good to ensure here too)
  2217.         firstHitBallIdThisShot = -1;      // No ball hit yet
  2218.         cueHitObjectBallThisShot = false; // Cue hasn't hit anything yet
  2219.         railHitAfterContact = false;     // No rail hit after contact yet
  2220.         // --- End Reset ---
  2221.  
  2222.                 // If this was the opening break shot, clear the flag
  2223.         if (isOpeningBreakShot) {
  2224.             isOpeningBreakShot = false; // Mark opening break as taken
  2225.         }
  2226.     }
  2227. }
  2228.  
  2229.  
  2230. // ---------------------------------------------------------------------
  2231. //  ProcessShotResults()
  2232. // ---------------------------------------------------------------------
  2233. void ProcessShotResults() {
  2234.     bool cueBallPocketed = false;
  2235.     bool eightBallPocketed = false;
  2236.     bool playerContinuesTurn = false;
  2237.  
  2238.     // --- Step 1: Update Ball Counts FIRST (THE CRITICAL FIX) ---
  2239.     // We must update the score before any other game logic runs.
  2240.     PlayerInfo& shootingPlayer = (currentPlayer == 1) ? player1Info : player2Info;
  2241.     int ownBallsPocketedThisTurn = 0;
  2242.  
  2243.     for (int id : pocketedThisTurn) {
  2244.         Ball* b = GetBallById(id);
  2245.         if (!b) continue;
  2246.  
  2247.         if (b->id == 0) {
  2248.             cueBallPocketed = true;
  2249.         }
  2250.         else if (b->id == 8) {
  2251.             eightBallPocketed = true;
  2252.         }
  2253.         else {
  2254.             // This is a numbered ball. Update the pocketed count for the correct player.
  2255.             if (b->type == player1Info.assignedType && player1Info.assignedType != BallType::NONE) {
  2256.                 player1Info.ballsPocketedCount++;
  2257.             }
  2258.             else if (b->type == player2Info.assignedType && player2Info.assignedType != BallType::NONE) {
  2259.                 player2Info.ballsPocketedCount++;
  2260.             }
  2261.  
  2262.             if (b->type == shootingPlayer.assignedType) {
  2263.                 ownBallsPocketedThisTurn++;
  2264.             }
  2265.         }
  2266.     }
  2267.  
  2268.     if (ownBallsPocketedThisTurn > 0) {
  2269.         playerContinuesTurn = true;
  2270.     }
  2271.  
  2272.     // --- Step 2: Handle Game-Ending 8-Ball Shot ---
  2273.     // Now that the score is updated, this check will have the correct information.
  2274.     if (eightBallPocketed) {
  2275.         CheckGameOverConditions(true, cueBallPocketed);
  2276.         if (currentGameState == GAME_OVER) {
  2277.             pocketedThisTurn.clear();
  2278.             return;
  2279.         }
  2280.     }
  2281.  
  2282.     // --- Step 3: Check for Fouls ---
  2283.     bool turnFoul = false;
  2284.     if (cueBallPocketed) {
  2285.         turnFoul = true;
  2286.     }
  2287.     else {
  2288.         Ball* firstHit = GetBallById(firstHitBallIdThisShot);
  2289.         if (!firstHit) { // Rule: Hitting nothing is a foul.
  2290.             turnFoul = true;
  2291.         }
  2292.         else { // Rule: Hitting the wrong ball type is a foul.
  2293.             if (player1Info.assignedType != BallType::NONE) { // Colors are assigned.
  2294.                 // We check if the player WAS on the 8-ball BEFORE this shot.
  2295.                 bool wasOnEightBall = (shootingPlayer.assignedType != BallType::NONE && (shootingPlayer.ballsPocketedCount - ownBallsPocketedThisTurn) >= 7);
  2296.                 if (wasOnEightBall) {
  2297.                     if (firstHit->id != 8) turnFoul = true;
  2298.                 }
  2299.                 else {
  2300.                     if (firstHit->type != shootingPlayer.assignedType) turnFoul = true;
  2301.                 }
  2302.             }
  2303.         }
  2304.     } //reenable below disabled for debugging
  2305.     //if (!turnFoul && cueHitObjectBallThisShot && !railHitAfterContact && pocketedThisTurn.empty()) {
  2306.         //turnFoul = true;
  2307.     //}
  2308.     foulCommitted = turnFoul;
  2309.  
  2310.     // --- Step 4: Final State Transition ---
  2311.     if (foulCommitted) {
  2312.         SwitchTurns();
  2313.         RespawnCueBall(false);
  2314.     }
  2315.     else if (player1Info.assignedType == BallType::NONE && !pocketedThisTurn.empty() && !cueBallPocketed) {
  2316.         // Assign types on the break.
  2317.         for (int id : pocketedThisTurn) {
  2318.             Ball* b = GetBallById(id);
  2319.             if (b && b->type != BallType::EIGHT_BALL) {
  2320.                 AssignPlayerBallTypes(b->type);
  2321.                 break;
  2322.             }
  2323.         }
  2324.         CheckAndTransitionToPocketChoice(currentPlayer);
  2325.     }
  2326.     else if (playerContinuesTurn) {
  2327.         // The player's turn continues. Now the check will work correctly.
  2328.         CheckAndTransitionToPocketChoice(currentPlayer);
  2329.     }
  2330.     else {
  2331.         SwitchTurns();
  2332.     }
  2333.  
  2334.     pocketedThisTurn.clear();
  2335. }
  2336.  
  2337. /*
  2338. // --- Step 3: Final State Transition ---
  2339. if (foulCommitted) {
  2340.     SwitchTurns();
  2341.     RespawnCueBall(false);
  2342. }
  2343. else if (playerContinuesTurn) {
  2344.     CheckAndTransitionToPocketChoice(currentPlayer);
  2345. }
  2346. else {
  2347.     SwitchTurns();
  2348. }
  2349.  
  2350. pocketedThisTurn.clear();
  2351. } */
  2352.  
  2353. //  Assign groups AND optionally give the shooter his first count.
  2354. bool AssignPlayerBallTypes(BallType firstPocketedType, bool creditShooter /*= true*/)
  2355. {
  2356.     if (firstPocketedType != SOLID && firstPocketedType != STRIPE)
  2357.         return false;                                 // safety
  2358.  
  2359.     /* ---------------------------------------------------------
  2360.        1.  Decide the groups
  2361.     --------------------------------------------------------- */
  2362.     if (currentPlayer == 1)
  2363.     {
  2364.         player1Info.assignedType = firstPocketedType;
  2365.         player2Info.assignedType =
  2366.             (firstPocketedType == SOLID) ? STRIPE : SOLID;
  2367.     }
  2368.     else
  2369.     {
  2370.         player2Info.assignedType = firstPocketedType;
  2371.         player1Info.assignedType =
  2372.             (firstPocketedType == SOLID) ? STRIPE : SOLID;
  2373.     }
  2374.  
  2375.     /* ---------------------------------------------------------
  2376.        2.  Count the very ball that made the assignment
  2377.     --------------------------------------------------------- */
  2378.     if (creditShooter)
  2379.     {
  2380.         if (currentPlayer == 1)
  2381.             ++player1Info.ballsPocketedCount;
  2382.         else
  2383.             ++player2Info.ballsPocketedCount;
  2384.     }
  2385.     return true;
  2386. }
  2387.  
  2388. /*bool AssignPlayerBallTypes(BallType firstPocketedType) {
  2389.     if (firstPocketedType == BallType::SOLID || firstPocketedType == BallType::STRIPE) {
  2390.         if (currentPlayer == 1) {
  2391.             player1Info.assignedType = firstPocketedType;
  2392.             player2Info.assignedType = (firstPocketedType == BallType::SOLID) ? BallType::STRIPE : BallType::SOLID;
  2393.         }
  2394.         else {
  2395.             player2Info.assignedType = firstPocketedType;
  2396.             player1Info.assignedType = (firstPocketedType == BallType::SOLID) ? BallType::STRIPE : BallType::SOLID;
  2397.         }
  2398.         return true; // Assignment was successful
  2399.     }
  2400.     return false; // No assignment made (e.g., 8-ball was pocketed on break)
  2401. }*/
  2402. // If 8-ball was first (illegal on break generally), rules vary.
  2403. // Here, we might ignore assignment until a solid/stripe is pocketed legally.
  2404. // Or assign based on what *else* was pocketed, if anything.
  2405. // Simplification: Assignment only happens on SOLID or STRIPE first pocket.
  2406.  
  2407.  
  2408. // --- Called in ProcessShotResults() after pocket detection ---
  2409. void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed)
  2410. {
  2411.     // Only care if the 8?ball really went in:
  2412.     if (!eightBallPocketed) return;
  2413.  
  2414.     // Who’s shooting now?
  2415.     PlayerInfo& shooter = (currentPlayer == 1) ? player1Info : player2Info;
  2416.     PlayerInfo& opponent = (currentPlayer == 1) ? player2Info : player1Info;
  2417.  
  2418.     // Which pocket did we CALL?
  2419.     int called = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  2420.     // Which pocket did it ACTUALLY fall into?
  2421.     int actual = lastEightBallPocketIndex;
  2422.  
  2423.     // Check legality: must have called a pocket ?0, must match actual,
  2424.     // must have pocketed all 7 of your balls first, and must not have scratched.
  2425.     bool legal = (called >= 0)
  2426.         && (called == actual)
  2427.         && (shooter.ballsPocketedCount >= 7)
  2428.         && (!cueBallPocketed);
  2429.  
  2430.     // Build a message that shows both values for debugging/tracing:
  2431.     if (legal) {
  2432.         gameOverMessage = shooter.name
  2433.             + L" Wins! "
  2434.             + L"(Called: " + std::to_wstring(called)
  2435.             + L", Actual: " + std::to_wstring(actual) + L")";
  2436.     }
  2437.     else {
  2438.         gameOverMessage = opponent.name
  2439.             + L" Wins! (Illegal 8-Ball) "
  2440.             + L"(Called: " + std::to_wstring(called)
  2441.             + L", Actual: " + std::to_wstring(actual) + L")";
  2442.     }
  2443.  
  2444.     currentGameState = GAME_OVER;
  2445. }
  2446.  
  2447.  
  2448.  
  2449. /*void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed) {
  2450.     if (!eightBallPocketed) return;
  2451.  
  2452.     PlayerInfo& shootingPlayer = (currentPlayer == 1) ? player1Info : player2Info;
  2453.     PlayerInfo& opponentPlayer = (currentPlayer == 1) ? player2Info : player1Info;
  2454.  
  2455.     // Handle 8-ball on break: re-spot and continue.
  2456.     if (player1Info.assignedType == BallType::NONE) {
  2457.         Ball* b = GetBallById(8);
  2458.         if (b) { b->isPocketed = false; b->x = RACK_POS_X; b->y = RACK_POS_Y; b->vx = b->vy = 0; }
  2459.         if (cueBallPocketed) foulCommitted = true;
  2460.         return;
  2461.     }
  2462.  
  2463.     // --- FOOLPROOF WIN/LOSS LOGIC ---
  2464.     bool wasOnEightBall = IsPlayerOnEightBall(currentPlayer);
  2465.     int calledPocket = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  2466.     int actualPocket = -1;
  2467.  
  2468.     // Find which pocket the 8-ball actually went into.
  2469.     for (int id : pocketedThisTurn) {
  2470.         if (id == 8) {
  2471.             Ball* b = GetBallById(8); // This ball is already marked as pocketed, but we need its last coords.
  2472.             if (b) {
  2473.                 for (int p_idx = 0; p_idx < 6; ++p_idx) {
  2474.                     // Check last known position against pocket centers
  2475.                     if (GetDistanceSq(b->x, b->y, pocketPositions[p_idx].x, pocketPositions[p_idx].y) < POCKET_RADIUS * POCKET_RADIUS * 1.5f) {
  2476.                         actualPocket = p_idx;
  2477.                         break;
  2478.                     }
  2479.                 }
  2480.             }
  2481.             break;
  2482.         }
  2483.     }
  2484.  
  2485.     // Evaluate win/loss based on a clear hierarchy of rules.
  2486.     if (!wasOnEightBall) {
  2487.         gameOverMessage = opponentPlayer.name + L" Wins! (8-Ball Pocketed Early)";
  2488.     }
  2489.     else if (cueBallPocketed) {
  2490.         gameOverMessage = opponentPlayer.name + L" Wins! (Scratched on 8-Ball)";
  2491.     }
  2492.     else if (calledPocket == -1) {
  2493.         gameOverMessage = opponentPlayer.name + L" Wins! (Pocket Not Called)";
  2494.     }
  2495.     else if (actualPocket != calledPocket) {
  2496.         gameOverMessage = opponentPlayer.name + L" Wins! (8-Ball in Wrong Pocket)";
  2497.     }
  2498.     else {
  2499.         // WIN! All loss conditions failed, this must be a legal win.
  2500.         gameOverMessage = shootingPlayer.name + L" Wins!";
  2501.     }
  2502.  
  2503.     currentGameState = GAME_OVER;
  2504. }*/
  2505.  
  2506. /*void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed)
  2507. {
  2508.     if (!eightBallPocketed) return;
  2509.  
  2510.     PlayerInfo& shooter = (currentPlayer == 1) ? player1Info : player2Info;
  2511.     PlayerInfo& opponent = (currentPlayer == 1) ? player2Info : player1Info;
  2512.     // Which pocket did we call?
  2513.     int called = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  2514.     // Which pocket did the ball really fall into?
  2515.     int actual = lastEightBallPocketIndex;
  2516.  
  2517.     // Legal victory only if:
  2518.     //  1) Shooter had already pocketed 7 of their object balls,
  2519.     //  2) They called a pocket,
  2520.     //  3) The 8?ball actually fell into that same pocket,
  2521.     //  4) They did not scratch on the 8?ball.
  2522.     bool legal =
  2523.         (shooter.ballsPocketedCount >= 7) &&
  2524.         (called >= 0) &&
  2525.         (called == actual) &&
  2526.         (!cueBallPocketed);
  2527.  
  2528.     if (legal) {
  2529.         gameOverMessage = shooter.name + L" Wins! "
  2530.             L"(called: " + std::to_wstring(called) +
  2531.             L", actual: " + std::to_wstring(actual) + L")";
  2532.     }
  2533.     else {
  2534.         gameOverMessage = opponent.name + L" Wins! (illegal 8-ball) "
  2535.         // For debugging you can append:
  2536.         + L" (called: " + std::to_wstring(called)
  2537.         + L", actual: " + std::to_wstring(actual) + L")";
  2538.     }
  2539.  
  2540.     currentGameState = GAME_OVER;
  2541. }*/
  2542.  
  2543. // ????????????????????????????????????????????????????????????????
  2544. //  CheckGameOverConditions()
  2545. //     – Called when the 8-ball has fallen.
  2546. //     – Decides who wins and builds the gameOverMessage.
  2547. // ????????????????????????????????????????????????????????????????
  2548. /*void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed)
  2549. {
  2550.     if (!eightBallPocketed) return;                     // safety
  2551.  
  2552.     PlayerInfo& shooter = (currentPlayer == 1) ? player1Info : player2Info;
  2553.     PlayerInfo& opponent = (currentPlayer == 1) ? player2Info : player1Info;
  2554.  
  2555.     int calledPocket = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  2556.     int actualPocket = lastEightBallPocketIndex;
  2557.  
  2558.     bool clearedSeven = (shooter.ballsPocketedCount >= 7);
  2559.     bool noScratch = !cueBallPocketed;
  2560.     bool callMade = (calledPocket >= 0);
  2561.  
  2562.     // helper ? turn “-1” into "None" for readability
  2563.     auto pocketToStr = [](int idx) -> std::wstring
  2564.     {
  2565.         return (idx >= 0) ? std::to_wstring(idx) : L"None";
  2566.     };
  2567.  
  2568.     if (clearedSeven && noScratch && callMade && actualPocket == calledPocket)
  2569.     {
  2570.         // legitimate win
  2571.         gameOverMessage =
  2572.             shooter.name +
  2573.             L" Wins! (Called pocket: " + pocketToStr(calledPocket) +
  2574.             L", Actual pocket: " + pocketToStr(actualPocket) + L")";
  2575.     }
  2576.     else
  2577.     {
  2578.         // wrong pocket, scratch, or early 8-ball
  2579.         gameOverMessage =
  2580.             opponent.name +
  2581.             L" Wins! (Called pocket: " + pocketToStr(calledPocket) +
  2582.             L", Actual pocket: " + pocketToStr(actualPocket) + L")";
  2583.     }
  2584.  
  2585.     currentGameState = GAME_OVER;
  2586. }*/
  2587.  
  2588. /* void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed) {
  2589.     if (!eightBallPocketed) return; // Only when 8-ball actually pocketed
  2590.  
  2591.     PlayerInfo& shooter = (currentPlayer == 1) ? player1Info : player2Info;
  2592.     PlayerInfo& opponent = (currentPlayer == 1) ? player2Info : player1Info;
  2593.     bool      onEightRoll = IsPlayerOnEightBall(currentPlayer);
  2594.     int       calledPocket = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  2595.     int       actualPocket = -1;
  2596.     Ball* bEight = GetBallById(8);
  2597.  
  2598.     // locate which hole the 8-ball went into
  2599.     if (bEight) {
  2600.         for (int i = 0; i < 6; ++i) {
  2601.             if (GetDistanceSq(bEight->x, bEight->y,
  2602.                 pocketPositions[i].x, pocketPositions[i].y)
  2603.                 < POCKET_RADIUS * POCKET_RADIUS * 1.5f) {
  2604.                 actualPocket = i; break;
  2605.             }
  2606.         }
  2607.     }
  2608.  
  2609.     // 1) On break / pre-assignment: re-spot & continue
  2610.     if (player1Info.assignedType == BallType::NONE) {
  2611.         if (bEight) {
  2612.             bEight->isPocketed = false;
  2613.             bEight->x = RACK_POS_X; bEight->y = RACK_POS_Y;
  2614.             bEight->vx = bEight->vy = 0;
  2615.         }
  2616.         if (cueBallPocketed) foulCommitted = true;
  2617.         return;
  2618.     }
  2619.  
  2620.     // 2) Loss if pocketed 8 early
  2621.     if (!onEightRoll) {
  2622.         gameOverMessage = opponent.name + L" Wins! (" + shooter.name + L" pocketed 8-ball early)";
  2623.     }
  2624.     // 3) Loss if scratched
  2625.     else if (cueBallPocketed) {
  2626.         gameOverMessage = opponent.name + L" Wins! (" + shooter.name + L" scratched on 8-ball)";
  2627.     }
  2628.     // 4) Loss if no pocket call
  2629.     else if (calledPocket < 0) {
  2630.         gameOverMessage = opponent.name + L" Wins! (" + shooter.name + L" did not call a pocket)";
  2631.     }
  2632.     // 5) Loss if in wrong pocket
  2633.     else if (actualPocket != calledPocket) {
  2634.         gameOverMessage = opponent.name + L" Wins! (" + shooter.name + L" 8-ball in wrong pocket)";
  2635.     }
  2636.     // 6) Otherwise, valid win
  2637.     else {
  2638.         gameOverMessage = shooter.name + L" Wins!";
  2639.     }
  2640.  
  2641.     currentGameState = GAME_OVER;
  2642. } */
  2643.  
  2644.  
  2645. // Switch the shooter, handle fouls and decide what state we go to next.
  2646. // ────────────────────────────────────────────────────────────────
  2647. //  SwitchTurns – final version (arrow–leak bug fixed)
  2648. // ────────────────────────────────────────────────────────────────
  2649. void SwitchTurns()
  2650. {
  2651.     /* --------------------------------------------------------- */
  2652.     /* 1.  Hand the table over to the other player               */
  2653.     /* --------------------------------------------------------- */
  2654.     currentPlayer = (currentPlayer == 1) ? 2 : 1;
  2655.  
  2656.     /* --------------------------------------------------------- */
  2657.     /* 2.  Generic per–turn resets                               */
  2658.     /* --------------------------------------------------------- */
  2659.     isAiming = false;
  2660.     shotPower = 0.0f;
  2661.     currentlyHoveredPocket = -1;
  2662.  
  2663.     /* --------------------------------------------------------- */
  2664.     /* 3.  Wipe every previous pocket call                       */
  2665.     /*    (the new shooter will choose again if needed)          */
  2666.     /* --------------------------------------------------------- */
  2667.     calledPocketP1 = -1;
  2668.     calledPocketP2 = -1;
  2669.     pocketCallMessage.clear();
  2670.  
  2671.     /* --------------------------------------------------------- */
  2672.     /* 4.  Handle fouls — cue-ball in hand overrides everything  */
  2673.     /* --------------------------------------------------------- */
  2674.     if (foulCommitted)
  2675.     {
  2676.         if (currentPlayer == 1)            // human
  2677.         {
  2678.             currentGameState = BALL_IN_HAND_P1;
  2679.             aiTurnPending = false;
  2680.         }
  2681.         else                               // P2
  2682.         {
  2683.             currentGameState = BALL_IN_HAND_P2;
  2684.             aiTurnPending = isPlayer2AI;   // AI will place cue-ball
  2685.         }
  2686.  
  2687.         foulCommitted = false;
  2688.         return;                            // we're done for this frame
  2689.     }
  2690.  
  2691.     /* --------------------------------------------------------- */
  2692.     /* 5.  Normal flow                                           */
  2693.     /*    Will put us in  ∘ PLAYER?_TURN                         */
  2694.     /*                    ∘ CHOOSING_POCKET_P?                   */
  2695.     /*                    ∘ AI_THINKING  (for CPU)               */
  2696.     /* --------------------------------------------------------- */
  2697.     CheckAndTransitionToPocketChoice(currentPlayer);
  2698. }
  2699.  
  2700.  
  2701. void AIBreakShot() {
  2702.     Ball* cueBall = GetCueBall();
  2703.     if (!cueBall) return;
  2704.  
  2705.     // This function is called when it's AI's turn for the opening break and state is PRE_BREAK_PLACEMENT.
  2706.     // AI will place the cue ball and then plan the shot.
  2707.     if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT) {
  2708.         // Place cue ball in the kitchen randomly
  2709.         /*float kitchenMinX = TABLE_LEFT + BALL_RADIUS; // [cite: 1071, 1072, 1587]
  2710.         float kitchenMaxX = HEADSTRING_X - BALL_RADIUS; // [cite: 1072, 1078, 1588]
  2711.         float kitchenMinY = TABLE_TOP + BALL_RADIUS; // [cite: 1071, 1072, 1588]
  2712.         float kitchenMaxY = TABLE_BOTTOM - BALL_RADIUS; // [cite: 1072, 1073, 1589]*/
  2713.  
  2714.         // --- AI Places Cue Ball for Break ---
  2715. // Decide if placing center or side. For simplicity, let's try placing slightly off-center
  2716. // towards one side for a more angled break, or center for direct apex hit.
  2717. // A common strategy is to hit the second ball of the rack.
  2718.  
  2719.         float placementY = RACK_POS_Y; // Align vertically with the rack center
  2720.         float placementX;
  2721.  
  2722.         // Randomly choose a side or center-ish placement for variation.
  2723.         int placementChoice = rand() % 3; // 0: Left-ish, 1: Center-ish, 2: Right-ish in kitchen
  2724.  
  2725.         if (placementChoice == 0) { // Left-ish
  2726.             placementX = HEADSTRING_X - (TABLE_WIDTH * 0.05f) - (BALL_RADIUS * (1 + (rand() % 3))); // Place slightly to the left within kitchen
  2727.         }
  2728.         else if (placementChoice == 2) { // Right-ish
  2729.             placementX = HEADSTRING_X - (TABLE_WIDTH * 0.05f) + (BALL_RADIUS * (1 + (rand() % 3))); // Place slightly to the right within kitchen
  2730.         }
  2731.         else { // Center-ish
  2732.             placementX = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f; // Roughly center of kitchen
  2733.         }
  2734.         placementX = std::max(TABLE_LEFT + BALL_RADIUS + 1.0f, std::min(placementX, HEADSTRING_X - BALL_RADIUS - 1.0f)); // Clamp within kitchen X
  2735.  
  2736.         bool validPos = false;
  2737.         int attempts = 0;
  2738.         while (!validPos && attempts < 100) {
  2739.             /*cueBall->x = kitchenMinX + static_cast<float>(rand()) / (static_cast<float>(RAND_MAX) / (kitchenMaxX - kitchenMinX)); // [cite: 1589]
  2740.             cueBall->y = kitchenMinY + static_cast<float>(rand()) / (static_cast<float>(RAND_MAX) / (kitchenMaxY - kitchenMinY)); // [cite: 1590]
  2741.             if (IsValidCueBallPosition(cueBall->x, cueBall->y, true)) { // [cite: 1591]
  2742.                 validPos = true; // [cite: 1591]*/
  2743.                 // Try the chosen X, but vary Y slightly to find a clear spot
  2744.             cueBall->x = placementX;
  2745.             cueBall->y = placementY + (static_cast<float>(rand() % 100 - 50) / 100.0f) * BALL_RADIUS * 2.0f; // Vary Y a bit
  2746.             cueBall->y = std::max(TABLE_TOP + BALL_RADIUS + 1.0f, std::min(cueBall->y, TABLE_BOTTOM - BALL_RADIUS - 1.0f)); // Clamp Y
  2747.  
  2748.             if (IsValidCueBallPosition(cueBall->x, cueBall->y, true /* behind headstring */)) {
  2749.                 validPos = true;
  2750.             }
  2751.             attempts++; // [cite: 1592]
  2752.         }
  2753.         if (!validPos) {
  2754.             // Fallback position
  2755.             /*cueBall->x = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f; // [cite: 1071, 1078, 1593]
  2756.             cueBall->y = (TABLE_TOP + TABLE_BOTTOM) * 0.5f; // [cite: 1071, 1073, 1594]
  2757.             if (!IsValidCueBallPosition(cueBall->x, cueBall->y, true)) { // [cite: 1594]
  2758.                 cueBall->x = HEADSTRING_X - BALL_RADIUS * 2; // [cite: 1072, 1078, 1594]
  2759.                 cueBall->y = RACK_POS_Y; // [cite: 1080, 1595]
  2760.             }
  2761.         }
  2762.         cueBall->vx = 0; // [cite: 1595]
  2763.         cueBall->vy = 0; // [cite: 1596]
  2764.  
  2765.         // Plan a break shot: aim at the center of the rack (apex ball)
  2766.         float targetX = RACK_POS_X; // [cite: 1079] Aim for the apex ball X-coordinate
  2767.         float targetY = RACK_POS_Y; // [cite: 1080] Aim for the apex ball Y-coordinate
  2768.  
  2769.         float dx = targetX - cueBall->x; // [cite: 1599]
  2770.         float dy = targetY - cueBall->y; // [cite: 1600]
  2771.         float shotAngle = atan2f(dy, dx); // [cite: 1600]
  2772.         float shotPowerValue = MAX_SHOT_POWER; // [cite: 1076, 1600] Use MAX_SHOT_POWER*/
  2773.  
  2774.             cueBall->x = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.75f; // A default safe spot in kitchen
  2775.             cueBall->y = RACK_POS_Y;
  2776.         }
  2777.         cueBall->vx = 0; cueBall->vy = 0;
  2778.  
  2779.         // --- AI Plans the Break Shot ---
  2780.         float targetX, targetY;
  2781.         // If cue ball is near center of kitchen width, aim for apex.
  2782.         // Otherwise, aim for the second ball on the side the cue ball is on (for a cut break).
  2783.         float kitchenCenterRegion = (HEADSTRING_X - TABLE_LEFT) * 0.3f; // Define a "center" region
  2784.         if (std::abs(cueBall->x - (TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) / 2.0f)) < kitchenCenterRegion / 2.0f) {
  2785.             // Center-ish placement: Aim for the apex ball (ball ID 1 or first ball in rack)
  2786.             targetX = RACK_POS_X; // Apex ball X
  2787.             targetY = RACK_POS_Y; // Apex ball Y
  2788.         }
  2789.         else {
  2790.             // Side placement: Aim to hit the "second" ball of the rack for a wider spread.
  2791.             // This is a simplification. A more robust way is to find the actual second ball.
  2792.             // For now, aim slightly off the apex towards the side the cue ball is on.
  2793.             targetX = RACK_POS_X + BALL_RADIUS * 2.0f * 0.866f; // X of the second row of balls
  2794.             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
  2795.         }
  2796.  
  2797.         float dx = targetX - cueBall->x;
  2798.         float dy = targetY - cueBall->y;
  2799.         float shotAngle = atan2f(dy, dx);
  2800.         float shotPowerValue = MAX_SHOT_POWER * (0.9f + (rand() % 11) / 100.0f); // Slightly vary max power
  2801.  
  2802.         // Store planned shot details for the AI
  2803.         /*aiPlannedShotDetails.angle = shotAngle; // [cite: 1102, 1601]
  2804.         aiPlannedShotDetails.power = shotPowerValue; // [cite: 1102, 1601]
  2805.         aiPlannedShotDetails.spinX = 0.0f; // [cite: 1102, 1601] No spin for a standard power break
  2806.         aiPlannedShotDetails.spinY = 0.0f; // [cite: 1103, 1602]
  2807.         aiPlannedShotDetails.isValid = true; // [cite: 1103, 1602]*/
  2808.  
  2809.         aiPlannedShotDetails.angle = shotAngle;
  2810.         aiPlannedShotDetails.power = shotPowerValue;
  2811.         aiPlannedShotDetails.spinX = 0.0f; // No spin for break usually
  2812.         aiPlannedShotDetails.spinY = 0.0f;
  2813.         aiPlannedShotDetails.isValid = true;
  2814.  
  2815.         // Update global cue parameters for immediate visual feedback if DrawAimingAids uses them
  2816.         /*::cueAngle = aiPlannedShotDetails.angle;      // [cite: 1109, 1603] Update global cueAngle
  2817.         ::shotPower = aiPlannedShotDetails.power;     // [cite: 1109, 1604] Update global shotPower
  2818.         ::cueSpinX = aiPlannedShotDetails.spinX;    // [cite: 1109]
  2819.         ::cueSpinY = aiPlannedShotDetails.spinY;    // [cite: 1110]*/
  2820.  
  2821.         ::cueAngle = aiPlannedShotDetails.angle;
  2822.         ::shotPower = aiPlannedShotDetails.power;
  2823.         ::cueSpinX = aiPlannedShotDetails.spinX;
  2824.         ::cueSpinY = aiPlannedShotDetails.spinY;
  2825.  
  2826.         // Set up for AI display via GameUpdate
  2827.         /*aiIsDisplayingAim = true;                   // [cite: 1104] Enable AI aiming visualization
  2828.         aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES; // [cite: 1105] Set duration for display
  2829.  
  2830.         currentGameState = AI_THINKING; // [cite: 1081] Transition to AI_THINKING state.
  2831.                                         // GameUpdate will handle the aiAimDisplayFramesLeft countdown
  2832.                                         // and then execute the shot using aiPlannedShotDetails.
  2833.                                         // isOpeningBreakShot will be set to false within ApplyShot.
  2834.  
  2835.         // No immediate ApplyShot or sound here; GameUpdate's AI execution logic will handle it.*/
  2836.  
  2837.         aiIsDisplayingAim = true;
  2838.         aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES;
  2839.         currentGameState = AI_THINKING; // State changes to AI_THINKING, GameUpdate will handle shot execution after display
  2840.         aiTurnPending = false;
  2841.  
  2842.         return; // The break shot is now planned and will be executed by GameUpdate
  2843.     }
  2844.  
  2845.     // 2. If not in PRE_BREAK_PLACEMENT (e.g., if this function were called at other times,
  2846.     //    though current game logic only calls it for PRE_BREAK_PLACEMENT)
  2847.     //    This part can be extended if AIBreakShot needs to handle other scenarios.
  2848.     //    For now, the primary logic is above.
  2849. }
  2850.  
  2851. // --- Helper Functions ---
  2852.  
  2853. Ball* GetBallById(int id) {
  2854.     for (size_t i = 0; i < balls.size(); ++i) {
  2855.         if (balls[i].id == id) {
  2856.             return &balls[i];
  2857.         }
  2858.     }
  2859.     return nullptr;
  2860. }
  2861.  
  2862. Ball* GetCueBall() {
  2863.     return GetBallById(0);
  2864. }
  2865.  
  2866. float GetDistance(float x1, float y1, float x2, float y2) {
  2867.     return sqrtf(GetDistanceSq(x1, y1, x2, y2));
  2868. }
  2869.  
  2870. float GetDistanceSq(float x1, float y1, float x2, float y2) {
  2871.     float dx = x2 - x1;
  2872.     float dy = y2 - y1;
  2873.     return dx * dx + dy * dy;
  2874. }
  2875.  
  2876. bool IsValidCueBallPosition(float x, float y, bool checkHeadstring) {
  2877.     // Basic bounds check (inside cushions)
  2878.     float left = TABLE_LEFT + CUSHION_THICKNESS + BALL_RADIUS;
  2879.     float right = TABLE_RIGHT - CUSHION_THICKNESS - BALL_RADIUS;
  2880.     float top = TABLE_TOP + CUSHION_THICKNESS + BALL_RADIUS;
  2881.     float bottom = TABLE_BOTTOM - CUSHION_THICKNESS - BALL_RADIUS;
  2882.  
  2883.     if (x < left || x > right || y < top || y > bottom) {
  2884.         return false;
  2885.     }
  2886.  
  2887.     // Check headstring restriction if needed
  2888.     if (checkHeadstring && x >= HEADSTRING_X) {
  2889.         return false;
  2890.     }
  2891.  
  2892.     // Check overlap with other balls
  2893.     for (size_t i = 0; i < balls.size(); ++i) {
  2894.         if (balls[i].id != 0 && !balls[i].isPocketed) { // Don't check against itself or pocketed balls
  2895.             if (GetDistanceSq(x, y, balls[i].x, balls[i].y) < (BALL_RADIUS * 2.0f) * (BALL_RADIUS * 2.0f)) {
  2896.                 return false; // Overlapping another ball
  2897.             }
  2898.         }
  2899.     }
  2900.  
  2901.     return true;
  2902. }
  2903.  
  2904. // --- NEW HELPER FUNCTION IMPLEMENTATIONS ---
  2905.  
  2906. // Checks if a player has pocketed all their balls and is now on the 8-ball.
  2907. bool IsPlayerOnEightBall(int player) {
  2908.     PlayerInfo& playerInfo = (player == 1) ? player1Info : player2Info;
  2909.     if (playerInfo.assignedType != BallType::NONE && playerInfo.assignedType != BallType::EIGHT_BALL && playerInfo.ballsPocketedCount >= 7) {
  2910.         Ball* eightBall = GetBallById(8);
  2911.         return (eightBall && !eightBall->isPocketed);
  2912.     }
  2913.     return false;
  2914. }
  2915.  
  2916. void CheckAndTransitionToPocketChoice(int playerID) {
  2917.     bool needsToCall = IsPlayerOnEightBall(playerID);
  2918.  
  2919.     if (needsToCall) {
  2920.         if (playerID == 1) { // Human Player 1
  2921.             currentGameState = CHOOSING_POCKET_P1;
  2922.             pocketCallMessage = player1Info.name + L": Choose a pocket for the 8-Ball...";
  2923.             if (calledPocketP1 == -1) calledPocketP1 = 2; // Default to bottom-right
  2924.         }
  2925.         else { // Player 2
  2926.             if (isPlayer2AI) {
  2927.                 // FOOLPROOF FIX: AI doesn't choose here. It transitions to a thinking state.
  2928.                 // AIMakeDecision will handle the choice and the pocket call.
  2929.                 currentGameState = AI_THINKING;
  2930.                 aiTurnPending = true; // Signal the main loop to run AIMakeDecision
  2931.             }
  2932.             else { // Human Player 2
  2933.                 currentGameState = CHOOSING_POCKET_P2;
  2934.                 pocketCallMessage = player2Info.name + L": Choose a pocket for the 8-Ball...";
  2935.                 if (calledPocketP2 == -1) calledPocketP2 = 2; // Default to bottom-right
  2936.             }
  2937.         }
  2938.     }
  2939.     else {
  2940.         // Player does not need to call a pocket, proceed to normal turn.
  2941.         pocketCallMessage = L"";
  2942.         currentGameState = (playerID == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  2943.         if (playerID == 2 && isPlayer2AI) {
  2944.             aiTurnPending = true;
  2945.         }
  2946.     }
  2947. }
  2948.  
  2949.  
  2950. template <typename T>
  2951. void SafeRelease(T** ppT) {
  2952.     if (*ppT) {
  2953.         (*ppT)->Release();
  2954.         *ppT = nullptr;
  2955.     }
  2956. }
  2957.  
  2958. // --- CPU Ball?in?Hand Placement --------------------------------
  2959. // Moves the cue ball to a legal "ball in hand" position for the AI.
  2960. void AIPlaceCueBall() {
  2961.     Ball* cue = GetCueBall();
  2962.     if (!cue) return;
  2963.  
  2964.     // Simple strategy: place back behind the headstring at the standard break spot
  2965.     cue->x = TABLE_LEFT + TABLE_WIDTH * 0.15f;
  2966.     cue->y = RACK_POS_Y;
  2967.     cue->vx = cue->vy = 0.0f;
  2968. }
  2969.  
  2970. // --- Helper Function for Line Segment Intersection ---
  2971. // Finds intersection point of line segment P1->P2 and line segment P3->P4
  2972. // Returns true if they intersect, false otherwise. Stores intersection point in 'intersection'.
  2973. bool LineSegmentIntersection(D2D1_POINT_2F p1, D2D1_POINT_2F p2, D2D1_POINT_2F p3, D2D1_POINT_2F p4, D2D1_POINT_2F& intersection)
  2974. {
  2975.     float denominator = (p4.y - p3.y) * (p2.x - p1.x) - (p4.x - p3.x) * (p2.y - p1.y);
  2976.  
  2977.     // Check if lines are parallel or collinear
  2978.     if (fabs(denominator) < 1e-6) {
  2979.         return false;
  2980.     }
  2981.  
  2982.     float ua = ((p4.x - p3.x) * (p1.y - p3.y) - (p4.y - p3.y) * (p1.x - p3.x)) / denominator;
  2983.     float ub = ((p2.x - p1.x) * (p1.y - p3.y) - (p2.y - p1.y) * (p1.x - p3.x)) / denominator;
  2984.  
  2985.     // Check if intersection point lies on both segments
  2986.     if (ua >= 0.0f && ua <= 1.0f && ub >= 0.0f && ub <= 1.0f) {
  2987.         intersection.x = p1.x + ua * (p2.x - p1.x);
  2988.         intersection.y = p1.y + ua * (p2.y - p1.y);
  2989.         return true;
  2990.     }
  2991.  
  2992.     return false;
  2993. }
  2994.  
  2995. // --- INSERT NEW HELPER FUNCTION HERE ---
  2996. // Calculates the squared distance from point P to the line segment AB.
  2997. float PointToLineSegmentDistanceSq(D2D1_POINT_2F p, D2D1_POINT_2F a, D2D1_POINT_2F b) {
  2998.     float l2 = GetDistanceSq(a.x, a.y, b.x, b.y);
  2999.     if (l2 == 0.0f) return GetDistanceSq(p.x, p.y, a.x, a.y); // Segment is a point
  3000.     // Consider P projecting onto the line AB infinite line
  3001.     // t = [(P-A) . (B-A)] / |B-A|^2
  3002.     float t = ((p.x - a.x) * (b.x - a.x) + (p.y - a.y) * (b.y - a.y)) / l2;
  3003.     t = std::max(0.0f, std::min(1.0f, t)); // Clamp t to the segment [0, 1]
  3004.     // Projection falls on the segment
  3005.     D2D1_POINT_2F projection = D2D1::Point2F(a.x + t * (b.x - a.x), a.y + t * (b.y - a.y));
  3006.     return GetDistanceSq(p.x, p.y, projection.x, projection.y);
  3007. }
  3008. // --- End New Helper ---
  3009.  
  3010. // --- NEW AI Implementation Functions ---
  3011.  
  3012. void AIMakeDecision() {
  3013.     // Start with a clean slate for the AI's plan.
  3014.     aiPlannedShotDetails.isValid = false;
  3015.     Ball* cueBall = GetCueBall();
  3016.     if (!cueBall || !isPlayer2AI || currentPlayer != 2) return;
  3017.  
  3018.     // Ask the "expert" (AIFindBestShot) for the best possible shot.
  3019.     AIShotInfo bestShot = AIFindBestShot();
  3020.  
  3021.     if (bestShot.possible) {
  3022.         // A good shot was found.
  3023.         // If it's an 8-ball shot, "call" the pocket.
  3024.         if (bestShot.involves8Ball) {
  3025.             calledPocketP2 = bestShot.pocketIndex;
  3026.         }
  3027.         else {
  3028.             calledPocketP2 = -1; // Ensure no pocket is called on a normal shot.
  3029.         }
  3030.  
  3031.         // Commit the details of the best shot to the AI's plan.
  3032.         aiPlannedShotDetails.angle = bestShot.angle;
  3033.         aiPlannedShotDetails.power = bestShot.power;
  3034.         aiPlannedShotDetails.spinX = bestShot.spinX;
  3035.         aiPlannedShotDetails.spinY = bestShot.spinY;
  3036.         aiPlannedShotDetails.isValid = true;
  3037.  
  3038.     }
  3039.     else {
  3040.         // No good offensive shot found, must play a safe defensive shot.
  3041.         // (This is a fallback and your current AIFindBestShot should prevent this)
  3042.         aiPlannedShotDetails.isValid = false;
  3043.     }
  3044.  
  3045.     // --- FOOLPROOF FIX: Trigger the Aim Display ---
  3046.     // If any valid plan was made, update the visuals and start the display pause.
  3047.     if (aiPlannedShotDetails.isValid) {
  3048.  
  3049.         // STEP 1: Copy the AI's plan into the global variables used for drawing.
  3050.         // This is the critical missing link.
  3051.         cueAngle = aiPlannedShotDetails.angle;
  3052.         shotPower = aiPlannedShotDetails.power;
  3053.  
  3054.         // STEP 2: Trigger the visual display pause.
  3055.         // These are the two lines you correctly identified.
  3056.         aiIsDisplayingAim = true;
  3057.         aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES;
  3058.  
  3059.     }
  3060.     else {
  3061.         // Absolute fallback: If no plan could be made, switch turns to prevent a freeze.
  3062.         SwitchTurns();
  3063.     }
  3064. }
  3065.  
  3066.  
  3067. AIShotInfo AIFindBestShot()
  3068. {
  3069.     AIShotInfo best;                       // .possible == false
  3070.     Ball* cue = GetCueBall();
  3071.     if (!cue) return best;
  3072.  
  3073.     const bool on8 = IsPlayerOnEightBall(2);
  3074.     const BallType wantType = player2Info.assignedType;
  3075.  
  3076.     for (Ball& b : balls)
  3077.     {
  3078.         if (b.isPocketed || b.id == 0) continue;
  3079.  
  3080.         // decide if this ball is a legal/interesting target
  3081.         bool ok =
  3082.             on8 ? (b.id == 8) :
  3083.             ((wantType == BallType::NONE) || (b.type == wantType));
  3084.  
  3085.         if (!ok) continue;
  3086.  
  3087.         for (int p = 0; p < 6; ++p)
  3088.         {
  3089.             AIShotInfo cand = EvaluateShot(&b, p);
  3090.             if (cand.possible &&
  3091.                 (!best.possible || cand.score > best.score))
  3092.                 best = cand;
  3093.         }
  3094.     }
  3095.  
  3096.     // fall-back: tap cue ball forward (safety) if no potting line exists
  3097.     if (!best.possible && cue)
  3098.     {
  3099.         best.possible = true;
  3100.         best.angle = static_cast<float>(rand()) / RAND_MAX * 2.0f * PI;
  3101.         best.power = MAX_SHOT_POWER * 0.30f;
  3102.         best.spinX = best.spinY = 0.0f;
  3103.         best.targetBall = nullptr;
  3104.         best.score = -99999.0f;
  3105.         best.pocketIndex = -1;
  3106.     }
  3107.     return best;
  3108. }
  3109.  
  3110.  
  3111. // Evaluate a potential shot at a specific target ball towards a specific pocket
  3112. AIShotInfo EvaluateShot(Ball* targetBall, int pocketIndex) {
  3113.     AIShotInfo shotInfo; // Defaults to not possible
  3114.     shotInfo.targetBall = targetBall;
  3115.     shotInfo.pocketIndex = pocketIndex;
  3116.     shotInfo.involves8Ball = (targetBall && targetBall->id == 8);
  3117.  
  3118.     Ball* cueBall = GetCueBall();
  3119.     if (!cueBall || !targetBall) return shotInfo;
  3120.  
  3121.     // 1. Calculate Ghost Ball position (where cue must hit target)
  3122.     shotInfo.ghostBallPos = CalculateGhostBallPos(targetBall, pocketIndex);
  3123.  
  3124.     // 2. Check Path: Cue Ball -> Ghost Ball Position
  3125.     if (!IsPathClear(D2D1::Point2F(cueBall->x, cueBall->y), shotInfo.ghostBallPos, cueBall->id, targetBall->id)) {
  3126.         return shotInfo; // Path blocked, shot is impossible.
  3127.     }
  3128.  
  3129.     // 3. Calculate Angle and Power
  3130.     float dx = shotInfo.ghostBallPos.x - cueBall->x;
  3131.     float dy = shotInfo.ghostBallPos.y - cueBall->y;
  3132.     shotInfo.angle = atan2f(dy, dx);
  3133.  
  3134.     float cueToGhostDist = GetDistance(cueBall->x, cueBall->y, shotInfo.ghostBallPos.x, shotInfo.ghostBallPos.y);
  3135.     float targetToPocketDist = GetDistance(targetBall->x, targetBall->y, pocketPositions[pocketIndex].x, pocketPositions[pocketIndex].y);
  3136.     shotInfo.power = CalculateShotPower(cueToGhostDist, targetToPocketDist);
  3137.  
  3138.     // 4. Score the shot (simple scoring: closer and straighter is better)
  3139.     shotInfo.score = 1000.0f - (cueToGhostDist + targetToPocketDist);
  3140.  
  3141.     // If we reached here, the shot is geometrically possible.
  3142.     shotInfo.possible = true;
  3143.     return shotInfo;
  3144. }
  3145.  
  3146.  
  3147. //  Estimate the power that will carry the cue-ball to the ghost position
  3148. //  *and* push the object-ball the remaining distance to the pocket.
  3149. //
  3150. //  • cueToGhostDist    – pixels from cue to ghost-ball centre
  3151. //  • targetToPocketDist– pixels from object-ball to chosen pocket
  3152. //
  3153. //  The function is fully deterministic (good for AI search) yet produces
  3154. //  human-looking power levels.
  3155. //
  3156. float CalculateShotPower(float cueToGhostDist, float targetToPocketDist)
  3157. {
  3158.     // Total distance the *energy* must cover (cue path + object-ball path)
  3159.     float totalDist = cueToGhostDist + targetToPocketDist;
  3160.  
  3161.     // Typical diagonal of the playable area (approx.) – used for scaling
  3162.     constexpr float TABLE_DIAG = 900.0f;
  3163.  
  3164.     // 1.  Convert distance to a 0-1 number (0: tap-in, 1: table length)
  3165.     float norm = std::clamp(totalDist / TABLE_DIAG, 0.0f, 1.0f);
  3166.  
  3167.     // 2.  Ease-in curve (smoothstep) for nicer progression
  3168.     norm = norm * norm * (3.0f - 2.0f * norm);
  3169.  
  3170.     // 3.  Blend between a gentle minimum and the absolute maximum
  3171.     const float MIN_POWER = MAX_SHOT_POWER * 0.18f;     // just enough to move
  3172.     float power = MIN_POWER + norm * (MAX_SHOT_POWER - MIN_POWER);
  3173.  
  3174.     // 4.  Safety clamp (also screens out degenerate calls)
  3175.     power = std::clamp(power, 0.15f, MAX_SHOT_POWER);
  3176.  
  3177.     return power;
  3178. }
  3179.  
  3180. // ------------------------------------------------------------------
  3181. //  Return the ghost-ball centre needed for the target ball to roll
  3182. //  straight into the chosen pocket.
  3183. // ------------------------------------------------------------------
  3184. D2D1_POINT_2F CalculateGhostBallPos(Ball* targetBall, int pocketIndex)
  3185. {
  3186.     if (!targetBall) return D2D1::Point2F(0, 0);
  3187.  
  3188.     D2D1_POINT_2F P = pocketPositions[pocketIndex];
  3189.  
  3190.     float vx = P.x - targetBall->x;
  3191.     float vy = P.y - targetBall->y;
  3192.     float L = sqrtf(vx * vx + vy * vy);
  3193.     if (L < 1.0f) L = 1.0f;                // safety
  3194.  
  3195.     vx /= L;   vy /= L;
  3196.  
  3197.     return D2D1::Point2F(
  3198.         targetBall->x - vx * (BALL_RADIUS * 2.0f),
  3199.         targetBall->y - vy * (BALL_RADIUS * 2.0f));
  3200. }
  3201.  
  3202. // Calculate the position the cue ball needs to hit for the target ball to go towards the pocket
  3203. // ────────────────────────────────────────────────────────────────
  3204. //   2.  Shot evaluation & search
  3205. // ────────────────────────────────────────────────────────────────
  3206.  
  3207. //  Calculate ghost-ball position so that cue hits target towards pocket
  3208. static inline D2D1_POINT_2F GhostPos(const Ball* tgt, int pocketIdx)
  3209. {
  3210.     D2D1_POINT_2F P = pocketPositions[pocketIdx];
  3211.     float vx = P.x - tgt->x;
  3212.     float vy = P.y - tgt->y;
  3213.     float L = sqrtf(vx * vx + vy * vy);
  3214.     vx /= L;  vy /= L;
  3215.     return D2D1::Point2F(tgt->x - vx * (BALL_RADIUS * 2.0f),
  3216.         tgt->y - vy * (BALL_RADIUS * 2.0f));
  3217. }
  3218.  
  3219. //  Heuristic: shorter + straighter + proper group = higher score
  3220. static inline float ScoreShot(float cue2Ghost,
  3221.     float tgt2Pocket,
  3222.     bool  correctGroup,
  3223.     bool  involves8)
  3224. {
  3225.     float base = 2000.0f - (cue2Ghost + tgt2Pocket);   // prefer close shots
  3226.     if (!correctGroup)  base -= 400.0f;                  // penalty
  3227.     if (involves8)      base += 150.0f;                  // a bit more desirable
  3228.     return base;
  3229. }
  3230.  
  3231. // Checks if line segment is clear of obstructing balls
  3232. // ────────────────────────────────────────────────────────────────
  3233. //   1.  Low-level helpers – IsPathClear & FindFirstHitBall
  3234. // ────────────────────────────────────────────────────────────────
  3235.  
  3236. //  Test if the capsule [ start … end ] (radius = BALL_RADIUS)
  3237. //  intersects any ball except the ids we want to ignore.
  3238. bool IsPathClear(D2D1_POINT_2F start,
  3239.     D2D1_POINT_2F end,
  3240.     int ignoredBallId1,
  3241.     int ignoredBallId2)
  3242. {
  3243.     float dx = end.x - start.x;
  3244.     float dy = end.y - start.y;
  3245.     float lenSq = dx * dx + dy * dy;
  3246.     if (lenSq < 1e-3f) return true;             // degenerate → treat as clear
  3247.  
  3248.     for (const Ball& b : balls)
  3249.     {
  3250.         if (b.isPocketed)      continue;
  3251.         if (b.id == ignoredBallId1 ||
  3252.             b.id == ignoredBallId2)             continue;
  3253.  
  3254.         // project ball centre onto the segment
  3255.         float t = ((b.x - start.x) * dx + (b.y - start.y) * dy) / lenSq;
  3256.         t = std::clamp(t, 0.0f, 1.0f);
  3257.  
  3258.         float cx = start.x + t * dx;
  3259.         float cy = start.y + t * dy;
  3260.  
  3261.         if (GetDistanceSq(b.x, b.y, cx, cy) < (BALL_RADIUS * BALL_RADIUS))
  3262.             return false;                       // blocked
  3263.     }
  3264.     return true;
  3265. }
  3266.  
  3267. //  Cast an (infinite) ray and return the first non-pocketed ball hit.
  3268. //  `hitDistSq` is distance² from the start point to the collision point.
  3269. Ball* FindFirstHitBall(D2D1_POINT_2F start,
  3270.     float        angle,
  3271.     float& hitDistSq)
  3272. {
  3273.     Ball* hitBall = nullptr;
  3274.     float  bestSq = std::numeric_limits<float>::max();
  3275.     float  cosA = cosf(angle);
  3276.     float  sinA = sinf(angle);
  3277.  
  3278.     for (Ball& b : balls)
  3279.     {
  3280.         if (b.id == 0 || b.isPocketed) continue;         // ignore cue & sunk balls
  3281.  
  3282.         float relX = b.x - start.x;
  3283.         float relY = b.y - start.y;
  3284.         float proj = relX * cosA + relY * sinA;          // distance along the ray
  3285.  
  3286.         if (proj <= 0) continue;                         // behind cue
  3287.  
  3288.         // closest approach of the ray to the sphere centre
  3289.         float closestX = start.x + proj * cosA;
  3290.         float closestY = start.y + proj * sinA;
  3291.         float dSq = GetDistanceSq(b.x, b.y, closestX, closestY);
  3292.  
  3293.         if (dSq <= BALL_RADIUS * BALL_RADIUS)            // intersection
  3294.         {
  3295.             float back = sqrtf(BALL_RADIUS * BALL_RADIUS - dSq);
  3296.             float collDist = proj - back;                // front surface
  3297.             float collSq = collDist * collDist;
  3298.             if (collSq < bestSq)
  3299.             {
  3300.                 bestSq = collSq;
  3301.                 hitBall = &b;
  3302.             }
  3303.         }
  3304.     }
  3305.     hitDistSq = bestSq;
  3306.     return hitBall;
  3307. }
  3308.  
  3309. // Basic check for reasonable AI aim angles (optional)
  3310. bool IsValidAIAimAngle(float angle) {
  3311.     // Placeholder - could check for NaN or infinity if calculations go wrong
  3312.     return isfinite(angle);
  3313. }
  3314.  
  3315. //midi func = start
  3316. void PlayMidiInBackground(HWND hwnd, const TCHAR* midiPath) {
  3317.     while (isMusicPlaying) {
  3318.         MCI_OPEN_PARMS mciOpen = { 0 };
  3319.         mciOpen.lpstrDeviceType = TEXT("sequencer");
  3320.         mciOpen.lpstrElementName = midiPath;
  3321.  
  3322.         if (mciSendCommand(0, MCI_OPEN, MCI_OPEN_TYPE | MCI_OPEN_ELEMENT, (DWORD_PTR)&mciOpen) == 0) {
  3323.             midiDeviceID = mciOpen.wDeviceID;
  3324.  
  3325.             MCI_PLAY_PARMS mciPlay = { 0 };
  3326.             mciSendCommand(midiDeviceID, MCI_PLAY, 0, (DWORD_PTR)&mciPlay);
  3327.  
  3328.             // Wait for playback to complete
  3329.             MCI_STATUS_PARMS mciStatus = { 0 };
  3330.             mciStatus.dwItem = MCI_STATUS_MODE;
  3331.  
  3332.             do {
  3333.                 mciSendCommand(midiDeviceID, MCI_STATUS, MCI_STATUS_ITEM, (DWORD_PTR)&mciStatus);
  3334.                 Sleep(100); // adjust as needed
  3335.             } while (mciStatus.dwReturn == MCI_MODE_PLAY && isMusicPlaying);
  3336.  
  3337.             mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
  3338.             midiDeviceID = 0;
  3339.         }
  3340.     }
  3341. }
  3342.  
  3343. void StartMidi(HWND hwnd, const TCHAR* midiPath) {
  3344.     if (isMusicPlaying) {
  3345.         StopMidi();
  3346.     }
  3347.     isMusicPlaying = true;
  3348.     musicThread = std::thread(PlayMidiInBackground, hwnd, midiPath);
  3349. }
  3350.  
  3351. void StopMidi() {
  3352.     if (isMusicPlaying) {
  3353.         isMusicPlaying = false;
  3354.         if (musicThread.joinable()) musicThread.join();
  3355.         if (midiDeviceID != 0) {
  3356.             mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
  3357.             midiDeviceID = 0;
  3358.         }
  3359.     }
  3360. }
  3361.  
  3362. /*void PlayGameMusic(HWND hwnd) {
  3363.     // Stop any existing playback
  3364.     if (isMusicPlaying) {
  3365.         isMusicPlaying = false;
  3366.         if (musicThread.joinable()) {
  3367.             musicThread.join();
  3368.         }
  3369.         if (midiDeviceID != 0) {
  3370.             mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
  3371.             midiDeviceID = 0;
  3372.         }
  3373.     }
  3374.  
  3375.     // Get the path of the executable
  3376.     TCHAR exePath[MAX_PATH];
  3377.     GetModuleFileName(NULL, exePath, MAX_PATH);
  3378.  
  3379.     // Extract the directory path
  3380.     TCHAR* lastBackslash = _tcsrchr(exePath, '\\');
  3381.     if (lastBackslash != NULL) {
  3382.         *(lastBackslash + 1) = '\0';
  3383.     }
  3384.  
  3385.     // Construct the full path to the MIDI file
  3386.     static TCHAR midiPath[MAX_PATH];
  3387.     _tcscpy_s(midiPath, MAX_PATH, exePath);
  3388.     _tcscat_s(midiPath, MAX_PATH, TEXT("BSQ.MID"));
  3389.  
  3390.     // Start the background playback
  3391.     isMusicPlaying = true;
  3392.     musicThread = std::thread(PlayMidiInBackground, hwnd, midiPath);
  3393. }*/
  3394. //midi func = end
  3395.  
  3396. // --- Drawing Functions ---
  3397.  
  3398. void OnPaint() {
  3399.     HRESULT hr = CreateDeviceResources(); // Ensure resources are valid
  3400.  
  3401.     if (SUCCEEDED(hr)) {
  3402.         pRenderTarget->BeginDraw();
  3403.         DrawScene(pRenderTarget); // Pass render target
  3404.         hr = pRenderTarget->EndDraw();
  3405.  
  3406.         if (hr == D2DERR_RECREATE_TARGET) {
  3407.             DiscardDeviceResources();
  3408.             // Optionally request another paint message: InvalidateRect(hwndMain, NULL, FALSE);
  3409.             // But the timer loop will trigger redraw anyway.
  3410.         }
  3411.     }
  3412.     // If CreateDeviceResources failed, EndDraw might not be called.
  3413.     // Consider handling this more robustly if needed.
  3414. }
  3415.  
  3416. void DrawScene(ID2D1RenderTarget* pRT) {
  3417.     if (!pRT) return;
  3418.  
  3419.     //pRT->Clear(D2D1::ColorF(D2D1::ColorF::LightGray)); // Background color
  3420.     // Set background color to #ffffcd (RGB: 255, 255, 205)
  3421.     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)
  3422.     //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)
  3423.  
  3424.     DrawTable(pRT, pFactory);
  3425.     DrawPocketSelectionIndicator(pRT); // Draw arrow over selected/called pocket
  3426.     DrawBalls(pRT);
  3427.     // Draw the cue stick right before/after drawing balls:
  3428.     DrawCueStick(pRT);
  3429.     DrawAimingAids(pRT); // Includes cue stick if aiming
  3430.     DrawUI(pRT);
  3431.     DrawPowerMeter(pRT);
  3432.     DrawSpinIndicator(pRT);
  3433.     DrawPocketedBallsIndicator(pRT);
  3434.     DrawBallInHandIndicator(pRT); // Draw cue ball ghost if placing
  3435.  
  3436.      // Draw Game Over Message
  3437.     if (currentGameState == GAME_OVER && pTextFormat) {
  3438.         ID2D1SolidColorBrush* pBrush = nullptr;
  3439.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pBrush);
  3440.         if (pBrush) {
  3441.             D2D1_RECT_F layoutRect = D2D1::RectF(TABLE_LEFT, TABLE_TOP + TABLE_HEIGHT / 2 - 30, TABLE_RIGHT, TABLE_TOP + TABLE_HEIGHT / 2 + 30);
  3442.             pRT->DrawText(
  3443.                 gameOverMessage.c_str(),
  3444.                 (UINT32)gameOverMessage.length(),
  3445.                 pTextFormat, // Use large format maybe?
  3446.                 &layoutRect,
  3447.                 pBrush
  3448.             );
  3449.             SafeRelease(&pBrush);
  3450.         }
  3451.     }
  3452.  
  3453. }
  3454.  
  3455. void DrawTable(ID2D1RenderTarget* pRT, ID2D1Factory* pFactory) {
  3456.     ID2D1SolidColorBrush* pBrush = nullptr;
  3457.  
  3458.     // --- FOOLPROOF FIX 1: Draw black backdrops for pockets FIRST ---
  3459.     ID2D1SolidColorBrush* pPocketBackdropBrush = nullptr;
  3460.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pPocketBackdropBrush);
  3461.     if (pPocketBackdropBrush) {
  3462.         for (int i = 0; i < 6; ++i) {
  3463.             // Draw a circle slightly larger than the visual hole to ensure it's prominent
  3464.             D2D1_ELLIPSE backdrop = D2D1::Ellipse(pocketPositions[i], HOLE_VISUAL_RADIUS + 5.0f, HOLE_VISUAL_RADIUS + 5.0f);
  3465.             pRT->FillEllipse(&backdrop, pPocketBackdropBrush);
  3466.         }
  3467.         SafeRelease(&pPocketBackdropBrush);
  3468.     }
  3469.     // --- END FIX ---
  3470.  
  3471.     // === Draw Full Orange Frame (Table Border) ===
  3472.     /*ID2D1SolidColorBrush* pFrameBrush = nullptr;
  3473.     pRT->CreateSolidColorBrush(D2D1::ColorF(0.9157f, 0.6157f, 0.2000f), &pFrameBrush); //NEWCOLOR ::Orange (no brackets) => (0.9157, 0.6157, 0.2000)
  3474.     //pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Orange), &pFrameBrush); //NEWCOLOR ::Orange (no brackets) => (0.9157, 0.6157, 0.2000)
  3475.     if (pFrameBrush) {
  3476.         D2D1_RECT_F outerRect = D2D1::RectF(
  3477.             TABLE_LEFT - CUSHION_THICKNESS,
  3478.             TABLE_TOP - CUSHION_THICKNESS,
  3479.             TABLE_RIGHT + CUSHION_THICKNESS,
  3480.             TABLE_BOTTOM + CUSHION_THICKNESS
  3481.         );
  3482.         pRT->FillRectangle(&outerRect, pFrameBrush);
  3483.         SafeRelease(&pFrameBrush);
  3484.     }*/
  3485.  
  3486.     // Draw Table Bed (Green Felt)
  3487.     pRT->CreateSolidColorBrush(TABLE_COLOR, &pBrush);
  3488.     if (!pBrush) return;
  3489.     D2D1_RECT_F tableRect = D2D1::RectF(TABLE_LEFT, TABLE_TOP, TABLE_RIGHT, TABLE_BOTTOM);
  3490.     pRT->FillRectangle(&tableRect, pBrush);
  3491.     SafeRelease(&pBrush);
  3492.  
  3493.     // ------------------------------------------------------------------
  3494. //  Spotlight overlay (soft radial inside a rounded rectangle)
  3495. // ------------------------------------------------------------------
  3496.     {
  3497.         // 2.1  Build a radial gradient brush (edge = base cloth, centre = lighter)
  3498.         ID2D1RadialGradientBrush* pSpot = nullptr;
  3499.         ID2D1GradientStopCollection* pStops = nullptr;
  3500.  
  3501.         D2D1_COLOR_F centreClr = D2D1::ColorF(
  3502.             std::min(1.f, TABLE_COLOR.r * 1.60f),   // lighten ~60 %
  3503.             std::min(1.f, TABLE_COLOR.g * 1.60f),
  3504.             std::min(1.f, TABLE_COLOR.b * 1.60f));
  3505.  
  3506.         const D2D1_GRADIENT_STOP gs[3] =
  3507.         {
  3508.             { 0.0f, D2D1::ColorF(centreClr.r, centreClr.g, centreClr.b, 0.95f) },
  3509.             { 0.6f, D2D1::ColorF(TABLE_COLOR.r, TABLE_COLOR.g, TABLE_COLOR.b, 0.55f) },
  3510.             { 1.0f, D2D1::ColorF(TABLE_COLOR.r, TABLE_COLOR.g, TABLE_COLOR.b, 0.0f) }
  3511.         };
  3512.         pRT->CreateGradientStopCollection(gs, 3, &pStops);
  3513.  
  3514.         if (pStops)
  3515.         {
  3516.             D2D1_RECT_F rc = tableRect;
  3517.             const float PAD = 18.0f;                   // inset so corners stay dark
  3518.             rc.left += PAD;  rc.top += PAD;
  3519.             rc.right -= PAD;  rc.bottom -= PAD;
  3520.  
  3521.             // centre point & radii
  3522.             D2D1_POINT_2F centre = D2D1::Point2F(
  3523.                 (rc.left + rc.right) / 2.0f,
  3524.                 (rc.top + rc.bottom) / 2.0f);
  3525.  
  3526.             float rx = (rc.right - rc.left) * 0.55f;
  3527.             float ry = (rc.bottom - rc.top) * 0.55f;
  3528.  
  3529.             D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  3530.                 D2D1::RadialGradientBrushProperties(
  3531.                     centre,                       // origin
  3532.                     D2D1::Point2F(0, 0),          // offset
  3533.                     rx, ry);
  3534.  
  3535.             pRT->CreateRadialGradientBrush(props, pStops, &pSpot);
  3536.             pStops->Release();
  3537.         }
  3538.  
  3539.         if (pSpot)
  3540.         {
  3541.             // Use the same rounded rectangle the pocket bar uses for subtle round corners
  3542.             const float RADIUS = 20.0f;                       // corner radius
  3543.             D2D1_ROUNDED_RECT spotlightRR =
  3544.                 D2D1::RoundedRect(tableRect, RADIUS, RADIUS);
  3545.  
  3546.             pRT->FillRoundedRectangle(&spotlightRR, pSpot);
  3547.             pSpot->Release();
  3548.         }
  3549.     }
  3550.  
  3551.     // Draw Cushions (Red Border)
  3552.     pRT->CreateSolidColorBrush(CUSHION_COLOR, &pBrush);
  3553.     if (!pBrush) return;
  3554.     // Top Cushion (split by middle pocket)
  3555.     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);
  3556.     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);
  3557.     // Bottom Cushion (split by middle pocket)
  3558.     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);
  3559.     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);
  3560.     // Left Cushion
  3561.     pRT->FillRectangle(D2D1::RectF(TABLE_LEFT - CUSHION_THICKNESS, TABLE_TOP + HOLE_VISUAL_RADIUS, TABLE_LEFT, TABLE_BOTTOM - HOLE_VISUAL_RADIUS), pBrush);
  3562.     // Right Cushion
  3563.     pRT->FillRectangle(D2D1::RectF(TABLE_RIGHT, TABLE_TOP + HOLE_VISUAL_RADIUS, TABLE_RIGHT + CUSHION_THICKNESS, TABLE_BOTTOM - HOLE_VISUAL_RADIUS), pBrush);
  3564.     SafeRelease(&pBrush);
  3565.  
  3566.  
  3567.     // Draw Pockets (Black Circles)
  3568.                     // --- FOOLPROOF FIX: Draw Realistic V-Cut Semicircle Pockets ---
  3569.     ID2D1SolidColorBrush* pPocketBrush = nullptr;
  3570.     ID2D1SolidColorBrush* pRimBrush = nullptr;
  3571.     pRT->CreateSolidColorBrush(POCKET_COLOR, &pPocketBrush);
  3572.     pRT->CreateSolidColorBrush(D2D1::ColorF(0.1f, 0.1f, 0.1f), &pRimBrush);
  3573.  
  3574.     if (pPocketBrush && pRimBrush) {
  3575.         for (int i = 0; i < 6; ++i) {
  3576.             ID2D1PathGeometry* pPath = nullptr;
  3577.             pFactory->CreatePathGeometry(&pPath);
  3578.             if (pPath) {
  3579.                 ID2D1GeometrySink* pSink = nullptr;
  3580.                 if (SUCCEEDED(pPath->Open(&pSink))) {
  3581.                     // Define the shape parameters
  3582.                     float mouthRadius = HOLE_VISUAL_RADIUS * 1.5f;
  3583.                     float backRadius = HOLE_VISUAL_RADIUS * 1.1f;
  3584.                     D2D1_POINT_2F center = pocketPositions[i];
  3585.  
  3586.                     // Points for the V-cut leading into the semicircle
  3587.                     D2D1_POINT_2F p1, p2;
  3588.                     D2D1_SWEEP_DIRECTION sweep;
  3589.  
  3590.                     // Determine points based on pocket position
  3591.                     if (i == 0) { // Top-Left
  3592.                         p1 = D2D1::Point2F(center.x + mouthRadius, center.y);
  3593.                         p2 = D2D1::Point2F(center.x, center.y + mouthRadius);
  3594.                         sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  3595.                     }
  3596.                     else if (i == 2) { // Top-Right
  3597.                         p1 = D2D1::Point2F(center.x, center.y + mouthRadius);
  3598.                         p2 = D2D1::Point2F(center.x - mouthRadius, center.y);
  3599.                         sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  3600.                     }
  3601.                     else if (i == 3) { // Bottom-Left
  3602.                         p1 = D2D1::Point2F(center.x, center.y - mouthRadius);
  3603.                         p2 = D2D1::Point2F(center.x + mouthRadius, center.y);
  3604.                         sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  3605.                     }
  3606.                     else if (i == 5) { // Bottom-Right
  3607.                         p1 = D2D1::Point2F(center.x - mouthRadius, center.y);
  3608.                         p2 = D2D1::Point2F(center.x, center.y - mouthRadius);
  3609.                         sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  3610.                     }
  3611.                     else if (i == 1) { // Top-Middle
  3612.                         p1 = D2D1::Point2F(center.x - mouthRadius / 1.5f, center.y);
  3613.                         p2 = D2D1::Point2F(center.x + mouthRadius / 1.5f, center.y);
  3614.                         sweep = D2D1_SWEEP_DIRECTION_CLOCKWISE;
  3615.                     }
  3616.                     else { // Bottom-Middle (i == 4)
  3617.                         p1 = D2D1::Point2F(center.x + mouthRadius / 1.5f, center.y);
  3618.                         p2 = D2D1::Point2F(center.x - mouthRadius / 1.5f, center.y);
  3619.                         sweep = D2D1_SWEEP_DIRECTION_CLOCKWISE;
  3620.                     }
  3621.  
  3622.                     // Build the keyhole shape
  3623.                     pSink->BeginFigure(center, D2D1_FIGURE_BEGIN_FILLED);
  3624.                     pSink->AddLine(p1);
  3625.                     pSink->AddArc(D2D1::ArcSegment(p2, D2D1::SizeF(backRadius, backRadius), 0.0f, sweep, D2D1_ARC_SIZE_SMALL));
  3626.                     pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  3627.                     pSink->Close();
  3628.                     SafeRelease(&pSink);
  3629.  
  3630.                     // Draw the shape
  3631.                     pRT->FillGeometry(pPath, pPocketBrush);
  3632.  
  3633.                     // Draw the inner rim for a beveled effect
  3634.                     D2D1::Matrix3x2F scale = D2D1::Matrix3x2F::Scale(0.8f, 0.8f, center);
  3635.                     ID2D1TransformedGeometry* pTransformedGeo = nullptr;
  3636.                     pFactory->CreateTransformedGeometry(pPath, &scale, &pTransformedGeo);
  3637.                     if (pTransformedGeo) {
  3638.                         pRT->FillGeometry(pTransformedGeo, pRimBrush);
  3639.                         SafeRelease(&pTransformedGeo);
  3640.                     }
  3641.                 }
  3642.                 SafeRelease(&pPath);
  3643.             }
  3644.         }
  3645.     }
  3646.     SafeRelease(&pPocketBrush);
  3647.     SafeRelease(&pRimBrush);
  3648.  
  3649.     // Draw Headstring Line (White)
  3650.     pRT->CreateSolidColorBrush(D2D1::ColorF(0.4235f, 0.5647f, 0.1765f, 1.0f), &pBrush); // NEWCOLOR ::White => (0.2784, 0.4549, 0.1843)
  3651.     //pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.5f), &pBrush); // NEWCOLOR ::White => (0.2784, 0.4549, 0.1843)
  3652.     if (!pBrush) return;
  3653.     pRT->DrawLine(
  3654.         D2D1::Point2F(HEADSTRING_X, TABLE_TOP),
  3655.         D2D1::Point2F(HEADSTRING_X, TABLE_BOTTOM),
  3656.         pBrush,
  3657.         1.0f // Line thickness
  3658.     );
  3659.     SafeRelease(&pBrush);
  3660.  
  3661.     // Draw Semicircle facing West (flat side East)
  3662.     // Draw Semicircle facing East (curved side on the East, flat side on the West)
  3663.     ID2D1PathGeometry* pGeometry = nullptr;
  3664.     HRESULT hr = pFactory->CreatePathGeometry(&pGeometry);
  3665.     if (SUCCEEDED(hr) && pGeometry)
  3666.     {
  3667.         ID2D1GeometrySink* pSink = nullptr;
  3668.         hr = pGeometry->Open(&pSink);
  3669.         if (SUCCEEDED(hr) && pSink)
  3670.         {
  3671.             float radius = 60.0f; // Radius for the semicircle
  3672.             D2D1_POINT_2F center = D2D1::Point2F(HEADSTRING_X, (TABLE_TOP + TABLE_BOTTOM) / 2.0f);
  3673.  
  3674.             // For a semicircle facing East (curved side on the East), use the top and bottom points.
  3675.             D2D1_POINT_2F startPoint = D2D1::Point2F(center.x, center.y - radius); // Top point
  3676.  
  3677.             pSink->BeginFigure(startPoint, D2D1_FIGURE_BEGIN_HOLLOW);
  3678.  
  3679.             D2D1_ARC_SEGMENT arc = {};
  3680.             arc.point = D2D1::Point2F(center.x, center.y + radius); // Bottom point
  3681.             arc.size = D2D1::SizeF(radius, radius);
  3682.             arc.rotationAngle = 0.0f;
  3683.             // Use the correct identifier with the extra underscore:
  3684.             arc.sweepDirection = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  3685.             arc.arcSize = D2D1_ARC_SIZE_SMALL;
  3686.  
  3687.             pSink->AddArc(&arc);
  3688.             pSink->EndFigure(D2D1_FIGURE_END_OPEN);
  3689.             pSink->Close();
  3690.             SafeRelease(&pSink);
  3691.  
  3692.             ID2D1SolidColorBrush* pArcBrush = nullptr;
  3693.             //pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.3f), &pArcBrush);
  3694.             pRT->CreateSolidColorBrush(D2D1::ColorF(0.4235f, 0.5647f, 0.1765f, 1.0f), &pArcBrush);
  3695.             if (pArcBrush)
  3696.             {
  3697.                 pRT->DrawGeometry(pGeometry, pArcBrush, 1.5f);
  3698.                 SafeRelease(&pArcBrush);
  3699.             }
  3700.         }
  3701.         SafeRelease(&pGeometry);
  3702.     }
  3703.  
  3704.  
  3705.  
  3706.  
  3707. }
  3708.  
  3709.  
  3710. // ----------------------------------------------
  3711. //  Helper : clamp to [0,1] and lighten a colour
  3712. // ----------------------------------------------
  3713. static D2D1_COLOR_F Lighten(const D2D1_COLOR_F& c, float factor = 1.25f)
  3714. {
  3715.     return D2D1::ColorF(
  3716.         std::min(1.0f, c.r * factor),
  3717.         std::min(1.0f, c.g * factor),
  3718.         std::min(1.0f, c.b * factor),
  3719.         c.a);
  3720. }
  3721.  
  3722. // ------------------------------------------------
  3723. //  NEW  DrawBalls – radial-gradient “spot-light”
  3724. // ------------------------------------------------
  3725. void DrawBalls(ID2D1RenderTarget* pRT)
  3726. {
  3727.     if (!pRT) return;
  3728.  
  3729.     ID2D1SolidColorBrush* pStripeBrush = nullptr;    // white stripe
  3730.     ID2D1SolidColorBrush* pBorderBrush = nullptr;    // black ring
  3731.     ID2D1SolidColorBrush* pNumWhite = nullptr; // NEW – white circle
  3732.     ID2D1SolidColorBrush* pNumBlack = nullptr; // NEW – digit colour
  3733.  
  3734.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
  3735.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
  3736.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pNumWhite);
  3737.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pNumBlack);
  3738.  
  3739.     for (const Ball& b : balls)
  3740.     {
  3741.         if (b.isPocketed) continue;
  3742.  
  3743.         //------------------------------------------
  3744.         // Build the radial gradient for THIS ball
  3745.         //------------------------------------------
  3746.         ID2D1GradientStopCollection* pStops = nullptr;
  3747.         ID2D1RadialGradientBrush* pRad = nullptr;
  3748.  
  3749.         D2D1_GRADIENT_STOP gs[3];
  3750.         gs[0].position = 0.0f;  gs[0].color = D2D1::ColorF(1, 1, 1, 0.95f);     // bright spot
  3751.         gs[1].position = 0.35f; gs[1].color = Lighten(b.color);                 // transitional
  3752.         gs[2].position = 1.0f;  gs[2].color = b.color;                          // base colour
  3753.  
  3754.         pRT->CreateGradientStopCollection(gs, 3, &pStops);
  3755.  
  3756.         if (pStops)
  3757.         {
  3758.             // Place the hot-spot slightly towards top-left to look more 3-D
  3759.             D2D1_POINT_2F origin = D2D1::Point2F(b.x - BALL_RADIUS * 0.4f,
  3760.                 b.y - BALL_RADIUS * 0.4f);
  3761.  
  3762.             D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  3763.                 D2D1::RadialGradientBrushProperties(
  3764.                     origin,                        // gradientOrigin
  3765.                     D2D1::Point2F(0, 0),           // offset (not used here)
  3766.                     BALL_RADIUS * 1.3f,            // radiusX
  3767.                     BALL_RADIUS * 1.3f);           // radiusY
  3768.  
  3769.             pRT->CreateRadialGradientBrush(props, pStops, &pRad);
  3770.             SafeRelease(&pStops);
  3771.         }
  3772.  
  3773.         //------------------------------------------
  3774.         //  Draw the solid or striped ball itself
  3775.         //------------------------------------------
  3776.         D2D1_ELLIPSE outer = D2D1::Ellipse(
  3777.             D2D1::Point2F(b.x, b.y), BALL_RADIUS, BALL_RADIUS);
  3778.  
  3779.         if (pRad)  pRT->FillEllipse(&outer, pRad);
  3780.  
  3781.         // ----------  Stripe overlay  -------------
  3782.         if (b.type == BallType::STRIPE && pStripeBrush)
  3783.         {
  3784.             // White band
  3785.             D2D1_RECT_F stripe = D2D1::RectF(
  3786.                 b.x - BALL_RADIUS,
  3787.                 b.y - BALL_RADIUS * 0.40f,
  3788.                 b.x + BALL_RADIUS,
  3789.                 b.y + BALL_RADIUS * 0.40f);
  3790.             pRT->FillRectangle(&stripe, pStripeBrush);
  3791.  
  3792.             // Inner circle (give stripe area same glossy shading)
  3793.             if (pRad)
  3794.             {
  3795.                 D2D1_ELLIPSE inner = D2D1::Ellipse(
  3796.                     D2D1::Point2F(b.x, b.y),
  3797.                     BALL_RADIUS * 0.60f,
  3798.                     BALL_RADIUS * 0.60f);
  3799.                 pRT->FillEllipse(&inner, pRad);
  3800.             }
  3801.         }
  3802.  
  3803.         // --------------------------------------------------------
  3804. //  Draw number decal (skip cue ball)
  3805. // --------------------------------------------------------
  3806.         if (b.id != 0 && pBallNumFormat && pNumWhite && pNumBlack)
  3807.         {
  3808.             // 1) white circle – slightly smaller on stripes so it fits
  3809.             const float decalR = (b.type == BallType::STRIPE) ?
  3810.                 BALL_RADIUS * 0.40f : BALL_RADIUS * 0.45f;
  3811.  
  3812.             D2D1_ELLIPSE decal = D2D1::Ellipse(
  3813.                 D2D1::Point2F(b.x, b.y), decalR, decalR);
  3814.  
  3815.             pRT->FillEllipse(&decal, pNumWhite);
  3816.             pRT->DrawEllipse(&decal, pNumBlack, 0.8f);   // thin border
  3817.  
  3818.             // 2) digit – convert id to printable number
  3819.             wchar_t numText[3];
  3820.             _snwprintf_s(numText, _TRUNCATE, L"%d", b.id);
  3821.  
  3822.             // layout rectangle exactly the diameter of the decal
  3823.             D2D1_RECT_F layout = D2D1::RectF(
  3824.                 b.x - decalR, b.y - decalR,
  3825.                 b.x + decalR, b.y + decalR);
  3826.  
  3827.             pRT->DrawText(numText,
  3828.                 (UINT32)wcslen(numText),
  3829.                 pBallNumFormat,
  3830.                 &layout,
  3831.                 pNumBlack);
  3832.         }
  3833.  
  3834.         // Black border
  3835.         if (pBorderBrush)
  3836.             pRT->DrawEllipse(&outer, pBorderBrush, 1.5f);
  3837.  
  3838.         SafeRelease(&pRad);
  3839.     }
  3840.  
  3841.     SafeRelease(&pStripeBrush);
  3842.     SafeRelease(&pBorderBrush);
  3843.     SafeRelease(&pNumWhite);   // NEW
  3844.     SafeRelease(&pNumBlack);   // NEW
  3845. }
  3846.  
  3847. /*void DrawBalls(ID2D1RenderTarget* pRT) {
  3848.     ID2D1SolidColorBrush* pBrush = nullptr;
  3849.     ID2D1SolidColorBrush* pStripeBrush = nullptr; // For stripe pattern
  3850.  
  3851.     pRT->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0), &pBrush); // Placeholder
  3852.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
  3853.  
  3854.     if (!pBrush || !pStripeBrush) {
  3855.         SafeRelease(&pBrush);
  3856.         SafeRelease(&pStripeBrush);
  3857.         return;
  3858.     }
  3859.  
  3860.  
  3861.     for (size_t i = 0; i < balls.size(); ++i) {
  3862.         const Ball& b = balls[i];
  3863.         if (!b.isPocketed) {
  3864.             D2D1_ELLIPSE ellipse = D2D1::Ellipse(D2D1::Point2F(b.x, b.y), BALL_RADIUS, BALL_RADIUS);
  3865.  
  3866.             // Set main ball color
  3867.             pBrush->SetColor(b.color);
  3868.             pRT->FillEllipse(&ellipse, pBrush);
  3869.  
  3870.             // Draw Stripe if applicable
  3871.             if (b.type == BallType::STRIPE) {
  3872.                 // Draw a white band across the middle (simplified stripe)
  3873.                 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);
  3874.                 // Need to clip this rectangle to the ellipse bounds - complex!
  3875.                 // Alternative: Draw two colored arcs leaving a white band.
  3876.                 // Simplest: Draw a white circle inside, slightly smaller.
  3877.                 D2D1_ELLIPSE innerEllipse = D2D1::Ellipse(D2D1::Point2F(b.x, b.y), BALL_RADIUS * 0.6f, BALL_RADIUS * 0.6f);
  3878.                 pRT->FillEllipse(innerEllipse, pStripeBrush); // White center part
  3879.                 pBrush->SetColor(b.color); // Set back to stripe color
  3880.                 pRT->FillEllipse(innerEllipse, pBrush); // Fill again, leaving a ring - No, this isn't right.
  3881.  
  3882.                 // Let's try drawing a thick white line across
  3883.                 // This doesn't look great. Just drawing solid red for stripes for now.
  3884.             }
  3885.  
  3886.             // Draw Number (Optional - requires more complex text layout or pre-rendered textures)
  3887.             // if (b.id != 0 && pTextFormat) {
  3888.             //     std::wstring numStr = std::to_wstring(b.id);
  3889.             //     D2D1_RECT_F textRect = D2D1::RectF(b.x - BALL_RADIUS, b.y - BALL_RADIUS, b.x + BALL_RADIUS, b.y + BALL_RADIUS);
  3890.             //     ID2D1SolidColorBrush* pNumBrush = nullptr;
  3891.             //     D2D1_COLOR_F numCol = (b.type == BallType::SOLID || b.id == 8) ? D2D1::ColorF(D2D1::ColorF::Black) : D2D1::ColorF(D2D1::ColorF::White);
  3892.             //     pRT->CreateSolidColorBrush(numCol, &pNumBrush);
  3893.             //     // Create a smaller text format...
  3894.             //     // pRT->DrawText(numStr.c_str(), numStr.length(), pSmallTextFormat, &textRect, pNumBrush);
  3895.             //     SafeRelease(&pNumBrush);
  3896.             // }
  3897.         }
  3898.     }
  3899.  
  3900.     SafeRelease(&pBrush);
  3901.     SafeRelease(&pStripeBrush);
  3902. }*/
  3903.  
  3904. // --------------------------------------------------------------------------------
  3905. // DrawCueStick: tapered stick (thick butt, narrow tip), beige shaft, white tip, black butt
  3906. // --------------------------------------------------------------------------------
  3907. void DrawCueStick(ID2D1RenderTarget* pRT)
  3908. {
  3909.     Ball* cue = GetCueBall();
  3910.     if (!cue) return;
  3911.  
  3912.     // parameters
  3913.     const float tipLength = 30.0f;
  3914.     const float buttLength = 50.0f;
  3915.     const float totalLength = 200.0f;    // from butt end to tip end
  3916.     const float buttWidth = 8.0f;      // thick end
  3917.     const float shaftWidth = 4.0f;      // narrow middle
  3918.  
  3919.     // compute end points in world coords
  3920.     float theta = cueAngle + PI; // stick points opposite aim
  3921.     D2D1_POINT_2F base = D2D1::Point2F(
  3922.         cue->x + cosf(theta) * buttLength,
  3923.         cue->y + sinf(theta) * buttLength
  3924.     );
  3925.     D2D1_POINT_2F tip = D2D1::Point2F(
  3926.         cue->x + cosf(theta) * totalLength,
  3927.         cue->y + sinf(theta) * totalLength
  3928.     );
  3929.  
  3930.     // Prepare brushes
  3931.     ID2D1SolidColorBrush* pButtBrush = nullptr;
  3932.     ID2D1SolidColorBrush* pShaftBrush = nullptr;
  3933.     ID2D1SolidColorBrush* pTipBrush = nullptr;
  3934.  
  3935.     pRT->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0), &pButtBrush);  // black butt
  3936.     pRT->CreateSolidColorBrush(D2D1::ColorF(0.96f, 0.85f, 0.60f), &pShaftBrush); // beige shaft
  3937.     pRT->CreateSolidColorBrush(D2D1::ColorF(1, 1, 1), &pTipBrush);   // white tip
  3938.  
  3939.     // Build a simple mesh: butt→shaft→tip as three quads
  3940.     auto buildRect = [&](D2D1_POINT_2F p1, D2D1_POINT_2F p2, float w1, float w2) {
  3941.         // p1 to p2, widths w1 at p1, w2 at p2
  3942.         D2D1_POINT_2F perp = { -sinf(theta) * 0.5f, cosf(theta) * 0.5f };
  3943.         perp.x *= w1; perp.y *= w1;
  3944.         D2D1_POINT_2F a = { p1.x + perp.x, p1.y + perp.y };
  3945.         D2D1_POINT_2F b = { p2.x + perp.x * (w2 / w1), p2.y + perp.y * (w2 / w1) };
  3946.         D2D1_POINT_2F c = { p2.x - perp.x * (w2 / w1), p2.y - perp.y * (w2 / w1) };
  3947.         D2D1_POINT_2F d = { p1.x - perp.x, p1.y - perp.y };
  3948.         ID2D1PathGeometry* geom = nullptr;
  3949.         if (SUCCEEDED(pFactory->CreatePathGeometry(&geom))) {
  3950.             ID2D1GeometrySink* sink = nullptr;
  3951.             if (SUCCEEDED(geom->Open(&sink))) {
  3952.                 sink->BeginFigure(a, D2D1_FIGURE_BEGIN_FILLED);
  3953.                 sink->AddLine(b);
  3954.                 sink->AddLine(c);
  3955.                 sink->AddLine(d);
  3956.                 sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  3957.                 sink->Close();
  3958.             }
  3959.             SafeRelease(&sink);
  3960.         }
  3961.         return geom;
  3962.     };
  3963.  
  3964.     // 1) butt segment: from base back toward cue center
  3965.     D2D1_POINT_2F mid1 = { cue->x + cosf(theta) * (buttLength * 0.5f), cue->y + sinf(theta) * (buttLength * 0.5f) };
  3966.     auto buttGeom = buildRect(base, mid1, buttWidth, shaftWidth);
  3967.     if (buttGeom) { pRT->FillGeometry(buttGeom, pButtBrush); SafeRelease(&buttGeom); }
  3968.  
  3969.     // 2) shaft segment: from mid1 to just before tip
  3970.     D2D1_POINT_2F mid2 = { cue->x + cosf(theta) * (totalLength - tipLength), cue->y + sinf(theta) * (totalLength - tipLength) };
  3971.     auto shaftGeom = buildRect(mid1, mid2, shaftWidth, shaftWidth);
  3972.     if (shaftGeom) { pRT->FillGeometry(shaftGeom, pShaftBrush); SafeRelease(&shaftGeom); }
  3973.  
  3974.     // 3) tip segment: last bit
  3975.     auto tipGeom = buildRect(mid2, tip, shaftWidth, shaftWidth);
  3976.     if (tipGeom) { pRT->FillGeometry(tipGeom, pTipBrush); SafeRelease(&tipGeom); }
  3977.  
  3978.     // cleanup
  3979.     SafeRelease(&pButtBrush);
  3980.     SafeRelease(&pShaftBrush);
  3981.     SafeRelease(&pTipBrush);
  3982. }
  3983.  
  3984.  
  3985.  
  3986. /*void DrawAimingAids(ID2D1RenderTarget* pRT) {
  3987.     // Condition check at start (Unchanged)
  3988.     //if (currentGameState != PLAYER1_TURN && currentGameState != PLAYER2_TURN &&
  3989.         //currentGameState != BREAKING && currentGameState != AIMING)
  3990.     //{
  3991.         //return;
  3992.     //}
  3993.         // NEW Condition: Allow drawing if it's a human player's active turn/aiming/breaking,
  3994.     // OR if it's AI's turn and it's in AI_THINKING state (calculating) or BREAKING (aiming break).
  3995.     bool isHumanInteracting = (!isPlayer2AI || currentPlayer == 1) &&
  3996.         (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN ||
  3997.             currentGameState == BREAKING || currentGameState == AIMING);
  3998.     // AI_THINKING state is when AI calculates shot. AIMakeDecision sets cueAngle/shotPower.
  3999.     // Also include BREAKING state if it's AI's turn and isOpeningBreakShot for break aim visualization.
  4000.         // NEW Condition: AI is displaying its aim
  4001.     bool isAiVisualizingShot = (isPlayer2AI && currentPlayer == 2 &&
  4002.         currentGameState == AI_THINKING && aiIsDisplayingAim);
  4003.  
  4004.     if (!isHumanInteracting && !(isAiVisualizingShot || (currentGameState == AI_THINKING && aiIsDisplayingAim))) {
  4005.         return;
  4006.     }
  4007.  
  4008.     Ball* cueBall = GetCueBall();
  4009.     if (!cueBall || cueBall->isPocketed) return; // Don't draw if cue ball is gone
  4010.  
  4011.     ID2D1SolidColorBrush* pBrush = nullptr;
  4012.     ID2D1SolidColorBrush* pGhostBrush = nullptr;
  4013.     ID2D1StrokeStyle* pDashedStyle = nullptr;
  4014.     ID2D1SolidColorBrush* pCueBrush = nullptr;
  4015.     ID2D1SolidColorBrush* pReflectBrush = nullptr; // Brush for reflection line
  4016.  
  4017.     // Ensure render target is valid
  4018.     if (!pRT) return;
  4019.  
  4020.     // Create Brushes and Styles (check for failures)
  4021.     HRESULT hr;
  4022.     hr = pRT->CreateSolidColorBrush(AIM_LINE_COLOR, &pBrush);
  4023.     if FAILED(hr) { SafeRelease(&pBrush); return; }
  4024.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.5f), &pGhostBrush);
  4025.     if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); return; }
  4026.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(0.6f, 0.4f, 0.2f), &pCueBrush);
  4027.     if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); SafeRelease(&pCueBrush); return; }
  4028.     // Create reflection brush (e.g., lighter shade or different color)
  4029.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::LightCyan, 0.6f), &pReflectBrush);
  4030.     if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); SafeRelease(&pCueBrush); SafeRelease(&pReflectBrush); return; }
  4031.     // Create a Cyan brush for primary and secondary lines //orig(75.0f / 255.0f, 0.0f, 130.0f / 255.0f);indigoColor
  4032.     D2D1::ColorF cyanColor(0.0, 255.0, 255.0, 255.0f);
  4033.     ID2D1SolidColorBrush* pCyanBrush = nullptr;
  4034.     hr = pRT->CreateSolidColorBrush(cyanColor, &pCyanBrush);
  4035.     if (FAILED(hr)) {
  4036.         SafeRelease(&pCyanBrush);
  4037.         // handle error if needed
  4038.     }
  4039.     // Create a Purple brush for primary and secondary lines
  4040.     D2D1::ColorF purpleColor(255.0f, 0.0f, 255.0f, 255.0f);
  4041.     ID2D1SolidColorBrush* pPurpleBrush = nullptr;
  4042.     hr = pRT->CreateSolidColorBrush(purpleColor, &pPurpleBrush);
  4043.     if (FAILED(hr)) {
  4044.         SafeRelease(&pPurpleBrush);
  4045.         // handle error if needed
  4046.     }
  4047.  
  4048.     if (pFactory) {
  4049.         D2D1_STROKE_STYLE_PROPERTIES strokeProps = D2D1::StrokeStyleProperties();
  4050.         strokeProps.dashStyle = D2D1_DASH_STYLE_DASH;
  4051.         hr = pFactory->CreateStrokeStyle(&strokeProps, nullptr, 0, &pDashedStyle);
  4052.         if FAILED(hr) { pDashedStyle = nullptr; }
  4053.     }
  4054.  
  4055.  
  4056.     // --- Cue Stick Drawing (Unchanged from previous fix) ---
  4057.     const float baseStickLength = 150.0f;
  4058.     const float baseStickThickness = 4.0f;
  4059.     float stickLength = baseStickLength * 1.4f;
  4060.     float stickThickness = baseStickThickness * 1.5f;
  4061.     float stickAngle = cueAngle + PI;
  4062.     float powerOffset = 0.0f;
  4063.     //if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
  4064.         // Show power offset if human is aiming/dragging, or if AI is preparing its shot (AI_THINKING or AI Break)
  4065.     if ((isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) || isAiVisualizingShot) { // Use the new condition
  4066.         powerOffset = shotPower * 5.0f;
  4067.     }
  4068.     D2D1_POINT_2F cueStickEnd = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (stickLength + powerOffset), cueBall->y + sinf(stickAngle) * (stickLength + powerOffset));
  4069.     D2D1_POINT_2F cueStickTip = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (powerOffset + 5.0f), cueBall->y + sinf(stickAngle) * (powerOffset + 5.0f));
  4070.     pRT->DrawLine(cueStickTip, cueStickEnd, pCueBrush, stickThickness);
  4071.  
  4072.  
  4073.     // --- Projection Line Calculation ---
  4074.     float cosA = cosf(cueAngle);
  4075.     float sinA = sinf(cueAngle);
  4076.     float rayLength = TABLE_WIDTH + TABLE_HEIGHT; // Ensure ray is long enough
  4077.     D2D1_POINT_2F rayStart = D2D1::Point2F(cueBall->x, cueBall->y);
  4078.     D2D1_POINT_2F rayEnd = D2D1::Point2F(rayStart.x + cosA * rayLength, rayStart.y + sinA * rayLength);*/
  4079.  
  4080. void DrawAimingAids(ID2D1RenderTarget* pRT) {
  4081.     // Determine if aiming aids should be drawn.
  4082.     bool isHumanInteracting = (!isPlayer2AI || currentPlayer == 1) &&
  4083.         (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN ||
  4084.             currentGameState == BREAKING || currentGameState == AIMING ||
  4085.             currentGameState == CHOOSING_POCKET_P1 || currentGameState == CHOOSING_POCKET_P2);
  4086.  
  4087.     // FOOLPROOF FIX: This is the new condition to show the AI's aim.
  4088.     bool isAiVisualizingShot = (isPlayer2AI && currentPlayer == 2 && aiIsDisplayingAim);
  4089.  
  4090.     if (!isHumanInteracting && !isAiVisualizingShot) {
  4091.         return;
  4092.     }
  4093.  
  4094.     Ball* cueBall = GetCueBall();
  4095.     if (!cueBall || cueBall->isPocketed) return;
  4096.  
  4097.     // --- Brush and Style Creation (No changes here) ---
  4098.     ID2D1SolidColorBrush* pBrush = nullptr;
  4099.     ID2D1SolidColorBrush* pGhostBrush = nullptr;
  4100.     ID2D1StrokeStyle* pDashedStyle = nullptr;
  4101.     ID2D1SolidColorBrush* pCueBrush = nullptr;
  4102.     ID2D1SolidColorBrush* pReflectBrush = nullptr;
  4103.     ID2D1SolidColorBrush* pCyanBrush = nullptr;
  4104.     ID2D1SolidColorBrush* pPurpleBrush = nullptr;
  4105.     pRT->CreateSolidColorBrush(AIM_LINE_COLOR, &pBrush);
  4106.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.5f), &pGhostBrush);
  4107.     pRT->CreateSolidColorBrush(D2D1::ColorF(0.6f, 0.4f, 0.2f), &pCueBrush);
  4108.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::LightCyan, 0.6f), &pReflectBrush);
  4109.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Cyan), &pCyanBrush);
  4110.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Purple), &pPurpleBrush);
  4111.     if (pFactory) {
  4112.         D2D1_STROKE_STYLE_PROPERTIES strokeProps = D2D1::StrokeStyleProperties();
  4113.         strokeProps.dashStyle = D2D1_DASH_STYLE_DASH;
  4114.         pFactory->CreateStrokeStyle(&strokeProps, nullptr, 0, &pDashedStyle);
  4115.     }
  4116.     // --- End Brush Creation ---
  4117.  
  4118.     // --- FOOLPROOF FIX: Use the AI's planned angle and power for drawing ---
  4119.     float angleToDraw = cueAngle;
  4120.     float powerToDraw = shotPower;
  4121.  
  4122.     if (isAiVisualizingShot) {
  4123.         // When the AI is showing its aim, force the drawing to use its planned shot details.
  4124.         angleToDraw = aiPlannedShotDetails.angle;
  4125.         powerToDraw = aiPlannedShotDetails.power;
  4126.     }
  4127.     // --- End AI Aiming Fix ---
  4128.  
  4129.     // --- Cue Stick Drawing ---
  4130.     /*const float baseStickLength = 150.0f;
  4131.     const float baseStickThickness = 4.0f;
  4132.     float stickLength = baseStickLength * 1.4f;
  4133.     float stickThickness = baseStickThickness * 1.5f;
  4134.     float stickAngle = angleToDraw + PI; // Use the angle we determined
  4135.     float powerOffset = 0.0f;
  4136.     if ((isAiming || isDraggingStick) || isAiVisualizingShot) {
  4137.         powerOffset = powerToDraw * 5.0f; // Use the power we determined
  4138.     }
  4139.     D2D1_POINT_2F cueStickEnd = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (stickLength + powerOffset), cueBall->y + sinf(stickAngle) * (stickLength + powerOffset));
  4140.     D2D1_POINT_2F cueStickTip = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (powerOffset + 5.0f), cueBall->y + sinf(stickAngle) * (powerOffset + 5.0f));
  4141.     pRT->DrawLine(cueStickTip, cueStickEnd, pCueBrush, stickThickness);*/
  4142.  
  4143.     // --- Projection Line Calculation ---
  4144.     float cosA = cosf(angleToDraw); // Use the angle we determined
  4145.     float sinA = sinf(angleToDraw);
  4146.     float rayLength = TABLE_WIDTH + TABLE_HEIGHT;
  4147.     D2D1_POINT_2F rayStart = D2D1::Point2F(cueBall->x, cueBall->y);
  4148.     D2D1_POINT_2F rayEnd = D2D1::Point2F(rayStart.x + cosA * rayLength, rayStart.y + sinA * rayLength);
  4149.  
  4150.     // Find the first ball hit by the aiming ray
  4151.     Ball* hitBall = nullptr;
  4152.     float firstHitDistSq = -1.0f;
  4153.     D2D1_POINT_2F ballCollisionPoint = { 0, 0 }; // Point on target ball circumference
  4154.     D2D1_POINT_2F ghostBallPosForHit = { 0, 0 }; // Ghost ball pos for the hit ball
  4155.  
  4156.     hitBall = FindFirstHitBall(rayStart, cueAngle, firstHitDistSq);
  4157.     if (hitBall) {
  4158.         // Calculate the point on the target ball's circumference
  4159.         float collisionDist = sqrtf(firstHitDistSq);
  4160.         ballCollisionPoint = D2D1::Point2F(rayStart.x + cosA * collisionDist, rayStart.y + sinA * collisionDist);
  4161.         // Calculate ghost ball position for this specific hit (used for projection consistency)
  4162.         ghostBallPosForHit = D2D1::Point2F(hitBall->x - cosA * BALL_RADIUS, hitBall->y - sinA * BALL_RADIUS); // Approx.
  4163.     }
  4164.  
  4165.     // Find the first rail hit by the aiming ray
  4166.     D2D1_POINT_2F railHitPoint = rayEnd; // Default to far end if no rail hit
  4167.     float minRailDistSq = rayLength * rayLength;
  4168.     int hitRailIndex = -1; // 0:Left, 1:Right, 2:Top, 3:Bottom
  4169.  
  4170.     // Define table edge segments for intersection checks
  4171.     D2D1_POINT_2F topLeft = D2D1::Point2F(TABLE_LEFT, TABLE_TOP);
  4172.     D2D1_POINT_2F topRight = D2D1::Point2F(TABLE_RIGHT, TABLE_TOP);
  4173.     D2D1_POINT_2F bottomLeft = D2D1::Point2F(TABLE_LEFT, TABLE_BOTTOM);
  4174.     D2D1_POINT_2F bottomRight = D2D1::Point2F(TABLE_RIGHT, TABLE_BOTTOM);
  4175.  
  4176.     D2D1_POINT_2F currentIntersection;
  4177.  
  4178.     // Check Left Rail
  4179.     if (LineSegmentIntersection(rayStart, rayEnd, topLeft, bottomLeft, currentIntersection)) {
  4180.         float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  4181.         if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 0; }
  4182.     }
  4183.     // Check Right Rail
  4184.     if (LineSegmentIntersection(rayStart, rayEnd, topRight, bottomRight, currentIntersection)) {
  4185.         float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  4186.         if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 1; }
  4187.     }
  4188.     // Check Top Rail
  4189.     if (LineSegmentIntersection(rayStart, rayEnd, topLeft, topRight, currentIntersection)) {
  4190.         float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  4191.         if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 2; }
  4192.     }
  4193.     // Check Bottom Rail
  4194.     if (LineSegmentIntersection(rayStart, rayEnd, bottomLeft, bottomRight, currentIntersection)) {
  4195.         float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  4196.         if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 3; }
  4197.     }
  4198.  
  4199.  
  4200.     // --- Determine final aim line end point ---
  4201.     D2D1_POINT_2F finalLineEnd = railHitPoint; // Assume rail hit first
  4202.     bool aimingAtRail = true;
  4203.  
  4204.     if (hitBall && firstHitDistSq < minRailDistSq) {
  4205.         // Ball collision is closer than rail collision
  4206.         finalLineEnd = ballCollisionPoint; // End line at the point of contact on the ball
  4207.         aimingAtRail = false;
  4208.     }
  4209.  
  4210.     // --- Draw Primary Aiming Line ---
  4211.     pRT->DrawLine(rayStart, finalLineEnd, pBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  4212.  
  4213.     // --- Draw Target Circle/Indicator ---
  4214.     D2D1_ELLIPSE targetCircle = D2D1::Ellipse(finalLineEnd, BALL_RADIUS / 2.0f, BALL_RADIUS / 2.0f);
  4215.     pRT->DrawEllipse(&targetCircle, pBrush, 1.0f);
  4216.  
  4217.     // --- Draw Projection/Reflection Lines ---
  4218.     if (!aimingAtRail && hitBall) {
  4219.         // Aiming at a ball: Draw Ghost Cue Ball and Target Ball Projection
  4220.         D2D1_ELLIPSE ghostCue = D2D1::Ellipse(ballCollisionPoint, BALL_RADIUS, BALL_RADIUS); // Ghost ball at contact point
  4221.         pRT->DrawEllipse(ghostCue, pGhostBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  4222.  
  4223.         // Calculate target ball projection based on impact line (cue collision point -> target center)
  4224.         float targetProjectionAngle = atan2f(hitBall->y - ballCollisionPoint.y, hitBall->x - ballCollisionPoint.x);
  4225.         // Clamp angle calculation if distance is tiny
  4226.         if (GetDistanceSq(hitBall->x, hitBall->y, ballCollisionPoint.x, ballCollisionPoint.y) < 1.0f) {
  4227.             targetProjectionAngle = cueAngle; // Fallback if overlapping
  4228.         }
  4229.  
  4230.         D2D1_POINT_2F targetStartPoint = D2D1::Point2F(hitBall->x, hitBall->y);
  4231.         D2D1_POINT_2F targetProjectionEnd = D2D1::Point2F(
  4232.             hitBall->x + cosf(targetProjectionAngle) * 50.0f, // Projection length 50 units
  4233.             hitBall->y + sinf(targetProjectionAngle) * 50.0f
  4234.         );
  4235.         // Draw solid line for target projection
  4236.         //pRT->DrawLine(targetStartPoint, targetProjectionEnd, pBrush, 1.0f);
  4237.  
  4238.     //new code start
  4239.  
  4240.                 // Dual trajectory with edge-aware contact simulation
  4241.         D2D1_POINT_2F dir = {
  4242.             targetProjectionEnd.x - targetStartPoint.x,
  4243.             targetProjectionEnd.y - targetStartPoint.y
  4244.         };
  4245.         float dirLen = sqrtf(dir.x * dir.x + dir.y * dir.y);
  4246.         dir.x /= dirLen;
  4247.         dir.y /= dirLen;
  4248.  
  4249.         D2D1_POINT_2F perp = { -dir.y, dir.x };
  4250.  
  4251.         // Approximate cue ball center by reversing from tip
  4252.         D2D1_POINT_2F cueBallCenterForGhostHit = { // Renamed for clarity if you use it elsewhere
  4253.             targetStartPoint.x - dir.x * BALL_RADIUS,
  4254.             targetStartPoint.y - dir.y * BALL_RADIUS
  4255.         };
  4256.  
  4257.         // REAL contact-ball center - use your physics object's center:
  4258.         // (replace 'objectBallPos' with whatever you actually call it)
  4259.         // (targetStartPoint is already hitBall->x, hitBall->y)
  4260.         D2D1_POINT_2F contactBallCenter = targetStartPoint; // Corrected: Use the object ball's actual center
  4261.         //D2D1_POINT_2F contactBallCenter = D2D1::Point2F(hitBall->x, hitBall->y);
  4262.  
  4263.        // The 'offset' calculation below uses 'cueBallCenterForGhostHit' (originally 'cueBallCenter').
  4264.        // This will result in 'offset' being 0 because 'cueBallCenterForGhostHit' is defined
  4265.        // such that (targetStartPoint - cueBallCenterForGhostHit) is parallel to 'dir',
  4266.        // and 'perp' is perpendicular to 'dir'.
  4267.        // Consider Change 2 if this 'offset' is not behaving as intended for the secondary line.
  4268.         /*float offset = ((targetStartPoint.x - cueBallCenterForGhostHit.x) * perp.x +
  4269.             (targetStartPoint.y - cueBallCenterForGhostHit.y) * perp.y);*/
  4270.             /*float offset = ((targetStartPoint.x - cueBallCenter.x) * perp.x +
  4271.                 (targetStartPoint.y - cueBallCenter.y) * perp.y);
  4272.             float absOffset = fabsf(offset);
  4273.             float side = (offset >= 0 ? 1.0f : -1.0f);*/
  4274.  
  4275.             // Use actual cue ball center for offset calculation if 'offset' is meant to quantify the cut
  4276.         D2D1_POINT_2F actualCueBallPhysicalCenter = D2D1::Point2F(cueBall->x, cueBall->y); // This is also rayStart
  4277.  
  4278.         // Offset calculation based on actual cue ball position relative to the 'dir' line through targetStartPoint
  4279.         float offset = ((targetStartPoint.x - actualCueBallPhysicalCenter.x) * perp.x +
  4280.             (targetStartPoint.y - actualCueBallPhysicalCenter.y) * perp.y);
  4281.         float absOffset = fabsf(offset);
  4282.         float side = (offset >= 0 ? 1.0f : -1.0f);
  4283.  
  4284.  
  4285.         // Actual contact point on target ball edge
  4286.         D2D1_POINT_2F contactPoint = {
  4287.         contactBallCenter.x + perp.x * BALL_RADIUS * side,
  4288.         contactBallCenter.y + perp.y * BALL_RADIUS * side
  4289.         };
  4290.  
  4291.         // Tangent (cut shot) path from contact point
  4292.             // Tangent (cut shot) path: from contact point to contact ball center
  4293.         D2D1_POINT_2F objectBallDir = {
  4294.             contactBallCenter.x - contactPoint.x,
  4295.             contactBallCenter.y - contactPoint.y
  4296.         };
  4297.         float oLen = sqrtf(objectBallDir.x * objectBallDir.x + objectBallDir.y * objectBallDir.y);
  4298.         if (oLen != 0.0f) {
  4299.             objectBallDir.x /= oLen;
  4300.             objectBallDir.y /= oLen;
  4301.         }
  4302.  
  4303.         const float PRIMARY_LEN = 150.0f; //default=150.0f
  4304.         const float SECONDARY_LEN = 150.0f; //default=150.0f
  4305.         const float STRAIGHT_EPSILON = BALL_RADIUS * 0.05f;
  4306.  
  4307.         D2D1_POINT_2F primaryEnd = {
  4308.             targetStartPoint.x + dir.x * PRIMARY_LEN,
  4309.             targetStartPoint.y + dir.y * PRIMARY_LEN
  4310.         };
  4311.  
  4312.         // Secondary line starts from the contact ball's center
  4313.         D2D1_POINT_2F secondaryStart = contactBallCenter;
  4314.         D2D1_POINT_2F secondaryEnd = {
  4315.             secondaryStart.x + objectBallDir.x * SECONDARY_LEN,
  4316.             secondaryStart.y + objectBallDir.y * SECONDARY_LEN
  4317.         };
  4318.  
  4319.         if (absOffset < STRAIGHT_EPSILON)  // straight shot?
  4320.         {
  4321.             // Straight: secondary behind primary
  4322.                     // secondary behind primary {pDashedStyle param at end}
  4323.             pRT->DrawLine(secondaryStart, secondaryEnd, pPurpleBrush, 2.0f);
  4324.             //pRT->DrawLine(secondaryStart, secondaryEnd, pGhostBrush, 1.0f);
  4325.             pRT->DrawLine(targetStartPoint, primaryEnd, pCyanBrush, 2.0f);
  4326.             //pRT->DrawLine(targetStartPoint, primaryEnd, pBrush, 1.0f);
  4327.         }
  4328.         else
  4329.         {
  4330.             // Cut shot: both visible
  4331.                     // both visible for cut shot
  4332.             pRT->DrawLine(secondaryStart, secondaryEnd, pPurpleBrush, 2.0f);
  4333.             //pRT->DrawLine(secondaryStart, secondaryEnd, pGhostBrush, 1.0f);
  4334.             pRT->DrawLine(targetStartPoint, primaryEnd, pCyanBrush, 2.0f);
  4335.             //pRT->DrawLine(targetStartPoint, primaryEnd, pBrush, 1.0f);
  4336.         }
  4337.         // End improved trajectory logic
  4338.  
  4339.     //new code end
  4340.  
  4341.         // -- Cue Ball Path after collision (Optional, requires physics) --
  4342.         // Very simplified: Assume cue deflects, angle depends on cut angle.
  4343.         // float cutAngle = acosf(cosf(cueAngle - targetProjectionAngle)); // Angle between paths
  4344.         // float cueDeflectionAngle = ? // Depends on cutAngle, spin, etc. Hard to predict accurately.
  4345.         // D2D1_POINT_2F cueProjectionEnd = ...
  4346.         // pRT->DrawLine(ballCollisionPoint, cueProjectionEnd, pGhostBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  4347.  
  4348.         // --- Accuracy Comment ---
  4349.         // Note: The visual accuracy of this projection, especially for cut shots (hitting the ball off-center)
  4350.         // or shots with spin, is limited by the simplified physics model. Real pool physics involves
  4351.         // collision-induced throw, spin transfer, and cue ball deflection not fully simulated here.
  4352.         // The ghost ball method shows the *ideal* line for a center-cue hit without spin.
  4353.  
  4354.     }
  4355.     else if (aimingAtRail && hitRailIndex != -1) {
  4356.         // Aiming at a rail: Draw reflection line
  4357.         float reflectAngle = cueAngle;
  4358.         // Reflect angle based on which rail was hit
  4359.         if (hitRailIndex == 0 || hitRailIndex == 1) { // Left or Right rail
  4360.             reflectAngle = PI - cueAngle; // Reflect horizontal component
  4361.         }
  4362.         else { // Top or Bottom rail
  4363.             reflectAngle = -cueAngle; // Reflect vertical component
  4364.         }
  4365.         // Normalize angle if needed (atan2 usually handles this)
  4366.         while (reflectAngle > PI) reflectAngle -= 2 * PI;
  4367.         while (reflectAngle <= -PI) reflectAngle += 2 * PI;
  4368.  
  4369.  
  4370.         float reflectionLength = 60.0f; // Length of the reflection line
  4371.         D2D1_POINT_2F reflectionEnd = D2D1::Point2F(
  4372.             finalLineEnd.x + cosf(reflectAngle) * reflectionLength,
  4373.             finalLineEnd.y + sinf(reflectAngle) * reflectionLength
  4374.         );
  4375.  
  4376.         // Draw the reflection line (e.g., using a different color/style)
  4377.         pRT->DrawLine(finalLineEnd, reflectionEnd, pReflectBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  4378.     }
  4379.  
  4380.     // Release resources
  4381.     SafeRelease(&pBrush);
  4382.     SafeRelease(&pGhostBrush);
  4383.     SafeRelease(&pCueBrush);
  4384.     SafeRelease(&pReflectBrush); // Release new brush
  4385.     SafeRelease(&pCyanBrush);
  4386.     SafeRelease(&pPurpleBrush);
  4387.     SafeRelease(&pDashedStyle);
  4388. }
  4389.  
  4390.  
  4391. void DrawUI(ID2D1RenderTarget* pRT) {
  4392.     if (!pTextFormat || !pLargeTextFormat) return;
  4393.  
  4394.     ID2D1SolidColorBrush* pBrush = nullptr;
  4395.     pRT->CreateSolidColorBrush(UI_TEXT_COLOR, &pBrush);
  4396.     if (!pBrush) return;
  4397.  
  4398.     //new code
  4399.     // --- Always draw AI's 8?Ball call arrow when it's Player?2's turn and AI has called ---
  4400.     //if (isPlayer2AI && currentPlayer == 2 && calledPocketP2 >= 0) {
  4401.         // FIX: This condition correctly shows the AI's called pocket arrow.
  4402.     if (isPlayer2AI && IsPlayerOnEightBall(2) && calledPocketP2 >= 0) {
  4403.         // pocket index that AI called
  4404.         int idx = calledPocketP2;
  4405.         // draw large blue arrow
  4406.         ID2D1SolidColorBrush* pArrow = nullptr;
  4407.         pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrow);
  4408.         if (pArrow) {
  4409.             auto P = pocketPositions[idx];
  4410.             D2D1_POINT_2F tri[3] = {
  4411.                 { P.x - 15.0f, P.y - 40.0f },
  4412.                 { P.x + 15.0f, P.y - 40.0f },
  4413.                 { P.x       , P.y - 10.0f }
  4414.             };
  4415.             ID2D1PathGeometry* geom = nullptr;
  4416.             pFactory->CreatePathGeometry(&geom);
  4417.             ID2D1GeometrySink* sink = nullptr;
  4418.             geom->Open(&sink);
  4419.             sink->BeginFigure(tri[0], D2D1_FIGURE_BEGIN_FILLED);
  4420.             sink->AddLines(&tri[1], 2);
  4421.             sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  4422.             sink->Close();
  4423.             pRT->FillGeometry(geom, pArrow);
  4424.             SafeRelease(&sink);
  4425.             SafeRelease(&geom);
  4426.             SafeRelease(&pArrow);
  4427.         }
  4428.         // draw “Choose a pocket...” prompt
  4429.         D2D1_RECT_F txt = D2D1::RectF(
  4430.             TABLE_LEFT,
  4431.             TABLE_BOTTOM + CUSHION_THICKNESS + 5.0f,
  4432.             TABLE_RIGHT,
  4433.             TABLE_BOTTOM + CUSHION_THICKNESS + 30.0f
  4434.         );
  4435.         pRT->DrawText(
  4436.             L"AI has called this pocket",
  4437.             (UINT32)wcslen(L"AI has called this pocket"),
  4438.             pTextFormat,
  4439.             &txt,
  4440.             pBrush
  4441.         );
  4442.         // note: no return here — we still draw fouls/turn text underneath
  4443.     }
  4444.     //end new code
  4445.  
  4446.     // --- Player Info Area (Top Left/Right) --- (Unchanged)
  4447.     float uiTop = TABLE_TOP - 80;
  4448.     float uiHeight = 60;
  4449.     float p1Left = TABLE_LEFT;
  4450.     float p1Width = 150;
  4451.     float p2Left = TABLE_RIGHT - p1Width;
  4452.     D2D1_RECT_F p1Rect = D2D1::RectF(p1Left, uiTop, p1Left + p1Width, uiTop + uiHeight);
  4453.     D2D1_RECT_F p2Rect = D2D1::RectF(p2Left, uiTop, p2Left + p1Width, uiTop + uiHeight);
  4454.  
  4455.     // Player 1 Info Text (Unchanged)
  4456.     std::wostringstream oss1;
  4457.     oss1 << player1Info.name.c_str();
  4458.     if (player1Info.assignedType != BallType::NONE) {
  4459.         if (IsPlayerOnEightBall(1)) {
  4460.             oss1 << L"\nON 8-BALL";
  4461.         }
  4462.         else {
  4463.             oss1 << L"\n" << ((player1Info.assignedType == BallType::SOLID) ? L"Solids" : L"Stripes");
  4464.             oss1 << L" [" << player1Info.ballsPocketedCount << L"/7]";
  4465.         }
  4466.     }
  4467.     else {
  4468.         oss1 << L"\n(Undecided)";
  4469.     }
  4470.     pRT->DrawText(oss1.str().c_str(), (UINT32)oss1.str().length(), pTextFormat, &p1Rect, pBrush);
  4471.     // Draw Player 1 Side Ball
  4472.     if (player1Info.assignedType != BallType::NONE)
  4473.     {
  4474.         D2D1_POINT_2F ballCenter = D2D1::Point2F(p1Rect.right + 15.0f, p1Rect.top + uiHeight / 2.0f);
  4475.         float radius = 10.0f;
  4476.         D2D1_ELLIPSE ball = D2D1::Ellipse(ballCenter, radius, radius);
  4477.  
  4478.         if (IsPlayerOnEightBall(1))
  4479.         {
  4480.             // Player is on the 8-ball, draw the 8-ball indicator.
  4481.             ID2D1SolidColorBrush* p8BallBrush = nullptr;
  4482.             pRT->CreateSolidColorBrush(EIGHT_BALL_COLOR, &p8BallBrush);
  4483.             if (p8BallBrush) pRT->FillEllipse(&ball, p8BallBrush);
  4484.             SafeRelease(&p8BallBrush);
  4485.  
  4486.             // Draw the number '8' decal
  4487.             ID2D1SolidColorBrush* pNumWhite = nullptr, * pNumBlack = nullptr;
  4488.             pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pNumWhite);
  4489.             pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pNumBlack);
  4490.             if (pBallNumFormat && pNumWhite && pNumBlack)
  4491.             {
  4492.                 const float decalR = radius * 0.7f;
  4493.                 D2D1_ELLIPSE decal = D2D1::Ellipse(ballCenter, decalR, decalR);
  4494.                 pRT->FillEllipse(&decal, pNumWhite);
  4495.                 pRT->DrawEllipse(&decal, pNumBlack, 0.8f);
  4496.                 wchar_t numText[] = L"8";
  4497.                 D2D1_RECT_F layout = { ballCenter.x - decalR, ballCenter.y - decalR, ballCenter.x + decalR, ballCenter.y + decalR };
  4498.                 pRT->DrawText(numText, (UINT32)wcslen(numText), pBallNumFormat, &layout, pNumBlack);
  4499.             }
  4500.  
  4501.             // If stripes, draw a stripe band
  4502.             SafeRelease(&pNumWhite);
  4503.             SafeRelease(&pNumBlack);
  4504.         }
  4505.         else
  4506.         {
  4507.             // Default: Draw the player's assigned ball type (solid/stripe).
  4508.             ID2D1SolidColorBrush* pBallBrush = nullptr;
  4509.             D2D1_COLOR_F ballColor = (player1Info.assignedType == BallType::SOLID) ?
  4510.                 D2D1::ColorF(1.0f, 1.0f, 0.0f) : D2D1::ColorF(1.0f, 0.0f, 0.0f);
  4511.             pRT->CreateSolidColorBrush(ballColor, &pBallBrush);
  4512.             if (pBallBrush)
  4513.             {
  4514.                 pRT->FillEllipse(&ball, pBallBrush);
  4515.                 SafeRelease(&pBallBrush);
  4516.                 if (player1Info.assignedType == BallType::STRIPE)
  4517.                 {
  4518.                     ID2D1SolidColorBrush* pStripeBrush = nullptr;
  4519.                     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
  4520.                     if (pStripeBrush)
  4521.                     {
  4522.                         D2D1_RECT_F stripeRect = { ballCenter.x - radius, ballCenter.y - 3.0f, ballCenter.x + radius, ballCenter.y + 3.0f };
  4523.                         pRT->FillRectangle(&stripeRect, pStripeBrush);
  4524.                         SafeRelease(&pStripeBrush);
  4525.                     }
  4526.                 }
  4527.             }
  4528.         }
  4529.         // Draw a border around the indicator ball, regardless of type.
  4530.         ID2D1SolidColorBrush* pBorderBrush = nullptr;
  4531.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
  4532.         if (pBorderBrush) pRT->DrawEllipse(&ball, pBorderBrush, 1.5f);
  4533.         SafeRelease(&pBorderBrush);
  4534.                 }
  4535.             //}
  4536.         //}
  4537.     //}
  4538.  
  4539.  
  4540.     // Player 2 Info Text (Unchanged)
  4541.     std::wostringstream oss2;
  4542.     oss2 << player2Info.name.c_str();
  4543.     if (player2Info.assignedType != BallType::NONE) {
  4544.         if (IsPlayerOnEightBall(2)) {
  4545.             oss2 << L"\nON 8-BALL";
  4546.         }
  4547.         else {
  4548.             oss2 << L"\n" << ((player2Info.assignedType == BallType::SOLID) ? L"Solids" : L"Stripes");
  4549.             oss2 << L" [" << player2Info.ballsPocketedCount << L"/7]";
  4550.         }
  4551.     }
  4552.     else {
  4553.         oss2 << L"\n(Undecided)";
  4554.     }
  4555.  
  4556.     pRT->DrawText(oss2.str().c_str(), (UINT32)oss2.str().length(), pTextFormat, &p2Rect, pBrush);
  4557.  
  4558.     // Draw Player 2 Side Ball
  4559.     if (player2Info.assignedType != BallType::NONE)
  4560.     {
  4561.         D2D1_POINT_2F ballCenter = D2D1::Point2F(p2Rect.left - 15.0f, p2Rect.top + uiHeight / 2.0f);
  4562.         float radius = 10.0f;
  4563.         D2D1_ELLIPSE ball = D2D1::Ellipse(ballCenter, radius, radius);
  4564.  
  4565.         if (IsPlayerOnEightBall(2))
  4566.         {
  4567.             // Player is on the 8-ball, draw the 8-ball indicator.
  4568.             ID2D1SolidColorBrush* p8BallBrush = nullptr;
  4569.             pRT->CreateSolidColorBrush(EIGHT_BALL_COLOR, &p8BallBrush);
  4570.             if (p8BallBrush) pRT->FillEllipse(&ball, p8BallBrush);
  4571.             SafeRelease(&p8BallBrush);
  4572.  
  4573.             // Draw the number '8' decal
  4574.             ID2D1SolidColorBrush* pNumWhite = nullptr, * pNumBlack = nullptr;
  4575.             pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pNumWhite);
  4576.             pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pNumBlack);
  4577.             if (pBallNumFormat && pNumWhite && pNumBlack)
  4578.             {
  4579.                 const float decalR = radius * 0.7f;
  4580.                 D2D1_ELLIPSE decal = D2D1::Ellipse(ballCenter, decalR, decalR);
  4581.                 pRT->FillEllipse(&decal, pNumWhite);
  4582.                 pRT->DrawEllipse(&decal, pNumBlack, 0.8f);
  4583.                 wchar_t numText[] = L"8";
  4584.                 D2D1_RECT_F layout = { ballCenter.x - decalR, ballCenter.y - decalR, ballCenter.x + decalR, ballCenter.y + decalR };
  4585.                 pRT->DrawText(numText, (UINT32)wcslen(numText), pBallNumFormat, &layout, pNumBlack);
  4586.             }
  4587.  
  4588.             // If stripes, draw a stripe band
  4589.             SafeRelease(&pNumWhite);
  4590.             SafeRelease(&pNumBlack);
  4591.         }
  4592.         else
  4593.         {
  4594.             // Default: Draw the player's assigned ball type (solid/stripe).
  4595.             ID2D1SolidColorBrush* pBallBrush = nullptr;
  4596.             D2D1_COLOR_F ballColor = (player2Info.assignedType == BallType::SOLID) ?
  4597.                 D2D1::ColorF(1.0f, 1.0f, 0.0f) : D2D1::ColorF(1.0f, 0.0f, 0.0f);
  4598.             pRT->CreateSolidColorBrush(ballColor, &pBallBrush);
  4599.             if (pBallBrush)
  4600.             {
  4601.                 pRT->FillEllipse(&ball, pBallBrush);
  4602.                 SafeRelease(&pBallBrush);
  4603.                 if (player2Info.assignedType == BallType::STRIPE)
  4604.                 {
  4605.                     ID2D1SolidColorBrush* pStripeBrush = nullptr;
  4606.                     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
  4607.                     if (pStripeBrush)
  4608.                     {
  4609.                         D2D1_RECT_F stripeRect = { ballCenter.x - radius, ballCenter.y - 3.0f, ballCenter.x + radius, ballCenter.y + 3.0f };
  4610.                         pRT->FillRectangle(&stripeRect, pStripeBrush);
  4611.                         SafeRelease(&pStripeBrush);
  4612.                     }
  4613.                 }
  4614.             }
  4615.         }
  4616.     //}
  4617.  
  4618.     // Draw a border around the indicator ball, regardless of type.
  4619.     ID2D1SolidColorBrush* pBorderBrush = nullptr;
  4620.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
  4621.     if (pBorderBrush) pRT->DrawEllipse(&ball, pBorderBrush, 1.5f);
  4622.     SafeRelease(&pBorderBrush);
  4623.     }
  4624.  
  4625.     // --- MODIFIED: Current Turn Arrow (Blue, Bigger, Beside Name) ---
  4626.     ID2D1SolidColorBrush* pArrowBrush = nullptr;
  4627.     pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrowBrush);
  4628.     if (pArrowBrush && currentGameState != GAME_OVER && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  4629.         float arrowSizeBase = 32.0f; // Base size for width/height offsets (4x original ~8)
  4630.         float arrowCenterY = p1Rect.top + uiHeight / 2.0f; // Center vertically with text box
  4631.         float arrowTipX, arrowBackX;
  4632.  
  4633.         D2D1_RECT_F playerBox = (currentPlayer == 1) ? p1Rect : p2Rect;
  4634.         arrowBackX = playerBox.left - 25.0f;
  4635.         arrowTipX = arrowBackX + arrowSizeBase * 0.75f;
  4636.  
  4637.         float notchDepth = 12.0f;  // Increased from 6.0f to make the rectangle longer
  4638.         float notchWidth = 10.0f;
  4639.  
  4640.         float cx = arrowBackX;
  4641.         float cy = arrowCenterY;
  4642.  
  4643.         // Define triangle + rectangle tail shape
  4644.         D2D1_POINT_2F tip = D2D1::Point2F(arrowTipX, cy);                           // tip
  4645.         D2D1_POINT_2F baseTop = D2D1::Point2F(cx, cy - arrowSizeBase / 2.0f);          // triangle top
  4646.         D2D1_POINT_2F baseBot = D2D1::Point2F(cx, cy + arrowSizeBase / 2.0f);          // triangle bottom
  4647.  
  4648.         // Rectangle coordinates for the tail portion:
  4649.         D2D1_POINT_2F r1 = D2D1::Point2F(cx - notchDepth, cy - notchWidth / 2.0f);   // rect top-left
  4650.         D2D1_POINT_2F r2 = D2D1::Point2F(cx, cy - notchWidth / 2.0f);                 // rect top-right
  4651.         D2D1_POINT_2F r3 = D2D1::Point2F(cx, cy + notchWidth / 2.0f);                 // rect bottom-right
  4652.         D2D1_POINT_2F r4 = D2D1::Point2F(cx - notchDepth, cy + notchWidth / 2.0f);    // rect bottom-left
  4653.  
  4654.         ID2D1PathGeometry* pPath = nullptr;
  4655.         if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  4656.             ID2D1GeometrySink* pSink = nullptr;
  4657.             if (SUCCEEDED(pPath->Open(&pSink))) {
  4658.                 pSink->BeginFigure(tip, D2D1_FIGURE_BEGIN_FILLED);
  4659.                 pSink->AddLine(baseTop);
  4660.                 pSink->AddLine(r2); // transition from triangle into rectangle
  4661.                 pSink->AddLine(r1);
  4662.                 pSink->AddLine(r4);
  4663.                 pSink->AddLine(r3);
  4664.                 pSink->AddLine(baseBot);
  4665.                 pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  4666.                 pSink->Close();
  4667.                 SafeRelease(&pSink);
  4668.                 pRT->FillGeometry(pPath, pArrowBrush);
  4669.             }
  4670.             SafeRelease(&pPath);
  4671.         }
  4672.  
  4673.  
  4674.         SafeRelease(&pArrowBrush);
  4675.     }
  4676.  
  4677.     //original
  4678. /*
  4679.     // --- MODIFIED: Current Turn Arrow (Blue, Bigger, Beside Name) ---
  4680.     ID2D1SolidColorBrush* pArrowBrush = nullptr;
  4681.     pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrowBrush);
  4682.     if (pArrowBrush && currentGameState != GAME_OVER && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  4683.         float arrowSizeBase = 32.0f; // Base size for width/height offsets (4x original ~8)
  4684.         float arrowCenterY = p1Rect.top + uiHeight / 2.0f; // Center vertically with text box
  4685.         float arrowTipX, arrowBackX;
  4686.  
  4687.         if (currentPlayer == 1) {
  4688. arrowBackX = p1Rect.left - 25.0f; // Position left of the box
  4689.             arrowTipX = arrowBackX + arrowSizeBase * 0.75f; // Pointy end extends right
  4690.             // Define points for right-pointing arrow
  4691.             //D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
  4692.             //D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
  4693.             //D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
  4694.             // Enhanced arrow with base rectangle intersection
  4695.     float notchDepth = 6.0f; // Depth of square base "stem"
  4696.     float notchWidth = 4.0f; // Thickness of square part
  4697.  
  4698.     D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
  4699.     D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
  4700.     D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX - notchDepth, arrowCenterY - notchWidth / 2.0f); // Square Left-Top
  4701.     D2D1_POINT_2F pt4 = D2D1::Point2F(arrowBackX - notchDepth, arrowCenterY + notchWidth / 2.0f); // Square Left-Bottom
  4702.     D2D1_POINT_2F pt5 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
  4703.  
  4704.  
  4705.     ID2D1PathGeometry* pPath = nullptr;
  4706.     if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  4707.         ID2D1GeometrySink* pSink = nullptr;
  4708.         if (SUCCEEDED(pPath->Open(&pSink))) {
  4709.             pSink->BeginFigure(pt1, D2D1_FIGURE_BEGIN_FILLED);
  4710.             pSink->AddLine(pt2);
  4711.             pSink->AddLine(pt3);
  4712.             pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  4713.             pSink->Close();
  4714.             SafeRelease(&pSink);
  4715.             pRT->FillGeometry(pPath, pArrowBrush);
  4716.         }
  4717.         SafeRelease(&pPath);
  4718.     }
  4719.         }
  4720.  
  4721.  
  4722.         //==================else player 2
  4723.         else { // Player 2
  4724.          // Player 2: Arrow left of P2 box, pointing right (or right of P2 box pointing left?)
  4725.          // Let's keep it consistent: Arrow left of the active player's box, pointing right.
  4726. // Let's keep it consistent: Arrow left of the active player's box, pointing right.
  4727. arrowBackX = p2Rect.left - 25.0f; // Position left of the box
  4728. arrowTipX = arrowBackX + arrowSizeBase * 0.75f; // Pointy end extends right
  4729. // Define points for right-pointing arrow
  4730. D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
  4731. D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
  4732. D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
  4733.  
  4734. ID2D1PathGeometry* pPath = nullptr;
  4735. if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  4736.     ID2D1GeometrySink* pSink = nullptr;
  4737.     if (SUCCEEDED(pPath->Open(&pSink))) {
  4738.         pSink->BeginFigure(pt1, D2D1_FIGURE_BEGIN_FILLED);
  4739.         pSink->AddLine(pt2);
  4740.         pSink->AddLine(pt3);
  4741.         pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  4742.         pSink->Close();
  4743.         SafeRelease(&pSink);
  4744.         pRT->FillGeometry(pPath, pArrowBrush);
  4745.     }
  4746.     SafeRelease(&pPath);
  4747. }
  4748.         }
  4749.         */
  4750.  
  4751.  
  4752.         // --- Persistent Blue 8?Ball Call Arrow & Prompt ---
  4753.     /*if (calledPocketP1 >= 0 || calledPocketP2 >= 0)
  4754.     {
  4755.         // determine index (default top?right)
  4756.         int idx = (currentPlayer == 1 ? calledPocketP1 : calledPocketP2);
  4757.         if (idx < 0) idx = (currentPlayer == 1 ? calledPocketP2 : calledPocketP1);
  4758.         if (idx < 0) idx = 2;
  4759.  
  4760.         // draw large blue arrow
  4761.         ID2D1SolidColorBrush* pArrow = nullptr;
  4762.         pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrow);
  4763.         if (pArrow) {
  4764.             auto P = pocketPositions[idx];
  4765.             D2D1_POINT_2F tri[3] = {
  4766.                 {P.x - 15.0f, P.y - 40.0f},
  4767.                 {P.x + 15.0f, P.y - 40.0f},
  4768.                 {P.x       , P.y - 10.0f}
  4769.             };
  4770.             ID2D1PathGeometry* geom = nullptr;
  4771.             pFactory->CreatePathGeometry(&geom);
  4772.             ID2D1GeometrySink* sink = nullptr;
  4773.             geom->Open(&sink);
  4774.             sink->BeginFigure(tri[0], D2D1_FIGURE_BEGIN_FILLED);
  4775.             sink->AddLines(&tri[1], 2);
  4776.             sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  4777.             sink->Close();
  4778.             pRT->FillGeometry(geom, pArrow);
  4779.             SafeRelease(&sink); SafeRelease(&geom); SafeRelease(&pArrow);
  4780.         }
  4781.  
  4782.         // draw prompt
  4783.         D2D1_RECT_F txt = D2D1::RectF(
  4784.             TABLE_LEFT,
  4785.             TABLE_BOTTOM + CUSHION_THICKNESS + 5.0f,
  4786.             TABLE_RIGHT,
  4787.             TABLE_BOTTOM + CUSHION_THICKNESS + 30.0f
  4788.         );
  4789.         pRT->DrawText(
  4790.             L"Choose a pocket...",
  4791.             (UINT32)wcslen(L"Choose a pocket..."),
  4792.             pTextFormat,
  4793.             &txt,
  4794.             pBrush
  4795.         );
  4796.     }*/
  4797.  
  4798.     // --- Persistent Blue 8?Ball Pocket Arrow & Prompt (once called) ---
  4799. /* if (calledPocketP1 >= 0 || calledPocketP2 >= 0)
  4800. {
  4801.     // 1) Determine pocket index
  4802.     int idx = (currentPlayer == 1 ? calledPocketP1 : calledPocketP2);
  4803.     // If the other player had called but it's now your turn, still show that call
  4804.     if (idx < 0) idx = (currentPlayer == 1 ? calledPocketP2 : calledPocketP1);
  4805.     if (idx < 0) idx = 2; // default to top?right if somehow still unset
  4806.  
  4807.     // 2) Draw large blue arrow
  4808.     ID2D1SolidColorBrush* pArrow = nullptr;
  4809.     pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrow);
  4810.     if (pArrow) {
  4811.         auto P = pocketPositions[idx];
  4812.         D2D1_POINT_2F tri[3] = {
  4813.             { P.x - 15.0f, P.y - 40.0f },
  4814.             { P.x + 15.0f, P.y - 40.0f },
  4815.             { P.x       , P.y - 10.0f }
  4816.         };
  4817.         ID2D1PathGeometry* geom = nullptr;
  4818.         pFactory->CreatePathGeometry(&geom);
  4819.         ID2D1GeometrySink* sink = nullptr;
  4820.         geom->Open(&sink);
  4821.         sink->BeginFigure(tri[0], D2D1_FIGURE_BEGIN_FILLED);
  4822.         sink->AddLines(&tri[1], 2);
  4823.         sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  4824.         sink->Close();
  4825.         pRT->FillGeometry(geom, pArrow);
  4826.         SafeRelease(&sink);
  4827.         SafeRelease(&geom);
  4828.         SafeRelease(&pArrow);
  4829.     }
  4830.  
  4831.     // 3) Draw persistent prompt text
  4832.     D2D1_RECT_F txt = D2D1::RectF(
  4833.         TABLE_LEFT,
  4834.         TABLE_BOTTOM + CUSHION_THICKNESS + 5.0f,
  4835.         TABLE_RIGHT,
  4836.         TABLE_BOTTOM + CUSHION_THICKNESS + 30.0f
  4837.     );
  4838.     pRT->DrawText(
  4839.         L"Choose a pocket...",
  4840.         (UINT32)wcslen(L"Choose a pocket..."),
  4841.         pTextFormat,
  4842.         &txt,
  4843.         pBrush
  4844.     );
  4845.     // Note: no 'return'; allow foul/turn text to draw beneath if needed
  4846. } */
  4847.  
  4848. // new code ends here
  4849.  
  4850.     // --- MODIFIED: Foul Text (Large Red, Bottom Center) ---
  4851.     if (foulCommitted && currentGameState != SHOT_IN_PROGRESS) {
  4852.         ID2D1SolidColorBrush* pFoulBrush = nullptr;
  4853.         pRT->CreateSolidColorBrush(FOUL_TEXT_COLOR, &pFoulBrush);
  4854.         if (pFoulBrush && pLargeTextFormat) {
  4855.             // Calculate Rect for bottom-middle area
  4856.             float foulWidth = 200.0f; // Adjust width as needed
  4857.             float foulHeight = 60.0f;
  4858.             float foulLeft = TABLE_LEFT + (TABLE_WIDTH / 2.0f) - (foulWidth / 2.0f);
  4859.             // Position below the pocketed balls bar
  4860.             float foulTop = pocketedBallsBarRect.bottom + 10.0f;
  4861.             D2D1_RECT_F foulRect = D2D1::RectF(foulLeft, foulTop, foulLeft + foulWidth, foulTop + foulHeight);
  4862.  
  4863.             // --- Set text alignment to center for foul text ---
  4864.             pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  4865.             pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  4866.  
  4867.             pRT->DrawText(L"FOUL!", 5, pLargeTextFormat, &foulRect, pFoulBrush);
  4868.  
  4869.             // --- Restore default alignment for large text if needed elsewhere ---
  4870.             // pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
  4871.             // pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  4872.  
  4873.             SafeRelease(&pFoulBrush);
  4874.         }
  4875.     }
  4876.  
  4877.     // --- Blue Arrow & Prompt for 8?Ball Call (while choosing or after called) ---
  4878.     if ((currentGameState == CHOOSING_POCKET_P1
  4879.         || currentGameState == CHOOSING_POCKET_P2)
  4880.         || (calledPocketP1 >= 0 || calledPocketP2 >= 0))
  4881.     {
  4882.         // determine index:
  4883.         //  - if a call exists, use it
  4884.         //  - if still choosing, use hover if any
  4885.         // determine index: use only the clicked call; default to top?right if unset
  4886.         int idx = (currentPlayer == 1 ? calledPocketP1 : calledPocketP2);
  4887.         if (idx < 0) idx = 2;
  4888.  
  4889.         // draw large blue arrow
  4890.         ID2D1SolidColorBrush* pArrow = nullptr;
  4891.         pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrow);
  4892.         if (pArrow) {
  4893.             auto P = pocketPositions[idx];
  4894.             D2D1_POINT_2F tri[3] = {
  4895.                 {P.x - 15.0f, P.y - 40.0f},
  4896.                 {P.x + 15.0f, P.y - 40.0f},
  4897.                 {P.x       , P.y - 10.0f}
  4898.             };
  4899.             ID2D1PathGeometry* geom = nullptr;
  4900.             pFactory->CreatePathGeometry(&geom);
  4901.             ID2D1GeometrySink* sink = nullptr;
  4902.             geom->Open(&sink);
  4903.             sink->BeginFigure(tri[0], D2D1_FIGURE_BEGIN_FILLED);
  4904.             sink->AddLines(&tri[1], 2);
  4905.             sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  4906.             sink->Close();
  4907.             pRT->FillGeometry(geom, pArrow);
  4908.             SafeRelease(&sink); SafeRelease(&geom); SafeRelease(&pArrow);
  4909.         }
  4910.  
  4911.         // draw prompt below pockets
  4912.         D2D1_RECT_F txt = D2D1::RectF(
  4913.             TABLE_LEFT,
  4914.             TABLE_BOTTOM + CUSHION_THICKNESS + 5.0f,
  4915.             TABLE_RIGHT,
  4916.             TABLE_BOTTOM + CUSHION_THICKNESS + 30.0f
  4917.         );
  4918.         pRT->DrawText(
  4919.             L"Choose a pocket...",
  4920.             (UINT32)wcslen(L"Choose a pocket..."),
  4921.             pTextFormat,
  4922.             &txt,
  4923.             pBrush
  4924.         );
  4925.         // do NOT return here; allow foul/turn text to display under the arrow
  4926.     }
  4927.  
  4928.     // Removed Obsolete
  4929.     /*
  4930.     // --- 8-Ball Pocket Selection Arrow & Prompt ---
  4931.     if (currentGameState == CHOOSING_POCKET_P1 || currentGameState == CHOOSING_POCKET_P2) {
  4932.         // Determine which pocket to highlight (default to Top-Right if unset)
  4933.         int idx = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  4934.         if (idx < 0) idx = 2;
  4935.  
  4936.         // Draw the downward arrow
  4937.         ID2D1SolidColorBrush* pArrowBrush = nullptr;
  4938.         pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrowBrush);
  4939.         if (pArrowBrush) {
  4940.             D2D1_POINT_2F P = pocketPositions[idx];
  4941.             D2D1_POINT_2F tri[3] = {
  4942.                 {P.x - 10.0f, P.y - 30.0f},
  4943.                 {P.x + 10.0f, P.y - 30.0f},
  4944.                 {P.x        , P.y - 10.0f}
  4945.             };
  4946.             ID2D1PathGeometry* geom = nullptr;
  4947.             pFactory->CreatePathGeometry(&geom);
  4948.             ID2D1GeometrySink* sink = nullptr;
  4949.             geom->Open(&sink);
  4950.             sink->BeginFigure(tri[0], D2D1_FIGURE_BEGIN_FILLED);
  4951.             sink->AddLines(&tri[1], 2);
  4952.             sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  4953.             sink->Close();
  4954.             pRT->FillGeometry(geom, pArrowBrush);
  4955.             SafeRelease(&sink);
  4956.             SafeRelease(&geom);
  4957.             SafeRelease(&pArrowBrush);
  4958.         }
  4959.  
  4960.         // Draw “Choose a pocket...” text under the table
  4961.         D2D1_RECT_F prompt = D2D1::RectF(
  4962.             TABLE_LEFT,
  4963.             TABLE_BOTTOM + CUSHION_THICKNESS + 5.0f,
  4964.             TABLE_RIGHT,
  4965.             TABLE_BOTTOM + CUSHION_THICKNESS + 30.0f
  4966.         );
  4967.         pRT->DrawText(
  4968.             L"Choose a pocket...",
  4969.             (UINT32)wcslen(L"Choose a pocket..."),
  4970.             pTextFormat,
  4971.             &prompt,
  4972.             pBrush
  4973.         );
  4974.  
  4975.         return; // Skip normal turn/foul text
  4976.     }
  4977.     */
  4978.  
  4979.  
  4980.     // Show AI Thinking State (Unchanged from previous step)
  4981.     if (currentGameState == AI_THINKING && pTextFormat) {
  4982.         ID2D1SolidColorBrush* pThinkingBrush = nullptr;
  4983.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Orange), &pThinkingBrush);
  4984.         if (pThinkingBrush) {
  4985.             D2D1_RECT_F thinkingRect = p2Rect;
  4986.             thinkingRect.top += 20; // Offset within P2 box
  4987.             // Ensure default text alignment for this
  4988.             pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  4989.             pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  4990.             pRT->DrawText(L"Thinking...", 11, pTextFormat, &thinkingRect, pThinkingBrush);
  4991.             SafeRelease(&pThinkingBrush);
  4992.         }
  4993.     }
  4994.  
  4995.     SafeRelease(&pBrush);
  4996.  
  4997.     // --- Draw CHEAT MODE label if active ---
  4998.     if (cheatModeEnabled) {
  4999.         ID2D1SolidColorBrush* pCheatBrush = nullptr;
  5000.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Red), &pCheatBrush);
  5001.         if (pCheatBrush && pTextFormat) {
  5002.             D2D1_RECT_F cheatTextRect = D2D1::RectF(
  5003.                 TABLE_LEFT + 10.0f,
  5004.                 TABLE_TOP + 10.0f,
  5005.                 TABLE_LEFT + 200.0f,
  5006.                 TABLE_TOP + 40.0f
  5007.             );
  5008.             pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
  5009.             pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
  5010.             pRT->DrawText(L"CHEAT MODE ON", wcslen(L"CHEAT MODE ON"), pTextFormat, &cheatTextRect, pCheatBrush);
  5011.         }
  5012.         SafeRelease(&pCheatBrush);
  5013.     }
  5014. }
  5015.  
  5016. void DrawPowerMeter(ID2D1RenderTarget* pRT) {
  5017.     // Draw Border
  5018.     ID2D1SolidColorBrush* pBorderBrush = nullptr;
  5019.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
  5020.     if (!pBorderBrush) return;
  5021.     pRT->DrawRectangle(&powerMeterRect, pBorderBrush, 2.0f);
  5022.     SafeRelease(&pBorderBrush);
  5023.  
  5024.     // Create Gradient Fill
  5025.     ID2D1GradientStopCollection* pGradientStops = nullptr;
  5026.     ID2D1LinearGradientBrush* pGradientBrush = nullptr;
  5027.     D2D1_GRADIENT_STOP gradientStops[4];
  5028.     gradientStops[0].position = 0.0f;
  5029.     gradientStops[0].color = D2D1::ColorF(D2D1::ColorF::Green);
  5030.     gradientStops[1].position = 0.45f;
  5031.     gradientStops[1].color = D2D1::ColorF(D2D1::ColorF::Yellow);
  5032.     gradientStops[2].position = 0.7f;
  5033.     gradientStops[2].color = D2D1::ColorF(D2D1::ColorF::Orange);
  5034.     gradientStops[3].position = 1.0f;
  5035.     gradientStops[3].color = D2D1::ColorF(D2D1::ColorF::Red);
  5036.  
  5037.     pRT->CreateGradientStopCollection(gradientStops, 4, &pGradientStops);
  5038.     if (pGradientStops) {
  5039.         D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props = {};
  5040.         props.startPoint = D2D1::Point2F(powerMeterRect.left, powerMeterRect.bottom);
  5041.         props.endPoint = D2D1::Point2F(powerMeterRect.left, powerMeterRect.top);
  5042.         pRT->CreateLinearGradientBrush(props, pGradientStops, &pGradientBrush);
  5043.         SafeRelease(&pGradientStops);
  5044.     }
  5045.  
  5046.     // Calculate Fill Height
  5047.     float fillRatio = 0;
  5048.     //if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
  5049.         // Determine if power meter should reflect shot power (human aiming or AI preparing)
  5050.     bool humanIsAimingPower = isAiming && (currentGameState == AIMING || currentGameState == BREAKING);
  5051.     // NEW Condition: AI is displaying its aim, so show its chosen power
  5052.     bool aiIsVisualizingPower = (isPlayer2AI && currentPlayer == 2 &&
  5053.         currentGameState == AI_THINKING && aiIsDisplayingAim);
  5054.  
  5055.     if (humanIsAimingPower || aiIsVisualizingPower) { // Use the new condition
  5056.         fillRatio = shotPower / MAX_SHOT_POWER;
  5057.     }
  5058.     float fillHeight = (powerMeterRect.bottom - powerMeterRect.top) * fillRatio;
  5059.     D2D1_RECT_F fillRect = D2D1::RectF(
  5060.         powerMeterRect.left,
  5061.         powerMeterRect.bottom - fillHeight,
  5062.         powerMeterRect.right,
  5063.         powerMeterRect.bottom
  5064.     );
  5065.  
  5066.     if (pGradientBrush) {
  5067.         pRT->FillRectangle(&fillRect, pGradientBrush);
  5068.         SafeRelease(&pGradientBrush);
  5069.     }
  5070.  
  5071.     // Draw scale notches
  5072.     ID2D1SolidColorBrush* pNotchBrush = nullptr;
  5073.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pNotchBrush);
  5074.     if (pNotchBrush) {
  5075.         for (int i = 0; i <= 8; ++i) {
  5076.             float y = powerMeterRect.top + (powerMeterRect.bottom - powerMeterRect.top) * (i / 8.0f);
  5077.             pRT->DrawLine(
  5078.                 D2D1::Point2F(powerMeterRect.right + 2.0f, y),
  5079.                 D2D1::Point2F(powerMeterRect.right + 8.0f, y),
  5080.                 pNotchBrush,
  5081.                 1.5f
  5082.             );
  5083.         }
  5084.         SafeRelease(&pNotchBrush);
  5085.     }
  5086.  
  5087.     // Draw "Power" Label Below Meter
  5088.     if (pTextFormat) {
  5089.         ID2D1SolidColorBrush* pTextBrush = nullptr;
  5090.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pTextBrush);
  5091.         if (pTextBrush) {
  5092.             D2D1_RECT_F textRect = D2D1::RectF(
  5093.                 powerMeterRect.left - 20.0f,
  5094.                 powerMeterRect.bottom + 8.0f,
  5095.                 powerMeterRect.right + 20.0f,
  5096.                 powerMeterRect.bottom + 38.0f
  5097.             );
  5098.             pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  5099.             pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
  5100.             pRT->DrawText(L"Power", 5, pTextFormat, &textRect, pTextBrush);
  5101.             SafeRelease(&pTextBrush);
  5102.         }
  5103.     }
  5104.  
  5105.     // Draw Glow Effect if fully charged or fading out
  5106.     static float glowPulse = 0.0f;
  5107.     static bool glowIncreasing = true;
  5108.     static float glowFadeOut = 0.0f; // NEW: tracks fading out
  5109.  
  5110.     if (shotPower >= MAX_SHOT_POWER * 0.99f) {
  5111.         // While fully charged, keep pulsing normally
  5112.         if (glowIncreasing) {
  5113.             glowPulse += 0.02f;
  5114.             if (glowPulse >= 1.0f) glowIncreasing = false;
  5115.         }
  5116.         else {
  5117.             glowPulse -= 0.02f;
  5118.             if (glowPulse <= 0.0f) glowIncreasing = true;
  5119.         }
  5120.         glowFadeOut = 1.0f; // Reset fade out to full
  5121.     }
  5122.     else if (glowFadeOut > 0.0f) {
  5123.         // If shot fired, gradually fade out
  5124.         glowFadeOut -= 0.02f;
  5125.         if (glowFadeOut < 0.0f) glowFadeOut = 0.0f;
  5126.     }
  5127.  
  5128.     if (glowFadeOut > 0.0f) {
  5129.         ID2D1SolidColorBrush* pGlowBrush = nullptr;
  5130.         float effectiveOpacity = (0.3f + 0.7f * glowPulse) * glowFadeOut;
  5131.         pRT->CreateSolidColorBrush(
  5132.             D2D1::ColorF(D2D1::ColorF::Red, effectiveOpacity),
  5133.             &pGlowBrush
  5134.         );
  5135.         if (pGlowBrush) {
  5136.             float glowCenterX = (powerMeterRect.left + powerMeterRect.right) / 2.0f;
  5137.             float glowCenterY = powerMeterRect.top;
  5138.             D2D1_ELLIPSE glowEllipse = D2D1::Ellipse(
  5139.                 D2D1::Point2F(glowCenterX, glowCenterY - 10.0f),
  5140.                 12.0f + 3.0f * glowPulse,
  5141.                 6.0f + 2.0f * glowPulse
  5142.             );
  5143.             pRT->FillEllipse(&glowEllipse, pGlowBrush);
  5144.             SafeRelease(&pGlowBrush);
  5145.         }
  5146.     }
  5147. }
  5148.  
  5149. void DrawSpinIndicator(ID2D1RenderTarget* pRT) {
  5150.     ID2D1SolidColorBrush* pWhiteBrush = nullptr;
  5151.     ID2D1SolidColorBrush* pRedBrush = nullptr;
  5152.  
  5153.     pRT->CreateSolidColorBrush(CUE_BALL_COLOR, &pWhiteBrush);
  5154.     pRT->CreateSolidColorBrush(ENGLISH_DOT_COLOR, &pRedBrush);
  5155.  
  5156.     if (!pWhiteBrush || !pRedBrush) {
  5157.         SafeRelease(&pWhiteBrush);
  5158.         SafeRelease(&pRedBrush);
  5159.         return;
  5160.     }
  5161.  
  5162.     // Draw White Ball Background
  5163.     D2D1_ELLIPSE bgEllipse = D2D1::Ellipse(spinIndicatorCenter, spinIndicatorRadius, spinIndicatorRadius);
  5164.     pRT->FillEllipse(&bgEllipse, pWhiteBrush);
  5165.     pRT->DrawEllipse(&bgEllipse, pRedBrush, 0.5f); // Thin red border
  5166.  
  5167.  
  5168.     // Draw Red Dot for Spin Position
  5169.     float dotRadius = 4.0f;
  5170.     float dotX = spinIndicatorCenter.x + cueSpinX * (spinIndicatorRadius - dotRadius); // Keep dot inside edge
  5171.     float dotY = spinIndicatorCenter.y + cueSpinY * (spinIndicatorRadius - dotRadius);
  5172.     D2D1_ELLIPSE dotEllipse = D2D1::Ellipse(D2D1::Point2F(dotX, dotY), dotRadius, dotRadius);
  5173.     pRT->FillEllipse(&dotEllipse, pRedBrush);
  5174.  
  5175.     SafeRelease(&pWhiteBrush);
  5176.     SafeRelease(&pRedBrush);
  5177. }
  5178.  
  5179.  
  5180. void DrawPocketedBallsIndicator(ID2D1RenderTarget* pRT) {
  5181.     ID2D1SolidColorBrush* pBgBrush = nullptr;
  5182.     ID2D1SolidColorBrush* pBallBrush = nullptr;
  5183.  
  5184.     // Ensure render target is valid before proceeding
  5185.     if (!pRT) return;
  5186.  
  5187.     HRESULT hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black, 0.8f), &pBgBrush); // Semi-transparent black
  5188.     if (FAILED(hr)) { SafeRelease(&pBgBrush); return; } // Exit if brush creation fails
  5189.  
  5190.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0), &pBallBrush); // Placeholder, color will be set per ball
  5191.     if (FAILED(hr)) {
  5192.         SafeRelease(&pBgBrush);
  5193.         SafeRelease(&pBallBrush);
  5194.         return; // Exit if brush creation fails
  5195.     }
  5196.  
  5197.     // Draw the background bar (rounded rect)
  5198.     D2D1_ROUNDED_RECT roundedRect = D2D1::RoundedRect(pocketedBallsBarRect, 10.0f, 10.0f); // Corner radius 10
  5199.     float baseAlpha = 0.8f;
  5200.     float flashBoost = pocketFlashTimer * 0.5f; // Make flash effect boost alpha slightly
  5201.     float finalAlpha = std::min(1.0f, baseAlpha + flashBoost);
  5202.     pBgBrush->SetOpacity(finalAlpha);
  5203.     pRT->FillRoundedRectangle(&roundedRect, pBgBrush);
  5204.     pBgBrush->SetOpacity(1.0f); // Reset opacity after drawing
  5205.  
  5206.     // --- Draw small circles for pocketed balls inside the bar ---
  5207.  
  5208.     // Calculate dimensions based on the bar's height for better scaling
  5209.     float barHeight = pocketedBallsBarRect.bottom - pocketedBallsBarRect.top;
  5210.     float ballDisplayRadius = barHeight * 0.30f; // Make balls slightly smaller relative to bar height
  5211.     float spacing = ballDisplayRadius * 2.2f; // Adjust spacing slightly
  5212.     float padding = spacing * 0.75f; // Add padding from the edges
  5213.     float center_Y = pocketedBallsBarRect.top + barHeight / 2.0f; // Vertical center
  5214.  
  5215.     // Starting X positions with padding
  5216.     float currentX_P1 = pocketedBallsBarRect.left + padding;
  5217.     float currentX_P2 = pocketedBallsBarRect.right - padding; // Start from right edge minus padding
  5218.  
  5219.     int p1DrawnCount = 0;
  5220.     int p2DrawnCount = 0;
  5221.     const int maxBallsToShow = 7; // Max balls per player in the bar
  5222.  
  5223.     for (const auto& b : balls) {
  5224.         if (b.isPocketed) {
  5225.             // Skip cue ball and 8-ball in this indicator
  5226.             if (b.id == 0 || b.id == 8) continue;
  5227.  
  5228.             bool isPlayer1Ball = (player1Info.assignedType != BallType::NONE && b.type == player1Info.assignedType);
  5229.             bool isPlayer2Ball = (player2Info.assignedType != BallType::NONE && b.type == player2Info.assignedType);
  5230.  
  5231.             if (isPlayer1Ball && p1DrawnCount < maxBallsToShow) {
  5232.                 pBallBrush->SetColor(b.color);
  5233.                 // Draw P1 balls from left to right
  5234.                 D2D1_ELLIPSE ballEllipse = D2D1::Ellipse(D2D1::Point2F(currentX_P1 + p1DrawnCount * spacing, center_Y), ballDisplayRadius, ballDisplayRadius);
  5235.                 pRT->FillEllipse(&ballEllipse, pBallBrush);
  5236.                 p1DrawnCount++;
  5237.             }
  5238.             else if (isPlayer2Ball && p2DrawnCount < maxBallsToShow) {
  5239.                 pBallBrush->SetColor(b.color);
  5240.                 // Draw P2 balls from right to left
  5241.                 D2D1_ELLIPSE ballEllipse = D2D1::Ellipse(D2D1::Point2F(currentX_P2 - p2DrawnCount * spacing, center_Y), ballDisplayRadius, ballDisplayRadius);
  5242.                 pRT->FillEllipse(&ballEllipse, pBallBrush);
  5243.                 p2DrawnCount++;
  5244.             }
  5245.             // Note: Balls pocketed before assignment or opponent balls are intentionally not shown here.
  5246.             // You could add logic here to display them differently if needed (e.g., smaller, grayed out).
  5247.         }
  5248.     }
  5249.  
  5250.     SafeRelease(&pBgBrush);
  5251.     SafeRelease(&pBallBrush);
  5252. }
  5253.  
  5254. void DrawBallInHandIndicator(ID2D1RenderTarget* pRT) {
  5255.     if (!isDraggingCueBall && (currentGameState != BALL_IN_HAND_P1 && currentGameState != BALL_IN_HAND_P2 && currentGameState != PRE_BREAK_PLACEMENT)) {
  5256.         return; // Only show when placing/dragging
  5257.     }
  5258.  
  5259.     Ball* cueBall = GetCueBall();
  5260.     if (!cueBall) return;
  5261.  
  5262.     ID2D1SolidColorBrush* pGhostBrush = nullptr;
  5263.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.6f), &pGhostBrush); // Semi-transparent white
  5264.  
  5265.     if (pGhostBrush) {
  5266.         D2D1_POINT_2F drawPos;
  5267.         if (isDraggingCueBall) {
  5268.             drawPos = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y);
  5269.         }
  5270.         else {
  5271.             // If not dragging but in placement state, show at current ball pos
  5272.             drawPos = D2D1::Point2F(cueBall->x, cueBall->y);
  5273.         }
  5274.  
  5275.         // Check if the placement is valid before drawing differently?
  5276.         bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  5277.         bool isValid = IsValidCueBallPosition(drawPos.x, drawPos.y, behindHeadstring);
  5278.  
  5279.         if (!isValid) {
  5280.             // Maybe draw red outline if invalid placement?
  5281.             pGhostBrush->SetColor(D2D1::ColorF(D2D1::ColorF::Red, 0.6f));
  5282.         }
  5283.  
  5284.  
  5285.         D2D1_ELLIPSE ghostEllipse = D2D1::Ellipse(drawPos, BALL_RADIUS, BALL_RADIUS);
  5286.         pRT->FillEllipse(&ghostEllipse, pGhostBrush);
  5287.         pRT->DrawEllipse(&ghostEllipse, pGhostBrush, 1.0f); // Outline
  5288.  
  5289.         SafeRelease(&pGhostBrush);
  5290.     }
  5291. }
  5292.  
  5293. void DrawPocketSelectionIndicator(ID2D1RenderTarget* pRT) {
  5294.     /*  Never show the arrow while the player is still placing the
  5295.     cue-ball (ball-in-hand) – it otherwise hides behind the
  5296.     ghost-ball and can lock the UI.                               */
  5297.  
  5298.     /* Still skip the opening-break placement,
  5299.    but show the arrow during BALL-IN-HAND */
  5300.    // ? skip when no active call for the CURRENT shooter
  5301.     if ((currentPlayer == 1 && calledPocketP1 < 0) ||
  5302.         (currentPlayer == 2 && calledPocketP2 < 0))    return;
  5303.     /*if (currentGameState == PRE_BREAK_PLACEMENT)
  5304.         return;*/ //new ai-asked-to-disable
  5305.         /*if (currentGameState == BALL_IN_HAND_P1 ||
  5306.             currentGameState == BALL_IN_HAND_P2 ||
  5307.             currentGameState == PRE_BREAK_PLACEMENT)
  5308.         {
  5309.             return;
  5310.         }*/
  5311.  
  5312.     int pocketToIndicate = -1;
  5313.     // Whenever EITHER player has pocketed their first 7 and has called (human or AI),
  5314.     // we forcibly show their arrow—regardless of currentGameState.
  5315.     if ((currentPlayer == 1 && player1Info.ballsPocketedCount >= 7 && calledPocketP1 >= 0) ||
  5316.         (currentPlayer == 2 && player2Info.ballsPocketedCount >= 7 && calledPocketP2 >= 0))
  5317.     {
  5318.         pocketToIndicate = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  5319.     }
  5320.     /*// A human player is actively choosing if they are in the CHOOSING_POCKET state.
  5321.     bool isHumanChoosing = (currentGameState == CHOOSING_POCKET_P1 || (currentGameState == CHOOSING_POCKET_P2 && !isPlayer2AI));
  5322.  
  5323.     if (isHumanChoosing) {
  5324.         // When choosing, show the currently selected pocket (which has a default).
  5325.         pocketToIndicate = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  5326.     }
  5327.     else if (IsPlayerOnEightBall(currentPlayer)) {
  5328.         // If it's a normal turn but the player is on the 8-ball, show their called pocket as a reminder.
  5329.         pocketToIndicate = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  5330.     }*/
  5331.  
  5332.     if (pocketToIndicate < 0 || pocketToIndicate > 5) {
  5333.         return; // Don't draw if no pocket is selected or relevant.
  5334.     }
  5335.  
  5336.     ID2D1SolidColorBrush* pArrowBrush = nullptr;
  5337.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Yellow, 0.9f), &pArrowBrush);
  5338.     if (!pArrowBrush) return;
  5339.  
  5340.     // ... The rest of your arrow drawing geometry logic remains exactly the same ...
  5341.     // (No changes needed to the points/path drawing, only the logic above)
  5342.     D2D1_POINT_2F targetPocketCenter = pocketPositions[pocketToIndicate];
  5343.     float arrowHeadSize = HOLE_VISUAL_RADIUS * 0.5f;
  5344.     float arrowShaftLength = HOLE_VISUAL_RADIUS * 0.3f;
  5345.     float arrowShaftWidth = arrowHeadSize * 0.4f;
  5346.     float verticalOffsetFromPocketCenter = HOLE_VISUAL_RADIUS * 1.6f;
  5347.     D2D1_POINT_2F tip, baseLeft, baseRight, shaftTopLeft, shaftTopRight, shaftBottomLeft, shaftBottomRight;
  5348.  
  5349.     if (targetPocketCenter.y == TABLE_TOP) {
  5350.         tip = D2D1::Point2F(targetPocketCenter.x, targetPocketCenter.y + verticalOffsetFromPocketCenter + arrowHeadSize);
  5351.         baseLeft = D2D1::Point2F(targetPocketCenter.x - arrowHeadSize / 2.0f, targetPocketCenter.y + verticalOffsetFromPocketCenter);
  5352.         baseRight = D2D1::Point2F(targetPocketCenter.x + arrowHeadSize / 2.0f, targetPocketCenter.y + verticalOffsetFromPocketCenter);
  5353.         shaftTopLeft = D2D1::Point2F(targetPocketCenter.x - arrowShaftWidth / 2.0f, baseLeft.y);
  5354.         shaftTopRight = D2D1::Point2F(targetPocketCenter.x + arrowShaftWidth / 2.0f, baseRight.y);
  5355.         shaftBottomLeft = D2D1::Point2F(targetPocketCenter.x - arrowShaftWidth / 2.0f, baseLeft.y - arrowShaftLength);
  5356.         shaftBottomRight = D2D1::Point2F(targetPocketCenter.x + arrowShaftWidth / 2.0f, baseRight.y - arrowShaftLength);
  5357.     }
  5358.     else {
  5359.         tip = D2D1::Point2F(targetPocketCenter.x, targetPocketCenter.y - verticalOffsetFromPocketCenter - arrowHeadSize);
  5360.         baseLeft = D2D1::Point2F(targetPocketCenter.x - arrowHeadSize / 2.0f, targetPocketCenter.y - verticalOffsetFromPocketCenter);
  5361.         baseRight = D2D1::Point2F(targetPocketCenter.x + arrowHeadSize / 2.0f, targetPocketCenter.y - verticalOffsetFromPocketCenter);
  5362.         shaftTopLeft = D2D1::Point2F(targetPocketCenter.x - arrowShaftWidth / 2.0f, baseLeft.y + arrowShaftLength);
  5363.         shaftTopRight = D2D1::Point2F(targetPocketCenter.x + arrowShaftWidth / 2.0f, baseRight.y + arrowShaftLength);
  5364.         shaftBottomLeft = D2D1::Point2F(targetPocketCenter.x - arrowShaftWidth / 2.0f, baseLeft.y);
  5365.         shaftBottomRight = D2D1::Point2F(targetPocketCenter.x + arrowShaftWidth / 2.0f, baseRight.y);
  5366.     }
  5367.  
  5368.     ID2D1PathGeometry* pPath = nullptr;
  5369.     if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  5370.         ID2D1GeometrySink* pSink = nullptr;
  5371.         if (SUCCEEDED(pPath->Open(&pSink))) {
  5372.             pSink->BeginFigure(tip, D2D1_FIGURE_BEGIN_FILLED);
  5373.             pSink->AddLine(baseLeft); pSink->AddLine(shaftBottomLeft); pSink->AddLine(shaftTopLeft);
  5374.             pSink->AddLine(shaftTopRight); pSink->AddLine(shaftBottomRight); pSink->AddLine(baseRight);
  5375.             pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  5376.             pSink->Close();
  5377.             SafeRelease(&pSink);
  5378.             pRT->FillGeometry(pPath, pArrowBrush);
  5379.         }
  5380.         SafeRelease(&pPath);
  5381.     }
  5382.     SafeRelease(&pArrowBrush);
  5383. }
  5384. ```
  5385.  
  5386. ==++ Heere's the full source code for Resource.h ++==:::
  5387. ```
  5388. //{{NO_DEPENDENCIES}}
  5389. // Microsoft Visual C++ generated include file.
  5390. // Used by Yahoo-8Ball-Pool-Clone.rc
  5391. //
  5392. #define IDI_ICON1                       101
  5393. // --- NEW Resource IDs (Define these in your .rc file / resource.h) ---
  5394. #define IDD_NEWGAMEDLG 106
  5395. #define IDC_RADIO_2P   1003
  5396. #define IDC_RADIO_CPU  1005
  5397. #define IDC_GROUP_AI   1006
  5398. #define IDC_RADIO_EASY 1007
  5399. #define IDC_RADIO_MEDIUM 1008
  5400. #define IDC_RADIO_HARD 1009
  5401. // --- NEW Resource IDs for Opening Break ---
  5402. #define IDC_GROUP_BREAK_MODE 1010
  5403. #define IDC_RADIO_CPU_BREAK  1011
  5404. #define IDC_RADIO_P1_BREAK   1012
  5405. #define IDC_RADIO_FLIP_BREAK 1013
  5406. // --- NEW Resource ID for Table Color Dropdown ---
  5407. #define IDC_COMBO_TABLECOLOR 1014
  5408. // Standard IDOK is usually defined, otherwise define it (e.g., #define IDOK 1)
  5409.  
  5410. // Next default values for new objects
  5411. //
  5412. #ifdef APSTUDIO_INVOKED
  5413. #ifndef APSTUDIO_READONLY_SYMBOLS
  5414. #define _APS_NEXT_RESOURCE_VALUE        102
  5415. #define _APS_NEXT_COMMAND_VALUE         40002 // Incremented
  5416. #define _APS_NEXT_CONTROL_VALUE         1014 // Incremented
  5417. #define _APS_NEXT_SYMED_VALUE           101
  5418. #endif
  5419. #endif
  5420.  
  5421. ```
  5422.  
  5423. ==++ :Here's the full source code for "Yahoo-8Ball-Pool-Clone.rc" ++==
  5424. ```
  5425. // Microsoft Visual C++ generated resource script.
  5426. //
  5427. #include "resource.h"
  5428.  
  5429. #define APSTUDIO_READONLY_SYMBOLS
  5430. /////////////////////////////////////////////////////////////////////////////
  5431. //
  5432. // Generated from the TEXTINCLUDE 2 resource.
  5433. //
  5434. #include "winres.h"
  5435.  
  5436. /////////////////////////////////////////////////////////////////////////////
  5437. #undef APSTUDIO_READONLY_SYMBOLS
  5438.  
  5439. /////////////////////////////////////////////////////////////////////////////
  5440. // English (United States) resources
  5441.  
  5442. #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
  5443. LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
  5444. #pragma code_page(1252)
  5445.  
  5446. #ifdef APSTUDIO_INVOKED
  5447. /////////////////////////////////////////////////////////////////////////////
  5448. //
  5449. // TEXTINCLUDE
  5450. //
  5451.  
  5452. 1 TEXTINCLUDE
  5453. BEGIN
  5454. "resource.h\0"
  5455. END
  5456.  
  5457. 2 TEXTINCLUDE
  5458. BEGIN
  5459. "#include ""winres.h""\r\n"
  5460. "\0"
  5461. END
  5462.  
  5463. 3 TEXTINCLUDE
  5464. BEGIN
  5465. "\r\n"
  5466. "\0"
  5467. END
  5468.  
  5469. #endif    // APSTUDIO_INVOKED
  5470.  
  5471.  
  5472. /////////////////////////////////////////////////////////////////////////////
  5473. //
  5474. // Icon
  5475. //
  5476.  
  5477. // Icon with lowest ID value placed first to ensure application icon
  5478. // remains consistent on all systems.
  5479. IDI_ICON1               ICON                    "D:\\Download\\8Ball_Colored.ico"
  5480.  
  5481. #endif    // English (United States) resources
  5482. /////////////////////////////////////////////////////////////////////////////
  5483.  
  5484.  
  5485.  
  5486. #ifndef APSTUDIO_INVOKED
  5487. /////////////////////////////////////////////////////////////////////////////
  5488. //
  5489. // Generated from the TEXTINCLUDE 3 resource.
  5490. //
  5491.  
  5492.  
  5493. /////////////////////////////////////////////////////////////////////////////
  5494. #endif    // not APSTUDIO_INVOKED
  5495.  
  5496. #include <windows.h> // Needed for control styles like WS_GROUP, BS_AUTORADIOBUTTON etc.
  5497.  
  5498. /////////////////////////////////////////////////////////////////////////////
  5499. //
  5500. // Dialog
  5501. //
  5502.  
  5503. IDD_NEWGAMEDLG DIALOGEX 0, 0, 220, 185 // Dialog position (x, y) and size (width, height) in Dialog Units (DLUs) - Increased Height
  5504. STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
  5505. CAPTION "New 8-Ball Game"
  5506. FONT 8, "MS Shell Dlg", 400, 0, 0x1 // Standard dialog font
  5507. BEGIN
  5508. // --- Game Mode Selection ---
  5509. // Group Box for Game Mode (Optional visually, but helps structure)
  5510. GROUPBOX        "Game Mode", IDC_STATIC, 7, 7, 90, 50
  5511.  
  5512. // "2 Player" Radio Button (First in this group)
  5513. CONTROL         "&2 Player (Human vs Human)", IDC_RADIO_2P, "Button",
  5514. BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP, 14, 20, 80, 10
  5515.  
  5516. // "Human vs CPU" Radio Button
  5517. CONTROL         "Human vs &CPU", IDC_RADIO_CPU, "Button",
  5518. BS_AUTORADIOBUTTON | WS_TABSTOP, 14, 35, 70, 10
  5519.  
  5520. // --- NEW: Table Color Selection ---
  5521. LTEXT           "Table Color:", IDC_STATIC, 7, 65, 50, 8
  5522. COMBOBOX        IDC_COMBO_TABLECOLOR, 7, 75, 90, 60,
  5523. CBS_DROPDOWNLIST | CBS_HASSTRINGS | WS_VSCROLL | WS_TABSTOP
  5524.  
  5525.  
  5526. // --- AI Difficulty Selection (Inside its own Group Box) ---
  5527. GROUPBOX        "AI Difficulty", IDC_GROUP_AI, 118, 7, 95, 70
  5528.  
  5529. // "Easy" Radio Button (First in the AI group)
  5530. CONTROL         "&Easy", IDC_RADIO_EASY, "Button",
  5531. BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP, 125, 20, 60, 10
  5532.  
  5533. // "Medium" Radio Button
  5534. CONTROL         "&Medium", IDC_RADIO_MEDIUM, "Button",
  5535. BS_AUTORADIOBUTTON | WS_TABSTOP, 125, 35, 60, 10
  5536.  
  5537. // "Hard" Radio Button
  5538. CONTROL         "&Hard", IDC_RADIO_HARD, "Button",
  5539. BS_AUTORADIOBUTTON | WS_TABSTOP, 125, 50, 60, 10
  5540.  
  5541. // --- Opening Break Modes (For Versus CPU Only) ---
  5542. GROUPBOX        "Opening Break Modes:", IDC_GROUP_BREAK_MODE, 118, 82, 95, 60
  5543.  
  5544. // "CPU Break" Radio Button (Default for this group)
  5545. CONTROL         "&CPU Break", IDC_RADIO_CPU_BREAK, "Button",
  5546. BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP, 125, 95, 70, 10
  5547.  
  5548. // "P1 Break" Radio Button
  5549. CONTROL         "&P1 Break", IDC_RADIO_P1_BREAK, "Button",
  5550. BS_AUTORADIOBUTTON | WS_TABSTOP, 125, 110, 70, 10
  5551.  
  5552. // "FlipCoin Break" Radio Button
  5553. CONTROL         "&FlipCoin Break", IDC_RADIO_FLIP_BREAK, "Button",
  5554. BS_AUTORADIOBUTTON | WS_TABSTOP, 125, 125, 70, 10
  5555.  
  5556.  
  5557. // --- Standard Buttons ---
  5558. DEFPUSHBUTTON   "Start", IDOK, 55, 160, 50, 14 // Default button (Enter key) - Adjusted Y position
  5559. PUSHBUTTON      "Cancel", IDCANCEL, 115, 160, 50, 14 // Adjusted Y position
  5560. END
  5561. ```
Advertisement
Add Comment
Please, Sign In to add comment