alien_fx_fiend

2D StickPool D2D C++ DrawAimingAidsDoneGeminiCollisionDetectToDo Bkp

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