alien_fx_fiend

2D StickPool C++ D2D Visual Feedback Pocketing Wrong Balls (FINALVER)

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