alien_fx_fiend

2D StickPool D2D C++ 3DChamfer-InnerRim+PocketLogic+AimRay+Stick1.5x Final

Sep 3rd, 2025
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 326.94 KB | Source Code | 0 0
  1. ==++ Here's the full source for (file 1/3 (No OOP-based)) "Pool-Game-CloneV18.cpp"::: ++==
  2. ```Pool-Game-CloneV18.cpp
  3. #define WIN32_LEAN_AND_MEAN
  4. #define NOMINMAX
  5. #include <windows.h>
  6. #include <d2d1_1.h> // For even-odd fill mode
  7. #include <d2d1.h>
  8. #include <dwrite.h>
  9. #include <fstream> // For file I/O
  10. #include <iostream> // For some basic I/O, though not strictly necessary for just file ops
  11. #include <array>
  12. #include <vector>
  13. #include <cmath>
  14. #include <string>
  15. #include <sstream> // Required for wostringstream
  16. #include <algorithm> // Required for std::max, std::min
  17. #include <ctime>    // Required for srand, time
  18. #include <cstdlib> // Required for srand, rand (often included by others, but good practice)
  19. #include <commctrl.h> // Needed for radio buttons etc. in dialog (if using native controls)
  20. #include <mmsystem.h> // For PlaySound
  21. #include <tchar.h> //midi func
  22. #include <thread>
  23. #include <atomic>
  24. #include <wincodec.h>   // WIC
  25. #include "resource.h"
  26.  
  27. #ifndef HAS_STD_CLAMP
  28. template <typename T>
  29. T clamp(const T& v, const T& lo, const T& hi)
  30. {
  31.    return (v < lo) ? lo : (v > hi) ? hi : v;
  32. }
  33. namespace std { using ::clamp; }   // inject into std:: for seamless use
  34. #define HAS_STD_CLAMP
  35. #endif
  36.  
  37. #pragma comment(lib, "Comctl32.lib") // Link against common controls library
  38. #pragma comment(lib, "d2d1.lib")
  39. #pragma comment(lib, "dwrite.lib")
  40. #pragma comment(lib, "Winmm.lib") // Link against Windows Multimedia library
  41. #pragma comment(lib, "windowscodecs.lib")
  42.  
  43. // --- Constants ---
  44. const float PI = 3.1415926535f;
  45. const float BALL_RADIUS = 10.0f;
  46. const float TABLE_LEFT = 80.0f;  // Adjusted for new window size
  47. const float TABLE_TOP = 80.0f;   // Adjusted for new window size
  48. const float TABLE_WIDTH = 840.0f;  // Increased by 20%
  49. const float TABLE_HEIGHT = 420.0f; // Increased by 20%
  50. const float TABLE_RIGHT = TABLE_LEFT + TABLE_WIDTH;
  51. const float TABLE_BOTTOM = TABLE_TOP + TABLE_HEIGHT;
  52. //const float CUSHION_THICKNESS = 20.0f;
  53. const float WOODEN_RAIL_THICKNESS = 20.0f; // This was formerly CUSHION_THICKNESS
  54. const float INNER_RIM_THICKNESS = 15.0f;    // This was formerly a local 'rimWidth'. Reduced from 15.0f to ~1/3rd.
  55. // --- WITH these new constants ---
  56. const float CORNER_HOLE_VISUAL_RADIUS = 26.0f; // (22.0f)
  57. const float MIDDLE_HOLE_VISUAL_RADIUS = 26.0f; // Middle pockets are now ~18% bigger (26.0f)
  58. //const float HOLE_VISUAL_RADIUS = 22.0f; // Visual size of the hole
  59. //const float POCKET_RADIUS = HOLE_VISUAL_RADIUS * 1.05f; // Make detection radius slightly larger // Make detection radius match visual size (or slightly larger)
  60. const float MAX_SHOT_POWER = 15.0f;
  61. const float FRICTION = 0.985f; // Friction factor per frame
  62. const float MIN_VELOCITY_SQ = 0.01f * 0.01f; // Stop balls below this squared velocity
  63. const float HEADSTRING_X = TABLE_LEFT + TABLE_WIDTH * 0.30f; // 30% line
  64. const float RACK_POS_X = TABLE_LEFT + TABLE_WIDTH * 0.65f; // 65% line for rack apex
  65. const float RACK_POS_Y = TABLE_TOP + TABLE_HEIGHT / 2.0f;
  66. const UINT ID_TIMER = 1;
  67. const int TARGET_FPS = 60; // Target frames per second for timer
  68. //const float V_CUT_DEPTH = 32.0f; // How deep the V-cut goes into the rim
  69. //const float V_CUT_WIDTH = 48.0f; // How wide the V-cut is at the rim edge
  70. //const float RIM_WIDTH = 25.0f;   // Width of the chamfered inner rim 32.0f=>10=>25(both)
  71. //const float rimWidth = 25.0f; // must match rimWidth used elsewhere in the project 15.0f=>10
  72. //const float chamferSize = 25.0f;    // Defines the size of the 45-degree V-cut 25.0f
  73. const float CHAMFER_SIZE = 25.0f;          // This was formerly a local 'chamferSize'.
  74.  
  75. // --- Enums ---
  76. // --- MODIFIED/NEW Enums ---
  77. enum GameState {
  78.    SHOWING_DIALOG,     // NEW: Game is waiting for initial dialog input
  79.    PRE_BREAK_PLACEMENT,// Player placing cue ball for break
  80.    BREAKING,           // Player is aiming/shooting the break shot
  81.    CHOOSING_POCKET_P1, // NEW: Player 1 needs to call a pocket for the 8-ball
  82.    CHOOSING_POCKET_P2, // NEW: Player 2 needs to call a pocket for the 8-ball
  83.    AIMING,             // Player is aiming
  84.    AI_THINKING,        // NEW: AI is calculating its move
  85.    SHOT_IN_PROGRESS,   // Balls are moving
  86.    ASSIGNING_BALLS,    // Turn after break where ball types are assigned
  87.    PLAYER1_TURN,
  88.    PLAYER2_TURN,
  89.    BALL_IN_HAND_P1,
  90.    BALL_IN_HAND_P2,
  91.    GAME_OVER
  92. };
  93.  
  94. enum BallType {
  95.    NONE,
  96.    SOLID,  // Yellow (1-7)
  97.    STRIPE, // Red (9-15)
  98.    EIGHT_BALL, // Black (8)
  99.    CUE_BALL // White (0)
  100. };
  101.  
  102. // NEW Enums for Game Mode and AI Difficulty
  103. enum GameMode {
  104.    HUMAN_VS_HUMAN,
  105.    HUMAN_VS_AI
  106. };
  107.  
  108. enum AIDifficulty {
  109.    EASY,
  110.    MEDIUM,
  111.    HARD
  112. };
  113.  
  114. enum OpeningBreakMode {
  115.    CPU_BREAK,
  116.    P1_BREAK,
  117.    FLIP_COIN_BREAK
  118. };
  119.  
  120. // NEW: Enum and arrays for table color options
  121. enum TableColor {
  122.    INDIGO,
  123.    TAN,
  124.    TEAL,
  125.    GREEN,
  126.    RED
  127. };
  128.  
  129. // --- Structs ---
  130. struct Ball {
  131.    int id;             // 0=Cue, 1-7=Solid, 8=Eight, 9-15=Stripe
  132.    BallType type;
  133.    float x, y;
  134.    float vx, vy;
  135.    D2D1_COLOR_F color;
  136.    bool isPocketed;
  137.    float rotationAngle; // radians, used for drawing rotation (visual spin)
  138.    float rotationAxis;  // direction (radians) perpendicular to travel - used to offset highlight
  139. };
  140.  
  141. struct PlayerInfo {
  142.    BallType assignedType;
  143.    int ballsPocketedCount;
  144.    std::wstring name;
  145. };
  146.  
  147. // --- Global Variables ---
  148.  
  149. // Direct2D & DirectWrite
  150. ID2D1Factory* pFactory = nullptr;
  151. //ID2D1Factory* g_pD2DFactory = nullptr;
  152. ID2D1HwndRenderTarget* pRenderTarget = nullptr;
  153. IDWriteFactory* pDWriteFactory = nullptr;
  154. IDWriteTextFormat* pTextFormat = nullptr;
  155. IDWriteTextFormat* pTextFormatBold = nullptr;
  156. IDWriteTextFormat* pLargeTextFormat = nullptr; // For "Foul!"
  157. IDWriteTextFormat* pBallNumFormat = nullptr;
  158. // -------------------- Globals for mask creation --------------------
  159. static IWICImagingFactory* g_pWICFactory_masks = nullptr;
  160. static std::vector<std::vector<uint8_t>> pocketMasks; // 6 masks, each maskWidth*maskHeight bytes (0/1)
  161. static int pocketMaskWidth = 0;
  162. static int pocketMaskHeight = 0;
  163. static float pocketMaskOriginX = TABLE_LEFT;
  164. static float pocketMaskOriginY = TABLE_TOP;
  165. static float pocketMaskScale = 1.0f; // pixels per world unit
  166. static const uint8_t POCKET_ALPHA_THRESHOLD = 48; // same idea as earlier
  167.  
  168. // Game State
  169. HWND hwndMain = nullptr;
  170. GameState currentGameState = SHOWING_DIALOG; // Start by showing dialog
  171. std::vector<Ball> balls;
  172. int currentPlayer = 1; // 1 or 2
  173. PlayerInfo player1Info = { BallType::NONE, 0, L"Vince Woods"/*"Player 1"*/ };
  174. PlayerInfo player2Info = { BallType::NONE, 0, L"Virtus Pro"/*"CPU"*/ }; // Default P2 name
  175. bool foulCommitted = false;
  176. std::wstring gameOverMessage = L"";
  177. bool firstBallPocketedAfterBreak = false;
  178. std::vector<int> pocketedThisTurn;
  179. // --- NEW: 8-Ball Pocket Call Globals ---
  180. int calledPocketP1 = -1; // Pocket index (0-5) called by Player 1 for the 8-ball. -1 means not called.
  181. int calledPocketP2 = -1; // Pocket index (0-5) called by Player 2 for the 8-ball.
  182. int currentlyHoveredPocket = -1; // For visual feedback on which pocket is being hovered
  183. std::wstring pocketCallMessage = L""; // Message like "Choose a pocket..."
  184.     // --- NEW: Remember which pocket the 8?ball actually went into last shot
  185. int lastEightBallPocketIndex = -1;
  186. //int lastPocketedIndex = -1; // pocket index (0–5) of the last ball pocketed
  187. int called = -1;
  188. bool cueBallPocketed = false;
  189.  
  190. // --- NEW: Foul Tracking Globals ---
  191. int firstHitBallIdThisShot = -1;      // ID of the first object ball hit by cue ball (-1 if none)
  192. bool cueHitObjectBallThisShot = false; // Did cue ball hit an object ball this shot?
  193. bool railHitAfterContact = false;     // Did any ball hit a rail AFTER cue hit an object ball?
  194. // How long to display the FOUL! HUD after a foul is detected (frames)
  195. int foulDisplayCounter = 0;           // counts down each frame; >0 => show FOUL!
  196. // --- End New Foul Tracking Globals ---
  197.  
  198. // NEW Game Mode/AI Globals
  199. GameMode gameMode = HUMAN_VS_HUMAN; // Default mode
  200. AIDifficulty aiDifficulty = MEDIUM; // Default difficulty
  201. OpeningBreakMode openingBreakMode = CPU_BREAK; // Default opening break mode
  202. bool isPlayer2AI = false;           // Is Player 2 controlled by AI?
  203. bool aiTurnPending = false;         // Flag: AI needs to take its turn when possible
  204. // bool aiIsThinking = false;       // Replaced by AI_THINKING game state
  205. // NEW: Flag to indicate if the current shot is the opening break of the game
  206. bool isOpeningBreakShot = false;
  207.  
  208. // NEW: For AI shot planning and visualization
  209. struct AIPlannedShot {
  210.    float angle;
  211.    float power;
  212.    float spinX;
  213.    float spinY;
  214.    bool isValid; // Is there a valid shot planned?
  215. };
  216. AIPlannedShot aiPlannedShotDetails; // Stores the AI's next shot
  217. bool aiIsDisplayingAim = false;    // True when AI has decided a shot and is in "display aim" mode
  218. int aiAimDisplayFramesLeft = 0;  // How many frames left to display AI aim
  219. const int AI_AIM_DISPLAY_DURATION_FRAMES = 45; // Approx 0.75 seconds at 60 FPS, adjust as needed
  220.  
  221. // Input & Aiming
  222. POINT ptMouse = { 0, 0 };
  223. bool isAiming = false;
  224. bool isDraggingCueBall = false;
  225. // --- ENSURE THIS LINE EXISTS HERE ---
  226. bool isDraggingStick = false; // True specifically when drag initiated on the stick graphic
  227. // --- End Ensure ---
  228. bool isSettingEnglish = false;
  229. D2D1_POINT_2F aimStartPoint = { 0, 0 };
  230. float cueAngle = 0.0f;
  231. float shotPower = 0.0f;
  232. float cueSpinX = 0.0f; // Range -1 to 1
  233. float cueSpinY = 0.0f; // Range -1 to 1
  234. float pocketFlashTimer = 0.0f;
  235. bool cheatModeEnabled = false; // Cheat Mode toggle (G key)
  236. int draggingBallId = -1;
  237. bool keyboardAimingActive = false; // NEW FLAG: true when arrow keys modify aim/power
  238. MCIDEVICEID midiDeviceID = 0; //midi func
  239. std::atomic<bool> isMusicPlaying(false); //midi func
  240. std::thread musicThread; //midi func
  241. void StartMidi(HWND hwnd, const TCHAR* midiPath);
  242. void StopMidi();
  243.  
  244. // NEW: Global for selected table color and definitions
  245. TableColor selectedTableColor = INDIGO; // Default color
  246. const WCHAR* tableColorNames[] = { L"Indigo", L"Tan", L"Teal", L"Green", L"Red" };
  247. const D2D1_COLOR_F tableColorValues[] = {
  248. D2D1::ColorF(0.05f, 0.09f, 0.28f),       // Indigo
  249. D2D1::ColorF(0.3529f, 0.3137f, 0.2196f), // Tan
  250. D2D1::ColorF(0.00392f, 0.467f, 0.439f)/*(0.0f, 0.545f, 0.541f)*//*(0.0f, 0.5f, 0.5f)*//*(0.0f, 0.4f, 0.4392f)*/,       // Teal default=(0.0f, 0.5f, 0.5f)
  251. D2D1::ColorF(0.1608f, 0.4000f, 0.1765f), // Green
  252. D2D1::ColorF(0.3882f, 0.1059f, 0.10196f) // Red
  253. };
  254.  
  255. // UI Element Positions
  256. D2D1_RECT_F powerMeterRect = { TABLE_RIGHT + WOODEN_RAIL_THICKNESS + 20, TABLE_TOP, TABLE_RIGHT + WOODEN_RAIL_THICKNESS + 50, TABLE_BOTTOM };
  257. D2D1_RECT_F spinIndicatorRect = { TABLE_LEFT - WOODEN_RAIL_THICKNESS - 60, TABLE_TOP + 20, TABLE_LEFT - WOODEN_RAIL_THICKNESS - 20, TABLE_TOP + 60 }; // Circle area
  258. D2D1_POINT_2F spinIndicatorCenter = { spinIndicatorRect.left + (spinIndicatorRect.right - spinIndicatorRect.left) / 2.0f, spinIndicatorRect.top + (spinIndicatorRect.bottom - spinIndicatorRect.top) / 2.0f };
  259. float spinIndicatorRadius = (spinIndicatorRect.right - spinIndicatorRect.left) / 2.0f;
  260. D2D1_RECT_F pocketedBallsBarRect = { TABLE_LEFT, TABLE_BOTTOM + WOODEN_RAIL_THICKNESS + 30, TABLE_RIGHT, TABLE_BOTTOM + WOODEN_RAIL_THICKNESS + 70 };
  261.  
  262. // Corrected Pocket Center Positions (aligned with table corners/edges)
  263. const D2D1_POINT_2F pocketPositions[6] = {
  264.     {TABLE_LEFT, TABLE_TOP},                           // Top-Left
  265.     {TABLE_LEFT + TABLE_WIDTH / 2.0f, TABLE_TOP},      // Top-Middle
  266.     {TABLE_RIGHT, TABLE_TOP},                          // Top-Right
  267.     {TABLE_LEFT, TABLE_BOTTOM},                        // Bottom-Left
  268.     {TABLE_LEFT + TABLE_WIDTH / 2.0f, TABLE_BOTTOM},   // Bottom-Middle
  269.     {TABLE_RIGHT, TABLE_BOTTOM}                        // Bottom-Right
  270. };
  271.  
  272. // Colors
  273. //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)
  274. // This is now a variable that can be changed, not a constant.
  275. D2D1_COLOR_F TABLE_COLOR = D2D1::ColorF(0.05f, 0.09f, 0.28f); // Default to Indigo
  276. //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)
  277. /*
  278. 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);
  279. Hex: Teal=#00abc2 Tan=#7c6d53 Teal2=#03adc2 xPurple=#314b69 ?Tan=#88785b Red=#631b1a
  280. */
  281. const D2D1_COLOR_F CUSHION_COLOR = D2D1::ColorF(D2D1::ColorF(0.3608f, 0.0275f, 0.0078f)); // NEWCOLOR ::Red => (0.3608f, 0.0275f, 0.0078f)
  282. //const D2D1_COLOR_F CUSHION_COLOR = D2D1::ColorF(D2D1::ColorF::Red); // NEWCOLOR ::Red => (0.3608f, 0.0275f, 0.0078f)
  283. const D2D1_COLOR_F POCKET_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
  284. const D2D1_COLOR_F CUE_BALL_COLOR = D2D1::ColorF(D2D1::ColorF::White);
  285. const D2D1_COLOR_F EIGHT_BALL_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
  286. const D2D1_COLOR_F SOLID_COLOR = D2D1::ColorF(D2D1::ColorF::Goldenrod); // Solids = Yellow Goldenrod
  287. const D2D1_COLOR_F STRIPE_COLOR = D2D1::ColorF(D2D1::ColorF::DarkOrchid);   // Stripes = Red DarkOrchid
  288. const D2D1_COLOR_F AIM_LINE_COLOR = D2D1::ColorF(D2D1::ColorF::White, 0.7f); // Semi-transparent white
  289. const D2D1_COLOR_F FOUL_TEXT_COLOR = D2D1::ColorF(D2D1::ColorF::Red);
  290. const D2D1_COLOR_F TURN_ARROW_COLOR = D2D1::ColorF(0.1333f, 0.7294f, 0.7490f); //NEWCOLOR 0.1333f, 0.7294f, 0.7490f => ::Blue
  291. //const D2D1_COLOR_F TURN_ARROW_COLOR = D2D1::ColorF(D2D1::ColorF::Blue);
  292. const D2D1_COLOR_F ENGLISH_DOT_COLOR = D2D1::ColorF(D2D1::ColorF::Red);
  293. const D2D1_COLOR_F UI_TEXT_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
  294.  
  295. // --------------------------------------------------------------------
  296. //  Realistic colours for each id (0-15)
  297. //  0 = cue-ball (white) | 1-7 solids | 8 = eight-ball | 9-15 stripes
  298. // --------------------------------------------------------------------
  299. static const D2D1_COLOR_F BALL_COLORS[16] =
  300. {
  301.     D2D1::ColorF(D2D1::ColorF::White),          // 0  cue
  302.     D2D1::ColorF(1.00f, 0.85f, 0.00f),          // 1  yellow
  303.     D2D1::ColorF(0.05f, 0.30f, 1.00f),          // 2  blue
  304.     D2D1::ColorF(0.90f, 0.10f, 0.10f),          // 3  red
  305.     D2D1::ColorF(0.55f, 0.25f, 0.85f),          // 4  purple
  306.     D2D1::ColorF(1.00f, 0.55f, 0.00f),          // 5  orange
  307.     D2D1::ColorF(0.00f, 0.60f, 0.30f),          // 6  green
  308.     D2D1::ColorF(0.50f, 0.05f, 0.05f),          // 7  maroon / burgundy
  309.     D2D1::ColorF(D2D1::ColorF::Black),          // 8  black
  310.     D2D1::ColorF(1.00f, 0.85f, 0.00f),          // 9  (yellow stripe)
  311.     D2D1::ColorF(0.05f, 0.30f, 1.00f),          // 10 blue stripe
  312.     D2D1::ColorF(0.90f, 0.10f, 0.10f),          // 11 red stripe
  313.     D2D1::ColorF(0.55f, 0.25f, 0.85f),          // 12 purple stripe
  314.     D2D1::ColorF(1.00f, 0.55f, 0.00f),          // 13 orange stripe
  315.     D2D1::ColorF(0.00f, 0.60f, 0.30f),          // 14 green stripe
  316.     D2D1::ColorF(0.50f, 0.05f, 0.05f)           // 15 maroon stripe
  317. };
  318.  
  319. // Quick helper
  320. inline D2D1_COLOR_F GetBallColor(int id)
  321. {
  322.     return (id >= 0 && id < 16) ? BALL_COLORS[id]
  323.         : D2D1::ColorF(D2D1::ColorF::White);
  324. }
  325.  
  326. // --- Forward Declarations ---
  327. HRESULT CreateDeviceResources();
  328. void DiscardDeviceResources();
  329. void OnPaint();
  330. void OnResize(UINT width, UINT height);
  331. void InitGame();
  332. void GameUpdate();
  333. void UpdatePhysics();
  334. void CheckCollisions();
  335. bool CheckPockets(); // Returns true if any ball was pocketed
  336. void ProcessShotResults();
  337. void ApplyShot(float power, float angle, float spinX, float spinY);
  338. void RespawnCueBall(bool behindHeadstring);
  339. bool AreBallsMoving();
  340. void SwitchTurns();
  341. //bool AssignPlayerBallTypes(BallType firstPocketedType);
  342. bool AssignPlayerBallTypes(BallType firstPocketedType,
  343.     bool creditShooter = true);
  344. void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed);
  345. Ball* GetBallById(int id);
  346. Ball* GetCueBall();
  347. //void PlayGameMusic(HWND hwnd); //midi func
  348. void AIBreakShot();
  349.  
  350. // Drawing Functions
  351. void DrawScene(ID2D1RenderTarget* pRT);
  352. void DrawTable(ID2D1RenderTarget* pRT, ID2D1Factory* pFactory);
  353. void DrawBalls(ID2D1RenderTarget* pRT);
  354. void DrawCueStick(ID2D1RenderTarget* pRT);
  355. void DrawAimingAids(ID2D1RenderTarget* pRT);
  356. void DrawUI(ID2D1RenderTarget* pRT);
  357. void DrawPowerMeter(ID2D1RenderTarget* pRT);
  358. void DrawSpinIndicator(ID2D1RenderTarget* pRT);
  359. void DrawPocketedBallsIndicator(ID2D1RenderTarget* pRT);
  360. void DrawBallInHandIndicator(ID2D1RenderTarget* pRT);
  361. // NEW
  362. void DrawPocketSelectionIndicator(ID2D1RenderTarget* pRT);
  363.  
  364. // Helper Functions
  365. float GetDistance(float x1, float y1, float x2, float y2);
  366. float GetDistanceSq(float x1, float y1, float x2, float y2);
  367. bool IsValidCueBallPosition(float x, float y, bool checkHeadstring);
  368. //template <typename T> void SafeRelease(T** ppT);
  369. template <typename T>
  370. void SafeRelease(T** ppT) {
  371.     if (*ppT) {
  372.         (*ppT)->Release();
  373.         *ppT = nullptr;
  374.     }
  375. }
  376. static D2D1_COLOR_F Lighten(const D2D1_COLOR_F& c, float factor);
  377. static bool IsBallInPocketBlackArea(const Ball& b, int p);
  378. static std::vector<std::vector<std::array<D2D1_POINT_2F, 4>>> g_pocketBezierCache;
  379. static bool g_pocketBezierCacheInitialized = false;
  380.  
  381. // --- NEW HELPER FORWARD DECLARATIONS ---
  382. bool IsPlayerOnEightBall(int player);
  383. void CheckAndTransitionToPocketChoice(int playerID);
  384. // --- ADD FORWARD DECLARATION FOR NEW HELPER HERE ---
  385. float PointToLineSegmentDistanceSq(D2D1_POINT_2F p, D2D1_POINT_2F a, D2D1_POINT_2F b);
  386. // --- End Forward Declaration ---
  387. 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
  388. bool PointInTriangle(const D2D1_POINT_2F& p, const D2D1_POINT_2F& a, const D2D1_POINT_2F& b, const D2D1_POINT_2F& c);
  389.  
  390. // Return the visual pocket radius for pocket index p
  391. inline float GetPocketVisualRadius(int p)
  392. {
  393.     // Middle pockets are larger; corners use the corner radius
  394.     return (p == 1 || p == 4) ? MIDDLE_HOLE_VISUAL_RADIUS : CORNER_HOLE_VISUAL_RADIUS;
  395. }
  396. // -----------------------------
  397. // Pocket / capsule collision helper
  398. // -----------------------------
  399. static inline float Dot(const D2D1_POINT_2F& a, const D2D1_POINT_2F& b) {
  400.     return a.x * b.x + a.y * b.y;
  401. }
  402. static inline float Clampf(float v, float a, float b) {
  403.     return (v < a) ? a : (v > b ? b : v);
  404. }
  405.  
  406. // Ensure WIC factory (call once)
  407. bool EnsureWICFactory_Masks()
  408. {
  409.     if (g_pWICFactory_masks) return true;
  410.     HRESULT hr = CoCreateInstance(
  411.         CLSID_WICImagingFactory,
  412.         nullptr,
  413.         CLSCTX_INPROC_SERVER,
  414.         IID_PPV_ARGS(&g_pWICFactory_masks));
  415.     return SUCCEEDED(hr);
  416. }
  417.  
  418. // Cleanup
  419. void ShutdownPocketMasks_D2D()
  420. {
  421.     pocketMasks.clear();
  422.     pocketMaskWidth = pocketMaskHeight = 0;
  423.     pocketMaskOriginX = pocketMaskOriginY = 0.0f;
  424.     pocketMaskScale = 1.0f;
  425.     if (g_pWICFactory_masks) { g_pWICFactory_masks->Release(); g_pWICFactory_masks = nullptr; }
  426. }
  427.  
  428. // ----------------------------------------------------------------------
  429. // CreatePocketMasks_D2D  (uses your pocket path geometry)
  430. // ----------------------------------------------------------------------
  431. void CreatePocketMasks_D2D(int pixelWidth, int pixelHeight, float originX, float originY, float scale)
  432. {
  433.     if (!EnsureWICFactory_Masks()) return;
  434.     if (!pFactory) return;
  435.  
  436.     pocketMaskWidth = pixelWidth;
  437.     pocketMaskHeight = pixelHeight;
  438.     pocketMaskOriginX = originX;
  439.     pocketMaskOriginY = originY;
  440.     pocketMaskScale = scale;
  441.  
  442.     pocketMasks.clear();
  443.     pocketMasks.resize(6);
  444.  
  445.     // Create WIC bitmap + D2D render target
  446.     IWICBitmap* pWicBitmap = nullptr;
  447.     HRESULT hr = g_pWICFactory_masks->CreateBitmap(
  448.         pocketMaskWidth, pocketMaskHeight,
  449.         GUID_WICPixelFormat32bppPBGRA,
  450.         WICBitmapCacheOnLoad,
  451.         &pWicBitmap);
  452.     if (FAILED(hr) || !pWicBitmap) {
  453.         SafeRelease(&pWicBitmap);
  454.         return;
  455.     }
  456.  
  457.     D2D1_RENDER_TARGET_PROPERTIES rtProps = D2D1::RenderTargetProperties();
  458.     rtProps.dpiX = 96.0f;
  459.     rtProps.dpiY = 96.0f;
  460.  
  461.     ID2D1RenderTarget* pWicRT = nullptr;
  462.     hr = pFactory->CreateWicBitmapRenderTarget(pWicBitmap, rtProps, &pWicRT);
  463.     if (FAILED(hr) || !pWicRT) {
  464.         SafeRelease(&pWicBitmap);
  465.         return;
  466.     }
  467.  
  468.     // Create pocket brush + rim brush (you provided both; mask uses pocket brush)
  469.     ID2D1SolidColorBrush* pPocketBrush = nullptr;
  470.     //ID2D1SolidColorBrush* pRimBrush = nullptr;
  471.     pWicRT->CreateSolidColorBrush(POCKET_COLOR, &pPocketBrush);
  472.     //pWicRT->CreateSolidColorBrush(D2D1::ColorF(0.1f, 0.1f, 0.1f), &pRimBrush);
  473.  
  474.     // Set transform so world -> mask pixels mapping is consistent:
  475.     //D2D1::Matrix3x2F transform = D2D1::Matrix3x2F::Translation(-pocketMaskOriginX, -pocketMaskOriginY) *
  476.         //D2D1::Matrix3x2F::Scale(pocketMaskScale, pocketMaskScale);
  477.     //pWicRT->SetTransform(transform);
  478.  
  479.     // For each pocket: clear, draw exact pocket path (your code), EndDraw, lock & read pixels
  480.     for (int i = 0; i < 6; ++i) {
  481.         pWicRT->BeginDraw();
  482.         pWicRT->Clear(D2D1::ColorF(0, 0.0f)); // fully transparent background
  483.  
  484.                 // --- DEFINITIVE FIX: Create a smaller, more accurate circular-only mask ---
  485.         // This mask represents ONLY the black hole, not the entire V-cut opening. This
  486.         // makes pocketing more precise and realistic.
  487.  
  488.         // We draw the circular hole in the center of our local mask bitmap.
  489.         D2D1_POINT_2F maskCenter = { pocketMaskWidth / 2.0f, pocketMaskHeight / 2.0f };
  490.  
  491.         // Use the visual radius, scaled to pixels, for a perfect match.
  492.         float radiusInPixels = GetPocketVisualRadius(i) * pocketMaskScale;
  493.  
  494.         // To make the middle pockets slightly less generous, we can apply a small reduction here.
  495.         if (i == 1 || i == 4) {
  496.             radiusInPixels *= 0.95f; // Middle pocket masks are 5% smaller than the visual hole.
  497.         }
  498.  
  499.         D2D1_ELLIPSE pocketEllipse = D2D1::Ellipse(maskCenter, radiusInPixels, radiusInPixels);
  500.         pWicRT->FillEllipse(&pocketEllipse, pPocketBrush);
  501.  
  502.                 /*// --- FOOLPROOF FIX: Create a unified "keyhole" mask for each pocket ---
  503.         // This ensures the mask perfectly matches the visual opening.
  504.  
  505.         // 1. Draw the main circular hole. We draw it in the center of our local bitmap.
  506.         D2D1_POINT_2F maskCenter = { pocketMaskWidth / 2.0f, pocketMaskHeight / 2.0f };
  507.         float radius = GetPocketVisualRadius(i) * pocketMaskScale; // Scale radius to pixels
  508.         D2D1_ELLIPSE pocketEllipse = D2D1::Ellipse(maskCenter, radius, radius);
  509.         pWicRT->FillEllipse(&pocketEllipse, pPocketBrush);
  510.  
  511.         // 2. Define and draw the V-shaped cutout that leads into the hole.
  512.         // The coordinates are calculated in the local space of the mask bitmap.
  513.         const float rimWidth = INNER_RIM_THICKNESS * pocketMaskScale;
  514.         const float vCutDepth = CHAMFER_SIZE * pocketMaskScale;
  515.  
  516.         D2D1_POINT_2F v_tip, v_base1, v_base2;
  517.         if (i == 1) { // Top-Middle
  518.             v_tip = { maskCenter.x, maskCenter.y + rimWidth + vCutDepth };
  519.             v_base1 = { maskCenter.x - vCutDepth, maskCenter.y + rimWidth };
  520.             v_base2 = { maskCenter.x + vCutDepth, maskCenter.y + rimWidth };
  521.         }
  522.         else if (i == 4) { // Bottom-Middle
  523.             v_tip = { maskCenter.x, maskCenter.y - rimWidth - vCutDepth };
  524.             v_base1 = { maskCenter.x + vCutDepth, maskCenter.y - rimWidth };
  525.             v_base2 = { maskCenter.x - vCutDepth, maskCenter.y - rimWidth };
  526.         }
  527.         else if (i == 0) { // Top-Left
  528.             v_tip = { maskCenter.x + rimWidth + vCutDepth, maskCenter.y + rimWidth + vCutDepth };
  529.             v_base1 = { maskCenter.x + rimWidth, maskCenter.y + vCutDepth };
  530.             v_base2 = { maskCenter.x + vCutDepth, maskCenter.y + rimWidth };
  531.         }
  532.         else if (i == 2) { // Top-Right
  533.             v_tip = { maskCenter.x - rimWidth - vCutDepth, maskCenter.y + rimWidth + vCutDepth };
  534.             v_base1 = { maskCenter.x - vCutDepth, maskCenter.y + rimWidth };
  535.             v_base2 = { maskCenter.x - rimWidth, maskCenter.y + vCutDepth };
  536.         }
  537.         else if (i == 3) { // Bottom-Left
  538.             v_tip = { maskCenter.x + rimWidth + vCutDepth, maskCenter.y - rimWidth - vCutDepth };
  539.             v_base1 = { maskCenter.x + vCutDepth, maskCenter.y - rimWidth };
  540.             v_base2 = { maskCenter.x + rimWidth, maskCenter.y - vCutDepth };
  541.         }
  542.         else { // i == 5, Bottom-Right
  543.             v_tip = { maskCenter.x - rimWidth - vCutDepth, maskCenter.y - rimWidth - vCutDepth };
  544.             v_base1 = { maskCenter.x - rimWidth, maskCenter.y - vCutDepth };
  545.             v_base2 = { maskCenter.x - vCutDepth, maskCenter.y - rimWidth };
  546.         }
  547.  
  548.         ID2D1PathGeometry* pTriPath = nullptr;
  549.         pFactory->CreatePathGeometry(&pTriPath);
  550.         if (pTriPath) {
  551.             ID2D1GeometrySink* pSink = nullptr;
  552.             if (SUCCEEDED(pTriPath->Open(&pSink))) {
  553.                 pSink->BeginFigure(v_tip, D2D1_FIGURE_BEGIN_FILLED);
  554.                 pSink->AddLine(v_base1);
  555.                 pSink->AddLine(v_base2);
  556.                 pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  557.                 pSink->Close();
  558.             }
  559.             SafeRelease(&pSink);
  560.             pWicRT->FillGeometry(pTriPath, pPocketBrush);
  561.             SafeRelease(&pTriPath);
  562.         }*/
  563.  
  564.         // --- Your pocket geometry (copied verbatim, using pPocketBrush) ---
  565.                 // --- FOOLPROOF FIX: Draw a simple, larger circle for the new pocket mask ---
  566.         // This matches the new visual style and provides a generous collision area.
  567.         /*if (pPocketBrush) {
  568.             float radius = (i == 1 || i == 4) ? MIDDLE_HOLE_VISUAL_RADIUS : CORNER_HOLE_VISUAL_RADIUS;
  569.             // The mask radius should be slightly larger than the visual one for a forgiving feel.
  570.             D2D1_ELLIPSE pocketEllipse = D2D1::Ellipse(pocketPositions[i], radius * 1.1f, radius * 1.1f);
  571.             pWicRT->FillEllipse(&pocketEllipse, pPocketBrush);
  572.             }
  573.         // --- end pocket geometry ---*/
  574.  
  575.         hr = pWicRT->EndDraw();
  576.         (void)hr; // continue even if EndDraw fails
  577.  
  578.         // Lock the WIC bitmap and extract alpha => build mask
  579.         WICRect lockRect = { 0, 0, pocketMaskWidth, pocketMaskHeight };
  580.         IWICBitmapLock* pLock = nullptr;
  581.         hr = pWicBitmap->Lock(&lockRect, WICBitmapLockRead, &pLock);
  582.         if (SUCCEEDED(hr) && pLock) {
  583.             UINT cbStride = 0;
  584.             UINT cbBufferSize = 0;
  585.             BYTE* pv = nullptr;
  586.             hr = pLock->GetDataPointer(&cbBufferSize, &pv);
  587.             pLock->GetStride(&cbStride);
  588.  
  589.             if (SUCCEEDED(hr) && pv) {
  590.                 pocketMasks[i].assign(pocketMaskWidth * pocketMaskHeight, 0);
  591.                 for (int y = 0; y < pocketMaskHeight; ++y) {
  592.                     BYTE* row = pv + y * cbStride;
  593.                     int base = y * pocketMaskWidth;
  594.                     for (int x = 0; x < pocketMaskWidth; ++x) {
  595.                         BYTE a = row[x * 4 + 3]; // premultiplied BGRA alpha at offset 3
  596.                         pocketMasks[i][base + x] = (a > POCKET_ALPHA_THRESHOLD) ? 1 : 0;
  597.                     }
  598.                 }
  599.             }
  600.             pLock->Release();
  601.         }
  602.     } // end for pockets
  603.  
  604.     // cleanup
  605.     SafeRelease(&pPocketBrush);
  606.     //SafeRelease(&pRimBrush);
  607.     SafeRelease(&pWicRT);
  608.     SafeRelease(&pWicBitmap);
  609. }
  610.  
  611. // Create six per-pocket masks by rendering each pocket individually into a WIC bitmap.
  612. // pixelWidth/Height = resolution for the masks
  613. // originX/originY = world coordinate mapping for mask pixel (0,0) -> these world coords
  614. // scale = pixels per world unit (1.0f = 1 pixel per D2D unit)
  615. /*void CreatePocketMasks_D2D(int pixelWidth, int pixelHeight, float originX, float originY, float scale)
  616. {
  617.     if (!EnsureWICFactory_Masks()) return;
  618.     if (!pFactory) return; // requires your ID2D1Factory*
  619.  
  620.     pocketMaskWidth = pixelWidth;
  621.     pocketMaskHeight = pixelHeight;
  622.     pocketMaskOriginX = originX;
  623.     pocketMaskOriginY = originY;
  624.     pocketMaskScale = scale;
  625.  
  626.     pocketMasks.clear();
  627.     pocketMasks.resize(6); // six pockets
  628.  
  629.     // Create a WIC bitmap and a D2D render-target that draws into it.
  630.     IWICBitmap* pWicBitmap = nullptr;
  631.     HRESULT hr = g_pWICFactory_masks->CreateBitmap(
  632.         pocketMaskWidth, pocketMaskHeight,
  633.         GUID_WICPixelFormat32bppPBGRA,
  634.         WICBitmapCacheOnLoad,
  635.         &pWicBitmap);
  636.     if (FAILED(hr) || !pWicBitmap) {
  637.         SafeRelease(&pWicBitmap);
  638.         return;
  639.     }
  640.  
  641.     D2D1_RENDER_TARGET_PROPERTIES rtProps = D2D1::RenderTargetProperties();
  642.     rtProps.dpiX = 96.0f;
  643.     rtProps.dpiY = 96.0f;
  644.  
  645.     ID2D1RenderTarget* pWicRT = nullptr;
  646.     hr = pFactory->CreateWicBitmapRenderTarget(pWicBitmap, rtProps, &pWicRT);
  647.     if (FAILED(hr) || !pWicRT) {
  648.         SafeRelease(&pWicBitmap);
  649.         return;
  650.     }
  651.  
  652.     // Create a brush for drawing the pocket shape (solid black)
  653.     ID2D1SolidColorBrush* pBrush = nullptr;
  654.     pWicRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black, 1.0f), &pBrush);
  655.  
  656.     // Set transform: world -> pixel = (world - origin) * scale
  657.     D2D1::Matrix3x2F transform = D2D1::Matrix3x2F::Translation(-pocketMaskOriginX, -pocketMaskOriginY) *
  658.         D2D1::Matrix3x2F::Scale(pocketMaskScale, pocketMaskScale);
  659.     pWicRT->SetTransform(transform);
  660.  
  661.     // For each pocket: clear, draw that pocket's black area, EndDraw, lock & read pixels into pocketMasks[i]
  662.     for (int p = 0; p < 6; ++p) {
  663.         pWicRT->BeginDraw();
  664.         // Clear to transparent
  665.         pWicRT->Clear(D2D1::ColorF(0, 0.0f));
  666.  
  667.         // Draw only the pocket p — use the same geometry you use for on-screen pockets.
  668.         // Example draws a filled ellipse of the visual pocket radius; if you draw semicircles
  669.         // or a path on screen, replicate that exact path here for pixel-perfect masks.
  670.         float visualRadius = GetPocketVisualRadius(p); // uses your helper (MIDDLE vs CORNER)
  671.         D2D1_ELLIPSE e = D2D1::Ellipse(D2D1::Point2F(pocketPositions[p].x, pocketPositions[p].y), visualRadius, visualRadius);
  672.         pWicRT->FillEllipse(&e, pBrush);
  673. */
  674. /*ID2D1SolidColorBrush* pPocketBrush = nullptr;
  675. ID2D1SolidColorBrush* pRimBrush = nullptr;
  676. pWicRT->CreateSolidColorBrush(POCKET_COLOR, &pPocketBrush);
  677. pWicRT->CreateSolidColorBrush(D2D1::ColorF(0.1f, 0.1f, 0.1f), &pRimBrush);
  678. if (pPocketBrush && pRimBrush) {
  679.     for (int i = 0; i < 6; ++i) {
  680.         ID2D1PathGeometry* pPath = nullptr;
  681.         pFactory->CreatePathGeometry(&pPath);
  682.         if (pPath) {
  683.             ID2D1GeometrySink* pSink = nullptr;
  684.             if (SUCCEEDED(pPath->Open(&pSink))) {
  685.                 float currentVisualRadius = (i == 1 || i == 4) ? MIDDLE_HOLE_VISUAL_RADIUS : CORNER_HOLE_VISUAL_RADIUS;
  686.                 float mouthRadius = currentVisualRadius * 1.5f;
  687.                 float backRadius = currentVisualRadius * 1.1f;
  688.                 D2D1_POINT_2F center = pocketPositions[i];
  689.                 D2D1_POINT_2F p1, p2;
  690.                 D2D1_SWEEP_DIRECTION sweep;
  691.                 if (i == 0) {
  692.                     p1 = D2D1::Point2F(center.x + mouthRadius, center.y);
  693.                     p2 = D2D1::Point2F(center.x, center.y + mouthRadius);
  694.                     sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  695.                 }
  696.                 else if (i == 2) {
  697.                     p1 = D2D1::Point2F(center.x, center.y + mouthRadius);
  698.                     p2 = D2D1::Point2F(center.x - mouthRadius, center.y);
  699.                     sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  700.                 }
  701.                 else if (i == 3) {
  702.                     p1 = D2D1::Point2F(center.x, center.y - mouthRadius);
  703.                     p2 = D2D1::Point2F(center.x + mouthRadius, center.y);
  704.                     sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  705.                 }
  706.                 else if (i == 5) {
  707.                     p1 = D2D1::Point2F(center.x - mouthRadius, center.y);
  708.                     p2 = D2D1::Point2F(center.x, center.y - mouthRadius);
  709.                     sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  710.                 }
  711.                 else if (i == 1) {
  712.                     p1 = D2D1::Point2F(center.x - mouthRadius / 1.5f, center.y);
  713.                     p2 = D2D1::Point2F(center.x + mouthRadius / 1.5f, center.y);
  714.                     sweep = D2D1_SWEEP_DIRECTION_CLOCKWISE;
  715.                 }
  716.                 else {
  717.                     p1 = D2D1::Point2F(center.x + mouthRadius / 1.5f, center.y);
  718.                     p2 = D2D1::Point2F(center.x - mouthRadius / 1.5f, center.y);
  719.                     sweep = D2D1_SWEEP_DIRECTION_CLOCKWISE;
  720.                 }
  721.                 pSink->BeginFigure(center, D2D1_FIGURE_BEGIN_FILLED);
  722.                 pSink->AddLine(p1);
  723.                 pSink->AddArc(D2D1::ArcSegment(p2, D2D1::SizeF(backRadius, backRadius), 0.0f, sweep, D2D1_ARC_SIZE_SMALL));
  724.                 pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  725.                 pSink->Close();
  726.                 SafeRelease(&pSink);
  727.                 pWicRT->FillGeometry(pPath, pPocketBrush);
  728.                 // Draw the inner rim for a beveled effect (Start)
  729.                 D2D1::Matrix3x2F scale = D2D1::Matrix3x2F::Scale(0.8f, 0.8f, center);
  730.                 ID2D1TransformedGeometry* pTransformedGeo = nullptr;
  731.                 pFactory->CreateTransformedGeometry(pPath, &scale, &pTransformedGeo);
  732.                 if (pTransformedGeo) {
  733.                     pWicRT->FillGeometry(pTransformedGeo, pRimBrush);
  734.                     SafeRelease(&pTransformedGeo);
  735.                 } //End
  736.             }
  737.             SafeRelease(&pPath);
  738.         }
  739.     }
  740. }
  741. SafeRelease(&pPocketBrush);
  742. SafeRelease(&pRimBrush);*/
  743. /*
  744.         // If your on-screen pocket is a semicircle / capsule / complex path,
  745.         // create & fill the same path geometry here instead of FillEllipse.
  746.  
  747.         hr = pWicRT->EndDraw();
  748.         if (FAILED(hr)) {
  749.             // continue but mask may be invalid
  750.         }
  751.  
  752.         // Lock WIC bitmap and read pixels
  753.         WICRect lockRect = { 0, 0, pocketMaskWidth, pocketMaskHeight };
  754.         IWICBitmapLock* pLock = nullptr;
  755.         hr = pWicBitmap->Lock(&lockRect, WICBitmapLockRead, &pLock);
  756.         if (SUCCEEDED(hr) && pLock) {
  757.             UINT cbStride = 0;
  758.             UINT cbBufferSize = 0;
  759.             BYTE* pv = nullptr;
  760.             hr = pLock->GetDataPointer(&cbBufferSize, &pv);
  761.             pLock->GetStride(&cbStride);
  762.  
  763.             if (SUCCEEDED(hr) && pv) {
  764.                 pocketMasks[p].assign(pocketMaskWidth * pocketMaskHeight, 0);
  765.                 for (int y = 0; y < pocketMaskHeight; ++y) {
  766.                     BYTE* row = pv + y * cbStride;
  767.                     int base = y * pocketMaskWidth;
  768.                     for (int x = 0; x < pocketMaskWidth; ++x) {
  769.                         BYTE a = row[x * 4 + 3]; // premultiplied BGRA -> alpha at offset 3
  770.                         pocketMasks[p][base + x] = (a > POCKET_ALPHA_THRESHOLD) ? 1 : 0;
  771.                     }
  772.                 }
  773.             }
  774.             pLock->Release();
  775.         }
  776.     } // end loop pockets
  777.  
  778.     // cleanup
  779.     SafeRelease(&pBrush);
  780.     SafeRelease(&pWicRT);
  781.     SafeRelease(&pWicBitmap);
  782. }*/
  783.  
  784. //orig function
  785. /*
  786. // Create pixel mask by rendering pocket shapes into a WIC bitmap via Direct2D
  787. // pixelWidth/height = desired mask resolution in pixels
  788. // originX/originY = world coordinate representing pixel (0,0) origin of mask
  789. // scale = pixels per world unit (use 1.0f for 1 pixel per D2D unit; >1 for supersampling)
  790. void CreatePocketMask_D2D(int pixelWidth, int pixelHeight, float originX, float originY, float scale)
  791. {
  792.     if (!EnsureWICFactory()) return;
  793.     if (!pFactory) return; // requires your ID2D1Factory* (global in your code)
  794.  
  795.     maskWidth = pixelWidth;
  796.     maskHeight = pixelHeight;
  797.     maskOriginX = originX;
  798.     maskOriginY = originY;
  799.     maskScale = scale;
  800.     pocketMask.assign(maskWidth * maskHeight, 0);
  801.  
  802.     // Create a WIC bitmap (32bpp premultiplied BGRA) to be the render target surface
  803.     IWICBitmap* pWicBitmap = nullptr;
  804.     HRESULT hr = g_pWICFactory->CreateBitmap(
  805.         maskWidth, maskHeight,
  806.         GUID_WICPixelFormat32bppPBGRA,
  807.         WICBitmapCacheOnLoad,
  808.         &pWicBitmap);
  809.     if (FAILED(hr) || !pWicBitmap) {
  810.         if (pWicBitmap) pWicBitmap->Release();
  811.         return;
  812.     }
  813.  
  814.     // Create a Direct2D render target that draws into the WIC bitmap
  815.     // Use default D2D render target properties but ensure DPI = 96 (pixels align)
  816.     D2D1_RENDER_TARGET_PROPERTIES rtProps = D2D1::RenderTargetProperties();
  817.     rtProps.dpiX = 96.0f;
  818.     rtProps.dpiY = 96.0f;
  819.     ID2D1RenderTarget* pWicRT = nullptr;
  820.     hr = pFactory->CreateWicBitmapRenderTarget(
  821.         pWicBitmap,
  822.         rtProps,
  823.         &pWicRT);
  824.     if (FAILED(hr) || !pWicRT) {
  825.         pWicBitmap->Release();
  826.         return;
  827.     }
  828.  
  829.     // Create a black brush for pocket fill
  830.     ID2D1SolidColorBrush* pBlackBrush = nullptr;
  831.     pWicRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black, 1.0f), &pBlackBrush);
  832.  
  833.     // Set transform: scale then translate so we can draw in world coords.
  834.     // world -> pixel: (world - origin) * scale
  835.     D2D1::Matrix3x2F transform = D2D1::Matrix3x2F::Translation(-maskOriginX, -maskOriginY) *
  836.         D2D1::Matrix3x2F::Scale(maskScale, maskScale);
  837.     pWicRT->SetTransform(transform);
  838.  
  839.     // Begin drawing
  840.     pWicRT->BeginDraw();
  841.     pWicRT->Clear(D2D1::ColorF(0, 0.0f)); // transparent
  842.  
  843.     // ---- Draw pocket shapes (use your exact same Direct2D math here) ----
  844.     // For pixel-perfect match you MUST draw the *same* shapes/paths you use in the screen render.
  845.     // The example below draws filled circles at pocketPositions; replace with your path code if needed.
  846. */
  847. /*    for (int i = 0; i < 6; ++i) {
  848.         float visualRadius = (i == 1 || i == 4) ? MIDDLE_HOLE_VISUAL_RADIUS : CORNER_HOLE_VISUAL_RADIUS;
  849.         // Draw as an ellipse centered at pocketPositions[i] in *world* coords — transform handles scale/origin.
  850.         D2D1_ELLIPSE e = D2D1::Ellipse(D2D1::Point2F(pocketPositions[i].x, pocketPositions[i].y), visualRadius, visualRadius);
  851.         pWicRT->FillEllipse(&e, pBlackBrush);
  852. */
  853. /*
  854. ID2D1SolidColorBrush* pPocketBrush = nullptr;
  855. ID2D1SolidColorBrush* pRimBrush = nullptr;
  856. pWicRT->CreateSolidColorBrush(POCKET_COLOR, &pPocketBrush);
  857. pWicRT->CreateSolidColorBrush(D2D1::ColorF(0.1f, 0.1f, 0.1f), &pRimBrush);
  858. if (pPocketBrush && pRimBrush) {
  859.     for (int i = 0; i < 6; ++i) {
  860.         ID2D1PathGeometry* pPath = nullptr;
  861.         pFactory->CreatePathGeometry(&pPath);
  862.         if (pPath) {
  863.             ID2D1GeometrySink* pSink = nullptr;
  864.             if (SUCCEEDED(pPath->Open(&pSink))) {
  865.                 float currentVisualRadius = (i == 1 || i == 4) ? MIDDLE_HOLE_VISUAL_RADIUS : CORNER_HOLE_VISUAL_RADIUS;
  866.                 float mouthRadius = currentVisualRadius * 1.5f;
  867.                 float backRadius = currentVisualRadius * 1.1f;
  868.                 D2D1_POINT_2F center = pocketPositions[i];
  869.                 D2D1_POINT_2F p1, p2;
  870.                 D2D1_SWEEP_DIRECTION sweep;
  871.                 if (i == 0) {
  872.                     p1 = D2D1::Point2F(center.x + mouthRadius, center.y);
  873.                     p2 = D2D1::Point2F(center.x, center.y + mouthRadius);
  874.                     sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  875.                 }
  876.                 else if (i == 2) {
  877.                     p1 = D2D1::Point2F(center.x, center.y + mouthRadius);
  878.                     p2 = D2D1::Point2F(center.x - mouthRadius, center.y);
  879.                     sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  880.                 }
  881.                 else if (i == 3) {
  882.                     p1 = D2D1::Point2F(center.x, center.y - mouthRadius);
  883.                     p2 = D2D1::Point2F(center.x + mouthRadius, center.y);
  884.                     sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  885.                 }
  886.                 else if (i == 5) {
  887.                     p1 = D2D1::Point2F(center.x - mouthRadius, center.y);
  888.                     p2 = D2D1::Point2F(center.x, center.y - mouthRadius);
  889.                     sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  890.                 }
  891.                 else if (i == 1) {
  892.                     p1 = D2D1::Point2F(center.x - mouthRadius / 1.5f, center.y);
  893.                     p2 = D2D1::Point2F(center.x + mouthRadius / 1.5f, center.y);
  894.                     sweep = D2D1_SWEEP_DIRECTION_CLOCKWISE;
  895.                 }
  896.                 else {
  897.                     p1 = D2D1::Point2F(center.x + mouthRadius / 1.5f, center.y);
  898.                     p2 = D2D1::Point2F(center.x - mouthRadius / 1.5f, center.y);
  899.                     sweep = D2D1_SWEEP_DIRECTION_CLOCKWISE;
  900.                 }
  901.                 pSink->BeginFigure(center, D2D1_FIGURE_BEGIN_FILLED);
  902.                 pSink->AddLine(p1);
  903.                 pSink->AddArc(D2D1::ArcSegment(p2, D2D1::SizeF(backRadius, backRadius), 0.0f, sweep, D2D1_ARC_SIZE_SMALL));
  904.                 pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  905.                 pSink->Close();
  906.                 SafeRelease(&pSink);
  907.                 pWicRT->FillGeometry(pPath, pPocketBrush);
  908.                 // Draw the inner rim for a beveled effect (Start)
  909.                 D2D1::Matrix3x2F scale = D2D1::Matrix3x2F::Scale(0.8f, 0.8f, center);
  910.                 ID2D1TransformedGeometry* pTransformedGeo = nullptr;
  911.                 pFactory->CreateTransformedGeometry(pPath, &scale, &pTransformedGeo);
  912.                 if (pTransformedGeo) {
  913.                     pWicRT->FillGeometry(pTransformedGeo, pRimBrush);
  914.                     SafeRelease(&pTransformedGeo);
  915.                 } //End
  916.             }
  917.             SafeRelease(&pPath);
  918.         }
  919.     }
  920. }
  921. SafeRelease(&pPocketBrush);
  922. SafeRelease(&pRimBrush);
  923.  
  924. // If your visual is a semicircle or a complex path, create + fill a path geometry here:
  925. // ID2D1PathGeometry* pPath; pFactory->CreatePathGeometry(&pPath); ... FillGeometry ...
  926. //}
  927.  
  928. // End drawing
  929. pWicRT->EndDraw();
  930.  
  931. // Release brush & render target (we still have the WIC bitmap to lock/read)
  932. //SafeRelease(&pBlackBrush);
  933. SafeRelease(&pWicRT);
  934.  
  935. // Lock WIC bitmap and read pixel data (32bppPBGRA -> bytes: B G R A premultiplied)
  936. WICRect lockRect = { 0, 0, maskWidth, maskHeight };
  937. IWICBitmapLock* pLock = nullptr;
  938. hr = pWicBitmap->Lock(&lockRect, WICBitmapLockRead, &pLock);
  939. if (SUCCEEDED(hr) && pLock) {
  940.     UINT cbStride = 0;
  941.     UINT cbBufferSize = 0;
  942.     BYTE* pv = nullptr;
  943.     hr = pLock->GetDataPointer(&cbBufferSize, &pv);
  944.     pLock->GetStride(&cbStride);
  945.  
  946.     if (SUCCEEDED(hr) && pv) {
  947.         // Iterate rows -> columns; pixel is 4 bytes (B,G,R,A) premultiplied
  948.         for (int y = 0; y < maskHeight; ++y) {
  949.             BYTE* row = pv + y * cbStride;
  950.             int base = y * maskWidth;
  951.             for (int x = 0; x < maskWidth; ++x) {
  952.                 BYTE a = row[x * 4 + 3]; // alpha channel
  953.                 pocketMask[base + x] = (a > ALPHA_THRESHOLD) ? 1 : 0;
  954.             }
  955.         }
  956.     }
  957.     pLock->Release();
  958. }
  959.  
  960. pWicBitmap->Release();
  961. }
  962. */
  963.  
  964. // Helper: world coords -> mask pixel coords (rounded). returns false if outside mask bounds.
  965. inline bool WorldToMaskPixel_Masks(float worldX, float worldY, int& outX, int& outY)
  966. {
  967.     float px = (worldX - pocketMaskOriginX) * pocketMaskScale;
  968.     float py = (worldY - pocketMaskOriginY) * pocketMaskScale;
  969.     int ix = (int)floorf(px + 0.5f);
  970.     int iy = (int)floorf(py + 0.5f);
  971.     if (ix < 0 || iy < 0 || ix >= pocketMaskWidth || iy >= pocketMaskHeight) return false;
  972.     outX = ix; outY = iy; return true;
  973. }
  974.  
  975. // ----------------------------------------------------------------------
  976. // IsBallTouchingPocketMask_D2D (unchanged pixel-perfect test)
  977. // ----------------------------------------------------------------------
  978. bool IsBallTouchingPocketMask_D2D(const Ball& b, int pocketIndex)
  979. {
  980.     if (pocketIndex < 0 || pocketIndex >= (int)pocketMasks.size()) return false;
  981.     if (pocketMaskWidth <= 0 || pocketMaskHeight <= 0) return false;
  982.     const std::vector<uint8_t>& mask = pocketMasks[pocketIndex];
  983.     if (mask.empty()) return false;
  984.  
  985.     // --- FOOLPROOF FIX: Transform the ball's center into the mask's local space ---
  986.     float ballMaskX = (b.x - pocketPositions[pocketIndex].x) * pocketMaskScale + (pocketMaskWidth / 2.0f);
  987.     float ballMaskY = (b.y - pocketPositions[pocketIndex].y) * pocketMaskScale + (pocketMaskHeight / 2.0f);
  988.     float radiusInPixels = BALL_RADIUS * pocketMaskScale;
  989.  
  990.     // Ball bounding box in world coords
  991.     /*float leftW = b.x - BALL_RADIUS;
  992.     float rightW = b.x + BALL_RADIUS;
  993.     float topW = b.y - BALL_RADIUS;
  994.     float bottomW = b.y + BALL_RADIUS;
  995.  
  996.     int leftPx = (int)floorf((leftW - pocketMaskOriginX) * pocketMaskScale);
  997.     int topPx = (int)floorf((topW - pocketMaskOriginY) * pocketMaskScale);
  998.     int rightPx = (int)ceilf((rightW - pocketMaskOriginX) * pocketMaskScale);
  999.     int bottomPx = (int)ceilf((bottomW - pocketMaskOriginY) * pocketMaskScale);
  1000.  
  1001.     // clamp to mask bounds
  1002.     leftPx = std::max(0, leftPx);
  1003.     topPx = std::max(0, topPx);
  1004.     rightPx = std::min(pocketMaskWidth - 1, rightPx);
  1005.     bottomPx = std::min(pocketMaskHeight - 1, bottomPx);
  1006.  
  1007.     // ball center and radius in pixels
  1008.     float cx = (b.x - pocketMaskOriginX) * pocketMaskScale;
  1009.     float cy = (b.y - pocketMaskOriginY) * pocketMaskScale;
  1010.     float rPx = BALL_RADIUS * pocketMaskScale;
  1011.     float rPx2 = rPx * rPx;*/
  1012.  
  1013.     // Define a search area around the ball's transformed position
  1014.     int startX = std::max(0, static_cast<int>(ballMaskX - radiusInPixels));
  1015.     int endX = std::min(pocketMaskWidth - 1, static_cast<int>(ballMaskX + radiusInPixels));
  1016.     int startY = std::max(0, static_cast<int>(ballMaskY - radiusInPixels));
  1017.     int endY = std::min(pocketMaskHeight - 1, static_cast<int>(ballMaskY + radiusInPixels));
  1018.  
  1019.     // Check each pixel within the search area
  1020.     for (int y = startY; y <= endY; ++y) {
  1021.         int rowBase = y * pocketMaskWidth;
  1022.         for (int x = startX; x <= endX; ++x) {
  1023.             // Check if this mask pixel is "solid" (part of the pocket)
  1024.             if (mask[rowBase + x] > 0) {
  1025.                 // Check if the distance from the pixel to the ball's center is within the ball's radius
  1026.                 float dx = (float)x - ballMaskX;
  1027.                 float dy = (float)y - ballMaskY;
  1028.                 if (dx * dx + dy * dy < radiusInPixels * radiusInPixels) {
  1029.                     return true; // Collision detected!
  1030.                 }
  1031.  
  1032.                 /*for (int yy = topPx; yy <= bottomPx; ++yy) {
  1033.                     int rowBase = yy * pocketMaskWidth;
  1034.                     for (int xx = leftPx; xx <= rightPx; ++xx) {
  1035.                         float px = (float)xx + 0.5f;
  1036.                         float py = (float)yy + 0.5f;
  1037.                         float dx = px - cx;
  1038.                         float dy = py - cy;
  1039.                         if (dx * dx + dy * dy <= rPx2) {
  1040.                             if (mask[rowBase + xx]) return true;*/
  1041.             }
  1042.         }
  1043.     }
  1044.     return false;
  1045. }
  1046.  
  1047. /*
  1048. // Pixel-perfect test using the selected pocket mask
  1049. bool IsBallTouchingPocketMask_D2D(const Ball& b, int pocketIndex)
  1050. {
  1051.     if (pocketIndex < 0 || pocketIndex >= (int)pocketMasks.size()) return false;
  1052.     if (pocketMaskWidth <= 0 || pocketMaskHeight <= 0) return false;
  1053.     const std::vector<uint8_t>& mask = pocketMasks[pocketIndex];
  1054.     if (mask.empty()) return false;
  1055.  
  1056.     // Ball bounding box in world coords
  1057.     float leftW = b.x - BALL_RADIUS;
  1058.     float rightW = b.x + BALL_RADIUS;
  1059.     float topW = b.y - BALL_RADIUS;
  1060.     float bottomW = b.y + BALL_RADIUS;
  1061.  
  1062.     int leftPx = (int)floorf((leftW - pocketMaskOriginX) * pocketMaskScale);
  1063.     int topPx = (int)floorf((topW - pocketMaskOriginY) * pocketMaskScale);
  1064.     int rightPx = (int)ceilf((rightW - pocketMaskOriginX) * pocketMaskScale);
  1065.     int bottomPx = (int)ceilf((bottomW - pocketMaskOriginY) * pocketMaskScale);
  1066.  
  1067.     // clamp to mask bounds
  1068.     leftPx = std::max(0, leftPx);
  1069.     topPx = std::max(0, topPx);
  1070.     rightPx = std::min(pocketMaskWidth - 1, rightPx);
  1071.     bottomPx = std::min(pocketMaskHeight - 1, bottomPx);
  1072.  
  1073.     // ball center and radius in pixels
  1074.     float cx = (b.x - pocketMaskOriginX) * pocketMaskScale;
  1075.     float cy = (b.y - pocketMaskOriginY) * pocketMaskScale;
  1076.     float rPx = BALL_RADIUS * pocketMaskScale;
  1077.     float rPx2 = rPx * rPx;
  1078.  
  1079.     for (int yy = topPx; yy <= bottomPx; ++yy) {
  1080.         int rowBase = yy * pocketMaskWidth;
  1081.         for (int xx = leftPx; xx <= rightPx; ++xx) {
  1082.             float px = (float)xx + 0.5f;
  1083.             float py = (float)yy + 0.5f;
  1084.             float dx = px - cx;
  1085.             float dy = py - cy;
  1086.             if (dx * dx + dy * dy <= rPx2) {
  1087.                 if (mask[rowBase + xx]) return true;
  1088.             }
  1089.         }
  1090.     }
  1091.     return false;
  1092. }*/
  1093.  
  1094. bool IsWrongTargetForCurrentPlayer(const Ball* ball) {
  1095.     if (!ball) return false;
  1096.     if (ball->id == 8) return false; // 8-ball is always legal when on 8-ball
  1097.     if (currentPlayer == 1 && player1Info.assignedType != BallType::NONE)
  1098.         return ball->type != player1Info.assignedType;
  1099.     if (currentPlayer == 2 && player2Info.assignedType != BallType::NONE)
  1100.         return ball->type != player2Info.assignedType;
  1101.     return false; // If not assigned yet, can't be wrong
  1102. }
  1103.  
  1104.  
  1105. //new polygon mask helpers
  1106. // -----------------------------
  1107. // Polygon-based pocket hit test
  1108. // -----------------------------
  1109. // Add these helper functions near your other geometry helpers.
  1110. // This implementation approximates pocket curves with a sampled polygon
  1111. // then does precise point-in-polygon and point-to-segment checks.
  1112. // This avoids any Direct2D FillContainsPoint incompatibility and
  1113. // gives deterministic shape-based results (not circle-based).
  1114. //
  1115. // Tweak SAMPLE_PER_QUARTER_CIRCLE if you want finer resolution.
  1116.  
  1117. static const int SAMPLE_PER_QUARTER_CIRCLE = 24; // controls polygon smoothness (increase = more precise) (default=14)
  1118.  
  1119. static float Sq(float v) { return v * v; }
  1120.  
  1121. static float DistancePointSegmentSq(const D2D1_POINT_2F& p, const D2D1_POINT_2F& a, const D2D1_POINT_2F& b)
  1122. {
  1123.     // compute squared distance from p to segment ab
  1124.     D2D1_POINT_2F ab = { b.x - a.x, b.y - a.y };
  1125.     D2D1_POINT_2F ap = { p.x - a.x, p.y - a.y };
  1126.     float abLen2 = ab.x * ab.x + ab.y * ab.y;
  1127.     if (abLen2 <= 1e-8f) {
  1128.         return (p.x - a.x) * (p.x - a.x) + (p.y - a.y) * (p.y - a.y);
  1129.     }
  1130.     float t = (ap.x * ab.x + ap.y * ab.y) / abLen2;
  1131.     if (t < 0.0f) t = 0.0f;
  1132.     else if (t > 1.0f) t = 1.0f;
  1133.     D2D1_POINT_2F proj = { a.x + ab.x * t, a.y + ab.y * t };
  1134.     return (p.x - proj.x) * (p.x - proj.x) + (p.y - proj.y) * (p.y - proj.y);
  1135. }
  1136.  
  1137. // Winding/ray-cast point-in-polygon (non-zero winding). Returns true if inside.
  1138. static bool PointInPolygon(const std::vector<D2D1_POINT_2F>& poly, const D2D1_POINT_2F& pt)
  1139. {
  1140.     bool inside = false;
  1141.     size_t n = poly.size();
  1142.     if (n < 3) return false;
  1143.     for (size_t i = 0, j = n - 1; i < n; j = i++) {
  1144.         const D2D1_POINT_2F& pi = poly[i], & pj = poly[j];
  1145.         bool intersect = ((pi.y > pt.y) != (pj.y > pt.y)) &&
  1146.             (pt.x < (pj.x - pi.x)* (pt.y - pi.y) / (pj.y - pi.y + 1e-12f) + pi.x);
  1147.         if (intersect) inside = !inside;
  1148.     }
  1149.     return inside;
  1150. }
  1151.  
  1152. // build an approximated polygon describing the black/inner pocket area (the "hole")
  1153. // pIndex: 0..5
  1154. // output poly is in the same coordinate space as your table (pixel coordinates)
  1155. static void BuildPocketPolygon(int pIndex, std::vector<D2D1_POINT_2F>& outPoly)
  1156. {
  1157.     outPoly.clear();
  1158.     D2D1_POINT_2F center = pocketPositions[pIndex];
  1159.  
  1160.     // choose inner black radius for the pocket (this should match the drawn 'black' mouth)
  1161.     float vis = GetPocketVisualRadius(pIndex);
  1162.     float innerRadius = vis * 0.55f; // tweak multiplier to match your drawn black area exactly (default=0.85)
  1163.  
  1164.     int samples = SAMPLE_PER_QUARTER_CIRCLE * 2; // semi-circle uses half circle of samples
  1165.  
  1166.     // Middle pockets (top-middle index 1, bottom-middle index 4) -> semicircle opening into table
  1167.     if (pIndex == 1 || pIndex == 4) {
  1168.         // top-middle (1): semicircle opening downward => angles [0..PI]
  1169.         // bottom-middle (4): semicircle opening upward => angles [PI..2PI]
  1170.         float a0 = (pIndex == 1) ? 0.0f : PI;
  1171.         float a1 = a0 + PI;
  1172.         for (int i = 0; i <= samples; ++i) {
  1173.             float t = float(i) / float(samples);
  1174.             float a = a0 + (a1 - a0) * t;
  1175.             float x = center.x + cosf(a) * innerRadius;
  1176.             float y = center.y + sinf(a) * innerRadius;
  1177.             outPoly.push_back(D2D1::Point2F(x, y));
  1178.         }
  1179.         // close polygon by adding the center "mouth" edge (slightly inside) to make a filled shape
  1180.         // we insert two small points inside the semicircle to make the polygon closed and reasonable
  1181.         outPoly.push_back(D2D1::Point2F(center.x + innerRadius * 0.25f, center.y)); // inner mid-right
  1182.         outPoly.push_back(D2D1::Point2F(center.x - innerRadius * 0.25f, center.y)); // inner mid-left
  1183.         return;
  1184.     }
  1185.  
  1186.     // Corner pockets: quarter-circle interior where black area is inside the table corner.
  1187.     // Create a quarter-arc polygon oriented depending on which corner.
  1188.     float startAngle = 0.0f, endAngle = 0.0f;
  1189.     // p0 TL, p2 TR, p3 BL, p5 BR
  1190.     // angle mapping:
  1191.     // 0 -> right (0), PI/2 -> down, PI -> left, 3PI/2 -> up
  1192.     if (pIndex == 0) { // top-left: interior down-right => angles [0 .. PI/2]
  1193.         startAngle = 0.0f; endAngle = PI / 2.0f;
  1194.     }
  1195.     else if (pIndex == 2) { // top-right: interior down-left => angles [PI/2 .. PI]
  1196.         startAngle = PI / 2.0f; endAngle = PI;
  1197.     }
  1198.     else if (pIndex == 3) { // bottom-left: interior up-right => angles [3PI/2 .. 2PI]
  1199.         startAngle = 3.0f * PI / 2.0f; endAngle = 2.0f * PI;
  1200.     }
  1201.     else if (pIndex == 5) { // bottom-right: interior up-left => angles [PI .. 3PI/2]
  1202.         startAngle = PI; endAngle = 3.0f * PI / 2.0f;
  1203.     }
  1204.     else {
  1205.         // fallback: full circle
  1206.         startAngle = 0.0f; endAngle = 2.0f * PI;
  1207.     }
  1208.  
  1209.     int quarterSamples = SAMPLE_PER_QUARTER_CIRCLE;
  1210.     for (int i = 0; i <= quarterSamples; ++i) {
  1211.         float t = float(i) / float(quarterSamples);
  1212.         float a = startAngle + (endAngle - startAngle) * t;
  1213.         float x = center.x + cosf(a) * innerRadius;
  1214.         float y = center.y + sinf(a) * innerRadius;
  1215.         outPoly.push_back(D2D1::Point2F(x, y));
  1216.     }
  1217.     // add a small interior chord to close polygon toward table inside
  1218.     // determine inward direction (table interior)
  1219.     D2D1_POINT_2F innerOffset = { 0, 0 };
  1220.     if (pIndex == 0) innerOffset = { innerRadius * 0.35f, innerRadius * 0.35f }; // down-right
  1221.     if (pIndex == 2) innerOffset = { -innerRadius * 0.35f, innerRadius * 0.35f }; // down-left
  1222.     if (pIndex == 3) innerOffset = { innerRadius * 0.35f, -innerRadius * 0.35f }; // up-right
  1223.     if (pIndex == 5) innerOffset = { -innerRadius * 0.35f, -innerRadius * 0.35f }; // up-left
  1224.  
  1225.     outPoly.push_back(D2D1::Point2F(center.x + innerOffset.x, center.y + innerOffset.y));
  1226. }
  1227.  
  1228. // Main high precision pocket test using polygon
  1229. // returns true if ball overlaps or touches the polygonal black area
  1230. bool IsBallInPocketPolygon(const Ball& b, int pIndex)
  1231. {
  1232.     if (pIndex < 0 || pIndex > 5) return false;
  1233.  
  1234.     // Build polygon describing pocket black area
  1235.     std::vector<D2D1_POINT_2F> poly;
  1236.     BuildPocketPolygon(pIndex, poly);
  1237.     if (poly.size() < 3) return false;
  1238.  
  1239.     D2D1_POINT_2F center = D2D1::Point2F(b.x, b.y);
  1240.  
  1241.     // Quick bounding-box reject (cheap)
  1242.     float minx = FLT_MAX, miny = FLT_MAX, maxx = -FLT_MAX, maxy = -FLT_MAX;
  1243.     for (auto& pt : poly) {
  1244.         if (pt.x < minx) minx = pt.x;
  1245.         if (pt.y < miny) miny = pt.y;
  1246.         if (pt.x > maxx) maxx = pt.x;
  1247.         if (pt.y > maxy) maxy = pt.y;
  1248.     }
  1249.     // expand by BALL_RADIUS
  1250.     minx -= BALL_RADIUS; miny -= BALL_RADIUS; maxx += BALL_RADIUS; maxy += BALL_RADIUS;
  1251.     if (center.x < minx || center.x > maxx || center.y < miny || center.y > maxy) {
  1252.         // center outside expanded bounds; not enough to intersect
  1253.         // but still we should check if the ball edge could overlap an extended corner -> we've expanded by BALL_RADIUS so safe
  1254.         return false;
  1255.     }
  1256.  
  1257.     // 1) If ball center is inside the polygon -> pocketed
  1258.     if (PointInPolygon(poly, center)) {
  1259.         // Table side check: ensure ball is approaching from table side (avoid false positives from below/above)
  1260.         bool topPocket = (pIndex == 0 || pIndex == 1 || pIndex == 2);
  1261.         if (topPocket) {
  1262.             if (b.y < pocketPositions[pIndex].y - BALL_RADIUS) return false;
  1263.         }
  1264.         else {
  1265.             if (b.y > pocketPositions[pIndex].y + BALL_RADIUS) return false;
  1266.         }
  1267.         return true;
  1268.     }
  1269.  
  1270.     // 2) Otherwise, check distance from ball center to any polygon edge
  1271.     float rr = BALL_RADIUS * BALL_RADIUS;
  1272.     for (size_t i = 0, n = poly.size(); i < n; ++i) {
  1273.         const D2D1_POINT_2F& a = poly[i];
  1274.         const D2D1_POINT_2F& bb = poly[(i + 1) % n];
  1275.         float d2 = DistancePointSegmentSq(center, a, bb);
  1276.         if (d2 <= rr + 1e-6f) {
  1277.             // edge-touch candidate -> verify table side (avoid outside approach)
  1278.             bool topPocket = (pIndex == 0 || pIndex == 1 || pIndex == 2);
  1279.             if (topPocket) {
  1280.                 if (b.y < pocketPositions[pIndex].y - BALL_RADIUS) return false;
  1281.             }
  1282.             else {
  1283.                 if (b.y > pocketPositions[pIndex].y + BALL_RADIUS) return false;
  1284.             }
  1285.             return true;
  1286.         }
  1287.     }
  1288.  
  1289.     return false;
  1290. }
  1291.  
  1292. bool IsBallInPocket(const D2D1_POINT_2F& ballPos) {
  1293.     // New: check if ball is within V-shaped cutout region at any pocket
  1294.     for (int i = 0; i < 6; ++i) {
  1295.         D2D1_POINT_2F center = pocketPositions[i];
  1296.         D2D1_POINT_2F prev = pocketPositions[(i + 5) % 6];
  1297.         D2D1_POINT_2F next = pocketPositions[(i + 1) % 6];
  1298.         float dx1 = center.x - prev.x, dy1 = center.y - prev.y;
  1299.         float dx2 = next.x - center.x, dy2 = next.y - center.y;
  1300.         float len1 = sqrtf(dx1 * dx1 + dy1 * dy1);
  1301.         float len2 = sqrtf(dx2 * dx2 + dy2 * dy2);
  1302.         dx1 /= len1; dy1 /= len1;
  1303.         dx2 /= len2; dy2 /= len2;
  1304.         float bisectX = dx1 + dx2;
  1305.         float bisectY = dy1 + dy2;
  1306.         float bisectLen = sqrtf(bisectX * bisectX + bisectY * bisectY);
  1307.         bisectX /= bisectLen; bisectY /= bisectLen;
  1308.         // V-cut tip
  1309.         D2D1_POINT_2F vTip = {
  1310.             center.x + bisectX * CHAMFER_SIZE,
  1311.             center.y + bisectY * CHAMFER_SIZE
  1312.         };
  1313.         // V-cut base points
  1314.         float perpX = -bisectY, perpY = bisectX;
  1315.         D2D1_POINT_2F vBase1 = {
  1316.             center.x + perpX * (CHAMFER_SIZE)+bisectX * INNER_RIM_THICKNESS, // width/2 becomes chamfer_size
  1317.             center.y + perpY * (CHAMFER_SIZE)+bisectY * INNER_RIM_THICKNESS
  1318.         };
  1319.         D2D1_POINT_2F vBase2 = {
  1320.             center.x - perpX * (CHAMFER_SIZE)+bisectX * INNER_RIM_THICKNESS,
  1321.             center.y - perpY * (CHAMFER_SIZE)+bisectY * INNER_RIM_THICKNESS
  1322.         };
  1323.         // Point-in-triangle test for V region
  1324.         if (PointInTriangle(ballPos, vBase1, vTip, vBase2))
  1325.             return true;
  1326.     }
  1327.     return false;
  1328. }
  1329.  
  1330. // Helper: Point-in-triangle test (barycentric)
  1331. bool PointInTriangle(const D2D1_POINT_2F& p, const D2D1_POINT_2F& a, const D2D1_POINT_2F& b, const D2D1_POINT_2F& c) {
  1332.     float dX = p.x - c.x;
  1333.     float dY = p.y - c.y;
  1334.     float dX21 = c.x - b.x;
  1335.     float dY12 = b.y - c.y;
  1336.     float D = dY12 * (a.x - c.x) + dX21 * (a.y - c.y);
  1337.     float s = dY12 * dX + dX21 * dY;
  1338.     float t = (c.y - a.y) * dX + (a.x - c.x) * dY;
  1339.     if (D < 0) return (s <= 0) && (t <= 0) && (s + t >= D);
  1340.     return (s >= 0) && (t >= 0) && (s + t <= D);
  1341. }
  1342.  
  1343. // Backwards-compatible alias: some places in the code call IsBallInPocket(...)
  1344. // so provide a thin wrapper that uses the precise black-area test.
  1345. bool IsBallInPocket(const Ball& b, int pIndex)
  1346. {
  1347.     return IsBallInPocketPolygon(b, pIndex);
  1348. }
  1349.  
  1350. // Backwards-compatible wrapper (if your code calls IsBallInPocket(...))
  1351. bool IsBallInPocket(const Ball* ball, int p)
  1352. {
  1353.     if (!ball) return false;
  1354.     return IsBallInPocketPolygon(*ball, p);
  1355. } //end
  1356.  
  1357.  
  1358. // Flatten one cubic bezier into a polyline (uniform sampling).
  1359. static void FlattenCubicBezier(const std::array<D2D1_POINT_2F, 4>& bz, std::vector<D2D1_POINT_2F>& outPts, int steps = 16)
  1360. {
  1361.     outPts.clear();
  1362.     outPts.reserve(steps + 1);
  1363.     for (int i = 0; i <= steps; ++i) {
  1364.         float t = (float)i / (float)steps;
  1365.         float mt = 1.0f - t;
  1366.         // De Casteljau cubic
  1367.         float x =
  1368.             mt * mt * mt * bz[0].x +
  1369.             3.0f * mt * mt * t * bz[1].x +
  1370.             3.0f * mt * t * t * bz[2].x +
  1371.             t * t * t * bz[3].x;
  1372.         float y =
  1373.             mt * mt * mt * bz[0].y +
  1374.             3.0f * mt * mt * t * bz[1].y +
  1375.             3.0f * mt * t * t * bz[2].y +
  1376.             t * t * t * bz[3].y;
  1377.         outPts.push_back(D2D1::Point2F(x, y));
  1378.     }
  1379. }
  1380.  
  1381. // squared distance point -> segment
  1382. static inline float PointSegDistSq(const D2D1_POINT_2F& p, const D2D1_POINT_2F& a, const D2D1_POINT_2F& b)
  1383. {
  1384.     float vx = b.x - a.x, vy = b.y - a.y;
  1385.     float wx = p.x - a.x, wy = p.y - a.y;
  1386.     float c1 = vx * wx + vy * wy;
  1387.     if (c1 <= 0.0f) {
  1388.         float dx = p.x - a.x, dy = p.y - a.y;
  1389.         return dx * dx + dy * dy;
  1390.     }
  1391.     float c2 = vx * vx + vy * vy;
  1392.     if (c2 <= c1) {
  1393.         float dx = p.x - b.x, dy = p.y - b.y;
  1394.         return dx * dx + dy * dy;
  1395.     }
  1396.     float t = c1 / c2;
  1397.     float projx = a.x + vx * t;
  1398.     float projy = a.y + vy * t;
  1399.     float dx = p.x - projx, dy = p.y - projy;
  1400.     return dx * dx + dy * dy;
  1401. }
  1402.  
  1403. // Point-in-polygon (winding rule). flattened polyline is assumed closed.
  1404. static bool PointInPolygonWinding(const D2D1_POINT_2F& pt, const std::vector<D2D1_POINT_2F>& poly)
  1405. {
  1406.     int wn = 0;
  1407.     size_t n = poly.size();
  1408.     if (n < 3) return false;
  1409.     for (size_t i = 0; i < n; ++i) {
  1410.         const D2D1_POINT_2F& a = poly[i];
  1411.         const D2D1_POINT_2F& b = poly[(i + 1) % n];
  1412.         if (a.y <= pt.y) {
  1413.             if (b.y > pt.y) { // upward crossing
  1414.                 float isLeft = (b.x - a.x) * (pt.y - a.y) - (pt.x - a.x) * (b.y - a.y);
  1415.                 if (isLeft > 0.0f) ++wn;
  1416.             }
  1417.         }
  1418.         else {
  1419.             if (b.y <= pt.y) { // downward crossing
  1420.                 float isLeft = (b.x - a.x) * (pt.y - a.y) - (pt.x - a.x) * (b.y - a.y);
  1421.                 if (isLeft < 0.0f) --wn;
  1422.             }
  1423.         }
  1424.     }
  1425.     return wn != 0;
  1426. }
  1427.  
  1428. // Add a circular arc (possibly >90deg) approximated by cubic beziers.
  1429. // center, radius, startAngle (radians), sweepAngle (radians). Sweep may be > PI/2,
  1430. // so we subdivide into <= PI/2 segments.
  1431. static void AddArcAsCubics(std::vector<std::array<D2D1_POINT_2F, 4>>& out, D2D1_POINT_2F center, float radius, float startAngle, float sweep)
  1432. {
  1433.     // normalize sweep sign and break into pieces of max 90 degrees
  1434.     const float MAXSEG = PI / 2.0f; // 90deg
  1435.     int segs = (int)ceilf(fabsf(sweep) / MAXSEG);
  1436.     float segAngle = sweep / segs;
  1437.     float a0 = startAngle;
  1438.     for (int i = 0; i < segs; ++i) {
  1439.         float a1 = a0 + segAngle;
  1440.         float theta = a1 - a0;
  1441.         float alpha = (4.0f / 3.0f) * tanf(theta / 4.0f); // control length factor
  1442.         D2D1_POINT_2F p0 = { center.x + radius * cosf(a0), center.y + radius * sinf(a0) };
  1443.         D2D1_POINT_2F p3 = { center.x + radius * cosf(a1), center.y + radius * sinf(a1) };
  1444.         D2D1_POINT_2F t0 = { -sinf(a0), cosf(a0) }; // unit tangent at p0
  1445.         D2D1_POINT_2F t1 = { -sinf(a1), cosf(a1) }; // unit tangent at p3
  1446.         D2D1_POINT_2F p1 = { p0.x + alpha * radius * t0.x, p0.y + alpha * radius * t0.y };
  1447.         D2D1_POINT_2F p2 = { p3.x - alpha * radius * t1.x, p3.y - alpha * radius * t1.y };
  1448.         out.push_back({ p0, p1, p2, p3 });
  1449.         a0 = a1;
  1450.     }
  1451. }
  1452.  
  1453. // Build the pocket black-area bezier description (semicircles for middles,
  1454. // quarter/rounded for corners). Caches results in g_pocketBezierCache.
  1455. static void EnsurePocketBezierCache()
  1456. {
  1457.     if (g_pocketBezierCacheInitialized) return;
  1458.     g_pocketBezierCacheInitialized = true;
  1459.     g_pocketBezierCache.clear();
  1460.     g_pocketBezierCache.resize(6);
  1461.  
  1462.     for (int p = 0; p < 6; ++p) {
  1463.         D2D1_POINT_2F c = pocketPositions[p];
  1464.         float pocketVis = GetPocketVisualRadius(p); // uses your existing helper
  1465.         float inner = pocketVis * 0.88f; // base for the 'black' mouth. tweak if needed
  1466.  
  1467.         // decide arc angles (y increases downward)
  1468.         // Top-left (0): quarter arc from angle 0 (right) to PI/2 (down)
  1469.         // Top-middle (1): semicircle from angle 0 (right) to PI (left) - lower half
  1470.         // Top-right (2): quarter arc from PI/2 (down) to PI (left)
  1471.         // Bottom-left (3): quarter arc from 3PI/2 (up) to 2PI (right)
  1472.         // Bottom-middle (4): semicircle from PI (left) to 2PI (right) - upper half
  1473.         // Bottom-right (5): quarter arc from PI (left) to 3PI/2 (up)
  1474.         const float TWO_PI = 2.0f * PI;
  1475.         if (p == 1) {
  1476.             // top middle -> semicircle opening downward (angles 0 -> PI)
  1477.             AddArcAsCubics(g_pocketBezierCache[p], c, inner, 0.0f, PI);
  1478.         }
  1479.         else if (p == 4) {
  1480.             // bottom middle -> semicircle opening upward (angles PI -> 2PI)
  1481.             AddArcAsCubics(g_pocketBezierCache[p], c, inner, PI, PI);
  1482.         }
  1483.         else if (p == 0) {
  1484.             // top-left quarter: right -> down (0 -> PI/2)
  1485.             AddArcAsCubics(g_pocketBezierCache[p], c, inner, 0.0f, PI / 2.0f);
  1486.         }
  1487.         else if (p == 2) {
  1488.             // top-right quarter: down -> left (PI/2 -> PI)
  1489.             AddArcAsCubics(g_pocketBezierCache[p], c, inner, PI / 2.0f, PI / 2.0f);
  1490.         }
  1491.         else if (p == 3) {
  1492.             // bottom-left quarter: up -> right (3PI/2 -> 2PI)
  1493.             AddArcAsCubics(g_pocketBezierCache[p], c, inner, 3.0f * PI / 2.0f, PI / 2.0f);
  1494.         }
  1495.         else if (p == 5) {
  1496.             // bottom-right quarter: left -> up (PI -> 3PI/2)
  1497.             AddArcAsCubics(g_pocketBezierCache[p], c, inner, PI, PI / 2.0f);
  1498.         }
  1499.     }
  1500. }
  1501. //above are bezier mask helpers
  1502.  
  1503. //below are pixel-perfect bezier matching helpers
  1504.  
  1505.  
  1506. // -------------------------------------------------------------------------
  1507. // Geometry helpers for precise pocket shape hit-testing
  1508. // -------------------------------------------------------------------------
  1509. static float DistPointToSegment(const D2D1_POINT_2F& p, const D2D1_POINT_2F& a, const D2D1_POINT_2F& b)
  1510. {
  1511.     // squared distance project of p onto segment ab
  1512.     D2D1_POINT_2F ab = { b.x - a.x, b.y - a.y };
  1513.     D2D1_POINT_2F ap = { p.x - a.x, p.y - a.y };
  1514.     float ab2 = ab.x * ab.x + ab.y * ab.y;
  1515.     if (ab2 <= 1e-8f) {
  1516.         float dx = p.x - a.x, dy = p.y - a.y;
  1517.         return sqrtf(dx * dx + dy * dy);
  1518.     }
  1519.     float t = (ap.x * ab.x + ap.y * ab.y) / ab2;
  1520.     if (t < 0.0f) t = 0.0f;
  1521.     if (t > 1.0f) t = 1.0f;
  1522.     D2D1_POINT_2F proj = { a.x + ab.x * t, a.y + ab.y * t };
  1523.     float dx = p.x - proj.x, dy = p.y - proj.y;
  1524.     return sqrtf(dx * dx + dy * dy);
  1525. }
  1526.  
  1527. static float NormalizeAngle(float a)
  1528. {
  1529.     // normalize to [0, 2PI)
  1530.     const float TWO_PI = 2.0f * PI;
  1531.     while (a < 0.0f) a += TWO_PI;
  1532.     while (a >= TWO_PI) a -= TWO_PI;
  1533.     return a;
  1534. }
  1535.  
  1536. // return true if angle `ang` is inside sector starting at startAngle
  1537. // sweeping `sweep` (sweep >= 0). Handles wrap-around.
  1538. static bool AngleInRange(float ang, float startAngle, float sweep)
  1539. {
  1540.     ang = NormalizeAngle(ang);
  1541.     startAngle = NormalizeAngle(startAngle);
  1542.     float endAngle = NormalizeAngle(startAngle + sweep);
  1543.     if (sweep >= 2.0f * PI - 1e-6f) return true;
  1544.     if (startAngle <= endAngle) {
  1545.         return (ang >= startAngle - 1e-6f && ang <= endAngle + 1e-6f);
  1546.     }
  1547.     else {
  1548.         // wrapped around
  1549.         return (ang >= startAngle - 1e-6f || ang <= endAngle + 1e-6f);
  1550.     }
  1551. }
  1552.  
  1553. // minimal distance from point `p` to a circular arc (centered at c, radius r,
  1554. // starting at startAngle for sweepAngle radians). Also returns if point is
  1555. // inside the filled sector (i.e., r0 <= r and angle in sector).
  1556. static float DistPointToArc(const D2D1_POINT_2F& p, const D2D1_POINT_2F& c, float r, float startAngle, float sweepAngle, bool& outInsideSector)
  1557. {
  1558.     float dx = p.x - c.x;
  1559.     float dy = p.y - c.y;
  1560.     float r0 = sqrtf(dx * dx + dy * dy);
  1561.     float ang = atan2f(dy, dx);
  1562.     ang = NormalizeAngle(ang);
  1563.  
  1564.     // endpoints of the arc
  1565.     float a1 = NormalizeAngle(startAngle);
  1566.     float a2 = NormalizeAngle(startAngle + sweepAngle);
  1567.  
  1568.     // is the point angle within sector?
  1569.     bool inSector = AngleInRange(ang, a1, sweepAngle);
  1570.     outInsideSector = (inSector && (r0 <= r + 1e-6f));
  1571.  
  1572.     if (inSector) {
  1573.         // distance to arc circle
  1574.         return fabsf(r0 - r);
  1575.     }
  1576.     else {
  1577.         // distance to arc endpoints
  1578.         D2D1_POINT_2F ep1 = { c.x + r * cosf(a1), c.y + r * sinf(a1) };
  1579.         D2D1_POINT_2F ep2 = { c.x + r * cosf(a2), c.y + r * sinf(a2) };
  1580.         float dx1 = p.x - ep1.x, dy1 = p.y - ep1.y;
  1581.         float dx2 = p.x - ep2.x, dy2 = p.y - ep2.y;
  1582.         float d1 = sqrtf(dx1 * dx1 + dy1 * dy1);
  1583.         float d2 = sqrtf(dx2 * dx2 + dy2 * dy2);
  1584.         return (d1 < d2) ? d1 : d2;
  1585.     }
  1586. }
  1587.  
  1588. // -------------------------------------------------------------------------
  1589. // High-precision pocket test: returns true when any part of the BALL
  1590. // overlaps the black pocket area (semicircle for middle pockets or
  1591. // corner pocket interior). Uses BALL_RADIUS so touching counts.
  1592. // Insert this function in the Helpers section (near other helpers).
  1593. // -------------------------------------------------------------------------
  1594. // -------------------------------------------------------------------------
  1595. // Precise test whether any part of the ball overlaps the black pocket shape
  1596. // (quarter/semicircle filled area). This function *replaces* the older loose
  1597. // radius/capsule approach and matches the actual black mouth shape.
  1598. // -------------------------------------------------------------------------
  1599. bool IsBallInPocketBlackArea(const Ball& b, int pIndex)
  1600. {
  1601.     if (pIndex < 0 || pIndex > 5) return false;
  1602.  
  1603.     D2D1_POINT_2F pc = pocketPositions[pIndex];
  1604.     // Use pocket visual radius converted to a conservative black-mouth radius
  1605.     float pocketVis = GetPocketVisualRadius(pIndex);
  1606.     // `blackRadius` controls how big the black area is relative to visual.
  1607.     // Reduce if you want more strictness.
  1608.     const float blackRadius = pocketVis * 0.55f; //0.88f(default) => 75 =>65=>55    
  1609.  
  1610.     // For top middle (1): semicircle opening downward (angles 0..PI),
  1611.     // for bottom middle (4): semicircle opening upward (angles PI..2PI).
  1612.     // For corners, quarter-circle angles depend on pocket index:
  1613.     // 0 (top-left): angles 0..PI/2  (right -> down)
  1614.     // 2 (top-right): angles PI/2..PI (down -> left)
  1615.     // 3 (bottom-left): angles 3PI/2..2PI (up -> right)
  1616.     // 5 (bottom-right): angles PI..3PI/2 (left -> up)
  1617.  
  1618.     D2D1_POINT_2F ballCenter = { b.x, b.y };
  1619.  
  1620.     // --- Middle pockets: semicircle + diameter segment ---
  1621.     if (pIndex == 1 || pIndex == 4) {
  1622.         // semicircle params
  1623.         float startAngle, sweep;
  1624.         if (pIndex == 1) {
  1625.             // top middle: arc from angle 0 (right) to pi (left) -> opening downward into table
  1626.             startAngle = 0.0f;
  1627.             sweep = PI;
  1628.             // require ball to be on table side (below center) when checking "inside"
  1629.             // we handle this orientation implicitly with the semicircle sector and diameter.
  1630.         }
  1631.         else {
  1632.             // bottom middle: arc from PI to 2PI (opening upward)
  1633.             startAngle = PI;
  1634.             sweep = PI;
  1635.         }
  1636.  
  1637.         // 1) If ball center is inside semicircular sector (r0 <= blackRadius and angle in sector)
  1638.         bool insideSector = false;
  1639.         float dx = ballCenter.x - pc.x;
  1640.         float dy = ballCenter.y - pc.y;
  1641.         float r0 = sqrtf(dx * dx + dy * dy);
  1642.         float ang = NormalizeAngle(atan2f(dy, dx));
  1643.         if (AngleInRange(ang, startAngle, sweep) && r0 <= blackRadius + 1e-6f) {
  1644.             // ball center lies strictly inside semicircle -> definitely overlaps
  1645.             return true;
  1646.         }
  1647.  
  1648.         // 2) if not, compute minimal distance to the semicircle filled shape boundary:
  1649.         //    boundary = arc (circular curve) + diameter segment (straight line between arc endpoints)
  1650.         bool tmpInsideArcSector = false;
  1651.         float distToArc = DistPointToArc(ballCenter, pc, blackRadius, startAngle, sweep, tmpInsideArcSector);
  1652.         // diameter endpoints
  1653.         D2D1_POINT_2F ep1 = { pc.x + blackRadius * cosf(startAngle), pc.y + blackRadius * sinf(startAngle) };
  1654.         D2D1_POINT_2F ep2 = { pc.x + blackRadius * cosf(startAngle + sweep), pc.y + blackRadius * sinf(startAngle + sweep) };
  1655.         float distToDiameter = DistPointToSegment(ballCenter, ep1, ep2);
  1656.  
  1657.         float minDist = (distToArc < distToDiameter) ? distToArc : distToDiameter;
  1658.  
  1659.         // If any part of the ball (circle radius) reaches into the filled semicircle -> collision
  1660.         return (minDist <= BALL_RADIUS + 1e-6f);
  1661.     }
  1662.     else {
  1663.         // --- Corner pockets: treat as filled quarter-circles ---
  1664.         float startAngle = 0.0f;
  1665.         // assign angles for each corner pocket (w/ y increasing downwards)
  1666.         if (pIndex == 0) {             // top-left: right->down (0 -> PI/2)
  1667.             startAngle = 0.0f;
  1668.         }
  1669.         else if (pIndex == 2) {      // top-right: down->left (PI/2 -> PI)
  1670.             startAngle = 0.5f * PI;
  1671.         }
  1672.         else if (pIndex == 5) {      // bottom-right: left->up (PI -> 3PI/2)
  1673.             startAngle = PI;
  1674.         }
  1675.         else if (pIndex == 3) {      // bottom-left: up->right (3PI/2 -> 2PI)
  1676.             startAngle = 1.5f * PI;
  1677.         }
  1678.         float sweep = 0.5f * PI; // 90 degrees
  1679.  
  1680.         // center-inside test (is ball center inside the quarter sector)
  1681.         float dx = ballCenter.x - pc.x;
  1682.         float dy = ballCenter.y - pc.y;
  1683.         float r0 = sqrtf(dx * dx + dy * dy);
  1684.         float ang = NormalizeAngle(atan2f(dy, dx));
  1685.         if (AngleInRange(ang, startAngle, sweep) && r0 <= blackRadius + 1e-6f) {
  1686.             return true;
  1687.         }
  1688.  
  1689.         // Otherwise compute minimal distance to arc OR to the two radial segments (center->endpoint)
  1690.         bool tmpInsideArcSector = false;
  1691.         float distToArc = DistPointToArc(ballCenter, pc, blackRadius, startAngle, sweep, tmpInsideArcSector);
  1692.  
  1693.         // radial endpoints
  1694.         D2D1_POINT_2F ep1 = { pc.x + blackRadius * cosf(startAngle), pc.y + blackRadius * sinf(startAngle) };
  1695.         D2D1_POINT_2F ep2 = { pc.x + blackRadius * cosf(startAngle + sweep), pc.y + blackRadius * sinf(startAngle + sweep) };
  1696.         float distToRadial1 = DistPointToSegment(ballCenter, pc, ep1);
  1697.         float distToRadial2 = DistPointToSegment(ballCenter, pc, ep2);
  1698.  
  1699.         float minDist = distToArc;
  1700.         if (distToRadial1 < minDist) minDist = distToRadial1;
  1701.         if (distToRadial2 < minDist) minDist = distToRadial2;
  1702.  
  1703.         return (minDist <= BALL_RADIUS + 1e-6f);
  1704.     }
  1705.  
  1706.     // fallback
  1707.     return false;
  1708. }
  1709. /*
  1710. // Backwards-compatible alias: some places in the code call IsBallInPocket(...)
  1711. // so provide a thin wrapper that uses the precise black-area test.
  1712. bool IsBallInPocket(const Ball& b, int pIndex)
  1713. {
  1714.     return IsBallInPocketBlackArea(b, pIndex);
  1715. }
  1716.  
  1717. // Return true if the ball circle intersects the pocket black area.
  1718. // Middle pockets (indexes 1 and 4) use a horizontal capsule; corners use a circle.
  1719. bool IsBallInPocket(const Ball* ball, int p)
  1720. {
  1721.     if (!ball) return false;
  1722.     D2D1_POINT_2F center = pocketPositions[p];
  1723.  
  1724.     // Get the visual radius appropriate for this pocket (corner vs middle)
  1725.     const float pocketVis = GetPocketVisualRadius(p);
  1726.     // black mouth visual radius (tweak these multipliers to get the feel you want)
  1727.     const float blackRadius = pocketVis * 0.9f;
  1728.     // When testing collision of a ball's **edge**, include BALL_RADIUS so the test is between centers:
  1729.     const float testRadius = blackRadius + BALL_RADIUS;
  1730.  
  1731.     // Middle pockets: treat as a horizontal capsule (line segment + circular end-caps)
  1732.     if (p == 1 || p == 4) {
  1733.         const float mouthHalfLength = pocketVis * 1.2f; // half-length of opening
  1734.         D2D1_POINT_2F a = { center.x - mouthHalfLength, center.y };
  1735.         D2D1_POINT_2F b = { center.x + mouthHalfLength, center.y };
  1736.  
  1737.         D2D1_POINT_2F ab = { b.x - a.x, b.y - a.y };
  1738.         D2D1_POINT_2F ap = { ball->x - a.x, ball->y - a.y };
  1739.         float abLen2 = ab.x * ab.x + ab.y * ab.y;
  1740.         if (abLen2 <= 1e-6f) { // degenerate fallback to circle
  1741.             float dx = ball->x - center.x;
  1742.             float dy = ball->y - center.y;
  1743.             return (dx * dx + dy * dy) <= (testRadius * testRadius);
  1744.         }
  1745.  
  1746.         float t = Dot(ap, ab) / abLen2;
  1747.         t = Clampf(t, 0.0f, 1.0f);
  1748.         D2D1_POINT_2F closest = { a.x + ab.x * t, a.y + ab.y * t };
  1749.         float dx = ball->x - closest.x;
  1750.         float dy = ball->y - closest.y;
  1751.         float dist2 = dx * dx + dy * dy;
  1752.  
  1753.         // Ensure ball is coming from the table side (not from outside)
  1754.         const float verticalTolerance = BALL_RADIUS * 0.35f;
  1755.         bool tableSideOk = true;
  1756.         if (p == 1) { // top middle; table interior is below center
  1757.             if (ball->y + verticalTolerance < center.y) tableSideOk = false;
  1758.         }
  1759.         else { // p == 4 bottom middle; table interior is above center
  1760.             if (ball->y - verticalTolerance > center.y) tableSideOk = false;
  1761.         }
  1762.  
  1763.         return tableSideOk && (dist2 <= (testRadius * testRadius));
  1764.     }
  1765.     else {
  1766.         // Corner pocket: simple circle test around pocket center (black mouth)
  1767.         float dx = ball->x - center.x;
  1768.         float dy = ball->y - center.y;
  1769.         float dist2 = dx * dx + dy * dy;
  1770.         return (dist2 <= (testRadius * testRadius));
  1771.     }
  1772. }
  1773. */
  1774. // --- NEW Forward Declarations ---
  1775.  
  1776. // AI Related
  1777. struct AIShotInfo; // Define below
  1778. void TriggerAIMove();
  1779. void AIMakeDecision();
  1780. void AIPlaceCueBall();
  1781. AIShotInfo AIFindBestShot();
  1782. AIShotInfo EvaluateShot(Ball* targetBall, int pocketIndex);
  1783. bool IsPathClear(D2D1_POINT_2F start, D2D1_POINT_2F end, int ignoredBallId1, int ignoredBallId2);
  1784. Ball* FindFirstHitBall(D2D1_POINT_2F start, float angle, float& hitDistSq); // Added hitDistSq output
  1785. float CalculateShotPower(float cueToGhostDist, float targetToPocketDist);
  1786. D2D1_POINT_2F CalculateGhostBallPos(Ball* targetBall, int pocketIndex);
  1787. bool IsValidAIAimAngle(float angle); // Basic check
  1788.  
  1789. // Dialog Related
  1790. INT_PTR CALLBACK NewGameDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam);
  1791. void ShowNewGameDialog(HINSTANCE hInstance);
  1792. void LoadSettings(); // For deserialization
  1793. void SaveSettings(); // For serialization
  1794. const std::wstring SETTINGS_FILE_NAME = L"Pool-Settings.txt";
  1795. void ResetGame(HINSTANCE hInstance); // Function to handle F2 reset
  1796.  
  1797. // --- Forward Declaration for Window Procedure --- <<< Add this line HERE
  1798. LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
  1799.  
  1800. // --- NEW Struct for AI Shot Evaluation ---
  1801. struct AIShotInfo {
  1802.     bool possible = false;          // Is this shot considered viable?
  1803.     Ball* targetBall = nullptr;     // Which ball to hit
  1804.     int pocketIndex = -1;           // Which pocket to aim for (0-5)
  1805.     D2D1_POINT_2F ghostBallPos = { 0,0 }; // Where cue ball needs to hit target ball
  1806.     D2D1_POINT_2F predictedCueEndPos = { 0,0 }; // For positional play
  1807.     float angle = 0.0f;             // Calculated shot angle
  1808.     float power = 0.0f;             // Calculated shot power
  1809.     float score = -9999.0f; // Use a very low initial score
  1810.     //float score = -1.0f;            // Score for this shot (higher is better)
  1811.     //bool involves8Ball = false;     // Is the target the 8-ball?
  1812.     float spinX = 0.0f;
  1813.     float spinY = 0.0f;
  1814.     bool isBankShot = false;
  1815.     bool involves8Ball = false;
  1816. };
  1817.  
  1818. /*
  1819. table = TABLE_COLOR new: #29662d (0.1608, 0.4000, 0.1765) => old: (0.0f, 0.5f, 0.1f)
  1820. rail CUSHION_COLOR = #5c0702 (0.3608, 0.0275, 0.0078) => ::Red
  1821. gap = #e99d33 (0.9157, 0.6157, 0.2000) => ::Orange
  1822. winbg = #5e8863 (0.3686, 0.5333, 0.3882) => 1.0f, 1.0f, 0.803f
  1823. headstring = #47742f (0.2784, 0.4549, 0.1843) => ::White
  1824. bluearrow = #08b0a5 (0.0314, 0.6902, 0.6471) *#22babf (0.1333,0.7294,0.7490) => ::Blue
  1825. */
  1826.  
  1827. // --- NEW Settings Serialization Functions ---
  1828. void SaveSettings() {
  1829.     std::ofstream outFile(SETTINGS_FILE_NAME);
  1830.     if (outFile.is_open()) {
  1831.         outFile << static_cast<int>(gameMode) << std::endl;
  1832.         outFile << static_cast<int>(aiDifficulty) << std::endl;
  1833.         outFile << static_cast<int>(openingBreakMode) << std::endl;
  1834.         outFile << static_cast<int>(selectedTableColor) << std::endl;
  1835.         outFile.close();
  1836.     }
  1837.     // else: Handle error, e.g., log or silently fail
  1838. }
  1839.  
  1840. void LoadSettings() {
  1841.     std::ifstream inFile(SETTINGS_FILE_NAME);
  1842.     if (inFile.is_open()) {
  1843.         int gm, aid, obm;
  1844.         if (inFile >> gm) {
  1845.             gameMode = static_cast<GameMode>(gm);
  1846.         }
  1847.         if (inFile >> aid) {
  1848.             aiDifficulty = static_cast<AIDifficulty>(aid);
  1849.         }
  1850.         if (inFile >> obm) {
  1851.             openingBreakMode = static_cast<OpeningBreakMode>(obm);
  1852.         }
  1853.         int tc;
  1854.         if (inFile >> tc) {
  1855.             selectedTableColor = static_cast<TableColor>(tc);
  1856.         }
  1857.         inFile.close();
  1858.  
  1859.         // Validate loaded settings (optional, but good practice)
  1860.         if (gameMode < HUMAN_VS_HUMAN || gameMode > HUMAN_VS_AI) gameMode = HUMAN_VS_HUMAN; // Default
  1861.         if (aiDifficulty < EASY || aiDifficulty > HARD) aiDifficulty = MEDIUM; // Default
  1862.         if (openingBreakMode < CPU_BREAK || openingBreakMode > FLIP_COIN_BREAK) openingBreakMode = CPU_BREAK; // Default
  1863.     }
  1864.     // else: File doesn't exist or couldn't be opened, use defaults (already set in global vars)
  1865. }
  1866. // --- End Settings Serialization Functions ---
  1867.  
  1868. // --- NEW Dialog Procedure ---
  1869. INT_PTR CALLBACK NewGameDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {
  1870.     switch (message) {
  1871.     case WM_INITDIALOG:
  1872.     {
  1873.         // --- ACTION 4: Center Dialog Box ---
  1874. // Optional: Force centering if default isn't working
  1875.         RECT rcDlg, rcOwner, rcScreen;
  1876.         HWND hwndOwner = GetParent(hDlg); // GetParent(hDlg) might be better if hwndMain is passed
  1877.         if (hwndOwner == NULL) hwndOwner = GetDesktopWindow();
  1878.  
  1879.         GetWindowRect(hwndOwner, &rcOwner);
  1880.         GetWindowRect(hDlg, &rcDlg);
  1881.         CopyRect(&rcScreen, &rcOwner); // Use owner rect as reference bounds
  1882.  
  1883.         // Offset the owner rect relative to the screen if it's not the desktop
  1884.         if (GetParent(hDlg) != NULL) { // If parented to main window (passed to DialogBoxParam)
  1885.             OffsetRect(&rcOwner, -rcScreen.left, -rcScreen.top);
  1886.             OffsetRect(&rcDlg, -rcScreen.left, -rcScreen.top);
  1887.             OffsetRect(&rcScreen, -rcScreen.left, -rcScreen.top);
  1888.         }
  1889.  
  1890.  
  1891.         // Calculate centered position
  1892.         int x = rcOwner.left + (rcOwner.right - rcOwner.left - (rcDlg.right - rcDlg.left)) / 2;
  1893.         int y = rcOwner.top + (rcOwner.bottom - rcOwner.top - (rcDlg.bottom - rcDlg.top)) / 2;
  1894.  
  1895.         // Ensure it stays within screen bounds (optional safety)
  1896.         x = std::max(static_cast<int>(rcScreen.left), x);
  1897.         y = std::max(static_cast<int>(rcScreen.top), y);
  1898.         if (x + (rcDlg.right - rcDlg.left) > rcScreen.right)
  1899.             x = rcScreen.right - (rcDlg.right - rcDlg.left);
  1900.         if (y + (rcDlg.bottom - rcDlg.top) > rcScreen.bottom)
  1901.             y = rcScreen.bottom - (rcDlg.bottom - rcDlg.top);
  1902.  
  1903.  
  1904.         // Set the dialog position
  1905.         SetWindowPos(hDlg, HWND_TOP, x, y, 0, 0, SWP_NOSIZE);
  1906.  
  1907.         // --- End Centering Code ---
  1908.  
  1909.         // Set initial state based on current global settings (or defaults)
  1910.         CheckRadioButton(hDlg, IDC_RADIO_2P, IDC_RADIO_CPU, (gameMode == HUMAN_VS_HUMAN) ? IDC_RADIO_2P : IDC_RADIO_CPU);
  1911.  
  1912.         CheckRadioButton(hDlg, IDC_RADIO_EASY, IDC_RADIO_HARD,
  1913.             (aiDifficulty == EASY) ? IDC_RADIO_EASY : ((aiDifficulty == MEDIUM) ? IDC_RADIO_MEDIUM : IDC_RADIO_HARD));
  1914.  
  1915.         // Enable/Disable AI group based on initial mode
  1916.         EnableWindow(GetDlgItem(hDlg, IDC_GROUP_AI), gameMode == HUMAN_VS_AI);
  1917.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_EASY), gameMode == HUMAN_VS_AI);
  1918.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_MEDIUM), gameMode == HUMAN_VS_AI);
  1919.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_HARD), gameMode == HUMAN_VS_AI);
  1920.         // Set initial state for Opening Break Mode
  1921.         CheckRadioButton(hDlg, IDC_RADIO_CPU_BREAK, IDC_RADIO_FLIP_BREAK,
  1922.             (openingBreakMode == CPU_BREAK) ? IDC_RADIO_CPU_BREAK : ((openingBreakMode == P1_BREAK) ? IDC_RADIO_P1_BREAK : IDC_RADIO_FLIP_BREAK));
  1923.         // Enable/Disable Opening Break group based on initial mode
  1924.         EnableWindow(GetDlgItem(hDlg, IDC_GROUP_BREAK_MODE), gameMode == HUMAN_VS_AI);
  1925.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_CPU_BREAK), gameMode == HUMAN_VS_AI);
  1926.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_P1_BREAK), gameMode == HUMAN_VS_AI);
  1927.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_FLIP_BREAK), gameMode == HUMAN_VS_AI);
  1928.         // --- NEW: Populate the Table Color ComboBox ---
  1929.         HWND hCombo = GetDlgItem(hDlg, IDC_COMBO_TABLECOLOR);
  1930.         for (int i = 0; i < 5; ++i) {
  1931.             SendMessage(hCombo, CB_ADDSTRING, 0, (LPARAM)tableColorNames[i]);
  1932.         }
  1933.         // Set the initial selection based on the loaded/default setting
  1934.         SendMessage(hCombo, CB_SETCURSEL, (WPARAM)selectedTableColor, 0);
  1935.     }
  1936.     return (INT_PTR)TRUE;
  1937.  
  1938.     case WM_COMMAND:
  1939.     { // Add an opening brace to create a new scope for the entire case.
  1940.         HWND hCombo;
  1941.         int selectedIndex;
  1942.         switch (LOWORD(wParam)) {
  1943.         case IDC_RADIO_2P:
  1944.         case IDC_RADIO_CPU:
  1945.         {
  1946.             bool isCPU = IsDlgButtonChecked(hDlg, IDC_RADIO_CPU) == BST_CHECKED;
  1947.             // Enable/Disable AI group controls based on selection
  1948.             EnableWindow(GetDlgItem(hDlg, IDC_GROUP_AI), isCPU);
  1949.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_EASY), isCPU);
  1950.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_MEDIUM), isCPU);
  1951.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_HARD), isCPU);
  1952.             // Also enable/disable Opening Break Mode group
  1953.             EnableWindow(GetDlgItem(hDlg, IDC_GROUP_BREAK_MODE), isCPU);
  1954.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_CPU_BREAK), isCPU);
  1955.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_P1_BREAK), isCPU);
  1956.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_FLIP_BREAK), isCPU);
  1957.         }
  1958.         return (INT_PTR)TRUE;
  1959.  
  1960.         case IDOK:
  1961.             // Retrieve selected options and store in global variables
  1962.             if (IsDlgButtonChecked(hDlg, IDC_RADIO_CPU) == BST_CHECKED) {
  1963.                 gameMode = HUMAN_VS_AI;
  1964.                 if (IsDlgButtonChecked(hDlg, IDC_RADIO_EASY) == BST_CHECKED) aiDifficulty = EASY;
  1965.                 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_MEDIUM) == BST_CHECKED) aiDifficulty = MEDIUM;
  1966.                 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_HARD) == BST_CHECKED) aiDifficulty = HARD;
  1967.  
  1968.                 if (IsDlgButtonChecked(hDlg, IDC_RADIO_CPU_BREAK) == BST_CHECKED) openingBreakMode = CPU_BREAK;
  1969.                 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_P1_BREAK) == BST_CHECKED) openingBreakMode = P1_BREAK;
  1970.                 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_FLIP_BREAK) == BST_CHECKED) openingBreakMode = FLIP_COIN_BREAK;
  1971.             }
  1972.             else {
  1973.                 gameMode = HUMAN_VS_HUMAN;
  1974.                 // openingBreakMode doesn't apply to HvsH, can leave as is or reset
  1975.             }
  1976.  
  1977.             // --- NEW: Retrieve selected table color ---
  1978.             hCombo = GetDlgItem(hDlg, IDC_COMBO_TABLECOLOR);
  1979.             selectedIndex = (int)SendMessage(hCombo, CB_GETCURSEL, 0, 0);
  1980.             if (selectedIndex != CB_ERR) {
  1981.                 selectedTableColor = static_cast<TableColor>(selectedIndex);
  1982.             }
  1983.  
  1984.             SaveSettings(); // Save settings when OK is pressed
  1985.             EndDialog(hDlg, IDOK); // Close dialog, return IDOK
  1986.             return (INT_PTR)TRUE;
  1987.  
  1988.         case IDCANCEL: // Handle Cancel or closing the dialog
  1989.             // Optionally, could reload settings here if you want cancel to revert to previously saved state
  1990.             EndDialog(hDlg, IDCANCEL);
  1991.             return (INT_PTR)TRUE;
  1992.         }
  1993.     } // Add a closing brace for the new scope.
  1994.     break; // End WM_COMMAND
  1995.     }
  1996.     return (INT_PTR)FALSE; // Default processing
  1997. }
  1998.  
  1999. // --- NEW Helper to Show Dialog ---
  2000. void ShowNewGameDialog(HINSTANCE hInstance) {
  2001.     if (DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_NEWGAMEDLG), hwndMain, NewGameDialogProc, 0) == IDOK) {
  2002.         // User clicked Start, reset game with new settings
  2003.         isPlayer2AI = (gameMode == HUMAN_VS_AI); // Update AI flag
  2004.         if (isPlayer2AI) {
  2005.             switch (aiDifficulty) {
  2006.             case EASY: player2Info.name = L"Virtus Pro (Easy)"/*"CPU (Easy)"*/; break;
  2007.             case MEDIUM: player2Info.name = L"Virtus Pro (Medium)"/*"CPU (Medium)"*/; break;
  2008.             case HARD: player2Info.name = L"Virtus Pro (Hard)"/*"CPU (Hard)"*/; break;
  2009.             }
  2010.         }
  2011.         else {
  2012.             player2Info.name = L"Billy Ray Cyrus"/*"Player 2"*/;
  2013.         }
  2014.         // Update window title
  2015.         std::wstring windowTitle = L"Midnight Pool 4"/*"Direct2D 8-Ball Pool"*/;
  2016.         if (gameMode == HUMAN_VS_HUMAN) windowTitle += L" (Human vs Human)";
  2017.         else windowTitle += L" (Human vs " + player2Info.name + L")";
  2018.         SetWindowText(hwndMain, windowTitle.c_str());
  2019.  
  2020.         // --- NEW: Apply the selected table color ---
  2021.         TABLE_COLOR = tableColorValues[selectedTableColor];
  2022.  
  2023.         InitGame(); // Re-initialize game logic & board
  2024.         InvalidateRect(hwndMain, NULL, TRUE); // Force redraw
  2025.     }
  2026.     else {
  2027.         // User cancelled dialog - maybe just resume game? Or exit?
  2028.         // For simplicity, we do nothing, game continues as it was.
  2029.         // To exit on cancel from F2, would need more complex state management.
  2030.     }
  2031. }
  2032.  
  2033. // --- NEW Reset Game Function ---
  2034. void ResetGame(HINSTANCE hInstance) {
  2035.     // Call the helper function to show the dialog and re-init if OK clicked
  2036.     ShowNewGameDialog(hInstance);
  2037. }
  2038.  
  2039. // --- WinMain ---
  2040. int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR, int nCmdShow) {
  2041.     if (FAILED(CoInitialize(NULL))) {
  2042.         MessageBox(NULL, L"COM Initialization Failed.", L"Error", MB_OK | MB_ICONERROR);
  2043.         return -1;
  2044.     }
  2045.  
  2046.     // --- NEW: Load settings at startup ---
  2047.     LoadSettings();
  2048.  
  2049.     // --- NEW: Show configuration dialog FIRST ---
  2050.     if (DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_NEWGAMEDLG), NULL, NewGameDialogProc, 0) != IDOK) {
  2051.         // User cancelled the dialog
  2052.         CoUninitialize();
  2053.         return 0; // Exit gracefully if dialog cancelled
  2054.     }
  2055.     // Global gameMode and aiDifficulty are now set by the DialogProc
  2056.  
  2057.     // --- Apply the selected table color to the global before anything else draws ---
  2058.     TABLE_COLOR = tableColorValues[selectedTableColor];
  2059.  
  2060.     // Set AI flag based on game mode
  2061.     isPlayer2AI = (gameMode == HUMAN_VS_AI);
  2062.     if (isPlayer2AI) {
  2063.         switch (aiDifficulty) {
  2064.         case EASY: player2Info.name = L"Virtus Pro (Easy)"/*"CPU (Easy)"*/; break;
  2065.         case MEDIUM:player2Info.name = L"Virtus Pro (Medium)"/*"CPU (Medium)"*/; break;
  2066.         case HARD: player2Info.name = L"Virtus Pro (Hard)"/*"CPU (Hard)"*/; break;
  2067.         }
  2068.     }
  2069.     else {
  2070.         player2Info.name = L"Billy Ray Cyrus"/*"Player 2"*/;
  2071.     }
  2072.     // --- End of Dialog Logic ---
  2073.  
  2074.  
  2075.     WNDCLASS wc = { };
  2076.     wc.lpfnWndProc = WndProc;
  2077.     wc.hInstance = hInstance;
  2078.     wc.lpszClassName = L"BLISS_GameEngine"/*"Direct2D_8BallPool"*/;
  2079.     wc.hCursor = LoadCursor(NULL, IDC_ARROW);
  2080.     wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
  2081.     wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1)); // Use your actual icon ID here
  2082.  
  2083.     if (!RegisterClass(&wc)) {
  2084.         MessageBox(NULL, L"Window Registration Failed.", L"Error", MB_OK | MB_ICONERROR);
  2085.         CoUninitialize();
  2086.         return -1;
  2087.     }
  2088.  
  2089.     // --- ACTION 4: Calculate Centered Window Position ---
  2090.     const int WINDOW_WIDTH = 1024; // Increased window size (1024=>1100)
  2091.     const int WINDOW_HEIGHT = 700; // Adjusted for new table aspect ratio (700)
  2092.     int screenWidth = GetSystemMetrics(SM_CXSCREEN);
  2093.     int screenHeight = GetSystemMetrics(SM_CYSCREEN);
  2094.     int windowX = (screenWidth - WINDOW_WIDTH) / 2;
  2095.     int windowY = (screenHeight - WINDOW_HEIGHT) / 2;
  2096.  
  2097.     // --- Change Window Title based on mode ---
  2098.     std::wstring windowTitle = L"Midnight Pool 4"/*"Direct2D 8-Ball Pool"*/;
  2099.     if (gameMode == HUMAN_VS_HUMAN) windowTitle += L" (Human vs Human)";
  2100.     else windowTitle += L" (Human vs " + player2Info.name + L")";
  2101.  
  2102.     DWORD dwStyle = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX; // No WS_THICKFRAME, No WS_MAXIMIZEBOX
  2103.  
  2104.     hwndMain = CreateWindowEx(
  2105.         0, L"BLISS_GameEngine"/*"Direct2D_8BallPool"*/, windowTitle.c_str(), dwStyle,
  2106.         windowX, windowY, WINDOW_WIDTH, WINDOW_HEIGHT,
  2107.         NULL, NULL, hInstance, NULL
  2108.     );
  2109.  
  2110.     if (!hwndMain) {
  2111.         MessageBox(NULL, L"Window Creation Failed.", L"Error", MB_OK | MB_ICONERROR);
  2112.         CoUninitialize();
  2113.         return -1;
  2114.     }
  2115.  
  2116.     // Initialize Direct2D Resources AFTER window creation
  2117.     if (FAILED(CreateDeviceResources())) {
  2118.         MessageBox(NULL, L"Failed to create Direct2D resources.", L"Error", MB_OK | MB_ICONERROR);
  2119.         DestroyWindow(hwndMain);
  2120.         CoUninitialize();
  2121.         return -1;
  2122.     }
  2123.  
  2124.     InitGame(); // Initialize game state AFTER resources are ready & mode is set
  2125.     Sleep(500); // Allow window to fully initialize before starting the countdown //midi func
  2126.     StartMidi(hwndMain, TEXT("BSQ.MID")); // Replace with your MIDI filename
  2127.     //PlayGameMusic(hwndMain); //midi func
  2128.  
  2129.     ShowWindow(hwndMain, nCmdShow);
  2130.     UpdateWindow(hwndMain);
  2131.  
  2132.     if (!SetTimer(hwndMain, ID_TIMER, 1000 / TARGET_FPS, NULL)) {
  2133.         MessageBox(NULL, L"Could not SetTimer().", L"Error", MB_OK | MB_ICONERROR);
  2134.         DestroyWindow(hwndMain);
  2135.         CoUninitialize();
  2136.         return -1;
  2137.     }
  2138.  
  2139.     MSG msg = { };
  2140.     // --- Modified Main Loop ---
  2141.     // Handles the case where the game starts in SHOWING_DIALOG state (handled now before loop)
  2142.     // or gets reset to it via F2. The main loop runs normally once game starts.
  2143.     while (GetMessage(&msg, NULL, 0, 0)) {
  2144.         // We might need modeless dialog handling here if F2 shows dialog
  2145.         // while window is active, but DialogBoxParam is modal.
  2146.         // Let's assume F2 hides main window, shows dialog, then restarts game loop.
  2147.         // Simpler: F2 calls ResetGame which calls DialogBoxParam (modal) then InitGame.
  2148.         TranslateMessage(&msg);
  2149.         DispatchMessage(&msg);
  2150.     }
  2151.  
  2152.  
  2153.     KillTimer(hwndMain, ID_TIMER);
  2154.     DiscardDeviceResources();
  2155.     SaveSettings(); // Save settings on exit
  2156.     CoUninitialize();
  2157.  
  2158.     return (int)msg.wParam;
  2159. }
  2160.  
  2161. // --- WndProc ---
  2162. LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
  2163.     Ball* cueBall = nullptr;
  2164.     switch (msg) {
  2165.     case WM_CREATE:
  2166.         return 0;
  2167.     case WM_PAINT:
  2168.         OnPaint();
  2169.         ValidateRect(hwnd, NULL);
  2170.         return 0;
  2171.     case WM_SIZE: {
  2172.         UINT width = LOWORD(lParam);
  2173.         UINT height = HIWORD(lParam);
  2174.         OnResize(width, height);
  2175.         return 0;
  2176.     }
  2177.     case WM_TIMER:
  2178.         if (wParam == ID_TIMER) {
  2179.             GameUpdate();
  2180.             InvalidateRect(hwnd, NULL, FALSE);
  2181.         }
  2182.         return 0;
  2183.     case WM_KEYDOWN:
  2184.     {
  2185.         cueBall = GetCueBall();
  2186.         bool canPlayerControl = ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == AIMING || currentGameState == BREAKING || currentGameState == BALL_IN_HAND_P1 || currentGameState == PRE_BREAK_PLACEMENT)) ||
  2187.             (currentPlayer == 2 && !isPlayer2AI && (currentGameState == PLAYER2_TURN || currentGameState == AIMING || currentGameState == BREAKING || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT)));
  2188.         if (wParam == VK_F2) {
  2189.             HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE);
  2190.             ResetGame(hInstance);
  2191.             return 0;
  2192.         }
  2193.         else if (wParam == VK_F1) {
  2194.             MessageBox(hwnd,
  2195.                 L"Direct2D-based StickPool game made in C++ from scratch (4827+ lines of code)\n"
  2196.                 L"First successful Clone in C++ (no other sites or projects were there to glean from.) Made /w AI assist\n"
  2197.                 L"(others were in JS/ non-8-Ball in C# etc.) w/o OOP and Graphics Frameworks all in a Single file.\n"
  2198.                 L"Copyright (C) 2025 Evans Thorpemorton, Entisoft Solutions. Midnight Pool 4. 'BLISS' Game Engine.\n"
  2199.                 L"Includes AI Difficulty Modes, Aim-Trajectory For Table Rails + Hard Angles TipShots. || F2=New Game",
  2200.                 L"About This Game", MB_OK | MB_ICONINFORMATION);
  2201.             return 0;
  2202.         }
  2203.         if (wParam == 'M' || wParam == 'm') {
  2204.             if (isMusicPlaying) {
  2205.                 StopMidi();
  2206.                 isMusicPlaying = false;
  2207.             }
  2208.             else {
  2209.                 TCHAR midiPath[MAX_PATH];
  2210.                 GetModuleFileName(NULL, midiPath, MAX_PATH);
  2211.                 TCHAR* lastBackslash = _tcsrchr(midiPath, '\\');
  2212.                 if (lastBackslash != NULL) {
  2213.                     *(lastBackslash + 1) = '\0';
  2214.                 }
  2215.                 _tcscat_s(midiPath, MAX_PATH, TEXT("BSQ.MID"));
  2216.                 StartMidi(hwndMain, midiPath);
  2217.                 isMusicPlaying = true;
  2218.             }
  2219.         }
  2220.         if (canPlayerControl) {
  2221.             bool shiftPressed = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
  2222.             float angleStep = shiftPressed ? 0.05f : 0.01f;
  2223.             float powerStep = 0.2f;
  2224.             switch (wParam) {
  2225.             case VK_LEFT:
  2226.                 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  2227.                     cueAngle -= angleStep;
  2228.                     if (cueAngle < 0) cueAngle += 2 * PI;
  2229.                     if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
  2230.                     isAiming = false;
  2231.                     isDraggingStick = false;
  2232.                     keyboardAimingActive = true;
  2233.                 }
  2234.                 break;
  2235.             case VK_RIGHT:
  2236.                 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  2237.                     cueAngle += angleStep;
  2238.                     if (cueAngle >= 2 * PI) cueAngle -= 2 * PI;
  2239.                     if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
  2240.                     isAiming = false;
  2241.                     isDraggingStick = false;
  2242.                     keyboardAimingActive = true;
  2243.                 }
  2244.                 break;
  2245.             case VK_UP:
  2246.                 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  2247.                     shotPower -= powerStep;
  2248.                     if (shotPower < 0.0f) shotPower = 0.0f;
  2249.                     if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
  2250.                     isAiming = true;
  2251.                     isDraggingStick = false;
  2252.                     keyboardAimingActive = true;
  2253.                 }
  2254.                 break;
  2255.             case VK_DOWN:
  2256.                 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  2257.                     shotPower += powerStep;
  2258.                     if (shotPower > MAX_SHOT_POWER) shotPower = MAX_SHOT_POWER;
  2259.                     if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
  2260.                     isAiming = true;
  2261.                     isDraggingStick = false;
  2262.                     keyboardAimingActive = true;
  2263.                 }
  2264.                 break;
  2265.             case VK_SPACE:
  2266.                 if ((currentGameState == AIMING || currentGameState == BREAKING || currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN)
  2267.                     && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING)
  2268.                 {
  2269.                     if (shotPower > 0.15f) {
  2270.                         firstHitBallIdThisShot = -1;
  2271.                         cueHitObjectBallThisShot = false;
  2272.                         railHitAfterContact = false;
  2273.                         std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
  2274.                         ApplyShot(shotPower, cueAngle, cueSpinX, cueSpinY);
  2275.                         currentGameState = SHOT_IN_PROGRESS;
  2276.                         foulCommitted = false;
  2277.                         pocketedThisTurn.clear();
  2278.                         shotPower = 0;
  2279.                         isAiming = false; isDraggingStick = false;
  2280.                         keyboardAimingActive = false;
  2281.                     }
  2282.                 }
  2283.                 break;
  2284.             case VK_ESCAPE:
  2285.                 if ((currentGameState == AIMING || currentGameState == BREAKING) || shotPower > 0)
  2286.                 {
  2287.                     shotPower = 0.0f;
  2288.                     isAiming = false;
  2289.                     isDraggingStick = false;
  2290.                     keyboardAimingActive = false;
  2291.                     if (currentGameState != BREAKING) {
  2292.                         currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  2293.                     }
  2294.                 }
  2295.                 break;
  2296.                 // === DEBUG: Press 'T' to set up endgame 8-ball test position ===
  2297.             case 'T':
  2298.             case 't':
  2299.             {
  2300.                 // Assign ball types to players
  2301.                 player1Info.assignedType = BallType::SOLID;
  2302.                 player2Info.assignedType = BallType::STRIPE;
  2303.                 player1Info.ballsPocketedCount = 6;
  2304.                 player2Info.ballsPocketedCount = 6;
  2305.  
  2306.                 // Reset foul/GameOver flags
  2307.                 foulCommitted = false;
  2308.                 gameOverMessage = L"";
  2309.  
  2310.                 // Stop all ball motion and clear pocket states first
  2311.                 for (auto& b : balls) {
  2312.                     b.vx = 0.0f;
  2313.                     b.vy = 0.0f;
  2314.                     b.rotationAngle = 0.0f;
  2315.                     b.rotationAxis = 0.0f;
  2316.                     b.isPocketed = false; // will mark pocketed ones below
  2317.                 }
  2318.  
  2319.                 // Pocket solids 1..6 (mark as pocketed)
  2320.                 for (int id = 1; id <= 6; ++id) {
  2321.                     for (auto& b : balls) {
  2322.                         if (b.id == id) {
  2323.                             b.isPocketed = true;
  2324.                             // place pocketed balls off-screen or at pocket position if you prefer:
  2325.                             b.x = TABLE_RIGHT + 40.0f + (id * 6.0f);
  2326.                             b.y = TABLE_TOP - 40.0f;
  2327.                         }
  2328.                     }
  2329.                 }
  2330.  
  2331.                 // Pocket stripes 9..14 (mark as pocketed)
  2332.                 for (int id = 9; id <= 14; ++id) {
  2333.                     for (auto& b : balls) {
  2334.                         if (b.id == id) {
  2335.                             b.isPocketed = true;
  2336.                             b.x = TABLE_RIGHT + 40.0f + (id * 6.0f);
  2337.                             b.y = TABLE_BOTTOM + 40.0f;
  2338.                         }
  2339.                     }
  2340.                 }
  2341.  
  2342.                 // Keep on-table: solid id=7, stripe id=15, eight id=8, cue id=0
  2343.                 // place them near the table center (cluster) and cue behind the kitchen (headstring)
  2344.                 float centerX = TABLE_LEFT + (TABLE_WIDTH * 0.5f);
  2345.                 float centerY = RACK_POS_Y; // use rack Y as approximate table center row
  2346.                 float spacing = BALL_RADIUS * 2.6f; // small separation
  2347.  
  2348.                 for (auto& b : balls) {
  2349.                     if (b.id == 7) {           // one solid left
  2350.                         b.isPocketed = false;
  2351.                         b.vx = b.vy = 0.0f;
  2352.                         b.x = centerX - spacing;
  2353.                         b.y = centerY;
  2354.                     }
  2355.                     else if (b.id == 15) {     // one stripe right
  2356.                         b.isPocketed = false;
  2357.                         b.vx = b.vy = 0.0f;
  2358.                         b.x = centerX + spacing;
  2359.                         b.y = centerY;
  2360.                     }
  2361.                     else if (b.id == 8) {      // 8-ball center
  2362.                         b.isPocketed = false;
  2363.                         b.vx = b.vy = 0.0f;
  2364.                         b.x = centerX;
  2365.                         b.y = centerY;
  2366.                     }
  2367.                     else if (b.id == 0) {      // cue ball behind the kitchen (HEADSTRING_X)
  2368.                         b.isPocketed = false;
  2369.                         b.vx = b.vy = 0.0f;
  2370.                         // place cue behind the headstring, a bit left of it for a natural break shot position
  2371.                         b.x = HEADSTRING_X - (TABLE_WIDTH * 0.08f);
  2372.                         b.y = centerY;
  2373.                     }
  2374.                 }
  2375.  
  2376.                 // Ensure current player is Player 1 and set game state so the HUD/UI reflects turn
  2377.                 currentPlayer = 1;
  2378.                 currentGameState = PLAYER1_TURN;
  2379.  
  2380.                 // Force a UI refresh so you see the new state immediately
  2381.                 InvalidateRect(hwnd, NULL, FALSE);
  2382.                 return 0;
  2383.             }
  2384.             break;
  2385.             case 'G':
  2386.                 cheatModeEnabled = !cheatModeEnabled;
  2387.                 if (cheatModeEnabled)
  2388.                     MessageBeep(MB_ICONEXCLAMATION);
  2389.                 else
  2390.                     MessageBeep(MB_OK);
  2391.                 break;
  2392.             default:
  2393.                 break;
  2394.             }
  2395.             return 0;
  2396.         }
  2397.     }
  2398.     return 0;
  2399.     case WM_MOUSEMOVE: {
  2400.         ptMouse.x = LOWORD(lParam);
  2401.         ptMouse.y = HIWORD(lParam);
  2402.         if ((currentGameState == CHOOSING_POCKET_P1 && currentPlayer == 1) ||
  2403.             (currentGameState == CHOOSING_POCKET_P2 && currentPlayer == 2 && !isPlayer2AI)) {
  2404.             int oldHover = currentlyHoveredPocket;
  2405.             currentlyHoveredPocket = -1;
  2406.             for (int i = 0; i < 6; ++i) {
  2407.                 // FIXED: Use correct radius for hover detection
  2408.                 float hoverRadius = (i == 1 || i == 4) ? MIDDLE_HOLE_VISUAL_RADIUS : CORNER_HOLE_VISUAL_RADIUS;
  2409.                 if (GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, pocketPositions[i].x, pocketPositions[i].y) < hoverRadius * hoverRadius * 2.25f) {
  2410.                     currentlyHoveredPocket = i;
  2411.                     break;
  2412.                 }
  2413.             }
  2414.             if (oldHover != currentlyHoveredPocket) {
  2415.                 InvalidateRect(hwnd, NULL, FALSE);
  2416.             }
  2417.         }
  2418.         cueBall = GetCueBall();
  2419.         if (isDraggingCueBall && cheatModeEnabled && draggingBallId != -1) {
  2420.             Ball* ball = GetBallById(draggingBallId);
  2421.             if (ball) {
  2422.                 ball->x = (float)ptMouse.x;
  2423.                 ball->y = (float)ptMouse.y;
  2424.                 ball->vx = ball->vy = 0.0f;
  2425.             }
  2426.             return 0;
  2427.         }
  2428.         if (!cueBall) return 0;
  2429.         if (isDraggingCueBall &&
  2430.             ((currentPlayer == 1 && currentGameState == BALL_IN_HAND_P1) ||
  2431.                 (!isPlayer2AI && currentPlayer == 2 && currentGameState == BALL_IN_HAND_P2) ||
  2432.                 currentGameState == PRE_BREAK_PLACEMENT))
  2433.         {
  2434.             bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  2435.             cueBall->x = (float)ptMouse.x;
  2436.             cueBall->y = (float)ptMouse.y;
  2437.             cueBall->vx = cueBall->vy = 0;
  2438.         }
  2439.         else if ((isAiming || isDraggingStick) &&
  2440.             ((currentPlayer == 1 && (currentGameState == AIMING || currentGameState == BREAKING)) ||
  2441.                 (!isPlayer2AI && currentPlayer == 2 && (currentGameState == AIMING || currentGameState == BREAKING))))
  2442.         {
  2443.             float dx = (float)ptMouse.x - cueBall->x;
  2444.             float dy = (float)ptMouse.y - cueBall->y;
  2445.             if (dx != 0 || dy != 0) cueAngle = atan2f(dy, dx);
  2446.             if (!keyboardAimingActive) {
  2447.                 float pullDist = GetDistance((float)ptMouse.x, (float)ptMouse.y, aimStartPoint.x, aimStartPoint.y);
  2448.                 shotPower = std::min(pullDist / 10.0f, MAX_SHOT_POWER);
  2449.             }
  2450.         }
  2451.         else if (isSettingEnglish &&
  2452.             ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == AIMING || currentGameState == BREAKING)) ||
  2453.                 (!isPlayer2AI && currentPlayer == 2 && (currentGameState == PLAYER2_TURN || currentGameState == AIMING || currentGameState == BREAKING))))
  2454.         {
  2455.             float dx = (float)ptMouse.x - spinIndicatorCenter.x;
  2456.             float dy = (float)ptMouse.y - spinIndicatorCenter.y;
  2457.             float dist = GetDistance(dx, dy, 0, 0);
  2458.             if (dist > spinIndicatorRadius) { dx *= spinIndicatorRadius / dist; dy *= spinIndicatorRadius / dist; }
  2459.             cueSpinX = dx / spinIndicatorRadius;
  2460.             cueSpinY = dy / spinIndicatorRadius;
  2461.         }
  2462.         else {
  2463.         }
  2464.         return 0;
  2465.     }
  2466.     case WM_LBUTTONDOWN: {
  2467.         ptMouse.x = LOWORD(lParam);
  2468.         ptMouse.y = HIWORD(lParam);
  2469.         if ((currentGameState == CHOOSING_POCKET_P1 && currentPlayer == 1) ||
  2470.             (currentGameState == CHOOSING_POCKET_P2 && currentPlayer == 2 && !isPlayer2AI)) {
  2471.             int clickedPocketIndex = -1;
  2472.             for (int i = 0; i < 6; ++i) {
  2473.                 // FIXED: Use correct radius for click detection
  2474.                 float clickRadius = (i == 1 || i == 4) ? MIDDLE_HOLE_VISUAL_RADIUS : CORNER_HOLE_VISUAL_RADIUS;
  2475.                 if (GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, pocketPositions[i].x, pocketPositions[i].y) < clickRadius * clickRadius * 2.25f) {
  2476.                     clickedPocketIndex = i;
  2477.                     break;
  2478.                 }
  2479.             }
  2480.             if (clickedPocketIndex != -1) {
  2481.                 if (currentPlayer == 1) calledPocketP1 = clickedPocketIndex;
  2482.                 else calledPocketP2 = clickedPocketIndex;
  2483.                 InvalidateRect(hwnd, NULL, FALSE);
  2484.                 return 0;
  2485.             }
  2486.             Ball* cueBall = GetCueBall();
  2487.             int calledPocket = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  2488.             if (cueBall && calledPocket != -1 && GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y) < BALL_RADIUS * BALL_RADIUS * 25) {
  2489.                 currentGameState = AIMING;
  2490.                 pocketCallMessage = L"";
  2491.                 isAiming = true;
  2492.                 aimStartPoint = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y);
  2493.                 return 0;
  2494.             }
  2495.             return 0;
  2496.         }
  2497.         if (cheatModeEnabled) {
  2498.             for (Ball& ball : balls) {
  2499.                 float distSq = GetDistanceSq(ball.x, ball.y, (float)ptMouse.x, (float)ptMouse.y);
  2500.                 if (distSq <= BALL_RADIUS * BALL_RADIUS * 4) {
  2501.                     isDraggingCueBall = true;
  2502.                     draggingBallId = ball.id;
  2503.                     if (ball.id == 0) {
  2504.                         if (currentPlayer == 1)
  2505.                             currentGameState = BALL_IN_HAND_P1;
  2506.                         else if (currentPlayer == 2 && !isPlayer2AI)
  2507.                             currentGameState = BALL_IN_HAND_P2;
  2508.                     }
  2509.                     return 0;
  2510.                 }
  2511.             }
  2512.         }
  2513.         Ball* cueBall = GetCueBall();
  2514.         bool canPlayerClickInteract = ((currentPlayer == 1) || (currentPlayer == 2 && !isPlayer2AI));
  2515.         bool canInteractState = (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN ||
  2516.             currentGameState == AIMING || currentGameState == BREAKING ||
  2517.             currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 ||
  2518.             currentGameState == PRE_BREAK_PLACEMENT);
  2519.         if (canPlayerClickInteract && canInteractState) {
  2520.             float spinDistSq = GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, spinIndicatorCenter.x, spinIndicatorCenter.y);
  2521.             if (spinDistSq < spinIndicatorRadius * spinIndicatorRadius * 1.2f) {
  2522.                 isSettingEnglish = true;
  2523.                 float dx = (float)ptMouse.x - spinIndicatorCenter.x;
  2524.                 float dy = (float)ptMouse.y - spinIndicatorCenter.y;
  2525.                 float dist = GetDistance(dx, dy, 0, 0);
  2526.                 if (dist > spinIndicatorRadius) { dx *= spinIndicatorRadius / dist; dy *= spinIndicatorRadius / dist; }
  2527.                 cueSpinX = dx / spinIndicatorRadius;
  2528.                 cueSpinY = dy / spinIndicatorRadius;
  2529.                 isAiming = false; isDraggingStick = false; isDraggingCueBall = false;
  2530.                 return 0;
  2531.             }
  2532.         }
  2533.         if (!cueBall) return 0;
  2534.         bool isPlacingBall = (currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT);
  2535.         bool isPlayerAllowedToPlace = (isPlacingBall &&
  2536.             ((currentPlayer == 1 && currentGameState == BALL_IN_HAND_P1) ||
  2537.                 (currentPlayer == 2 && !isPlayer2AI && currentGameState == BALL_IN_HAND_P2) ||
  2538.                 (currentGameState == PRE_BREAK_PLACEMENT)));
  2539.         if (isPlayerAllowedToPlace) {
  2540.             float distSq = GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y);
  2541.             if (distSq < BALL_RADIUS * BALL_RADIUS * 9.0f) {
  2542.                 isDraggingCueBall = true;
  2543.                 isAiming = false; isDraggingStick = false;
  2544.             }
  2545.             else {
  2546.                 bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  2547.                 if (IsValidCueBallPosition((float)ptMouse.x, (float)ptMouse.y, behindHeadstring)) {
  2548.                     cueBall->x = (float)ptMouse.x; cueBall->y = (float)ptMouse.y;
  2549.                     cueBall->vx = 0; cueBall->vy = 0;
  2550.                     isDraggingCueBall = false;
  2551.                     if (currentGameState == PRE_BREAK_PLACEMENT) currentGameState = BREAKING;
  2552.                     else if (currentGameState == BALL_IN_HAND_P1) currentGameState = PLAYER1_TURN;
  2553.                     else if (currentGameState == BALL_IN_HAND_P2) currentGameState = PLAYER2_TURN;
  2554.                     cueAngle = 0.0f;
  2555.                 }
  2556.             }
  2557.             return 0;
  2558.         }
  2559.         bool canAim = ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == BREAKING)) ||
  2560.             (currentPlayer == 2 && !isPlayer2AI && (currentGameState == PLAYER2_TURN || currentGameState == BREAKING)));
  2561.         if (canAim) {
  2562.             const float stickDrawLength = 150.0f * 1.4f;
  2563.             float currentStickAngle = cueAngle + PI;
  2564.             D2D1_POINT_2F currentStickEnd = D2D1::Point2F(cueBall->x + cosf(currentStickAngle) * stickDrawLength, cueBall->y + sinf(currentStickAngle) * stickDrawLength);
  2565.             D2D1_POINT_2F currentStickTip = D2D1::Point2F(cueBall->x + cosf(currentStickAngle) * 5.0f, cueBall->y + sinf(currentStickAngle) * 5.0f);
  2566.             float distToStickSq = PointToLineSegmentDistanceSq(D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y), currentStickTip, currentStickEnd);
  2567.             float stickClickThresholdSq = 36.0f;
  2568.             float distToCueBallSq = GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y);
  2569.             float cueBallClickRadiusSq = BALL_RADIUS * BALL_RADIUS * 25;
  2570.             bool clickedStick = (distToStickSq < stickClickThresholdSq);
  2571.             bool clickedCueArea = (distToCueBallSq < cueBallClickRadiusSq);
  2572.             if (clickedStick || clickedCueArea) {
  2573.                 isDraggingStick = clickedStick && !clickedCueArea;
  2574.                 isAiming = clickedCueArea;
  2575.                 aimStartPoint = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y);
  2576.                 shotPower = 0;
  2577.                 float dx = (float)ptMouse.x - cueBall->x;
  2578.                 float dy = (float)ptMouse.y - cueBall->y;
  2579.                 if (dx != 0 || dy != 0) cueAngle = atan2f(dy, dx);
  2580.                 if (currentGameState != BREAKING) currentGameState = AIMING;
  2581.             }
  2582.         }
  2583.         return 0;
  2584.     }
  2585.     case WM_LBUTTONUP: {
  2586.         // --- Cheat-mode pocket processing: uses the exact same IsBallInPocketBlackArea() test
  2587.         if (cheatModeEnabled && draggingBallId != -1) {
  2588.             Ball* b = GetBallById(draggingBallId);
  2589.             if (b) {
  2590.                 bool playedPocketSound = false;
  2591.                 for (int p = 0; p < 6; ++p) {
  2592.                     // Use the same precise black-area test used by physics.
  2593.                     if (!IsBallTouchingPocketMask_D2D(*b, p)) continue;
  2594.  
  2595.                     // Mark pocketed and record which pocket (especially important for the 8-ball)
  2596.                     if (b->id == 8) {
  2597.                         lastEightBallPocketIndex = p;
  2598.                     }
  2599.                     b->isPocketed = true;
  2600.                     b->vx = b->vy = 0.0f;
  2601.                     pocketedThisTurn.push_back(b->id);
  2602.                     if (!playedPocketSound) {
  2603.                         std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("pocket.wav")).detach();
  2604.                         playedPocketSound = true;
  2605.                     }
  2606.  
  2607.                     // If table is still "open" (no assignments yet) and the pocketed ball is an object ball,
  2608.                     // assign types to the shooter immediately.
  2609.                     if (player1Info.assignedType == BallType::NONE
  2610.                         && player2Info.assignedType == BallType::NONE
  2611.                         && (b->type == BallType::SOLID || b->type == BallType::STRIPE))
  2612.                     {
  2613.                         AssignPlayerBallTypes(b->type);
  2614.                         // Give the shooter one ball counted immediately (they just pocketed it)
  2615.                         if (currentPlayer == 1) player1Info.ballsPocketedCount = 1;
  2616.                         else                    player2Info.ballsPocketedCount = 1;
  2617.                     }
  2618.  
  2619.                     // Update pocket counts (don't count cue or 8-ball here)
  2620.                     if (b->id != 0 && b->id != 8) {
  2621.                         if (b->type == player1Info.assignedType) player1Info.ballsPocketedCount++;
  2622.                         else if (b->type == player2Info.assignedType) player2Info.ballsPocketedCount++;
  2623.                     }
  2624.  
  2625.                     // If this was an object ball (not the 8-ball), check if shooter now has 7 balls.
  2626.                     if (b->id != 8) {
  2627.                         PlayerInfo& shooter = (currentPlayer == 1 ? player1Info : player2Info);
  2628.                         if (shooter.ballsPocketedCount >= 7) {
  2629.                             // Prepare for called-pocket selection for the 8-ball
  2630.                             if (currentPlayer == 1) calledPocketP1 = -1;
  2631.                             else                  calledPocketP2 = -1;
  2632.                             currentGameState = (currentPlayer == 1) ? CHOOSING_POCKET_P1 : CHOOSING_POCKET_P2;
  2633.                             // finalize this cheat pocket step and return from WM_LBUTTONUP
  2634.                             draggingBallId = -1;
  2635.                             isDraggingCueBall = false;
  2636.                             return 0;
  2637.                         }
  2638.                         else {
  2639.                             // Keep the shooter's turn (cheat pocket gives them another opportunity)
  2640.                             currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  2641.                             if (currentPlayer == 2 && isPlayer2AI) aiTurnPending = true;
  2642.                         }
  2643.                     }
  2644.                     else {
  2645.                         // 8-ball pocketed during cheat: enforce the "called pocket" rule.
  2646.                         int called = (currentPlayer == 1 ? calledPocketP1 : calledPocketP2);
  2647.                         int actual = lastEightBallPocketIndex;
  2648.                         currentGameState = GAME_OVER;
  2649.                         if (actual == called) {
  2650.                             gameOverMessage = (currentPlayer == 1 ? player1Info.name : player2Info.name)
  2651.                                 + L" Wins! (Called pocket: " + std::to_wstring(called)
  2652.                                 + L", Actual pocket: " + std::to_wstring(actual) + L")";
  2653.                         }
  2654.                         else {
  2655.                             gameOverMessage = (currentPlayer == 1 ? player2Info.name : player1Info.name)
  2656.                                 + L" Wins! (Called: " + std::to_wstring(called)
  2657.                                 + L", Actual: " + std::to_wstring(actual) + L")";
  2658.                         }
  2659.                         // end the message processing immediately
  2660.                         draggingBallId = -1;
  2661.                         isDraggingCueBall = false;
  2662.                         return 0;
  2663.                     }
  2664.  
  2665.                     // we pocketed this ball — don't test other pockets for it
  2666.                     break;
  2667.                 } // end pocket loop
  2668.             }
  2669.         }
  2670.         ptMouse.x = LOWORD(lParam);
  2671.         ptMouse.y = HIWORD(lParam);
  2672.         Ball* cueBall = GetCueBall();
  2673.         if ((isAiming || isDraggingStick) &&
  2674.             ((currentPlayer == 1 && (currentGameState == AIMING || currentGameState == BREAKING)) ||
  2675.                 (!isPlayer2AI && currentPlayer == 2 && (currentGameState == AIMING || currentGameState == BREAKING))))
  2676.         {
  2677.             bool wasAiming = isAiming;
  2678.             bool wasDraggingStick = isDraggingStick;
  2679.             isAiming = false; isDraggingStick = false;
  2680.             if (shotPower > 0.15f) {
  2681.                 if (currentGameState != AI_THINKING) {
  2682.                     firstHitBallIdThisShot = -1; cueHitObjectBallThisShot = false; railHitAfterContact = false;
  2683.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
  2684.                     ApplyShot(shotPower, cueAngle, cueSpinX, cueSpinY);
  2685.                     currentGameState = SHOT_IN_PROGRESS;
  2686.                     foulCommitted = false; pocketedThisTurn.clear();
  2687.                 }
  2688.             }
  2689.             else if (currentGameState != AI_THINKING) {
  2690.                 if (currentGameState == BREAKING) {}
  2691.                 else {
  2692.                     currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  2693.                     if (currentPlayer == 2 && isPlayer2AI) aiTurnPending = false;
  2694.                 }
  2695.             }
  2696.             shotPower = 0;
  2697.         }
  2698.         if (isDraggingCueBall) {
  2699.             isDraggingCueBall = false;
  2700.             bool isPlacingState = (currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT);
  2701.             bool isPlayerAllowed = (isPlacingState &&
  2702.                 ((currentPlayer == 1 && currentGameState == BALL_IN_HAND_P1) ||
  2703.                     (currentPlayer == 2 && !isPlayer2AI && currentGameState == BALL_IN_HAND_P2) ||
  2704.                     (currentGameState == PRE_BREAK_PLACEMENT)));
  2705.             if (isPlayerAllowed && cueBall) {
  2706.                 bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  2707.                 if (IsValidCueBallPosition(cueBall->x, cueBall->y, behindHeadstring)) {
  2708.                     if (currentGameState == PRE_BREAK_PLACEMENT) currentGameState = BREAKING;
  2709.                     else if (currentGameState == BALL_IN_HAND_P1) currentGameState = PLAYER1_TURN;
  2710.                     else if (currentGameState == BALL_IN_HAND_P2) currentGameState = PLAYER2_TURN;
  2711.                     cueAngle = 0.0f;
  2712.                     if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN)
  2713.                     {
  2714.                         CheckAndTransitionToPocketChoice(currentPlayer);
  2715.                     }
  2716.                 }
  2717.                 else {}
  2718.             }
  2719.         }
  2720.         if (isSettingEnglish) {
  2721.             isSettingEnglish = false;
  2722.         }
  2723.         return 0;
  2724.     }
  2725.     case WM_DESTROY:
  2726.         isMusicPlaying = false;
  2727.         if (midiDeviceID != 0) {
  2728.             mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
  2729.             midiDeviceID = 0;
  2730.             SaveSettings();
  2731.         }
  2732.         PostQuitMessage(0);
  2733.         return 0;
  2734.     default:
  2735.         return DefWindowProc(hwnd, msg, wParam, lParam);
  2736.     }
  2737.     return 0;
  2738. }
  2739.  
  2740. // --- Direct2D Resource Management ---
  2741.  
  2742. HRESULT CreateDeviceResources() {
  2743.     HRESULT hr = S_OK;
  2744.  
  2745.     // Create Direct2D Factory
  2746.     if (!pFactory) {
  2747.         hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &pFactory);
  2748.         if (FAILED(hr)) return hr;
  2749.     }
  2750.  
  2751.     // Create DirectWrite Factory
  2752.     if (!pDWriteFactory) {
  2753.         hr = DWriteCreateFactory(
  2754.             DWRITE_FACTORY_TYPE_SHARED,
  2755.             __uuidof(IDWriteFactory),
  2756.             reinterpret_cast<IUnknown**>(&pDWriteFactory)
  2757.         );
  2758.         if (FAILED(hr)) return hr;
  2759.     }
  2760.  
  2761.     // Create Text Formats
  2762.     if (!pTextFormat && pDWriteFactory) {
  2763.         hr = pDWriteFactory->CreateTextFormat(
  2764.             L"Segoe UI", NULL, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
  2765.             16.0f, L"en-us", &pTextFormat
  2766.         );
  2767.         if (FAILED(hr)) return hr;
  2768.         // Center align text
  2769.         pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  2770.         pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  2771.     }
  2772.     if (!pTextFormatBold && pDWriteFactory) {
  2773.         hr = pDWriteFactory->CreateTextFormat(
  2774.             L"Segoe UI", NULL, DWRITE_FONT_WEIGHT_BOLD, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
  2775.             16.0f, L"en-us", &pTextFormatBold
  2776.         );
  2777.         if (SUCCEEDED(hr)) {
  2778.             pTextFormatBold->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  2779.             pTextFormatBold->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  2780.         }
  2781.     }
  2782.     if (!pLargeTextFormat && pDWriteFactory) {
  2783.         hr = pDWriteFactory->CreateTextFormat(
  2784.             L"Impact", NULL, DWRITE_FONT_WEIGHT_BOLD, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
  2785.             48.0f, L"en-us", &pLargeTextFormat
  2786.         );
  2787.         if (FAILED(hr)) return hr;
  2788.         pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING); // Align left
  2789.         pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  2790.     }
  2791.  
  2792.     if (!pBallNumFormat && pDWriteFactory)
  2793.     {
  2794.         hr = pDWriteFactory->CreateTextFormat(
  2795.             L"Segoe UI", nullptr,
  2796.             DWRITE_FONT_WEIGHT_BOLD, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
  2797.             10.0f,                       // << small size for ball decals
  2798.             L"en-us",
  2799.             &pBallNumFormat);
  2800.         if (SUCCEEDED(hr))
  2801.         {
  2802.             pBallNumFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  2803.             pBallNumFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  2804.         }
  2805.     }
  2806.  
  2807.  
  2808.     // Create Render Target (needs valid hwnd)
  2809.     if (!pRenderTarget && hwndMain) {
  2810.         RECT rc;
  2811.         GetClientRect(hwndMain, &rc);
  2812.         D2D1_SIZE_U size = D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top);
  2813.  
  2814.         hr = pFactory->CreateHwndRenderTarget(
  2815.             D2D1::RenderTargetProperties(),
  2816.             D2D1::HwndRenderTargetProperties(hwndMain, size),
  2817.             &pRenderTarget
  2818.         );
  2819.         if (FAILED(hr)) {
  2820.             // If failed, release factories if they were created in this call
  2821.             SafeRelease(&pTextFormat);
  2822.             SafeRelease(&pLargeTextFormat);
  2823.             SafeRelease(&pDWriteFactory);
  2824.             SafeRelease(&pFactory);
  2825.             pRenderTarget = nullptr; // Ensure it's null on failure
  2826.             return hr;
  2827.         }
  2828.     }
  2829.  
  2830.     //CreatePocketMasks_D2D((int)TABLE_WIDTH, (int)TABLE_HEIGHT, TABLE_LEFT, TABLE_TOP, 1.0f);
  2831.         // --- FOOLPROOF FIX: Create a larger, padded canvas for the collision masks ---
  2832.     // This padding ensures that the enlarged pocket shapes are not clipped.
  2833.     const float maskPadding = MIDDLE_HOLE_VISUAL_RADIUS * 3.0f; // Generous padding
  2834.     CreatePocketMasks_D2D(
  2835.         (int)TABLE_WIDTH + 2 * (int)maskPadding,    // New, wider canvas
  2836.         (int)TABLE_HEIGHT + 2 * (int)maskPadding,   // New, taller canvas
  2837.         TABLE_LEFT - maskPadding,                   // Shift the origin to the top-left of the new canvas
  2838.         TABLE_TOP - maskPadding,
  2839.         1.0f
  2840.     );
  2841.  
  2842.     return hr;
  2843. }
  2844.  
  2845. void DiscardDeviceResources() {
  2846.     SafeRelease(&pRenderTarget);
  2847.     SafeRelease(&pTextFormat);
  2848.     SafeRelease(&pTextFormatBold);
  2849.     SafeRelease(&pLargeTextFormat);
  2850.     SafeRelease(&pBallNumFormat);            // NEW
  2851.     SafeRelease(&pDWriteFactory);
  2852.     ShutdownPocketMasks_D2D();
  2853.     // Keep pFactory until application exit? Or release here too? Let's release.
  2854.     SafeRelease(&pFactory);
  2855. }
  2856.  
  2857. void OnResize(UINT width, UINT height) {
  2858.     if (pRenderTarget) {
  2859.         D2D1_SIZE_U size = D2D1::SizeU(width, height);
  2860.         pRenderTarget->Resize(size); // Ignore HRESULT for simplicity here
  2861.     }
  2862. }
  2863.  
  2864. // --- Game Initialization ---
  2865. void InitGame() {
  2866.     srand((unsigned int)time(NULL)); // Seed random number generator
  2867.     isOpeningBreakShot = true; // This is the start of a new game, so the next shot is an opening break.
  2868.     aiPlannedShotDetails.isValid = false; // Reset AI planned shot
  2869.     aiIsDisplayingAim = false;
  2870.     aiAimDisplayFramesLeft = 0;
  2871.     // ... (rest of InitGame())
  2872.  
  2873.     // --- Ensure pocketed list is clear from the absolute start ---
  2874.     pocketedThisTurn.clear();
  2875.  
  2876.     balls.clear(); // Clear existing balls
  2877.  
  2878.     // Reset Player Info (Names should be set by Dialog/wWinMain/ResetGame)
  2879.     player1Info.assignedType = BallType::NONE;
  2880.     player1Info.ballsPocketedCount = 0;
  2881.     // Player 1 Name usually remains "Player 1"
  2882.     player2Info.assignedType = BallType::NONE;
  2883.     player2Info.ballsPocketedCount = 0;
  2884.     // Player 2 Name is set based on gameMode in ShowNewGameDialog
  2885.         // --- Reset any 8?Ball call state on new game ---
  2886.     lastEightBallPocketIndex = -1;
  2887.     calledPocketP1 = -1;
  2888.     calledPocketP2 = -1;
  2889.     pocketCallMessage = L"";
  2890.     aiPlannedShotDetails.isValid = false; // THIS IS THE CRITICAL FIX: Reset the AI's plan.
  2891.  
  2892.     // Create Cue Ball (ID 0)
  2893.     // Initial position will be set during PRE_BREAK_PLACEMENT state
  2894.     balls.push_back({ 0, BallType::CUE_BALL, TABLE_LEFT + TABLE_WIDTH * 0.15f, RACK_POS_Y, 0, 0, CUE_BALL_COLOR, false, 0.0f, 0.0f });
  2895.  
  2896.     // --- Create Object Balls (Temporary List) ---
  2897.     std::vector<Ball> objectBalls;
  2898.     // Solids (1-7, Yellow)
  2899.     for (int i = 1; i <= 7; ++i) {
  2900.         //objectBalls.push_back({ i, BallType::SOLID, 0, 0, 0, 0, SOLID_COLOR, false });
  2901.         objectBalls.push_back({ i, BallType::SOLID, 0,0,0,0,
  2902.                     GetBallColor(i), false });
  2903.     }
  2904.     // Stripes (9-15, Red)
  2905.     for (int i = 9; i <= 15; ++i) {
  2906.         //objectBalls.push_back({ i, BallType::STRIPE, 0, 0, 0, 0, STRIPE_COLOR, false });
  2907.         objectBalls.push_back({ i, BallType::STRIPE, 0,0,0,0,
  2908.                     GetBallColor(i), false });
  2909.     }
  2910.     // 8-Ball (ID 8) - Add it to the list to be placed
  2911.     //objectBalls.push_back({ 8, BallType::EIGHT_BALL, 0, 0, 0, 0, EIGHT_BALL_COLOR, false });
  2912.     objectBalls.push_back({ 8, BallType::EIGHT_BALL, 0,0,0,0,
  2913.           GetBallColor(8), false });
  2914.  
  2915.  
  2916.     // --- Racking Logic (Improved) ---
  2917.     float spacingX = BALL_RADIUS * 2.0f * 0.866f; // cos(30) for horizontal spacing
  2918.     float spacingY = BALL_RADIUS * 2.0f * 1.0f;   // Vertical spacing
  2919.  
  2920.     // Define rack positions (0-14 indices corresponding to triangle spots)
  2921.     D2D1_POINT_2F rackPositions[15];
  2922.     int rackIndex = 0;
  2923.     for (int row = 0; row < 5; ++row) {
  2924.         for (int col = 0; col <= row; ++col) {
  2925.             if (rackIndex >= 15) break;
  2926.             float x = RACK_POS_X + row * spacingX;
  2927.             float y = RACK_POS_Y + (col - row / 2.0f) * spacingY;
  2928.             rackPositions[rackIndex++] = D2D1::Point2F(x, y);
  2929.         }
  2930.     }
  2931.  
  2932.     // Separate 8-ball
  2933.     Ball eightBall;
  2934.     std::vector<Ball> otherBalls; // Solids and Stripes
  2935.     bool eightBallFound = false;
  2936.     for (const auto& ball : objectBalls) {
  2937.         if (ball.id == 8) {
  2938.             eightBall = ball;
  2939.             eightBallFound = true;
  2940.         }
  2941.         else {
  2942.             otherBalls.push_back(ball);
  2943.         }
  2944.     }
  2945.     // Ensure 8 ball was actually created (should always be true)
  2946.     if (!eightBallFound) {
  2947.         // Handle error - perhaps recreate it? For now, proceed.
  2948.         eightBall = { 8, BallType::EIGHT_BALL, 0, 0, 0, 0, EIGHT_BALL_COLOR, false };
  2949.     }
  2950.  
  2951.  
  2952.     // Shuffle the other 14 balls
  2953.     // Use std::shuffle if available (C++11 and later) for better randomness
  2954.     // std::random_device rd;
  2955.     // std::mt19937 g(rd());
  2956.     // std::shuffle(otherBalls.begin(), otherBalls.end(), g);
  2957.     std::random_shuffle(otherBalls.begin(), otherBalls.end()); // Using deprecated for now
  2958.  
  2959.     // --- Place balls into the main 'balls' vector in rack order ---
  2960.     // Important: Add the cue ball (already created) first.
  2961.     // (Cue ball added at the start of the function now)
  2962.  
  2963.     // 1. Place the 8-ball in its fixed position (index 4 for the 3rd row center)
  2964.     int eightBallRackIndex = 4;
  2965.     eightBall.x = rackPositions[eightBallRackIndex].x;
  2966.     eightBall.y = rackPositions[eightBallRackIndex].y;
  2967.     eightBall.vx = 0;
  2968.     eightBall.vy = 0;
  2969.     eightBall.isPocketed = false;
  2970.     balls.push_back(eightBall); // Add 8 ball to the main vector
  2971.  
  2972.     // 2. Place the shuffled Solids and Stripes in the remaining spots
  2973.     size_t otherBallIdx = 0;
  2974.     //int otherBallIdx = 0;
  2975.     for (int i = 0; i < 15; ++i) {
  2976.         if (i == eightBallRackIndex) continue; // Skip the 8-ball spot
  2977.  
  2978.         if (otherBallIdx < otherBalls.size()) {
  2979.             Ball& ballToPlace = otherBalls[otherBallIdx++];
  2980.             ballToPlace.x = rackPositions[i].x;
  2981.             ballToPlace.y = rackPositions[i].y;
  2982.             ballToPlace.vx = 0;
  2983.             ballToPlace.vy = 0;
  2984.             ballToPlace.isPocketed = false;
  2985.             balls.push_back(ballToPlace); // Add to the main game vector
  2986.         }
  2987.     }
  2988.     // --- End Racking Logic ---
  2989.  
  2990.  
  2991.     // --- Determine Who Breaks and Initial State ---
  2992.     if (isPlayer2AI) {
  2993.         /*// AI Mode: Randomly decide who breaks
  2994.         if ((rand() % 2) == 0) {
  2995.             // AI (Player 2) breaks
  2996.             currentPlayer = 2;
  2997.             currentGameState = PRE_BREAK_PLACEMENT; // AI needs to place ball first
  2998.             aiTurnPending = true; // Trigger AI logic
  2999.         }
  3000.         else {
  3001.             // Player 1 (Human) breaks
  3002.             currentPlayer = 1;
  3003.             currentGameState = PRE_BREAK_PLACEMENT; // Human places cue ball
  3004.             aiTurnPending = false;*/
  3005.         switch (openingBreakMode) {
  3006.         case CPU_BREAK:
  3007.             currentPlayer = 2; // AI breaks
  3008.             currentGameState = PRE_BREAK_PLACEMENT;
  3009.             aiTurnPending = true;
  3010.             break;
  3011.         case P1_BREAK:
  3012.             currentPlayer = 1; // Player 1 breaks
  3013.             currentGameState = PRE_BREAK_PLACEMENT;
  3014.             aiTurnPending = false;
  3015.             break;
  3016.         case FLIP_COIN_BREAK:
  3017.             if ((rand() % 2) == 0) { // 0 for AI, 1 for Player 1
  3018.                 currentPlayer = 2; // AI breaks
  3019.                 currentGameState = PRE_BREAK_PLACEMENT;
  3020.                 aiTurnPending = true;
  3021.             }
  3022.             else {
  3023.                 currentPlayer = 1; // Player 1 breaks
  3024.                 currentGameState = PRE_BREAK_PLACEMENT;
  3025.                 aiTurnPending = false;
  3026.             }
  3027.             break;
  3028.         default: // Fallback to CPU break
  3029.             currentPlayer = 2;
  3030.             currentGameState = PRE_BREAK_PLACEMENT;
  3031.             aiTurnPending = true;
  3032.             break;
  3033.         }
  3034.     }
  3035.     else {
  3036.         // Human vs Human, Player 1 always breaks (or could add a flip coin for HvsH too if desired)
  3037.         currentPlayer = 1;
  3038.         currentGameState = PRE_BREAK_PLACEMENT;
  3039.         aiTurnPending = false; // No AI involved
  3040.     }
  3041.  
  3042.     // Reset other relevant game state variables
  3043.     foulCommitted = false;
  3044.     gameOverMessage = L"";
  3045.     firstBallPocketedAfterBreak = false;
  3046.     // pocketedThisTurn cleared at start
  3047.     // Reset shot parameters and input flags
  3048.     shotPower = 0.0f;
  3049.     cueSpinX = 0.0f;
  3050.     cueSpinY = 0.0f;
  3051.     isAiming = false;
  3052.     isDraggingCueBall = false;
  3053.     isSettingEnglish = false;
  3054.     cueAngle = 0.0f; // Reset aim angle
  3055. }
  3056.  
  3057.  
  3058. // --------------------------------------------------------------------------------
  3059. // Full GameUpdate(): integrates AI call?pocket ? aim ? shoot (no omissions)
  3060. // --------------------------------------------------------------------------------
  3061. void GameUpdate() {
  3062.     // --- 1) Handle an in?flight shot ---
  3063.     if (currentGameState == SHOT_IN_PROGRESS) {
  3064.         UpdatePhysics();
  3065.         // ? clear old 8?ball pocket info before any new pocket checks
  3066.         //lastEightBallPocketIndex = -1;
  3067.         CheckCollisions();
  3068.         CheckPockets(); // FIX: This line was missing. It's essential to check for pocketed balls every frame.
  3069.  
  3070.         if (AreBallsMoving()) {
  3071.             isAiming = false;
  3072.             aiIsDisplayingAim = false;
  3073.         }
  3074.  
  3075.         if (!AreBallsMoving()) {
  3076.             ProcessShotResults();
  3077.         }
  3078.         return;
  3079.     }
  3080.  
  3081.     // --- 2) CPU’s turn (table is static) ---
  3082.     if (isPlayer2AI && currentPlayer == 2 && !AreBallsMoving()) {
  3083.         // ??? If we've just auto?entered AI_THINKING for the 8?ball call, actually make the decision ???
  3084.         if (currentGameState == AI_THINKING && aiTurnPending) {
  3085.             aiTurnPending = false;        // consume the pending flag
  3086.             AIMakeDecision();             // CPU calls its pocket or plans its shot
  3087.             return;                       // done this tick
  3088.         }
  3089.  
  3090.         // ??? Automate the AI pocket?selection click ???
  3091.         if (currentGameState == CHOOSING_POCKET_P2) {
  3092.             // AI immediately confirms its call and moves to thinking/shooting
  3093.             currentGameState = AI_THINKING;
  3094.             aiTurnPending = true;
  3095.             return; // process on next tick
  3096.         }
  3097.         // 2A) If AI is displaying its aim line, count down then shoot
  3098.         if (aiIsDisplayingAim) {
  3099.             aiAimDisplayFramesLeft--;
  3100.             if (aiAimDisplayFramesLeft <= 0) {
  3101.                 aiIsDisplayingAim = false;
  3102.                 if (aiPlannedShotDetails.isValid) {
  3103.                     firstHitBallIdThisShot = -1;
  3104.                     cueHitObjectBallThisShot = false;
  3105.                     railHitAfterContact = false;
  3106.                     std::thread([](const TCHAR* soundName) {
  3107.                         PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT);
  3108.                         }, TEXT("cue.wav")).detach();
  3109.  
  3110.                         ApplyShot(
  3111.                             aiPlannedShotDetails.power,
  3112.                             aiPlannedShotDetails.angle,
  3113.                             aiPlannedShotDetails.spinX,
  3114.                             aiPlannedShotDetails.spinY
  3115.                         );
  3116.                         aiPlannedShotDetails.isValid = false;
  3117.                 }
  3118.                 currentGameState = SHOT_IN_PROGRESS;
  3119.                 foulCommitted = false;
  3120.                 pocketedThisTurn.clear();
  3121.             }
  3122.             return;
  3123.         }
  3124.  
  3125.         // 2B) Immediately after calling pocket, transition into AI_THINKING
  3126.         if (currentGameState == CHOOSING_POCKET_P2 && aiTurnPending) {
  3127.             // Start thinking/shooting right away—no human click required
  3128.             currentGameState = AI_THINKING;
  3129.             aiTurnPending = false;
  3130.             AIMakeDecision();
  3131.             return;
  3132.         }
  3133.  
  3134.         // 2C) If AI has pending actions (break, ball?in?hand, or normal turn)
  3135.         if (aiTurnPending) {
  3136.             if (currentGameState == BALL_IN_HAND_P2) {
  3137.                 AIPlaceCueBall();
  3138.                 currentGameState = AI_THINKING;
  3139.                 aiTurnPending = false;
  3140.                 AIMakeDecision();
  3141.             }
  3142.             else if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT) {
  3143.                 AIBreakShot();
  3144.             }
  3145.             else if (currentGameState == PLAYER2_TURN || currentGameState == BREAKING) {
  3146.                 currentGameState = AI_THINKING;
  3147.                 aiTurnPending = false;
  3148.                 AIMakeDecision();
  3149.             }
  3150.             return;
  3151.         }
  3152.     }
  3153. }
  3154.  
  3155.  
  3156. // --- Physics and Collision ---
  3157. void UpdatePhysics() {
  3158.     for (size_t i = 0; i < balls.size(); ++i) {
  3159.         Ball& b = balls[i];
  3160.         if (!b.isPocketed) {
  3161.  
  3162.             // --- FOOLPROOF FIX: Update rotation based on velocity ---
  3163.             float speed = sqrtf(b.vx * b.vx + b.vy * b.vy);
  3164.             if (speed > 0.01f) {
  3165.                 // The amount of rotation is proportional to the distance traveled.
  3166.                 // We can use the horizontal velocity component for a simple, effective rolling look.
  3167.                 b.rotationAngle += b.vx / (BALL_RADIUS * 10.0f); // Adjust divisor for spin speed
  3168.  
  3169.                 // Normalize the angle to keep it within the 0 to 2*PI range
  3170.                 const float TWO_PI = 2.0f * 3.1415926535f;
  3171.                 if (b.rotationAngle > TWO_PI) b.rotationAngle -= TWO_PI;
  3172.                 if (b.rotationAngle < 0) b.rotationAngle += TWO_PI;
  3173.             }
  3174.             // --- End Rotation Fix ---
  3175.  
  3176.                         // move
  3177.             b.x += b.vx;
  3178.             b.y += b.vy;
  3179.  
  3180.             // --- Update rotation from distance travelled this frame ---
  3181.             // Use the magnitude of the displacement (speed) to compute angular change:
  3182.             //   deltaAngle (radians) = distance / radius
  3183.             // This produces physically-plausible rotation regardless of direction.
  3184.             /* {
  3185.                 float speed = sqrtf(b.vx * b.vx + b.vy * b.vy); // distance units per frame
  3186.                 if (speed > 1e-6f) {
  3187.                     float deltaAngle = speed / BALL_RADIUS; // radians
  3188.                     // subtract -> clockwise feel, you can invert if you prefer
  3189.                     b.rotationAngle -= deltaAngle;
  3190.                     // keep angle bounded to avoid large drift (optional)
  3191.                     if (b.rotationAngle > 2.0f * PI || b.rotationAngle < -2.0f * PI)
  3192.                         b.rotationAngle = fmodf(b.rotationAngle, 2.0f * PI);
  3193.                 }
  3194.             }*/
  3195.  
  3196.             // Apply friction
  3197.             b.vx *= FRICTION;
  3198.             b.vy *= FRICTION;
  3199.  
  3200.             // --- ROTATION UPDATE: convert linear motion into visual rotation ---
  3201.             // Use the distance moved per frame (approx = speed since position increased by vx/vy per tick)
  3202.             // and convert to angular delta: deltaAngle = distance / radius.
  3203.             // Choose a sign so opposite directions produce opposite rotation.
  3204.             {
  3205.                 const float eps = 1e-5f;
  3206.                 float vx = b.vx;
  3207.                 float vy = b.vy;
  3208.                 float speed = sqrtf(vx * vx + vy * vy);
  3209.                 if (speed > eps) {
  3210.                     // distance moved this frame (we assume velocity units per tick)
  3211.                     float distance = speed; // velocities are per-tick; scale if you have explicit dt
  3212.                     float deltaAngle = distance / BALL_RADIUS; // radians per tick
  3213.  
  3214.                     // Heuristic sign: prefer rightwards motion to rotate positive, leftwards negative.
  3215.                     // This is a simple robust sign determination that gives visually plausible spin.
  3216.                     float sign = (vx > 0.0f) ? 1.0f : -1.0f;
  3217.  
  3218.                     // A small refinement: if horizontal velocity near zero, base sign on vertical
  3219.                     if (fabsf(vx) < 0.0001f) sign = (vy > 0.0f) ? 1.0f : -1.0f;
  3220.  
  3221.                     b.rotationAngle += deltaAngle * sign;
  3222.  
  3223.                     // Keep angle bounded to avoid large values
  3224.                     if (b.rotationAngle > 2.0f * PI) b.rotationAngle = fmodf(b.rotationAngle, 2.0f * PI);
  3225.                     if (b.rotationAngle < -2.0f * PI) b.rotationAngle = fmodf(b.rotationAngle, 2.0f * PI);
  3226.  
  3227.                     // rotation axis = direction perpendicular to travel. Used for highlight offset.
  3228.                     b.rotationAxis = atan2f(vy, vx) + (PI * 0.5f);
  3229.                 }
  3230.             }
  3231.             // --- End rotation update ---
  3232.  
  3233.             // Stop balls if velocity is very low
  3234.             if (GetDistanceSq(b.vx, b.vy, 0, 0) < MIN_VELOCITY_SQ) {
  3235.                 b.vx = 0;
  3236.                 b.vy = 0;
  3237.             }
  3238.  
  3239.             /* -----------------------------------------------------------------
  3240.    Additional clamp to guarantee the ball never escapes the table.
  3241.    The existing wall–collision code can momentarily disable the
  3242.    reflection test while the ball is close to a pocket mouth;
  3243.    that rare case allowed it to ‘slide’ through the cushion and
  3244.    leave the board.  We therefore enforce a final boundary check
  3245.    after the normal physics step.
  3246.    ----------------------------------------------------------------- */
  3247.             const float leftBound = TABLE_LEFT + BALL_RADIUS;
  3248.             const float rightBound = TABLE_RIGHT - BALL_RADIUS;
  3249.             const float topBound = TABLE_TOP + BALL_RADIUS;
  3250.             const float bottomBound = TABLE_BOTTOM - BALL_RADIUS;
  3251.  
  3252.             if (b.x < leftBound) { b.x = leftBound;   b.vx = fabsf(b.vx); }
  3253.             if (b.x > rightBound) { b.x = rightBound;  b.vx = -fabsf(b.vx); }
  3254.             if (b.y < topBound) { b.y = topBound;    b.vy = fabsf(b.vy); }
  3255.             if (b.y > bottomBound) { b.y = bottomBound; b.vy = -fabsf(b.vy); }
  3256.         }
  3257.     }
  3258. }
  3259.  
  3260. void CheckCollisions() {
  3261.     float left = TABLE_LEFT;
  3262.     float right = TABLE_RIGHT;
  3263.     float top = TABLE_TOP;
  3264.     float bottom = TABLE_BOTTOM;
  3265.  
  3266.     bool playedWallSoundThisFrame = false;
  3267.     bool playedCollideSoundThisFrame = false;
  3268.     for (size_t i = 0; i < balls.size(); ++i) {
  3269.         Ball& b1 = balls[i];
  3270.         if (b1.isPocketed) continue;
  3271.  
  3272.         // --- FOOLPROOF FIX 2: Synchronize Rim Collision with Pocketing ---
  3273.         // If a ball is already inside a pocket's mask area, we MUST skip rim collision
  3274.         // to prevent it from bouncing back out.
  3275.         bool skipRimCollisionForThisBall = false;
  3276.         for (int p = 0; p < 6; ++p) {
  3277.             if (IsBallTouchingPocketMask_D2D(b1, p)) {
  3278.                 skipRimCollisionForThisBall = true;
  3279.                 break;
  3280.             }
  3281.         }
  3282.         if (skipRimCollisionForThisBall) {
  3283.             continue; // Skip all wall/rim collision checks for this ball and move to the next.
  3284.         }
  3285.         // --- END OF SYNCHRONIZATION FIX ---
  3286.  
  3287.         // --- FOOLPROOF FIX 1: Accurate V-Cut Rim Collision Physics ---
  3288. //const float rimWidth = 15.0f;
  3289.         //const float vCutDepth = 35.0f; // How deep the V-cut is.
  3290.  
  3291.         // --- NEW: If this ball already overlaps a pocket mouth/area then skip rim collision.
  3292.         // Rationale: avoid reflecting balls back off the rim when they are inside the V-cut opening.
  3293.         //bool skipRimCollisionForThisBall = false;
  3294.         for (int p = 0; p < 6; ++p) {
  3295.             if (IsBallInPocketPolygon(b1, p) || IsBallTouchingPocketMask_D2D(b1, p)) {
  3296.                 skipRimCollisionForThisBall = true;
  3297.                 break;
  3298.             }
  3299.         }
  3300.  
  3301.         // If the ball is not near a pocket mouth, do the rim collision tests. Otherwise allow pocketing logic.
  3302.         if (!skipRimCollisionForThisBall) {
  3303.             // Define the 12 vertices of the new inner rim boundary
  3304.             D2D1_POINT_2F vertices[12] = {
  3305.                 /*0*/ D2D1::Point2F(TABLE_LEFT + INNER_RIM_THICKNESS, TABLE_TOP + CHAMFER_SIZE),                                 // Top-Left pocket V-cut (inner point)
  3306.                 /*1*/ D2D1::Point2F(TABLE_LEFT + CHAMFER_SIZE, TABLE_TOP + INNER_RIM_THICKNESS),                                 // Top-Left pocket V-cut (outer point)
  3307.                 /*2*/ D2D1::Point2F(TABLE_RIGHT - CHAMFER_SIZE, TABLE_TOP + INNER_RIM_THICKNESS),                                // Top-Right pocket V-cut (outer point)
  3308.                 /*3*/ D2D1::Point2F(TABLE_RIGHT - INNER_RIM_THICKNESS, TABLE_TOP + CHAMFER_SIZE),                                 // Top-Right pocket V-cut (inner point)
  3309.                 /*4*/ D2D1::Point2F(TABLE_RIGHT - INNER_RIM_THICKNESS, TABLE_BOTTOM - CHAMFER_SIZE),                              // Bottom-Right pocket V-cut (inner point)
  3310.                 /*5*/ D2D1::Point2F(TABLE_RIGHT - CHAMFER_SIZE, TABLE_BOTTOM - INNER_RIM_THICKNESS),                              // Bottom-Right pocket V-cut (outer point)
  3311.                 /*6*/ D2D1::Point2F(TABLE_LEFT + CHAMFER_SIZE, TABLE_BOTTOM - INNER_RIM_THICKNESS),                               // Bottom-Left pocket V-cut (outer point)
  3312.                 /*7*/ D2D1::Point2F(TABLE_LEFT + INNER_RIM_THICKNESS, TABLE_BOTTOM - CHAMFER_SIZE),                               // Bottom-Left pocket V-cut (inner point)
  3313.                 /*8*/ D2D1::Point2F(TABLE_LEFT + INNER_RIM_THICKNESS, TABLE_TOP + TABLE_HEIGHT / 2 - CHAMFER_SIZE / 2),           // Mid-Left pocket V-cut (top point)
  3314.                 /*9*/ D2D1::Point2F(TABLE_LEFT + INNER_RIM_THICKNESS, TABLE_TOP + TABLE_HEIGHT / 2 + CHAMFER_SIZE / 2),           // Mid-Left pocket V-cut (bottom point)
  3315.                 /*10*/ D2D1::Point2F(TABLE_RIGHT - INNER_RIM_THICKNESS, TABLE_TOP + TABLE_HEIGHT / 2 + CHAMFER_SIZE / 2),          // Mid-Right pocket V-cut (bottom point)
  3316.                 /*11*/ D2D1::Point2F(TABLE_RIGHT - INNER_RIM_THICKNESS, TABLE_TOP + TABLE_HEIGHT / 2 - CHAMFER_SIZE / 2)           // Mid-Right pocket V-cut (top point)
  3317.             };
  3318.  
  3319.             // Define the 12 line segments that form the entire inner boundary
  3320.             D2D1_POINT_2F segments[12][2] = {
  3321.                 { vertices[1], vertices[2] },   // Top rail
  3322.                 { vertices[2], vertices[3] },   // Top-Right V
  3323.                 { vertices[3], vertices[11] },  // Right rail (top part)
  3324.                 { vertices[11], vertices[10] }, // Right rail (middle part - straight)
  3325.                 { vertices[10], vertices[4] },  // Right rail (bottom part)
  3326.                 { vertices[4], vertices[5] },   // Bottom-Right V
  3327.                 { vertices[5], vertices[6] },   // Bottom rail
  3328.                 { vertices[6], vertices[7] },   // Bottom-Left V
  3329.                 { vertices[7], vertices[9] },   // Left rail (bottom part)
  3330.                 { vertices[9], vertices[8] },   // Left rail (middle part - straight)
  3331.                 { vertices[8], vertices[0] },   // Left rail (top part)
  3332.                 { vertices[0], vertices[1] }    // Top-Left V
  3333.             };
  3334.  
  3335.             for (int j = 0; j < 12; ++j) { // Iterate through all 12 rim segments
  3336.                 D2D1_POINT_2F p1 = segments[j][0];
  3337.                 D2D1_POINT_2F p2 = segments[j][1];
  3338.                 float distSq = PointToLineSegmentDistanceSq(D2D1::Point2F(b1.x, b1.y), p1, p2);
  3339.  
  3340.                 if (distSq < BALL_RADIUS * BALL_RADIUS) {
  3341.                     float segDx = p2.x - p1.x, segDy = p2.y - p1.y;
  3342.                     float normalX = -segDy, normalY = segDx;
  3343.                     float normalLen = sqrtf(normalX * normalX + normalY * normalY);
  3344.                     if (normalLen > 1e-6f) { normalX /= normalLen; normalY /= normalLen; }
  3345.  
  3346.                     float dot = b1.vx * normalX + b1.vy * normalY;
  3347.                     b1.vx -= 2 * dot * normalX;
  3348.                     b1.vy -= 2 * dot * normalY;
  3349.  
  3350.                     b1.x += normalX * (BALL_RADIUS - sqrtf(distSq));
  3351.                     b1.y += normalY * (BALL_RADIUS - sqrtf(distSq));
  3352.  
  3353.                     if (!playedWallSoundThisFrame) {
  3354.                         std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  3355.                         playedWallSoundThisFrame = true;
  3356.                     }
  3357.                     break; // A ball can only hit one wall segment per frame.
  3358.                 }
  3359.             }
  3360.         }
  3361.         // --- END OF V-CUT RIM COLLISION FIX ---
  3362.  
  3363.         /*// --- FOOLPROOF FIX 1: Inner Chamfered Rim Collision ---
  3364.         const float rimWidth = 15.0f; // This MUST match the rimWidth in DrawTable
  3365.         const float rimLeft = TABLE_LEFT + rimWidth;
  3366.         const float rimRight = TABLE_RIGHT - rimWidth;
  3367.         const float rimTop = TABLE_TOP + rimWidth;
  3368.         const float rimBottom = TABLE_BOTTOM - rimWidth;
  3369.  
  3370.         // Check for collision with the four segments of the inner rim
  3371.         if (b1.x - BALL_RADIUS < rimLeft && b1.x > TABLE_LEFT) {
  3372.             b1.x = rimLeft + BALL_RADIUS;
  3373.             b1.vx *= -1.0f; // Reverse horizontal velocity
  3374.             if (!playedWallSoundThisFrame) {
  3375.                 std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  3376.                 playedWallSoundThisFrame = true;
  3377.             }
  3378.         }
  3379.         if (b1.x + BALL_RADIUS > rimRight && b1.x < TABLE_RIGHT) {
  3380.             b1.x = rimRight - BALL_RADIUS;
  3381.             b1.vx *= -1.0f;
  3382.             if (!playedWallSoundThisFrame) {
  3383.                 std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  3384.                 playedWallSoundThisFrame = true;
  3385.             }
  3386.         }
  3387.         if (b1.y - BALL_RADIUS < rimTop && b1.y > TABLE_TOP) {
  3388.             b1.y = rimTop + BALL_RADIUS;
  3389.             b1.vy *= -1.0f; // Reverse vertical velocity
  3390.             if (!playedWallSoundThisFrame) {
  3391.                 std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  3392.                 playedWallSoundThisFrame = true;
  3393.             }
  3394.         }
  3395.         if (b1.y + BALL_RADIUS > rimBottom && b1.y < TABLE_BOTTOM) {
  3396.             b1.y = rimBottom - BALL_RADIUS;
  3397.             b1.vy *= -1.0f;
  3398.             if (!playedWallSoundThisFrame) {
  3399.                 std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  3400.                 playedWallSoundThisFrame = true;
  3401.             }
  3402.         }
  3403.         // --- END OF RIM COLLISION FIX ---*/
  3404.  
  3405.         bool nearPocket[6];
  3406.         for (int p = 0; p < 6; ++p) {
  3407.             // Use correct radius to check if a ball is near a pocket to prevent wall collisions
  3408.             float physicalPocketRadius = ((p == 1 || p == 4) ? MIDDLE_HOLE_VISUAL_RADIUS : CORNER_HOLE_VISUAL_RADIUS) * 1.05f;
  3409.             float checkRadiusSq = (physicalPocketRadius + BALL_RADIUS) * (physicalPocketRadius + BALL_RADIUS) * 1.1f;
  3410.             nearPocket[p] = GetDistanceSq(b1.x, b1.y, pocketPositions[p].x, pocketPositions[p].y) < checkRadiusSq;
  3411.         }
  3412.  
  3413.         bool nearTopLeftPocket = nearPocket[0];
  3414.         bool nearTopMidPocket = nearPocket[1];
  3415.         bool nearTopRightPocket = nearPocket[2];
  3416.         bool nearBottomLeftPocket = nearPocket[3];
  3417.         bool nearBottomMidPocket = nearPocket[4];
  3418.         bool nearBottomRightPocket = nearPocket[5];
  3419.         bool collidedWallThisBall = false;
  3420.         if (b1.x - BALL_RADIUS < left) {
  3421.             if (!nearTopLeftPocket && !nearBottomLeftPocket) {
  3422.                 b1.x = left + BALL_RADIUS; b1.vx *= -1.0f; collidedWallThisBall = true;
  3423.                 if (!playedWallSoundThisFrame) {
  3424.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  3425.                     playedWallSoundThisFrame = true;
  3426.                 }
  3427.                 if (cueHitObjectBallThisShot) railHitAfterContact = true;
  3428.             }
  3429.         }
  3430.         if (b1.x + BALL_RADIUS > right) {
  3431.             if (!nearTopRightPocket && !nearBottomRightPocket) {
  3432.                 b1.x = right - BALL_RADIUS; b1.vx *= -1.0f; collidedWallThisBall = true;
  3433.                 if (!playedWallSoundThisFrame) {
  3434.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  3435.                     playedWallSoundThisFrame = true;
  3436.                 }
  3437.                 if (cueHitObjectBallThisShot) railHitAfterContact = true;
  3438.             }
  3439.         }
  3440.         if (b1.y - BALL_RADIUS < top) {
  3441.             if (!nearTopLeftPocket && !nearTopMidPocket && !nearTopRightPocket) {
  3442.                 b1.y = top + BALL_RADIUS; b1.vy *= -1.0f; collidedWallThisBall = true;
  3443.                 if (!playedWallSoundThisFrame) {
  3444.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  3445.                     playedWallSoundThisFrame = true;
  3446.                 }
  3447.                 if (cueHitObjectBallThisShot) railHitAfterContact = true;
  3448.             }
  3449.         }
  3450.         if (b1.y + BALL_RADIUS > bottom) {
  3451.             if (!nearBottomLeftPocket && !nearBottomMidPocket && !nearBottomRightPocket) {
  3452.                 b1.y = bottom - BALL_RADIUS; b1.vy *= -1.0f; collidedWallThisBall = true;
  3453.                 if (!playedWallSoundThisFrame) {
  3454.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  3455.                     playedWallSoundThisFrame = true;
  3456.                 }
  3457.                 if (cueHitObjectBallThisShot) railHitAfterContact = true;
  3458.             }
  3459.         }
  3460.         if (collidedWallThisBall) {
  3461.             if (b1.x <= left + BALL_RADIUS || b1.x >= right - BALL_RADIUS) { b1.vy += cueSpinX * b1.vx * 0.05f; }
  3462.             if (b1.y <= top + BALL_RADIUS || b1.y >= bottom - BALL_RADIUS) { b1.vx -= cueSpinY * b1.vy * 0.05f; }
  3463.             cueSpinX *= 0.7f; cueSpinY *= 0.7f;
  3464.         }
  3465.         for (size_t j = i + 1; j < balls.size(); ++j) {
  3466.             Ball& b2 = balls[j];
  3467.             if (b2.isPocketed) continue;
  3468.             float dx = b2.x - b1.x; float dy = b2.y - b1.y;
  3469.             float distSq = dx * dx + dy * dy;
  3470.             float minDist = BALL_RADIUS * 2.0f;
  3471.             if (distSq > 1e-6 && distSq < minDist * minDist) {
  3472.                 float dist = sqrtf(distSq);
  3473.                 float overlap = minDist - dist;
  3474.                 float nx = dx / dist; float ny = dy / dist;
  3475.                 b1.x -= overlap * 0.5f * nx; b1.y -= overlap * 0.5f * ny;
  3476.                 b2.x += overlap * 0.5f * nx; b2.y += overlap * 0.5f * ny;
  3477.                 float rvx = b1.vx - b2.vx; float rvy = b1.vy - b2.vy;
  3478.                 float velAlongNormal = rvx * nx + rvy * ny;
  3479.                 if (velAlongNormal > 0) {
  3480.                     if (!playedCollideSoundThisFrame) {
  3481.                         std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("poolballhit.wav")).detach();
  3482.                         playedCollideSoundThisFrame = true;
  3483.                     }
  3484.                     if (firstHitBallIdThisShot == -1) {
  3485.                         if (b1.id == 0) {
  3486.                             firstHitBallIdThisShot = b2.id;
  3487.                             cueHitObjectBallThisShot = true;
  3488.                         }
  3489.                         else if (b2.id == 0) {
  3490.                             firstHitBallIdThisShot = b1.id;
  3491.                             cueHitObjectBallThisShot = true;
  3492.                         }
  3493.                     }
  3494.                     else if (b1.id == 0 || b2.id == 0) {
  3495.                         cueHitObjectBallThisShot = true;
  3496.                     }
  3497.                     float impulse = velAlongNormal;
  3498.                     b1.vx -= impulse * nx; b1.vy -= impulse * ny;
  3499.                     b2.vx += impulse * nx; b2.vy += impulse * ny;
  3500.                     if (b1.id == 0 || b2.id == 0) {
  3501.                         float spinEffectFactor = 0.08f;
  3502.                         b1.vx += (cueSpinY * ny - cueSpinX * nx) * spinEffectFactor;
  3503.                         b1.vy += (cueSpinY * nx + cueSpinX * ny) * spinEffectFactor;
  3504.                         b2.vx -= (cueSpinY * ny - cueSpinX * nx) * spinEffectFactor;
  3505.                         b2.vy -= (cueSpinY * nx + cueSpinX * ny) * spinEffectFactor;
  3506.                         cueSpinX *= 0.85f; cueSpinY *= 0.85f;
  3507.                     }
  3508.                 }
  3509.             }
  3510.         }
  3511.     }
  3512. }
  3513.  
  3514.  
  3515. bool CheckPockets() {
  3516.     bool anyPocketed = false;
  3517.     bool playedPocketSound = false; // Ensures sound plays only once per frame
  3518.  
  3519.     for (auto& b : balls) {
  3520.         if (b.isPocketed) continue;
  3521.  
  3522.         for (int p = 0; p < 6; ++p) {
  3523.             // --- FOOLPROOF FIX 3: Use the Unified Mask for Pocket Detection ---
  3524.             // This is now the ONLY test for whether a ball is pocketed.
  3525.             if (IsBallTouchingPocketMask_D2D(b, p)) {
  3526.  
  3527.                 // Mark the ball as pocketed
  3528.                 b.isPocketed = true;
  3529.                 b.vx = b.vy = 0.0f; // Stop its movement
  3530.                 pocketedThisTurn.push_back(b.id);
  3531.                 anyPocketed = true;
  3532.  
  3533.                 if (b.id == 8) {
  3534.                     lastEightBallPocketIndex = p;
  3535.                 }
  3536.  
  3537.                 // Play the pocket sound (only once per physics update)
  3538.                 if (!playedPocketSound) {
  3539.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("pocket.wav")).detach();
  3540.                     playedPocketSound = true;
  3541.                 }
  3542.  
  3543.                 break; // Ball is pocketed, no need to check other pockets for it.
  3544.             }
  3545.         }
  3546.     }
  3547.     return anyPocketed;
  3548. }
  3549.  
  3550.  
  3551. /*bool CheckPockets() {
  3552.     bool anyPocketed = false;
  3553.     bool ballPocketedThisCheck = false;
  3554.     for (auto& b : balls) {
  3555.         if (b.isPocketed) continue;
  3556.         for (int p = 0; p < 6; ++p) {
  3557.             D2D1_POINT_2F center = pocketPositions[p];
  3558.             float dx = b.x - center.x;
  3559.             float dy = b.y - center.y;
  3560.  
  3561.             // Use the correct radius for the pocket being checked
  3562.             float currentPocketRadius = (p == 1 || p == 4) ? MIDDLE_HOLE_VISUAL_RADIUS : CORNER_HOLE_VISUAL_RADIUS;
  3563.  
  3564.             bool isInPocket = false;
  3565.             // The pocketing conditions now use the correct radius
  3566.             if (p == 1) {
  3567.                 if (dy >= 0 && dx * dx + dy * dy <= currentPocketRadius * currentPocketRadius)
  3568.                     isInPocket = true;
  3569.             }
  3570.             else if (p == 4) {
  3571.                 if (dy <= 0 && dx * dx + dy * dy <= currentPocketRadius * currentPocketRadius)
  3572.                     isInPocket = true;
  3573.             }
  3574.             else {
  3575.                 if (dx * dx + dy * dy <= currentPocketRadius * currentPocketRadius)
  3576.                     isInPocket = true;
  3577.             }
  3578.  
  3579.             if (isInPocket) {
  3580.                 if (b.id == 8) {
  3581.                     lastEightBallPocketIndex = p;
  3582.                 }
  3583.                 b.isPocketed = true;
  3584.                 b.vx = b.vy = 0.0f;
  3585.                 pocketedThisTurn.push_back(b.id);
  3586.                 anyPocketed = true;
  3587.                 if (!ballPocketedThisCheck) {
  3588.                     std::thread([](const TCHAR* soundName) {
  3589.                         PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT);
  3590.                         }, TEXT("pocket.wav")).detach();
  3591.                         ballPocketedThisCheck = true;
  3592.                 }
  3593.                 break;
  3594.             }
  3595.         }
  3596.     }
  3597.     return anyPocketed;
  3598. }*/
  3599.  
  3600.  
  3601. bool AreBallsMoving() {
  3602.     for (size_t i = 0; i < balls.size(); ++i) {
  3603.         if (!balls[i].isPocketed && (balls[i].vx != 0 || balls[i].vy != 0)) {
  3604.             return true;
  3605.         }
  3606.     }
  3607.     return false;
  3608. }
  3609.  
  3610. void RespawnCueBall(bool behindHeadstring) {
  3611.     Ball* cueBall = GetCueBall();
  3612.     if (cueBall) {
  3613.         // Determine the initial target position
  3614.         float targetX, targetY;
  3615.         if (behindHeadstring) {
  3616.             targetX = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f;
  3617.             targetY = TABLE_TOP + TABLE_HEIGHT / 2.0f;
  3618.         }
  3619.         else {
  3620.             targetX = TABLE_LEFT + TABLE_WIDTH / 2.0f;
  3621.             targetY = TABLE_TOP + TABLE_HEIGHT / 2.0f;
  3622.         }
  3623.  
  3624.         // FOOLPROOF FIX: Check if the target spot is valid. If not, nudge it until it is.
  3625.         int attempts = 0;
  3626.         while (!IsValidCueBallPosition(targetX, targetY, behindHeadstring) && attempts < 100) {
  3627.             // If the spot is occupied, try nudging the ball slightly.
  3628.             targetX += (static_cast<float>(rand() % 100 - 50) / 50.0f) * BALL_RADIUS;
  3629.             targetY += (static_cast<float>(rand() % 100 - 50) / 50.0f) * BALL_RADIUS;
  3630.             // Clamp to stay within reasonable bounds
  3631.             targetX = std::max(TABLE_LEFT + BALL_RADIUS, std::min(targetX, TABLE_RIGHT - BALL_RADIUS));
  3632.             targetY = std::max(TABLE_TOP + BALL_RADIUS, std::min(targetY, TABLE_BOTTOM - BALL_RADIUS));
  3633.             attempts++;
  3634.         }
  3635.  
  3636.         // Set the final, valid position.
  3637.         cueBall->x = targetX;
  3638.         cueBall->y = targetY;
  3639.         cueBall->vx = 0;
  3640.         cueBall->vy = 0;
  3641.         cueBall->isPocketed = false;
  3642.  
  3643.         // Set the correct game state for ball-in-hand.
  3644.         if (currentPlayer == 1) {
  3645.             currentGameState = BALL_IN_HAND_P1;
  3646.             aiTurnPending = false;
  3647.         }
  3648.         else {
  3649.             currentGameState = BALL_IN_HAND_P2;
  3650.             if (isPlayer2AI) {
  3651.                 aiTurnPending = true;
  3652.             }
  3653.         }
  3654.     }
  3655. }
  3656.  
  3657.  
  3658. // --- Game Logic ---
  3659.  
  3660. void ApplyShot(float power, float angle, float spinX, float spinY) {
  3661.     Ball* cueBall = GetCueBall();
  3662.     if (cueBall) {
  3663.  
  3664.         // --- Play Cue Strike Sound (Threaded) ---
  3665.         if (power > 0.1f) { // Only play if it's an audible shot
  3666.             std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
  3667.         }
  3668.         // --- End Sound ---
  3669.  
  3670.         cueBall->vx = cosf(angle) * power;
  3671.         cueBall->vy = sinf(angle) * power;
  3672.  
  3673.         // Apply English (Spin) - Simplified effect (Unchanged)
  3674.         cueBall->vx += sinf(angle) * spinY * 0.5f;
  3675.         cueBall->vy -= cosf(angle) * spinY * 0.5f;
  3676.         cueBall->vx -= cosf(angle) * spinX * 0.5f;
  3677.         cueBall->vy -= sinf(angle) * spinX * 0.5f;
  3678.  
  3679.         // Store spin (Unchanged)
  3680.         cueSpinX = spinX;
  3681.         cueSpinY = spinY;
  3682.  
  3683.         // --- Reset Foul Tracking flags for the new shot ---
  3684.         // (Also reset in LBUTTONUP, but good to ensure here too)
  3685.         firstHitBallIdThisShot = -1;      // No ball hit yet
  3686.         cueHitObjectBallThisShot = false; // Cue hasn't hit anything yet
  3687.         railHitAfterContact = false;     // No rail hit after contact yet
  3688.         // --- End Reset ---
  3689.  
  3690.                 // If this was the opening break shot, clear the flag
  3691.         if (isOpeningBreakShot) {
  3692.             isOpeningBreakShot = false; // Mark opening break as taken
  3693.         }
  3694.     }
  3695. }
  3696.  
  3697.  
  3698. // ---------------------------------------------------------------------
  3699. //  ProcessShotResults()
  3700. // ---------------------------------------------------------------------
  3701. void ProcessShotResults() {
  3702.     bool cueBallPocketed = false;
  3703.     bool eightBallPocketed = false;
  3704.     bool playerContinuesTurn = false;
  3705.  
  3706.     // --- Step 1: Update Ball Counts FIRST (THE CRITICAL FIX) ---
  3707.     // We must update the score before any other game logic runs.
  3708.     PlayerInfo& shootingPlayer = (currentPlayer == 1) ? player1Info : player2Info;
  3709.     int ownBallsPocketedThisTurn = 0;
  3710.  
  3711.     for (int id : pocketedThisTurn) {
  3712.         Ball* b = GetBallById(id);
  3713.         if (!b) continue;
  3714.  
  3715.         if (b->id == 0) {
  3716.             cueBallPocketed = true;
  3717.         }
  3718.         else if (b->id == 8) {
  3719.             eightBallPocketed = true;
  3720.         }
  3721.         else {
  3722.             // This is a numbered ball. Update the pocketed count for the correct player.
  3723.             if (b->type == player1Info.assignedType && player1Info.assignedType != BallType::NONE) {
  3724.                 player1Info.ballsPocketedCount++;
  3725.             }
  3726.             else if (b->type == player2Info.assignedType && player2Info.assignedType != BallType::NONE) {
  3727.                 player2Info.ballsPocketedCount++;
  3728.             }
  3729.  
  3730.             if (b->type == shootingPlayer.assignedType) {
  3731.                 ownBallsPocketedThisTurn++;
  3732.             }
  3733.         }
  3734.     }
  3735.  
  3736.     if (ownBallsPocketedThisTurn > 0) {
  3737.         playerContinuesTurn = true;
  3738.     }
  3739.  
  3740.     // --- Step 2: Handle Game-Ending 8-Ball Shot ---
  3741.     // Now that the score is updated, this check will have the correct information.
  3742.     if (eightBallPocketed) {
  3743.         CheckGameOverConditions(true, cueBallPocketed);
  3744.         if (currentGameState == GAME_OVER) {
  3745.             pocketedThisTurn.clear();
  3746.             return;
  3747.         }
  3748.     }
  3749.  
  3750.     // --- Step 3: Check for Fouls ---
  3751.     bool turnFoul = false;
  3752.     if (cueBallPocketed) {
  3753.         turnFoul = true;
  3754.     }
  3755.     else {
  3756.         Ball* firstHit = GetBallById(firstHitBallIdThisShot);
  3757.         if (!firstHit) { // Rule: Hitting nothing is a foul.
  3758.             turnFoul = true;
  3759.         }
  3760.         else { // Rule: Hitting the wrong ball type is a foul.
  3761.             if (player1Info.assignedType != BallType::NONE) { // Colors are assigned.
  3762.                 // We check if the player WAS on the 8-ball BEFORE this shot.
  3763.                 bool wasOnEightBall = (shootingPlayer.assignedType != BallType::NONE && (shootingPlayer.ballsPocketedCount - ownBallsPocketedThisTurn) >= 7);
  3764.                 if (wasOnEightBall) {
  3765.                     if (firstHit->id != 8) turnFoul = true;
  3766.                 }
  3767.                 else {
  3768.                     if (firstHit->type != shootingPlayer.assignedType) turnFoul = true;
  3769.                 }
  3770.             }
  3771.         }
  3772.     } //reenable below disabled for debugging
  3773.     //if (!turnFoul && cueHitObjectBallThisShot && !railHitAfterContact && pocketedThisTurn.empty()) {
  3774.         //turnFoul = true;
  3775.     //}
  3776.         // remember logical foul for game flow
  3777.     foulCommitted = turnFoul;
  3778.     // Also set a short-lived display counter so FOUL! can be shown on the HUD
  3779.     if (turnFoul) {
  3780.         // ~120 frames (about 2 seconds at 60fps); tweak as desired
  3781.         foulDisplayCounter = 120;
  3782.     }
  3783.     //foulCommitted = turnFoul;
  3784.  
  3785.     // --- Step 4: Final State Transition ---
  3786.     if (foulCommitted) {
  3787.         SwitchTurns();
  3788.         RespawnCueBall(false);
  3789.     }
  3790.     else if (player1Info.assignedType == BallType::NONE && !pocketedThisTurn.empty() && !cueBallPocketed) {
  3791.         // Assign types on the break.
  3792.         for (int id : pocketedThisTurn) {
  3793.             Ball* b = GetBallById(id);
  3794.             if (b && b->type != BallType::EIGHT_BALL) {
  3795.                 AssignPlayerBallTypes(b->type);
  3796.                 break;
  3797.             }
  3798.         }
  3799.         CheckAndTransitionToPocketChoice(currentPlayer);
  3800.     }
  3801.     else if (playerContinuesTurn) {
  3802.         // The player's turn continues. Now the check will work correctly.
  3803.         CheckAndTransitionToPocketChoice(currentPlayer);
  3804.     }
  3805.     else {
  3806.         SwitchTurns();
  3807.     }
  3808.  
  3809.     pocketedThisTurn.clear();
  3810. }
  3811.  
  3812. /*
  3813. // --- Step 3: Final State Transition ---
  3814. if (foulCommitted) {
  3815.     SwitchTurns();
  3816.     RespawnCueBall(false);
  3817. }
  3818. else if (playerContinuesTurn) {
  3819.     CheckAndTransitionToPocketChoice(currentPlayer);
  3820. }
  3821. else {
  3822.     SwitchTurns();
  3823. }
  3824.  
  3825. pocketedThisTurn.clear();
  3826. } */
  3827.  
  3828. //  Assign groups AND optionally give the shooter his first count.
  3829. bool AssignPlayerBallTypes(BallType firstPocketedType, bool creditShooter /*= true*/)
  3830. {
  3831.     if (firstPocketedType != SOLID && firstPocketedType != STRIPE)
  3832.         return false;                                 // safety
  3833.  
  3834.     /* ---------------------------------------------------------
  3835.        1.  Decide the groups
  3836.     --------------------------------------------------------- */
  3837.     if (currentPlayer == 1)
  3838.     {
  3839.         player1Info.assignedType = firstPocketedType;
  3840.         player2Info.assignedType =
  3841.             (firstPocketedType == SOLID) ? STRIPE : SOLID;
  3842.     }
  3843.     else
  3844.     {
  3845.         player2Info.assignedType = firstPocketedType;
  3846.         player1Info.assignedType =
  3847.             (firstPocketedType == SOLID) ? STRIPE : SOLID;
  3848.     }
  3849.  
  3850.     /* ---------------------------------------------------------
  3851.        2.  Count the very ball that made the assignment
  3852.     --------------------------------------------------------- */
  3853.     if (creditShooter)
  3854.     {
  3855.         if (currentPlayer == 1)
  3856.             ++player1Info.ballsPocketedCount;
  3857.         else
  3858.             ++player2Info.ballsPocketedCount;
  3859.     }
  3860.     return true;
  3861. }
  3862.  
  3863. /*bool AssignPlayerBallTypes(BallType firstPocketedType) {
  3864.     if (firstPocketedType == BallType::SOLID || firstPocketedType == BallType::STRIPE) {
  3865.         if (currentPlayer == 1) {
  3866.             player1Info.assignedType = firstPocketedType;
  3867.             player2Info.assignedType = (firstPocketedType == BallType::SOLID) ? BallType::STRIPE : BallType::SOLID;
  3868.         }
  3869.         else {
  3870.             player2Info.assignedType = firstPocketedType;
  3871.             player1Info.assignedType = (firstPocketedType == BallType::SOLID) ? BallType::STRIPE : BallType::SOLID;
  3872.         }
  3873.         return true; // Assignment was successful
  3874.     }
  3875.     return false; // No assignment made (e.g., 8-ball was pocketed on break)
  3876. }*/
  3877. // If 8-ball was first (illegal on break generally), rules vary.
  3878. // Here, we might ignore assignment until a solid/stripe is pocketed legally.
  3879. // Or assign based on what *else* was pocketed, if anything.
  3880. // Simplification: Assignment only happens on SOLID or STRIPE first pocket.
  3881.  
  3882.  
  3883. // --- Called in ProcessShotResults() after pocket detection ---
  3884. void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed)
  3885. {
  3886.     // Only care if the 8?ball really went in:
  3887.     if (!eightBallPocketed) return;
  3888.  
  3889.     // Who’s shooting now?
  3890.     PlayerInfo& shooter = (currentPlayer == 1) ? player1Info : player2Info;
  3891.     PlayerInfo& opponent = (currentPlayer == 1) ? player2Info : player1Info;
  3892.  
  3893.     // Which pocket did we CALL?
  3894.     int called = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  3895.     // Which pocket did it ACTUALLY fall into?
  3896.     int actual = lastEightBallPocketIndex;
  3897.  
  3898.     // Check legality: must have called a pocket ?0, must match actual,
  3899.     // must have pocketed all 7 of your balls first, and must not have scratched.
  3900.     bool legal = (called >= 0)
  3901.         && (called == actual)
  3902.         && (shooter.ballsPocketedCount >= 7)
  3903.         && (!cueBallPocketed);
  3904.  
  3905.     // Build a message that shows both values for debugging/tracing:
  3906.     if (legal) {
  3907.         gameOverMessage = shooter.name
  3908.             + L" Wins! "
  3909.             + L"(Called: " + std::to_wstring(called)
  3910.             + L", Actual: " + std::to_wstring(actual) + L")";
  3911.     }
  3912.     else {
  3913.         gameOverMessage = opponent.name
  3914.             + L" Wins! (Illegal 8-Ball) "
  3915.             + L"(Called: " + std::to_wstring(called)
  3916.             + L", Actual: " + std::to_wstring(actual) + L")";
  3917.     }
  3918.  
  3919.     currentGameState = GAME_OVER;
  3920. }
  3921.  
  3922.  
  3923.  
  3924. /*void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed) {
  3925.     if (!eightBallPocketed) return;
  3926.  
  3927.     PlayerInfo& shootingPlayer = (currentPlayer == 1) ? player1Info : player2Info;
  3928.     PlayerInfo& opponentPlayer = (currentPlayer == 1) ? player2Info : player1Info;
  3929.  
  3930.     // Handle 8-ball on break: re-spot and continue.
  3931.     if (player1Info.assignedType == BallType::NONE) {
  3932.         Ball* b = GetBallById(8);
  3933.         if (b) { b->isPocketed = false; b->x = RACK_POS_X; b->y = RACK_POS_Y; b->vx = b->vy = 0; }
  3934.         if (cueBallPocketed) foulCommitted = true;
  3935.         return;
  3936.     }
  3937.  
  3938.     // --- FOOLPROOF WIN/LOSS LOGIC ---
  3939.     bool wasOnEightBall = IsPlayerOnEightBall(currentPlayer);
  3940.     int calledPocket = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  3941.     int actualPocket = -1;
  3942.  
  3943.     // Find which pocket the 8-ball actually went into.
  3944.     for (int id : pocketedThisTurn) {
  3945.         if (id == 8) {
  3946.             Ball* b = GetBallById(8); // This ball is already marked as pocketed, but we need its last coords.
  3947.             if (b) {
  3948.                 for (int p_idx = 0; p_idx < 6; ++p_idx) {
  3949.                     // Check last known position against pocket centers
  3950.                     if (GetDistanceSq(b->x, b->y, pocketPositions[p_idx].x, pocketPositions[p_idx].y) < POCKET_RADIUS * POCKET_RADIUS * 1.5f) {
  3951.                         actualPocket = p_idx;
  3952.                         break;
  3953.                     }
  3954.                 }
  3955.             }
  3956.             break;
  3957.         }
  3958.     }
  3959.  
  3960.     // Evaluate win/loss based on a clear hierarchy of rules.
  3961.     if (!wasOnEightBall) {
  3962.         gameOverMessage = opponentPlayer.name + L" Wins! (8-Ball Pocketed Early)";
  3963.     }
  3964.     else if (cueBallPocketed) {
  3965.         gameOverMessage = opponentPlayer.name + L" Wins! (Scratched on 8-Ball)";
  3966.     }
  3967.     else if (calledPocket == -1) {
  3968.         gameOverMessage = opponentPlayer.name + L" Wins! (Pocket Not Called)";
  3969.     }
  3970.     else if (actualPocket != calledPocket) {
  3971.         gameOverMessage = opponentPlayer.name + L" Wins! (8-Ball in Wrong Pocket)";
  3972.     }
  3973.     else {
  3974.         // WIN! All loss conditions failed, this must be a legal win.
  3975.         gameOverMessage = shootingPlayer.name + L" Wins!";
  3976.     }
  3977.  
  3978.     currentGameState = GAME_OVER;
  3979. }*/
  3980.  
  3981. /*void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed)
  3982. {
  3983.     if (!eightBallPocketed) return;
  3984.  
  3985.     PlayerInfo& shooter = (currentPlayer == 1) ? player1Info : player2Info;
  3986.     PlayerInfo& opponent = (currentPlayer == 1) ? player2Info : player1Info;
  3987.     // Which pocket did we call?
  3988.     int called = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  3989.     // Which pocket did the ball really fall into?
  3990.     int actual = lastEightBallPocketIndex;
  3991.  
  3992.     // Legal victory only if:
  3993.     //  1) Shooter had already pocketed 7 of their object balls,
  3994.     //  2) They called a pocket,
  3995.     //  3) The 8?ball actually fell into that same pocket,
  3996.     //  4) They did not scratch on the 8?ball.
  3997.     bool legal =
  3998.         (shooter.ballsPocketedCount >= 7) &&
  3999.         (called >= 0) &&
  4000.         (called == actual) &&
  4001.         (!cueBallPocketed);
  4002.  
  4003.     if (legal) {
  4004.         gameOverMessage = shooter.name + L" Wins! "
  4005.             L"(called: " + std::to_wstring(called) +
  4006.             L", actual: " + std::to_wstring(actual) + L")";
  4007.     }
  4008.     else {
  4009.         gameOverMessage = opponent.name + L" Wins! (illegal 8-ball) "
  4010.         // For debugging you can append:
  4011.         + L" (called: " + std::to_wstring(called)
  4012.         + L", actual: " + std::to_wstring(actual) + L")";
  4013.     }
  4014.  
  4015.     currentGameState = GAME_OVER;
  4016. }*/
  4017.  
  4018. // ????????????????????????????????????????????????????????????????
  4019. //  CheckGameOverConditions()
  4020. //     – Called when the 8-ball has fallen.
  4021. //     – Decides who wins and builds the gameOverMessage.
  4022. // ????????????????????????????????????????????????????????????????
  4023. /*void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed)
  4024. {
  4025.     if (!eightBallPocketed) return;                     // safety
  4026.  
  4027.     PlayerInfo& shooter = (currentPlayer == 1) ? player1Info : player2Info;
  4028.     PlayerInfo& opponent = (currentPlayer == 1) ? player2Info : player1Info;
  4029.  
  4030.     int calledPocket = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  4031.     int actualPocket = lastEightBallPocketIndex;
  4032.  
  4033.     bool clearedSeven = (shooter.ballsPocketedCount >= 7);
  4034.     bool noScratch = !cueBallPocketed;
  4035.     bool callMade = (calledPocket >= 0);
  4036.  
  4037.     // helper ? turn “-1” into "None" for readability
  4038.     auto pocketToStr = [](int idx) -> std::wstring
  4039.     {
  4040.         return (idx >= 0) ? std::to_wstring(idx) : L"None";
  4041.     };
  4042.  
  4043.     if (clearedSeven && noScratch && callMade && actualPocket == calledPocket)
  4044.     {
  4045.         // legitimate win
  4046.         gameOverMessage =
  4047.             shooter.name +
  4048.             L" Wins! (Called pocket: " + pocketToStr(calledPocket) +
  4049.             L", Actual pocket: " + pocketToStr(actualPocket) + L")";
  4050.     }
  4051.     else
  4052.     {
  4053.         // wrong pocket, scratch, or early 8-ball
  4054.         gameOverMessage =
  4055.             opponent.name +
  4056.             L" Wins! (Called pocket: " + pocketToStr(calledPocket) +
  4057.             L", Actual pocket: " + pocketToStr(actualPocket) + L")";
  4058.     }
  4059.  
  4060.     currentGameState = GAME_OVER;
  4061. }*/
  4062.  
  4063. /* void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed) {
  4064.     if (!eightBallPocketed) return; // Only when 8-ball actually pocketed
  4065.  
  4066.     PlayerInfo& shooter = (currentPlayer == 1) ? player1Info : player2Info;
  4067.     PlayerInfo& opponent = (currentPlayer == 1) ? player2Info : player1Info;
  4068.     bool      onEightRoll = IsPlayerOnEightBall(currentPlayer);
  4069.     int       calledPocket = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  4070.     int       actualPocket = -1;
  4071.     Ball* bEight = GetBallById(8);
  4072.  
  4073.     // locate which hole the 8-ball went into
  4074.     if (bEight) {
  4075.         for (int i = 0; i < 6; ++i) {
  4076.             if (GetDistanceSq(bEight->x, bEight->y,
  4077.                 pocketPositions[i].x, pocketPositions[i].y)
  4078.                 < POCKET_RADIUS * POCKET_RADIUS * 1.5f) {
  4079.                 actualPocket = i; break;
  4080.             }
  4081.         }
  4082.     }
  4083.  
  4084.     // 1) On break / pre-assignment: re-spot & continue
  4085.     if (player1Info.assignedType == BallType::NONE) {
  4086.         if (bEight) {
  4087.             bEight->isPocketed = false;
  4088.             bEight->x = RACK_POS_X; bEight->y = RACK_POS_Y;
  4089.             bEight->vx = bEight->vy = 0;
  4090.         }
  4091.         if (cueBallPocketed) foulCommitted = true;
  4092.         return;
  4093.     }
  4094.  
  4095.     // 2) Loss if pocketed 8 early
  4096.     if (!onEightRoll) {
  4097.         gameOverMessage = opponent.name + L" Wins! (" + shooter.name + L" pocketed 8-ball early)";
  4098.     }
  4099.     // 3) Loss if scratched
  4100.     else if (cueBallPocketed) {
  4101.         gameOverMessage = opponent.name + L" Wins! (" + shooter.name + L" scratched on 8-ball)";
  4102.     }
  4103.     // 4) Loss if no pocket call
  4104.     else if (calledPocket < 0) {
  4105.         gameOverMessage = opponent.name + L" Wins! (" + shooter.name + L" did not call a pocket)";
  4106.     }
  4107.     // 5) Loss if in wrong pocket
  4108.     else if (actualPocket != calledPocket) {
  4109.         gameOverMessage = opponent.name + L" Wins! (" + shooter.name + L" 8-ball in wrong pocket)";
  4110.     }
  4111.     // 6) Otherwise, valid win
  4112.     else {
  4113.         gameOverMessage = shooter.name + L" Wins!";
  4114.     }
  4115.  
  4116.     currentGameState = GAME_OVER;
  4117. } */
  4118.  
  4119.  
  4120. // Switch the shooter, handle fouls and decide what state we go to next.
  4121. // ────────────────────────────────────────────────────────────────
  4122. //  SwitchTurns – final version (arrow–leak bug fixed)
  4123. // ────────────────────────────────────────────────────────────────
  4124. void SwitchTurns()
  4125. {
  4126.     /* --------------------------------------------------------- */
  4127.     /* 1.  Hand the table over to the other player               */
  4128.     /* --------------------------------------------------------- */
  4129.     currentPlayer = (currentPlayer == 1) ? 2 : 1;
  4130.  
  4131.     /* --------------------------------------------------------- */
  4132.     /* 2.  Generic per–turn resets                               */
  4133.     /* --------------------------------------------------------- */
  4134.     isAiming = false;
  4135.     shotPower = 0.0f;
  4136.     currentlyHoveredPocket = -1;
  4137.  
  4138.     /* --------------------------------------------------------- */
  4139.     /* 3.  Wipe every previous pocket call                       */
  4140.     /*    (the new shooter will choose again if needed)          */
  4141.     /* --------------------------------------------------------- */
  4142.     calledPocketP1 = -1;
  4143.     calledPocketP2 = -1;
  4144.     pocketCallMessage.clear();
  4145.  
  4146.     /* --------------------------------------------------------- */
  4147.     /* 4.  Handle fouls — cue-ball in hand overrides everything  */
  4148.     /* --------------------------------------------------------- */
  4149.     if (foulCommitted)
  4150.     {
  4151.         if (currentPlayer == 1)            // human
  4152.         {
  4153.             currentGameState = BALL_IN_HAND_P1;
  4154.             aiTurnPending = false;
  4155.         }
  4156.         else                               // P2
  4157.         {
  4158.             currentGameState = BALL_IN_HAND_P2;
  4159.             aiTurnPending = isPlayer2AI;   // AI will place cue-ball
  4160.         }
  4161.  
  4162.         foulCommitted = false;
  4163.         return;                            // we're done for this frame
  4164.     }
  4165.  
  4166.     /* --------------------------------------------------------- */
  4167.     /* 5.  Normal flow                                           */
  4168.     /*    Will put us in  ∘ PLAYER?_TURN                         */
  4169.     /*                    ∘ CHOOSING_POCKET_P?                   */
  4170.     /*                    ∘ AI_THINKING  (for CPU)               */
  4171.     /* --------------------------------------------------------- */
  4172.     CheckAndTransitionToPocketChoice(currentPlayer);
  4173. }
  4174.  
  4175.  
  4176. void AIBreakShot() {
  4177.     Ball* cueBall = GetCueBall();
  4178.     if (!cueBall) return;
  4179.  
  4180.     // This function is called when it's AI's turn for the opening break and state is PRE_BREAK_PLACEMENT.
  4181.     // AI will place the cue ball and then plan the shot.
  4182.     if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT) {
  4183.         // Place cue ball in the kitchen randomly
  4184.         /*float kitchenMinX = TABLE_LEFT + BALL_RADIUS; // [cite: 1071, 1072, 1587]
  4185.         float kitchenMaxX = HEADSTRING_X - BALL_RADIUS; // [cite: 1072, 1078, 1588]
  4186.         float kitchenMinY = TABLE_TOP + BALL_RADIUS; // [cite: 1071, 1072, 1588]
  4187.         float kitchenMaxY = TABLE_BOTTOM - BALL_RADIUS; // [cite: 1072, 1073, 1589]*/
  4188.  
  4189.         // --- AI Places Cue Ball for Break ---
  4190. // Decide if placing center or side. For simplicity, let's try placing slightly off-center
  4191. // towards one side for a more angled break, or center for direct apex hit.
  4192. // A common strategy is to hit the second ball of the rack.
  4193.  
  4194.         float placementY = RACK_POS_Y; // Align vertically with the rack center
  4195.         float placementX;
  4196.  
  4197.         // Randomly choose a side or center-ish placement for variation.
  4198.         int placementChoice = rand() % 3; // 0: Left-ish, 1: Center-ish, 2: Right-ish in kitchen
  4199.  
  4200.         if (placementChoice == 0) { // Left-ish
  4201.             placementX = HEADSTRING_X - (TABLE_WIDTH * 0.05f) - (BALL_RADIUS * (1 + (rand() % 3))); // Place slightly to the left within kitchen
  4202.         }
  4203.         else if (placementChoice == 2) { // Right-ish
  4204.             placementX = HEADSTRING_X - (TABLE_WIDTH * 0.05f) + (BALL_RADIUS * (1 + (rand() % 3))); // Place slightly to the right within kitchen
  4205.         }
  4206.         else { // Center-ish
  4207.             placementX = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f; // Roughly center of kitchen
  4208.         }
  4209.         placementX = std::max(TABLE_LEFT + BALL_RADIUS + 1.0f, std::min(placementX, HEADSTRING_X - BALL_RADIUS - 1.0f)); // Clamp within kitchen X
  4210.  
  4211.         bool validPos = false;
  4212.         int attempts = 0;
  4213.         while (!validPos && attempts < 100) {
  4214.             /*cueBall->x = kitchenMinX + static_cast<float>(rand()) / (static_cast<float>(RAND_MAX) / (kitchenMaxX - kitchenMinX)); // [cite: 1589]
  4215.             cueBall->y = kitchenMinY + static_cast<float>(rand()) / (static_cast<float>(RAND_MAX) / (kitchenMaxY - kitchenMinY)); // [cite: 1590]
  4216.             if (IsValidCueBallPosition(cueBall->x, cueBall->y, true)) { // [cite: 1591]
  4217.                 validPos = true; // [cite: 1591]*/
  4218.                 // Try the chosen X, but vary Y slightly to find a clear spot
  4219.             cueBall->x = placementX;
  4220.             cueBall->y = placementY + (static_cast<float>(rand() % 100 - 50) / 100.0f) * BALL_RADIUS * 2.0f; // Vary Y a bit
  4221.             cueBall->y = std::max(TABLE_TOP + BALL_RADIUS + 1.0f, std::min(cueBall->y, TABLE_BOTTOM - BALL_RADIUS - 1.0f)); // Clamp Y
  4222.  
  4223.             if (IsValidCueBallPosition(cueBall->x, cueBall->y, true /* behind headstring */)) {
  4224.                 validPos = true;
  4225.             }
  4226.             attempts++; // [cite: 1592]
  4227.         }
  4228.         if (!validPos) {
  4229.             // Fallback position
  4230.             /*cueBall->x = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f; // [cite: 1071, 1078, 1593]
  4231.             cueBall->y = (TABLE_TOP + TABLE_BOTTOM) * 0.5f; // [cite: 1071, 1073, 1594]
  4232.             if (!IsValidCueBallPosition(cueBall->x, cueBall->y, true)) { // [cite: 1594]
  4233.                 cueBall->x = HEADSTRING_X - BALL_RADIUS * 2; // [cite: 1072, 1078, 1594]
  4234.                 cueBall->y = RACK_POS_Y; // [cite: 1080, 1595]
  4235.             }
  4236.         }
  4237.         cueBall->vx = 0; // [cite: 1595]
  4238.         cueBall->vy = 0; // [cite: 1596]
  4239.  
  4240.         // Plan a break shot: aim at the center of the rack (apex ball)
  4241.         float targetX = RACK_POS_X; // [cite: 1079] Aim for the apex ball X-coordinate
  4242.         float targetY = RACK_POS_Y; // [cite: 1080] Aim for the apex ball Y-coordinate
  4243.  
  4244.         float dx = targetX - cueBall->x; // [cite: 1599]
  4245.         float dy = targetY - cueBall->y; // [cite: 1600]
  4246.         float shotAngle = atan2f(dy, dx); // [cite: 1600]
  4247.         float shotPowerValue = MAX_SHOT_POWER; // [cite: 1076, 1600] Use MAX_SHOT_POWER*/
  4248.  
  4249.             cueBall->x = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.75f; // A default safe spot in kitchen
  4250.             cueBall->y = RACK_POS_Y;
  4251.         }
  4252.         cueBall->vx = 0; cueBall->vy = 0;
  4253.  
  4254.         // --- AI Plans the Break Shot ---
  4255.         float targetX, targetY;
  4256.         // If cue ball is near center of kitchen width, aim for apex.
  4257.         // Otherwise, aim for the second ball on the side the cue ball is on (for a cut break).
  4258.         float kitchenCenterRegion = (HEADSTRING_X - TABLE_LEFT) * 0.3f; // Define a "center" region
  4259.         if (std::abs(cueBall->x - (TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) / 2.0f)) < kitchenCenterRegion / 2.0f) {
  4260.             // Center-ish placement: Aim for the apex ball (ball ID 1 or first ball in rack)
  4261.             targetX = RACK_POS_X; // Apex ball X
  4262.             targetY = RACK_POS_Y; // Apex ball Y
  4263.         }
  4264.         else {
  4265.             // Side placement: Aim to hit the "second" ball of the rack for a wider spread.
  4266.             // This is a simplification. A more robust way is to find the actual second ball.
  4267.             // For now, aim slightly off the apex towards the side the cue ball is on.
  4268.             targetX = RACK_POS_X + BALL_RADIUS * 2.0f * 0.866f; // X of the second row of balls
  4269.             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
  4270.         }
  4271.  
  4272.         float dx = targetX - cueBall->x;
  4273.         float dy = targetY - cueBall->y;
  4274.         float shotAngle = atan2f(dy, dx);
  4275.         float shotPowerValue = MAX_SHOT_POWER * (0.9f + (rand() % 11) / 100.0f); // Slightly vary max power
  4276.  
  4277.         // Store planned shot details for the AI
  4278.         /*aiPlannedShotDetails.angle = shotAngle; // [cite: 1102, 1601]
  4279.         aiPlannedShotDetails.power = shotPowerValue; // [cite: 1102, 1601]
  4280.         aiPlannedShotDetails.spinX = 0.0f; // [cite: 1102, 1601] No spin for a standard power break
  4281.         aiPlannedShotDetails.spinY = 0.0f; // [cite: 1103, 1602]
  4282.         aiPlannedShotDetails.isValid = true; // [cite: 1103, 1602]*/
  4283.  
  4284.         aiPlannedShotDetails.angle = shotAngle;
  4285.         aiPlannedShotDetails.power = shotPowerValue;
  4286.         aiPlannedShotDetails.spinX = 0.0f; // No spin for break usually
  4287.         aiPlannedShotDetails.spinY = 0.0f;
  4288.         aiPlannedShotDetails.isValid = true;
  4289.  
  4290.         // Update global cue parameters for immediate visual feedback if DrawAimingAids uses them
  4291.         /*::cueAngle = aiPlannedShotDetails.angle;      // [cite: 1109, 1603] Update global cueAngle
  4292.         ::shotPower = aiPlannedShotDetails.power;     // [cite: 1109, 1604] Update global shotPower
  4293.         ::cueSpinX = aiPlannedShotDetails.spinX;    // [cite: 1109]
  4294.         ::cueSpinY = aiPlannedShotDetails.spinY;    // [cite: 1110]*/
  4295.  
  4296.         ::cueAngle = aiPlannedShotDetails.angle;
  4297.         ::shotPower = aiPlannedShotDetails.power;
  4298.         ::cueSpinX = aiPlannedShotDetails.spinX;
  4299.         ::cueSpinY = aiPlannedShotDetails.spinY;
  4300.  
  4301.         // Set up for AI display via GameUpdate
  4302.         /*aiIsDisplayingAim = true;                   // [cite: 1104] Enable AI aiming visualization
  4303.         aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES; // [cite: 1105] Set duration for display
  4304.  
  4305.         currentGameState = AI_THINKING; // [cite: 1081] Transition to AI_THINKING state.
  4306.                                         // GameUpdate will handle the aiAimDisplayFramesLeft countdown
  4307.                                         // and then execute the shot using aiPlannedShotDetails.
  4308.                                         // isOpeningBreakShot will be set to false within ApplyShot.
  4309.  
  4310.         // No immediate ApplyShot or sound here; GameUpdate's AI execution logic will handle it.*/
  4311.  
  4312.         aiIsDisplayingAim = true;
  4313.         aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES;
  4314.         currentGameState = AI_THINKING; // State changes to AI_THINKING, GameUpdate will handle shot execution after display
  4315.         aiTurnPending = false;
  4316.  
  4317.         return; // The break shot is now planned and will be executed by GameUpdate
  4318.     }
  4319.  
  4320.     // 2. If not in PRE_BREAK_PLACEMENT (e.g., if this function were called at other times,
  4321.     //    though current game logic only calls it for PRE_BREAK_PLACEMENT)
  4322.     //    This part can be extended if AIBreakShot needs to handle other scenarios.
  4323.     //    For now, the primary logic is above.
  4324. }
  4325.  
  4326. // --- Helper Functions ---
  4327.  
  4328. Ball* GetBallById(int id) {
  4329.     for (size_t i = 0; i < balls.size(); ++i) {
  4330.         if (balls[i].id == id) {
  4331.             return &balls[i];
  4332.         }
  4333.     }
  4334.     return nullptr;
  4335. }
  4336.  
  4337. Ball* GetCueBall() {
  4338.     return GetBallById(0);
  4339. }
  4340.  
  4341. float GetDistance(float x1, float y1, float x2, float y2) {
  4342.     return sqrtf(GetDistanceSq(x1, y1, x2, y2));
  4343. }
  4344.  
  4345. float GetDistanceSq(float x1, float y1, float x2, float y2) {
  4346.     float dx = x2 - x1;
  4347.     float dy = y2 - y1;
  4348.     return dx * dx + dy * dy;
  4349. }
  4350.  
  4351. bool IsValidCueBallPosition(float x, float y, bool checkHeadstring) {
  4352.     // Basic bounds check (inside cushions)
  4353.     float left = TABLE_LEFT + WOODEN_RAIL_THICKNESS + BALL_RADIUS;
  4354.     float right = TABLE_RIGHT - WOODEN_RAIL_THICKNESS - BALL_RADIUS;
  4355.     float top = TABLE_TOP + WOODEN_RAIL_THICKNESS + BALL_RADIUS;
  4356.     float bottom = TABLE_BOTTOM - WOODEN_RAIL_THICKNESS - BALL_RADIUS;
  4357.  
  4358.     if (x < left || x > right || y < top || y > bottom) {
  4359.         return false;
  4360.     }
  4361.  
  4362.     // Check headstring restriction if needed
  4363.     if (checkHeadstring && x >= HEADSTRING_X) {
  4364.         return false;
  4365.     }
  4366.  
  4367.     // Check overlap with other balls
  4368.     for (size_t i = 0; i < balls.size(); ++i) {
  4369.         if (balls[i].id != 0 && !balls[i].isPocketed) { // Don't check against itself or pocketed balls
  4370.             if (GetDistanceSq(x, y, balls[i].x, balls[i].y) < (BALL_RADIUS * 2.0f) * (BALL_RADIUS * 2.0f)) {
  4371.                 return false; // Overlapping another ball
  4372.             }
  4373.         }
  4374.     }
  4375.  
  4376.     return true;
  4377. }
  4378.  
  4379. // --- NEW HELPER FUNCTION IMPLEMENTATIONS ---
  4380.  
  4381. // Checks if a player has pocketed all their balls and is now on the 8-ball.
  4382. bool IsPlayerOnEightBall(int player) {
  4383.     PlayerInfo& playerInfo = (player == 1) ? player1Info : player2Info;
  4384.     if (playerInfo.assignedType != BallType::NONE && playerInfo.assignedType != BallType::EIGHT_BALL && playerInfo.ballsPocketedCount >= 7) {
  4385.         Ball* eightBall = GetBallById(8);
  4386.         return (eightBall && !eightBall->isPocketed);
  4387.     }
  4388.     return false;
  4389. }
  4390.  
  4391. void CheckAndTransitionToPocketChoice(int playerID) {
  4392.     bool needsToCall = IsPlayerOnEightBall(playerID);
  4393.  
  4394.     if (needsToCall) {
  4395.         if (playerID == 1) { // Human Player 1
  4396.             currentGameState = CHOOSING_POCKET_P1;
  4397.             pocketCallMessage = player1Info.name + L": Choose a pocket for the 8-Ball...";
  4398.             if (calledPocketP1 == -1) calledPocketP1 = 2; // Default to bottom-right
  4399.         }
  4400.         else { // Player 2
  4401.             if (isPlayer2AI) {
  4402.                 // FOOLPROOF FIX: AI doesn't choose here. It transitions to a thinking state.
  4403.                 // AIMakeDecision will handle the choice and the pocket call.
  4404.                 currentGameState = AI_THINKING;
  4405.                 aiTurnPending = true; // Signal the main loop to run AIMakeDecision
  4406.             }
  4407.             else { // Human Player 2
  4408.                 currentGameState = CHOOSING_POCKET_P2;
  4409.                 pocketCallMessage = player2Info.name + L": Choose a pocket for the 8-Ball...";
  4410.                 if (calledPocketP2 == -1) calledPocketP2 = 2; // Default to bottom-right
  4411.             }
  4412.         }
  4413.     }
  4414.     else {
  4415.         // Player does not need to call a pocket, proceed to normal turn.
  4416.         pocketCallMessage = L"";
  4417.         currentGameState = (playerID == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  4418.         if (playerID == 2 && isPlayer2AI) {
  4419.             aiTurnPending = true;
  4420.         }
  4421.     }
  4422. }
  4423.  
  4424. //template here
  4425.  
  4426.  
  4427. // --- CPU Ball?in?Hand Placement --------------------------------
  4428. // Moves the cue ball to a legal "ball in hand" position for the AI.
  4429. void AIPlaceCueBall() {
  4430.     Ball* cue = GetCueBall();
  4431.     if (!cue) return;
  4432.  
  4433.     // Simple strategy: place back behind the headstring at the standard break spot
  4434.     cue->x = TABLE_LEFT + TABLE_WIDTH * 0.15f;
  4435.     cue->y = RACK_POS_Y;
  4436.     cue->vx = cue->vy = 0.0f;
  4437. }
  4438.  
  4439. // --- Helper Function for Line Segment Intersection ---
  4440. // Finds intersection point of line segment P1->P2 and line segment P3->P4
  4441. // Returns true if they intersect, false otherwise. Stores intersection point in 'intersection'.
  4442. bool LineSegmentIntersection(D2D1_POINT_2F p1, D2D1_POINT_2F p2, D2D1_POINT_2F p3, D2D1_POINT_2F p4, D2D1_POINT_2F& intersection)
  4443. {
  4444.     float denominator = (p4.y - p3.y) * (p2.x - p1.x) - (p4.x - p3.x) * (p2.y - p1.y);
  4445.  
  4446.     // Check if lines are parallel or collinear
  4447.     if (fabs(denominator) < 1e-6) {
  4448.         return false;
  4449.     }
  4450.  
  4451.     float ua = ((p4.x - p3.x) * (p1.y - p3.y) - (p4.y - p3.y) * (p1.x - p3.x)) / denominator;
  4452.     float ub = ((p2.x - p1.x) * (p1.y - p3.y) - (p2.y - p1.y) * (p1.x - p3.x)) / denominator;
  4453.  
  4454.     // Check if intersection point lies on both segments
  4455.     if (ua >= 0.0f && ua <= 1.0f && ub >= 0.0f && ub <= 1.0f) {
  4456.         intersection.x = p1.x + ua * (p2.x - p1.x);
  4457.         intersection.y = p1.y + ua * (p2.y - p1.y);
  4458.         return true;
  4459.     }
  4460.  
  4461.     return false;
  4462. }
  4463.  
  4464. // --- INSERT NEW HELPER FUNCTION HERE ---
  4465. // Calculates the squared distance from point P to the line segment AB.
  4466. float PointToLineSegmentDistanceSq(D2D1_POINT_2F p, D2D1_POINT_2F a, D2D1_POINT_2F b) {
  4467.     float l2 = GetDistanceSq(a.x, a.y, b.x, b.y);
  4468.     if (l2 == 0.0f) return GetDistanceSq(p.x, p.y, a.x, a.y); // Segment is a point
  4469.     // Consider P projecting onto the line AB infinite line
  4470.     // t = [(P-A) . (B-A)] / |B-A|^2
  4471.     float t = ((p.x - a.x) * (b.x - a.x) + (p.y - a.y) * (b.y - a.y)) / l2;
  4472.     t = std::max(0.0f, std::min(1.0f, t)); // Clamp t to the segment [0, 1]
  4473.     // Projection falls on the segment
  4474.     D2D1_POINT_2F projection = D2D1::Point2F(a.x + t * (b.x - a.x), a.y + t * (b.y - a.y));
  4475.     return GetDistanceSq(p.x, p.y, projection.x, projection.y);
  4476. }
  4477. // --- End New Helper ---
  4478.  
  4479. // --- NEW AI Implementation Functions ---
  4480.  
  4481. // --- BEGIN: ENHANCED AI LOGIC ---
  4482.  
  4483. // Helper function to evaluate the quality of the table layout from the cue ball's perspective.
  4484. // A higher score means a better "leave" with more options for the next shot.
  4485. float EvaluateTableState(int player, Ball* cueBall) {
  4486.     if (!cueBall) return 0.0f;
  4487.     float score = 0.0f;
  4488.     const BallType targetType = (player == 1) ? player1Info.assignedType : player2Info.assignedType;
  4489.  
  4490.     for (Ball& b : balls) {
  4491.         // Only consider own balls that are on the table
  4492.         if (b.isPocketed || b.id == 0 || b.type != targetType) continue;
  4493.  
  4494.         // Check for clear shots to any pocket
  4495.         for (int p = 0; p < 6; ++p) {
  4496.             D2D1_POINT_2F ghostPos = CalculateGhostBallPos(&b, p);
  4497.             if (IsPathClear(D2D1::Point2F(cueBall->x, cueBall->y), ghostPos, cueBall->id, b.id)) {
  4498.                 // Bonus for having any open, pottable shot
  4499.                 score += 50.0f;
  4500.             }
  4501.         }
  4502.     }
  4503.     return score;
  4504. }
  4505.  
  4506. // Enhanced power calculation for more realistic and impactful shots.
  4507. float CalculateShotPower(float cueToGhostDist, float targetToPocketDist)
  4508. {
  4509.     constexpr float TABLE_DIAG = 900.0f;
  4510.  
  4511.     // Base power on a combination of cue travel and object ball travel.
  4512.     float powerRatio = std::clamp(cueToGhostDist / (TABLE_WIDTH * 0.7f), 0.0f, 1.0f);
  4513.     // Give more weight to the object ball's travel distance.
  4514.     powerRatio += std::clamp(targetToPocketDist / TABLE_DIAG, 0.0f, 1.0f) * 0.8f;
  4515.     powerRatio = std::clamp(powerRatio, 0.0f, 1.0f);
  4516.  
  4517.     // Use a more aggressive cubic power curve. This keeps power low for taps but ramps up very fast.
  4518.     powerRatio = powerRatio * powerRatio * powerRatio;
  4519.  
  4520.     // Heavily bias towards high power. The AI will start shots at 50% power and go up.
  4521.     const float MIN_POWER = MAX_SHOT_POWER * 0.50f;
  4522.     float power = MIN_POWER + powerRatio * (MAX_SHOT_POWER - MIN_POWER);
  4523.  
  4524.     // For very long shots, just use full power to ensure the ball gets there and for break-out potential.
  4525.     if (cueToGhostDist + targetToPocketDist > TABLE_DIAG * 0.85f) {
  4526.         power = MAX_SHOT_POWER;
  4527.     }
  4528.  
  4529.     return std::clamp(power, 0.2f, MAX_SHOT_POWER);
  4530. }
  4531.  
  4532. // Evaluates a potential shot, calculating its difficulty and the quality of the resulting cue ball position.
  4533. AIShotInfo EvaluateShot(Ball* targetBall, int pocketIndex, bool isBank) {
  4534.     AIShotInfo shotInfo;
  4535.     shotInfo.targetBall = targetBall;
  4536.     shotInfo.pocketIndex = pocketIndex;
  4537.     shotInfo.isBankShot = isBank;
  4538.     shotInfo.involves8Ball = (targetBall && targetBall->id == 8);
  4539.  
  4540.     Ball* cue = GetCueBall();
  4541.     if (!cue || !targetBall) return shotInfo;
  4542.  
  4543.     D2D1_POINT_2F pocketPos = pocketPositions[pocketIndex];
  4544.     D2D1_POINT_2F targetPos = D2D1::Point2F(targetBall->x, targetBall->y);
  4545.     D2D1_POINT_2F ghostBallPos = CalculateGhostBallPos(targetBall, pocketIndex);
  4546.  
  4547.     // The path from cue to the ghost ball position must be clear.
  4548.     if (!IsPathClear(D2D1::Point2F(cue->x, cue->y), ghostBallPos, cue->id, targetBall->id)) {
  4549.         return shotInfo; // Path is blocked, invalid shot.
  4550.     }
  4551.  
  4552.     // For direct shots, the path from the target ball to the pocket must also be clear.
  4553.     if (!isBank && !IsPathClear(targetPos, pocketPos, targetBall->id, -1)) {
  4554.         return shotInfo;
  4555.     }
  4556.  
  4557.     float dx = ghostBallPos.x - cue->x;
  4558.     float dy = ghostBallPos.y - cue->y;
  4559.     shotInfo.angle = atan2f(dy, dx);
  4560.  
  4561.     float cueToGhostDist = GetDistance(cue->x, cue->y, ghostBallPos.x, ghostBallPos.y);
  4562.     float targetToPocketDist = GetDistance(targetBall->x, targetBall->y, pocketPos.x, pocketPos.y);
  4563.  
  4564.     shotInfo.power = CalculateShotPower(cueToGhostDist, targetToPocketDist); // Set a base power
  4565.     shotInfo.score = 1000.0f - (cueToGhostDist + targetToPocketDist * 1.5f); // Base score on shot difficulty.
  4566.     if (isBank) shotInfo.score -= 250.0f; // Bank shots are harder, so they have a score penalty.
  4567.  
  4568.  
  4569.     // --- Positional Play & English (Spin) Evaluation ---
  4570.     float bestLeaveScore = -1.0f;
  4571.     // Try different spins: -1 (draw/backspin), 0 (stun), 1 (follow/topspin)
  4572.     for (int spin_type = -1; spin_type <= 1; ++spin_type) {
  4573.         float spinY = spin_type * 0.7f; // Apply vertical spin.
  4574.  
  4575.         // Adjust power based on spin type. Draw shots need more power.
  4576.         float powerMultiplier = 1.0f;
  4577.         if (spin_type == -1) powerMultiplier = 1.2f;  // 20% more power for draw
  4578.         else if (spin_type == 1) powerMultiplier = 1.05f; // 5% more power for follow
  4579.  
  4580.         float adjustedPower = std::clamp(shotInfo.power * powerMultiplier, 0.2f, MAX_SHOT_POWER);
  4581.  
  4582.         // Predict where the cue ball will end up after the shot.
  4583.         D2D1_POINT_2F cueEndPos;
  4584.         float cueTravelDist = targetToPocketDist * 0.5f + adjustedPower * 5.0f;
  4585.  
  4586.         if (spin_type == 1) { // Follow (topspin)
  4587.             cueEndPos.x = targetPos.x + cosf(shotInfo.angle) * cueTravelDist * 0.6f;
  4588.             cueEndPos.y = targetPos.y + sinf(shotInfo.angle) * cueTravelDist * 0.6f;
  4589.         }
  4590.         else if (spin_type == -1) { // Draw (backspin)
  4591.             cueEndPos.x = ghostBallPos.x - cosf(shotInfo.angle) * cueTravelDist * 0.4f;
  4592.             cueEndPos.y = ghostBallPos.y - sinf(shotInfo.angle) * cueTravelDist * 0.4f;
  4593.         }
  4594.         else { // Stun (no vertical spin) - cue ball deflects
  4595.             float perpAngle = shotInfo.angle + PI / 2.0f;
  4596.             cueEndPos.x = ghostBallPos.x + cosf(perpAngle) * cueTravelDist * 0.3f;
  4597.             cueEndPos.y = ghostBallPos.y + sinf(perpAngle) * cueTravelDist * 0.3f;
  4598.         }
  4599.  
  4600.         // Create a temporary cue ball at the predicted position to evaluate the leave.
  4601.         Ball tempCue = *cue;
  4602.         tempCue.x = cueEndPos.x;
  4603.         tempCue.y = cueEndPos.y;
  4604.         float leaveScore = EvaluateTableState(2, &tempCue);
  4605.  
  4606.         // Penalize scratches heavily.
  4607.         for (int p = 0; p < 6; ++p) {
  4608.             float physicalPocketRadius = ((p == 1 || p == 4) ? MIDDLE_HOLE_VISUAL_RADIUS : CORNER_HOLE_VISUAL_RADIUS) * 1.05f;
  4609.             if (GetDistanceSq(cueEndPos.x, cueEndPos.y, pocketPositions[p].x, pocketPositions[p].y) < physicalPocketRadius * physicalPocketRadius * 1.5f) {
  4610.                 leaveScore -= 5000.0f; // Massive penalty for a predicted scratch.
  4611.                 break;
  4612.             }
  4613.         }
  4614.  
  4615.         // If this spin results in a better position, store it.
  4616.         if (leaveScore > bestLeaveScore) {
  4617.             bestLeaveScore = leaveScore;
  4618.             shotInfo.spinY = spinY;
  4619.             shotInfo.spinX = 0; // Focusing on top/back spin for positional play.
  4620.             shotInfo.predictedCueEndPos = cueEndPos;
  4621.             shotInfo.power = adjustedPower; // IMPORTANT: Update the shot's power to the adjusted value for this spin
  4622.         }
  4623.     }
  4624.  
  4625.     shotInfo.score += bestLeaveScore * 0.5f; // Add positional score to the shot's total score.
  4626.     shotInfo.possible = true;
  4627.     return shotInfo;
  4628. }
  4629.  
  4630. // High-level planner that decides which shot to take.
  4631. AIShotInfo AIFindBestShot() {
  4632.     AIShotInfo bestShot;
  4633.     bestShot.possible = false;
  4634.  
  4635.     Ball* cue = GetCueBall();
  4636.     if (!cue) return bestShot;
  4637.  
  4638.     const bool on8 = IsPlayerOnEightBall(2);
  4639.     const BallType wantType = player2Info.assignedType;
  4640.     std::vector<AIShotInfo> possibleShots;
  4641.  
  4642.     // 1. Evaluate all possible direct shots on legal targets.
  4643.     for (Ball& b : balls) {
  4644.         if (b.isPocketed || b.id == 0) continue;
  4645.  
  4646.         bool isLegalTarget = on8 ? (b.id == 8) : (wantType == BallType::NONE || b.type == wantType);
  4647.         if (!isLegalTarget) continue;
  4648.  
  4649.         for (int p = 0; p < 6; ++p) {
  4650.             AIShotInfo cand = EvaluateShot(&b, p, false); // false = not a bank shot
  4651.             if (cand.possible) {
  4652.                 possibleShots.push_back(cand);
  4653.             }
  4654.         }
  4655.     }
  4656.  
  4657.     // TODO: Add evaluation for bank shots here if desired.
  4658.  
  4659.     // 2. Find the best shot from the list of possibilities.
  4660.     if (!possibleShots.empty()) {
  4661.         bestShot = possibleShots[0];
  4662.         for (size_t i = 1; i < possibleShots.size(); ++i) {
  4663.             if (possibleShots[i].score > bestShot.score) {
  4664.                 bestShot = possibleShots[i];
  4665.             }
  4666.         }
  4667.     }
  4668.     else {
  4669.         // 3. If no makeable shots are found, play a defensive "safety" shot.
  4670.         // This involves hitting a legal ball softly to a safe location.
  4671.         bestShot.possible = true;
  4672.         bestShot.angle = static_cast<float>(rand()) / RAND_MAX * 2.0f * PI;
  4673.         bestShot.power = MAX_SHOT_POWER * 0.25f; // A soft safety hit.
  4674.         bestShot.spinX = bestShot.spinY = 0.0f;
  4675.         bestShot.targetBall = nullptr;
  4676.         bestShot.score = -99999.0f; // Safety is a last resort.
  4677.         bestShot.pocketIndex = -1;
  4678.     }
  4679.  
  4680.     return bestShot;
  4681. }
  4682.  
  4683. // The top-level function that orchestrates the AI's turn.
  4684. void AIMakeDecision() {
  4685.     aiPlannedShotDetails.isValid = false;
  4686.     Ball* cueBall = GetCueBall();
  4687.     if (!cueBall || !isPlayer2AI || currentPlayer != 2) return;
  4688.  
  4689.     AIShotInfo bestShot = AIFindBestShot();
  4690.  
  4691.     if (bestShot.possible) {
  4692.         // If the best shot involves the 8-ball, the AI must "call" the pocket.
  4693.         if (bestShot.involves8Ball) {
  4694.             calledPocketP2 = bestShot.pocketIndex;
  4695.         }
  4696.         else {
  4697.             calledPocketP2 = -1;
  4698.         }
  4699.  
  4700.         // Load the chosen shot parameters into the game state.
  4701.         aiPlannedShotDetails.angle = bestShot.angle;
  4702.         aiPlannedShotDetails.power = bestShot.power;
  4703.         aiPlannedShotDetails.spinX = bestShot.spinX;
  4704.         aiPlannedShotDetails.spinY = bestShot.spinY;
  4705.         aiPlannedShotDetails.isValid = true;
  4706.     }
  4707.     else {
  4708.         // This case should be rare now, but as a fallback, switch turns.
  4709.         aiPlannedShotDetails.isValid = false;
  4710.     }
  4711.  
  4712.     if (aiPlannedShotDetails.isValid) {
  4713.         // Set the global aiming variables to visualize the AI's planned shot.
  4714.         cueAngle = aiPlannedShotDetails.angle;
  4715.         shotPower = aiPlannedShotDetails.power;
  4716.         aiIsDisplayingAim = true;
  4717.         aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES;
  4718.     }
  4719.     else {
  4720.         // If no valid shot could be found at all, concede the turn.
  4721.         SwitchTurns();
  4722.     }
  4723. }
  4724.  
  4725. // --- END: ENHANCED AI LOGIC ---
  4726.  
  4727.  
  4728.  
  4729. //  Estimate the power that will carry the cue-ball to the ghost position
  4730. //  *and* push the object-ball the remaining distance to the pocket.
  4731. //
  4732. //  • cueToGhostDist    – pixels from cue to ghost-ball centre
  4733. //  • targetToPocketDist– pixels from object-ball to chosen pocket
  4734. //
  4735. //  The function is fully deterministic (good for AI search) yet produces
  4736. //  human-looking power levels.
  4737. //
  4738.  
  4739.  
  4740. // ------------------------------------------------------------------
  4741. //  Return the ghost-ball centre needed for the target ball to roll
  4742. //  straight into the chosen pocket.
  4743. // ------------------------------------------------------------------
  4744. D2D1_POINT_2F CalculateGhostBallPos(Ball* targetBall, int pocketIndex)
  4745. {
  4746.     if (!targetBall) return D2D1::Point2F(0, 0);
  4747.  
  4748.     D2D1_POINT_2F P = pocketPositions[pocketIndex];
  4749.  
  4750.     float vx = P.x - targetBall->x;
  4751.     float vy = P.y - targetBall->y;
  4752.     float L = sqrtf(vx * vx + vy * vy);
  4753.     if (L < 1.0f) L = 1.0f;                // safety
  4754.  
  4755.     vx /= L;   vy /= L;
  4756.  
  4757.     return D2D1::Point2F(
  4758.         targetBall->x - vx * (BALL_RADIUS * 2.0f),
  4759.         targetBall->y - vy * (BALL_RADIUS * 2.0f));
  4760. }
  4761.  
  4762. // Calculate the position the cue ball needs to hit for the target ball to go towards the pocket
  4763. // ────────────────────────────────────────────────────────────────
  4764. //   2.  Shot evaluation & search
  4765. // ────────────────────────────────────────────────────────────────
  4766.  
  4767. //  Calculate ghost-ball position so that cue hits target towards pocket
  4768. static inline D2D1_POINT_2F GhostPos(const Ball* tgt, int pocketIdx)
  4769. {
  4770.     D2D1_POINT_2F P = pocketPositions[pocketIdx];
  4771.     float vx = P.x - tgt->x;
  4772.     float vy = P.y - tgt->y;
  4773.     float L = sqrtf(vx * vx + vy * vy);
  4774.     vx /= L;  vy /= L;
  4775.     return D2D1::Point2F(tgt->x - vx * (BALL_RADIUS * 2.0f),
  4776.         tgt->y - vy * (BALL_RADIUS * 2.0f));
  4777. }
  4778.  
  4779. //  Heuristic: shorter + straighter + proper group = higher score
  4780. static inline float ScoreShot(float cue2Ghost,
  4781.     float tgt2Pocket,
  4782.     bool  correctGroup,
  4783.     bool  involves8)
  4784. {
  4785.     float base = 2000.0f - (cue2Ghost + tgt2Pocket);   // prefer close shots
  4786.     if (!correctGroup)  base -= 400.0f;                  // penalty
  4787.     if (involves8)      base += 150.0f;                  // a bit more desirable
  4788.     return base;
  4789. }
  4790.  
  4791. // Checks if line segment is clear of obstructing balls
  4792. // ────────────────────────────────────────────────────────────────
  4793. //   1.  Low-level helpers – IsPathClear & FindFirstHitBall
  4794. // ────────────────────────────────────────────────────────────────
  4795.  
  4796. //  Test if the capsule [ start … end ] (radius = BALL_RADIUS)
  4797. //  intersects any ball except the ids we want to ignore.
  4798. bool IsPathClear(D2D1_POINT_2F start,
  4799.     D2D1_POINT_2F end,
  4800.     int ignoredBallId1,
  4801.     int ignoredBallId2)
  4802. {
  4803.     float dx = end.x - start.x;
  4804.     float dy = end.y - start.y;
  4805.     float lenSq = dx * dx + dy * dy;
  4806.     if (lenSq < 1e-3f) return true;             // degenerate → treat as clear
  4807.  
  4808.     for (const Ball& b : balls)
  4809.     {
  4810.         if (b.isPocketed)      continue;
  4811.         if (b.id == ignoredBallId1 ||
  4812.             b.id == ignoredBallId2)             continue;
  4813.  
  4814.         // project ball centre onto the segment
  4815.         float t = ((b.x - start.x) * dx + (b.y - start.y) * dy) / lenSq;
  4816.         t = std::clamp(t, 0.0f, 1.0f);
  4817.  
  4818.         float cx = start.x + t * dx;
  4819.         float cy = start.y + t * dy;
  4820.  
  4821.         if (GetDistanceSq(b.x, b.y, cx, cy) < (BALL_RADIUS * BALL_RADIUS))
  4822.             return false;                       // blocked
  4823.     }
  4824.     return true;
  4825. }
  4826.  
  4827. //  Cast an (infinite) ray and return the first non-pocketed ball hit.
  4828. //  `hitDistSq` is distance² from the start point to the collision point.
  4829. Ball* FindFirstHitBall(D2D1_POINT_2F start,
  4830.     float        angle,
  4831.     float& hitDistSq)
  4832. {
  4833.     Ball* hitBall = nullptr;
  4834.     float  bestSq = std::numeric_limits<float>::max();
  4835.     float  cosA = cosf(angle);
  4836.     float  sinA = sinf(angle);
  4837.  
  4838.     for (Ball& b : balls)
  4839.     {
  4840.         if (b.id == 0 || b.isPocketed) continue;         // ignore cue & sunk balls
  4841.  
  4842.         float relX = b.x - start.x;
  4843.         float relY = b.y - start.y;
  4844.         float proj = relX * cosA + relY * sinA;          // distance along the ray
  4845.  
  4846.         if (proj <= 0) continue;                         // behind cue
  4847.  
  4848.         // closest approach of the ray to the sphere centre
  4849.         float closestX = start.x + proj * cosA;
  4850.         float closestY = start.y + proj * sinA;
  4851.         float dSq = GetDistanceSq(b.x, b.y, closestX, closestY);
  4852.  
  4853.         if (dSq <= BALL_RADIUS * BALL_RADIUS)            // intersection
  4854.         {
  4855.             float back = sqrtf(BALL_RADIUS * BALL_RADIUS - dSq);
  4856.             float collDist = proj - back;                // front surface
  4857.             float collSq = collDist * collDist;
  4858.             if (collSq < bestSq)
  4859.             {
  4860.                 bestSq = collSq;
  4861.                 hitBall = &b;
  4862.             }
  4863.         }
  4864.     }
  4865.     hitDistSq = bestSq;
  4866.     return hitBall;
  4867. }
  4868.  
  4869. // Basic check for reasonable AI aim angles (optional)
  4870. bool IsValidAIAimAngle(float angle) {
  4871.     // Placeholder - could check for NaN or infinity if calculations go wrong
  4872.     return isfinite(angle);
  4873. }
  4874.  
  4875. //midi func = start
  4876. void PlayMidiInBackground(HWND hwnd, const TCHAR* midiPath) {
  4877.     while (isMusicPlaying) {
  4878.         MCI_OPEN_PARMS mciOpen = { 0 };
  4879.         mciOpen.lpstrDeviceType = TEXT("sequencer");
  4880.         mciOpen.lpstrElementName = midiPath;
  4881.  
  4882.         if (mciSendCommand(0, MCI_OPEN, MCI_OPEN_TYPE | MCI_OPEN_ELEMENT, (DWORD_PTR)&mciOpen) == 0) {
  4883.             midiDeviceID = mciOpen.wDeviceID;
  4884.  
  4885.             MCI_PLAY_PARMS mciPlay = { 0 };
  4886.             mciSendCommand(midiDeviceID, MCI_PLAY, 0, (DWORD_PTR)&mciPlay);
  4887.  
  4888.             // Wait for playback to complete
  4889.             MCI_STATUS_PARMS mciStatus = { 0 };
  4890.             mciStatus.dwItem = MCI_STATUS_MODE;
  4891.  
  4892.             do {
  4893.                 mciSendCommand(midiDeviceID, MCI_STATUS, MCI_STATUS_ITEM, (DWORD_PTR)&mciStatus);
  4894.                 Sleep(100); // adjust as needed
  4895.             } while (mciStatus.dwReturn == MCI_MODE_PLAY && isMusicPlaying);
  4896.  
  4897.             mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
  4898.             midiDeviceID = 0;
  4899.         }
  4900.     }
  4901. }
  4902.  
  4903. void StartMidi(HWND hwnd, const TCHAR* midiPath) {
  4904.     if (isMusicPlaying) {
  4905.         StopMidi();
  4906.     }
  4907.     isMusicPlaying = true;
  4908.     musicThread = std::thread(PlayMidiInBackground, hwnd, midiPath);
  4909. }
  4910.  
  4911. void StopMidi() {
  4912.     if (isMusicPlaying) {
  4913.         isMusicPlaying = false;
  4914.         if (musicThread.joinable()) musicThread.join();
  4915.         if (midiDeviceID != 0) {
  4916.             mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
  4917.             midiDeviceID = 0;
  4918.         }
  4919.     }
  4920. }
  4921.  
  4922. /*void PlayGameMusic(HWND hwnd) {
  4923.     // Stop any existing playback
  4924.     if (isMusicPlaying) {
  4925.         isMusicPlaying = false;
  4926.         if (musicThread.joinable()) {
  4927.             musicThread.join();
  4928.         }
  4929.         if (midiDeviceID != 0) {
  4930.             mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
  4931.             midiDeviceID = 0;
  4932.         }
  4933.     }
  4934.  
  4935.     // Get the path of the executable
  4936.     TCHAR exePath[MAX_PATH];
  4937.     GetModuleFileName(NULL, exePath, MAX_PATH);
  4938.  
  4939.     // Extract the directory path
  4940.     TCHAR* lastBackslash = _tcsrchr(exePath, '\\');
  4941.     if (lastBackslash != NULL) {
  4942.         *(lastBackslash + 1) = '\0';
  4943.     }
  4944.  
  4945.     // Construct the full path to the MIDI file
  4946.     static TCHAR midiPath[MAX_PATH];
  4947.     _tcscpy_s(midiPath, MAX_PATH, exePath);
  4948.     _tcscat_s(midiPath, MAX_PATH, TEXT("BSQ.MID"));
  4949.  
  4950.     // Start the background playback
  4951.     isMusicPlaying = true;
  4952.     musicThread = std::thread(PlayMidiInBackground, hwnd, midiPath);
  4953. }*/
  4954. //midi func = end
  4955.  
  4956. // --- Drawing Functions ---
  4957.  
  4958. void OnPaint() {
  4959.     HRESULT hr = CreateDeviceResources(); // Ensure resources are valid
  4960.  
  4961.     if (SUCCEEDED(hr)) {
  4962.         pRenderTarget->BeginDraw();
  4963.         DrawScene(pRenderTarget); // Pass render target
  4964.         hr = pRenderTarget->EndDraw();
  4965.  
  4966.         if (hr == D2DERR_RECREATE_TARGET) {
  4967.             DiscardDeviceResources();
  4968.             // Optionally request another paint message: InvalidateRect(hwndMain, NULL, FALSE);
  4969.             // But the timer loop will trigger redraw anyway.
  4970.         }
  4971.     }
  4972.     // If CreateDeviceResources failed, EndDraw might not be called.
  4973.     // Consider handling this more robustly if needed.
  4974. }
  4975.  
  4976. void DrawScene(ID2D1RenderTarget* pRT) {
  4977.     if (!pRT) return;
  4978.  
  4979.     //pRT->Clear(D2D1::ColorF(D2D1::ColorF::LightGray)); // Background color
  4980.     // Set background color to #ffffcd (RGB: 255, 255, 205)
  4981.     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)
  4982.     //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)
  4983.  
  4984.     DrawTable(pRT, pFactory);
  4985.     DrawPocketSelectionIndicator(pRT); // Draw arrow over selected/called pocket
  4986.     DrawBalls(pRT);
  4987.     // Draw the cue stick right before/after drawing balls:
  4988.     DrawCueStick(pRT);
  4989.     DrawAimingAids(pRT); // Includes cue stick if aiming
  4990.     DrawUI(pRT);
  4991.     DrawPowerMeter(pRT);
  4992.     DrawSpinIndicator(pRT);
  4993.     DrawPocketedBallsIndicator(pRT);
  4994.     DrawBallInHandIndicator(pRT); // Draw cue ball ghost if placing
  4995.  
  4996.      // Draw Game Over Message
  4997.     if (currentGameState == GAME_OVER && pTextFormat) {
  4998.         ID2D1SolidColorBrush* pBrush = nullptr;
  4999.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pBrush);
  5000.         if (pBrush) {
  5001.             D2D1_RECT_F layoutRect = D2D1::RectF(TABLE_LEFT, TABLE_TOP + TABLE_HEIGHT / 2 - 30, TABLE_RIGHT, TABLE_TOP + TABLE_HEIGHT / 2 + 30);
  5002.             pRT->DrawText(
  5003.                 gameOverMessage.c_str(),
  5004.                 (UINT32)gameOverMessage.length(),
  5005.                 pTextFormat, // Use large format maybe?
  5006.                 &layoutRect,
  5007.                 pBrush
  5008.             );
  5009.             SafeRelease(&pBrush);
  5010.         }
  5011.     }
  5012.  
  5013. }
  5014.  
  5015. void DrawTable(ID2D1RenderTarget* pRT, ID2D1Factory* pFactory) {
  5016.     if (!pRT || !pFactory) return;
  5017.  
  5018.     // --- Layer 0: Black Pocket Backdrops (Optional, but makes pockets look deeper) ---
  5019.     ID2D1SolidColorBrush* pPocketBackdropBrush = nullptr;
  5020.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pPocketBackdropBrush);
  5021.     if (pPocketBackdropBrush) {
  5022.         for (int i = 0; i < 6; ++i) {
  5023.             float currentVisualRadius = (i == 1 || i == 4) ? MIDDLE_HOLE_VISUAL_RADIUS : CORNER_HOLE_VISUAL_RADIUS;
  5024.             D2D1_ELLIPSE backdrop = D2D1::Ellipse(pocketPositions[i], currentVisualRadius + 5.0f, currentVisualRadius + 5.0f);
  5025.             pRT->FillEllipse(&backdrop, pPocketBackdropBrush);
  5026.         }
  5027.         SafeRelease(&pPocketBackdropBrush);
  5028.     }
  5029.  
  5030.     // --- Layer 1: Base Felt Surface ---
  5031.     ID2D1SolidColorBrush* pFeltBrush = nullptr;
  5032.     pRT->CreateSolidColorBrush(TABLE_COLOR, &pFeltBrush);
  5033.     if (!pFeltBrush) return;
  5034.     D2D1_RECT_F tableRect = D2D1::RectF(TABLE_LEFT, TABLE_TOP, TABLE_RIGHT, TABLE_BOTTOM);
  5035.     pRT->FillRectangle(&tableRect, pFeltBrush);
  5036.     SafeRelease(&pFeltBrush); // Release now, it's not needed for the rest of the function
  5037.  
  5038.     // --- Layer 2: Center Spotlight Effect ---
  5039.     // This is your original, preserved spotlight code.
  5040.     {
  5041.         ID2D1RadialGradientBrush* pSpot = nullptr;
  5042.         ID2D1GradientStopCollection* pStops = nullptr;
  5043.         D2D1_COLOR_F centreClr = D2D1::ColorF(
  5044.             std::min(1.f, TABLE_COLOR.r * 1.60f),
  5045.             std::min(1.f, TABLE_COLOR.g * 1.60f),
  5046.             std::min(1.f, TABLE_COLOR.b * 1.60f));
  5047.         const D2D1_GRADIENT_STOP gs[3] =
  5048.         {
  5049.             { 0.0f, D2D1::ColorF(centreClr.r, centreClr.g, centreClr.b, 0.95f) },
  5050.             { 0.6f, D2D1::ColorF(TABLE_COLOR.r, TABLE_COLOR.g, TABLE_COLOR.b, 0.55f) },
  5051.             { 1.0f, D2D1::ColorF(TABLE_COLOR.r, TABLE_COLOR.g, TABLE_COLOR.b, 0.0f) }
  5052.         };
  5053.         pRT->CreateGradientStopCollection(gs, 3, &pStops);
  5054.         if (pStops)
  5055.         {
  5056.             D2D1_RECT_F rc = tableRect;
  5057.             const float PAD = 18.0f;
  5058.             rc.left += PAD;  rc.top += PAD;
  5059.             rc.right -= PAD;  rc.bottom -= PAD;
  5060.             D2D1_POINT_2F centre = D2D1::Point2F(
  5061.                 (rc.left + rc.right) / 2.0f,
  5062.                 (rc.top + rc.bottom) / 2.0f);
  5063.             float rx = (rc.right - rc.left) * 0.55f;
  5064.             float ry = (rc.bottom - rc.top) * 0.55f;
  5065.             D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  5066.                 D2D1::RadialGradientBrushProperties(
  5067.                     centre,
  5068.                     D2D1::Point2F(0, 0),
  5069.                     rx, ry);
  5070.             pRT->CreateRadialGradientBrush(props, pStops, &pSpot);
  5071.             pStops->Release();
  5072.         }
  5073.         if (pSpot)
  5074.         {
  5075.             const float RADIUS = 20.0f;
  5076.             D2D1_ROUNDED_RECT spotlightRR =
  5077.                 D2D1::RoundedRect(tableRect, RADIUS, RADIUS);
  5078.             pRT->FillRoundedRectangle(&spotlightRR, pSpot);
  5079.             pSpot->Release();
  5080.         }
  5081.     }
  5082.  
  5083.     // --- Layer 3: Grainy Felt Texture ---
  5084.     // This is your original, preserved grain code.
  5085.     ID2D1SolidColorBrush* pGrainBrush = nullptr;
  5086.     pRT->CreateSolidColorBrush(TABLE_COLOR, &pGrainBrush);
  5087.     if (pGrainBrush)
  5088.     {
  5089.         const int NUM_GRAINS = 20000;
  5090.         for (int i = 0; i < NUM_GRAINS; ++i)
  5091.         {
  5092.             float x = TABLE_LEFT + (rand() % (int)TABLE_WIDTH);
  5093.             float y = TABLE_TOP + (rand() % (int)TABLE_HEIGHT);
  5094.             float colorFactor = 0.85f + (rand() % 31) / 100.0f;
  5095.             D2D1_COLOR_F grainColor = D2D1::ColorF(
  5096.                 std::clamp(TABLE_COLOR.r * colorFactor, 0.0f, 1.0f),
  5097.                 std::clamp(TABLE_COLOR.g * colorFactor, 0.0f, 1.0f),
  5098.                 std::clamp(TABLE_COLOR.b * colorFactor, 0.0f, 1.0f),
  5099.                 0.75f
  5100.             );
  5101.             pGrainBrush->SetColor(grainColor);
  5102.             pRT->FillRectangle(D2D1::RectF(x, y, x + 1.0f, y + 1.0f), pGrainBrush);
  5103.         }
  5104.         SafeRelease(&pGrainBrush);
  5105.     }
  5106.  
  5107.     // --- Layer 4: Black Pocket Holes ---
  5108.     // These are drawn on top of the felt but will be underneath the cushions.
  5109.     ID2D1SolidColorBrush* pPocketBrush = nullptr;
  5110.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pPocketBrush);
  5111.     if (pPocketBrush) {
  5112.         for (int i = 0; i < 6; ++i) {
  5113.             float radius = (i == 1 || i == 4) ? MIDDLE_HOLE_VISUAL_RADIUS : CORNER_HOLE_VISUAL_RADIUS;
  5114.             pRT->FillEllipse(D2D1::Ellipse(pocketPositions[i], radius, radius), pPocketBrush);
  5115.         }
  5116.         SafeRelease(&pPocketBrush);
  5117.     }
  5118.  
  5119.     // --- FOOLPROOF FIX: Draw Unified Rails and V-Cut Inner Rim ---
  5120. // This new block draws both the outer wooden rails and the inner gradient rim
  5121. // with the correct 45-degree V-Cut chamfers at the pockets.
  5122.  
  5123. // Part 1: Draw the Outer Wooden Rails (Solid Rectangles)
  5124.     ID2D1SolidColorBrush* pRailBrush = nullptr;
  5125.     pRT->CreateSolidColorBrush(CUSHION_COLOR, &pRailBrush); // Using your existing cushion color
  5126.     if (pRailBrush) {
  5127.         // Top Rails (split by middle pocket)
  5128.         pRT->FillRectangle(D2D1::RectF(TABLE_LEFT + CORNER_HOLE_VISUAL_RADIUS, TABLE_TOP - WOODEN_RAIL_THICKNESS, TABLE_LEFT + TABLE_WIDTH / 2.f - MIDDLE_HOLE_VISUAL_RADIUS, TABLE_TOP), pRailBrush);
  5129.         pRT->FillRectangle(D2D1::RectF(TABLE_LEFT + TABLE_WIDTH / 2.f + MIDDLE_HOLE_VISUAL_RADIUS, TABLE_TOP - WOODEN_RAIL_THICKNESS, TABLE_RIGHT - CORNER_HOLE_VISUAL_RADIUS, TABLE_TOP), pRailBrush);
  5130.         // Bottom Rails (split by middle pocket)
  5131.         pRT->FillRectangle(D2D1::RectF(TABLE_LEFT + CORNER_HOLE_VISUAL_RADIUS, TABLE_BOTTOM, TABLE_LEFT + TABLE_WIDTH / 2.f - MIDDLE_HOLE_VISUAL_RADIUS, TABLE_BOTTOM + WOODEN_RAIL_THICKNESS), pRailBrush);
  5132.         pRT->FillRectangle(D2D1::RectF(TABLE_LEFT + TABLE_WIDTH / 2.f + MIDDLE_HOLE_VISUAL_RADIUS, TABLE_BOTTOM, TABLE_RIGHT - CORNER_HOLE_VISUAL_RADIUS, TABLE_BOTTOM + WOODEN_RAIL_THICKNESS), pRailBrush);
  5133.         // Side Rails
  5134.         pRT->FillRectangle(D2D1::RectF(TABLE_LEFT - WOODEN_RAIL_THICKNESS, TABLE_TOP + CORNER_HOLE_VISUAL_RADIUS, TABLE_LEFT, TABLE_BOTTOM - CORNER_HOLE_VISUAL_RADIUS), pRailBrush);
  5135.         pRT->FillRectangle(D2D1::RectF(TABLE_RIGHT, TABLE_TOP + CORNER_HOLE_VISUAL_RADIUS, TABLE_RIGHT + WOODEN_RAIL_THICKNESS, TABLE_BOTTOM - CORNER_HOLE_VISUAL_RADIUS), pRailBrush);
  5136.         SafeRelease(&pRailBrush);
  5137.     }
  5138.  
  5139.     // Part 2: Draw the Inner Gradient Rim as 6 Polygons with Correct V-Cuts
  5140.     //const float rimWidth = 20.0f;       // Defines the thickness of the inner rim overlay 15=>20
  5141.     //const float chamferSize = 25.0f;    // Defines the size of the 45-degree V-cut
  5142.  
  5143.     // Create a single Gradient Stop Collection to be reused for the 3D effect
  5144.     ID2D1GradientStopCollection* pStops = nullptr;
  5145.     D2D1_GRADIENT_STOP stops[2] = { {0.0f, Lighten(TABLE_COLOR, 1.5f)}, {1.0f, Lighten(TABLE_COLOR, 0.7f)} };
  5146.     pRT->CreateGradientStopCollection(stops, 2, &pStops);
  5147.  
  5148.     if (pStops) {
  5149.         // Define the vertices for all 6 rim/cushion polygons with CORRECTED outward-facing cuts
  5150.         // OUTWARD-facing chamfer tips: short edge is OUTSIDE (at wood), long edge is INSIDE (at felt)
  5151.                 // --- FOOLPROOF FIX: Recalculated vertices for correct, non-bloated, outward-facing V-cuts ---
  5152.                 // --- FOOLPROOF FIX: Recalculated vertices for REVERSED, non-bloated, outward-facing V-cuts ---
  5153.         // This version places the short edge against the rail and the long edge facing the felt.
  5154.                 // --- FINAL FOOLPROOF FIX: Corrected vertices for ALL rails, including Left and Right ---
  5155.                 // --- FINAL, DEFINITIVE FIX: Corrected vertices for the Right Rail ---
  5156.         D2D1_POINT_2F rim_pieces[6][4] = {
  5157.             // Top Rail (Left Part) - CORRECT
  5158.             { {TABLE_LEFT + CORNER_HOLE_VISUAL_RADIUS, TABLE_TOP}, {TABLE_LEFT + TABLE_WIDTH / 2.f - MIDDLE_HOLE_VISUAL_RADIUS, TABLE_TOP}, {TABLE_LEFT + TABLE_WIDTH / 2.f - MIDDLE_HOLE_VISUAL_RADIUS - CHAMFER_SIZE, TABLE_TOP + INNER_RIM_THICKNESS}, {TABLE_LEFT + CORNER_HOLE_VISUAL_RADIUS + CHAMFER_SIZE, TABLE_TOP + INNER_RIM_THICKNESS} },
  5159.             // Top Rail (Right Part) - CORRECT
  5160.             { {TABLE_LEFT + TABLE_WIDTH / 2.f + MIDDLE_HOLE_VISUAL_RADIUS, TABLE_TOP}, {TABLE_RIGHT - CORNER_HOLE_VISUAL_RADIUS, TABLE_TOP}, {TABLE_RIGHT - CORNER_HOLE_VISUAL_RADIUS - CHAMFER_SIZE, TABLE_TOP + INNER_RIM_THICKNESS}, {TABLE_LEFT + TABLE_WIDTH / 2.f + MIDDLE_HOLE_VISUAL_RADIUS + CHAMFER_SIZE, TABLE_TOP + INNER_RIM_THICKNESS} },
  5161.             // Bottom Rail (Left Part) - CORRECT
  5162.             { {TABLE_LEFT + CORNER_HOLE_VISUAL_RADIUS + CHAMFER_SIZE, TABLE_BOTTOM - INNER_RIM_THICKNESS}, {TABLE_LEFT + TABLE_WIDTH / 2.f - MIDDLE_HOLE_VISUAL_RADIUS - CHAMFER_SIZE, TABLE_BOTTOM - INNER_RIM_THICKNESS}, {TABLE_LEFT + TABLE_WIDTH / 2.f - MIDDLE_HOLE_VISUAL_RADIUS, TABLE_BOTTOM}, {TABLE_LEFT + CORNER_HOLE_VISUAL_RADIUS, TABLE_BOTTOM} },
  5163.             // Bottom Rail (Right Part) - CORRECT
  5164.             { {TABLE_LEFT + TABLE_WIDTH / 2.f + MIDDLE_HOLE_VISUAL_RADIUS + CHAMFER_SIZE, TABLE_BOTTOM - INNER_RIM_THICKNESS}, {TABLE_RIGHT - CORNER_HOLE_VISUAL_RADIUS - CHAMFER_SIZE, TABLE_BOTTOM - INNER_RIM_THICKNESS}, {TABLE_RIGHT - CORNER_HOLE_VISUAL_RADIUS, TABLE_BOTTOM}, {TABLE_LEFT + TABLE_WIDTH / 2.f + MIDDLE_HOLE_VISUAL_RADIUS, TABLE_BOTTOM} },
  5165.             // Left Rail - CORRECT
  5166.             { {TABLE_LEFT + INNER_RIM_THICKNESS, TABLE_TOP + CORNER_HOLE_VISUAL_RADIUS + CHAMFER_SIZE}, {TABLE_LEFT + INNER_RIM_THICKNESS, TABLE_BOTTOM - CORNER_HOLE_VISUAL_RADIUS - CHAMFER_SIZE}, {TABLE_LEFT, TABLE_BOTTOM - CORNER_HOLE_VISUAL_RADIUS}, {TABLE_LEFT, TABLE_TOP + CORNER_HOLE_VISUAL_RADIUS} },
  5167.             // Right Rail - RECALCULATED AND CORRECTED
  5168.             { {TABLE_RIGHT, TABLE_TOP + CORNER_HOLE_VISUAL_RADIUS}, {TABLE_RIGHT, TABLE_BOTTOM - CORNER_HOLE_VISUAL_RADIUS}, {TABLE_RIGHT - INNER_RIM_THICKNESS, TABLE_BOTTOM - CORNER_HOLE_VISUAL_RADIUS - CHAMFER_SIZE}, {TABLE_RIGHT - INNER_RIM_THICKNESS, TABLE_TOP + CORNER_HOLE_VISUAL_RADIUS + CHAMFER_SIZE} }
  5169.         };
  5170.  
  5171.  
  5172.         // Create a unique gradient brush for each of the 4 orientations
  5173.         ID2D1LinearGradientBrush* pTopBrush = nullptr, * pBottomBrush = nullptr, * pLeftBrush = nullptr, * pRightBrush = nullptr;
  5174.         pRT->CreateLinearGradientBrush(D2D1::LinearGradientBrushProperties({ 0, TABLE_TOP }, { 0, TABLE_TOP + INNER_RIM_THICKNESS }), pStops, &pTopBrush);
  5175.         pRT->CreateLinearGradientBrush(D2D1::LinearGradientBrushProperties({ 0, TABLE_BOTTOM - INNER_RIM_THICKNESS }, { 0, TABLE_BOTTOM }), pStops, &pBottomBrush);
  5176.         pRT->CreateLinearGradientBrush(D2D1::LinearGradientBrushProperties({ TABLE_LEFT, 0 }, { TABLE_LEFT + INNER_RIM_THICKNESS, 0 }), pStops, &pLeftBrush);
  5177.         pRT->CreateLinearGradientBrush(D2D1::LinearGradientBrushProperties({ TABLE_RIGHT - INNER_RIM_THICKNESS, 0 }, { TABLE_RIGHT, 0 }), pStops, &pRightBrush);
  5178.  
  5179.         ID2D1LinearGradientBrush* brushes[] = { pTopBrush, pTopBrush, pBottomBrush, pBottomBrush, pLeftBrush, pRightBrush };
  5180.  
  5181.         // Draw each rim piece as a filled polygon with its corresponding gradient
  5182.         for (int i = 0; i < 6; ++i) {
  5183.             if (!brushes[i]) continue;
  5184.             ID2D1PathGeometry* pPath = nullptr;
  5185.             pFactory->CreatePathGeometry(&pPath);
  5186.             if (pPath) {
  5187.                 ID2D1GeometrySink* pSink = nullptr;
  5188.                 if (SUCCEEDED(pPath->Open(&pSink))) {
  5189.                     pSink->BeginFigure(rim_pieces[i][0], D2D1_FIGURE_BEGIN_FILLED);
  5190.                     pSink->AddLines(&rim_pieces[i][1], 3);
  5191.                     pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  5192.                     pSink->Close();
  5193.                 }
  5194.                 SafeRelease(&pSink);
  5195.                 pRT->FillGeometry(pPath, brushes[i]);
  5196.                 SafeRelease(&pPath);
  5197.             }
  5198.         }
  5199.         SafeRelease(&pTopBrush); SafeRelease(&pBottomBrush); SafeRelease(&pLeftBrush); SafeRelease(&pRightBrush);
  5200.         SafeRelease(&pStops);
  5201.     }
  5202.  
  5203.     // --- Layer 6: Headstring and Kitchen Arc ---
  5204.     // This is drawn on top of the felt and cushions.
  5205.     ID2D1SolidColorBrush* pLineBrush = nullptr;
  5206.     pRT->CreateSolidColorBrush(D2D1::ColorF(0.4235f, 0.5647f, 0.1765f, 1.0f), &pLineBrush);
  5207.     if (pLineBrush) {
  5208.         pRT->DrawLine(
  5209.             D2D1::Point2F(HEADSTRING_X, TABLE_TOP),
  5210.             D2D1::Point2F(HEADSTRING_X, TABLE_BOTTOM),
  5211.             pLineBrush,
  5212.             1.0f
  5213.         );
  5214.  
  5215.         // This is your original, preserved kitchen semicircle code.
  5216.         ID2D1PathGeometry* pGeometry = nullptr;
  5217.         HRESULT hr = pFactory->CreatePathGeometry(&pGeometry);
  5218.         if (SUCCEEDED(hr) && pGeometry)
  5219.         {
  5220.             ID2D1GeometrySink* pSink = nullptr;
  5221.             hr = pGeometry->Open(&pSink);
  5222.             if (SUCCEEDED(hr) && pSink)
  5223.             {
  5224.                 float radius = 60.0f;
  5225.                 D2D1_POINT_2F center = D2D1::Point2F(HEADSTRING_X, (TABLE_TOP + TABLE_BOTTOM) / 2.0f);
  5226.                 D2D1_POINT_2F startPoint = D2D1::Point2F(center.x, center.y - radius);
  5227.                 pSink->BeginFigure(startPoint, D2D1_FIGURE_BEGIN_HOLLOW);
  5228.                 D2D1_ARC_SEGMENT arc = {};
  5229.                 arc.point = D2D1::Point2F(center.x, center.y + radius);
  5230.                 arc.size = D2D1::SizeF(radius, radius);
  5231.                 arc.rotationAngle = 0.0f;
  5232.                 arc.sweepDirection = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  5233.                 arc.arcSize = D2D1_ARC_SIZE_SMALL;
  5234.                 pSink->AddArc(&arc);
  5235.                 pSink->EndFigure(D2D1_FIGURE_END_OPEN);
  5236.                 pSink->Close();
  5237.                 SafeRelease(&pSink);
  5238.  
  5239.                 pRT->DrawGeometry(pGeometry, pLineBrush, 1.5f);
  5240.             }
  5241.             SafeRelease(&pGeometry);
  5242.         }
  5243.         SafeRelease(&pLineBrush);
  5244.     }
  5245. }
  5246.  
  5247.  
  5248. // ----------------------------------------------
  5249. //  Helper : clamp to [0,1] and lighten a colour
  5250. // ----------------------------------------------
  5251. static D2D1_COLOR_F Lighten(const D2D1_COLOR_F& c, float factor = 1.25f)
  5252. {
  5253.     return D2D1::ColorF(
  5254.         std::min(1.0f, c.r * factor),
  5255.         std::min(1.0f, c.g * factor),
  5256.         std::min(1.0f, c.b * factor),
  5257.         c.a);
  5258. }
  5259.  
  5260. // ------------------------------------------------
  5261. //  NEW  DrawBalls – radial-gradient “spot-light”
  5262. // ------------------------------------------------
  5263. void DrawBalls(ID2D1RenderTarget* pRT)
  5264. {
  5265.     if (!pRT) return;
  5266.  
  5267.     ID2D1SolidColorBrush* pStripeBrush = nullptr;    // white stripe
  5268.     ID2D1SolidColorBrush* pBorderBrush = nullptr;    // black ring
  5269.     ID2D1SolidColorBrush* pNumWhite = nullptr;       // white decal circle
  5270.     ID2D1SolidColorBrush* pNumBlack = nullptr;       // digit colour
  5271.  
  5272.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
  5273.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
  5274.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pNumWhite);
  5275.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pNumBlack);
  5276.  
  5277.     for (const Ball& b : balls)
  5278.     {
  5279.         if (b.isPocketed) continue;
  5280.  
  5281.         // Save the original transform for restoration at the end of this ball.
  5282.         D2D1::Matrix3x2F originalTransform;
  5283.         pRT->GetTransform(&originalTransform);
  5284.  
  5285.         // Build the radial gradient for THIS ball
  5286.         ID2D1GradientStopCollection* pStops = nullptr;
  5287.         ID2D1RadialGradientBrush* pRad = nullptr;
  5288.  
  5289.         D2D1_GRADIENT_STOP gs[3];
  5290.         gs[0].position = 0.0f;  gs[0].color = D2D1::ColorF(1, 1, 1, 0.95f);   // bright spot
  5291.         gs[1].position = 0.35f; gs[1].color = Lighten(b.color);               // transitional
  5292.         gs[2].position = 1.0f;  gs[2].color = b.color;                        // base colour
  5293.  
  5294.         pRT->CreateGradientStopCollection(gs, 3, &pStops);
  5295.         if (pStops)
  5296.         {
  5297.             // Place the hot-spot slightly towards top-left to look more 3-D,
  5298.             // then nudge it along the rotationAxis so the highlight follows travel.
  5299.             // This gives the illusion of 'spinning on the side'.
  5300.             float baseHotX = b.x - BALL_RADIUS * 0.4f;
  5301.             float baseHotY = b.y - BALL_RADIUS * 0.4f;
  5302.  
  5303.             // small dynamic offset based on rotationAxis and rotationAngle magnitude
  5304.             float axis = b.rotationAxis; // radians, perpendicular to travel
  5305.             float spinInfluence = 0.14f; // tweak: how much spin moves the highlight (0..0.4 typical)
  5306.             float offsetMag = (fmodf(fabsf(b.rotationAngle), 2.0f * PI) / (2.0f * PI)) * (BALL_RADIUS * spinInfluence);
  5307.             D2D1_POINT_2F origin = D2D1::Point2F(
  5308.                 baseHotX + cosf(axis) * offsetMag,
  5309.                 baseHotY + sinf(axis) * offsetMag
  5310.             );
  5311.  
  5312.             D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  5313.                 D2D1::RadialGradientBrushProperties(
  5314.                     origin,
  5315.                     D2D1::Point2F(0, 0),
  5316.                     BALL_RADIUS * 1.3f,
  5317.                     BALL_RADIUS * 1.3f);
  5318.  
  5319.             /*// Place the hotspot slightly towards top-left (in world coords)
  5320.             D2D1_POINT_2F origin = D2D1::Point2F(b.x - BALL_RADIUS * 0.4f,
  5321.                 b.y - BALL_RADIUS * 0.4f);
  5322.             D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  5323.                 D2D1::RadialGradientBrushProperties(
  5324.                     origin,                        // gradientOrigin
  5325.                     D2D1::Point2F(0, 0),           // offset (unused)
  5326.                     BALL_RADIUS * 1.3f,            // radiusX
  5327.                     BALL_RADIUS * 1.3f);           // radiusY*/
  5328.  
  5329.             pRT->CreateRadialGradientBrush(props, pStops, &pRad);
  5330.             SafeRelease(&pStops); // safe to release stops after brush creation
  5331.         }
  5332.  
  5333.         // Compute rotation transform (convert radians -> degrees)
  5334.         float angleDeg = (b.rotationAngle * 180.0f) / PI;
  5335.         D2D1::Matrix3x2F rot = D2D1::Matrix3x2F::Rotation(angleDeg, D2D1::Point2F(b.x, b.y));
  5336.         // Apply rotation on top of existing transform
  5337.         pRT->SetTransform(rot * originalTransform);
  5338.  
  5339.         // Draw the ball (body)
  5340.         D2D1_ELLIPSE body = D2D1::Ellipse(D2D1::Point2F(b.x, b.y), BALL_RADIUS, BALL_RADIUS);
  5341.         if (pRad) pRT->FillEllipse(&body, pRad);
  5342.  
  5343.         // Stripes overlay (if applicable)
  5344.         if (b.type == BallType::STRIPE && pStripeBrush)
  5345.         {
  5346.             D2D1_RECT_F stripe = D2D1::RectF(
  5347.                 b.x - BALL_RADIUS,
  5348.                 b.y - BALL_RADIUS * 0.40f,
  5349.                 b.x + BALL_RADIUS,
  5350.                 b.y + BALL_RADIUS * 0.40f);
  5351.             pRT->FillRectangle(&stripe, pStripeBrush);
  5352.  
  5353.             if (pRad)
  5354.             {
  5355.                 D2D1_ELLIPSE inner = D2D1::Ellipse(D2D1::Point2F(b.x, b.y),
  5356.                     BALL_RADIUS * 0.60f, BALL_RADIUS * 0.60f);
  5357.                 pRT->FillEllipse(&inner, pRad);
  5358.             }
  5359.         }
  5360.  
  5361.         // Draw number decal (skip cue ball)
  5362.         if (b.id != 0 && pBallNumFormat && pNumWhite && pNumBlack)
  5363.         {
  5364.             const float decalR = (b.type == BallType::STRIPE) ? BALL_RADIUS * 0.40f : BALL_RADIUS * 0.45f;
  5365.             D2D1_ELLIPSE decal = D2D1::Ellipse(D2D1::Point2F(b.x, b.y), decalR, decalR);
  5366.             pRT->FillEllipse(&decal, pNumWhite);
  5367.             pRT->DrawEllipse(&decal, pNumBlack, 0.8f);
  5368.  
  5369.             // Use std::wstring to avoid _snwprintf_s/wcslen and literal issues.
  5370.             std::wstring numText = std::to_wstring(b.id);
  5371.             D2D1_RECT_F layout = D2D1::RectF(
  5372.                 b.x - decalR, b.y - decalR,
  5373.                 b.x + decalR, b.y + decalR);
  5374.  
  5375.             pRT->DrawTextW(
  5376.                 numText.c_str(),
  5377.                 static_cast<UINT32>(numText.length()),
  5378.                 pBallNumFormat,
  5379.                 &layout,
  5380.                 pNumBlack);
  5381.         }
  5382.  
  5383.         // Draw black border for the ball
  5384.         if (pBorderBrush)
  5385.             pRT->DrawEllipse(&body, pBorderBrush, 1.5f);
  5386.  
  5387.         // restore the render target transform for next objects
  5388.         pRT->SetTransform(originalTransform);
  5389.  
  5390.         // cleanup per-ball D2D resources
  5391.         SafeRelease(&pRad);
  5392.     } // end for each ball
  5393.  
  5394.     SafeRelease(&pStripeBrush);
  5395.     SafeRelease(&pBorderBrush);
  5396.     SafeRelease(&pNumWhite);
  5397.     SafeRelease(&pNumBlack);
  5398. }
  5399.  
  5400. /*void DrawBalls(ID2D1RenderTarget* pRT) {
  5401.     ID2D1SolidColorBrush* pBrush = nullptr;
  5402.     ID2D1SolidColorBrush* pStripeBrush = nullptr; // For stripe pattern
  5403.  
  5404.     pRT->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0), &pBrush); // Placeholder
  5405.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
  5406.  
  5407.     if (!pBrush || !pStripeBrush) {
  5408.         SafeRelease(&pBrush);
  5409.         SafeRelease(&pStripeBrush);
  5410.         return;
  5411.     }
  5412.  
  5413.  
  5414.     for (size_t i = 0; i < balls.size(); ++i) {
  5415.         const Ball& b = balls[i];
  5416.         if (!b.isPocketed) {
  5417.             D2D1_ELLIPSE ellipse = D2D1::Ellipse(D2D1::Point2F(b.x, b.y), BALL_RADIUS, BALL_RADIUS);
  5418.  
  5419.             // Set main ball color
  5420.             pBrush->SetColor(b.color);
  5421.             pRT->FillEllipse(&ellipse, pBrush);
  5422.  
  5423.             // Draw Stripe if applicable
  5424.             if (b.type == BallType::STRIPE) {
  5425.                 // Draw a white band across the middle (simplified stripe)
  5426.                 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);
  5427.                 // Need to clip this rectangle to the ellipse bounds - complex!
  5428.                 // Alternative: Draw two colored arcs leaving a white band.
  5429.                 // Simplest: Draw a white circle inside, slightly smaller.
  5430.                 D2D1_ELLIPSE innerEllipse = D2D1::Ellipse(D2D1::Point2F(b.x, b.y), BALL_RADIUS * 0.6f, BALL_RADIUS * 0.6f);
  5431.                 pRT->FillEllipse(innerEllipse, pStripeBrush); // White center part
  5432.                 pBrush->SetColor(b.color); // Set back to stripe color
  5433.                 pRT->FillEllipse(innerEllipse, pBrush); // Fill again, leaving a ring - No, this isn't right.
  5434.  
  5435.                 // Let's try drawing a thick white line across
  5436.                 // This doesn't look great. Just drawing solid red for stripes for now.
  5437.             }
  5438.  
  5439.             // Draw Number (Optional - requires more complex text layout or pre-rendered textures)
  5440.             // if (b.id != 0 && pTextFormat) {
  5441.             //     std::wstring numStr = std::to_wstring(b.id);
  5442.             //     D2D1_RECT_F textRect = D2D1::RectF(b.x - BALL_RADIUS, b.y - BALL_RADIUS, b.x + BALL_RADIUS, b.y + BALL_RADIUS);
  5443.             //     ID2D1SolidColorBrush* pNumBrush = nullptr;
  5444.             //     D2D1_COLOR_F numCol = (b.type == BallType::SOLID || b.id == 8) ? D2D1::ColorF(D2D1::ColorF::Black) : D2D1::ColorF(D2D1::ColorF::White);
  5445.             //     pRT->CreateSolidColorBrush(numCol, &pNumBrush);
  5446.             //     // Create a smaller text format...
  5447.             //     // pRT->DrawText(numStr.c_str(), numStr.length(), pSmallTextFormat, &textRect, pNumBrush);
  5448.             //     SafeRelease(&pNumBrush);
  5449.             // }
  5450.         }
  5451.     }
  5452.  
  5453.     SafeRelease(&pBrush);
  5454.     SafeRelease(&pStripeBrush);
  5455. }*/
  5456.  
  5457. void DrawCueStick(ID2D1RenderTarget* pRT)
  5458. {
  5459.     // --- Logic to determine if the cue stick should be visible ---
  5460.     // This part of your code is correct and is preserved.
  5461.     bool shouldDrawStick = false;
  5462.     if (aiIsDisplayingAim) {
  5463.         shouldDrawStick = true;
  5464.     }
  5465.     else if (currentPlayer == 1 || !isPlayer2AI) {
  5466.         switch (currentGameState) {
  5467.         case AIMING:
  5468.         case BREAKING:
  5469.         case PLAYER1_TURN:
  5470.         case PLAYER2_TURN:
  5471.         case CHOOSING_POCKET_P1:
  5472.         case CHOOSING_POCKET_P2:
  5473.             shouldDrawStick = true;
  5474.             break;
  5475.         }
  5476.     }
  5477.     if (!shouldDrawStick) return;
  5478.     // --- End visibility logic ---
  5479.  
  5480.     Ball* cue = GetCueBall();
  5481.     if (!cue) return;
  5482.  
  5483.     // --- FIX: Increased dimensions and added retraction logic ---
  5484.  
  5485.     // --- FOOLPROOF FIX: Scaled dimensions for a 150% larger cue stick ---
  5486.  
  5487.     // 1. Define the new, proportionally larger dimensions for the cue stick.
  5488.     const float scale = 1.5f; // 150%
  5489.     const float tipLength = 30.0f * scale;
  5490.     const float buttLength = 60.0f * scale;
  5491.     const float totalLength = 220.0f * scale;
  5492.     const float buttWidth = 9.0f * scale;
  5493.     const float shaftWidth = 5.0f * scale;
  5494.  
  5495.     // 2. Determine the correct angle and power to draw with.
  5496.     float angleToDraw = cueAngle;
  5497.     float powerToDraw = shotPower;
  5498.     if (aiIsDisplayingAim) { // If AI is showing its aim, use its planned shot.
  5499.         angleToDraw = aiPlannedShotDetails.angle;
  5500.         powerToDraw = aiPlannedShotDetails.power;
  5501.     }
  5502.  
  5503.     // 3. Calculate the "power offset" based on the current shot strength.
  5504.     // This is the logic from your old code that makes the stick pull back.
  5505.     float powerOffset = 0.0f;
  5506.     if ((isAiming || isDraggingStick) || aiIsDisplayingAim) {
  5507.         // The multiplier controls how far the stick pulls back.
  5508.         powerOffset = powerToDraw * 5.0f;
  5509.     }
  5510.  
  5511.     // 4. Calculate the start and end points of the cue stick, applying the offset.
  5512.     float theta = angleToDraw + PI;
  5513.     D2D1_POINT_2F base = D2D1::Point2F(
  5514.         cue->x + cosf(theta) * (buttLength + powerOffset),
  5515.         cue->y + sinf(theta) * (buttLength + powerOffset)
  5516.     );
  5517.     D2D1_POINT_2F tip = D2D1::Point2F(
  5518.         cue->x + cosf(theta) * (totalLength + powerOffset),
  5519.         cue->y + sinf(theta) * (totalLength + powerOffset)
  5520.     );
  5521.     // --- END OF FIX ---
  5522.  
  5523.     // --- The rest of your tapered drawing logic is preserved and will now use the new points ---
  5524.     ID2D1SolidColorBrush* pButtBrush = nullptr;
  5525.     ID2D1SolidColorBrush* pShaftBrush = nullptr;
  5526.     ID2D1SolidColorBrush* pTipBrush = nullptr;
  5527.     pRT->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0), &pButtBrush);
  5528.     pRT->CreateSolidColorBrush(D2D1::ColorF(0.96f, 0.85f, 0.60f), &pShaftBrush);
  5529.     pRT->CreateSolidColorBrush(D2D1::ColorF(1, 1, 1), &pTipBrush);
  5530.  
  5531.     auto buildRect = [&](D2D1_POINT_2F p1, D2D1_POINT_2F p2, float w1, float w2) {
  5532.         D2D1_POINT_2F perp = { -sinf(theta) * 0.5f, cosf(theta) * 0.5f };
  5533.         perp.x *= w1; perp.y *= w1;
  5534.         D2D1_POINT_2F a = { p1.x + perp.x, p1.y + perp.y };
  5535.         D2D1_POINT_2F b = { p2.x + perp.x * (w2 / w1), p2.y + perp.y * (w2 / w1) };
  5536.         D2D1_POINT_2F c = { p2.x - perp.x * (w2 / w1), p2.y - perp.y * (w2 / w1) };
  5537.         D2D1_POINT_2F d = { p1.x - perp.x, p1.y - perp.y };
  5538.         ID2D1PathGeometry* geom = nullptr;
  5539.         if (SUCCEEDED(pFactory->CreatePathGeometry(&geom))) {
  5540.             ID2D1GeometrySink* sink = nullptr;
  5541.             if (SUCCEEDED(geom->Open(&sink))) {
  5542.                 sink->BeginFigure(a, D2D1_FIGURE_BEGIN_FILLED);
  5543.                 sink->AddLine(b);
  5544.                 sink->AddLine(c);
  5545.                 sink->AddLine(d);
  5546.                 sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  5547.                 sink->Close();
  5548.             }
  5549.             SafeRelease(&sink);
  5550.         }
  5551.         return geom;
  5552.     };
  5553.  
  5554.     // --- FIX: These points are now also offset by the power ---
  5555.     D2D1_POINT_2F mid1 = { cue->x + cosf(theta) * (buttLength * 0.5f + powerOffset), cue->y + sinf(theta) * (buttLength * 0.5f + powerOffset) };
  5556.     D2D1_POINT_2F mid2 = { cue->x + cosf(theta) * (totalLength - tipLength + powerOffset), cue->y + sinf(theta) * (totalLength - tipLength + powerOffset) };
  5557.     // --- END OF FIX ---
  5558.  
  5559.     auto buttGeom = buildRect(base, mid1, buttWidth, shaftWidth);
  5560.     if (buttGeom) { pRT->FillGeometry(buttGeom, pButtBrush); SafeRelease(&buttGeom); }
  5561.  
  5562.     auto shaftGeom = buildRect(mid1, mid2, shaftWidth, shaftWidth);
  5563.     if (shaftGeom) { pRT->FillGeometry(shaftGeom, pShaftBrush); SafeRelease(&shaftGeom); }
  5564.  
  5565.     auto tipGeom = buildRect(mid2, tip, shaftWidth, shaftWidth);
  5566.     if (tipGeom) { pRT->FillGeometry(tipGeom, pTipBrush); SafeRelease(&tipGeom); }
  5567.  
  5568.     SafeRelease(&pButtBrush);
  5569.     SafeRelease(&pShaftBrush);
  5570.     SafeRelease(&pTipBrush);
  5571. }
  5572.  
  5573.  
  5574.  
  5575. /*void DrawAimingAids(ID2D1RenderTarget* pRT) {
  5576.     // Condition check at start (Unchanged)
  5577.     //if (currentGameState != PLAYER1_TURN && currentGameState != PLAYER2_TURN &&
  5578.         //currentGameState != BREAKING && currentGameState != AIMING)
  5579.     //{
  5580.         //return;
  5581.     //}
  5582.         // NEW Condition: Allow drawing if it's a human player's active turn/aiming/breaking,
  5583.     // OR if it's AI's turn and it's in AI_THINKING state (calculating) or BREAKING (aiming break).
  5584.     bool isHumanInteracting = (!isPlayer2AI || currentPlayer == 1) &&
  5585.         (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN ||
  5586.             currentGameState == BREAKING || currentGameState == AIMING);
  5587.     // AI_THINKING state is when AI calculates shot. AIMakeDecision sets cueAngle/shotPower.
  5588.     // Also include BREAKING state if it's AI's turn and isOpeningBreakShot for break aim visualization.
  5589.         // NEW Condition: AI is displaying its aim
  5590.     bool isAiVisualizingShot = (isPlayer2AI && currentPlayer == 2 &&
  5591.         currentGameState == AI_THINKING && aiIsDisplayingAim);
  5592.  
  5593.     if (!isHumanInteracting && !(isAiVisualizingShot || (currentGameState == AI_THINKING && aiIsDisplayingAim))) {
  5594.         return;
  5595.     }
  5596.  
  5597.     Ball* cueBall = GetCueBall();
  5598.     if (!cueBall || cueBall->isPocketed) return; // Don't draw if cue ball is gone
  5599.  
  5600.     ID2D1SolidColorBrush* pBrush = nullptr;
  5601.     ID2D1SolidColorBrush* pGhostBrush = nullptr;
  5602.     ID2D1StrokeStyle* pDashedStyle = nullptr;
  5603.     ID2D1SolidColorBrush* pCueBrush = nullptr;
  5604.     ID2D1SolidColorBrush* pReflectBrush = nullptr; // Brush for reflection line
  5605.  
  5606.     // Ensure render target is valid
  5607.     if (!pRT) return;
  5608.  
  5609.     // Create Brushes and Styles (check for failures)
  5610.     HRESULT hr;
  5611.     hr = pRT->CreateSolidColorBrush(AIM_LINE_COLOR, &pBrush);
  5612.     if FAILED(hr) { SafeRelease(&pBrush); return; }
  5613.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.5f), &pGhostBrush);
  5614.     if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); return; }
  5615.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(0.6f, 0.4f, 0.2f), &pCueBrush);
  5616.     if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); SafeRelease(&pCueBrush); return; }
  5617.     // Create reflection brush (e.g., lighter shade or different color)
  5618.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::LightCyan, 0.6f), &pReflectBrush);
  5619.     if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); SafeRelease(&pCueBrush); SafeRelease(&pReflectBrush); return; }
  5620.     // Create a Cyan brush for primary and secondary lines //orig(75.0f / 255.0f, 0.0f, 130.0f / 255.0f);indigoColor
  5621.     D2D1::ColorF cyanColor(0.0, 255.0, 255.0, 255.0f);
  5622.     ID2D1SolidColorBrush* pCyanBrush = nullptr;
  5623.     hr = pRT->CreateSolidColorBrush(cyanColor, &pCyanBrush);
  5624.     if (FAILED(hr)) {
  5625.         SafeRelease(&pCyanBrush);
  5626.         // handle error if needed
  5627.     }
  5628.     // Create a Purple brush for primary and secondary lines
  5629.     D2D1::ColorF purpleColor(255.0f, 0.0f, 255.0f, 255.0f);
  5630.     ID2D1SolidColorBrush* pPurpleBrush = nullptr;
  5631.     hr = pRT->CreateSolidColorBrush(purpleColor, &pPurpleBrush);
  5632.     if (FAILED(hr)) {
  5633.         SafeRelease(&pPurpleBrush);
  5634.         // handle error if needed
  5635.     }
  5636.  
  5637.     if (pFactory) {
  5638.         D2D1_STROKE_STYLE_PROPERTIES strokeProps = D2D1::StrokeStyleProperties();
  5639.         strokeProps.dashStyle = D2D1_DASH_STYLE_DASH;
  5640.         hr = pFactory->CreateStrokeStyle(&strokeProps, nullptr, 0, &pDashedStyle);
  5641.         if FAILED(hr) { pDashedStyle = nullptr; }
  5642.     }
  5643.  
  5644.  
  5645.     // --- Cue Stick Drawing (Unchanged from previous fix) ---
  5646.     const float baseStickLength = 150.0f;
  5647.     const float baseStickThickness = 4.0f;
  5648.     float stickLength = baseStickLength * 1.4f;
  5649.     float stickThickness = baseStickThickness * 1.5f;
  5650.     float stickAngle = cueAngle + PI;
  5651.     float powerOffset = 0.0f;
  5652.     //if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
  5653.         // Show power offset if human is aiming/dragging, or if AI is preparing its shot (AI_THINKING or AI Break)
  5654.     if ((isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) || isAiVisualizingShot) { // Use the new condition
  5655.         powerOffset = shotPower * 5.0f;
  5656.     }
  5657.     D2D1_POINT_2F cueStickEnd = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (stickLength + powerOffset), cueBall->y + sinf(stickAngle) * (stickLength + powerOffset));
  5658.     D2D1_POINT_2F cueStickTip = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (powerOffset + 5.0f), cueBall->y + sinf(stickAngle) * (powerOffset + 5.0f));
  5659.     pRT->DrawLine(cueStickTip, cueStickEnd, pCueBrush, stickThickness);
  5660.  
  5661.  
  5662.     // --- Projection Line Calculation ---
  5663.     float cosA = cosf(cueAngle);
  5664.     float sinA = sinf(cueAngle);
  5665.     float rayLength = TABLE_WIDTH + TABLE_HEIGHT; // Ensure ray is long enough
  5666.     D2D1_POINT_2F rayStart = D2D1::Point2F(cueBall->x, cueBall->y);
  5667.     D2D1_POINT_2F rayEnd = D2D1::Point2F(rayStart.x + cosA * rayLength, rayStart.y + sinA * rayLength);*/
  5668.  
  5669. void DrawAimingAids(ID2D1RenderTarget* pRT) {
  5670.     // Determine if aiming aids should be drawn.
  5671.     bool isHumanInteracting = (!isPlayer2AI || currentPlayer == 1) &&
  5672.         (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN ||
  5673.             currentGameState == BREAKING || currentGameState == AIMING ||
  5674.             currentGameState == CHOOSING_POCKET_P1 || currentGameState == CHOOSING_POCKET_P2);
  5675.  
  5676.     // FOOLPROOF FIX: This is the new condition to show the AI's aim.
  5677.     bool isAiVisualizingShot = (isPlayer2AI && currentPlayer == 2 && aiIsDisplayingAim);
  5678.  
  5679.     if (!isHumanInteracting && !isAiVisualizingShot) {
  5680.         return;
  5681.     }
  5682.  
  5683.     Ball* cueBall = GetCueBall();
  5684.     if (!cueBall || cueBall->isPocketed) return;
  5685.  
  5686.     // --- Brush and Style Creation (No changes here) ---
  5687.     ID2D1SolidColorBrush* pBrush = nullptr;
  5688.     ID2D1SolidColorBrush* pGhostBrush = nullptr;
  5689.     ID2D1StrokeStyle* pDashedStyle = nullptr;
  5690.     ID2D1SolidColorBrush* pCueBrush = nullptr;
  5691.     ID2D1SolidColorBrush* pReflectBrush = nullptr;
  5692.     ID2D1SolidColorBrush* pCyanBrush = nullptr;
  5693.     ID2D1SolidColorBrush* pPurpleBrush = nullptr;
  5694.     pRT->CreateSolidColorBrush(AIM_LINE_COLOR, &pBrush);
  5695.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.5f), &pGhostBrush);
  5696.     pRT->CreateSolidColorBrush(D2D1::ColorF(0.6f, 0.4f, 0.2f), &pCueBrush);
  5697.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::LightCyan, 0.6f), &pReflectBrush);
  5698.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Cyan), &pCyanBrush);
  5699.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Purple), &pPurpleBrush);
  5700.     if (pFactory) {
  5701.         D2D1_STROKE_STYLE_PROPERTIES strokeProps = D2D1::StrokeStyleProperties();
  5702.         strokeProps.dashStyle = D2D1_DASH_STYLE_DASH;
  5703.         pFactory->CreateStrokeStyle(&strokeProps, nullptr, 0, &pDashedStyle);
  5704.     }
  5705.     // --- End Brush Creation ---
  5706.  
  5707.     // --- FOOLPROOF FIX: Use the AI's planned angle and power for drawing ---
  5708.     float angleToDraw = cueAngle;
  5709.     float powerToDraw = shotPower;
  5710.  
  5711.     if (isAiVisualizingShot) {
  5712.         // When the AI is showing its aim, force the drawing to use its planned shot details.
  5713.         angleToDraw = aiPlannedShotDetails.angle;
  5714.         powerToDraw = aiPlannedShotDetails.power;
  5715.     }
  5716.     // --- End AI Aiming Fix ---
  5717.  
  5718.     // --- Cue Stick Drawing ---
  5719.     /*const float baseStickLength = 150.0f;
  5720.     const float baseStickThickness = 4.0f;
  5721.     float stickLength = baseStickLength * 1.4f;
  5722.     float stickThickness = baseStickThickness * 1.5f;
  5723.     float stickAngle = angleToDraw + PI; // Use the angle we determined
  5724.     float powerOffset = 0.0f;
  5725.     if ((isAiming || isDraggingStick) || isAiVisualizingShot) {
  5726.         powerOffset = powerToDraw * 5.0f; // Use the power we determined
  5727.     }
  5728.     D2D1_POINT_2F cueStickEnd = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (stickLength + powerOffset), cueBall->y + sinf(stickAngle) * (stickLength + powerOffset));
  5729.     D2D1_POINT_2F cueStickTip = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (powerOffset + 5.0f), cueBall->y + sinf(stickAngle) * (powerOffset + 5.0f));
  5730.     pRT->DrawLine(cueStickTip, cueStickEnd, pCueBrush, stickThickness);*/
  5731.  
  5732.     // --- Projection Line Calculation ---
  5733.     float cosA = cosf(angleToDraw); // Use the angle we determined
  5734.     float sinA = sinf(angleToDraw);
  5735.     float rayLength = TABLE_WIDTH + TABLE_HEIGHT;
  5736.     D2D1_POINT_2F rayStart = D2D1::Point2F(cueBall->x, cueBall->y);
  5737.     D2D1_POINT_2F rayEnd = D2D1::Point2F(rayStart.x + cosA * rayLength, rayStart.y + sinA * rayLength);
  5738.  
  5739.     // Find the first ball hit by the aiming ray
  5740.     Ball* hitBall = nullptr;
  5741.     float firstHitDistSq = -1.0f;
  5742.     D2D1_POINT_2F ballCollisionPoint = { 0, 0 }; // Point on target ball circumference
  5743.     D2D1_POINT_2F ghostBallPosForHit = { 0, 0 }; // Ghost ball pos for the hit ball
  5744.  
  5745.     hitBall = FindFirstHitBall(rayStart, cueAngle, firstHitDistSq);
  5746.     if (hitBall) {
  5747.         // Calculate the point on the target ball's circumference
  5748.         float collisionDist = sqrtf(firstHitDistSq);
  5749.         ballCollisionPoint = D2D1::Point2F(rayStart.x + cosA * collisionDist, rayStart.y + sinA * collisionDist);
  5750.         // Calculate ghost ball position for this specific hit (used for projection consistency)
  5751.         ghostBallPosForHit = D2D1::Point2F(hitBall->x - cosA * BALL_RADIUS, hitBall->y - sinA * BALL_RADIUS); // Approx.
  5752.     }
  5753.  
  5754.     //new code start for visual feedback targetting wrong player balls (robust, non-destructive)
  5755.     if (hitBall && IsWrongTargetForCurrentPlayer(hitBall)) {
  5756.         // Use dedicated brushes for the overlay so we don't change or reuse pBrush/pTextFormat state.
  5757.         ID2D1SolidColorBrush* pOverlayFill = nullptr;   // semi-opaque black backdrop for readability
  5758.         ID2D1SolidColorBrush* pOverlayRed = nullptr;    // red outline + text
  5759.         ID2D1SolidColorBrush* pOverlaySpec = nullptr;   // tiny spec highlight
  5760.  
  5761.         HRESULT hr1 = pRT->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0, 0.55f), &pOverlayFill);
  5762.         HRESULT hr2 = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Red, 0.98f), &pOverlayRed);
  5763.         HRESULT hr3 = pRT->CreateSolidColorBrush(D2D1::ColorF(1.0f, 1.0f, 1.0f, 0.9f), &pOverlaySpec);
  5764.  
  5765.         if (SUCCEEDED(hr1) && SUCCEEDED(hr2) && SUCCEEDED(hr3) && pOverlayFill && pOverlayRed && pOverlaySpec) {
  5766.             // Outline circle (thin) so the user still sees the ball
  5767.             D2D1_ELLIPSE outlineEllipse = D2D1::Ellipse(D2D1::Point2F(hitBall->x, hitBall->y),
  5768.                 BALL_RADIUS + 3.0f, BALL_RADIUS + 3.0f);
  5769.             pRT->DrawEllipse(&outlineEllipse, pOverlayRed, 2.6f);
  5770.  
  5771.             // Prepare text string and layout rect above the ball
  5772.             const wchar_t* overlayText = L"WRONG BALL";
  5773.             const UINT32 overlayLen = (UINT32)wcslen(overlayText);
  5774.             float txtW = 92.0f;   // text box width
  5775.             float txtH = 20.0f;   // text box height
  5776.             D2D1_RECT_F textRect = D2D1::RectF(
  5777.                 hitBall->x - txtW / 2.0f,
  5778.                 hitBall->y - BALL_RADIUS - txtH - 6.0f,
  5779.                 hitBall->x + txtW / 2.0f,
  5780.                 hitBall->y - BALL_RADIUS - 6.0f
  5781.             );
  5782.  
  5783.             // Draw semi-opaque rounded rectangular backdrop to improve readability
  5784.             D2D1_ROUNDED_RECT backdrop = D2D1::RoundedRect(textRect, 4.0f, 4.0f);
  5785.             pRT->FillRoundedRectangle(&backdrop, pOverlayFill);
  5786.             pRT->DrawRoundedRectangle(&backdrop, pOverlayRed, 1.2f);
  5787.  
  5788.             // Draw the overlay text centered in the box using existing pTextFormat (no modifications)
  5789.             if (pTextFormat) {
  5790.                 // Save original alignment and temporarily center the text (do not modify global format objects)
  5791.                 // We'll use DrawText with a temporary local copy of DWRITE alignment by creating a local format
  5792.                 // to avoid changing pTextFormat's global state. Creating a tiny local bold format is cheap.
  5793.                 IDWriteTextFormat* pLocalFormat = nullptr;
  5794.                 if (pDWriteFactory) {
  5795.                     if (SUCCEEDED(pDWriteFactory->CreateTextFormat(
  5796.                         L"Segoe UI", NULL, DWRITE_FONT_WEIGHT_BOLD, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
  5797.                         12.0f, L"en-us", &pLocalFormat)))
  5798.                     {
  5799.                         pLocalFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  5800.                         pLocalFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  5801.                     }
  5802.                 }
  5803.  
  5804.                 // draw text using the local format if available, otherwise fallback to global pTextFormat
  5805.                 IDWriteTextFormat* pUseFmt = pLocalFormat ? pLocalFormat : pTextFormat;
  5806.                 pRT->DrawTextW(overlayText, overlayLen, pUseFmt, &textRect, pOverlayRed);
  5807.  
  5808.                 SafeRelease(&pLocalFormat);
  5809.             }
  5810.  
  5811.             // small white spec highlight inside the red outline to give a metal/flash feel
  5812.             D2D1_ELLIPSE spec = D2D1::Ellipse(D2D1::Point2F(hitBall->x + 6.0f, hitBall->y - BALL_RADIUS - 6.0f),
  5813.                 2.0f, 2.0f);
  5814.             pRT->FillEllipse(&spec, pOverlaySpec);
  5815.         }
  5816.  
  5817.         SafeRelease(&pOverlayFill);
  5818.         SafeRelease(&pOverlayRed);
  5819.         SafeRelease(&pOverlaySpec);
  5820.     }
  5821.     //new code end for visual feedback targetting wrong player balls
  5822.  
  5823.     /*//new code start for visual feedback targetting wrong player balls
  5824.     if (hitBall && IsWrongTargetForCurrentPlayer(hitBall)) {
  5825.         // Create red brush for outline and text
  5826.         ID2D1SolidColorBrush* pRedBrush = nullptr;
  5827.         HRESULT hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Red), &pRedBrush);
  5828.         if (SUCCEEDED(hr) && pRedBrush) {
  5829.             // Draw red outline circle slightly larger than ball radius
  5830.             D2D1_ELLIPSE outlineEllipse = D2D1::Ellipse(D2D1::Point2F(hitBall->x, hitBall->y), BALL_RADIUS + 3.0f, BALL_RADIUS + 3.0f);
  5831.             pRT->DrawEllipse(&outlineEllipse, pRedBrush, 3.0f);
  5832.  
  5833.             // Draw "WRONG BALL" text above the ball
  5834.             if (pTextFormat) {
  5835.                 // Define a rectangle above the ball for the text
  5836.                 D2D1_RECT_F textRect = D2D1::RectF(
  5837.                     hitBall->x - 40.0f,
  5838.                     hitBall->y - BALL_RADIUS - 30.0f,
  5839.                     hitBall->x + 40.0f,
  5840.                     hitBall->y - BALL_RADIUS - 10.0f
  5841.                 );
  5842.                 pRT->DrawText(L"WRONG", 5, pTextFormat, &textRect, pRedBrush);
  5843.                 //pRT->DrawText(L"WRONG BALL", 10, pTextFormat, &textRect, pRedBrush);
  5844.             }
  5845.  
  5846.             SafeRelease(&pRedBrush);
  5847.         }
  5848.     }*/
  5849.     //new code end for visual feedback targetting wrong player balls
  5850.  
  5851.     // Find the first rail hit by the aiming ray
  5852.     D2D1_POINT_2F railHitPoint = rayEnd; // Default to far end if no rail hit
  5853.     float minRailDistSq = rayLength * rayLength;
  5854.     int hitRailIndex = -1; // 0:Left, 1:Right, 2:Top, 3:Bottom
  5855.  
  5856.         // --- Use inner chamfered rim segments (avoid pocket openings) for aim-bounce intersection checks ---
  5857.     //const float rimWidth = 15.0f; // must match rimWidth used elsewhere in the project 15
  5858.     const float rimLeft = TABLE_LEFT + INNER_RIM_THICKNESS;
  5859.     const float rimRight = TABLE_RIGHT - INNER_RIM_THICKNESS;
  5860.     const float rimTop = TABLE_TOP + INNER_RIM_THICKNESS;
  5861.     const float rimBottom = TABLE_BOTTOM - INNER_RIM_THICKNESS;
  5862.  
  5863.     D2D1_POINT_2F currentIntersection;
  5864.     const float gapMargin = 6.0f; // space to keep away from pocket mouth visuals
  5865.  
  5866.     // LEFT inner rim segment (vertical), skip the corner pocket areas
  5867.     {
  5868.         D2D1_POINT_2F segA = D2D1::Point2F(rimLeft, rimTop + CORNER_HOLE_VISUAL_RADIUS + gapMargin);
  5869.         D2D1_POINT_2F segB = D2D1::Point2F(rimLeft, rimBottom - CORNER_HOLE_VISUAL_RADIUS - gapMargin);
  5870.         // Only test if segment is valid
  5871.         if (segB.y > segA.y) {
  5872.             if (LineSegmentIntersection(rayStart, rayEnd, segA, segB, currentIntersection)) {
  5873.                 float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  5874.                 if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 0; }
  5875.             }
  5876.         }
  5877.     }
  5878.  
  5879.     // RIGHT inner rim segment (vertical)
  5880.     {
  5881.         D2D1_POINT_2F segA = D2D1::Point2F(rimRight, rimTop + CORNER_HOLE_VISUAL_RADIUS + gapMargin);
  5882.         D2D1_POINT_2F segB = D2D1::Point2F(rimRight, rimBottom - CORNER_HOLE_VISUAL_RADIUS - gapMargin);
  5883.         if (segB.y > segA.y) {
  5884.             if (LineSegmentIntersection(rayStart, rayEnd, segA, segB, currentIntersection)) {
  5885.                 float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  5886.                 if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 1; }
  5887.             }
  5888.         }
  5889.     }
  5890.  
  5891.     // TOP inner rim — split into left and right segments around the top-middle pocket
  5892.     {
  5893.         float midX = pocketPositions[1].x;
  5894.         float midRadius = GetPocketVisualRadius(1);
  5895.         float leftStartX = rimLeft + CORNER_HOLE_VISUAL_RADIUS + gapMargin;
  5896.         float leftEndX = midX - midRadius - gapMargin;
  5897.         if (leftEndX > leftStartX) {
  5898.             D2D1_POINT_2F segA = D2D1::Point2F(leftStartX, rimTop);
  5899.             D2D1_POINT_2F segB = D2D1::Point2F(leftEndX, rimTop);
  5900.             if (LineSegmentIntersection(rayStart, rayEnd, segA, segB, currentIntersection)) {
  5901.                 float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  5902.                 if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 2; }
  5903.             }
  5904.         }
  5905.  
  5906.         float rightStartX = midX + midRadius + gapMargin;
  5907.         float rightEndX = rimRight - CORNER_HOLE_VISUAL_RADIUS - gapMargin;
  5908.         if (rightEndX > rightStartX) {
  5909.             D2D1_POINT_2F segA = D2D1::Point2F(rightStartX, rimTop);
  5910.             D2D1_POINT_2F segB = D2D1::Point2F(rightEndX, rimTop);
  5911.             if (LineSegmentIntersection(rayStart, rayEnd, segA, segB, currentIntersection)) {
  5912.                 float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  5913.                 if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 2; }
  5914.             }
  5915.         }
  5916.     }
  5917.  
  5918.     // BOTTOM inner rim — split into left and right around bottom-middle pocket
  5919.     {
  5920.         float midX = pocketPositions[4].x; // bottom-middle pocket index is 4
  5921.         float midRadius = GetPocketVisualRadius(4);
  5922.         float leftStartX = rimLeft + CORNER_HOLE_VISUAL_RADIUS + gapMargin;
  5923.         float leftEndX = midX - midRadius - gapMargin;
  5924.         if (leftEndX > leftStartX) {
  5925.             D2D1_POINT_2F segA = D2D1::Point2F(leftStartX, rimBottom);
  5926.             D2D1_POINT_2F segB = D2D1::Point2F(leftEndX, rimBottom);
  5927.             if (LineSegmentIntersection(rayStart, rayEnd, segA, segB, currentIntersection)) {
  5928.                 float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  5929.                 if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 3; }
  5930.             }
  5931.         }
  5932.  
  5933.         float rightStartX = midX + midRadius + gapMargin;
  5934.         float rightEndX = rimRight - CORNER_HOLE_VISUAL_RADIUS - gapMargin;
  5935.         if (rightEndX > rightStartX) {
  5936.             D2D1_POINT_2F segA = D2D1::Point2F(rightStartX, rimBottom);
  5937.             D2D1_POINT_2F segB = D2D1::Point2F(rightEndX, rimBottom);
  5938.             if (LineSegmentIntersection(rayStart, rayEnd, segA, segB, currentIntersection)) {
  5939.                 float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  5940.                 if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 3; }
  5941.             }
  5942.         }
  5943.     }
  5944.  
  5945.     /*// Define table edge segments for intersection checks
  5946.     D2D1_POINT_2F topLeft = D2D1::Point2F(TABLE_LEFT, TABLE_TOP);
  5947.     D2D1_POINT_2F topRight = D2D1::Point2F(TABLE_RIGHT, TABLE_TOP);
  5948.     D2D1_POINT_2F bottomLeft = D2D1::Point2F(TABLE_LEFT, TABLE_BOTTOM);
  5949.     D2D1_POINT_2F bottomRight = D2D1::Point2F(TABLE_RIGHT, TABLE_BOTTOM);
  5950.  
  5951.     D2D1_POINT_2F currentIntersection;
  5952.  
  5953.     // Check Left Rail
  5954.     if (LineSegmentIntersection(rayStart, rayEnd, topLeft, bottomLeft, currentIntersection)) {
  5955.         float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  5956.         if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 0; }
  5957.     }
  5958.     // Check Right Rail
  5959.     if (LineSegmentIntersection(rayStart, rayEnd, topRight, bottomRight, currentIntersection)) {
  5960.         float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  5961.         if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 1; }
  5962.     }
  5963.     // Check Top Rail
  5964.     if (LineSegmentIntersection(rayStart, rayEnd, topLeft, topRight, currentIntersection)) {
  5965.         float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  5966.         if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 2; }
  5967.     }
  5968.     // Check Bottom Rail
  5969.     if (LineSegmentIntersection(rayStart, rayEnd, bottomLeft, bottomRight, currentIntersection)) {
  5970.         float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  5971.         if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 3; }
  5972.     }*/
  5973.  
  5974.     //gpt5code start
  5975.  
  5976.     // --- FALLBACK: If the aiming ray did NOT hit any inner-rim segment (i.e. it goes through a pocket),
  5977. // clamp the aiming line to the table felt perimeter so it never draws past the felt/pocket holes.
  5978. // We compute intersections with the table rectangle edges and pick the nearest one.
  5979.     if (railHitPoint.x == rayEnd.x && railHitPoint.y == rayEnd.y) {
  5980.         // table outer edges (felt perimeter)
  5981.         D2D1_POINT_2F edgeA[4] = {
  5982.             { TABLE_LEFT,  TABLE_TOP },    // top-left
  5983.             { TABLE_RIGHT, TABLE_TOP },    // top-right
  5984.             { TABLE_RIGHT, TABLE_BOTTOM }, // bottom-right
  5985.             { TABLE_LEFT,  TABLE_BOTTOM }  // bottom-left
  5986.         };
  5987.         D2D1_POINT_2F edgeB[4] = {
  5988.             { TABLE_RIGHT, TABLE_TOP },    // top
  5989.             { TABLE_RIGHT, TABLE_BOTTOM }, // right
  5990.             { TABLE_LEFT,  TABLE_BOTTOM }, // bottom
  5991.             { TABLE_LEFT,  TABLE_TOP }     // left
  5992.         };
  5993.  
  5994.         D2D1_POINT_2F tableIntersection;
  5995.         for (int ei = 0; ei < 4; ++ei) {
  5996.             if (LineSegmentIntersection(rayStart, rayEnd, edgeA[ei], edgeB[ei], tableIntersection)) {
  5997.                 float distSq = GetDistanceSq(rayStart.x, rayStart.y, tableIntersection.x, tableIntersection.y);
  5998.                 if (distSq < minRailDistSq) {
  5999.                     minRailDistSq = distSq;
  6000.                     railHitPoint = tableIntersection;
  6001.                     // Map edge index to hitRailIndex semantics (0:left,1:right,2:top,3:bottom)
  6002.                     if (ei == 0) hitRailIndex = 2; // top
  6003.                     else if (ei == 1) hitRailIndex = 1; // right
  6004.                     else if (ei == 2) hitRailIndex = 3; // bottom
  6005.                     else hitRailIndex = 0; // left
  6006.                 }
  6007.             }
  6008.         }
  6009.     }
  6010.     //gpt5code end
  6011.  
  6012.     // --- Determine final aim line end point ---
  6013.     D2D1_POINT_2F finalLineEnd = railHitPoint; // Assume rail hit first
  6014.     bool aimingAtRail = true;
  6015.  
  6016.     if (hitBall && firstHitDistSq < minRailDistSq) {
  6017.         // Ball collision is closer than rail collision
  6018.         finalLineEnd = ballCollisionPoint; // End line at the point of contact on the ball
  6019.         aimingAtRail = false;
  6020.     }
  6021.  
  6022.     // --- Draw Primary Aiming Line ---
  6023.     pRT->DrawLine(rayStart, finalLineEnd, pBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  6024.  
  6025.     // --- Draw Target Circle/Indicator ---
  6026.     D2D1_ELLIPSE targetCircle = D2D1::Ellipse(finalLineEnd, BALL_RADIUS / 2.0f, BALL_RADIUS / 2.0f);
  6027.     pRT->DrawEllipse(&targetCircle, pBrush, 1.0f);
  6028.  
  6029.     // --- Draw Projection/Reflection Lines ---
  6030.     if (!aimingAtRail && hitBall) {
  6031.         // Aiming at a ball: Draw Ghost Cue Ball and Target Ball Projection
  6032.         D2D1_ELLIPSE ghostCue = D2D1::Ellipse(ballCollisionPoint, BALL_RADIUS, BALL_RADIUS); // Ghost ball at contact point
  6033.         pRT->DrawEllipse(ghostCue, pGhostBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  6034.  
  6035.         // Calculate target ball projection based on impact line (cue collision point -> target center)
  6036.         float targetProjectionAngle = atan2f(hitBall->y - ballCollisionPoint.y, hitBall->x - ballCollisionPoint.x);
  6037.         // Clamp angle calculation if distance is tiny
  6038.         if (GetDistanceSq(hitBall->x, hitBall->y, ballCollisionPoint.x, ballCollisionPoint.y) < 1.0f) {
  6039.             targetProjectionAngle = cueAngle; // Fallback if overlapping
  6040.         }
  6041.  
  6042.         D2D1_POINT_2F targetStartPoint = D2D1::Point2F(hitBall->x, hitBall->y);
  6043.         D2D1_POINT_2F targetProjectionEnd = D2D1::Point2F(
  6044.             hitBall->x + cosf(targetProjectionAngle) * 50.0f, // Projection length 50 units
  6045.             hitBall->y + sinf(targetProjectionAngle) * 50.0f
  6046.         );
  6047.         // Draw solid line for target projection
  6048.         //pRT->DrawLine(targetStartPoint, targetProjectionEnd, pBrush, 1.0f);
  6049.  
  6050.     //new code start
  6051.  
  6052.                 // Dual trajectory with edge-aware contact simulation
  6053.         D2D1_POINT_2F dir = {
  6054.             targetProjectionEnd.x - targetStartPoint.x,
  6055.             targetProjectionEnd.y - targetStartPoint.y
  6056.         };
  6057.         float dirLen = sqrtf(dir.x * dir.x + dir.y * dir.y);
  6058.         dir.x /= dirLen;
  6059.         dir.y /= dirLen;
  6060.  
  6061.         D2D1_POINT_2F perp = { -dir.y, dir.x };
  6062.  
  6063.         // Approximate cue ball center by reversing from tip
  6064.         D2D1_POINT_2F cueBallCenterForGhostHit = { // Renamed for clarity if you use it elsewhere
  6065.             targetStartPoint.x - dir.x * BALL_RADIUS,
  6066.             targetStartPoint.y - dir.y * BALL_RADIUS
  6067.         };
  6068.  
  6069.         // REAL contact-ball center - use your physics object's center:
  6070.         // (replace 'objectBallPos' with whatever you actually call it)
  6071.         // (targetStartPoint is already hitBall->x, hitBall->y)
  6072.         D2D1_POINT_2F contactBallCenter = targetStartPoint; // Corrected: Use the object ball's actual center
  6073.         //D2D1_POINT_2F contactBallCenter = D2D1::Point2F(hitBall->x, hitBall->y);
  6074.  
  6075.        // The 'offset' calculation below uses 'cueBallCenterForGhostHit' (originally 'cueBallCenter').
  6076.        // This will result in 'offset' being 0 because 'cueBallCenterForGhostHit' is defined
  6077.        // such that (targetStartPoint - cueBallCenterForGhostHit) is parallel to 'dir',
  6078.        // and 'perp' is perpendicular to 'dir'.
  6079.        // Consider Change 2 if this 'offset' is not behaving as intended for the secondary line.
  6080.         /*float offset = ((targetStartPoint.x - cueBallCenterForGhostHit.x) * perp.x +
  6081.             (targetStartPoint.y - cueBallCenterForGhostHit.y) * perp.y);*/
  6082.             /*float offset = ((targetStartPoint.x - cueBallCenter.x) * perp.x +
  6083.                 (targetStartPoint.y - cueBallCenter.y) * perp.y);
  6084.             float absOffset = fabsf(offset);
  6085.             float side = (offset >= 0 ? 1.0f : -1.0f);*/
  6086.  
  6087.             // Use actual cue ball center for offset calculation if 'offset' is meant to quantify the cut
  6088.         D2D1_POINT_2F actualCueBallPhysicalCenter = D2D1::Point2F(cueBall->x, cueBall->y); // This is also rayStart
  6089.  
  6090.         // Offset calculation based on actual cue ball position relative to the 'dir' line through targetStartPoint
  6091.         float offset = ((targetStartPoint.x - actualCueBallPhysicalCenter.x) * perp.x +
  6092.             (targetStartPoint.y - actualCueBallPhysicalCenter.y) * perp.y);
  6093.         float absOffset = fabsf(offset);
  6094.         float side = (offset >= 0 ? 1.0f : -1.0f);
  6095.  
  6096.  
  6097.         // Actual contact point on target ball edge
  6098.         D2D1_POINT_2F contactPoint = {
  6099.         contactBallCenter.x + perp.x * BALL_RADIUS * side,
  6100.         contactBallCenter.y + perp.y * BALL_RADIUS * side
  6101.         };
  6102.  
  6103.         // Tangent (cut shot) path from contact point
  6104.             // Tangent (cut shot) path: from contact point to contact ball center
  6105.         D2D1_POINT_2F objectBallDir = {
  6106.             contactBallCenter.x - contactPoint.x,
  6107.             contactBallCenter.y - contactPoint.y
  6108.         };
  6109.         float oLen = sqrtf(objectBallDir.x * objectBallDir.x + objectBallDir.y * objectBallDir.y);
  6110.         if (oLen != 0.0f) {
  6111.             objectBallDir.x /= oLen;
  6112.             objectBallDir.y /= oLen;
  6113.         }
  6114.  
  6115.         const float PRIMARY_LEN = 150.0f; //default=150.0f
  6116.         const float SECONDARY_LEN = 150.0f; //default=150.0f
  6117.         const float STRAIGHT_EPSILON = BALL_RADIUS * 0.05f;
  6118.  
  6119.         D2D1_POINT_2F primaryEnd = {
  6120.             targetStartPoint.x + dir.x * PRIMARY_LEN,
  6121.             targetStartPoint.y + dir.y * PRIMARY_LEN
  6122.         };
  6123.  
  6124.         // Secondary line starts from the contact ball's center
  6125.         D2D1_POINT_2F secondaryStart = contactBallCenter;
  6126.         D2D1_POINT_2F secondaryEnd = {
  6127.             secondaryStart.x + objectBallDir.x * SECONDARY_LEN,
  6128.             secondaryStart.y + objectBallDir.y * SECONDARY_LEN
  6129.         };
  6130.  
  6131.         if (absOffset < STRAIGHT_EPSILON)  // straight shot?
  6132.         {
  6133.             // Straight: secondary behind primary
  6134.                     // secondary behind primary {pDashedStyle param at end}
  6135.             pRT->DrawLine(secondaryStart, secondaryEnd, pPurpleBrush, 2.0f);
  6136.             //pRT->DrawLine(secondaryStart, secondaryEnd, pGhostBrush, 1.0f);
  6137.             pRT->DrawLine(targetStartPoint, primaryEnd, pCyanBrush, 2.0f);
  6138.             //pRT->DrawLine(targetStartPoint, primaryEnd, pBrush, 1.0f);
  6139.         }
  6140.         else
  6141.         {
  6142.             // Cut shot: both visible
  6143.                     // both visible for cut shot
  6144.             pRT->DrawLine(secondaryStart, secondaryEnd, pPurpleBrush, 2.0f);
  6145.             //pRT->DrawLine(secondaryStart, secondaryEnd, pGhostBrush, 1.0f);
  6146.             pRT->DrawLine(targetStartPoint, primaryEnd, pCyanBrush, 2.0f);
  6147.             //pRT->DrawLine(targetStartPoint, primaryEnd, pBrush, 1.0f);
  6148.         }
  6149.         // End improved trajectory logic
  6150.  
  6151.     //new code end
  6152.  
  6153.         // -- Cue Ball Path after collision (Optional, requires physics) --
  6154.         // Very simplified: Assume cue deflects, angle depends on cut angle.
  6155.         // float cutAngle = acosf(cosf(cueAngle - targetProjectionAngle)); // Angle between paths
  6156.         // float cueDeflectionAngle = ? // Depends on cutAngle, spin, etc. Hard to predict accurately.
  6157.         // D2D1_POINT_2F cueProjectionEnd = ...
  6158.         // pRT->DrawLine(ballCollisionPoint, cueProjectionEnd, pGhostBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  6159.  
  6160.         // --- Accuracy Comment ---
  6161.         // Note: The visual accuracy of this projection, especially for cut shots (hitting the ball off-center)
  6162.         // or shots with spin, is limited by the simplified physics model. Real pool physics involves
  6163.         // collision-induced throw, spin transfer, and cue ball deflection not fully simulated here.
  6164.         // The ghost ball method shows the *ideal* line for a center-cue hit without spin.
  6165.  
  6166.     }
  6167.     else if (aimingAtRail && hitRailIndex != -1) {
  6168.         // Aiming at a rail: Draw reflection line
  6169.         float reflectAngle = cueAngle;
  6170.         // Reflect angle based on which rail was hit
  6171.         if (hitRailIndex == 0 || hitRailIndex == 1) { // Left or Right rail
  6172.             reflectAngle = PI - cueAngle; // Reflect horizontal component
  6173.         }
  6174.         else { // Top or Bottom rail
  6175.             reflectAngle = -cueAngle; // Reflect vertical component
  6176.         }
  6177.         // Normalize angle if needed (atan2 usually handles this)
  6178.         while (reflectAngle > PI) reflectAngle -= 2 * PI;
  6179.         while (reflectAngle <= -PI) reflectAngle += 2 * PI;
  6180.  
  6181.  
  6182.         float reflectionLength = 60.0f; // Length of the reflection line
  6183.         D2D1_POINT_2F reflectionEnd = D2D1::Point2F(
  6184.             finalLineEnd.x + cosf(reflectAngle) * reflectionLength,
  6185.             finalLineEnd.y + sinf(reflectAngle) * reflectionLength
  6186.         );
  6187.  
  6188.         // Draw the reflection line (e.g., using a different color/style)
  6189.         pRT->DrawLine(finalLineEnd, reflectionEnd, pReflectBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  6190.     }
  6191.  
  6192.     // Release resources
  6193.     SafeRelease(&pBrush);
  6194.     SafeRelease(&pGhostBrush);
  6195.     SafeRelease(&pCueBrush);
  6196.     SafeRelease(&pReflectBrush); // Release new brush
  6197.     SafeRelease(&pCyanBrush);
  6198.     SafeRelease(&pPurpleBrush);
  6199.     SafeRelease(&pDashedStyle);
  6200. }
  6201.  
  6202.  
  6203. void DrawUI(ID2D1RenderTarget* pRT) {
  6204.     if (!pTextFormat || !pLargeTextFormat) return;
  6205.  
  6206.     ID2D1SolidColorBrush* pBrush = nullptr;
  6207.     pRT->CreateSolidColorBrush(UI_TEXT_COLOR, &pBrush);
  6208.     if (!pBrush) return;
  6209.  
  6210.     //new code
  6211.     // --- Always draw AI's 8?Ball call arrow when it's Player?2's turn and AI has called ---
  6212.     //if (isPlayer2AI && currentPlayer == 2 && calledPocketP2 >= 0) {
  6213.         // FIX: This condition correctly shows the AI's called pocket arrow.
  6214.     if (isPlayer2AI && IsPlayerOnEightBall(2) && calledPocketP2 >= 0) {
  6215.         // pocket index that AI called
  6216.         int idx = calledPocketP2;
  6217.         // draw large blue arrow
  6218.         ID2D1SolidColorBrush* pArrow = nullptr;
  6219.         pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrow);
  6220.         if (pArrow) {
  6221.             auto P = pocketPositions[idx];
  6222.             D2D1_POINT_2F tri[3] = {
  6223.                 { P.x - 15.0f, P.y - 40.0f },
  6224.                 { P.x + 15.0f, P.y - 40.0f },
  6225.                 { P.x       , P.y - 10.0f }
  6226.             };
  6227.             ID2D1PathGeometry* geom = nullptr;
  6228.             pFactory->CreatePathGeometry(&geom);
  6229.             ID2D1GeometrySink* sink = nullptr;
  6230.             geom->Open(&sink);
  6231.             sink->BeginFigure(tri[0], D2D1_FIGURE_BEGIN_FILLED);
  6232.             sink->AddLines(&tri[1], 2);
  6233.             sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  6234.             sink->Close();
  6235.             pRT->FillGeometry(geom, pArrow);
  6236.             SafeRelease(&sink);
  6237.             SafeRelease(&geom);
  6238.             SafeRelease(&pArrow);
  6239.         }
  6240.         // draw “Choose a pocket...” prompt
  6241.         D2D1_RECT_F txt = D2D1::RectF(
  6242.             TABLE_LEFT,
  6243.             TABLE_BOTTOM + WOODEN_RAIL_THICKNESS + 5.0f,
  6244.             TABLE_RIGHT,
  6245.             TABLE_BOTTOM + WOODEN_RAIL_THICKNESS + 30.0f
  6246.         );
  6247.         pRT->DrawText(
  6248.             L"AI has called this pocket",
  6249.             (UINT32)wcslen(L"AI has called this pocket"),
  6250.             pTextFormat,
  6251.             &txt,
  6252.             pBrush
  6253.         );
  6254.         // note: no return here — we still draw fouls/turn text underneath
  6255.     }
  6256.     //end new code
  6257.  
  6258.     // --- Player Info Area (Top Left/Right) --- (Unchanged)
  6259.     float uiTop = TABLE_TOP - 80;
  6260.     float uiHeight = 60;
  6261.     float p1Left = TABLE_LEFT;
  6262.     float p1Width = 150;
  6263.     float p2Left = TABLE_RIGHT - p1Width;
  6264.     D2D1_RECT_F p1Rect = D2D1::RectF(p1Left, uiTop, p1Left + p1Width, uiTop + uiHeight);
  6265.     D2D1_RECT_F p2Rect = D2D1::RectF(p2Left, uiTop, p2Left + p1Width, uiTop + uiHeight);
  6266.  
  6267.     // Player 1 Info Text (Unchanged)
  6268.     std::wostringstream oss1;
  6269.     oss1 << player1Info.name.c_str();
  6270.     if (player1Info.assignedType != BallType::NONE) {
  6271.         if (IsPlayerOnEightBall(1)) {
  6272.             oss1 << L"\nON 8-BALL";
  6273.         }
  6274.         else {
  6275.             oss1 << L"\n" << ((player1Info.assignedType == BallType::SOLID) ? L"Solids" : L"Stripes");
  6276.             oss1 << L" [" << player1Info.ballsPocketedCount << L"/7]";
  6277.         }
  6278.     }
  6279.     else {
  6280.         oss1 << L"\n(Undecided)";
  6281.     }
  6282.     //pRT->DrawText(oss1.str().c_str(), (UINT32)oss1.str().length(), pTextFormat, &p1Rect, pBrush);
  6283.     // Use bold for current player, normal for the other
  6284.     IDWriteTextFormat* pFormatP1 = (currentPlayer == 1) ? pTextFormatBold : pTextFormat;
  6285.     pRT->DrawText(oss1.str().c_str(), (UINT32)oss1.str().length(), pFormatP1, &p1Rect, pBrush);
  6286.  
  6287.     // Draw Player 1 Side Ball
  6288.     if (player1Info.assignedType != BallType::NONE)
  6289.     {
  6290.         D2D1_POINT_2F ballCenter = D2D1::Point2F(p1Rect.right + 15.0f, p1Rect.top + uiHeight / 2.0f);
  6291.         float radius = 10.0f;
  6292.         D2D1_ELLIPSE ball = D2D1::Ellipse(ballCenter, radius, radius);
  6293.  
  6294.         if (IsPlayerOnEightBall(1))
  6295.         {
  6296.             // Player is on the 8-ball, draw the 8-ball indicator.
  6297.             ID2D1SolidColorBrush* p8BallBrush = nullptr;
  6298.             pRT->CreateSolidColorBrush(EIGHT_BALL_COLOR, &p8BallBrush);
  6299.             if (p8BallBrush) pRT->FillEllipse(&ball, p8BallBrush);
  6300.             SafeRelease(&p8BallBrush);
  6301.  
  6302.             // Draw the number '8' decal
  6303.             ID2D1SolidColorBrush* pNumWhite = nullptr, * pNumBlack = nullptr;
  6304.             pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pNumWhite);
  6305.             pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pNumBlack);
  6306.             if (pBallNumFormat && pNumWhite && pNumBlack)
  6307.             {
  6308.                 const float decalR = radius * 0.7f;
  6309.                 D2D1_ELLIPSE decal = D2D1::Ellipse(ballCenter, decalR, decalR);
  6310.                 pRT->FillEllipse(&decal, pNumWhite);
  6311.                 pRT->DrawEllipse(&decal, pNumBlack, 0.8f);
  6312.                 wchar_t numText[] = L"8";
  6313.                 D2D1_RECT_F layout = { ballCenter.x - decalR, ballCenter.y - decalR, ballCenter.x + decalR, ballCenter.y + decalR };
  6314.                 pRT->DrawText(numText, (UINT32)wcslen(numText), pBallNumFormat, &layout, pNumBlack);
  6315.             }
  6316.  
  6317.             // If stripes, draw a stripe band
  6318.             SafeRelease(&pNumWhite);
  6319.             SafeRelease(&pNumBlack);
  6320.         }
  6321.         else
  6322.         {
  6323.             // Default: Draw the player's assigned ball type (solid/stripe).
  6324.             ID2D1SolidColorBrush* pBallBrush = nullptr;
  6325.             D2D1_COLOR_F ballColor = (player1Info.assignedType == BallType::SOLID) ?
  6326.                 D2D1::ColorF(1.0f, 1.0f, 0.0f) : D2D1::ColorF(1.0f, 0.0f, 0.0f);
  6327.             pRT->CreateSolidColorBrush(ballColor, &pBallBrush);
  6328.             if (pBallBrush)
  6329.             {
  6330.                 pRT->FillEllipse(&ball, pBallBrush);
  6331.                 SafeRelease(&pBallBrush);
  6332.                 if (player1Info.assignedType == BallType::STRIPE)
  6333.                 {
  6334.                     ID2D1SolidColorBrush* pStripeBrush = nullptr;
  6335.                     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
  6336.                     if (pStripeBrush)
  6337.                     {
  6338.                         D2D1_RECT_F stripeRect = { ballCenter.x - radius, ballCenter.y - 3.0f, ballCenter.x + radius, ballCenter.y + 3.0f };
  6339.                         pRT->FillRectangle(&stripeRect, pStripeBrush);
  6340.                         SafeRelease(&pStripeBrush);
  6341.                     }
  6342.                 }
  6343.             }
  6344.         }
  6345.         // Draw a border around the indicator ball, regardless of type.
  6346.         ID2D1SolidColorBrush* pBorderBrush = nullptr;
  6347.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
  6348.         if (pBorderBrush) pRT->DrawEllipse(&ball, pBorderBrush, 1.5f);
  6349.         SafeRelease(&pBorderBrush);
  6350.     }
  6351.     //}
  6352. //}
  6353. //}
  6354.  
  6355.  
  6356. // Player 2 Info Text (Unchanged)
  6357.     std::wostringstream oss2;
  6358.     oss2 << player2Info.name.c_str();
  6359.     if (player2Info.assignedType != BallType::NONE) {
  6360.         if (IsPlayerOnEightBall(2)) {
  6361.             oss2 << L"\nON 8-BALL";
  6362.         }
  6363.         else {
  6364.             oss2 << L"\n" << ((player2Info.assignedType == BallType::SOLID) ? L"Solids" : L"Stripes");
  6365.             oss2 << L" [" << player2Info.ballsPocketedCount << L"/7]";
  6366.         }
  6367.     }
  6368.     else {
  6369.         oss2 << L"\n(Undecided)";
  6370.     }
  6371.  
  6372.     //pRT->DrawText(oss2.str().c_str(), (UINT32)oss2.str().length(), pTextFormat, &p2Rect, pBrush);
  6373.     // Use bold for current player, normal for the other
  6374.     IDWriteTextFormat* pFormatP2 = (currentPlayer == 2) ? pTextFormatBold : pTextFormat;
  6375.     pRT->DrawText(oss2.str().c_str(), (UINT32)oss2.str().length(), pFormatP2, &p2Rect, pBrush);
  6376.  
  6377.     // Draw Player 2 Side Ball
  6378.     if (player2Info.assignedType != BallType::NONE)
  6379.     {
  6380.         D2D1_POINT_2F ballCenter = D2D1::Point2F(p2Rect.left - 15.0f, p2Rect.top + uiHeight / 2.0f);
  6381.         float radius = 10.0f;
  6382.         D2D1_ELLIPSE ball = D2D1::Ellipse(ballCenter, radius, radius);
  6383.  
  6384.         if (IsPlayerOnEightBall(2))
  6385.         {
  6386.             // Player is on the 8-ball, draw the 8-ball indicator.
  6387.             ID2D1SolidColorBrush* p8BallBrush = nullptr;
  6388.             pRT->CreateSolidColorBrush(EIGHT_BALL_COLOR, &p8BallBrush);
  6389.             if (p8BallBrush) pRT->FillEllipse(&ball, p8BallBrush);
  6390.             SafeRelease(&p8BallBrush);
  6391.  
  6392.             // Draw the number '8' decal
  6393.             ID2D1SolidColorBrush* pNumWhite = nullptr, * pNumBlack = nullptr;
  6394.             pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pNumWhite);
  6395.             pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pNumBlack);
  6396.             if (pBallNumFormat && pNumWhite && pNumBlack)
  6397.             {
  6398.                 const float decalR = radius * 0.7f;
  6399.                 D2D1_ELLIPSE decal = D2D1::Ellipse(ballCenter, decalR, decalR);
  6400.                 pRT->FillEllipse(&decal, pNumWhite);
  6401.                 pRT->DrawEllipse(&decal, pNumBlack, 0.8f);
  6402.                 wchar_t numText[] = L"8";
  6403.                 D2D1_RECT_F layout = { ballCenter.x - decalR, ballCenter.y - decalR, ballCenter.x + decalR, ballCenter.y + decalR };
  6404.                 pRT->DrawText(numText, (UINT32)wcslen(numText), pBallNumFormat, &layout, pNumBlack);
  6405.             }
  6406.  
  6407.             // If stripes, draw a stripe band
  6408.             SafeRelease(&pNumWhite);
  6409.             SafeRelease(&pNumBlack);
  6410.         }
  6411.         else
  6412.         {
  6413.             // Default: Draw the player's assigned ball type (solid/stripe).
  6414.             ID2D1SolidColorBrush* pBallBrush = nullptr;
  6415.             D2D1_COLOR_F ballColor = (player2Info.assignedType == BallType::SOLID) ?
  6416.                 D2D1::ColorF(1.0f, 1.0f, 0.0f) : D2D1::ColorF(1.0f, 0.0f, 0.0f);
  6417.             pRT->CreateSolidColorBrush(ballColor, &pBallBrush);
  6418.             if (pBallBrush)
  6419.             {
  6420.                 pRT->FillEllipse(&ball, pBallBrush);
  6421.                 SafeRelease(&pBallBrush);
  6422.                 if (player2Info.assignedType == BallType::STRIPE)
  6423.                 {
  6424.                     ID2D1SolidColorBrush* pStripeBrush = nullptr;
  6425.                     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
  6426.                     if (pStripeBrush)
  6427.                     {
  6428.                         D2D1_RECT_F stripeRect = { ballCenter.x - radius, ballCenter.y - 3.0f, ballCenter.x + radius, ballCenter.y + 3.0f };
  6429.                         pRT->FillRectangle(&stripeRect, pStripeBrush);
  6430.                         SafeRelease(&pStripeBrush);
  6431.                     }
  6432.                 }
  6433.             }
  6434.         }
  6435.         //}
  6436.  
  6437.         // Draw a border around the indicator ball, regardless of type.
  6438.         ID2D1SolidColorBrush* pBorderBrush = nullptr;
  6439.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
  6440.         if (pBorderBrush) pRT->DrawEllipse(&ball, pBorderBrush, 1.5f);
  6441.         SafeRelease(&pBorderBrush);
  6442.     }
  6443.  
  6444.     // --- MODIFIED: Current Turn Arrow (Blue, Bigger, Beside Name) ---
  6445.     ID2D1SolidColorBrush* pArrowBrush = nullptr;
  6446.     pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrowBrush);
  6447.     if (pArrowBrush && currentGameState != GAME_OVER && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  6448.         float arrowSizeBase = 32.0f; // Base size for width/height offsets (4x original ~8)
  6449.         float arrowCenterY = p1Rect.top + uiHeight / 2.0f; // Center vertically with text box
  6450.         float arrowTipX, arrowBackX;
  6451.  
  6452.         D2D1_RECT_F playerBox = (currentPlayer == 1) ? p1Rect : p2Rect;
  6453.         arrowBackX = playerBox.left - 57.0f; //25.0f
  6454.         arrowTipX = arrowBackX + arrowSizeBase * 0.75f;
  6455.  
  6456.         float notchDepth = 12.0f;  // Increased from 6.0f to make the rectangle longer
  6457.         float notchWidth = 10.0f;
  6458.  
  6459.         float cx = arrowBackX;
  6460.         float cy = arrowCenterY;
  6461.  
  6462.         // Define triangle + rectangle tail shape
  6463.         D2D1_POINT_2F tip = D2D1::Point2F(arrowTipX, cy);                           // tip
  6464.         D2D1_POINT_2F baseTop = D2D1::Point2F(cx, cy - arrowSizeBase / 2.0f);          // triangle top
  6465.         D2D1_POINT_2F baseBot = D2D1::Point2F(cx, cy + arrowSizeBase / 2.0f);          // triangle bottom
  6466.  
  6467.         // Rectangle coordinates for the tail portion:
  6468.         D2D1_POINT_2F r1 = D2D1::Point2F(cx - notchDepth, cy - notchWidth / 2.0f);   // rect top-left
  6469.         D2D1_POINT_2F r2 = D2D1::Point2F(cx, cy - notchWidth / 2.0f);                 // rect top-right
  6470.         D2D1_POINT_2F r3 = D2D1::Point2F(cx, cy + notchWidth / 2.0f);                 // rect bottom-right
  6471.         D2D1_POINT_2F r4 = D2D1::Point2F(cx - notchDepth, cy + notchWidth / 2.0f);    // rect bottom-left
  6472.  
  6473.         ID2D1PathGeometry* pPath = nullptr;
  6474.         if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  6475.             ID2D1GeometrySink* pSink = nullptr;
  6476.             if (SUCCEEDED(pPath->Open(&pSink))) {
  6477.                 pSink->BeginFigure(tip, D2D1_FIGURE_BEGIN_FILLED);
  6478.                 pSink->AddLine(baseTop);
  6479.                 pSink->AddLine(r2); // transition from triangle into rectangle
  6480.                 pSink->AddLine(r1);
  6481.                 pSink->AddLine(r4);
  6482.                 pSink->AddLine(r3);
  6483.                 pSink->AddLine(baseBot);
  6484.                 pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  6485.                 pSink->Close();
  6486.                 SafeRelease(&pSink);
  6487.                 pRT->FillGeometry(pPath, pArrowBrush);
  6488.             }
  6489.             SafeRelease(&pPath);
  6490.         }
  6491.  
  6492.  
  6493.         SafeRelease(&pArrowBrush);
  6494.     }
  6495.  
  6496.     //original
  6497. /*
  6498.     // --- MODIFIED: Current Turn Arrow (Blue, Bigger, Beside Name) ---
  6499.     ID2D1SolidColorBrush* pArrowBrush = nullptr;
  6500.     pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrowBrush);
  6501.     if (pArrowBrush && currentGameState != GAME_OVER && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  6502.         float arrowSizeBase = 32.0f; // Base size for width/height offsets (4x original ~8)
  6503.         float arrowCenterY = p1Rect.top + uiHeight / 2.0f; // Center vertically with text box
  6504.         float arrowTipX, arrowBackX;
  6505.  
  6506.         if (currentPlayer == 1) {
  6507. arrowBackX = p1Rect.left - 25.0f; // Position left of the box
  6508.             arrowTipX = arrowBackX + arrowSizeBase * 0.75f; // Pointy end extends right
  6509.             // Define points for right-pointing arrow
  6510.             //D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
  6511.             //D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
  6512.             //D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
  6513.             // Enhanced arrow with base rectangle intersection
  6514.     float notchDepth = 6.0f; // Depth of square base "stem"
  6515.     float notchWidth = 4.0f; // Thickness of square part
  6516.  
  6517.     D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
  6518.     D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
  6519.     D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX - notchDepth, arrowCenterY - notchWidth / 2.0f); // Square Left-Top
  6520.     D2D1_POINT_2F pt4 = D2D1::Point2F(arrowBackX - notchDepth, arrowCenterY + notchWidth / 2.0f); // Square Left-Bottom
  6521.     D2D1_POINT_2F pt5 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
  6522.  
  6523.  
  6524.     ID2D1PathGeometry* pPath = nullptr;
  6525.     if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  6526.         ID2D1GeometrySink* pSink = nullptr;
  6527.         if (SUCCEEDED(pPath->Open(&pSink))) {
  6528.             pSink->BeginFigure(pt1, D2D1_FIGURE_BEGIN_FILLED);
  6529.             pSink->AddLine(pt2);
  6530.             pSink->AddLine(pt3);
  6531.             pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  6532.             pSink->Close();
  6533.             SafeRelease(&pSink);
  6534.             pRT->FillGeometry(pPath, pArrowBrush);
  6535.         }
  6536.         SafeRelease(&pPath);
  6537.     }
  6538.         }
  6539.  
  6540.  
  6541.         //==================else player 2
  6542.         else { // Player 2
  6543.          // Player 2: Arrow left of P2 box, pointing right (or right of P2 box pointing left?)
  6544.          // Let's keep it consistent: Arrow left of the active player's box, pointing right.
  6545. // Let's keep it consistent: Arrow left of the active player's box, pointing right.
  6546. arrowBackX = p2Rect.left - 25.0f; // Position left of the box
  6547. arrowTipX = arrowBackX + arrowSizeBase * 0.75f; // Pointy end extends right
  6548. // Define points for right-pointing arrow
  6549. D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
  6550. D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
  6551. D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
  6552.  
  6553. ID2D1PathGeometry* pPath = nullptr;
  6554. if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  6555.     ID2D1GeometrySink* pSink = nullptr;
  6556.     if (SUCCEEDED(pPath->Open(&pSink))) {
  6557.         pSink->BeginFigure(pt1, D2D1_FIGURE_BEGIN_FILLED);
  6558.         pSink->AddLine(pt2);
  6559.         pSink->AddLine(pt3);
  6560.         pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  6561.         pSink->Close();
  6562.         SafeRelease(&pSink);
  6563.         pRT->FillGeometry(pPath, pArrowBrush);
  6564.     }
  6565.     SafeRelease(&pPath);
  6566. }
  6567.         }
  6568.         */
  6569.  
  6570.  
  6571.         // --- Persistent Blue 8?Ball Call Arrow & Prompt ---
  6572.     /*if (calledPocketP1 >= 0 || calledPocketP2 >= 0)
  6573.     {
  6574.         // determine index (default top?right)
  6575.         int idx = (currentPlayer == 1 ? calledPocketP1 : calledPocketP2);
  6576.         if (idx < 0) idx = (currentPlayer == 1 ? calledPocketP2 : calledPocketP1);
  6577.         if (idx < 0) idx = 2;
  6578.  
  6579.         // draw large blue arrow
  6580.         ID2D1SolidColorBrush* pArrow = nullptr;
  6581.         pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrow);
  6582.         if (pArrow) {
  6583.             auto P = pocketPositions[idx];
  6584.             D2D1_POINT_2F tri[3] = {
  6585.                 {P.x - 15.0f, P.y - 40.0f},
  6586.                 {P.x + 15.0f, P.y - 40.0f},
  6587.                 {P.x       , P.y - 10.0f}
  6588.             };
  6589.             ID2D1PathGeometry* geom = nullptr;
  6590.             pFactory->CreatePathGeometry(&geom);
  6591.             ID2D1GeometrySink* sink = nullptr;
  6592.             geom->Open(&sink);
  6593.             sink->BeginFigure(tri[0], D2D1_FIGURE_BEGIN_FILLED);
  6594.             sink->AddLines(&tri[1], 2);
  6595.             sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  6596.             sink->Close();
  6597.             pRT->FillGeometry(geom, pArrow);
  6598.             SafeRelease(&sink); SafeRelease(&geom); SafeRelease(&pArrow);
  6599.         }
  6600.  
  6601.         // draw prompt
  6602.         D2D1_RECT_F txt = D2D1::RectF(
  6603.             TABLE_LEFT,
  6604.             TABLE_BOTTOM + CUSHION_THICKNESS + 5.0f,
  6605.             TABLE_RIGHT,
  6606.             TABLE_BOTTOM + CUSHION_THICKNESS + 30.0f
  6607.         );
  6608.         pRT->DrawText(
  6609.             L"Choose a pocket...",
  6610.             (UINT32)wcslen(L"Choose a pocket..."),
  6611.             pTextFormat,
  6612.             &txt,
  6613.             pBrush
  6614.         );
  6615.     }*/
  6616.  
  6617.     // --- Persistent Blue 8?Ball Pocket Arrow & Prompt (once called) ---
  6618. /* if (calledPocketP1 >= 0 || calledPocketP2 >= 0)
  6619. {
  6620.     // 1) Determine pocket index
  6621.     int idx = (currentPlayer == 1 ? calledPocketP1 : calledPocketP2);
  6622.     // If the other player had called but it's now your turn, still show that call
  6623.     if (idx < 0) idx = (currentPlayer == 1 ? calledPocketP2 : calledPocketP1);
  6624.     if (idx < 0) idx = 2; // default to top?right if somehow still unset
  6625.  
  6626.     // 2) Draw large blue arrow
  6627.     ID2D1SolidColorBrush* pArrow = nullptr;
  6628.     pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrow);
  6629.     if (pArrow) {
  6630.         auto P = pocketPositions[idx];
  6631.         D2D1_POINT_2F tri[3] = {
  6632.             { P.x - 15.0f, P.y - 40.0f },
  6633.             { P.x + 15.0f, P.y - 40.0f },
  6634.             { P.x       , P.y - 10.0f }
  6635.         };
  6636.         ID2D1PathGeometry* geom = nullptr;
  6637.         pFactory->CreatePathGeometry(&geom);
  6638.         ID2D1GeometrySink* sink = nullptr;
  6639.         geom->Open(&sink);
  6640.         sink->BeginFigure(tri[0], D2D1_FIGURE_BEGIN_FILLED);
  6641.         sink->AddLines(&tri[1], 2);
  6642.         sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  6643.         sink->Close();
  6644.         pRT->FillGeometry(geom, pArrow);
  6645.         SafeRelease(&sink);
  6646.         SafeRelease(&geom);
  6647.         SafeRelease(&pArrow);
  6648.     }
  6649.  
  6650.     // 3) Draw persistent prompt text
  6651.     D2D1_RECT_F txt = D2D1::RectF(
  6652.         TABLE_LEFT,
  6653.         TABLE_BOTTOM + CUSHION_THICKNESS + 5.0f,
  6654.         TABLE_RIGHT,
  6655.         TABLE_BOTTOM + CUSHION_THICKNESS + 30.0f
  6656.     );
  6657.     pRT->DrawText(
  6658.         L"Choose a pocket...",
  6659.         (UINT32)wcslen(L"Choose a pocket..."),
  6660.         pTextFormat,
  6661.         &txt,
  6662.         pBrush
  6663.     );
  6664.     // Note: no 'return'; allow foul/turn text to draw beneath if needed
  6665. } */
  6666.  
  6667. // new code ends here
  6668.  
  6669.         // --- MODIFIED: Foul Text (Large Red, Bottom Center) ---
  6670.     // Draw if the logical foul flag is set OR if the display counter is active.
  6671. if ((foulCommitted || foulDisplayCounter > 0) && currentGameState != SHOT_IN_PROGRESS) {
  6672.         ID2D1SolidColorBrush* pFoulBrush = nullptr;
  6673.         pRT->CreateSolidColorBrush(FOUL_TEXT_COLOR, &pFoulBrush);
  6674.         if (pFoulBrush && pLargeTextFormat) {
  6675.             // Calculate Rect for bottom-middle area
  6676.             float foulWidth = 200.0f; // Adjust width as needed
  6677.             float foulHeight = 60.0f;
  6678.             float foulLeft = TABLE_LEFT + (TABLE_WIDTH / 2.0f) - (foulWidth / 2.0f);
  6679.             // Position below the pocketed balls bar
  6680.             float foulTop = pocketedBallsBarRect.bottom + 10.0f;
  6681.             D2D1_RECT_F foulRect = D2D1::RectF(foulLeft, foulTop, foulLeft + foulWidth, foulTop + foulHeight);
  6682.  
  6683.             // --- Set text alignment to center for foul text ---
  6684.             pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  6685.             pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  6686.  
  6687.             pRT->DrawText(L"FOUL!", 5, pLargeTextFormat, &foulRect, pFoulBrush);
  6688.  
  6689.             // --- Restore default alignment for large text if needed elsewhere ---
  6690.             // pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
  6691.             // pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  6692.  
  6693.             SafeRelease(&pFoulBrush);
  6694.         }
  6695.     }
  6696.  
  6697.     // Decrement the FOUL display counter here (per-frame). Keep it >= 0.
  6698.     if (foulDisplayCounter > 0) foulDisplayCounter--;
  6699.  
  6700.     // --- Blue Arrow & Prompt for 8?Ball Call (while choosing or after called) ---
  6701.     if ((currentGameState == CHOOSING_POCKET_P1
  6702.         || currentGameState == CHOOSING_POCKET_P2)
  6703.         || (calledPocketP1 >= 0 || calledPocketP2 >= 0))
  6704.     {
  6705.         // determine index:
  6706.         //  - if a call exists, use it
  6707.         //  - if still choosing, use hover if any
  6708.         // determine index: use only the clicked call; default to top?right if unset
  6709.         int idx = (currentPlayer == 1 ? calledPocketP1 : calledPocketP2);
  6710.         if (idx < 0) idx = 2;
  6711.  
  6712.         // draw large blue arrow
  6713.         ID2D1SolidColorBrush* pArrow = nullptr;
  6714.         pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrow);
  6715.         if (pArrow) {
  6716.             auto P = pocketPositions[idx];
  6717.             D2D1_POINT_2F tri[3] = {
  6718.                 {P.x - 15.0f, P.y - 40.0f},
  6719.                 {P.x + 15.0f, P.y - 40.0f},
  6720.                 {P.x       , P.y - 10.0f}
  6721.             };
  6722.             ID2D1PathGeometry* geom = nullptr;
  6723.             pFactory->CreatePathGeometry(&geom);
  6724.             ID2D1GeometrySink* sink = nullptr;
  6725.             geom->Open(&sink);
  6726.             sink->BeginFigure(tri[0], D2D1_FIGURE_BEGIN_FILLED);
  6727.             sink->AddLines(&tri[1], 2);
  6728.             sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  6729.             sink->Close();
  6730.             pRT->FillGeometry(geom, pArrow);
  6731.             SafeRelease(&sink); SafeRelease(&geom); SafeRelease(&pArrow);
  6732.         }
  6733.  
  6734.         // draw prompt below pockets
  6735.         D2D1_RECT_F txt = D2D1::RectF(
  6736.             TABLE_LEFT,
  6737.             TABLE_BOTTOM + WOODEN_RAIL_THICKNESS + 5.0f,
  6738.             TABLE_RIGHT,
  6739.             TABLE_BOTTOM + WOODEN_RAIL_THICKNESS + 30.0f
  6740.         );
  6741.         pRT->DrawText(
  6742.             L"Choose a pocket...",
  6743.             (UINT32)wcslen(L"Choose a pocket..."),
  6744.             pTextFormat,
  6745.             &txt,
  6746.             pBrush
  6747.         );
  6748.         // do NOT return here; allow foul/turn text to display under the arrow
  6749.     }
  6750.  
  6751.     // Removed Obsolete
  6752.     /*
  6753.     // --- 8-Ball Pocket Selection Arrow & Prompt ---
  6754.     if (currentGameState == CHOOSING_POCKET_P1 || currentGameState == CHOOSING_POCKET_P2) {
  6755.         // Determine which pocket to highlight (default to Top-Right if unset)
  6756.         int idx = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  6757.         if (idx < 0) idx = 2;
  6758.  
  6759.         // Draw the downward arrow
  6760.         ID2D1SolidColorBrush* pArrowBrush = nullptr;
  6761.         pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrowBrush);
  6762.         if (pArrowBrush) {
  6763.             D2D1_POINT_2F P = pocketPositions[idx];
  6764.             D2D1_POINT_2F tri[3] = {
  6765.                 {P.x - 10.0f, P.y - 30.0f},
  6766.                 {P.x + 10.0f, P.y - 30.0f},
  6767.                 {P.x        , P.y - 10.0f}
  6768.             };
  6769.             ID2D1PathGeometry* geom = nullptr;
  6770.             pFactory->CreatePathGeometry(&geom);
  6771.             ID2D1GeometrySink* sink = nullptr;
  6772.             geom->Open(&sink);
  6773.             sink->BeginFigure(tri[0], D2D1_FIGURE_BEGIN_FILLED);
  6774.             sink->AddLines(&tri[1], 2);
  6775.             sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  6776.             sink->Close();
  6777.             pRT->FillGeometry(geom, pArrowBrush);
  6778.             SafeRelease(&sink);
  6779.             SafeRelease(&geom);
  6780.             SafeRelease(&pArrowBrush);
  6781.         }
  6782.  
  6783.         // Draw “Choose a pocket...” text under the table
  6784.         D2D1_RECT_F prompt = D2D1::RectF(
  6785.             TABLE_LEFT,
  6786.             TABLE_BOTTOM + CUSHION_THICKNESS + 5.0f,
  6787.             TABLE_RIGHT,
  6788.             TABLE_BOTTOM + CUSHION_THICKNESS + 30.0f
  6789.         );
  6790.         pRT->DrawText(
  6791.             L"Choose a pocket...",
  6792.             (UINT32)wcslen(L"Choose a pocket..."),
  6793.             pTextFormat,
  6794.             &prompt,
  6795.             pBrush
  6796.         );
  6797.  
  6798.         return; // Skip normal turn/foul text
  6799.     }
  6800.     */
  6801.  
  6802.  
  6803.     // Show AI Thinking State (Unchanged from previous step)
  6804.     if (currentGameState == AI_THINKING && pTextFormat) {
  6805.         ID2D1SolidColorBrush* pThinkingBrush = nullptr;
  6806.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Orange), &pThinkingBrush);
  6807.         if (pThinkingBrush) {
  6808.             D2D1_RECT_F thinkingRect = p2Rect;
  6809.             thinkingRect.top += 20; // Offset within P2 box
  6810.             // Ensure default text alignment for this
  6811.             pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  6812.             pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  6813.             pRT->DrawText(L"Thinking...", 11, pTextFormat, &thinkingRect, pThinkingBrush);
  6814.             SafeRelease(&pThinkingBrush);
  6815.         }
  6816.     }
  6817.  
  6818.     SafeRelease(&pBrush);
  6819.  
  6820.     // --- Draw CHEAT MODE label if active ---
  6821.     if (cheatModeEnabled) {
  6822.         ID2D1SolidColorBrush* pCheatBrush = nullptr;
  6823.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Red), &pCheatBrush);
  6824.         if (pCheatBrush && pTextFormat) {
  6825.             D2D1_RECT_F cheatTextRect = D2D1::RectF(
  6826.                 TABLE_LEFT + 10.0f,
  6827.                 TABLE_TOP + 10.0f,
  6828.                 TABLE_LEFT + 200.0f,
  6829.                 TABLE_TOP + 40.0f
  6830.             );
  6831.             pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
  6832.             pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
  6833.             pRT->DrawText(L"CHEAT MODE ON", static_cast<UINT32>(wcslen(L"CHEAT MODE ON")), pTextFormat, &cheatTextRect, pCheatBrush);
  6834.         }
  6835.         SafeRelease(&pCheatBrush);
  6836.     }
  6837. }
  6838.  
  6839. void DrawPowerMeter(ID2D1RenderTarget* pRT) {
  6840.     // Draw Border
  6841.     ID2D1SolidColorBrush* pBorderBrush = nullptr;
  6842.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
  6843.     if (!pBorderBrush) return;
  6844.     pRT->DrawRectangle(&powerMeterRect, pBorderBrush, 2.0f);
  6845.     SafeRelease(&pBorderBrush);
  6846.  
  6847.     // Create Gradient Fill
  6848.     ID2D1GradientStopCollection* pGradientStops = nullptr;
  6849.     ID2D1LinearGradientBrush* pGradientBrush = nullptr;
  6850.     D2D1_GRADIENT_STOP gradientStops[4];
  6851.     gradientStops[0].position = 0.0f;
  6852.     gradientStops[0].color = D2D1::ColorF(D2D1::ColorF::Green);
  6853.     gradientStops[1].position = 0.45f;
  6854.     gradientStops[1].color = D2D1::ColorF(D2D1::ColorF::Yellow);
  6855.     gradientStops[2].position = 0.7f;
  6856.     gradientStops[2].color = D2D1::ColorF(D2D1::ColorF::Orange);
  6857.     gradientStops[3].position = 1.0f;
  6858.     gradientStops[3].color = D2D1::ColorF(D2D1::ColorF::Red);
  6859.  
  6860.     pRT->CreateGradientStopCollection(gradientStops, 4, &pGradientStops);
  6861.     if (pGradientStops) {
  6862.         D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props = {};
  6863.         props.startPoint = D2D1::Point2F(powerMeterRect.left, powerMeterRect.bottom);
  6864.         props.endPoint = D2D1::Point2F(powerMeterRect.left, powerMeterRect.top);
  6865.         pRT->CreateLinearGradientBrush(props, pGradientStops, &pGradientBrush);
  6866.         SafeRelease(&pGradientStops);
  6867.     }
  6868.  
  6869.     // Calculate Fill Height
  6870.     float fillRatio = 0;
  6871.     //if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
  6872.         // Determine if power meter should reflect shot power (human aiming or AI preparing)
  6873.     bool humanIsAimingPower = isAiming && (currentGameState == AIMING || currentGameState == BREAKING);
  6874.     // NEW Condition: AI is displaying its aim, so show its chosen power
  6875.     bool aiIsVisualizingPower = (isPlayer2AI && currentPlayer == 2 &&
  6876.         currentGameState == AI_THINKING && aiIsDisplayingAim);
  6877.  
  6878.     if (humanIsAimingPower || aiIsVisualizingPower) { // Use the new condition
  6879.         fillRatio = shotPower / MAX_SHOT_POWER;
  6880.     }
  6881.     float fillHeight = (powerMeterRect.bottom - powerMeterRect.top) * fillRatio;
  6882.     D2D1_RECT_F fillRect = D2D1::RectF(
  6883.         powerMeterRect.left,
  6884.         powerMeterRect.bottom - fillHeight,
  6885.         powerMeterRect.right,
  6886.         powerMeterRect.bottom
  6887.     );
  6888.  
  6889.     if (pGradientBrush) {
  6890.         pRT->FillRectangle(&fillRect, pGradientBrush);
  6891.         SafeRelease(&pGradientBrush);
  6892.     }
  6893.  
  6894.     // Draw scale notches
  6895.     ID2D1SolidColorBrush* pNotchBrush = nullptr;
  6896.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pNotchBrush);
  6897.     if (pNotchBrush) {
  6898.         for (int i = 0; i <= 8; ++i) {
  6899.             float y = powerMeterRect.top + (powerMeterRect.bottom - powerMeterRect.top) * (i / 8.0f);
  6900.             pRT->DrawLine(
  6901.                 D2D1::Point2F(powerMeterRect.right + 2.0f, y),
  6902.                 D2D1::Point2F(powerMeterRect.right + 8.0f, y),
  6903.                 pNotchBrush,
  6904.                 1.5f
  6905.             );
  6906.         }
  6907.         SafeRelease(&pNotchBrush);
  6908.     }
  6909.  
  6910.     // Draw "Power" Label Below Meter
  6911.     if (pTextFormat) {
  6912.         ID2D1SolidColorBrush* pTextBrush = nullptr;
  6913.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pTextBrush);
  6914.         if (pTextBrush) {
  6915.             D2D1_RECT_F textRect = D2D1::RectF(
  6916.                 powerMeterRect.left - 20.0f,
  6917.                 powerMeterRect.bottom + 8.0f,
  6918.                 powerMeterRect.right + 20.0f,
  6919.                 powerMeterRect.bottom + 38.0f
  6920.             );
  6921.             pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  6922.             pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
  6923.             pRT->DrawText(L"Power", 5, pTextFormat, &textRect, pTextBrush);
  6924.             SafeRelease(&pTextBrush);
  6925.         }
  6926.     }
  6927.  
  6928.     // Draw Glow Effect if fully charged or fading out
  6929.     static float glowPulse = 0.0f;
  6930.     static bool glowIncreasing = true;
  6931.     static float glowFadeOut = 0.0f; // NEW: tracks fading out
  6932.  
  6933.     if (shotPower >= MAX_SHOT_POWER * 0.99f) {
  6934.         // While fully charged, keep pulsing normally
  6935.         if (glowIncreasing) {
  6936.             glowPulse += 0.02f;
  6937.             if (glowPulse >= 1.0f) glowIncreasing = false;
  6938.         }
  6939.         else {
  6940.             glowPulse -= 0.02f;
  6941.             if (glowPulse <= 0.0f) glowIncreasing = true;
  6942.         }
  6943.         glowFadeOut = 1.0f; // Reset fade out to full
  6944.     }
  6945.     else if (glowFadeOut > 0.0f) {
  6946.         // If shot fired, gradually fade out
  6947.         glowFadeOut -= 0.02f;
  6948.         if (glowFadeOut < 0.0f) glowFadeOut = 0.0f;
  6949.     }
  6950.  
  6951.     if (glowFadeOut > 0.0f) {
  6952.         ID2D1SolidColorBrush* pGlowBrush = nullptr;
  6953.         float effectiveOpacity = (0.3f + 0.7f * glowPulse) * glowFadeOut;
  6954.         pRT->CreateSolidColorBrush(
  6955.             D2D1::ColorF(D2D1::ColorF::Red, effectiveOpacity),
  6956.             &pGlowBrush
  6957.         );
  6958.         if (pGlowBrush) {
  6959.             float glowCenterX = (powerMeterRect.left + powerMeterRect.right) / 2.0f;
  6960.             float glowCenterY = powerMeterRect.top;
  6961.             D2D1_ELLIPSE glowEllipse = D2D1::Ellipse(
  6962.                 D2D1::Point2F(glowCenterX, glowCenterY - 10.0f),
  6963.                 12.0f + 3.0f * glowPulse,
  6964.                 6.0f + 2.0f * glowPulse
  6965.             );
  6966.             pRT->FillEllipse(&glowEllipse, pGlowBrush);
  6967.             SafeRelease(&pGlowBrush);
  6968.         }
  6969.     }
  6970. }
  6971.  
  6972. void DrawSpinIndicator(ID2D1RenderTarget* pRT) {
  6973.     ID2D1SolidColorBrush* pWhiteBrush = nullptr;
  6974.     ID2D1SolidColorBrush* pRedBrush = nullptr;
  6975.  
  6976.     pRT->CreateSolidColorBrush(CUE_BALL_COLOR, &pWhiteBrush);
  6977.     pRT->CreateSolidColorBrush(ENGLISH_DOT_COLOR, &pRedBrush);
  6978.  
  6979.     if (!pWhiteBrush || !pRedBrush) {
  6980.         SafeRelease(&pWhiteBrush);
  6981.         SafeRelease(&pRedBrush);
  6982.         return;
  6983.     }
  6984.  
  6985.     // Draw White Ball Background
  6986.     D2D1_ELLIPSE bgEllipse = D2D1::Ellipse(spinIndicatorCenter, spinIndicatorRadius, spinIndicatorRadius);
  6987.     pRT->FillEllipse(&bgEllipse, pWhiteBrush);
  6988.     pRT->DrawEllipse(&bgEllipse, pRedBrush, 0.5f); // Thin red border
  6989.  
  6990.  
  6991.     // Draw Red Dot for Spin Position
  6992.     float dotRadius = 4.0f;
  6993.     float dotX = spinIndicatorCenter.x + cueSpinX * (spinIndicatorRadius - dotRadius); // Keep dot inside edge
  6994.     float dotY = spinIndicatorCenter.y + cueSpinY * (spinIndicatorRadius - dotRadius);
  6995.     D2D1_ELLIPSE dotEllipse = D2D1::Ellipse(D2D1::Point2F(dotX, dotY), dotRadius, dotRadius);
  6996.     pRT->FillEllipse(&dotEllipse, pRedBrush);
  6997.  
  6998.     SafeRelease(&pWhiteBrush);
  6999.     SafeRelease(&pRedBrush);
  7000. }
  7001.  
  7002.  
  7003. void DrawPocketedBallsIndicator(ID2D1RenderTarget* pRT) {
  7004.     ID2D1SolidColorBrush* pBgBrush = nullptr;
  7005.     ID2D1SolidColorBrush* pBallBrush = nullptr;
  7006.  
  7007.     // Ensure render target is valid before proceeding
  7008.     if (!pRT) return;
  7009.  
  7010.     HRESULT hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black, 0.8f), &pBgBrush); // Semi-transparent black
  7011.     if (FAILED(hr)) { SafeRelease(&pBgBrush); return; } // Exit if brush creation fails
  7012.  
  7013.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0), &pBallBrush); // Placeholder, color will be set per ball
  7014.     if (FAILED(hr)) {
  7015.         SafeRelease(&pBgBrush);
  7016.         SafeRelease(&pBallBrush);
  7017.         return; // Exit if brush creation fails
  7018.     }
  7019.  
  7020.     // Draw the background bar (rounded rect)
  7021.     D2D1_ROUNDED_RECT roundedRect = D2D1::RoundedRect(pocketedBallsBarRect, 10.0f, 10.0f); // Corner radius 10
  7022.     float baseAlpha = 0.8f;
  7023.     float flashBoost = pocketFlashTimer * 0.5f; // Make flash effect boost alpha slightly
  7024.     float finalAlpha = std::min(1.0f, baseAlpha + flashBoost);
  7025.     pBgBrush->SetOpacity(finalAlpha);
  7026.     pRT->FillRoundedRectangle(&roundedRect, pBgBrush);
  7027.     pBgBrush->SetOpacity(1.0f); // Reset opacity after drawing
  7028.  
  7029.     // --- Draw small circles for pocketed balls inside the bar ---
  7030.  
  7031.     // Calculate dimensions based on the bar's height for better scaling
  7032.     float barHeight = pocketedBallsBarRect.bottom - pocketedBallsBarRect.top;
  7033.     float ballDisplayRadius = barHeight * 0.30f; // Make balls slightly smaller relative to bar height
  7034.     float spacing = ballDisplayRadius * 2.2f; // Adjust spacing slightly
  7035.     float padding = spacing * 0.75f; // Add padding from the edges
  7036.     float center_Y = pocketedBallsBarRect.top + barHeight / 2.0f; // Vertical center
  7037.  
  7038.     // Starting X positions with padding
  7039.     float currentX_P1 = pocketedBallsBarRect.left + padding;
  7040.     float currentX_P2 = pocketedBallsBarRect.right - padding; // Start from right edge minus padding
  7041.  
  7042.     int p1DrawnCount = 0;
  7043.     int p2DrawnCount = 0;
  7044.     const int maxBallsToShow = 7; // Max balls per player in the bar
  7045.  
  7046.     for (const auto& b : balls) {
  7047.         if (b.isPocketed) {
  7048.             // Skip cue ball and 8-ball in this indicator
  7049.             if (b.id == 0 || b.id == 8) continue;
  7050.  
  7051.             bool isPlayer1Ball = (player1Info.assignedType != BallType::NONE && b.type == player1Info.assignedType);
  7052.             bool isPlayer2Ball = (player2Info.assignedType != BallType::NONE && b.type == player2Info.assignedType);
  7053.  
  7054.             if (isPlayer1Ball && p1DrawnCount < maxBallsToShow) {
  7055.                 pBallBrush->SetColor(b.color);
  7056.                 // Draw P1 balls from left to right
  7057.                 D2D1_ELLIPSE ballEllipse = D2D1::Ellipse(D2D1::Point2F(currentX_P1 + p1DrawnCount * spacing, center_Y), ballDisplayRadius, ballDisplayRadius);
  7058.                 pRT->FillEllipse(&ballEllipse, pBallBrush);
  7059.                 p1DrawnCount++;
  7060.             }
  7061.             else if (isPlayer2Ball && p2DrawnCount < maxBallsToShow) {
  7062.                 pBallBrush->SetColor(b.color);
  7063.                 // Draw P2 balls from right to left
  7064.                 D2D1_ELLIPSE ballEllipse = D2D1::Ellipse(D2D1::Point2F(currentX_P2 - p2DrawnCount * spacing, center_Y), ballDisplayRadius, ballDisplayRadius);
  7065.                 pRT->FillEllipse(&ballEllipse, pBallBrush);
  7066.                 p2DrawnCount++;
  7067.             }
  7068.             // Note: Balls pocketed before assignment or opponent balls are intentionally not shown here.
  7069.             // You could add logic here to display them differently if needed (e.g., smaller, grayed out).
  7070.         }
  7071.     }
  7072.  
  7073.     SafeRelease(&pBgBrush);
  7074.     SafeRelease(&pBallBrush);
  7075. }
  7076.  
  7077. void DrawBallInHandIndicator(ID2D1RenderTarget* pRT) {
  7078.     if (!isDraggingCueBall && (currentGameState != BALL_IN_HAND_P1 && currentGameState != BALL_IN_HAND_P2 && currentGameState != PRE_BREAK_PLACEMENT)) {
  7079.         return; // Only show when placing/dragging
  7080.     }
  7081.  
  7082.     Ball* cueBall = GetCueBall();
  7083.     if (!cueBall) return;
  7084.  
  7085.     ID2D1SolidColorBrush* pGhostBrush = nullptr;
  7086.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.6f), &pGhostBrush); // Semi-transparent white
  7087.  
  7088.     if (pGhostBrush) {
  7089.         D2D1_POINT_2F drawPos;
  7090.         if (isDraggingCueBall) {
  7091.             drawPos = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y);
  7092.         }
  7093.         else {
  7094.             // If not dragging but in placement state, show at current ball pos
  7095.             drawPos = D2D1::Point2F(cueBall->x, cueBall->y);
  7096.         }
  7097.  
  7098.         // Check if the placement is valid before drawing differently?
  7099.         bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  7100.         bool isValid = IsValidCueBallPosition(drawPos.x, drawPos.y, behindHeadstring);
  7101.  
  7102.         if (!isValid) {
  7103.             // Maybe draw red outline if invalid placement?
  7104.             pGhostBrush->SetColor(D2D1::ColorF(D2D1::ColorF::Red, 0.6f));
  7105.         }
  7106.  
  7107.  
  7108.         D2D1_ELLIPSE ghostEllipse = D2D1::Ellipse(drawPos, BALL_RADIUS, BALL_RADIUS);
  7109.         pRT->FillEllipse(&ghostEllipse, pGhostBrush);
  7110.         pRT->DrawEllipse(&ghostEllipse, pGhostBrush, 1.0f); // Outline
  7111.  
  7112.         SafeRelease(&pGhostBrush);
  7113.     }
  7114. }
  7115.  
  7116. void DrawPocketSelectionIndicator(ID2D1RenderTarget* pRT) {
  7117.     if (!pFactory) return; // Need factory to create geometry
  7118.  
  7119.     int pocketToIndicate = -1;
  7120.     if (currentGameState == CHOOSING_POCKET_P1 || (currentPlayer == 1 && IsPlayerOnEightBall(1))) {
  7121.         pocketToIndicate = (calledPocketP1 >= 0) ? calledPocketP1 : currentlyHoveredPocket;
  7122.     }
  7123.     else if (currentGameState == CHOOSING_POCKET_P2 || (currentPlayer == 2 && IsPlayerOnEightBall(2))) {
  7124.         pocketToIndicate = (calledPocketP2 >= 0) ? calledPocketP2 : currentlyHoveredPocket;
  7125.     }
  7126.  
  7127.     if (pocketToIndicate < 0 || pocketToIndicate > 5) {
  7128.         return;
  7129.     }
  7130.  
  7131.     ID2D1SolidColorBrush* pArrowBrush = nullptr;
  7132.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Yellow, 0.9f), &pArrowBrush);
  7133.     if (!pArrowBrush) return;
  7134.  
  7135.     // FIXED: Get the correct radius for the indicated pocket
  7136.     float currentPocketRadius = (pocketToIndicate == 1 || pocketToIndicate == 4) ? MIDDLE_HOLE_VISUAL_RADIUS : CORNER_HOLE_VISUAL_RADIUS;
  7137.  
  7138.     D2D1_POINT_2F targetPocketCenter = pocketPositions[pocketToIndicate];
  7139.     // FIXED: Calculate arrow dimensions based on the correct pocket radius
  7140.     float pocketVis = GetPocketVisualRadius(pocketToIndicate);
  7141.     float arrowHeadSize = pocketVis * 0.5f;
  7142.     float arrowShaftLength = pocketVis * 0.3f;
  7143.     float arrowShaftWidth = arrowHeadSize * 0.4f;
  7144.     float verticalOffsetFromPocketCenter = pocketVis * 1.6f;
  7145.  
  7146.     D2D1_POINT_2F tip, baseLeft, baseRight, shaftTopLeft, shaftTopRight, shaftBottomLeft, shaftBottomRight;
  7147.  
  7148.     // Determine arrow direction based on pocket position (top or bottom row)
  7149.     if (targetPocketCenter.y == TABLE_TOP) { // Top row pockets
  7150.         tip = D2D1::Point2F(targetPocketCenter.x, targetPocketCenter.y - verticalOffsetFromPocketCenter - arrowHeadSize);
  7151.         baseLeft = D2D1::Point2F(targetPocketCenter.x - arrowHeadSize / 2.0f, targetPocketCenter.y - verticalOffsetFromPocketCenter);
  7152.         baseRight = D2D1::Point2F(targetPocketCenter.x + arrowHeadSize / 2.0f, targetPocketCenter.y - verticalOffsetFromPocketCenter);
  7153.         shaftTopLeft = D2D1::Point2F(targetPocketCenter.x - arrowShaftWidth / 2.0f, baseLeft.y + arrowShaftLength);
  7154.         shaftTopRight = D2D1::Point2F(targetPocketCenter.x + arrowShaftWidth / 2.0f, baseRight.y + arrowShaftLength);
  7155.         shaftBottomLeft = D2D1::Point2F(targetPocketCenter.x - arrowShaftWidth / 2.0f, baseLeft.y);
  7156.         shaftBottomRight = D2D1::Point2F(targetPocketCenter.x + arrowShaftWidth / 2.0f, baseRight.y);
  7157.     }
  7158.     else { // Bottom row pockets
  7159.         tip = D2D1::Point2F(targetPocketCenter.x, targetPocketCenter.y + verticalOffsetFromPocketCenter + arrowHeadSize);
  7160.         baseLeft = D2D1::Point2F(targetPocketCenter.x - arrowHeadSize / 2.0f, targetPocketCenter.y + verticalOffsetFromPocketCenter);
  7161.         baseRight = D2D1::Point2F(targetPocketCenter.x + arrowHeadSize / 2.0f, targetPocketCenter.y + verticalOffsetFromPocketCenter);
  7162.         shaftTopLeft = D2D1::Point2F(targetPocketCenter.x - arrowShaftWidth / 2.0f, baseLeft.y);
  7163.         shaftTopRight = D2D1::Point2F(targetPocketCenter.x + arrowShaftWidth / 2.0f, baseRight.y);
  7164.         shaftBottomLeft = D2D1::Point2F(targetPocketCenter.x - arrowShaftWidth / 2.0f, baseLeft.y - arrowShaftLength);
  7165.         shaftBottomRight = D2D1::Point2F(targetPocketCenter.x + arrowShaftWidth / 2.0f, baseRight.y - arrowShaftLength);
  7166.     }
  7167.     ID2D1PathGeometry* pPath = nullptr;
  7168.     if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  7169.         ID2D1GeometrySink* pSink = nullptr;
  7170.         if (SUCCEEDED(pPath->Open(&pSink))) {
  7171.             pSink->BeginFigure(tip, D2D1_FIGURE_BEGIN_FILLED);
  7172.             pSink->AddLine(baseLeft); pSink->AddLine(shaftBottomLeft); pSink->AddLine(shaftTopLeft);
  7173.             pSink->AddLine(shaftTopRight); pSink->AddLine(shaftBottomRight); pSink->AddLine(baseRight);
  7174.             pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  7175.             pSink->Close();
  7176.             SafeRelease(&pSink);
  7177.             pRT->FillGeometry(pPath, pArrowBrush);
  7178.         }
  7179.         SafeRelease(&pPath);
  7180.     }
  7181.     SafeRelease(&pArrowBrush);
  7182. }
  7183. ```
  7184.  
  7185. ==++ Here's the full source for (file 2/3 (No OOP-based)) "resource.h"::: ++==
  7186. ```resource.h
  7187. //{{NO_DEPENDENCIES}}
  7188. // Microsoft Visual C++ generated include file.
  7189. // Used by Yahoo-8Ball-Pool-Clone.rc
  7190. //
  7191. #define IDI_ICON1                       101
  7192. // --- NEW Resource IDs (Define these in your .rc file / resource.h) ---
  7193. #define IDD_NEWGAMEDLG 106
  7194. #define IDC_RADIO_2P   1003
  7195. #define IDC_RADIO_CPU  1005
  7196. #define IDC_GROUP_AI   1006
  7197. #define IDC_RADIO_EASY 1007
  7198. #define IDC_RADIO_MEDIUM 1008
  7199. #define IDC_RADIO_HARD 1009
  7200. // --- NEW Resource IDs for Opening Break ---
  7201. #define IDC_GROUP_BREAK_MODE 1010
  7202. #define IDC_RADIO_CPU_BREAK  1011
  7203. #define IDC_RADIO_P1_BREAK   1012
  7204. #define IDC_RADIO_FLIP_BREAK 1013
  7205. // --- NEW Resource ID for Table Color Dropdown ---
  7206. #define IDC_COMBO_TABLECOLOR 1014
  7207. // Standard IDOK is usually defined, otherwise define it (e.g., #define IDOK 1)
  7208.  
  7209. // Next default values for new objects
  7210. //
  7211. #ifdef APSTUDIO_INVOKED
  7212. #ifndef APSTUDIO_READONLY_SYMBOLS
  7213. #define _APS_NEXT_RESOURCE_VALUE        102
  7214. #define _APS_NEXT_COMMAND_VALUE         40002 // Incremented
  7215. #define _APS_NEXT_CONTROL_VALUE         1014 // Incremented
  7216. #define _APS_NEXT_SYMED_VALUE           101
  7217. #endif
  7218. #endif
  7219.  
  7220. ```
  7221.  
  7222. ==++ Here's the full source for (file 3/3 (No OOP-based)) "Yahoo-8Ball-Pool-Clone.rc"::: ++==
  7223. ```Yahoo-8Ball-Pool-Clone.rc
  7224. // Microsoft Visual C++ generated resource script.
  7225. //
  7226. #include "resource.h"
  7227.  
  7228. #define APSTUDIO_READONLY_SYMBOLS
  7229. /////////////////////////////////////////////////////////////////////////////
  7230. //
  7231. // Generated from the TEXTINCLUDE 2 resource.
  7232. //
  7233. #include "winres.h"
  7234.  
  7235. /////////////////////////////////////////////////////////////////////////////
  7236. #undef APSTUDIO_READONLY_SYMBOLS
  7237.  
  7238. /////////////////////////////////////////////////////////////////////////////
  7239. // English (United States) resources
  7240.  
  7241. #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
  7242. LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
  7243. #pragma code_page(1252)
  7244.  
  7245. #ifdef APSTUDIO_INVOKED
  7246. /////////////////////////////////////////////////////////////////////////////
  7247. //
  7248. // TEXTINCLUDE
  7249. //
  7250.  
  7251. 1 TEXTINCLUDE
  7252. BEGIN
  7253. "resource.h\0"
  7254. END
  7255.  
  7256. 2 TEXTINCLUDE
  7257. BEGIN
  7258. "#include ""winres.h""\r\n"
  7259. "\0"
  7260. END
  7261.  
  7262. 3 TEXTINCLUDE
  7263. BEGIN
  7264. "\r\n"
  7265. "\0"
  7266. END
  7267.  
  7268. #endif    // APSTUDIO_INVOKED
  7269.  
  7270.  
  7271. /////////////////////////////////////////////////////////////////////////////
  7272. //
  7273. // Icon
  7274. //
  7275.  
  7276. // Icon with lowest ID value placed first to ensure application icon
  7277. // remains consistent on all systems.
  7278. IDI_ICON1               ICON                    "D:\\Download\\8Ball_Colored.ico"
  7279.  
  7280. #endif    // English (United States) resources
  7281. /////////////////////////////////////////////////////////////////////////////
  7282.  
  7283.  
  7284.  
  7285. #ifndef APSTUDIO_INVOKED
  7286. /////////////////////////////////////////////////////////////////////////////
  7287. //
  7288. // Generated from the TEXTINCLUDE 3 resource.
  7289. //
  7290.  
  7291.  
  7292. /////////////////////////////////////////////////////////////////////////////
  7293. #endif    // not APSTUDIO_INVOKED
  7294.  
  7295. #include <windows.h> // Needed for control styles like WS_GROUP, BS_AUTORADIOBUTTON etc.
  7296.  
  7297. /////////////////////////////////////////////////////////////////////////////
  7298. //
  7299. // Dialog
  7300. //
  7301.  
  7302. IDD_NEWGAMEDLG DIALOGEX 0, 0, 220, 185 // Dialog position (x, y) and size (width, height) in Dialog Units (DLUs) - Increased Height
  7303. STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
  7304. CAPTION "New 8-Ball Game"
  7305. FONT 8, "MS Shell Dlg", 400, 0, 0x1 // Standard dialog font
  7306. BEGIN
  7307. // --- Game Mode Selection ---
  7308. // Group Box for Game Mode (Optional visually, but helps structure)
  7309. GROUPBOX        "Game Mode", IDC_STATIC, 7, 7, 90, 50
  7310.  
  7311. // "2 Player" Radio Button (First in this group)
  7312. CONTROL         "&2 Player (Human vs Human)", IDC_RADIO_2P, "Button",
  7313. BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP, 14, 20, 80, 10
  7314.  
  7315. // "Human vs CPU" Radio Button
  7316. CONTROL         "Human vs &CPU", IDC_RADIO_CPU, "Button",
  7317. BS_AUTORADIOBUTTON | WS_TABSTOP, 14, 35, 70, 10
  7318.  
  7319. // --- NEW: Table Color Selection ---
  7320. LTEXT           "Table Color:", IDC_STATIC, 7, 65, 50, 8
  7321. COMBOBOX        IDC_COMBO_TABLECOLOR, 7, 75, 90, 60,
  7322. CBS_DROPDOWNLIST | CBS_HASSTRINGS | WS_VSCROLL | WS_TABSTOP
  7323.  
  7324.  
  7325. // --- AI Difficulty Selection (Inside its own Group Box) ---
  7326. GROUPBOX        "AI Difficulty", IDC_GROUP_AI, 118, 7, 95, 70
  7327.  
  7328. // "Easy" Radio Button (First in the AI group)
  7329. CONTROL         "&Easy", IDC_RADIO_EASY, "Button",
  7330. BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP, 125, 20, 60, 10
  7331.  
  7332. // "Medium" Radio Button
  7333. CONTROL         "&Medium", IDC_RADIO_MEDIUM, "Button",
  7334. BS_AUTORADIOBUTTON | WS_TABSTOP, 125, 35, 60, 10
  7335.  
  7336. // "Hard" Radio Button
  7337. CONTROL         "&Hard", IDC_RADIO_HARD, "Button",
  7338. BS_AUTORADIOBUTTON | WS_TABSTOP, 125, 50, 60, 10
  7339.  
  7340. // --- Opening Break Modes (For Versus CPU Only) ---
  7341. GROUPBOX        "Opening Break Modes:", IDC_GROUP_BREAK_MODE, 118, 82, 95, 60
  7342.  
  7343. // "CPU Break" Radio Button (Default for this group)
  7344. CONTROL         "&CPU Break", IDC_RADIO_CPU_BREAK, "Button",
  7345. BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP, 125, 95, 70, 10
  7346.  
  7347. // "P1 Break" Radio Button
  7348. CONTROL         "&P1 Break", IDC_RADIO_P1_BREAK, "Button",
  7349. BS_AUTORADIOBUTTON | WS_TABSTOP, 125, 110, 70, 10
  7350.  
  7351. // "FlipCoin Break" Radio Button
  7352. CONTROL         "&FlipCoin Break", IDC_RADIO_FLIP_BREAK, "Button",
  7353. BS_AUTORADIOBUTTON | WS_TABSTOP, 125, 125, 70, 10
  7354.  
  7355.  
  7356. // --- Standard Buttons ---
  7357. DEFPUSHBUTTON   "Start", IDOK, 55, 160, 50, 14 // Default button (Enter key) - Adjusted Y position
  7358. PUSHBUTTON      "Cancel", IDCANCEL, 115, 160, 50, 14 // Adjusted Y position
  7359. END
  7360. ```
Advertisement
Add Comment
Please, Sign In to add comment