alien_fx_fiend

2D Pool C++ D2DImplemented Raster Mask Advanced HitTesting Pixel-Perfect (High-Precision) Collision

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