· 3 months ago · Jun 27, 2025, 01:30 PM
1#define WIN32_LEAN_AND_MEAN
2#define NOMINMAX
3#include <windows.h>
4#include <d2d1.h>
5#include <dwrite.h>
6#include <fstream> // For file I/O
7#include <iostream> // For some basic I/O, though not strictly necessary for just file ops
8#include <vector>
9#include <cmath>
10#include <string>
11#include <sstream> // Required for wostringstream
12#include <algorithm> // Required for std::max, std::min
13#include <ctime> // Required for srand, time
14#include <cstdlib> // Required for srand, rand (often included by others, but good practice)
15#include <commctrl.h> // Needed for radio buttons etc. in dialog (if using native controls)
16#include <mmsystem.h> // For PlaySound
17#include <tchar.h> //midi func
18#include <thread>
19#include <atomic>
20#include "resource.h"
21
22#pragma comment(lib, "Comctl32.lib") // Link against common controls library
23#pragma comment(lib, "d2d1.lib")
24#pragma comment(lib, "dwrite.lib")
25#pragma comment(lib, "Winmm.lib") // Link against Windows Multimedia library
26
27// --- Constants ---
28const float PI = 3.1415926535f;
29const float BALL_RADIUS = 10.0f;
30const float TABLE_LEFT = 100.0f;
31const float TABLE_TOP = 100.0f;
32const float TABLE_WIDTH = 700.0f;
33const float TABLE_HEIGHT = 350.0f;
34const float TABLE_RIGHT = TABLE_LEFT + TABLE_WIDTH;
35const float TABLE_BOTTOM = TABLE_TOP + TABLE_HEIGHT;
36const float CUSHION_THICKNESS = 20.0f;
37const float HOLE_VISUAL_RADIUS = 22.0f; // Visual size of the hole
38const float POCKET_RADIUS = HOLE_VISUAL_RADIUS * 1.05f; // Make detection radius slightly larger // Make detection radius match visual size (or slightly larger)
39const float MAX_SHOT_POWER = 15.0f;
40const float FRICTION = 0.985f; // Friction factor per frame
41const float MIN_VELOCITY_SQ = 0.01f * 0.01f; // Stop balls below this squared velocity
42const float HEADSTRING_X = TABLE_LEFT + TABLE_WIDTH * 0.30f; // 30% line
43const float RACK_POS_X = TABLE_LEFT + TABLE_WIDTH * 0.65f; // 65% line for rack apex
44const float RACK_POS_Y = TABLE_TOP + TABLE_HEIGHT / 2.0f;
45const UINT ID_TIMER = 1;
46const int TARGET_FPS = 60; // Target frames per second for timer
47
48// --- Enums ---
49// --- MODIFIED/NEW Enums ---
50enum GameState {
51 SHOWING_DIALOG, // NEW: Game is waiting for initial dialog input
52 PRE_BREAK_PLACEMENT,// Player placing cue ball for break
53 BREAKING, // Player is aiming/shooting the break shot
54 AIMING, // Player is aiming
55 AI_THINKING, // NEW: AI is calculating its move
56 SHOT_IN_PROGRESS, // Balls are moving
57 ASSIGNING_BALLS, // Turn after break where ball types are assigned
58 PLAYER1_TURN,
59 PLAYER2_TURN,
60 BALL_IN_HAND_P1,
61 BALL_IN_HAND_P2,
62 GAME_OVER
63};
64
65enum BallType {
66 NONE,
67 SOLID, // Yellow (1-7)
68 STRIPE, // Red (9-15)
69 EIGHT_BALL, // Black (8)
70 CUE_BALL // White (0)
71};
72
73// NEW Enums for Game Mode and AI Difficulty
74enum GameMode {
75 HUMAN_VS_HUMAN,
76 HUMAN_VS_AI
77};
78
79enum AIDifficulty {
80 EASY,
81 MEDIUM,
82 HARD
83};
84
85enum OpeningBreakMode {
86 CPU_BREAK,
87 P1_BREAK,
88 FLIP_COIN_BREAK
89};
90
91// --- Structs ---
92struct Ball {
93 int id; // 0=Cue, 1-7=Solid, 8=Eight, 9-15=Stripe
94 BallType type;
95 float x, y;
96 float vx, vy;
97 D2D1_COLOR_F color;
98 bool isPocketed;
99};
100
101struct PlayerInfo {
102 BallType assignedType;
103 int ballsPocketedCount;
104 std::wstring name;
105};
106
107// --- Global Variables ---
108
109// Direct2D & DirectWrite
110ID2D1Factory* pFactory = nullptr;
111//ID2D1Factory* g_pD2DFactory = nullptr;
112ID2D1HwndRenderTarget* pRenderTarget = nullptr;
113IDWriteFactory* pDWriteFactory = nullptr;
114IDWriteTextFormat* pTextFormat = nullptr;
115IDWriteTextFormat* pLargeTextFormat = nullptr; // For "Foul!"
116
117// Game State
118HWND hwndMain = nullptr;
119GameState currentGameState = SHOWING_DIALOG; // Start by showing dialog
120std::vector<Ball> balls;
121int currentPlayer = 1; // 1 or 2
122PlayerInfo player1Info = { BallType::NONE, 0, L"Player 1" };
123PlayerInfo player2Info = { BallType::NONE, 0, L"CPU" }; // Default P2 name
124bool foulCommitted = false;
125std::wstring gameOverMessage = L"";
126bool firstBallPocketedAfterBreak = false;
127std::vector<int> pocketedThisTurn;
128// --- NEW: Foul Tracking Globals ---
129int firstHitBallIdThisShot = -1; // ID of the first object ball hit by cue ball (-1 if none)
130bool cueHitObjectBallThisShot = false; // Did cue ball hit an object ball this shot?
131bool railHitAfterContact = false; // Did any ball hit a rail AFTER cue hit an object ball?
132// --- End New Foul Tracking Globals ---
133
134// NEW Game Mode/AI Globals
135GameMode gameMode = HUMAN_VS_HUMAN; // Default mode
136AIDifficulty aiDifficulty = MEDIUM; // Default difficulty
137OpeningBreakMode openingBreakMode = CPU_BREAK; // Default opening break mode
138bool isPlayer2AI = false; // Is Player 2 controlled by AI?
139bool aiTurnPending = false; // Flag: AI needs to take its turn when possible
140// bool aiIsThinking = false; // Replaced by AI_THINKING game state
141// NEW: Flag to indicate if the current shot is the opening break of the game
142bool isOpeningBreakShot = false;
143
144// NEW: For AI shot planning and visualization
145struct AIPlannedShot {
146 float angle;
147 float power;
148 float spinX;
149 float spinY;
150 bool isValid; // Is there a valid shot planned?
151};
152AIPlannedShot aiPlannedShotDetails; // Stores the AI's next shot
153bool aiIsDisplayingAim = false; // True when AI has decided a shot and is in "display aim" mode
154int aiAimDisplayFramesLeft = 0; // How many frames left to display AI aim
155const int AI_AIM_DISPLAY_DURATION_FRAMES = 45; // Approx 0.75 seconds at 60 FPS, adjust as needed
156
157// Input & Aiming
158POINT ptMouse = { 0, 0 };
159bool isAiming = false;
160bool isDraggingCueBall = false;
161// --- ENSURE THIS LINE EXISTS HERE ---
162bool isDraggingStick = false; // True specifically when drag initiated on the stick graphic
163// --- End Ensure ---
164bool isSettingEnglish = false;
165D2D1_POINT_2F aimStartPoint = { 0, 0 };
166float cueAngle = 0.0f;
167float shotPower = 0.0f;
168float cueSpinX = 0.0f; // Range -1 to 1
169float cueSpinY = 0.0f; // Range -1 to 1
170float pocketFlashTimer = 0.0f;
171bool cheatModeEnabled = false; // Cheat Mode toggle (G key)
172int draggingBallId = -1;
173bool keyboardAimingActive = false; // NEW FLAG: true when arrow keys modify aim/power
174MCIDEVICEID midiDeviceID = 0; //midi func
175std::atomic<bool> isMusicPlaying(false); //midi func
176std::thread musicThread; //midi func
177void StartMidi(HWND hwnd, const TCHAR* midiPath);
178void StopMidi();
179
180// UI Element Positions
181D2D1_RECT_F powerMeterRect = { TABLE_RIGHT + CUSHION_THICKNESS + 10, TABLE_TOP, TABLE_RIGHT + CUSHION_THICKNESS + 40, TABLE_BOTTOM };
182D2D1_RECT_F spinIndicatorRect = { TABLE_LEFT - CUSHION_THICKNESS - 60, TABLE_TOP + 20, TABLE_LEFT - CUSHION_THICKNESS - 20, TABLE_TOP + 60 }; // Circle area
183D2D1_POINT_2F spinIndicatorCenter = { spinIndicatorRect.left + (spinIndicatorRect.right - spinIndicatorRect.left) / 2.0f, spinIndicatorRect.top + (spinIndicatorRect.bottom - spinIndicatorRect.top) / 2.0f };
184float spinIndicatorRadius = (spinIndicatorRect.right - spinIndicatorRect.left) / 2.0f;
185D2D1_RECT_F pocketedBallsBarRect = { TABLE_LEFT, TABLE_BOTTOM + CUSHION_THICKNESS + 30, TABLE_RIGHT, TABLE_BOTTOM + CUSHION_THICKNESS + 70 };
186
187// Corrected Pocket Center Positions (aligned with table corners/edges)
188const D2D1_POINT_2F pocketPositions[6] = {
189 {TABLE_LEFT, TABLE_TOP}, // Top-Left
190 {TABLE_LEFT + TABLE_WIDTH / 2.0f, TABLE_TOP}, // Top-Middle
191 {TABLE_RIGHT, TABLE_TOP}, // Top-Right
192 {TABLE_LEFT, TABLE_BOTTOM}, // Bottom-Left
193 {TABLE_LEFT + TABLE_WIDTH / 2.0f, TABLE_BOTTOM}, // Bottom-Middle
194 {TABLE_RIGHT, TABLE_BOTTOM} // Bottom-Right
195};
196
197// Colors
198const D2D1_COLOR_F TABLE_COLOR = D2D1::ColorF(0.1608f, 0.4000f, 0.1765f); // Darker Green NEWCOLOR (0.0f, 0.5f, 0.1f) => (0.1608f, 0.4000f, 0.1765f)
199//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)
200const D2D1_COLOR_F CUSHION_COLOR = D2D1::ColorF(D2D1::ColorF(0.3608f, 0.0275f, 0.0078f)); // NEWCOLOR ::Red => (0.3608f, 0.0275f, 0.0078f)
201//const D2D1_COLOR_F CUSHION_COLOR = D2D1::ColorF(D2D1::ColorF::Red); // NEWCOLOR ::Red => (0.3608f, 0.0275f, 0.0078f)
202const D2D1_COLOR_F POCKET_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
203const D2D1_COLOR_F CUE_BALL_COLOR = D2D1::ColorF(D2D1::ColorF::White);
204const D2D1_COLOR_F EIGHT_BALL_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
205const D2D1_COLOR_F SOLID_COLOR = D2D1::ColorF(D2D1::ColorF::Yellow); // Solids = Yellow
206const D2D1_COLOR_F STRIPE_COLOR = D2D1::ColorF(D2D1::ColorF::Red); // Stripes = Red
207const D2D1_COLOR_F AIM_LINE_COLOR = D2D1::ColorF(D2D1::ColorF::White, 0.7f); // Semi-transparent white
208const D2D1_COLOR_F FOUL_TEXT_COLOR = D2D1::ColorF(D2D1::ColorF::Red);
209const D2D1_COLOR_F TURN_ARROW_COLOR = D2D1::ColorF(0.1333f, 0.7294f, 0.7490f); //NEWCOLOR 0.1333f, 0.7294f, 0.7490f => ::Blue
210//const D2D1_COLOR_F TURN_ARROW_COLOR = D2D1::ColorF(D2D1::ColorF::Blue);
211const D2D1_COLOR_F ENGLISH_DOT_COLOR = D2D1::ColorF(D2D1::ColorF::Red);
212const D2D1_COLOR_F UI_TEXT_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
213
214// --- Forward Declarations ---
215HRESULT CreateDeviceResources();
216void DiscardDeviceResources();
217void OnPaint();
218void OnResize(UINT width, UINT height);
219void InitGame();
220void GameUpdate();
221void UpdatePhysics();
222void CheckCollisions();
223bool CheckPockets(); // Returns true if any ball was pocketed
224void ProcessShotResults();
225void ApplyShot(float power, float angle, float spinX, float spinY);
226void RespawnCueBall(bool behindHeadstring);
227bool AreBallsMoving();
228void SwitchTurns();
229void AssignPlayerBallTypes(BallType firstPocketedType);
230void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed);
231Ball* GetBallById(int id);
232Ball* GetCueBall();
233//void PlayGameMusic(HWND hwnd); //midi func
234void AIBreakShot();
235
236// Drawing Functions
237void DrawScene(ID2D1RenderTarget* pRT);
238void DrawTable(ID2D1RenderTarget* pRT, ID2D1Factory* pFactory);
239void DrawBalls(ID2D1RenderTarget* pRT);
240void DrawCueStick(ID2D1RenderTarget* pRT);
241void DrawAimingAids(ID2D1RenderTarget* pRT);
242void DrawUI(ID2D1RenderTarget* pRT);
243void DrawPowerMeter(ID2D1RenderTarget* pRT);
244void DrawSpinIndicator(ID2D1RenderTarget* pRT);
245void DrawPocketedBallsIndicator(ID2D1RenderTarget* pRT);
246void DrawBallInHandIndicator(ID2D1RenderTarget* pRT);
247
248// Helper Functions
249float GetDistance(float x1, float y1, float x2, float y2);
250float GetDistanceSq(float x1, float y1, float x2, float y2);
251bool IsValidCueBallPosition(float x, float y, bool checkHeadstring);
252template <typename T> void SafeRelease(T** ppT);
253// --- ADD FORWARD DECLARATION FOR NEW HELPER HERE ---
254float PointToLineSegmentDistanceSq(D2D1_POINT_2F p, D2D1_POINT_2F a, D2D1_POINT_2F b);
255// --- End Forward Declaration ---
256bool 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
257
258// --- NEW Forward Declarations ---
259
260// AI Related
261struct AIShotInfo; // Define below
262void TriggerAIMove();
263void AIMakeDecision();
264void AIPlaceCueBall();
265AIShotInfo AIFindBestShot();
266AIShotInfo EvaluateShot(Ball* targetBall, int pocketIndex);
267bool IsPathClear(D2D1_POINT_2F start, D2D1_POINT_2F end, int ignoredBallId1, int ignoredBallId2);
268Ball* FindFirstHitBall(D2D1_POINT_2F start, float angle, float& hitDistSq); // Added hitDistSq output
269float CalculateShotPower(float cueToGhostDist, float targetToPocketDist);
270D2D1_POINT_2F CalculateGhostBallPos(Ball* targetBall, int pocketIndex);
271bool IsValidAIAimAngle(float angle); // Basic check
272
273// Dialog Related
274INT_PTR CALLBACK NewGameDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam);
275void ShowNewGameDialog(HINSTANCE hInstance);
276void LoadSettings(); // For deserialization
277void SaveSettings(); // For serialization
278const std::wstring SETTINGS_FILE_NAME = L"Pool-Settings.txt";
279void ResetGame(HINSTANCE hInstance); // Function to handle F2 reset
280
281// --- Forward Declaration for Window Procedure --- <<< Add this line HERE
282LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
283
284// --- NEW Struct for AI Shot Evaluation ---
285struct AIShotInfo {
286 bool possible = false; // Is this shot considered viable?
287 Ball* targetBall = nullptr; // Which ball to hit
288 int pocketIndex = -1; // Which pocket to aim for (0-5)
289 D2D1_POINT_2F ghostBallPos = { 0,0 }; // Where cue ball needs to hit target ball
290 float angle = 0.0f; // Calculated shot angle
291 float power = 0.0f; // Calculated shot power
292 float score = -1.0f; // Score for this shot (higher is better)
293 bool involves8Ball = false; // Is the target the 8-ball?
294};
295
296/*
297table = TABLE_COLOR new: #29662d (0.1608, 0.4000, 0.1765) => old: (0.0f, 0.5f, 0.1f)
298rail CUSHION_COLOR = #5c0702 (0.3608, 0.0275, 0.0078) => ::Red
299gap = #e99d33 (0.9157, 0.6157, 0.2000) => ::Orange
300winbg = #5e8863 (0.3686, 0.5333, 0.3882) => 1.0f, 1.0f, 0.803f
301headstring = #47742f (0.2784, 0.4549, 0.1843) => ::White
302bluearrow = #08b0a5 (0.0314, 0.6902, 0.6471) *#22babf (0.1333,0.7294,0.7490) => ::Blue
303*/
304
305// --- NEW Settings Serialization Functions ---
306void SaveSettings() {
307 std::ofstream outFile(SETTINGS_FILE_NAME);
308 if (outFile.is_open()) {
309 outFile << static_cast<int>(gameMode) << std::endl;
310 outFile << static_cast<int>(aiDifficulty) << std::endl;
311 outFile << static_cast<int>(openingBreakMode) << std::endl;
312 outFile.close();
313 }
314 // else: Handle error, e.g., log or silently fail
315}
316
317void LoadSettings() {
318 std::ifstream inFile(SETTINGS_FILE_NAME);
319 if (inFile.is_open()) {
320 int gm, aid, obm;
321 if (inFile >> gm) {
322 gameMode = static_cast<GameMode>(gm);
323 }
324 if (inFile >> aid) {
325 aiDifficulty = static_cast<AIDifficulty>(aid);
326 }
327 if (inFile >> obm) {
328 openingBreakMode = static_cast<OpeningBreakMode>(obm);
329 }
330 inFile.close();
331
332 // Validate loaded settings (optional, but good practice)
333 if (gameMode < HUMAN_VS_HUMAN || gameMode > HUMAN_VS_AI) gameMode = HUMAN_VS_HUMAN; // Default
334 if (aiDifficulty < EASY || aiDifficulty > HARD) aiDifficulty = MEDIUM; // Default
335 if (openingBreakMode < CPU_BREAK || openingBreakMode > FLIP_COIN_BREAK) openingBreakMode = CPU_BREAK; // Default
336 }
337 // else: File doesn't exist or couldn't be opened, use defaults (already set in global vars)
338}
339// --- End Settings Serialization Functions ---
340
341// --- NEW Dialog Procedure ---
342INT_PTR CALLBACK NewGameDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {
343 switch (message) {
344 case WM_INITDIALOG:
345 {
346 // --- ACTION 4: Center Dialog Box ---
347// Optional: Force centering if default isn't working
348 RECT rcDlg, rcOwner, rcScreen;
349 HWND hwndOwner = GetParent(hDlg); // GetParent(hDlg) might be better if hwndMain is passed
350 if (hwndOwner == NULL) hwndOwner = GetDesktopWindow();
351
352 GetWindowRect(hwndOwner, &rcOwner);
353 GetWindowRect(hDlg, &rcDlg);
354 CopyRect(&rcScreen, &rcOwner); // Use owner rect as reference bounds
355
356 // Offset the owner rect relative to the screen if it's not the desktop
357 if (GetParent(hDlg) != NULL) { // If parented to main window (passed to DialogBoxParam)
358 OffsetRect(&rcOwner, -rcScreen.left, -rcScreen.top);
359 OffsetRect(&rcDlg, -rcScreen.left, -rcScreen.top);
360 OffsetRect(&rcScreen, -rcScreen.left, -rcScreen.top);
361 }
362
363
364 // Calculate centered position
365 int x = rcOwner.left + (rcOwner.right - rcOwner.left - (rcDlg.right - rcDlg.left)) / 2;
366 int y = rcOwner.top + (rcOwner.bottom - rcOwner.top - (rcDlg.bottom - rcDlg.top)) / 2;
367
368 // Ensure it stays within screen bounds (optional safety)
369 x = std::max(static_cast<int>(rcScreen.left), x);
370 y = std::max(static_cast<int>(rcScreen.top), y);
371 if (x + (rcDlg.right - rcDlg.left) > rcScreen.right)
372 x = rcScreen.right - (rcDlg.right - rcDlg.left);
373 if (y + (rcDlg.bottom - rcDlg.top) > rcScreen.bottom)
374 y = rcScreen.bottom - (rcDlg.bottom - rcDlg.top);
375
376
377 // Set the dialog position
378 SetWindowPos(hDlg, HWND_TOP, x, y, 0, 0, SWP_NOSIZE);
379
380 // --- End Centering Code ---
381
382 // Set initial state based on current global settings (or defaults)
383 CheckRadioButton(hDlg, IDC_RADIO_2P, IDC_RADIO_CPU, (gameMode == HUMAN_VS_HUMAN) ? IDC_RADIO_2P : IDC_RADIO_CPU);
384
385 CheckRadioButton(hDlg, IDC_RADIO_EASY, IDC_RADIO_HARD,
386 (aiDifficulty == EASY) ? IDC_RADIO_EASY : ((aiDifficulty == MEDIUM) ? IDC_RADIO_MEDIUM : IDC_RADIO_HARD));
387
388 // Enable/Disable AI group based on initial mode
389 EnableWindow(GetDlgItem(hDlg, IDC_GROUP_AI), gameMode == HUMAN_VS_AI);
390 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_EASY), gameMode == HUMAN_VS_AI);
391 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_MEDIUM), gameMode == HUMAN_VS_AI);
392 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_HARD), gameMode == HUMAN_VS_AI);
393 // Set initial state for Opening Break Mode
394 CheckRadioButton(hDlg, IDC_RADIO_CPU_BREAK, IDC_RADIO_FLIP_BREAK,
395 (openingBreakMode == CPU_BREAK) ? IDC_RADIO_CPU_BREAK : ((openingBreakMode == P1_BREAK) ? IDC_RADIO_P1_BREAK : IDC_RADIO_FLIP_BREAK));
396 // Enable/Disable Opening Break group based on initial mode
397 EnableWindow(GetDlgItem(hDlg, IDC_GROUP_BREAK_MODE), gameMode == HUMAN_VS_AI);
398 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_CPU_BREAK), gameMode == HUMAN_VS_AI);
399 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_P1_BREAK), gameMode == HUMAN_VS_AI);
400 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_FLIP_BREAK), gameMode == HUMAN_VS_AI);
401 }
402 return (INT_PTR)TRUE;
403
404 case WM_COMMAND:
405 switch (LOWORD(wParam)) {
406 case IDC_RADIO_2P:
407 case IDC_RADIO_CPU:
408 {
409 bool isCPU = IsDlgButtonChecked(hDlg, IDC_RADIO_CPU) == BST_CHECKED;
410 // Enable/Disable AI group controls based on selection
411 EnableWindow(GetDlgItem(hDlg, IDC_GROUP_AI), isCPU);
412 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_EASY), isCPU);
413 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_MEDIUM), isCPU);
414 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_HARD), isCPU);
415 // Also enable/disable Opening Break Mode group
416 EnableWindow(GetDlgItem(hDlg, IDC_GROUP_BREAK_MODE), isCPU);
417 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_CPU_BREAK), isCPU);
418 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_P1_BREAK), isCPU);
419 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_FLIP_BREAK), isCPU);
420 }
421 return (INT_PTR)TRUE;
422
423 case IDOK:
424 // Retrieve selected options and store in global variables
425 if (IsDlgButtonChecked(hDlg, IDC_RADIO_CPU) == BST_CHECKED) {
426 gameMode = HUMAN_VS_AI;
427 if (IsDlgButtonChecked(hDlg, IDC_RADIO_EASY) == BST_CHECKED) aiDifficulty = EASY;
428 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_MEDIUM) == BST_CHECKED) aiDifficulty = MEDIUM;
429 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_HARD) == BST_CHECKED) aiDifficulty = HARD;
430
431 if (IsDlgButtonChecked(hDlg, IDC_RADIO_CPU_BREAK) == BST_CHECKED) openingBreakMode = CPU_BREAK;
432 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_P1_BREAK) == BST_CHECKED) openingBreakMode = P1_BREAK;
433 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_FLIP_BREAK) == BST_CHECKED) openingBreakMode = FLIP_COIN_BREAK;
434 }
435 else {
436 gameMode = HUMAN_VS_HUMAN;
437 // openingBreakMode doesn't apply to HvsH, can leave as is or reset
438 }
439 SaveSettings(); // Save settings when OK is pressed
440 EndDialog(hDlg, IDOK); // Close dialog, return IDOK
441 return (INT_PTR)TRUE;
442
443 case IDCANCEL: // Handle Cancel or closing the dialog
444 // Optionally, could reload settings here if you want cancel to revert to previously saved state
445 EndDialog(hDlg, IDCANCEL);
446 return (INT_PTR)TRUE;
447 }
448 break; // End WM_COMMAND
449 }
450 return (INT_PTR)FALSE; // Default processing
451}
452
453// --- NEW Helper to Show Dialog ---
454void ShowNewGameDialog(HINSTANCE hInstance) {
455 if (DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_NEWGAMEDLG), hwndMain, NewGameDialogProc, 0) == IDOK) {
456 // User clicked Start, reset game with new settings
457 isPlayer2AI = (gameMode == HUMAN_VS_AI); // Update AI flag
458 if (isPlayer2AI) {
459 switch (aiDifficulty) {
460 case EASY: player2Info.name = L"CPU (Easy)"; break;
461 case MEDIUM: player2Info.name = L"CPU (Medium)"; break;
462 case HARD: player2Info.name = L"CPU (Hard)"; break;
463 }
464 }
465 else {
466 player2Info.name = L"Player 2";
467 }
468 // Update window title
469 std::wstring windowTitle = L"Direct2D 8-Ball Pool";
470 if (gameMode == HUMAN_VS_HUMAN) windowTitle += L" (Human vs Human)";
471 else windowTitle += L" (Human vs " + player2Info.name + L")";
472 SetWindowText(hwndMain, windowTitle.c_str());
473
474 InitGame(); // Re-initialize game logic & board
475 InvalidateRect(hwndMain, NULL, TRUE); // Force redraw
476 }
477 else {
478 // User cancelled dialog - maybe just resume game? Or exit?
479 // For simplicity, we do nothing, game continues as it was.
480 // To exit on cancel from F2, would need more complex state management.
481 }
482}
483
484// --- NEW Reset Game Function ---
485void ResetGame(HINSTANCE hInstance) {
486 // Call the helper function to show the dialog and re-init if OK clicked
487 ShowNewGameDialog(hInstance);
488}
489
490// --- WinMain ---
491int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR, int nCmdShow) {
492 if (FAILED(CoInitialize(NULL))) {
493 MessageBox(NULL, L"COM Initialization Failed.", L"Error", MB_OK | MB_ICONERROR);
494 return -1;
495 }
496
497 // --- NEW: Load settings at startup ---
498 LoadSettings();
499
500 // --- NEW: Show configuration dialog FIRST ---
501 if (DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_NEWGAMEDLG), NULL, NewGameDialogProc, 0) != IDOK) {
502 // User cancelled the dialog
503 CoUninitialize();
504 return 0; // Exit gracefully if dialog cancelled
505 }
506 // Global gameMode and aiDifficulty are now set by the DialogProc
507
508 // Set AI flag based on game mode
509 isPlayer2AI = (gameMode == HUMAN_VS_AI);
510 if (isPlayer2AI) {
511 switch (aiDifficulty) {
512 case EASY: player2Info.name = L"CPU (Easy)"; break;
513 case MEDIUM: player2Info.name = L"CPU (Medium)"; break;
514 case HARD: player2Info.name = L"CPU (Hard)"; break;
515 }
516 }
517 else {
518 player2Info.name = L"Player 2";
519 }
520 // --- End of Dialog Logic ---
521
522
523 WNDCLASS wc = { };
524 wc.lpfnWndProc = WndProc;
525 wc.hInstance = hInstance;
526 wc.lpszClassName = L"Direct2D_8BallPool";
527 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
528 wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
529 wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1)); // Use your actual icon ID here
530
531 if (!RegisterClass(&wc)) {
532 MessageBox(NULL, L"Window Registration Failed.", L"Error", MB_OK | MB_ICONERROR);
533 CoUninitialize();
534 return -1;
535 }
536
537 // --- ACTION 4: Calculate Centered Window Position ---
538 const int WINDOW_WIDTH = 1000; // Define desired width
539 const int WINDOW_HEIGHT = 700; // Define desired height
540 int screenWidth = GetSystemMetrics(SM_CXSCREEN);
541 int screenHeight = GetSystemMetrics(SM_CYSCREEN);
542 int windowX = (screenWidth - WINDOW_WIDTH) / 2;
543 int windowY = (screenHeight - WINDOW_HEIGHT) / 2;
544
545 // --- Change Window Title based on mode ---
546 std::wstring windowTitle = L"Direct2D 8-Ball Pool";
547 if (gameMode == HUMAN_VS_HUMAN) windowTitle += L" (Human vs Human)";
548 else windowTitle += L" (Human vs " + player2Info.name + L")";
549
550 DWORD dwStyle = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX; // No WS_THICKFRAME, No WS_MAXIMIZEBOX
551
552 hwndMain = CreateWindowEx(
553 0, L"Direct2D_8BallPool", windowTitle.c_str(), dwStyle,
554 windowX, windowY, WINDOW_WIDTH, WINDOW_HEIGHT,
555 NULL, NULL, hInstance, NULL
556 );
557
558 if (!hwndMain) {
559 MessageBox(NULL, L"Window Creation Failed.", L"Error", MB_OK | MB_ICONERROR);
560 CoUninitialize();
561 return -1;
562 }
563
564 // Initialize Direct2D Resources AFTER window creation
565 if (FAILED(CreateDeviceResources())) {
566 MessageBox(NULL, L"Failed to create Direct2D resources.", L"Error", MB_OK | MB_ICONERROR);
567 DestroyWindow(hwndMain);
568 CoUninitialize();
569 return -1;
570 }
571
572 InitGame(); // Initialize game state AFTER resources are ready & mode is set
573 Sleep(500); // Allow window to fully initialize before starting the countdown //midi func
574 StartMidi(hwndMain, TEXT("BSQ.MID")); // Replace with your MIDI filename
575 //PlayGameMusic(hwndMain); //midi func
576
577 ShowWindow(hwndMain, nCmdShow);
578 UpdateWindow(hwndMain);
579
580 if (!SetTimer(hwndMain, ID_TIMER, 1000 / TARGET_FPS, NULL)) {
581 MessageBox(NULL, L"Could not SetTimer().", L"Error", MB_OK | MB_ICONERROR);
582 DestroyWindow(hwndMain);
583 CoUninitialize();
584 return -1;
585 }
586
587 MSG msg = { };
588 // --- Modified Main Loop ---
589 // Handles the case where the game starts in SHOWING_DIALOG state (handled now before loop)
590 // or gets reset to it via F2. The main loop runs normally once game starts.
591 while (GetMessage(&msg, NULL, 0, 0)) {
592 // We might need modeless dialog handling here if F2 shows dialog
593 // while window is active, but DialogBoxParam is modal.
594 // Let's assume F2 hides main window, shows dialog, then restarts game loop.
595 // Simpler: F2 calls ResetGame which calls DialogBoxParam (modal) then InitGame.
596 TranslateMessage(&msg);
597 DispatchMessage(&msg);
598 }
599
600
601 KillTimer(hwndMain, ID_TIMER);
602 DiscardDeviceResources();
603 SaveSettings(); // Save settings on exit
604 CoUninitialize();
605
606 return (int)msg.wParam;
607}
608
609// --- WndProc ---
610LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
611 // Declare cueBall pointer once at the top, used in multiple cases
612 // For clarity, often better to declare within each case where needed.
613 Ball* cueBall = nullptr; // Initialize to nullptr
614 switch (msg) {
615 case WM_CREATE:
616 // Resources are now created in WinMain after CreateWindowEx
617 return 0;
618
619 case WM_PAINT:
620 OnPaint();
621 // Validate the entire window region after painting
622 ValidateRect(hwnd, NULL);
623 return 0;
624
625 case WM_SIZE: {
626 UINT width = LOWORD(lParam);
627 UINT height = HIWORD(lParam);
628 OnResize(width, height);
629 return 0;
630 }
631
632 case WM_TIMER:
633 if (wParam == ID_TIMER) {
634 GameUpdate(); // Update game logic and physics
635 InvalidateRect(hwnd, NULL, FALSE); // Request redraw
636 }
637 return 0;
638
639 // --- NEW: Handle F2 Key for Reset ---
640 // --- MODIFIED: Handle More Keys ---
641 case WM_KEYDOWN:
642 { // Add scope for variable declarations
643
644 // --- FIX: Get Cue Ball pointer for this scope ---
645 cueBall = GetCueBall();
646 // We might allow some keys even if cue ball is gone (like F1/F2), but actions need it
647 // --- End Fix ---
648
649 // Check which player can interact via keyboard (Humans only)
650 bool canPlayerControl = ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == AIMING || currentGameState == BREAKING || currentGameState == BALL_IN_HAND_P1 || currentGameState == PRE_BREAK_PLACEMENT)) ||
651 (currentPlayer == 2 && !isPlayer2AI && (currentGameState == PLAYER2_TURN || currentGameState == AIMING || currentGameState == BREAKING || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT)));
652
653 // --- F1 / F2 Keys (Always available) ---
654 if (wParam == VK_F2) {
655 HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE);
656 ResetGame(hInstance); // Call reset function
657 return 0; // Indicate key was processed
658 }
659 else if (wParam == VK_F1) {
660 MessageBox(hwnd,
661 L"Direct2D-based StickPool game made in C++ from scratch (2764+ lines of code)\n" // Update line count if needed
662 L"First successful Clone in C++ (no other sites or projects were there to glean from.) Made /w AI assist\n"
663 L"(others were in JS/ non-8-Ball in C# etc.) w/o OOP and Graphics Frameworks all in a Single file.\n"
664 L"Copyright (C) 2025 Evans Thorpemorton, Entisoft Solutions.\n"
665 L"Includes AI Difficulty Modes, Aim-Trajectory For Table Rails + Hard Angles TipShots. || F2=New Game",
666 L"About This Game", MB_OK | MB_ICONINFORMATION);
667 return 0; // Indicate key was processed
668 }
669
670 // Check for 'M' key (uppercase or lowercase)
671 // Toggle music with "M"
672 if (wParam == 'M' || wParam == 'm') {
673 //static bool isMusicPlaying = false;
674 if (isMusicPlaying) {
675 // Stop the music
676 StopMidi();
677 isMusicPlaying = false;
678 }
679 else {
680 // Build the MIDI file path
681 TCHAR midiPath[MAX_PATH];
682 GetModuleFileName(NULL, midiPath, MAX_PATH);
683 // Keep only the directory part
684 TCHAR* lastBackslash = _tcsrchr(midiPath, '\\');
685 if (lastBackslash != NULL) {
686 *(lastBackslash + 1) = '\0';
687 }
688 // Append the MIDI filename
689 _tcscat_s(midiPath, MAX_PATH, TEXT("BSQ.MID")); // Adjust filename if needed
690
691 // Start playing MIDI
692 StartMidi(hwndMain, midiPath);
693 isMusicPlaying = true;
694 }
695 }
696
697
698 // --- Player Interaction Keys (Only if allowed) ---
699 if (canPlayerControl) {
700 // --- Get Shift Key State ---
701 bool shiftPressed = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
702 float angleStep = shiftPressed ? 0.05f : 0.01f; // Base step / Faster step (Adjust as needed) // Multiplier was 5x
703 float powerStep = 0.2f; // Power step (Adjust as needed)
704
705 switch (wParam) {
706 case VK_LEFT: // Rotate Cue Stick Counter-Clockwise
707 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
708 cueAngle -= angleStep;
709 // Normalize angle (keep between 0 and 2*PI)
710 if (cueAngle < 0) cueAngle += 2 * PI;
711 // Ensure state shows aiming visuals if turn just started
712 if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
713 isAiming = false; // Keyboard adjust doesn't use mouse aiming state
714 isDraggingStick = false;
715 keyboardAimingActive = true;
716 }
717 break;
718
719 case VK_RIGHT: // Rotate Cue Stick Clockwise
720 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
721 cueAngle += angleStep;
722 // Normalize angle (keep between 0 and 2*PI)
723 if (cueAngle >= 2 * PI) cueAngle -= 2 * PI;
724 // Ensure state shows aiming visuals if turn just started
725 if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
726 isAiming = false;
727 isDraggingStick = false;
728 keyboardAimingActive = true;
729 }
730 break;
731
732 case VK_UP: // Decrease Shot Power
733 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
734 shotPower -= powerStep;
735 if (shotPower < 0.0f) shotPower = 0.0f;
736 // Ensure state shows aiming visuals if turn just started
737 if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
738 isAiming = true; // Keyboard adjust doesn't use mouse aiming state
739 isDraggingStick = false;
740 keyboardAimingActive = true;
741 }
742 break;
743
744 case VK_DOWN: // Increase Shot Power
745 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
746 shotPower += powerStep;
747 if (shotPower > MAX_SHOT_POWER) shotPower = MAX_SHOT_POWER;
748 // Ensure state shows aiming visuals if turn just started
749 if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
750 isAiming = true;
751 isDraggingStick = false;
752 keyboardAimingActive = true;
753 }
754 break;
755
756 case VK_SPACE: // Trigger Shot
757 if ((currentGameState == AIMING || currentGameState == BREAKING || currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN)
758 && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING)
759 {
760 if (shotPower > 0.15f) { // Use same threshold as mouse
761 // Reset foul flags BEFORE applying shot
762 firstHitBallIdThisShot = -1;
763 cueHitObjectBallThisShot = false;
764 railHitAfterContact = false;
765
766 // Play sound & Apply Shot
767 std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
768 ApplyShot(shotPower, cueAngle, cueSpinX, cueSpinY);
769
770 // Update State
771 currentGameState = SHOT_IN_PROGRESS;
772 foulCommitted = false;
773 pocketedThisTurn.clear();
774 shotPower = 0; // Reset power after shooting
775 isAiming = false; isDraggingStick = false; // Reset aiming flags
776 keyboardAimingActive = false;
777 }
778 }
779 break;
780
781 case VK_ESCAPE: // Cancel Aim/Shot Setup
782 if ((currentGameState == AIMING || currentGameState == BREAKING) || shotPower > 0)
783 {
784 shotPower = 0.0f;
785 isAiming = false;
786 isDraggingStick = false;
787 keyboardAimingActive = false;
788 // Revert to basic turn state if not breaking
789 if (currentGameState != BREAKING) {
790 currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
791 }
792 }
793 break;
794
795 case 'G': // Toggle Cheat Mode
796 cheatModeEnabled = !cheatModeEnabled;
797 if (cheatModeEnabled)
798 MessageBeep(MB_ICONEXCLAMATION); // Play a beep when enabling
799 else
800 MessageBeep(MB_OK); // Play a different beep when disabling
801 break;
802
803 default:
804 // Allow default processing for other keys if needed
805 // return DefWindowProc(hwnd, msg, wParam, lParam); // Usually not needed for WM_KEYDOWN
806 break;
807 } // End switch(wParam) for player controls
808 return 0; // Indicate player control key was processed
809 } // End if(canPlayerControl)
810 } // End scope for WM_KEYDOWN case
811 // If key wasn't F1/F2 and player couldn't control, maybe allow default processing?
812 // return DefWindowProc(hwnd, msg, wParam, lParam); // Or just return 0
813 return 0;
814
815 case WM_MOUSEMOVE: {
816 ptMouse.x = LOWORD(lParam);
817 ptMouse.y = HIWORD(lParam);
818
819 cueBall = GetCueBall(); // Declare and get cueBall pointer
820
821 if (isDraggingCueBall && cheatModeEnabled && draggingBallId != -1) {
822 Ball* ball = GetBallById(draggingBallId);
823 if (ball) {
824 ball->x = (float)ptMouse.x;
825 ball->y = (float)ptMouse.y;
826 ball->vx = ball->vy = 0.0f;
827 }
828 return 0;
829 }
830
831 if (!cueBall) return 0;
832
833 // Update Aiming Logic (Check player turn)
834 if (isDraggingCueBall &&
835 ((currentPlayer == 1 && currentGameState == BALL_IN_HAND_P1) ||
836 (!isPlayer2AI && currentPlayer == 2 && currentGameState == BALL_IN_HAND_P2) ||
837 currentGameState == PRE_BREAK_PLACEMENT))
838 {
839 bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
840 // Tentative position update
841 cueBall->x = (float)ptMouse.x;
842 cueBall->y = (float)ptMouse.y;
843 cueBall->vx = cueBall->vy = 0;
844 }
845 else if ((isAiming || isDraggingStick) &&
846 ((currentPlayer == 1 && (currentGameState == AIMING || currentGameState == BREAKING)) ||
847 (!isPlayer2AI && currentPlayer == 2 && (currentGameState == AIMING || currentGameState == BREAKING))))
848 {
849 //NEW2 MOUSEBOUND CODE = START
850 /*// Clamp mouse inside table bounds during aiming
851 if (ptMouse.x < TABLE_LEFT) ptMouse.x = TABLE_LEFT;
852 if (ptMouse.x > TABLE_RIGHT) ptMouse.x = TABLE_RIGHT;
853 if (ptMouse.y < TABLE_TOP) ptMouse.y = TABLE_TOP;
854 if (ptMouse.y > TABLE_BOTTOM) ptMouse.y = TABLE_BOTTOM;*/
855 //NEW2 MOUSEBOUND CODE = END
856 // Aiming drag updates angle and power
857 float dx = (float)ptMouse.x - cueBall->x;
858 float dy = (float)ptMouse.y - cueBall->y;
859 if (dx != 0 || dy != 0) cueAngle = atan2f(dy, dx);
860 //float pullDist = GetDistance((float)ptMouse.x, (float)ptMouse.y, aimStartPoint.x, aimStartPoint.y);
861 //shotPower = std::min(pullDist / 10.0f, MAX_SHOT_POWER);
862 if (!keyboardAimingActive) { // Only update shotPower if NOT keyboard aiming
863 float pullDist = GetDistance((float)ptMouse.x, (float)ptMouse.y, aimStartPoint.x, aimStartPoint.y);
864 shotPower = std::min(pullDist / 10.0f, MAX_SHOT_POWER);
865 }
866 }
867 else if (isSettingEnglish &&
868 ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == AIMING || currentGameState == BREAKING)) ||
869 (!isPlayer2AI && currentPlayer == 2 && (currentGameState == PLAYER2_TURN || currentGameState == AIMING || currentGameState == BREAKING))))
870 {
871 // Setting English
872 float dx = (float)ptMouse.x - spinIndicatorCenter.x;
873 float dy = (float)ptMouse.y - spinIndicatorCenter.y;
874 float dist = GetDistance(dx, dy, 0, 0);
875 if (dist > spinIndicatorRadius) { dx *= spinIndicatorRadius / dist; dy *= spinIndicatorRadius / dist; }
876 cueSpinX = dx / spinIndicatorRadius;
877 cueSpinY = dy / spinIndicatorRadius;
878 }
879 else {
880 //DISABLE PERM AIMING = START
881 /*// Update visual angle even when not aiming/dragging (Check player turn)
882 bool canUpdateVisualAngle = ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == BALL_IN_HAND_P1)) ||
883 (currentPlayer == 2 && !isPlayer2AI && (currentGameState == PLAYER2_TURN || currentGameState == BALL_IN_HAND_P2)) ||
884 currentGameState == PRE_BREAK_PLACEMENT || currentGameState == BREAKING || currentGameState == AIMING);
885
886 if (canUpdateVisualAngle && !isDraggingCueBall && !isAiming && !isDraggingStick && !keyboardAimingActive) // NEW: Prevent mouse override if keyboard aiming
887 {
888 // NEW MOUSEBOUND CODE = START
889 // Only update cue angle if mouse is inside the playable table area
890 if (ptMouse.x >= TABLE_LEFT && ptMouse.x <= TABLE_RIGHT &&
891 ptMouse.y >= TABLE_TOP && ptMouse.y <= TABLE_BOTTOM)
892 {
893 // NEW MOUSEBOUND CODE = END
894 Ball* cb = cueBall; // Use function-scope cueBall // Already got cueBall above
895 if (cb) {
896 float dx = (float)ptMouse.x - cb->x;
897 float dy = (float)ptMouse.y - cb->y;
898 if (dx != 0 || dy != 0) cueAngle = atan2f(dy, dx);
899 }
900 } //NEW MOUSEBOUND CODE LINE = DISABLE
901 }*/
902 //DISABLE PERM AIMING = END
903 }
904 return 0;
905 } // End WM_MOUSEMOVE
906
907 case WM_LBUTTONDOWN: {
908 ptMouse.x = LOWORD(lParam);
909 ptMouse.y = HIWORD(lParam);
910
911 if (cheatModeEnabled) {
912 // Allow dragging any ball freely
913 for (Ball& ball : balls) {
914 float distSq = GetDistanceSq(ball.x, ball.y, (float)ptMouse.x, (float)ptMouse.y);
915 if (distSq <= BALL_RADIUS * BALL_RADIUS * 4) { // Click near ball
916 isDraggingCueBall = true;
917 draggingBallId = ball.id;
918 if (ball.id == 0) {
919 // If dragging cue ball manually, ensure we stay in Ball-In-Hand state
920 if (currentPlayer == 1)
921 currentGameState = BALL_IN_HAND_P1;
922 else if (currentPlayer == 2 && !isPlayer2AI)
923 currentGameState = BALL_IN_HAND_P2;
924 }
925 return 0;
926 }
927 }
928 }
929
930 Ball* cueBall = GetCueBall(); // Declare and get cueBall pointer
931
932 // Check which player is allowed to interact via mouse click
933 bool canPlayerClickInteract = ((currentPlayer == 1) || (currentPlayer == 2 && !isPlayer2AI));
934 // Define states where interaction is generally allowed
935 bool canInteractState = (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN ||
936 currentGameState == AIMING || currentGameState == BREAKING ||
937 currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 ||
938 currentGameState == PRE_BREAK_PLACEMENT);
939
940 // Check Spin Indicator first (Allow if player's turn/aim phase)
941 if (canPlayerClickInteract && canInteractState) {
942 float spinDistSq = GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, spinIndicatorCenter.x, spinIndicatorCenter.y);
943 if (spinDistSq < spinIndicatorRadius * spinIndicatorRadius * 1.2f) {
944 isSettingEnglish = true;
945 float dx = (float)ptMouse.x - spinIndicatorCenter.x;
946 float dy = (float)ptMouse.y - spinIndicatorCenter.y;
947 float dist = GetDistance(dx, dy, 0, 0);
948 if (dist > spinIndicatorRadius) { dx *= spinIndicatorRadius / dist; dy *= spinIndicatorRadius / dist; }
949 cueSpinX = dx / spinIndicatorRadius;
950 cueSpinY = dy / spinIndicatorRadius;
951 isAiming = false; isDraggingStick = false; isDraggingCueBall = false;
952 return 0;
953 }
954 }
955
956 if (!cueBall) return 0;
957
958 // Check Ball-in-Hand placement/drag
959 bool isPlacingBall = (currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT);
960 bool isPlayerAllowedToPlace = (isPlacingBall &&
961 ((currentPlayer == 1 && currentGameState == BALL_IN_HAND_P1) ||
962 (currentPlayer == 2 && !isPlayer2AI && currentGameState == BALL_IN_HAND_P2) ||
963 (currentGameState == PRE_BREAK_PLACEMENT))); // Allow current player in break setup
964
965 if (isPlayerAllowedToPlace) {
966 float distSq = GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y);
967 if (distSq < BALL_RADIUS * BALL_RADIUS * 9.0f) {
968 isDraggingCueBall = true;
969 isAiming = false; isDraggingStick = false;
970 }
971 else {
972 bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
973 if (IsValidCueBallPosition((float)ptMouse.x, (float)ptMouse.y, behindHeadstring)) {
974 cueBall->x = (float)ptMouse.x; cueBall->y = (float)ptMouse.y;
975 cueBall->vx = 0; cueBall->vy = 0;
976 isDraggingCueBall = false;
977 // Transition state
978 if (currentGameState == PRE_BREAK_PLACEMENT) currentGameState = BREAKING;
979 else if (currentGameState == BALL_IN_HAND_P1) currentGameState = PLAYER1_TURN;
980 else if (currentGameState == BALL_IN_HAND_P2) currentGameState = PLAYER2_TURN;
981 cueAngle = 0.0f;
982 }
983 }
984 return 0;
985 }
986
987 // Check for starting Aim (Cue Ball OR Stick)
988 bool canAim = ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == BREAKING)) ||
989 (currentPlayer == 2 && !isPlayer2AI && (currentGameState == PLAYER2_TURN || currentGameState == BREAKING)));
990
991 if (canAim) {
992 const float stickDrawLength = 150.0f * 1.4f;
993 float currentStickAngle = cueAngle + PI;
994 D2D1_POINT_2F currentStickEnd = D2D1::Point2F(cueBall->x + cosf(currentStickAngle) * stickDrawLength, cueBall->y + sinf(currentStickAngle) * stickDrawLength);
995 D2D1_POINT_2F currentStickTip = D2D1::Point2F(cueBall->x + cosf(currentStickAngle) * 5.0f, cueBall->y + sinf(currentStickAngle) * 5.0f);
996 float distToStickSq = PointToLineSegmentDistanceSq(D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y), currentStickTip, currentStickEnd);
997 float stickClickThresholdSq = 36.0f;
998 float distToCueBallSq = GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y);
999 float cueBallClickRadiusSq = BALL_RADIUS * BALL_RADIUS * 25;
1000
1001 bool clickedStick = (distToStickSq < stickClickThresholdSq);
1002 bool clickedCueArea = (distToCueBallSq < cueBallClickRadiusSq);
1003
1004 if (clickedStick || clickedCueArea) {
1005 isDraggingStick = clickedStick && !clickedCueArea;
1006 isAiming = clickedCueArea;
1007 aimStartPoint = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y);
1008 shotPower = 0;
1009 float dx = (float)ptMouse.x - cueBall->x;
1010 float dy = (float)ptMouse.y - cueBall->y;
1011 if (dx != 0 || dy != 0) cueAngle = atan2f(dy, dx);
1012 if (currentGameState != BREAKING) currentGameState = AIMING;
1013 }
1014 }
1015 return 0;
1016 } // End WM_LBUTTONDOWN
1017
1018
1019 case WM_LBUTTONUP: {
1020 if (cheatModeEnabled && isDraggingCueBall) {
1021 isDraggingCueBall = false;
1022 if (draggingBallId == 0) {
1023 // After dropping CueBall, stay Ball-In-Hand mode if needed
1024 if (currentPlayer == 1)
1025 currentGameState = BALL_IN_HAND_P1;
1026 else if (currentPlayer == 2 && !isPlayer2AI)
1027 currentGameState = BALL_IN_HAND_P2;
1028 }
1029 draggingBallId = -1;
1030 return 0;
1031 }
1032
1033 ptMouse.x = LOWORD(lParam);
1034 ptMouse.y = HIWORD(lParam);
1035
1036 Ball* cueBall = GetCueBall(); // Get cueBall pointer
1037
1038 // Check for releasing aim drag (Stick OR Cue Ball)
1039 if ((isAiming || isDraggingStick) &&
1040 ((currentPlayer == 1 && (currentGameState == AIMING || currentGameState == BREAKING)) ||
1041 (!isPlayer2AI && currentPlayer == 2 && (currentGameState == AIMING || currentGameState == BREAKING))))
1042 {
1043 bool wasAiming = isAiming;
1044 bool wasDraggingStick = isDraggingStick;
1045 isAiming = false; isDraggingStick = false;
1046
1047 if (shotPower > 0.15f) { // Check power threshold
1048 if (currentGameState != AI_THINKING) {
1049 firstHitBallIdThisShot = -1; cueHitObjectBallThisShot = false; railHitAfterContact = false; // Reset foul flags
1050 std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
1051 ApplyShot(shotPower, cueAngle, cueSpinX, cueSpinY);
1052 currentGameState = SHOT_IN_PROGRESS;
1053 foulCommitted = false; pocketedThisTurn.clear();
1054 }
1055 }
1056 else if (currentGameState != AI_THINKING) { // Revert state if power too low
1057 if (currentGameState == BREAKING) { /* Still breaking */ }
1058 else {
1059 currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
1060 if (currentPlayer == 2 && isPlayer2AI) aiTurnPending = false;
1061 }
1062 }
1063 shotPower = 0; // Reset power indicator regardless
1064 }
1065
1066 // Handle releasing cue ball drag (placement)
1067 if (isDraggingCueBall) {
1068 isDraggingCueBall = false;
1069 // Check player allowed to place
1070 bool isPlacingState = (currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT);
1071 bool isPlayerAllowed = (isPlacingState &&
1072 ((currentPlayer == 1 && currentGameState == BALL_IN_HAND_P1) ||
1073 (currentPlayer == 2 && !isPlayer2AI && currentGameState == BALL_IN_HAND_P2) ||
1074 (currentGameState == PRE_BREAK_PLACEMENT)));
1075
1076 if (isPlayerAllowed && cueBall) {
1077 bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
1078 if (IsValidCueBallPosition(cueBall->x, cueBall->y, behindHeadstring)) {
1079 // Finalize position already set by mouse move
1080 // Transition state
1081 if (currentGameState == PRE_BREAK_PLACEMENT) currentGameState = BREAKING;
1082 else if (currentGameState == BALL_IN_HAND_P1) currentGameState = PLAYER1_TURN;
1083 else if (currentGameState == BALL_IN_HAND_P2) currentGameState = PLAYER2_TURN;
1084 cueAngle = 0.0f;
1085 }
1086 else { /* Stay in BALL_IN_HAND state if final pos invalid */ }
1087 }
1088 }
1089
1090 // Handle releasing english setting
1091 if (isSettingEnglish) {
1092 isSettingEnglish = false;
1093 }
1094 return 0;
1095 } // End WM_LBUTTONUP
1096
1097 case WM_DESTROY:
1098 isMusicPlaying = false;
1099 if (midiDeviceID != 0) {
1100 mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
1101 midiDeviceID = 0;
1102 SaveSettings(); // Save settings on exit
1103 }
1104 PostQuitMessage(0);
1105 return 0;
1106
1107 default:
1108 return DefWindowProc(hwnd, msg, wParam, lParam);
1109 }
1110 return 0;
1111}
1112
1113// --- Direct2D Resource Management ---
1114
1115HRESULT CreateDeviceResources() {
1116 HRESULT hr = S_OK;
1117
1118 // Create Direct2D Factory
1119 if (!pFactory) {
1120 hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &pFactory);
1121 if (FAILED(hr)) return hr;
1122 }
1123
1124 // Create DirectWrite Factory
1125 if (!pDWriteFactory) {
1126 hr = DWriteCreateFactory(
1127 DWRITE_FACTORY_TYPE_SHARED,
1128 __uuidof(IDWriteFactory),
1129 reinterpret_cast<IUnknown**>(&pDWriteFactory)
1130 );
1131 if (FAILED(hr)) return hr;
1132 }
1133
1134 // Create Text Formats
1135 if (!pTextFormat && pDWriteFactory) {
1136 hr = pDWriteFactory->CreateTextFormat(
1137 L"Segoe UI", NULL, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
1138 16.0f, L"en-us", &pTextFormat
1139 );
1140 if (FAILED(hr)) return hr;
1141 // Center align text
1142 pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
1143 pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
1144 }
1145 if (!pLargeTextFormat && pDWriteFactory) {
1146 hr = pDWriteFactory->CreateTextFormat(
1147 L"Impact", NULL, DWRITE_FONT_WEIGHT_BOLD, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
1148 48.0f, L"en-us", &pLargeTextFormat
1149 );
1150 if (FAILED(hr)) return hr;
1151 pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING); // Align left
1152 pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
1153 }
1154
1155
1156 // Create Render Target (needs valid hwnd)
1157 if (!pRenderTarget && hwndMain) {
1158 RECT rc;
1159 GetClientRect(hwndMain, &rc);
1160 D2D1_SIZE_U size = D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top);
1161
1162 hr = pFactory->CreateHwndRenderTarget(
1163 D2D1::RenderTargetProperties(),
1164 D2D1::HwndRenderTargetProperties(hwndMain, size),
1165 &pRenderTarget
1166 );
1167 if (FAILED(hr)) {
1168 // If failed, release factories if they were created in this call
1169 SafeRelease(&pTextFormat);
1170 SafeRelease(&pLargeTextFormat);
1171 SafeRelease(&pDWriteFactory);
1172 SafeRelease(&pFactory);
1173 pRenderTarget = nullptr; // Ensure it's null on failure
1174 return hr;
1175 }
1176 }
1177
1178 return hr;
1179}
1180
1181void DiscardDeviceResources() {
1182 SafeRelease(&pRenderTarget);
1183 SafeRelease(&pTextFormat);
1184 SafeRelease(&pLargeTextFormat);
1185 SafeRelease(&pDWriteFactory);
1186 // Keep pFactory until application exit? Or release here too? Let's release.
1187 SafeRelease(&pFactory);
1188}
1189
1190void OnResize(UINT width, UINT height) {
1191 if (pRenderTarget) {
1192 D2D1_SIZE_U size = D2D1::SizeU(width, height);
1193 pRenderTarget->Resize(size); // Ignore HRESULT for simplicity here
1194 }
1195}
1196
1197// --- Game Initialization ---
1198void InitGame() {
1199 srand((unsigned int)time(NULL)); // Seed random number generator
1200 isOpeningBreakShot = true; // This is the start of a new game, so the next shot is an opening break.
1201 aiPlannedShotDetails.isValid = false; // Reset AI planned shot
1202 aiIsDisplayingAim = false;
1203 aiAimDisplayFramesLeft = 0;
1204 // ... (rest of InitGame())
1205
1206 // --- Ensure pocketed list is clear from the absolute start ---
1207 pocketedThisTurn.clear();
1208
1209 balls.clear(); // Clear existing balls
1210
1211 // Reset Player Info (Names should be set by Dialog/wWinMain/ResetGame)
1212 player1Info.assignedType = BallType::NONE;
1213 player1Info.ballsPocketedCount = 0;
1214 // Player 1 Name usually remains "Player 1"
1215 player2Info.assignedType = BallType::NONE;
1216 player2Info.ballsPocketedCount = 0;
1217 // Player 2 Name is set based on gameMode in ShowNewGameDialog
1218
1219 // Create Cue Ball (ID 0)
1220 // Initial position will be set during PRE_BREAK_PLACEMENT state
1221 balls.push_back({ 0, BallType::CUE_BALL, TABLE_LEFT + TABLE_WIDTH * 0.15f, RACK_POS_Y, 0, 0, CUE_BALL_COLOR, false });
1222
1223 // --- Create Object Balls (Temporary List) ---
1224 std::vector<Ball> objectBalls;
1225 // Solids (1-7, Yellow)
1226 for (int i = 1; i <= 7; ++i) {
1227 objectBalls.push_back({ i, BallType::SOLID, 0, 0, 0, 0, SOLID_COLOR, false });
1228 }
1229 // Stripes (9-15, Red)
1230 for (int i = 9; i <= 15; ++i) {
1231 objectBalls.push_back({ i, BallType::STRIPE, 0, 0, 0, 0, STRIPE_COLOR, false });
1232 }
1233 // 8-Ball (ID 8) - Add it to the list to be placed
1234 objectBalls.push_back({ 8, BallType::EIGHT_BALL, 0, 0, 0, 0, EIGHT_BALL_COLOR, false });
1235
1236
1237 // --- Racking Logic (Improved) ---
1238 float spacingX = BALL_RADIUS * 2.0f * 0.866f; // cos(30) for horizontal spacing
1239 float spacingY = BALL_RADIUS * 2.0f * 1.0f; // Vertical spacing
1240
1241 // Define rack positions (0-14 indices corresponding to triangle spots)
1242 D2D1_POINT_2F rackPositions[15];
1243 int rackIndex = 0;
1244 for (int row = 0; row < 5; ++row) {
1245 for (int col = 0; col <= row; ++col) {
1246 if (rackIndex >= 15) break;
1247 float x = RACK_POS_X + row * spacingX;
1248 float y = RACK_POS_Y + (col - row / 2.0f) * spacingY;
1249 rackPositions[rackIndex++] = D2D1::Point2F(x, y);
1250 }
1251 }
1252
1253 // Separate 8-ball
1254 Ball eightBall;
1255 std::vector<Ball> otherBalls; // Solids and Stripes
1256 bool eightBallFound = false;
1257 for (const auto& ball : objectBalls) {
1258 if (ball.id == 8) {
1259 eightBall = ball;
1260 eightBallFound = true;
1261 }
1262 else {
1263 otherBalls.push_back(ball);
1264 }
1265 }
1266 // Ensure 8 ball was actually created (should always be true)
1267 if (!eightBallFound) {
1268 // Handle error - perhaps recreate it? For now, proceed.
1269 eightBall = { 8, BallType::EIGHT_BALL, 0, 0, 0, 0, EIGHT_BALL_COLOR, false };
1270 }
1271
1272
1273 // Shuffle the other 14 balls
1274 // Use std::shuffle if available (C++11 and later) for better randomness
1275 // std::random_device rd;
1276 // std::mt19937 g(rd());
1277 // std::shuffle(otherBalls.begin(), otherBalls.end(), g);
1278 std::random_shuffle(otherBalls.begin(), otherBalls.end()); // Using deprecated for now
1279
1280 // --- Place balls into the main 'balls' vector in rack order ---
1281 // Important: Add the cue ball (already created) first.
1282 // (Cue ball added at the start of the function now)
1283
1284 // 1. Place the 8-ball in its fixed position (index 4 for the 3rd row center)
1285 int eightBallRackIndex = 4;
1286 eightBall.x = rackPositions[eightBallRackIndex].x;
1287 eightBall.y = rackPositions[eightBallRackIndex].y;
1288 eightBall.vx = 0;
1289 eightBall.vy = 0;
1290 eightBall.isPocketed = false;
1291 balls.push_back(eightBall); // Add 8 ball to the main vector
1292
1293 // 2. Place the shuffled Solids and Stripes in the remaining spots
1294 size_t otherBallIdx = 0;
1295 //int otherBallIdx = 0;
1296 for (int i = 0; i < 15; ++i) {
1297 if (i == eightBallRackIndex) continue; // Skip the 8-ball spot
1298
1299 if (otherBallIdx < otherBalls.size()) {
1300 Ball& ballToPlace = otherBalls[otherBallIdx++];
1301 ballToPlace.x = rackPositions[i].x;
1302 ballToPlace.y = rackPositions[i].y;
1303 ballToPlace.vx = 0;
1304 ballToPlace.vy = 0;
1305 ballToPlace.isPocketed = false;
1306 balls.push_back(ballToPlace); // Add to the main game vector
1307 }
1308 }
1309 // --- End Racking Logic ---
1310
1311
1312 // --- Determine Who Breaks and Initial State ---
1313 if (isPlayer2AI) {
1314 /*// AI Mode: Randomly decide who breaks
1315 if ((rand() % 2) == 0) {
1316 // AI (Player 2) breaks
1317 currentPlayer = 2;
1318 currentGameState = PRE_BREAK_PLACEMENT; // AI needs to place ball first
1319 aiTurnPending = true; // Trigger AI logic
1320 }
1321 else {
1322 // Player 1 (Human) breaks
1323 currentPlayer = 1;
1324 currentGameState = PRE_BREAK_PLACEMENT; // Human places cue ball
1325 aiTurnPending = false;*/
1326 switch (openingBreakMode) {
1327 case CPU_BREAK:
1328 currentPlayer = 2; // AI breaks
1329 currentGameState = PRE_BREAK_PLACEMENT;
1330 aiTurnPending = true;
1331 break;
1332 case P1_BREAK:
1333 currentPlayer = 1; // Player 1 breaks
1334 currentGameState = PRE_BREAK_PLACEMENT;
1335 aiTurnPending = false;
1336 break;
1337 case FLIP_COIN_BREAK:
1338 if ((rand() % 2) == 0) { // 0 for AI, 1 for Player 1
1339 currentPlayer = 2; // AI breaks
1340 currentGameState = PRE_BREAK_PLACEMENT;
1341 aiTurnPending = true;
1342 }
1343 else {
1344 currentPlayer = 1; // Player 1 breaks
1345 currentGameState = PRE_BREAK_PLACEMENT;
1346 aiTurnPending = false;
1347 }
1348 break;
1349 default: // Fallback to CPU break
1350 currentPlayer = 2;
1351 currentGameState = PRE_BREAK_PLACEMENT;
1352 aiTurnPending = true;
1353 break;
1354 }
1355 }
1356 else {
1357 // Human vs Human, Player 1 always breaks (or could add a flip coin for HvsH too if desired)
1358 currentPlayer = 1;
1359 currentGameState = PRE_BREAK_PLACEMENT;
1360 aiTurnPending = false; // No AI involved
1361 }
1362
1363 // Reset other relevant game state variables
1364 foulCommitted = false;
1365 gameOverMessage = L"";
1366 firstBallPocketedAfterBreak = false;
1367 // pocketedThisTurn cleared at start
1368 // Reset shot parameters and input flags
1369 shotPower = 0.0f;
1370 cueSpinX = 0.0f;
1371 cueSpinY = 0.0f;
1372 isAiming = false;
1373 isDraggingCueBall = false;
1374 isSettingEnglish = false;
1375 cueAngle = 0.0f; // Reset aim angle
1376}
1377
1378
1379// --- Game Loop ---
1380void GameUpdate() {
1381 if (currentGameState == SHOT_IN_PROGRESS) {
1382 UpdatePhysics();
1383 CheckCollisions();
1384
1385 if (AreBallsMoving()) {
1386 // When all balls stop, clear aiming flags
1387 isAiming = false;
1388 aiIsDisplayingAim = false;
1389 //ProcessShotResults();
1390 }
1391
1392 bool pocketed = CheckPockets(); // Store if any ball was pocketed
1393
1394 // --- Update pocket flash animation timer ---
1395 if (pocketFlashTimer > 0.0f) {
1396 pocketFlashTimer -= 0.02f;
1397 if (pocketFlashTimer < 0.0f) pocketFlashTimer = 0.0f;
1398 }
1399
1400 if (!AreBallsMoving()) {
1401 ProcessShotResults(); // Determine next state based on what happened
1402 }
1403 }
1404
1405 // --- Check if AI needs to act ---
1406 else if (isPlayer2AI && currentPlayer == 2 && !AreBallsMoving()) {
1407 if (aiIsDisplayingAim) { // AI has decided a shot and is displaying aim
1408 aiAimDisplayFramesLeft--;
1409 if (aiAimDisplayFramesLeft <= 0) {
1410 aiIsDisplayingAim = false; // Done displaying
1411 if (aiPlannedShotDetails.isValid) {
1412 // Execute the planned shot
1413 firstHitBallIdThisShot = -1;
1414 cueHitObjectBallThisShot = false;
1415 railHitAfterContact = false;
1416 std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
1417 ApplyShot(aiPlannedShotDetails.power, aiPlannedShotDetails.angle, aiPlannedShotDetails.spinX, aiPlannedShotDetails.spinY);
1418 aiPlannedShotDetails.isValid = false; // Clear the planned shot
1419 }
1420 currentGameState = SHOT_IN_PROGRESS;
1421 foulCommitted = false;
1422 pocketedThisTurn.clear();
1423 }
1424 // Else, continue displaying aim
1425 }
1426 else if (aiTurnPending) { // AI needs to start its decision process
1427 // Valid states for AI to start thinking
1428 /*/if (currentGameState == PRE_BREAK_PLACEMENT && isOpeningBreakShot) {*/
1429 //newcode 1 commented out
1430 /*if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT && currentPlayer == 2 && isPlayer2AI) {
1431 // Handle the break shot
1432 AIBreakShot();
1433 }*/ //new code 1 end
1434 /*else if (currentGameState == PRE_BREAK_PLACEMENT || currentGameState == BREAKING ||
1435 currentGameState == PLAYER2_TURN || currentGameState == BALL_IN_HAND_P2) {*/
1436
1437 // aiTurnPending might be consumed by AIBreakShot or remain for next cycle if needed
1438 /* } //new code 2 commented out
1439 else if (currentGameState == BALL_IN_HAND_P2 && currentPlayer == 2 && isPlayer2AI) {
1440 AIPlaceCueBall(); // AI places the ball first
1441 // After placement, AI needs to decide its shot.
1442 // Transition to a state where AIMakeDecision will be called for shot selection.
1443 currentGameState = PLAYER2_TURN; // Or a specific AI_AIMING_AFTER_PLACEMENT state
1444 // aiTurnPending remains true to trigger AIMakeDecision next.
1445 }
1446 else if (currentGameState == PLAYER2_TURN && currentPlayer == 2 && isPlayer2AI) {
1447 // This is for a normal turn (not break, not immediately after ball-in-hand placement)
1448
1449 currentGameState = AI_THINKING; // Set state to indicate AI is processing
1450 aiTurnPending = false; // Consume the pending turn flag
1451 AIMakeDecision(); // For normal shots (non-break)
1452 }
1453 else {
1454 // Not a state where AI should act
1455 aiTurnPending = false;
1456 }*/
1457 // 2b) AI is ready to think (pending flag)
1458 // **1) Ball-in-Hand** let AI place the cue ball first
1459 if (currentGameState == BALL_IN_HAND_P2) {
1460 // Step 1: AI places the cue ball.
1461 AIPlaceCueBall();
1462 // Step 2: Transition to thinking state for shot decision.
1463 currentGameState = AI_THINKING; //newcode5
1464 // Step 3: Consume the pending flag for the placement phase.
1465 // AIMakeDecision will handle shot planning now.
1466 aiTurnPending = false; //newcode5
1467 // Step 4: AI immediately decides the shot from the new position.
1468 AIMakeDecision(); //newcode5
1469 }
1470 // **2) Opening break** special break shot logic
1471 else if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT) {
1472 AIBreakShot();
1473 }
1474 else if (currentGameState == PLAYER2_TURN || currentGameState == BREAKING) { //newcode5
1475 // General turn for AI to think (not ball-in-hand, not initial break placement)
1476 currentGameState = AI_THINKING; //newcode5
1477 aiTurnPending = false; // Consume the flag //newcode5
1478 AIMakeDecision(); //newcode5
1479 }
1480 // **3) Otherwise** normal shot planning
1481 /*else { //orig uncommented oldcode5
1482 currentGameState = AI_THINKING;
1483 aiTurnPending = false;
1484 AIMakeDecision();
1485 }*/
1486 }
1487
1488 //} //bracefix
1489 // If current state is AI_THINKING but not displaying aim, then AI decision has already been made
1490 }
1491}
1492
1493// --- Physics and Collision ---
1494void UpdatePhysics() {
1495 for (size_t i = 0; i < balls.size(); ++i) {
1496 Ball& b = balls[i];
1497 if (!b.isPocketed) {
1498 b.x += b.vx;
1499 b.y += b.vy;
1500
1501 // Apply friction
1502 b.vx *= FRICTION;
1503 b.vy *= FRICTION;
1504
1505 // Stop balls if velocity is very low
1506 if (GetDistanceSq(b.vx, b.vy, 0, 0) < MIN_VELOCITY_SQ) {
1507 b.vx = 0;
1508 b.vy = 0;
1509 }
1510 }
1511 }
1512}
1513
1514void CheckCollisions() {
1515 float left = TABLE_LEFT;
1516 float right = TABLE_RIGHT;
1517 float top = TABLE_TOP;
1518 float bottom = TABLE_BOTTOM;
1519 const float pocketMouthCheckRadiusSq = (POCKET_RADIUS + BALL_RADIUS) * (POCKET_RADIUS + BALL_RADIUS) * 1.1f;
1520
1521 // --- Reset Per-Frame Sound Flags ---
1522 bool playedWallSoundThisFrame = false;
1523 bool playedCollideSoundThisFrame = false;
1524 // ---
1525
1526 for (size_t i = 0; i < balls.size(); ++i) {
1527 Ball& b1 = balls[i];
1528 if (b1.isPocketed) continue;
1529
1530 bool nearPocket[6];
1531 for (int p = 0; p < 6; ++p) {
1532 nearPocket[p] = GetDistanceSq(b1.x, b1.y, pocketPositions[p].x, pocketPositions[p].y) < pocketMouthCheckRadiusSq;
1533 }
1534 bool nearTopLeftPocket = nearPocket[0];
1535 bool nearTopMidPocket = nearPocket[1];
1536 bool nearTopRightPocket = nearPocket[2];
1537 bool nearBottomLeftPocket = nearPocket[3];
1538 bool nearBottomMidPocket = nearPocket[4];
1539 bool nearBottomRightPocket = nearPocket[5];
1540
1541 bool collidedWallThisBall = false;
1542
1543 // --- Ball-Wall Collisions ---
1544 // (Check logic unchanged, added sound calls and railHitAfterContact update)
1545 // Left Wall
1546 if (b1.x - BALL_RADIUS < left) {
1547 if (!nearTopLeftPocket && !nearBottomLeftPocket) {
1548 b1.x = left + BALL_RADIUS; b1.vx *= -1.0f; collidedWallThisBall = true;
1549 if (!playedWallSoundThisFrame) {
1550 std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
1551 playedWallSoundThisFrame = true;
1552 }
1553 if (cueHitObjectBallThisShot) railHitAfterContact = true; // Track rail hit after contact
1554 }
1555 }
1556 // Right Wall
1557 if (b1.x + BALL_RADIUS > right) {
1558 if (!nearTopRightPocket && !nearBottomRightPocket) {
1559 b1.x = right - BALL_RADIUS; b1.vx *= -1.0f; collidedWallThisBall = true;
1560 if (!playedWallSoundThisFrame) {
1561 std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
1562 playedWallSoundThisFrame = true;
1563 }
1564 if (cueHitObjectBallThisShot) railHitAfterContact = true; // Track rail hit after contact
1565 }
1566 }
1567 // Top Wall
1568 if (b1.y - BALL_RADIUS < top) {
1569 if (!nearTopLeftPocket && !nearTopMidPocket && !nearTopRightPocket) {
1570 b1.y = top + BALL_RADIUS; b1.vy *= -1.0f; collidedWallThisBall = true;
1571 if (!playedWallSoundThisFrame) {
1572 std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
1573 playedWallSoundThisFrame = true;
1574 }
1575 if (cueHitObjectBallThisShot) railHitAfterContact = true; // Track rail hit after contact
1576 }
1577 }
1578 // Bottom Wall
1579 if (b1.y + BALL_RADIUS > bottom) {
1580 if (!nearBottomLeftPocket && !nearBottomMidPocket && !nearBottomRightPocket) {
1581 b1.y = bottom - BALL_RADIUS; b1.vy *= -1.0f; collidedWallThisBall = true;
1582 if (!playedWallSoundThisFrame) {
1583 std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
1584 playedWallSoundThisFrame = true;
1585 }
1586 if (cueHitObjectBallThisShot) railHitAfterContact = true; // Track rail hit after contact
1587 }
1588 }
1589
1590 // Spin effect (Unchanged)
1591 if (collidedWallThisBall) {
1592 if (b1.x <= left + BALL_RADIUS || b1.x >= right - BALL_RADIUS) { b1.vy += cueSpinX * b1.vx * 0.05f; }
1593 if (b1.y <= top + BALL_RADIUS || b1.y >= bottom - BALL_RADIUS) { b1.vx -= cueSpinY * b1.vy * 0.05f; }
1594 cueSpinX *= 0.7f; cueSpinY *= 0.7f;
1595 }
1596
1597
1598 // --- Ball-Ball Collisions ---
1599 for (size_t j = i + 1; j < balls.size(); ++j) {
1600 Ball& b2 = balls[j];
1601 if (b2.isPocketed) continue;
1602
1603 float dx = b2.x - b1.x; float dy = b2.y - b1.y;
1604 float distSq = dx * dx + dy * dy;
1605 float minDist = BALL_RADIUS * 2.0f;
1606
1607 if (distSq > 1e-6 && distSq < minDist * minDist) {
1608 float dist = sqrtf(distSq);
1609 float overlap = minDist - dist;
1610 float nx = dx / dist; float ny = dy / dist;
1611
1612 // Separation (Unchanged)
1613 b1.x -= overlap * 0.5f * nx; b1.y -= overlap * 0.5f * ny;
1614 b2.x += overlap * 0.5f * nx; b2.y += overlap * 0.5f * ny;
1615
1616 float rvx = b1.vx - b2.vx; float rvy = b1.vy - b2.vy;
1617 float velAlongNormal = rvx * nx + rvy * ny;
1618
1619 if (velAlongNormal > 0) { // Colliding
1620 // --- Play Ball Collision Sound ---
1621 if (!playedCollideSoundThisFrame) {
1622 std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("poolballhit.wav")).detach();
1623 playedCollideSoundThisFrame = true; // Set flag
1624 }
1625 // --- End Sound ---
1626
1627 // --- NEW: Track First Hit and Cue/Object Collision ---
1628 if (firstHitBallIdThisShot == -1) { // If first hit hasn't been recorded yet
1629 if (b1.id == 0) { // Cue ball hit b2 first
1630 firstHitBallIdThisShot = b2.id;
1631 cueHitObjectBallThisShot = true;
1632 }
1633 else if (b2.id == 0) { // Cue ball hit b1 first
1634 firstHitBallIdThisShot = b1.id;
1635 cueHitObjectBallThisShot = true;
1636 }
1637 // If neither is cue ball, doesn't count as first hit for foul purposes
1638 }
1639 else if (b1.id == 0 || b2.id == 0) {
1640 // Track subsequent cue ball collisions with object balls
1641 cueHitObjectBallThisShot = true;
1642 }
1643 // --- End First Hit Tracking ---
1644
1645
1646 // Impulse (Unchanged)
1647 float impulse = velAlongNormal;
1648 b1.vx -= impulse * nx; b1.vy -= impulse * ny;
1649 b2.vx += impulse * nx; b2.vy += impulse * ny;
1650
1651 // Spin Transfer (Unchanged)
1652 if (b1.id == 0 || b2.id == 0) {
1653 float spinEffectFactor = 0.08f;
1654 b1.vx += (cueSpinY * ny - cueSpinX * nx) * spinEffectFactor;
1655 b1.vy += (cueSpinY * nx + cueSpinX * ny) * spinEffectFactor;
1656 b2.vx -= (cueSpinY * ny - cueSpinX * nx) * spinEffectFactor;
1657 b2.vy -= (cueSpinY * nx + cueSpinX * ny) * spinEffectFactor;
1658 cueSpinX *= 0.85f; cueSpinY *= 0.85f;
1659 }
1660 }
1661 }
1662 } // End ball-ball loop
1663 } // End ball loop
1664} // End CheckCollisions
1665
1666
1667bool CheckPockets() {
1668 bool ballPocketedThisCheck = false; // Local flag for this specific check run
1669 for (size_t i = 0; i < balls.size(); ++i) {
1670 Ball& b = balls[i];
1671 if (!b.isPocketed) { // Only check balls that aren't already flagged as pocketed
1672 for (int p = 0; p < 6; ++p) {
1673 float distSq = GetDistanceSq(b.x, b.y, pocketPositions[p].x, pocketPositions[p].y);
1674 // --- Use updated POCKET_RADIUS ---
1675 if (distSq < POCKET_RADIUS * POCKET_RADIUS) {
1676 b.isPocketed = true;
1677 b.vx = b.vy = 0;
1678 pocketedThisTurn.push_back(b.id);
1679
1680 // --- Play Pocket Sound (Threaded) ---
1681 if (!ballPocketedThisCheck) {
1682 std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("pocket.wav")).detach();
1683 ballPocketedThisCheck = true;
1684 }
1685 // --- End Sound ---
1686
1687 break; // Ball is pocketed
1688 }
1689 }
1690 }
1691 }
1692 return ballPocketedThisCheck;
1693}
1694
1695bool AreBallsMoving() {
1696 for (size_t i = 0; i < balls.size(); ++i) {
1697 if (!balls[i].isPocketed && (balls[i].vx != 0 || balls[i].vy != 0)) {
1698 return true;
1699 }
1700 }
1701 return false;
1702}
1703
1704void RespawnCueBall(bool behindHeadstring) { // 'behindHeadstring' only relevant for initial break placement
1705 Ball* cueBall = GetCueBall();
1706 if (cueBall) {
1707 // Reset position to a default
1708 //disabled for behind headstring (now move anywhere)
1709 /*cueBall->x = HEADSTRING_X * 0.5f;
1710 cueBall->y = TABLE_TOP + TABLE_HEIGHT / 2.0f;*/
1711 // Reset position to a default:
1712 if (behindHeadstring) {
1713 // Opening break: kitchen center
1714 cueBall->x = HEADSTRING_X * 0.5f;
1715 cueBall->y = TABLE_TOP + TABLE_HEIGHT / 2.0f;
1716 }
1717 else {
1718 // Ball-in-hand (foul): center of full table
1719 cueBall->x = TABLE_LEFT + TABLE_WIDTH / 2.0f;
1720 cueBall->y = TABLE_TOP + TABLE_HEIGHT / 2.0f;
1721 }
1722 cueBall->vx = 0;
1723 cueBall->vy = 0;
1724 cueBall->isPocketed = false;
1725
1726 // Set state based on who gets ball-in-hand
1727 /*// 'currentPlayer' already reflects who's turn it is NOW (switched before calling this)*/
1728 // 'currentPlayer' has already been switched to the player whose turn it will be.
1729 // The 'behindHeadstring' parameter to RespawnCueBall is mostly for historical reasons / initial setup.
1730 if (currentPlayer == 1) { // Player 2 (AI/Human) fouled, Player 1 (Human) gets ball-in-hand
1731 currentGameState = BALL_IN_HAND_P1;
1732 aiTurnPending = false; // Ensure AI flag off
1733 }
1734 else { // Player 1 (Human) fouled, Player 2 gets ball-in-hand
1735 if (isPlayer2AI) {
1736 // --- CONFIRMED FIX: Set correct state for AI Ball-in-Hand ---
1737 currentGameState = BALL_IN_HAND_P2; // AI now needs to place the ball
1738 aiTurnPending = true; // Trigger AI logic (will call AIPlaceCueBall first)
1739 }
1740 else { // Human Player 2
1741 currentGameState = BALL_IN_HAND_P2;
1742 aiTurnPending = false; // Ensure AI flag off
1743 }
1744 }
1745 // Handle initial placement state correctly if called from InitGame
1746 /*if (behindHeadstring && currentGameState != PRE_BREAK_PLACEMENT) {
1747 // This case might need review depending on exact initial setup flow,
1748 // but the foul logic above should now be correct.
1749 // Let's ensure initial state is PRE_BREAK_PLACEMENT if behindHeadstring is true.*/
1750 //currentGameState = PRE_BREAK_PLACEMENT;
1751 }
1752}
1753//}
1754
1755
1756// --- Game Logic ---
1757
1758void ApplyShot(float power, float angle, float spinX, float spinY) {
1759 Ball* cueBall = GetCueBall();
1760 if (cueBall) {
1761
1762 // --- Play Cue Strike Sound (Threaded) ---
1763 if (power > 0.1f) { // Only play if it's an audible shot
1764 std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
1765 }
1766 // --- End Sound ---
1767
1768 cueBall->vx = cosf(angle) * power;
1769 cueBall->vy = sinf(angle) * power;
1770
1771 // Apply English (Spin) - Simplified effect (Unchanged)
1772 cueBall->vx += sinf(angle) * spinY * 0.5f;
1773 cueBall->vy -= cosf(angle) * spinY * 0.5f;
1774 cueBall->vx -= cosf(angle) * spinX * 0.5f;
1775 cueBall->vy -= sinf(angle) * spinX * 0.5f;
1776
1777 // Store spin (Unchanged)
1778 cueSpinX = spinX;
1779 cueSpinY = spinY;
1780
1781 // --- Reset Foul Tracking flags for the new shot ---
1782 // (Also reset in LBUTTONUP, but good to ensure here too)
1783 firstHitBallIdThisShot = -1; // No ball hit yet
1784 cueHitObjectBallThisShot = false; // Cue hasn't hit anything yet
1785 railHitAfterContact = false; // No rail hit after contact yet
1786 // --- End Reset ---
1787
1788 // If this was the opening break shot, clear the flag
1789 if (isOpeningBreakShot) {
1790 isOpeningBreakShot = false; // Mark opening break as taken
1791 }
1792 }
1793}
1794
1795
1796void ProcessShotResults() {
1797 bool cueBallPocketed = false;
1798 bool eightBallPocketed = false;
1799 bool legalBallPocketed = false;
1800 bool opponentBallPocketed = false;
1801 bool anyNonCueBallPocketed = false; // Includes opponent balls
1802 BallType firstPocketedType = BallType::NONE;
1803 int firstPocketedId = -1;
1804
1805 PlayerInfo& currentPlayerInfo = (currentPlayer == 1) ? player1Info : player2Info;
1806 PlayerInfo& opponentPlayerInfo = (currentPlayer == 1) ? player2Info : player1Info;
1807
1808 // Analyze pocketed balls (Unchanged logic)
1809 for (int pocketedId : pocketedThisTurn) {
1810 Ball* b = GetBallById(pocketedId);
1811 if (!b) continue;
1812 if (!pocketedThisTurn.empty()) {
1813 pocketFlashTimer = 1.0f; // Flash boost when any ball is pocketed
1814 }
1815 if (b->id == 0) { cueBallPocketed = true; }
1816 else if (b->id == 8) { eightBallPocketed = true; }
1817 else {
1818 anyNonCueBallPocketed = true;
1819 if (firstPocketedId == -1) { firstPocketedId = b->id; firstPocketedType = b->type; }
1820 if (currentPlayerInfo.assignedType != BallType::NONE) {
1821 if (b->type == currentPlayerInfo.assignedType) legalBallPocketed = true;
1822 else if (b->type == opponentPlayerInfo.assignedType) opponentBallPocketed = true;
1823 }
1824 }
1825 }
1826
1827 // --- Game Over Checks --- (Unchanged logic)
1828 if (eightBallPocketed) {
1829 CheckGameOverConditions(eightBallPocketed, cueBallPocketed);
1830 if (currentGameState == GAME_OVER) return;
1831 }
1832
1833 // --- MODIFIED: Enhanced Foul Checks ---
1834 bool turnFoul = false;
1835
1836 // Foul 1: Scratch (Cue ball pocketed)
1837 if (cueBallPocketed) {
1838 foulCommitted = true; turnFoul = true;
1839 }
1840
1841 // Foul 2: Hit Nothing (Only if not already a scratch)
1842 // Condition: Cue ball didn't hit *any* object ball during the shot.
1843 if (!turnFoul && !cueHitObjectBallThisShot) {
1844 // Check if the cue ball actually moved significantly to constitute a shot attempt
1845 Ball* cue = GetCueBall();
1846 // Use a small threshold to avoid foul on accidental tiny nudge if needed
1847 // For now, any shot attempt that doesn't hit an object ball is a foul.
1848 // (Could add velocity check from ApplyShot if needed)
1849 if (cue) { // Ensure cue ball exists
1850 foulCommitted = true; turnFoul = true;
1851 }
1852 }
1853
1854 // Foul 3: Wrong Ball First (Check only if not already foul and *something* was hit)
1855 if (!turnFoul && firstHitBallIdThisShot != -1) {
1856 Ball* firstHitBall = GetBallById(firstHitBallIdThisShot);
1857 if (firstHitBall) {
1858 bool isBreakShot = (player1Info.assignedType == BallType::NONE && player2Info.assignedType == BallType::NONE);
1859 bool mustTarget8Ball = (!isBreakShot && currentPlayerInfo.assignedType != BallType::NONE && currentPlayerInfo.ballsPocketedCount >= 7);
1860
1861 if (!isBreakShot) { // Standard play rules
1862 if (mustTarget8Ball) {
1863 if (firstHitBall->id != 8) { foulCommitted = true; turnFoul = true; }
1864 }
1865 else if (currentPlayerInfo.assignedType != BallType::NONE) { // Colors assigned
1866 // Illegal to hit opponent ball OR 8-ball first
1867 if (firstHitBall->type == opponentPlayerInfo.assignedType || firstHitBall->id == 8) {
1868 foulCommitted = true; turnFoul = true;
1869 }
1870 }
1871 // If colors NOT assigned yet (e.g. shot immediately after break), hitting any ball is legal first.
1872 }
1873 // No specific first-hit foul rules applied for the break itself here.
1874 }
1875 }
1876
1877 // Foul 4: No Rail After Contact (Check only if not already foul)
1878 // Condition: Cue hit an object ball, BUT after that first contact,
1879 // NO ball hit a rail AND NO object ball was pocketed (excluding cue/8-ball).
1880 if (!turnFoul && cueHitObjectBallThisShot && !railHitAfterContact && !anyNonCueBallPocketed) {
1881 foulCommitted = true;
1882 turnFoul = true;
1883 }
1884
1885 // Foul 5: Pocketing Opponent's Ball (Optional stricter rule - can uncomment if desired)
1886 // if (!turnFoul && opponentBallPocketed) {
1887 // foulCommitted = true; turnFoul = true;
1888 // }
1889 // --- End Enhanced Foul Checks ---
1890
1891
1892 // --- State Transitions ---
1893 if (turnFoul) {
1894 SwitchTurns();
1895 RespawnCueBall(false); // Ball in hand for opponent (state set in Respawn)
1896 }
1897 // --- Assign Ball Types only AFTER checking for fouls on the break/first shot ---
1898 else if (player1Info.assignedType == BallType::NONE && anyNonCueBallPocketed) {
1899 // (Assign types logic - unchanged)
1900 bool firstTypeVerified = false;
1901 for (int id : pocketedThisTurn) { if (id == firstPocketedId) { firstTypeVerified = true; break; } }
1902
1903 if (firstTypeVerified && (firstPocketedType == BallType::SOLID || firstPocketedType == BallType::STRIPE)) {
1904 AssignPlayerBallTypes(firstPocketedType);
1905 legalBallPocketed = true;
1906 }
1907 // After assignment (or if types already assigned), check if turn continues
1908 if (legalBallPocketed) { // Player legally pocketed their assigned type (newly or existing)
1909 currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
1910 if (currentPlayer == 2 && isPlayer2AI) aiTurnPending = true;
1911 }
1912 else { // Pocketed wrong ball, or only opponent ball, or missed (but no foul committed)
1913 SwitchTurns();
1914 }
1915 }
1916 // --- Normal Play Results (Types Assigned) ---
1917 else if (player1Info.assignedType != BallType::NONE) { // Ensure types assigned before this block
1918 if (legalBallPocketed) { // Legally pocketed own ball
1919 currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
1920 if (currentPlayer == 2 && isPlayer2AI) aiTurnPending = true; // AI continues turn
1921 }
1922 else { // No legal ball pocketed (or no ball pocketed at all) and no foul
1923 SwitchTurns();
1924 }
1925 }
1926 // --- Handle case where shot occurred but no balls pocketed and no foul ---
1927 else if (!anyNonCueBallPocketed && !turnFoul) {
1928 SwitchTurns();
1929 }
1930
1931
1932 // Update pocketed counts AFTER handling turns/fouls/assignment
1933 int p1NewlyPocketed = 0;
1934 int p2NewlyPocketed = 0;
1935 for (int id : pocketedThisTurn) {
1936 if (id == 0 || id == 8) continue; // Skip cue ball and 8-ball
1937 Ball* b = GetBallById(id);
1938 if (!b) continue; // extra safety
1939 if (b->type == player1Info.assignedType) p1NewlyPocketed++;
1940 else if (b->type == player2Info.assignedType) p2NewlyPocketed++;
1941 }
1942 if (currentGameState != GAME_OVER) {
1943 player1Info.ballsPocketedCount += p1NewlyPocketed;
1944 player2Info.ballsPocketedCount += p2NewlyPocketed;
1945 }
1946
1947
1948 // --- Cleanup for next actual shot attempt ---
1949 pocketedThisTurn.clear();
1950 // Reset foul tracking flags (done before next shot applied)
1951 // firstHitBallIdThisShot = -1; // Reset these before next shot call
1952 // cueHitObjectBallThisShot = false;
1953 // railHitAfterContact = false;
1954}
1955
1956void AssignPlayerBallTypes(BallType firstPocketedType) {
1957 if (firstPocketedType == BallType::SOLID || firstPocketedType == BallType::STRIPE) {
1958 if (currentPlayer == 1) {
1959 player1Info.assignedType = firstPocketedType;
1960 player2Info.assignedType = (firstPocketedType == BallType::SOLID) ? BallType::STRIPE : BallType::SOLID;
1961 }
1962 else {
1963 player2Info.assignedType = firstPocketedType;
1964 player1Info.assignedType = (firstPocketedType == BallType::SOLID) ? BallType::STRIPE : BallType::SOLID;
1965 }
1966 }
1967 // If 8-ball was first (illegal on break generally), rules vary.
1968 // Here, we might ignore assignment until a solid/stripe is pocketed legally.
1969 // Or assign based on what *else* was pocketed, if anything.
1970 // Simplification: Assignment only happens on SOLID or STRIPE first pocket.
1971}
1972
1973void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed) {
1974 if (!eightBallPocketed) return; // Only proceed if 8-ball was pocketed
1975
1976 PlayerInfo& currentPlayerInfo = (currentPlayer == 1) ? player1Info : player2Info;
1977 bool playerClearedBalls = (currentPlayerInfo.assignedType != BallType::NONE && currentPlayerInfo.ballsPocketedCount >= 7);
1978
1979 // Loss Conditions:
1980 // 1. Pocket 8-ball AND scratch (pocket cue ball)
1981 // 2. Pocket 8-ball before clearing own color group
1982 if (cueBallPocketed || (!playerClearedBalls && currentPlayerInfo.assignedType != BallType::NONE)) {
1983 gameOverMessage = (currentPlayer == 1) ? L"Player 2 Wins! (Player 1 fouled on 8-ball)" : L"Player 1 Wins! (Player 2 fouled on 8-ball)";
1984 currentGameState = GAME_OVER;
1985 }
1986 // Win Condition:
1987 // 1. Pocket 8-ball legally after clearing own color group
1988 else if (playerClearedBalls) {
1989 gameOverMessage = (currentPlayer == 1) ? L"Player 1 Wins!" : L"Player 2 Wins!";
1990 currentGameState = GAME_OVER;
1991 }
1992 // Special case: 8 ball pocketed on break. Usually re-spot or re-rack.
1993 // Simple: If it happens during assignment phase, treat as foul, respawn 8ball.
1994 else if (player1Info.assignedType == BallType::NONE) {
1995 Ball* eightBall = GetBallById(8);
1996 if (eightBall) {
1997 eightBall->isPocketed = false;
1998 // Place 8-ball on foot spot (approx RACK_POS_X) or center if occupied
1999 eightBall->x = RACK_POS_X;
2000 eightBall->y = RACK_POS_Y;
2001 eightBall->vx = eightBall->vy = 0;
2002 // Check overlap and nudge if necessary (simplified)
2003 }
2004 // Apply foul rules if cue ball was also pocketed
2005 if (cueBallPocketed) {
2006 foulCommitted = true;
2007 // Don't switch turns on break scratch + 8ball pocket? Rules vary.
2008 // Let's make it a foul, switch turns, ball in hand.
2009 SwitchTurns();
2010 RespawnCueBall(false); // Ball in hand for opponent
2011 }
2012 else {
2013 // Just respawned 8ball, continue turn or switch based on other balls pocketed.
2014 // Let ProcessShotResults handle turn logic based on other pocketed balls.
2015 }
2016 // Prevent immediate game over message by returning here
2017 return;
2018 }
2019
2020
2021}
2022
2023
2024void SwitchTurns() {
2025 currentPlayer = (currentPlayer == 1) ? 2 : 1;
2026 // Reset aiming state for the new player
2027 isAiming = false;
2028 shotPower = 0;
2029 // Reset foul flag before new turn *really* starts (AI might take over)
2030 // Foul flag is mainly for display, gets cleared before human/AI shot
2031 // foulCommitted = false; // Probably better to clear before ApplyShot
2032
2033 // Set the correct state based on who's turn it is
2034 if (currentPlayer == 1) {
2035 currentGameState = PLAYER1_TURN;
2036 aiTurnPending = false; // Ensure AI flag is off for P1
2037 }
2038 else { // Player 2's turn
2039 if (isPlayer2AI) {
2040 currentGameState = PLAYER2_TURN; // State indicates it's P2's turn
2041 aiTurnPending = true; // Set flag for GameUpdate to trigger AI
2042 // AI will handle Ball-in-Hand logic if necessary within its decision making
2043 }
2044 else {
2045 currentGameState = PLAYER2_TURN; // Human P2
2046 aiTurnPending = false;
2047 }
2048 }
2049}
2050
2051void AIBreakShot() {
2052 Ball* cueBall = GetCueBall();
2053 if (!cueBall) return;
2054
2055 // This function is called when it's AI's turn for the opening break and state is PRE_BREAK_PLACEMENT.
2056 // AI will place the cue ball and then plan the shot.
2057 if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT) {
2058 // Place cue ball in the kitchen randomly
2059 /*float kitchenMinX = TABLE_LEFT + BALL_RADIUS; // [cite: 1071, 1072, 1587]
2060 float kitchenMaxX = HEADSTRING_X - BALL_RADIUS; // [cite: 1072, 1078, 1588]
2061 float kitchenMinY = TABLE_TOP + BALL_RADIUS; // [cite: 1071, 1072, 1588]
2062 float kitchenMaxY = TABLE_BOTTOM - BALL_RADIUS; // [cite: 1072, 1073, 1589]*/
2063
2064 // --- AI Places Cue Ball for Break ---
2065// Decide if placing center or side. For simplicity, let's try placing slightly off-center
2066// towards one side for a more angled break, or center for direct apex hit.
2067// A common strategy is to hit the second ball of the rack.
2068
2069 float placementY = RACK_POS_Y; // Align vertically with the rack center
2070 float placementX;
2071
2072 // Randomly choose a side or center-ish placement for variation.
2073 int placementChoice = rand() % 3; // 0: Left-ish, 1: Center-ish, 2: Right-ish in kitchen
2074
2075 if (placementChoice == 0) { // Left-ish
2076 placementX = HEADSTRING_X - (TABLE_WIDTH * 0.05f) - (BALL_RADIUS * (1 + (rand() % 3))); // Place slightly to the left within kitchen
2077 }
2078 else if (placementChoice == 2) { // Right-ish
2079 placementX = HEADSTRING_X - (TABLE_WIDTH * 0.05f) + (BALL_RADIUS * (1 + (rand() % 3))); // Place slightly to the right within kitchen
2080 }
2081 else { // Center-ish
2082 placementX = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f; // Roughly center of kitchen
2083 }
2084 placementX = std::max(TABLE_LEFT + BALL_RADIUS + 1.0f, std::min(placementX, HEADSTRING_X - BALL_RADIUS - 1.0f)); // Clamp within kitchen X
2085
2086 bool validPos = false;
2087 int attempts = 0;
2088 while (!validPos && attempts < 100) {
2089 /*cueBall->x = kitchenMinX + static_cast<float>(rand()) / (static_cast<float>(RAND_MAX) / (kitchenMaxX - kitchenMinX)); // [cite: 1589]
2090 cueBall->y = kitchenMinY + static_cast<float>(rand()) / (static_cast<float>(RAND_MAX) / (kitchenMaxY - kitchenMinY)); // [cite: 1590]
2091 if (IsValidCueBallPosition(cueBall->x, cueBall->y, true)) { // [cite: 1591]
2092 validPos = true; // [cite: 1591]*/
2093 // Try the chosen X, but vary Y slightly to find a clear spot
2094 cueBall->x = placementX;
2095 cueBall->y = placementY + (static_cast<float>(rand() % 100 - 50) / 100.0f) * BALL_RADIUS * 2.0f; // Vary Y a bit
2096 cueBall->y = std::max(TABLE_TOP + BALL_RADIUS + 1.0f, std::min(cueBall->y, TABLE_BOTTOM - BALL_RADIUS - 1.0f)); // Clamp Y
2097
2098 if (IsValidCueBallPosition(cueBall->x, cueBall->y, true /* behind headstring */)) {
2099 validPos = true;
2100 }
2101 attempts++; // [cite: 1592]
2102 }
2103 if (!validPos) {
2104 // Fallback position
2105 /*cueBall->x = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f; // [cite: 1071, 1078, 1593]
2106 cueBall->y = (TABLE_TOP + TABLE_BOTTOM) * 0.5f; // [cite: 1071, 1073, 1594]
2107 if (!IsValidCueBallPosition(cueBall->x, cueBall->y, true)) { // [cite: 1594]
2108 cueBall->x = HEADSTRING_X - BALL_RADIUS * 2; // [cite: 1072, 1078, 1594]
2109 cueBall->y = RACK_POS_Y; // [cite: 1080, 1595]
2110 }
2111 }
2112 cueBall->vx = 0; // [cite: 1595]
2113 cueBall->vy = 0; // [cite: 1596]
2114
2115 // Plan a break shot: aim at the center of the rack (apex ball)
2116 float targetX = RACK_POS_X; // [cite: 1079] Aim for the apex ball X-coordinate
2117 float targetY = RACK_POS_Y; // [cite: 1080] Aim for the apex ball Y-coordinate
2118
2119 float dx = targetX - cueBall->x; // [cite: 1599]
2120 float dy = targetY - cueBall->y; // [cite: 1600]
2121 float shotAngle = atan2f(dy, dx); // [cite: 1600]
2122 float shotPowerValue = MAX_SHOT_POWER; // [cite: 1076, 1600] Use MAX_SHOT_POWER*/
2123
2124 cueBall->x = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.75f; // A default safe spot in kitchen
2125 cueBall->y = RACK_POS_Y;
2126 }
2127 cueBall->vx = 0; cueBall->vy = 0;
2128
2129 // --- AI Plans the Break Shot ---
2130 float targetX, targetY;
2131 // If cue ball is near center of kitchen width, aim for apex.
2132 // Otherwise, aim for the second ball on the side the cue ball is on (for a cut break).
2133 float kitchenCenterRegion = (HEADSTRING_X - TABLE_LEFT) * 0.3f; // Define a "center" region
2134 if (std::abs(cueBall->x - (TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) / 2.0f)) < kitchenCenterRegion / 2.0f) {
2135 // Center-ish placement: Aim for the apex ball (ball ID 1 or first ball in rack)
2136 targetX = RACK_POS_X; // Apex ball X
2137 targetY = RACK_POS_Y; // Apex ball Y
2138 }
2139 else {
2140 // Side placement: Aim to hit the "second" ball of the rack for a wider spread.
2141 // This is a simplification. A more robust way is to find the actual second ball.
2142 // For now, aim slightly off the apex towards the side the cue ball is on.
2143 targetX = RACK_POS_X + BALL_RADIUS * 2.0f * 0.866f; // X of the second row of balls
2144 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
2145 }
2146
2147 float dx = targetX - cueBall->x;
2148 float dy = targetY - cueBall->y;
2149 float shotAngle = atan2f(dy, dx);
2150 float shotPowerValue = MAX_SHOT_POWER * (0.9f + (rand() % 11) / 100.0f); // Slightly vary max power
2151
2152 // Store planned shot details for the AI
2153 /*aiPlannedShotDetails.angle = shotAngle; // [cite: 1102, 1601]
2154 aiPlannedShotDetails.power = shotPowerValue; // [cite: 1102, 1601]
2155 aiPlannedShotDetails.spinX = 0.0f; // [cite: 1102, 1601] No spin for a standard power break
2156 aiPlannedShotDetails.spinY = 0.0f; // [cite: 1103, 1602]
2157 aiPlannedShotDetails.isValid = true; // [cite: 1103, 1602]*/
2158
2159 aiPlannedShotDetails.angle = shotAngle;
2160 aiPlannedShotDetails.power = shotPowerValue;
2161 aiPlannedShotDetails.spinX = 0.0f; // No spin for break usually
2162 aiPlannedShotDetails.spinY = 0.0f;
2163 aiPlannedShotDetails.isValid = true;
2164
2165 // Update global cue parameters for immediate visual feedback if DrawAimingAids uses them
2166 /*::cueAngle = aiPlannedShotDetails.angle; // [cite: 1109, 1603] Update global cueAngle
2167 ::shotPower = aiPlannedShotDetails.power; // [cite: 1109, 1604] Update global shotPower
2168 ::cueSpinX = aiPlannedShotDetails.spinX; // [cite: 1109]
2169 ::cueSpinY = aiPlannedShotDetails.spinY; // [cite: 1110]*/
2170
2171 ::cueAngle = aiPlannedShotDetails.angle;
2172 ::shotPower = aiPlannedShotDetails.power;
2173 ::cueSpinX = aiPlannedShotDetails.spinX;
2174 ::cueSpinY = aiPlannedShotDetails.spinY;
2175
2176 // Set up for AI display via GameUpdate
2177 /*aiIsDisplayingAim = true; // [cite: 1104] Enable AI aiming visualization
2178 aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES; // [cite: 1105] Set duration for display
2179
2180 currentGameState = AI_THINKING; // [cite: 1081] Transition to AI_THINKING state.
2181 // GameUpdate will handle the aiAimDisplayFramesLeft countdown
2182 // and then execute the shot using aiPlannedShotDetails.
2183 // isOpeningBreakShot will be set to false within ApplyShot.
2184
2185 // No immediate ApplyShot or sound here; GameUpdate's AI execution logic will handle it.*/
2186
2187 aiIsDisplayingAim = true;
2188 aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES;
2189 currentGameState = AI_THINKING; // State changes to AI_THINKING, GameUpdate will handle shot execution after display
2190
2191 return; // The break shot is now planned and will be executed by GameUpdate
2192 }
2193
2194 // 2. If not in PRE_BREAK_PLACEMENT (e.g., if this function were called at other times,
2195 // though current game logic only calls it for PRE_BREAK_PLACEMENT)
2196 // This part can be extended if AIBreakShot needs to handle other scenarios.
2197 // For now, the primary logic is above.
2198}
2199
2200// --- Helper Functions ---
2201
2202Ball* GetBallById(int id) {
2203 for (size_t i = 0; i < balls.size(); ++i) {
2204 if (balls[i].id == id) {
2205 return &balls[i];
2206 }
2207 }
2208 return nullptr;
2209}
2210
2211Ball* GetCueBall() {
2212 return GetBallById(0);
2213}
2214
2215float GetDistance(float x1, float y1, float x2, float y2) {
2216 return sqrtf(GetDistanceSq(x1, y1, x2, y2));
2217}
2218
2219float GetDistanceSq(float x1, float y1, float x2, float y2) {
2220 float dx = x2 - x1;
2221 float dy = y2 - y1;
2222 return dx * dx + dy * dy;
2223}
2224
2225bool IsValidCueBallPosition(float x, float y, bool checkHeadstring) {
2226 // Basic bounds check (inside cushions)
2227 float left = TABLE_LEFT + CUSHION_THICKNESS + BALL_RADIUS;
2228 float right = TABLE_RIGHT - CUSHION_THICKNESS - BALL_RADIUS;
2229 float top = TABLE_TOP + CUSHION_THICKNESS + BALL_RADIUS;
2230 float bottom = TABLE_BOTTOM - CUSHION_THICKNESS - BALL_RADIUS;
2231
2232 if (x < left || x > right || y < top || y > bottom) {
2233 return false;
2234 }
2235
2236 // Check headstring restriction if needed
2237 if (checkHeadstring && x >= HEADSTRING_X) {
2238 return false;
2239 }
2240
2241 // Check overlap with other balls
2242 for (size_t i = 0; i < balls.size(); ++i) {
2243 if (balls[i].id != 0 && !balls[i].isPocketed) { // Don't check against itself or pocketed balls
2244 if (GetDistanceSq(x, y, balls[i].x, balls[i].y) < (BALL_RADIUS * 2.0f) * (BALL_RADIUS * 2.0f)) {
2245 return false; // Overlapping another ball
2246 }
2247 }
2248 }
2249
2250 return true;
2251}
2252
2253
2254template <typename T>
2255void SafeRelease(T** ppT) {
2256 if (*ppT) {
2257 (*ppT)->Release();
2258 *ppT = nullptr;
2259 }
2260}
2261
2262// --- Helper Function for Line Segment Intersection ---
2263// Finds intersection point of line segment P1->P2 and line segment P3->P4
2264// Returns true if they intersect, false otherwise. Stores intersection point in 'intersection'.
2265bool LineSegmentIntersection(D2D1_POINT_2F p1, D2D1_POINT_2F p2, D2D1_POINT_2F p3, D2D1_POINT_2F p4, D2D1_POINT_2F& intersection)
2266{
2267 float denominator = (p4.y - p3.y) * (p2.x - p1.x) - (p4.x - p3.x) * (p2.y - p1.y);
2268
2269 // Check if lines are parallel or collinear
2270 if (fabs(denominator) < 1e-6) {
2271 return false;
2272 }
2273
2274 float ua = ((p4.x - p3.x) * (p1.y - p3.y) - (p4.y - p3.y) * (p1.x - p3.x)) / denominator;
2275 float ub = ((p2.x - p1.x) * (p1.y - p3.y) - (p2.y - p1.y) * (p1.x - p3.x)) / denominator;
2276
2277 // Check if intersection point lies on both segments
2278 if (ua >= 0.0f && ua <= 1.0f && ub >= 0.0f && ub <= 1.0f) {
2279 intersection.x = p1.x + ua * (p2.x - p1.x);
2280 intersection.y = p1.y + ua * (p2.y - p1.y);
2281 return true;
2282 }
2283
2284 return false;
2285}
2286
2287// --- INSERT NEW HELPER FUNCTION HERE ---
2288// Calculates the squared distance from point P to the line segment AB.
2289float PointToLineSegmentDistanceSq(D2D1_POINT_2F p, D2D1_POINT_2F a, D2D1_POINT_2F b) {
2290 float l2 = GetDistanceSq(a.x, a.y, b.x, b.y);
2291 if (l2 == 0.0f) return GetDistanceSq(p.x, p.y, a.x, a.y); // Segment is a point
2292 // Consider P projecting onto the line AB infinite line
2293 // t = [(P-A) . (B-A)] / |B-A|^2
2294 float t = ((p.x - a.x) * (b.x - a.x) + (p.y - a.y) * (b.y - a.y)) / l2;
2295 t = std::max(0.0f, std::min(1.0f, t)); // Clamp t to the segment [0, 1]
2296 // Projection falls on the segment
2297 D2D1_POINT_2F projection = D2D1::Point2F(a.x + t * (b.x - a.x), a.y + t * (b.y - a.y));
2298 return GetDistanceSq(p.x, p.y, projection.x, projection.y);
2299}
2300// --- End New Helper ---
2301
2302// --- NEW AI Implementation Functions ---
2303
2304// Main entry point for AI turn
2305void AIMakeDecision() {
2306 //AIShotInfo bestShot = { false }; // Declare here
2307 // This function is called when currentGameState is AI_THINKING (for a normal shot decision)
2308 Ball* cueBall = GetCueBall();
2309 if (!cueBall || !isPlayer2AI || currentPlayer != 2) {
2310 aiPlannedShotDetails.isValid = false; // Ensure no shot if conditions not met
2311 return;
2312 }
2313
2314 // Phase 1: Placement if needed (Ball-in-Hand or Initial Break)
2315 /*if ((isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT) || currentGameState == BALL_IN_HAND_P2) {
2316 AIPlaceCueBall(); // Handles kitchen placement for break or regular ball-in-hand
2317 if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT) {
2318 currentGameState = BREAKING; // Now AI needs to decide the break shot parameters
2319 }
2320 // For regular BALL_IN_HAND_P2, after placement, it will proceed to find a shot.
2321 }*/
2322
2323 aiPlannedShotDetails.isValid = false; // Default to no valid shot found yet for this decision cycle
2324 // Note: isOpeningBreakShot is false here because AIBreakShot handles the break.
2325
2326 // Phase 2: Decide shot parameters (Break or Normal play)
2327 /*if (isOpeningBreakShot && currentGameState == BREAKING) {
2328 // Force cue ball into center of kitchen
2329 cueBall->x = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f;
2330 cueBall->y = (TABLE_TOP + TABLE_BOTTOM) * 0.5f;
2331 cueBall->vx = cueBall->vy = 0.0f;
2332
2333 float rackCenterX = RACK_POS_X + BALL_RADIUS * 2.0f * 0.866f * 2.0f;
2334 float rackCenterY = RACK_POS_Y;
2335 float dx = rackCenterX - cueBall->x;
2336 float dy = rackCenterY - cueBall->y;
2337
2338 aiPlannedShotDetails.angle = atan2f(dy, dx);
2339 aiPlannedShotDetails.power = MAX_SHOT_POWER;
2340 aiPlannedShotDetails.spinX = 0.0f;
2341 aiPlannedShotDetails.spinY = 0.0f;
2342 aiPlannedShotDetails.isValid = true;
2343
2344 // Apply shot immediately
2345 cueAngle = aiPlannedShotDetails.angle;
2346 shotPower = aiPlannedShotDetails.power;
2347 cueSpinX = aiPlannedShotDetails.spinX;
2348 cueSpinY = aiPlannedShotDetails.spinY;
2349
2350 firstHitBallIdThisShot = -1;
2351 cueHitObjectBallThisShot = false;
2352 railHitAfterContact = false;
2353 isAiming = false;
2354 aiIsDisplayingAim = false;
2355 aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES;
2356 //bool aiIsDisplayingAim = true;
2357
2358 std::thread([](const TCHAR* soundName) {
2359 PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT);
2360 }, TEXT("cue.wav")).detach();
2361
2362 ApplyShot(shotPower, cueAngle, cueSpinX, cueSpinY);
2363 currentGameState = SHOT_IN_PROGRESS;
2364 isOpeningBreakShot = false;
2365 aiTurnPending = false;
2366 pocketedThisTurn.clear();
2367 return;
2368 }
2369 else {*/
2370 // --- Normal AI Shot Decision (using AIFindBestShot) ---
2371 AIShotInfo bestShot = AIFindBestShot(); // bugtraq
2372 //bestShot = AIFindBestShot(); // bugtraq
2373 if (bestShot.possible) {
2374 aiPlannedShotDetails.angle = bestShot.angle;
2375 aiPlannedShotDetails.power = bestShot.power;
2376 aiPlannedShotDetails.spinX = 0.0f; // AI doesn't use spin yet
2377 aiPlannedShotDetails.spinY = 0.0f;
2378 aiPlannedShotDetails.isValid = true;
2379 }
2380 else {
2381 // Safety tap if no better shot found
2382 // Try to hit the closest 'own' ball gently or any ball if types not assigned
2383 Ball* ballToNudge = nullptr;
2384 float minDistSq = -1.0f;
2385 BallType aiTargetType = player2Info.assignedType;
2386 bool mustHit8Ball = (aiTargetType != BallType::NONE && player2Info.ballsPocketedCount >= 7);
2387
2388 for (auto& b : balls) {
2389 if (b.isPocketed || b.id == 0) continue;
2390 bool canHitThis = false;
2391 if (mustHit8Ball) canHitThis = (b.id == 8);
2392 else if (aiTargetType != BallType::NONE) canHitThis = (b.type == aiTargetType);
2393 else canHitThis = (b.id != 8); // Can hit any non-8-ball if types not assigned
2394
2395 if (canHitThis) {
2396 float dSq = GetDistanceSq(cueBall->x, cueBall->y, b.x, b.y);
2397 if (ballToNudge == nullptr || dSq < minDistSq) {
2398 ballToNudge = &b;
2399 minDistSq = dSq;
2400 }
2401 }
2402 }
2403 if (ballToNudge) { // Found a ball to nudge
2404 aiPlannedShotDetails.angle = atan2f(ballToNudge->y - cueBall->y, ballToNudge->x - cueBall->x);
2405 aiPlannedShotDetails.power = MAX_SHOT_POWER * 0.15f; // Gentle tap
2406 }
2407 else { // Absolute fallback: small tap forward
2408 aiPlannedShotDetails.angle = cueAngle; // Keep last angle or default
2409 //aiPlannedShotDetails.power = MAX_SHOT_POWER * 0.1f;
2410 aiPlannedShotDetails.power = MAX_SHOT_POWER * 0.1f;
2411 }
2412 aiPlannedShotDetails.spinX = 0.0f;
2413 aiPlannedShotDetails.spinY = 0.0f;
2414 aiPlannedShotDetails.isValid = true; // Safety shot is a "valid" plan
2415 }
2416 //} //bracefix
2417
2418 // Phase 3: Setup for Aim Display (if a valid shot was decided)
2419 if (aiPlannedShotDetails.isValid) {
2420 cueAngle = aiPlannedShotDetails.angle; // Update global for drawing
2421 shotPower = aiPlannedShotDetails.power; // Update global for drawing
2422 // cueSpinX and cueSpinY could also be set here if AI used them
2423 cueSpinX = aiPlannedShotDetails.spinX; // Also set these for drawing consistency
2424 cueSpinY = aiPlannedShotDetails.spinY; //
2425
2426 aiIsDisplayingAim = true;
2427 aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES;
2428 // currentGameState remains AI_THINKING, GameUpdate will handle the display countdown and shot execution.
2429 // FIRE THE BREAK SHOT NOW
2430 // Immediately execute the break shot after setting parameters
2431 /*ApplyShot(aiPlannedShotDetails.power, aiPlannedShotDetails.angle, aiPlannedShotDetails.spinX, aiPlannedShotDetails.spinY);
2432 currentGameState = SHOT_IN_PROGRESS;
2433 aiTurnPending = false;
2434 isOpeningBreakShot = false;*/
2435 }
2436 else {
2437 // Should not happen if safety shot is always planned, but as a fallback:
2438 aiIsDisplayingAim = false;
2439 // If AI truly can't decide anything, maybe switch turn or log error. For now, it will do nothing this frame.
2440 // Or force a minimal safety tap without display.
2441 // To ensure game progresses, let's plan a minimal tap if nothing else.
2442 if (!aiPlannedShotDetails.isValid) { // Double check
2443 aiPlannedShotDetails.angle = 0.0f;
2444 aiPlannedShotDetails.power = MAX_SHOT_POWER * 0.05f; // Very small tap
2445 aiPlannedShotDetails.spinX = 0.0f; aiPlannedShotDetails.spinY = 0.0f;
2446 aiPlannedShotDetails.isValid = true;
2447 //cueAngle = aiPlannedShotDetails.angle; shotPower = aiPlannedShotDetails.power;
2448 cueAngle = aiPlannedShotDetails.angle;
2449 shotPower = aiPlannedShotDetails.power;
2450 cueSpinX = aiPlannedShotDetails.spinX;
2451 cueSpinY = aiPlannedShotDetails.spinY;
2452 aiIsDisplayingAim = true; // Allow display for this minimal tap too
2453 aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES / 2; // Shorter display for fallback
2454 }
2455 }
2456 // aiTurnPending was set to false by GameUpdate before calling AIMakeDecision.
2457 // AIMakeDecision's job is to populate aiPlannedShotDetails and trigger display.
2458}
2459
2460// AI logic for placing cue ball during ball-in-hand
2461void AIPlaceCueBall() {
2462 Ball* cueBall = GetCueBall();
2463 if (!cueBall) return;
2464
2465 // --- CPU AI Opening Break: Kitchen Placement ---
2466 /*if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT && currentPlayer == 2 && isPlayer2AI) {
2467 float kitchenMinX = TABLE_LEFT + BALL_RADIUS;
2468 float kitchenMaxX = HEADSTRING_X - BALL_RADIUS;
2469 float kitchenMinY = TABLE_TOP + BALL_RADIUS;
2470 float kitchenMaxY = TABLE_BOTTOM - BALL_RADIUS;
2471 bool validPositionFound = false;
2472 int attempts = 0;
2473 while (!validPositionFound && attempts < 100) {
2474 cueBall->x = kitchenMinX + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (kitchenMaxX - kitchenMinX)));
2475 cueBall->y = kitchenMinY + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (kitchenMaxY - kitchenMinY)));
2476 if (IsValidCueBallPosition(cueBall->x, cueBall->y, true)) {
2477 validPositionFound = true;
2478 }
2479 attempts++;
2480 }
2481 if (!validPositionFound) {
2482 cueBall->x = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f;
2483 cueBall->y = TABLE_TOP + TABLE_HEIGHT / 2.0f;
2484 if (!IsValidCueBallPosition(cueBall->x, cueBall->y, true)) {
2485 cueBall->x = HEADSTRING_X - BALL_RADIUS * 2.0f;
2486 cueBall->y = RACK_POS_Y;
2487 }
2488 }
2489 cueBall->vx = 0; cueBall->vy = 0;
2490 return;
2491 }*/
2492 // --- End CPU AI Opening Break Placement ---
2493
2494 // This function is now SOLELY for Ball-In-Hand placement for the AI (anywhere on the table).
2495 // Break placement is handled by AIBreakShot().
2496
2497 // Simple Strategy: Find the easiest possible shot for the AI's ball type
2498 // Place the cue ball directly behind that target ball, aiming straight at a pocket.
2499 // (More advanced: find spot offering multiple options or safety)
2500
2501 AIShotInfo bestPlacementShot = { false };
2502 D2D1_POINT_2F bestPlacePos = D2D1::Point2F(HEADSTRING_X * 0.5f, RACK_POS_Y); // Default placement
2503
2504 // A better default for ball-in-hand (anywhere) might be center table if no shot found.
2505 bestPlacePos = D2D1::Point2F(TABLE_LEFT + TABLE_WIDTH / 2.0f, TABLE_TOP + TABLE_HEIGHT / 2.0f);
2506 float bestPlacementScore = -1.0f; // Keep track of the score for the best placement found
2507
2508 BallType targetType = player2Info.assignedType;
2509 bool canTargetAnyPlacement = false; // Local scope variable for placement logic
2510 if (targetType == BallType::NONE) {
2511 canTargetAnyPlacement = true;
2512 }
2513 bool target8Ball = (!canTargetAnyPlacement && targetType != BallType::NONE && player2Info.ballsPocketedCount >= 7);
2514 if (target8Ball) targetType = BallType::EIGHT_BALL;
2515
2516
2517 for (auto& targetBall : balls) {
2518 if (targetBall.isPocketed || targetBall.id == 0) continue;
2519
2520 // Determine if current ball is a valid target for placement consideration
2521 bool currentBallIsValidTarget = false;
2522 if (target8Ball && targetBall.id == 8) currentBallIsValidTarget = true;
2523 else if (canTargetAnyPlacement && targetBall.id != 8) currentBallIsValidTarget = true;
2524 else if (!canTargetAnyPlacement && !target8Ball && targetBall.type == targetType) currentBallIsValidTarget = true;
2525
2526 if (!currentBallIsValidTarget) continue; // Skip if not a valid target
2527
2528 for (int p = 0; p < 6; ++p) {
2529 // Calculate ideal cue ball position: straight line behind target ball aiming at pocket p
2530 float targetToPocketX = pocketPositions[p].x - targetBall.x;
2531 float targetToPocketY = pocketPositions[p].y - targetBall.y;
2532 float dist = sqrtf(targetToPocketX * targetToPocketX + targetToPocketY * targetToPocketY);
2533 if (dist < 1.0f) continue; // Avoid division by zero
2534
2535 float idealAngle = atan2f(targetToPocketY, targetToPocketX);
2536 // Place cue ball slightly behind target ball along this line
2537 float placeDist = BALL_RADIUS * 3.0f; // Place a bit behind
2538 D2D1_POINT_2F potentialPlacePos = D2D1::Point2F( // Use factory function
2539 targetBall.x - cosf(idealAngle) * placeDist,
2540 targetBall.y - sinf(idealAngle) * placeDist
2541 );
2542
2543 // Check if this placement is valid (on table, behind headstring if break, not overlapping)
2544 /*bool behindHeadstringRule = (currentGameState == PRE_BREAK_PLACEMENT);*/
2545 // For ball-in-hand (NOT break), behindHeadstringRule is false.
2546 // The currentGameState should be BALL_IN_HAND_P2 when this is called for a foul.
2547 bool behindHeadstringRule = false; // Player can place anywhere after a foul
2548 if (IsValidCueBallPosition(potentialPlacePos.x, potentialPlacePos.y, behindHeadstringRule)) {
2549 // Is path from potentialPlacePos to targetBall clear?
2550 // Use D2D1::Point2F() factory function here
2551 if (IsPathClear(potentialPlacePos, D2D1::Point2F(targetBall.x, targetBall.y), 0, targetBall.id)) {
2552 // Is path from targetBall to pocket clear?
2553 // Use D2D1::Point2F() factory function here
2554 if (IsPathClear(D2D1::Point2F(targetBall.x, targetBall.y), pocketPositions[p], targetBall.id, -1)) {
2555 // This seems like a good potential placement. Score it?
2556 // Easy AI: Just take the first valid one found.
2557 /*bestPlacePos = potentialPlacePos;
2558 goto placement_found;*/ // Use goto for simplicity in non-OOP structure
2559 // This is a possible shot. Score this placement.
2560// A simple score: distance to target ball (shorter is better for placement).
2561// More advanced: consider angle to pocket, difficulty of the shot from this placement.
2562 AIShotInfo tempShotInfo;
2563 tempShotInfo.possible = true;
2564 tempShotInfo.targetBall = &targetBall;
2565 tempShotInfo.pocketIndex = p;
2566 tempShotInfo.ghostBallPos = CalculateGhostBallPos(&targetBall, p); // Not strictly needed for placement score but good for consistency
2567 tempShotInfo.angle = idealAngle; // The angle from the placed ball to target
2568 // Use EvaluateShot's scoring mechanism if possible, or a simpler one here.
2569 float currentScore = 1000.0f / (1.0f + GetDistance(potentialPlacePos.x, potentialPlacePos.y, targetBall.x, targetBall.y)); // Inverse distance
2570
2571 if (currentScore > bestPlacementScore) {
2572 bestPlacementScore = currentScore;
2573 bestPlacePos = potentialPlacePos;
2574 }
2575 }
2576 }
2577 }
2578 }
2579 }
2580
2581placement_found:
2582 // Place the cue ball at the best found position (or default if no good spot found)
2583 cueBall->x = bestPlacePos.x;
2584 cueBall->y = bestPlacePos.y;
2585 cueBall->vx = 0;
2586 cueBall->vy = 0;
2587}
2588
2589
2590// AI finds the best shot available on the table
2591AIShotInfo AIFindBestShot() {
2592 AIShotInfo bestShotOverall = { false };
2593 Ball* cueBall = GetCueBall();
2594 if (!cueBall) return bestShotOverall;
2595 // Ensure cue ball position is up-to-date if AI just placed it
2596 // (AIPlaceCueBall should have already set cueBall->x, cueBall->y)
2597
2598 // Determine target ball type for AI (Player 2)
2599 BallType targetType = player2Info.assignedType;
2600 bool canTargetAny = false; // Can AI hit any ball (e.g., after break, before assignment)?
2601 if (targetType == BallType::NONE) {
2602 // If colors not assigned, AI aims to pocket *something* (usually lowest numbered ball legally)
2603 // Or, more simply, treat any ball as a potential target to make *a* pocket
2604 canTargetAny = true; // Simplification: allow targeting any non-8 ball.
2605 // A better rule is hit lowest numbered ball first on break follow-up.
2606 }
2607
2608 // Check if AI needs to shoot the 8-ball
2609 bool target8Ball = (!canTargetAny && targetType != BallType::NONE && player2Info.ballsPocketedCount >= 7);
2610
2611
2612 // Iterate through all potential target balls
2613 for (auto& potentialTarget : balls) {
2614 if (potentialTarget.isPocketed || potentialTarget.id == 0) continue; // Skip pocketed and cue ball
2615
2616 // Check if this ball is a valid target
2617 bool isValidTarget = false;
2618 if (target8Ball) {
2619 isValidTarget = (potentialTarget.id == 8);
2620 }
2621 else if (canTargetAny) {
2622 isValidTarget = (potentialTarget.id != 8); // Can hit any non-8 ball
2623 }
2624 else { // Colors assigned, not yet shooting 8-ball
2625 isValidTarget = (potentialTarget.type == targetType);
2626 }
2627
2628 if (!isValidTarget) continue; // Skip if not a valid target for this turn
2629
2630 // Now, check all pockets for this target ball
2631 for (int p = 0; p < 6; ++p) {
2632 AIShotInfo currentShot = EvaluateShot(&potentialTarget, p);
2633 currentShot.involves8Ball = (potentialTarget.id == 8);
2634
2635 if (currentShot.possible) {
2636 // Compare scores to find the best shot
2637 if (!bestShotOverall.possible || currentShot.score > bestShotOverall.score) {
2638 bestShotOverall = currentShot;
2639 }
2640 }
2641 }
2642 } // End loop through potential target balls
2643
2644 // If targeting 8-ball and no shot found, or targeting own balls and no shot found,
2645 // need a safety strategy. Current simple AI just takes best found or taps cue ball.
2646
2647 return bestShotOverall;
2648}
2649
2650
2651// Evaluate a potential shot at a specific target ball towards a specific pocket
2652AIShotInfo EvaluateShot(Ball* targetBall, int pocketIndex) {
2653 AIShotInfo shotInfo;
2654 shotInfo.possible = false; // Assume not possible initially
2655 shotInfo.targetBall = targetBall;
2656 shotInfo.pocketIndex = pocketIndex;
2657
2658 Ball* cueBall = GetCueBall();
2659 if (!cueBall || !targetBall) return shotInfo;
2660
2661 // --- Define local state variables needed for legality checks ---
2662 BallType aiAssignedType = player2Info.assignedType;
2663 bool canTargetAny = (aiAssignedType == BallType::NONE); // Can AI hit any ball?
2664 bool mustTarget8Ball = (!canTargetAny && aiAssignedType != BallType::NONE && player2Info.ballsPocketedCount >= 7);
2665 // ---
2666
2667 // 1. Calculate Ghost Ball position
2668 shotInfo.ghostBallPos = CalculateGhostBallPos(targetBall, pocketIndex);
2669
2670 // 2. Calculate Angle from Cue Ball to Ghost Ball
2671 float dx = shotInfo.ghostBallPos.x - cueBall->x;
2672 float dy = shotInfo.ghostBallPos.y - cueBall->y;
2673 if (fabs(dx) < 0.01f && fabs(dy) < 0.01f) return shotInfo; // Avoid aiming at same spot
2674 shotInfo.angle = atan2f(dy, dx);
2675
2676 // Basic angle validity check (optional)
2677 if (!IsValidAIAimAngle(shotInfo.angle)) {
2678 // Maybe log this or handle edge cases
2679 }
2680
2681 // 3. Check Path: Cue Ball -> Ghost Ball Position
2682 // Use D2D1::Point2F() factory function here
2683 if (!IsPathClear(D2D1::Point2F(cueBall->x, cueBall->y), shotInfo.ghostBallPos, cueBall->id, targetBall->id)) {
2684 return shotInfo; // Path blocked
2685 }
2686
2687 // 4. Check Path: Target Ball -> Pocket
2688 // Use D2D1::Point2F() factory function here
2689 if (!IsPathClear(D2D1::Point2F(targetBall->x, targetBall->y), pocketPositions[pocketIndex], targetBall->id, -1)) {
2690 return shotInfo; // Path blocked
2691 }
2692
2693 // 5. Check First Ball Hit Legality
2694 float firstHitDistSq = -1.0f;
2695 // Use D2D1::Point2F() factory function here
2696 Ball* firstHit = FindFirstHitBall(D2D1::Point2F(cueBall->x, cueBall->y), shotInfo.angle, firstHitDistSq);
2697
2698 if (!firstHit) {
2699 return shotInfo; // AI aims but doesn't hit anything? Impossible shot.
2700 }
2701
2702 // Check if the first ball hit is the intended target ball
2703 if (firstHit->id != targetBall->id) {
2704 // Allow hitting slightly off target if it's very close to ghost ball pos
2705 float ghostDistSq = GetDistanceSq(shotInfo.ghostBallPos.x, shotInfo.ghostBallPos.y, firstHit->x, firstHit->y);
2706 // Allow a tolerance roughly half the ball radius squared
2707 if (ghostDistSq > (BALL_RADIUS * 0.7f) * (BALL_RADIUS * 0.7f)) {
2708 // First hit is significantly different from the target point.
2709 // This shot path leads to hitting the wrong ball first.
2710 return shotInfo; // Foul or unintended shot
2711 }
2712 // If first hit is not target, but very close, allow it for now (might still be foul based on type).
2713 }
2714
2715 // Check legality of the *first ball actually hit* based on game rules
2716 if (!canTargetAny) { // Colors are assigned (or should be)
2717 if (mustTarget8Ball) { // Must hit 8-ball first
2718 if (firstHit->id != 8) {
2719 // return shotInfo; // FOUL - Hitting wrong ball when aiming for 8-ball
2720 // Keep shot possible for now, rely on AIFindBestShot to prioritize legal ones
2721 }
2722 }
2723 else { // Must hit own ball type first
2724 if (firstHit->type != aiAssignedType && firstHit->id != 8) { // Allow hitting 8-ball if own type blocked? No, standard rules usually require hitting own first.
2725 // return shotInfo; // FOUL - Hitting opponent ball or 8-ball when shouldn't
2726 // Keep shot possible for now, rely on AIFindBestShot to prioritize legal ones
2727 }
2728 else if (firstHit->id == 8) {
2729 // return shotInfo; // FOUL - Hitting 8-ball when shouldn't
2730 // Keep shot possible for now
2731 }
2732 }
2733 }
2734 // (If canTargetAny is true, hitting any ball except 8 first is legal - assuming not scratching)
2735
2736
2737 // 6. Calculate Score & Power (Difficulty affects this)
2738 shotInfo.possible = true; // If we got here, the shot is geometrically possible and likely legal enough for AI to consider
2739
2740 float cueToGhostDist = GetDistance(cueBall->x, cueBall->y, shotInfo.ghostBallPos.x, shotInfo.ghostBallPos.y);
2741 float targetToPocketDist = GetDistance(targetBall->x, targetBall->y, pocketPositions[pocketIndex].x, pocketPositions[pocketIndex].y);
2742
2743 // Simple Score: Shorter shots are better, straighter shots are slightly better.
2744 float distanceScore = 1000.0f / (1.0f + cueToGhostDist + targetToPocketDist);
2745
2746 // Angle Score: Calculate cut angle
2747 // Vector Cue -> Ghost
2748 float v1x = shotInfo.ghostBallPos.x - cueBall->x;
2749 float v1y = shotInfo.ghostBallPos.y - cueBall->y;
2750 // Vector Target -> Pocket
2751 float v2x = pocketPositions[pocketIndex].x - targetBall->x;
2752 float v2y = pocketPositions[pocketIndex].y - targetBall->y;
2753 // Normalize vectors
2754 float mag1 = sqrtf(v1x * v1x + v1y * v1y);
2755 float mag2 = sqrtf(v2x * v2x + v2y * v2y);
2756 float angleScoreFactor = 0.5f; // Default if vectors are zero len
2757 if (mag1 > 0.1f && mag2 > 0.1f) {
2758 v1x /= mag1; v1y /= mag1;
2759 v2x /= mag2; v2y /= mag2;
2760 // Dot product gives cosine of angle between cue ball path and target ball path
2761 float dotProduct = v1x * v2x + v1y * v2y;
2762 // Straighter shot (dot product closer to 1) gets higher score
2763 angleScoreFactor = (1.0f + dotProduct) / 2.0f; // Map [-1, 1] to [0, 1]
2764 }
2765 angleScoreFactor = std::max(0.1f, angleScoreFactor); // Ensure some minimum score factor
2766
2767 shotInfo.score = distanceScore * angleScoreFactor;
2768
2769 // Bonus for pocketing 8-ball legally
2770 if (mustTarget8Ball && targetBall->id == 8) {
2771 shotInfo.score *= 10.0; // Strongly prefer the winning shot
2772 }
2773
2774 // Penalty for difficult cuts? Already partially handled by angleScoreFactor.
2775
2776 // 7. Calculate Power
2777 shotInfo.power = CalculateShotPower(cueToGhostDist, targetToPocketDist);
2778
2779 // 8. Add Inaccuracy based on Difficulty (same as before)
2780 float angleError = 0.0f;
2781 float powerErrorFactor = 1.0f;
2782
2783 switch (aiDifficulty) {
2784 case EASY:
2785 angleError = (float)(rand() % 100 - 50) / 1000.0f; // +/- ~3 deg
2786 powerErrorFactor = 0.8f + (float)(rand() % 40) / 100.0f; // 80-120%
2787 shotInfo.power *= 0.8f;
2788 break;
2789 case MEDIUM:
2790 angleError = (float)(rand() % 60 - 30) / 1000.0f; // +/- ~1.7 deg
2791 powerErrorFactor = 0.9f + (float)(rand() % 20) / 100.0f; // 90-110%
2792 break;
2793 case HARD:
2794 angleError = (float)(rand() % 10 - 5) / 1000.0f; // +/- ~0.3 deg
2795 powerErrorFactor = 0.98f + (float)(rand() % 4) / 100.0f; // 98-102%
2796 break;
2797 }
2798 shotInfo.angle += angleError;
2799 shotInfo.power *= powerErrorFactor;
2800 shotInfo.power = std::max(1.0f, std::min(shotInfo.power, MAX_SHOT_POWER)); // Clamp power
2801
2802 return shotInfo;
2803}
2804
2805
2806// Calculates required power (simplified)
2807float CalculateShotPower(float cueToGhostDist, float targetToPocketDist) {
2808 // Basic model: Power needed increases with total distance the balls need to travel.
2809 // Need enough power for cue ball to reach target AND target to reach pocket.
2810 float totalDist = cueToGhostDist + targetToPocketDist;
2811
2812 // Map distance to power (needs tuning)
2813 // Let's say max power is needed for longest possible shot (e.g., corner to corner ~ 1000 units)
2814 float powerRatio = std::min(1.0f, totalDist / 800.0f); // Normalize based on estimated max distance
2815
2816 float basePower = MAX_SHOT_POWER * 0.2f; // Minimum power to move balls reliably
2817 float variablePower = (MAX_SHOT_POWER * 0.8f) * powerRatio; // Scale remaining power range
2818
2819 // Harder AI could adjust based on desired cue ball travel (more power for draw/follow)
2820 return std::min(MAX_SHOT_POWER, basePower + variablePower);
2821}
2822
2823// Calculate the position the cue ball needs to hit for the target ball to go towards the pocket
2824D2D1_POINT_2F CalculateGhostBallPos(Ball* targetBall, int pocketIndex) {
2825 float targetToPocketX = pocketPositions[pocketIndex].x - targetBall->x;
2826 float targetToPocketY = pocketPositions[pocketIndex].y - targetBall->y;
2827 float dist = sqrtf(targetToPocketX * targetToPocketX + targetToPocketY * targetToPocketY);
2828
2829 if (dist < 1.0f) { // Target is basically in the pocket
2830 // Aim slightly off-center to avoid weird physics? Or directly at center?
2831 // For simplicity, return a point slightly behind center along the reverse line.
2832 return D2D1::Point2F(targetBall->x - targetToPocketX * 0.1f, targetBall->y - targetToPocketY * 0.1f);
2833 }
2834
2835 // Normalize direction vector from target to pocket
2836 float nx = targetToPocketX / dist;
2837 float ny = targetToPocketY / dist;
2838
2839 // Ghost ball position is diameter distance *behind* the target ball along this line
2840 float ghostX = targetBall->x - nx * (BALL_RADIUS * 2.0f);
2841 float ghostY = targetBall->y - ny * (BALL_RADIUS * 2.0f);
2842
2843 return D2D1::Point2F(ghostX, ghostY);
2844}
2845
2846// Checks if line segment is clear of obstructing balls
2847bool IsPathClear(D2D1_POINT_2F start, D2D1_POINT_2F end, int ignoredBallId1, int ignoredBallId2) {
2848 float dx = end.x - start.x;
2849 float dy = end.y - start.y;
2850 float segmentLenSq = dx * dx + dy * dy;
2851
2852 if (segmentLenSq < 0.01f) return true; // Start and end are same point
2853
2854 for (const auto& ball : balls) {
2855 if (ball.isPocketed) continue;
2856 if (ball.id == ignoredBallId1) continue;
2857 if (ball.id == ignoredBallId2) continue;
2858
2859 // Check distance from ball center to the line segment
2860 float ballToStartX = ball.x - start.x;
2861 float ballToStartY = ball.y - start.y;
2862
2863 // Project ball center onto the line defined by the segment
2864 float dot = (ballToStartX * dx + ballToStartY * dy) / segmentLenSq;
2865
2866 D2D1_POINT_2F closestPointOnLine;
2867 if (dot < 0) { // Closest point is start point
2868 closestPointOnLine = start;
2869 }
2870 else if (dot > 1) { // Closest point is end point
2871 closestPointOnLine = end;
2872 }
2873 else { // Closest point is along the segment
2874 closestPointOnLine = D2D1::Point2F(start.x + dot * dx, start.y + dot * dy);
2875 }
2876
2877 // Check if the closest point is within collision distance (ball radius + path radius)
2878 if (GetDistanceSq(ball.x, ball.y, closestPointOnLine.x, closestPointOnLine.y) < (BALL_RADIUS * BALL_RADIUS)) {
2879 // Consider slightly wider path check? Maybe BALL_RADIUS * 1.1f?
2880 // if (GetDistanceSq(ball.x, ball.y, closestPointOnLine.x, closestPointOnLine.y) < (BALL_RADIUS * 1.1f)*(BALL_RADIUS*1.1f)) {
2881 return false; // Path is blocked
2882 }
2883 }
2884 return true; // No obstructions found
2885}
2886
2887// Finds the first ball hit along a path (simplified)
2888Ball* FindFirstHitBall(D2D1_POINT_2F start, float angle, float& hitDistSq) {
2889 Ball* hitBall = nullptr;
2890 hitDistSq = -1.0f; // Initialize hit distance squared
2891 float minCollisionDistSq = -1.0f;
2892
2893 float cosA = cosf(angle);
2894 float sinA = sinf(angle);
2895
2896 for (auto& ball : balls) {
2897 if (ball.isPocketed || ball.id == 0) continue; // Skip cue ball and pocketed
2898
2899 float dx = ball.x - start.x;
2900 float dy = ball.y - start.y;
2901
2902 // Project vector from start->ball onto the aim direction vector
2903 float dot = dx * cosA + dy * sinA;
2904
2905 if (dot > 0) { // Ball is generally in front
2906 // Find closest point on aim line to the ball's center
2907 float closestPointX = start.x + dot * cosA;
2908 float closestPointY = start.y + dot * sinA;
2909 float distSq = GetDistanceSq(ball.x, ball.y, closestPointX, closestPointY);
2910
2911 // Check if the aim line passes within the ball's radius
2912 if (distSq < (BALL_RADIUS * BALL_RADIUS)) {
2913 // Calculate distance from start to the collision point on the ball's circumference
2914 float backDist = sqrtf(std::max(0.f, BALL_RADIUS * BALL_RADIUS - distSq));
2915 float collisionDist = dot - backDist; // Distance along aim line to collision
2916
2917 if (collisionDist > 0) { // Ensure collision is in front
2918 float collisionDistSq = collisionDist * collisionDist;
2919 if (hitBall == nullptr || collisionDistSq < minCollisionDistSq) {
2920 minCollisionDistSq = collisionDistSq;
2921 hitBall = &ball; // Found a closer hit ball
2922 }
2923 }
2924 }
2925 }
2926 }
2927 hitDistSq = minCollisionDistSq; // Return distance squared to the first hit
2928 return hitBall;
2929}
2930
2931// Basic check for reasonable AI aim angles (optional)
2932bool IsValidAIAimAngle(float angle) {
2933 // Placeholder - could check for NaN or infinity if calculations go wrong
2934 return isfinite(angle);
2935}
2936
2937//midi func = start
2938void PlayMidiInBackground(HWND hwnd, const TCHAR* midiPath) {
2939 while (isMusicPlaying) {
2940 MCI_OPEN_PARMS mciOpen = { 0 };
2941 mciOpen.lpstrDeviceType = TEXT("sequencer");
2942 mciOpen.lpstrElementName = midiPath;
2943
2944 if (mciSendCommand(0, MCI_OPEN, MCI_OPEN_TYPE | MCI_OPEN_ELEMENT, (DWORD_PTR)&mciOpen) == 0) {
2945 midiDeviceID = mciOpen.wDeviceID;
2946
2947 MCI_PLAY_PARMS mciPlay = { 0 };
2948 mciSendCommand(midiDeviceID, MCI_PLAY, 0, (DWORD_PTR)&mciPlay);
2949
2950 // Wait for playback to complete
2951 MCI_STATUS_PARMS mciStatus = { 0 };
2952 mciStatus.dwItem = MCI_STATUS_MODE;
2953
2954 do {
2955 mciSendCommand(midiDeviceID, MCI_STATUS, MCI_STATUS_ITEM, (DWORD_PTR)&mciStatus);
2956 Sleep(100); // adjust as needed
2957 } while (mciStatus.dwReturn == MCI_MODE_PLAY && isMusicPlaying);
2958
2959 mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
2960 midiDeviceID = 0;
2961 }
2962 }
2963}
2964
2965void StartMidi(HWND hwnd, const TCHAR* midiPath) {
2966 if (isMusicPlaying) {
2967 StopMidi();
2968 }
2969 isMusicPlaying = true;
2970 musicThread = std::thread(PlayMidiInBackground, hwnd, midiPath);
2971}
2972
2973void StopMidi() {
2974 if (isMusicPlaying) {
2975 isMusicPlaying = false;
2976 if (musicThread.joinable()) musicThread.join();
2977 if (midiDeviceID != 0) {
2978 mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
2979 midiDeviceID = 0;
2980 }
2981 }
2982}
2983
2984/*void PlayGameMusic(HWND hwnd) {
2985 // Stop any existing playback
2986 if (isMusicPlaying) {
2987 isMusicPlaying = false;
2988 if (musicThread.joinable()) {
2989 musicThread.join();
2990 }
2991 if (midiDeviceID != 0) {
2992 mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
2993 midiDeviceID = 0;
2994 }
2995 }
2996
2997 // Get the path of the executable
2998 TCHAR exePath[MAX_PATH];
2999 GetModuleFileName(NULL, exePath, MAX_PATH);
3000
3001 // Extract the directory path
3002 TCHAR* lastBackslash = _tcsrchr(exePath, '\\');
3003 if (lastBackslash != NULL) {
3004 *(lastBackslash + 1) = '\0';
3005 }
3006
3007 // Construct the full path to the MIDI file
3008 static TCHAR midiPath[MAX_PATH];
3009 _tcscpy_s(midiPath, MAX_PATH, exePath);
3010 _tcscat_s(midiPath, MAX_PATH, TEXT("BSQ.MID"));
3011
3012 // Start the background playback
3013 isMusicPlaying = true;
3014 musicThread = std::thread(PlayMidiInBackground, hwnd, midiPath);
3015}*/
3016//midi func = end
3017
3018// --- Drawing Functions ---
3019
3020void OnPaint() {
3021 HRESULT hr = CreateDeviceResources(); // Ensure resources are valid
3022
3023 if (SUCCEEDED(hr)) {
3024 pRenderTarget->BeginDraw();
3025 DrawScene(pRenderTarget); // Pass render target
3026 hr = pRenderTarget->EndDraw();
3027
3028 if (hr == D2DERR_RECREATE_TARGET) {
3029 DiscardDeviceResources();
3030 // Optionally request another paint message: InvalidateRect(hwndMain, NULL, FALSE);
3031 // But the timer loop will trigger redraw anyway.
3032 }
3033 }
3034 // If CreateDeviceResources failed, EndDraw might not be called.
3035 // Consider handling this more robustly if needed.
3036}
3037
3038void DrawScene(ID2D1RenderTarget* pRT) {
3039 if (!pRT) return;
3040
3041 //pRT->Clear(D2D1::ColorF(D2D1::ColorF::LightGray)); // Background color
3042 // Set background color to #ffffcd (RGB: 255, 255, 205)
3043 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)
3044 //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)
3045
3046 DrawTable(pRT, pFactory);
3047 DrawBalls(pRT);
3048 DrawAimingAids(pRT); // Includes cue stick if aiming
3049 DrawUI(pRT);
3050 DrawPowerMeter(pRT);
3051 DrawSpinIndicator(pRT);
3052 DrawPocketedBallsIndicator(pRT);
3053 DrawBallInHandIndicator(pRT); // Draw cue ball ghost if placing
3054
3055 // Draw Game Over Message
3056 if (currentGameState == GAME_OVER && pTextFormat) {
3057 ID2D1SolidColorBrush* pBrush = nullptr;
3058 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pBrush);
3059 if (pBrush) {
3060 D2D1_RECT_F layoutRect = D2D1::RectF(TABLE_LEFT, TABLE_TOP + TABLE_HEIGHT / 2 - 30, TABLE_RIGHT, TABLE_TOP + TABLE_HEIGHT / 2 + 30);
3061 pRT->DrawText(
3062 gameOverMessage.c_str(),
3063 (UINT32)gameOverMessage.length(),
3064 pTextFormat, // Use large format maybe?
3065 &layoutRect,
3066 pBrush
3067 );
3068 SafeRelease(&pBrush);
3069 }
3070 }
3071
3072}
3073
3074void DrawTable(ID2D1RenderTarget* pRT, ID2D1Factory* pFactory) {
3075 ID2D1SolidColorBrush* pBrush = nullptr;
3076
3077 // === Draw Full Orange Frame (Table Border) ===
3078 ID2D1SolidColorBrush* pFrameBrush = nullptr;
3079 pRT->CreateSolidColorBrush(D2D1::ColorF(0.9157f, 0.6157f, 0.2000f), &pFrameBrush); //NEWCOLOR ::Orange (no brackets) => (0.9157, 0.6157, 0.2000)
3080 //pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Orange), &pFrameBrush); //NEWCOLOR ::Orange (no brackets) => (0.9157, 0.6157, 0.2000)
3081 if (pFrameBrush) {
3082 D2D1_RECT_F outerRect = D2D1::RectF(
3083 TABLE_LEFT - CUSHION_THICKNESS,
3084 TABLE_TOP - CUSHION_THICKNESS,
3085 TABLE_RIGHT + CUSHION_THICKNESS,
3086 TABLE_BOTTOM + CUSHION_THICKNESS
3087 );
3088 pRT->FillRectangle(&outerRect, pFrameBrush);
3089 SafeRelease(&pFrameBrush);
3090 }
3091
3092 // Draw Table Bed (Green Felt)
3093 pRT->CreateSolidColorBrush(TABLE_COLOR, &pBrush);
3094 if (!pBrush) return;
3095 D2D1_RECT_F tableRect = D2D1::RectF(TABLE_LEFT, TABLE_TOP, TABLE_RIGHT, TABLE_BOTTOM);
3096 pRT->FillRectangle(&tableRect, pBrush);
3097 SafeRelease(&pBrush);
3098
3099 // Draw Cushions (Red Border)
3100 pRT->CreateSolidColorBrush(CUSHION_COLOR, &pBrush);
3101 if (!pBrush) return;
3102 // Top Cushion (split by middle pocket)
3103 pRT->FillRectangle(D2D1::RectF(TABLE_LEFT + HOLE_VISUAL_RADIUS, TABLE_TOP - CUSHION_THICKNESS, TABLE_LEFT + TABLE_WIDTH / 2.f - HOLE_VISUAL_RADIUS, TABLE_TOP), pBrush);
3104 pRT->FillRectangle(D2D1::RectF(TABLE_LEFT + TABLE_WIDTH / 2.f + HOLE_VISUAL_RADIUS, TABLE_TOP - CUSHION_THICKNESS, TABLE_RIGHT - HOLE_VISUAL_RADIUS, TABLE_TOP), pBrush);
3105 // Bottom Cushion (split by middle pocket)
3106 pRT->FillRectangle(D2D1::RectF(TABLE_LEFT + HOLE_VISUAL_RADIUS, TABLE_BOTTOM, TABLE_LEFT + TABLE_WIDTH / 2.f - HOLE_VISUAL_RADIUS, TABLE_BOTTOM + CUSHION_THICKNESS), pBrush);
3107 pRT->FillRectangle(D2D1::RectF(TABLE_LEFT + TABLE_WIDTH / 2.f + HOLE_VISUAL_RADIUS, TABLE_BOTTOM, TABLE_RIGHT - HOLE_VISUAL_RADIUS, TABLE_BOTTOM + CUSHION_THICKNESS), pBrush);
3108 // Left Cushion
3109 pRT->FillRectangle(D2D1::RectF(TABLE_LEFT - CUSHION_THICKNESS, TABLE_TOP + HOLE_VISUAL_RADIUS, TABLE_LEFT, TABLE_BOTTOM - HOLE_VISUAL_RADIUS), pBrush);
3110 // Right Cushion
3111 pRT->FillRectangle(D2D1::RectF(TABLE_RIGHT, TABLE_TOP + HOLE_VISUAL_RADIUS, TABLE_RIGHT + CUSHION_THICKNESS, TABLE_BOTTOM - HOLE_VISUAL_RADIUS), pBrush);
3112 SafeRelease(&pBrush);
3113
3114
3115 // Draw Pockets (Black Circles)
3116 pRT->CreateSolidColorBrush(POCKET_COLOR, &pBrush);
3117 if (!pBrush) return;
3118 for (int i = 0; i < 6; ++i) {
3119 D2D1_ELLIPSE ellipse = D2D1::Ellipse(pocketPositions[i], HOLE_VISUAL_RADIUS, HOLE_VISUAL_RADIUS);
3120 pRT->FillEllipse(&ellipse, pBrush);
3121 }
3122 SafeRelease(&pBrush);
3123
3124 // Draw Headstring Line (White)
3125 pRT->CreateSolidColorBrush(D2D1::ColorF(0.4235f, 0.5647f, 0.1765f, 1.0f), &pBrush); // NEWCOLOR ::White => (0.2784, 0.4549, 0.1843)
3126 //pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.5f), &pBrush); // NEWCOLOR ::White => (0.2784, 0.4549, 0.1843)
3127 if (!pBrush) return;
3128 pRT->DrawLine(
3129 D2D1::Point2F(HEADSTRING_X, TABLE_TOP),
3130 D2D1::Point2F(HEADSTRING_X, TABLE_BOTTOM),
3131 pBrush,
3132 1.0f // Line thickness
3133 );
3134 SafeRelease(&pBrush);
3135
3136 // Draw Semicircle facing West (flat side East)
3137 // Draw Semicircle facing East (curved side on the East, flat side on the West)
3138 ID2D1PathGeometry* pGeometry = nullptr;
3139 HRESULT hr = pFactory->CreatePathGeometry(&pGeometry);
3140 if (SUCCEEDED(hr) && pGeometry)
3141 {
3142 ID2D1GeometrySink* pSink = nullptr;
3143 hr = pGeometry->Open(&pSink);
3144 if (SUCCEEDED(hr) && pSink)
3145 {
3146 float radius = 60.0f; // Radius for the semicircle
3147 D2D1_POINT_2F center = D2D1::Point2F(HEADSTRING_X, (TABLE_TOP + TABLE_BOTTOM) / 2.0f);
3148
3149 // For a semicircle facing East (curved side on the East), use the top and bottom points.
3150 D2D1_POINT_2F startPoint = D2D1::Point2F(center.x, center.y - radius); // Top point
3151
3152 pSink->BeginFigure(startPoint, D2D1_FIGURE_BEGIN_HOLLOW);
3153
3154 D2D1_ARC_SEGMENT arc = {};
3155 arc.point = D2D1::Point2F(center.x, center.y + radius); // Bottom point
3156 arc.size = D2D1::SizeF(radius, radius);
3157 arc.rotationAngle = 0.0f;
3158 // Use the correct identifier with the extra underscore:
3159 arc.sweepDirection = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
3160 arc.arcSize = D2D1_ARC_SIZE_SMALL;
3161
3162 pSink->AddArc(&arc);
3163 pSink->EndFigure(D2D1_FIGURE_END_OPEN);
3164 pSink->Close();
3165 SafeRelease(&pSink);
3166
3167 ID2D1SolidColorBrush* pArcBrush = nullptr;
3168 //pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.3f), &pArcBrush);
3169 pRT->CreateSolidColorBrush(D2D1::ColorF(0.4235f, 0.5647f, 0.1765f, 1.0f), &pArcBrush);
3170 if (pArcBrush)
3171 {
3172 pRT->DrawGeometry(pGeometry, pArcBrush, 1.5f);
3173 SafeRelease(&pArcBrush);
3174 }
3175 }
3176 SafeRelease(&pGeometry);
3177 }
3178
3179
3180
3181
3182}
3183
3184
3185void DrawBalls(ID2D1RenderTarget* pRT) {
3186 ID2D1SolidColorBrush* pBrush = nullptr;
3187 ID2D1SolidColorBrush* pStripeBrush = nullptr; // For stripe pattern
3188
3189 pRT->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0), &pBrush); // Placeholder
3190 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
3191
3192 if (!pBrush || !pStripeBrush) {
3193 SafeRelease(&pBrush);
3194 SafeRelease(&pStripeBrush);
3195 return;
3196 }
3197
3198
3199 for (size_t i = 0; i < balls.size(); ++i) {
3200 const Ball& b = balls[i];
3201 if (!b.isPocketed) {
3202 D2D1_ELLIPSE ellipse = D2D1::Ellipse(D2D1::Point2F(b.x, b.y), BALL_RADIUS, BALL_RADIUS);
3203
3204 // Set main ball color
3205 pBrush->SetColor(b.color);
3206 pRT->FillEllipse(&ellipse, pBrush);
3207
3208 // Draw Stripe if applicable
3209 if (b.type == BallType::STRIPE) {
3210 // Draw a white band across the middle (simplified stripe)
3211 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);
3212 // Need to clip this rectangle to the ellipse bounds - complex!
3213 // Alternative: Draw two colored arcs leaving a white band.
3214 // Simplest: Draw a white circle inside, slightly smaller.
3215 D2D1_ELLIPSE innerEllipse = D2D1::Ellipse(D2D1::Point2F(b.x, b.y), BALL_RADIUS * 0.6f, BALL_RADIUS * 0.6f);
3216 pRT->FillEllipse(innerEllipse, pStripeBrush); // White center part
3217 pBrush->SetColor(b.color); // Set back to stripe color
3218 pRT->FillEllipse(innerEllipse, pBrush); // Fill again, leaving a ring - No, this isn't right.
3219
3220 // Let's try drawing a thick white line across
3221 // This doesn't look great. Just drawing solid red for stripes for now.
3222 }
3223
3224 // Draw Number (Optional - requires more complex text layout or pre-rendered textures)
3225 // if (b.id != 0 && pTextFormat) {
3226 // std::wstring numStr = std::to_wstring(b.id);
3227 // D2D1_RECT_F textRect = D2D1::RectF(b.x - BALL_RADIUS, b.y - BALL_RADIUS, b.x + BALL_RADIUS, b.y + BALL_RADIUS);
3228 // ID2D1SolidColorBrush* pNumBrush = nullptr;
3229 // D2D1_COLOR_F numCol = (b.type == BallType::SOLID || b.id == 8) ? D2D1::ColorF(D2D1::ColorF::Black) : D2D1::ColorF(D2D1::ColorF::White);
3230 // pRT->CreateSolidColorBrush(numCol, &pNumBrush);
3231 // // Create a smaller text format...
3232 // // pRT->DrawText(numStr.c_str(), numStr.length(), pSmallTextFormat, &textRect, pNumBrush);
3233 // SafeRelease(&pNumBrush);
3234 // }
3235 }
3236 }
3237
3238 SafeRelease(&pBrush);
3239 SafeRelease(&pStripeBrush);
3240}
3241
3242
3243void DrawAimingAids(ID2D1RenderTarget* pRT) {
3244 // Condition check at start (Unchanged)
3245 //if (currentGameState != PLAYER1_TURN && currentGameState != PLAYER2_TURN &&
3246 //currentGameState != BREAKING && currentGameState != AIMING)
3247 //{
3248 //return;
3249 //}
3250 // NEW Condition: Allow drawing if it's a human player's active turn/aiming/breaking,
3251 // OR if it's AI's turn and it's in AI_THINKING state (calculating) or BREAKING (aiming break).
3252 bool isHumanInteracting = (!isPlayer2AI || currentPlayer == 1) &&
3253 (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN ||
3254 currentGameState == BREAKING || currentGameState == AIMING);
3255 // AI_THINKING state is when AI calculates shot. AIMakeDecision sets cueAngle/shotPower.
3256 // Also include BREAKING state if it's AI's turn and isOpeningBreakShot for break aim visualization.
3257 // NEW Condition: AI is displaying its aim
3258 bool isAiVisualizingShot = (isPlayer2AI && currentPlayer == 2 &&
3259 currentGameState == AI_THINKING && aiIsDisplayingAim);
3260
3261 if (!isHumanInteracting && !(isAiVisualizingShot || (currentGameState == AI_THINKING && aiIsDisplayingAim))) {
3262 return;
3263 }
3264
3265 Ball* cueBall = GetCueBall();
3266 if (!cueBall || cueBall->isPocketed) return; // Don't draw if cue ball is gone
3267
3268 ID2D1SolidColorBrush* pBrush = nullptr;
3269 ID2D1SolidColorBrush* pGhostBrush = nullptr;
3270 ID2D1StrokeStyle* pDashedStyle = nullptr;
3271 ID2D1SolidColorBrush* pCueBrush = nullptr;
3272 ID2D1SolidColorBrush* pReflectBrush = nullptr; // Brush for reflection line
3273
3274 // Ensure render target is valid
3275 if (!pRT) return;
3276
3277 // Create Brushes and Styles (check for failures)
3278 HRESULT hr;
3279 hr = pRT->CreateSolidColorBrush(AIM_LINE_COLOR, &pBrush);
3280 if FAILED(hr) { SafeRelease(&pBrush); return; }
3281 hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.5f), &pGhostBrush);
3282 if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); return; }
3283 hr = pRT->CreateSolidColorBrush(D2D1::ColorF(0.6f, 0.4f, 0.2f), &pCueBrush);
3284 if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); SafeRelease(&pCueBrush); return; }
3285 // Create reflection brush (e.g., lighter shade or different color)
3286 hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::LightCyan, 0.6f), &pReflectBrush);
3287 if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); SafeRelease(&pCueBrush); SafeRelease(&pReflectBrush); return; }
3288 // Create a Cyan brush for primary and secondary lines //orig(75.0f / 255.0f, 0.0f, 130.0f / 255.0f);indigoColor
3289 D2D1::ColorF cyanColor(0.0, 255.0, 255.0, 255.0f);
3290 ID2D1SolidColorBrush* pCyanBrush = nullptr;
3291 hr = pRT->CreateSolidColorBrush(cyanColor, &pCyanBrush);
3292 if (FAILED(hr)) {
3293 SafeRelease(&pCyanBrush);
3294 // handle error if needed
3295 }
3296 // Create a Purple brush for primary and secondary lines
3297 D2D1::ColorF purpleColor(255.0f, 0.0f, 255.0f, 255.0f);
3298 ID2D1SolidColorBrush* pPurpleBrush = nullptr;
3299 hr = pRT->CreateSolidColorBrush(purpleColor, &pPurpleBrush);
3300 if (FAILED(hr)) {
3301 SafeRelease(&pPurpleBrush);
3302 // handle error if needed
3303 }
3304
3305 if (pFactory) {
3306 D2D1_STROKE_STYLE_PROPERTIES strokeProps = D2D1::StrokeStyleProperties();
3307 strokeProps.dashStyle = D2D1_DASH_STYLE_DASH;
3308 hr = pFactory->CreateStrokeStyle(&strokeProps, nullptr, 0, &pDashedStyle);
3309 if FAILED(hr) { pDashedStyle = nullptr; }
3310 }
3311
3312
3313 // --- Cue Stick Drawing (Unchanged from previous fix) ---
3314 const float baseStickLength = 150.0f;
3315 const float baseStickThickness = 4.0f;
3316 float stickLength = baseStickLength * 1.4f;
3317 float stickThickness = baseStickThickness * 1.5f;
3318 float stickAngle = cueAngle + PI;
3319 float powerOffset = 0.0f;
3320 //if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
3321 // Show power offset if human is aiming/dragging, or if AI is preparing its shot (AI_THINKING or AI Break)
3322 if ((isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) || isAiVisualizingShot) { // Use the new condition
3323 powerOffset = shotPower * 5.0f;
3324 }
3325 D2D1_POINT_2F cueStickEnd = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (stickLength + powerOffset), cueBall->y + sinf(stickAngle) * (stickLength + powerOffset));
3326 D2D1_POINT_2F cueStickTip = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (powerOffset + 5.0f), cueBall->y + sinf(stickAngle) * (powerOffset + 5.0f));
3327 pRT->DrawLine(cueStickTip, cueStickEnd, pCueBrush, stickThickness);
3328
3329
3330 // --- Projection Line Calculation ---
3331 float cosA = cosf(cueAngle);
3332 float sinA = sinf(cueAngle);
3333 float rayLength = TABLE_WIDTH + TABLE_HEIGHT; // Ensure ray is long enough
3334 D2D1_POINT_2F rayStart = D2D1::Point2F(cueBall->x, cueBall->y);
3335 D2D1_POINT_2F rayEnd = D2D1::Point2F(rayStart.x + cosA * rayLength, rayStart.y + sinA * rayLength);
3336
3337 // Find the first ball hit by the aiming ray
3338 Ball* hitBall = nullptr;
3339 float firstHitDistSq = -1.0f;
3340 D2D1_POINT_2F ballCollisionPoint = { 0, 0 }; // Point on target ball circumference
3341 D2D1_POINT_2F ghostBallPosForHit = { 0, 0 }; // Ghost ball pos for the hit ball
3342
3343 hitBall = FindFirstHitBall(rayStart, cueAngle, firstHitDistSq);
3344 if (hitBall) {
3345 // Calculate the point on the target ball's circumference
3346 float collisionDist = sqrtf(firstHitDistSq);
3347 ballCollisionPoint = D2D1::Point2F(rayStart.x + cosA * collisionDist, rayStart.y + sinA * collisionDist);
3348 // Calculate ghost ball position for this specific hit (used for projection consistency)
3349 ghostBallPosForHit = D2D1::Point2F(hitBall->x - cosA * BALL_RADIUS, hitBall->y - sinA * BALL_RADIUS); // Approx.
3350 }
3351
3352 // Find the first rail hit by the aiming ray
3353 D2D1_POINT_2F railHitPoint = rayEnd; // Default to far end if no rail hit
3354 float minRailDistSq = rayLength * rayLength;
3355 int hitRailIndex = -1; // 0:Left, 1:Right, 2:Top, 3:Bottom
3356
3357 // Define table edge segments for intersection checks
3358 D2D1_POINT_2F topLeft = D2D1::Point2F(TABLE_LEFT, TABLE_TOP);
3359 D2D1_POINT_2F topRight = D2D1::Point2F(TABLE_RIGHT, TABLE_TOP);
3360 D2D1_POINT_2F bottomLeft = D2D1::Point2F(TABLE_LEFT, TABLE_BOTTOM);
3361 D2D1_POINT_2F bottomRight = D2D1::Point2F(TABLE_RIGHT, TABLE_BOTTOM);
3362
3363 D2D1_POINT_2F currentIntersection;
3364
3365 // Check Left Rail
3366 if (LineSegmentIntersection(rayStart, rayEnd, topLeft, bottomLeft, currentIntersection)) {
3367 float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
3368 if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 0; }
3369 }
3370 // Check Right Rail
3371 if (LineSegmentIntersection(rayStart, rayEnd, topRight, bottomRight, currentIntersection)) {
3372 float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
3373 if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 1; }
3374 }
3375 // Check Top Rail
3376 if (LineSegmentIntersection(rayStart, rayEnd, topLeft, topRight, currentIntersection)) {
3377 float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
3378 if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 2; }
3379 }
3380 // Check Bottom Rail
3381 if (LineSegmentIntersection(rayStart, rayEnd, bottomLeft, bottomRight, currentIntersection)) {
3382 float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
3383 if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 3; }
3384 }
3385
3386
3387 // --- Determine final aim line end point ---
3388 D2D1_POINT_2F finalLineEnd = railHitPoint; // Assume rail hit first
3389 bool aimingAtRail = true;
3390
3391 if (hitBall && firstHitDistSq < minRailDistSq) {
3392 // Ball collision is closer than rail collision
3393 finalLineEnd = ballCollisionPoint; // End line at the point of contact on the ball
3394 aimingAtRail = false;
3395 }
3396
3397 // --- Draw Primary Aiming Line ---
3398 pRT->DrawLine(rayStart, finalLineEnd, pBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
3399
3400 // --- Draw Target Circle/Indicator ---
3401 D2D1_ELLIPSE targetCircle = D2D1::Ellipse(finalLineEnd, BALL_RADIUS / 2.0f, BALL_RADIUS / 2.0f);
3402 pRT->DrawEllipse(&targetCircle, pBrush, 1.0f);
3403
3404 // --- Draw Projection/Reflection Lines ---
3405 if (!aimingAtRail && hitBall) {
3406 // Aiming at a ball: Draw Ghost Cue Ball and Target Ball Projection
3407 D2D1_ELLIPSE ghostCue = D2D1::Ellipse(ballCollisionPoint, BALL_RADIUS, BALL_RADIUS); // Ghost ball at contact point
3408 pRT->DrawEllipse(ghostCue, pGhostBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
3409
3410 // Calculate target ball projection based on impact line (cue collision point -> target center)
3411 float targetProjectionAngle = atan2f(hitBall->y - ballCollisionPoint.y, hitBall->x - ballCollisionPoint.x);
3412 // Clamp angle calculation if distance is tiny
3413 if (GetDistanceSq(hitBall->x, hitBall->y, ballCollisionPoint.x, ballCollisionPoint.y) < 1.0f) {
3414 targetProjectionAngle = cueAngle; // Fallback if overlapping
3415 }
3416
3417 D2D1_POINT_2F targetStartPoint = D2D1::Point2F(hitBall->x, hitBall->y);
3418 D2D1_POINT_2F targetProjectionEnd = D2D1::Point2F(
3419 hitBall->x + cosf(targetProjectionAngle) * 50.0f, // Projection length 50 units
3420 hitBall->y + sinf(targetProjectionAngle) * 50.0f
3421 );
3422 // Draw solid line for target projection
3423 //pRT->DrawLine(targetStartPoint, targetProjectionEnd, pBrush, 1.0f);
3424
3425 //new code start
3426
3427 // Dual trajectory with edge-aware contact simulation
3428 D2D1_POINT_2F dir = {
3429 targetProjectionEnd.x - targetStartPoint.x,
3430 targetProjectionEnd.y - targetStartPoint.y
3431 };
3432 float dirLen = sqrtf(dir.x * dir.x + dir.y * dir.y);
3433 dir.x /= dirLen;
3434 dir.y /= dirLen;
3435
3436 D2D1_POINT_2F perp = { -dir.y, dir.x };
3437
3438 // Approximate cue ball center by reversing from tip
3439 D2D1_POINT_2F cueBallCenterForGhostHit = { // Renamed for clarity if you use it elsewhere
3440 targetStartPoint.x - dir.x * BALL_RADIUS,
3441 targetStartPoint.y - dir.y * BALL_RADIUS
3442 };
3443
3444 // REAL contact-ball center - use your physics object's center:
3445 // (replace 'objectBallPos' with whatever you actually call it)
3446 // (targetStartPoint is already hitBall->x, hitBall->y)
3447 D2D1_POINT_2F contactBallCenter = targetStartPoint; // Corrected: Use the object ball's actual center
3448 //D2D1_POINT_2F contactBallCenter = D2D1::Point2F(hitBall->x, hitBall->y);
3449
3450 // The 'offset' calculation below uses 'cueBallCenterForGhostHit' (originally 'cueBallCenter').
3451 // This will result in 'offset' being 0 because 'cueBallCenterForGhostHit' is defined
3452 // such that (targetStartPoint - cueBallCenterForGhostHit) is parallel to 'dir',
3453 // and 'perp' is perpendicular to 'dir'.
3454 // Consider Change 2 if this 'offset' is not behaving as intended for the secondary line.
3455 /*float offset = ((targetStartPoint.x - cueBallCenterForGhostHit.x) * perp.x +
3456 (targetStartPoint.y - cueBallCenterForGhostHit.y) * perp.y);*/
3457 /*float offset = ((targetStartPoint.x - cueBallCenter.x) * perp.x +
3458 (targetStartPoint.y - cueBallCenter.y) * perp.y);
3459 float absOffset = fabsf(offset);
3460 float side = (offset >= 0 ? 1.0f : -1.0f);*/
3461
3462 // Use actual cue ball center for offset calculation if 'offset' is meant to quantify the cut
3463 D2D1_POINT_2F actualCueBallPhysicalCenter = D2D1::Point2F(cueBall->x, cueBall->y); // This is also rayStart
3464
3465 // Offset calculation based on actual cue ball position relative to the 'dir' line through targetStartPoint
3466 float offset = ((targetStartPoint.x - actualCueBallPhysicalCenter.x) * perp.x +
3467 (targetStartPoint.y - actualCueBallPhysicalCenter.y) * perp.y);
3468 float absOffset = fabsf(offset);
3469 float side = (offset >= 0 ? 1.0f : -1.0f);
3470
3471
3472 // Actual contact point on target ball edge
3473 D2D1_POINT_2F contactPoint = {
3474 contactBallCenter.x + perp.x * BALL_RADIUS * side,
3475 contactBallCenter.y + perp.y * BALL_RADIUS * side
3476 };
3477
3478 // Tangent (cut shot) path from contact point
3479 // Tangent (cut shot) path: from contact point to contact ball center
3480 D2D1_POINT_2F objectBallDir = {
3481 contactBallCenter.x - contactPoint.x,
3482 contactBallCenter.y - contactPoint.y
3483 };
3484 float oLen = sqrtf(objectBallDir.x * objectBallDir.x + objectBallDir.y * objectBallDir.y);
3485 if (oLen != 0.0f) {
3486 objectBallDir.x /= oLen;
3487 objectBallDir.y /= oLen;
3488 }
3489
3490 const float PRIMARY_LEN = 150.0f; //default=150.0f
3491 const float SECONDARY_LEN = 150.0f; //default=150.0f
3492 const float STRAIGHT_EPSILON = BALL_RADIUS * 0.05f;
3493
3494 D2D1_POINT_2F primaryEnd = {
3495 targetStartPoint.x + dir.x * PRIMARY_LEN,
3496 targetStartPoint.y + dir.y * PRIMARY_LEN
3497 };
3498
3499 // Secondary line starts from the contact ball's center
3500 D2D1_POINT_2F secondaryStart = contactBallCenter;
3501 D2D1_POINT_2F secondaryEnd = {
3502 secondaryStart.x + objectBallDir.x * SECONDARY_LEN,
3503 secondaryStart.y + objectBallDir.y * SECONDARY_LEN
3504 };
3505
3506 if (absOffset < STRAIGHT_EPSILON) // straight shot?
3507 {
3508 // Straight: secondary behind primary
3509 // secondary behind primary {pDashedStyle param at end}
3510 pRT->DrawLine(secondaryStart, secondaryEnd, pPurpleBrush, 2.0f);
3511 //pRT->DrawLine(secondaryStart, secondaryEnd, pGhostBrush, 1.0f);
3512 pRT->DrawLine(targetStartPoint, primaryEnd, pCyanBrush, 2.0f);
3513 //pRT->DrawLine(targetStartPoint, primaryEnd, pBrush, 1.0f);
3514 }
3515 else
3516 {
3517 // Cut shot: both visible
3518 // both visible for cut shot
3519 pRT->DrawLine(secondaryStart, secondaryEnd, pPurpleBrush, 2.0f);
3520 //pRT->DrawLine(secondaryStart, secondaryEnd, pGhostBrush, 1.0f);
3521 pRT->DrawLine(targetStartPoint, primaryEnd, pCyanBrush, 2.0f);
3522 //pRT->DrawLine(targetStartPoint, primaryEnd, pBrush, 1.0f);
3523 }
3524 // End improved trajectory logic
3525
3526 //new code end
3527
3528 // -- Cue Ball Path after collision (Optional, requires physics) --
3529 // Very simplified: Assume cue deflects, angle depends on cut angle.
3530 // float cutAngle = acosf(cosf(cueAngle - targetProjectionAngle)); // Angle between paths
3531 // float cueDeflectionAngle = ? // Depends on cutAngle, spin, etc. Hard to predict accurately.
3532 // D2D1_POINT_2F cueProjectionEnd = ...
3533 // pRT->DrawLine(ballCollisionPoint, cueProjectionEnd, pGhostBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
3534
3535 // --- Accuracy Comment ---
3536 // Note: The visual accuracy of this projection, especially for cut shots (hitting the ball off-center)
3537 // or shots with spin, is limited by the simplified physics model. Real pool physics involves
3538 // collision-induced throw, spin transfer, and cue ball deflection not fully simulated here.
3539 // The ghost ball method shows the *ideal* line for a center-cue hit without spin.
3540
3541 }
3542 else if (aimingAtRail && hitRailIndex != -1) {
3543 // Aiming at a rail: Draw reflection line
3544 float reflectAngle = cueAngle;
3545 // Reflect angle based on which rail was hit
3546 if (hitRailIndex == 0 || hitRailIndex == 1) { // Left or Right rail
3547 reflectAngle = PI - cueAngle; // Reflect horizontal component
3548 }
3549 else { // Top or Bottom rail
3550 reflectAngle = -cueAngle; // Reflect vertical component
3551 }
3552 // Normalize angle if needed (atan2 usually handles this)
3553 while (reflectAngle > PI) reflectAngle -= 2 * PI;
3554 while (reflectAngle <= -PI) reflectAngle += 2 * PI;
3555
3556
3557 float reflectionLength = 60.0f; // Length of the reflection line
3558 D2D1_POINT_2F reflectionEnd = D2D1::Point2F(
3559 finalLineEnd.x + cosf(reflectAngle) * reflectionLength,
3560 finalLineEnd.y + sinf(reflectAngle) * reflectionLength
3561 );
3562
3563 // Draw the reflection line (e.g., using a different color/style)
3564 pRT->DrawLine(finalLineEnd, reflectionEnd, pReflectBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
3565 }
3566
3567 // Release resources
3568 SafeRelease(&pBrush);
3569 SafeRelease(&pGhostBrush);
3570 SafeRelease(&pCueBrush);
3571 SafeRelease(&pReflectBrush); // Release new brush
3572 SafeRelease(&pCyanBrush);
3573 SafeRelease(&pPurpleBrush);
3574 SafeRelease(&pDashedStyle);
3575}
3576
3577
3578void DrawUI(ID2D1RenderTarget* pRT) {
3579 if (!pTextFormat || !pLargeTextFormat) return;
3580
3581 ID2D1SolidColorBrush* pBrush = nullptr;
3582 pRT->CreateSolidColorBrush(UI_TEXT_COLOR, &pBrush);
3583 if (!pBrush) return;
3584
3585 // --- Player Info Area (Top Left/Right) --- (Unchanged)
3586 float uiTop = TABLE_TOP - 80;
3587 float uiHeight = 60;
3588 float p1Left = TABLE_LEFT;
3589 float p1Width = 150;
3590 float p2Left = TABLE_RIGHT - p1Width;
3591 D2D1_RECT_F p1Rect = D2D1::RectF(p1Left, uiTop, p1Left + p1Width, uiTop + uiHeight);
3592 D2D1_RECT_F p2Rect = D2D1::RectF(p2Left, uiTop, p2Left + p1Width, uiTop + uiHeight);
3593
3594 // Player 1 Info Text (Unchanged)
3595 std::wostringstream oss1;
3596 oss1 << player1Info.name.c_str() << L"\n";
3597 if (player1Info.assignedType != BallType::NONE) {
3598 oss1 << ((player1Info.assignedType == BallType::SOLID) ? L"Solids (Yellow)" : L"Stripes (Red)");
3599 oss1 << L" [" << player1Info.ballsPocketedCount << L"/7]";
3600 }
3601 else {
3602 oss1 << L"(Undecided)";
3603 }
3604 pRT->DrawText(oss1.str().c_str(), (UINT32)oss1.str().length(), pTextFormat, &p1Rect, pBrush);
3605 // Draw Player 1 Side Ball
3606 if (player1Info.assignedType != BallType::NONE)
3607 {
3608 ID2D1SolidColorBrush* pBallBrush = nullptr;
3609 D2D1_COLOR_F ballColor = (player1Info.assignedType == BallType::SOLID) ?
3610 D2D1::ColorF(1.0f, 1.0f, 0.0f) : D2D1::ColorF(1.0f, 0.0f, 0.0f);
3611 pRT->CreateSolidColorBrush(ballColor, &pBallBrush);
3612 if (pBallBrush)
3613 {
3614 D2D1_POINT_2F ballCenter = D2D1::Point2F(p1Rect.right + 10.0f, p1Rect.top + 20.0f);
3615 float radius = 10.0f;
3616 D2D1_ELLIPSE ball = D2D1::Ellipse(ballCenter, radius, radius);
3617 pRT->FillEllipse(&ball, pBallBrush);
3618 SafeRelease(&pBallBrush);
3619 // Draw border around the ball
3620 ID2D1SolidColorBrush* pBorderBrush = nullptr;
3621 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
3622 if (pBorderBrush)
3623 {
3624 pRT->DrawEllipse(&ball, pBorderBrush, 1.5f); // thin border
3625 SafeRelease(&pBorderBrush);
3626 }
3627
3628 // If stripes, draw a stripe band
3629 if (player1Info.assignedType == BallType::STRIPE)
3630 {
3631 ID2D1SolidColorBrush* pStripeBrush = nullptr;
3632 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
3633 if (pStripeBrush)
3634 {
3635 D2D1_RECT_F stripeRect = D2D1::RectF(
3636 ballCenter.x - radius,
3637 ballCenter.y - 3.0f,
3638 ballCenter.x + radius,
3639 ballCenter.y + 3.0f
3640 );
3641 pRT->FillRectangle(&stripeRect, pStripeBrush);
3642 SafeRelease(&pStripeBrush);
3643 }
3644 }
3645 }
3646 }
3647
3648
3649 // Player 2 Info Text (Unchanged)
3650 std::wostringstream oss2;
3651 oss2 << player2Info.name.c_str() << L"\n";
3652 if (player2Info.assignedType != BallType::NONE) {
3653 oss2 << ((player2Info.assignedType == BallType::SOLID) ? L"Solids (Yellow)" : L"Stripes (Red)");
3654 oss2 << L" [" << player2Info.ballsPocketedCount << L"/7]";
3655 }
3656 else {
3657 oss2 << L"(Undecided)";
3658 }
3659 pRT->DrawText(oss2.str().c_str(), (UINT32)oss2.str().length(), pTextFormat, &p2Rect, pBrush);
3660 // Draw Player 2 Side Ball
3661 if (player2Info.assignedType != BallType::NONE)
3662 {
3663 ID2D1SolidColorBrush* pBallBrush = nullptr;
3664 D2D1_COLOR_F ballColor = (player2Info.assignedType == BallType::SOLID) ?
3665 D2D1::ColorF(1.0f, 1.0f, 0.0f) : D2D1::ColorF(1.0f, 0.0f, 0.0f);
3666 pRT->CreateSolidColorBrush(ballColor, &pBallBrush);
3667 if (pBallBrush)
3668 {
3669 D2D1_POINT_2F ballCenter = D2D1::Point2F(p2Rect.right + 10.0f, p2Rect.top + 20.0f);
3670 float radius = 10.0f;
3671 D2D1_ELLIPSE ball = D2D1::Ellipse(ballCenter, radius, radius);
3672 pRT->FillEllipse(&ball, pBallBrush);
3673 SafeRelease(&pBallBrush);
3674 // Draw border around the ball
3675 ID2D1SolidColorBrush* pBorderBrush = nullptr;
3676 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
3677 if (pBorderBrush)
3678 {
3679 pRT->DrawEllipse(&ball, pBorderBrush, 1.5f); // thin border
3680 SafeRelease(&pBorderBrush);
3681 }
3682
3683 // If stripes, draw a stripe band
3684 if (player2Info.assignedType == BallType::STRIPE)
3685 {
3686 ID2D1SolidColorBrush* pStripeBrush = nullptr;
3687 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
3688 if (pStripeBrush)
3689 {
3690 D2D1_RECT_F stripeRect = D2D1::RectF(
3691 ballCenter.x - radius,
3692 ballCenter.y - 3.0f,
3693 ballCenter.x + radius,
3694 ballCenter.y + 3.0f
3695 );
3696 pRT->FillRectangle(&stripeRect, pStripeBrush);
3697 SafeRelease(&pStripeBrush);
3698 }
3699 }
3700 }
3701 }
3702
3703
3704 // --- MODIFIED: Current Turn Arrow (Blue, Bigger, Beside Name) ---
3705 ID2D1SolidColorBrush* pArrowBrush = nullptr;
3706 pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrowBrush);
3707 if (pArrowBrush && currentGameState != GAME_OVER && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
3708 float arrowSizeBase = 32.0f; // Base size for width/height offsets (4x original ~8)
3709 float arrowCenterY = p1Rect.top + uiHeight / 2.0f; // Center vertically with text box
3710 float arrowTipX, arrowBackX;
3711
3712 D2D1_RECT_F playerBox = (currentPlayer == 1) ? p1Rect : p2Rect;
3713 arrowBackX = playerBox.left - 25.0f;
3714 arrowTipX = arrowBackX + arrowSizeBase * 0.75f;
3715
3716 float notchDepth = 12.0f; // Increased from 6.0f to make the rectangle longer
3717 float notchWidth = 10.0f;
3718
3719 float cx = arrowBackX;
3720 float cy = arrowCenterY;
3721
3722 // Define triangle + rectangle tail shape
3723 D2D1_POINT_2F tip = D2D1::Point2F(arrowTipX, cy); // tip
3724 D2D1_POINT_2F baseTop = D2D1::Point2F(cx, cy - arrowSizeBase / 2.0f); // triangle top
3725 D2D1_POINT_2F baseBot = D2D1::Point2F(cx, cy + arrowSizeBase / 2.0f); // triangle bottom
3726
3727 // Rectangle coordinates for the tail portion:
3728 D2D1_POINT_2F r1 = D2D1::Point2F(cx - notchDepth, cy - notchWidth / 2.0f); // rect top-left
3729 D2D1_POINT_2F r2 = D2D1::Point2F(cx, cy - notchWidth / 2.0f); // rect top-right
3730 D2D1_POINT_2F r3 = D2D1::Point2F(cx, cy + notchWidth / 2.0f); // rect bottom-right
3731 D2D1_POINT_2F r4 = D2D1::Point2F(cx - notchDepth, cy + notchWidth / 2.0f); // rect bottom-left
3732
3733 ID2D1PathGeometry* pPath = nullptr;
3734 if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
3735 ID2D1GeometrySink* pSink = nullptr;
3736 if (SUCCEEDED(pPath->Open(&pSink))) {
3737 pSink->BeginFigure(tip, D2D1_FIGURE_BEGIN_FILLED);
3738 pSink->AddLine(baseTop);
3739 pSink->AddLine(r2); // transition from triangle into rectangle
3740 pSink->AddLine(r1);
3741 pSink->AddLine(r4);
3742 pSink->AddLine(r3);
3743 pSink->AddLine(baseBot);
3744 pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
3745 pSink->Close();
3746 SafeRelease(&pSink);
3747 pRT->FillGeometry(pPath, pArrowBrush);
3748 }
3749 SafeRelease(&pPath);
3750 }
3751
3752
3753 SafeRelease(&pArrowBrush);
3754 }
3755
3756 //original
3757/*
3758 // --- MODIFIED: Current Turn Arrow (Blue, Bigger, Beside Name) ---
3759 ID2D1SolidColorBrush* pArrowBrush = nullptr;
3760 pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrowBrush);
3761 if (pArrowBrush && currentGameState != GAME_OVER && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
3762 float arrowSizeBase = 32.0f; // Base size for width/height offsets (4x original ~8)
3763 float arrowCenterY = p1Rect.top + uiHeight / 2.0f; // Center vertically with text box
3764 float arrowTipX, arrowBackX;
3765
3766 if (currentPlayer == 1) {
3767arrowBackX = p1Rect.left - 25.0f; // Position left of the box
3768 arrowTipX = arrowBackX + arrowSizeBase * 0.75f; // Pointy end extends right
3769 // Define points for right-pointing arrow
3770 //D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
3771 //D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
3772 //D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
3773 // Enhanced arrow with base rectangle intersection
3774 float notchDepth = 6.0f; // Depth of square base "stem"
3775 float notchWidth = 4.0f; // Thickness of square part
3776
3777 D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
3778 D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
3779 D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX - notchDepth, arrowCenterY - notchWidth / 2.0f); // Square Left-Top
3780 D2D1_POINT_2F pt4 = D2D1::Point2F(arrowBackX - notchDepth, arrowCenterY + notchWidth / 2.0f); // Square Left-Bottom
3781 D2D1_POINT_2F pt5 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
3782
3783
3784 ID2D1PathGeometry* pPath = nullptr;
3785 if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
3786 ID2D1GeometrySink* pSink = nullptr;
3787 if (SUCCEEDED(pPath->Open(&pSink))) {
3788 pSink->BeginFigure(pt1, D2D1_FIGURE_BEGIN_FILLED);
3789 pSink->AddLine(pt2);
3790 pSink->AddLine(pt3);
3791 pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
3792 pSink->Close();
3793 SafeRelease(&pSink);
3794 pRT->FillGeometry(pPath, pArrowBrush);
3795 }
3796 SafeRelease(&pPath);
3797 }
3798 }
3799
3800
3801 //==================else player 2
3802 else { // Player 2
3803 // Player 2: Arrow left of P2 box, pointing right (or right of P2 box pointing left?)
3804 // Let's keep it consistent: Arrow left of the active player's box, pointing right.
3805// Let's keep it consistent: Arrow left of the active player's box, pointing right.
3806arrowBackX = p2Rect.left - 25.0f; // Position left of the box
3807arrowTipX = arrowBackX + arrowSizeBase * 0.75f; // Pointy end extends right
3808// Define points for right-pointing arrow
3809D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
3810D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
3811D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
3812
3813ID2D1PathGeometry* pPath = nullptr;
3814if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
3815 ID2D1GeometrySink* pSink = nullptr;
3816 if (SUCCEEDED(pPath->Open(&pSink))) {
3817 pSink->BeginFigure(pt1, D2D1_FIGURE_BEGIN_FILLED);
3818 pSink->AddLine(pt2);
3819 pSink->AddLine(pt3);
3820 pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
3821 pSink->Close();
3822 SafeRelease(&pSink);
3823 pRT->FillGeometry(pPath, pArrowBrush);
3824 }
3825 SafeRelease(&pPath);
3826}
3827 }
3828 */
3829
3830 // --- MODIFIED: Foul Text (Large Red, Bottom Center) ---
3831 if (foulCommitted && currentGameState != SHOT_IN_PROGRESS) {
3832 ID2D1SolidColorBrush* pFoulBrush = nullptr;
3833 pRT->CreateSolidColorBrush(FOUL_TEXT_COLOR, &pFoulBrush);
3834 if (pFoulBrush && pLargeTextFormat) {
3835 // Calculate Rect for bottom-middle area
3836 float foulWidth = 200.0f; // Adjust width as needed
3837 float foulHeight = 60.0f;
3838 float foulLeft = TABLE_LEFT + (TABLE_WIDTH / 2.0f) - (foulWidth / 2.0f);
3839 // Position below the pocketed balls bar
3840 float foulTop = pocketedBallsBarRect.bottom + 10.0f;
3841 D2D1_RECT_F foulRect = D2D1::RectF(foulLeft, foulTop, foulLeft + foulWidth, foulTop + foulHeight);
3842
3843 // --- Set text alignment to center for foul text ---
3844 pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
3845 pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
3846
3847 pRT->DrawText(L"FOUL!", 5, pLargeTextFormat, &foulRect, pFoulBrush);
3848
3849 // --- Restore default alignment for large text if needed elsewhere ---
3850 // pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
3851 // pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
3852
3853 SafeRelease(&pFoulBrush);
3854 }
3855 }
3856
3857 // Show AI Thinking State (Unchanged from previous step)
3858 if (currentGameState == AI_THINKING && pTextFormat) {
3859 ID2D1SolidColorBrush* pThinkingBrush = nullptr;
3860 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Orange), &pThinkingBrush);
3861 if (pThinkingBrush) {
3862 D2D1_RECT_F thinkingRect = p2Rect;
3863 thinkingRect.top += 20; // Offset within P2 box
3864 // Ensure default text alignment for this
3865 pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
3866 pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
3867 pRT->DrawText(L"Thinking...", 11, pTextFormat, &thinkingRect, pThinkingBrush);
3868 SafeRelease(&pThinkingBrush);
3869 }
3870 }
3871
3872 SafeRelease(&pBrush);
3873
3874 // --- Draw CHEAT MODE label if active ---
3875 if (cheatModeEnabled) {
3876 ID2D1SolidColorBrush* pCheatBrush = nullptr;
3877 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Red), &pCheatBrush);
3878 if (pCheatBrush && pTextFormat) {
3879 D2D1_RECT_F cheatTextRect = D2D1::RectF(
3880 TABLE_LEFT + 10.0f,
3881 TABLE_TOP + 10.0f,
3882 TABLE_LEFT + 200.0f,
3883 TABLE_TOP + 40.0f
3884 );
3885 pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
3886 pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
3887 pRT->DrawText(L"CHEAT MODE ON", wcslen(L"CHEAT MODE ON"), pTextFormat, &cheatTextRect, pCheatBrush);
3888 }
3889 SafeRelease(&pCheatBrush);
3890 }
3891}
3892
3893void DrawPowerMeter(ID2D1RenderTarget* pRT) {
3894 // Draw Border
3895 ID2D1SolidColorBrush* pBorderBrush = nullptr;
3896 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
3897 if (!pBorderBrush) return;
3898 pRT->DrawRectangle(&powerMeterRect, pBorderBrush, 2.0f);
3899 SafeRelease(&pBorderBrush);
3900
3901 // Create Gradient Fill
3902 ID2D1GradientStopCollection* pGradientStops = nullptr;
3903 ID2D1LinearGradientBrush* pGradientBrush = nullptr;
3904 D2D1_GRADIENT_STOP gradientStops[4];
3905 gradientStops[0].position = 0.0f;
3906 gradientStops[0].color = D2D1::ColorF(D2D1::ColorF::Green);
3907 gradientStops[1].position = 0.45f;
3908 gradientStops[1].color = D2D1::ColorF(D2D1::ColorF::Yellow);
3909 gradientStops[2].position = 0.7f;
3910 gradientStops[2].color = D2D1::ColorF(D2D1::ColorF::Orange);
3911 gradientStops[3].position = 1.0f;
3912 gradientStops[3].color = D2D1::ColorF(D2D1::ColorF::Red);
3913
3914 pRT->CreateGradientStopCollection(gradientStops, 4, &pGradientStops);
3915 if (pGradientStops) {
3916 D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props = {};
3917 props.startPoint = D2D1::Point2F(powerMeterRect.left, powerMeterRect.bottom);
3918 props.endPoint = D2D1::Point2F(powerMeterRect.left, powerMeterRect.top);
3919 pRT->CreateLinearGradientBrush(props, pGradientStops, &pGradientBrush);
3920 SafeRelease(&pGradientStops);
3921 }
3922
3923 // Calculate Fill Height
3924 float fillRatio = 0;
3925 //if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
3926 // Determine if power meter should reflect shot power (human aiming or AI preparing)
3927 bool humanIsAimingPower = isAiming && (currentGameState == AIMING || currentGameState == BREAKING);
3928 // NEW Condition: AI is displaying its aim, so show its chosen power
3929 bool aiIsVisualizingPower = (isPlayer2AI && currentPlayer == 2 &&
3930 currentGameState == AI_THINKING && aiIsDisplayingAim);
3931
3932 if (humanIsAimingPower || aiIsVisualizingPower) { // Use the new condition
3933 fillRatio = shotPower / MAX_SHOT_POWER;
3934 }
3935 float fillHeight = (powerMeterRect.bottom - powerMeterRect.top) * fillRatio;
3936 D2D1_RECT_F fillRect = D2D1::RectF(
3937 powerMeterRect.left,
3938 powerMeterRect.bottom - fillHeight,
3939 powerMeterRect.right,
3940 powerMeterRect.bottom
3941 );
3942
3943 if (pGradientBrush) {
3944 pRT->FillRectangle(&fillRect, pGradientBrush);
3945 SafeRelease(&pGradientBrush);
3946 }
3947
3948 // Draw scale notches
3949 ID2D1SolidColorBrush* pNotchBrush = nullptr;
3950 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pNotchBrush);
3951 if (pNotchBrush) {
3952 for (int i = 0; i <= 8; ++i) {
3953 float y = powerMeterRect.top + (powerMeterRect.bottom - powerMeterRect.top) * (i / 8.0f);
3954 pRT->DrawLine(
3955 D2D1::Point2F(powerMeterRect.right + 2.0f, y),
3956 D2D1::Point2F(powerMeterRect.right + 8.0f, y),
3957 pNotchBrush,
3958 1.5f
3959 );
3960 }
3961 SafeRelease(&pNotchBrush);
3962 }
3963
3964 // Draw "Power" Label Below Meter
3965 if (pTextFormat) {
3966 ID2D1SolidColorBrush* pTextBrush = nullptr;
3967 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pTextBrush);
3968 if (pTextBrush) {
3969 D2D1_RECT_F textRect = D2D1::RectF(
3970 powerMeterRect.left - 20.0f,
3971 powerMeterRect.bottom + 8.0f,
3972 powerMeterRect.right + 20.0f,
3973 powerMeterRect.bottom + 38.0f
3974 );
3975 pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
3976 pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
3977 pRT->DrawText(L"Power", 5, pTextFormat, &textRect, pTextBrush);
3978 SafeRelease(&pTextBrush);
3979 }
3980 }
3981
3982 // Draw Glow Effect if fully charged or fading out
3983 static float glowPulse = 0.0f;
3984 static bool glowIncreasing = true;
3985 static float glowFadeOut = 0.0f; // NEW: tracks fading out
3986
3987 if (shotPower >= MAX_SHOT_POWER * 0.99f) {
3988 // While fully charged, keep pulsing normally
3989 if (glowIncreasing) {
3990 glowPulse += 0.02f;
3991 if (glowPulse >= 1.0f) glowIncreasing = false;
3992 }
3993 else {
3994 glowPulse -= 0.02f;
3995 if (glowPulse <= 0.0f) glowIncreasing = true;
3996 }
3997 glowFadeOut = 1.0f; // Reset fade out to full
3998 }
3999 else if (glowFadeOut > 0.0f) {
4000 // If shot fired, gradually fade out
4001 glowFadeOut -= 0.02f;
4002 if (glowFadeOut < 0.0f) glowFadeOut = 0.0f;
4003 }
4004
4005 if (glowFadeOut > 0.0f) {
4006 ID2D1SolidColorBrush* pGlowBrush = nullptr;
4007 float effectiveOpacity = (0.3f + 0.7f * glowPulse) * glowFadeOut;
4008 pRT->CreateSolidColorBrush(
4009 D2D1::ColorF(D2D1::ColorF::Red, effectiveOpacity),
4010 &pGlowBrush
4011 );
4012 if (pGlowBrush) {
4013 float glowCenterX = (powerMeterRect.left + powerMeterRect.right) / 2.0f;
4014 float glowCenterY = powerMeterRect.top;
4015 D2D1_ELLIPSE glowEllipse = D2D1::Ellipse(
4016 D2D1::Point2F(glowCenterX, glowCenterY - 10.0f),
4017 12.0f + 3.0f * glowPulse,
4018 6.0f + 2.0f * glowPulse
4019 );
4020 pRT->FillEllipse(&glowEllipse, pGlowBrush);
4021 SafeRelease(&pGlowBrush);
4022 }
4023 }
4024}
4025
4026void DrawSpinIndicator(ID2D1RenderTarget* pRT) {
4027 ID2D1SolidColorBrush* pWhiteBrush = nullptr;
4028 ID2D1SolidColorBrush* pRedBrush = nullptr;
4029
4030 pRT->CreateSolidColorBrush(CUE_BALL_COLOR, &pWhiteBrush);
4031 pRT->CreateSolidColorBrush(ENGLISH_DOT_COLOR, &pRedBrush);
4032
4033 if (!pWhiteBrush || !pRedBrush) {
4034 SafeRelease(&pWhiteBrush);
4035 SafeRelease(&pRedBrush);
4036 return;
4037 }
4038
4039 // Draw White Ball Background
4040 D2D1_ELLIPSE bgEllipse = D2D1::Ellipse(spinIndicatorCenter, spinIndicatorRadius, spinIndicatorRadius);
4041 pRT->FillEllipse(&bgEllipse, pWhiteBrush);
4042 pRT->DrawEllipse(&bgEllipse, pRedBrush, 0.5f); // Thin red border
4043
4044
4045 // Draw Red Dot for Spin Position
4046 float dotRadius = 4.0f;
4047 float dotX = spinIndicatorCenter.x + cueSpinX * (spinIndicatorRadius - dotRadius); // Keep dot inside edge
4048 float dotY = spinIndicatorCenter.y + cueSpinY * (spinIndicatorRadius - dotRadius);
4049 D2D1_ELLIPSE dotEllipse = D2D1::Ellipse(D2D1::Point2F(dotX, dotY), dotRadius, dotRadius);
4050 pRT->FillEllipse(&dotEllipse, pRedBrush);
4051
4052 SafeRelease(&pWhiteBrush);
4053 SafeRelease(&pRedBrush);
4054}
4055
4056
4057void DrawPocketedBallsIndicator(ID2D1RenderTarget* pRT) {
4058 ID2D1SolidColorBrush* pBgBrush = nullptr;
4059 ID2D1SolidColorBrush* pBallBrush = nullptr;
4060
4061 // Ensure render target is valid before proceeding
4062 if (!pRT) return;
4063
4064 HRESULT hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black, 0.8f), &pBgBrush); // Semi-transparent black
4065 if (FAILED(hr)) { SafeRelease(&pBgBrush); return; } // Exit if brush creation fails
4066
4067 hr = pRT->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0), &pBallBrush); // Placeholder, color will be set per ball
4068 if (FAILED(hr)) {
4069 SafeRelease(&pBgBrush);
4070 SafeRelease(&pBallBrush);
4071 return; // Exit if brush creation fails
4072 }
4073
4074 // Draw the background bar (rounded rect)
4075 D2D1_ROUNDED_RECT roundedRect = D2D1::RoundedRect(pocketedBallsBarRect, 10.0f, 10.0f); // Corner radius 10
4076 float baseAlpha = 0.8f;
4077 float flashBoost = pocketFlashTimer * 0.5f; // Make flash effect boost alpha slightly
4078 float finalAlpha = std::min(1.0f, baseAlpha + flashBoost);
4079 pBgBrush->SetOpacity(finalAlpha);
4080 pRT->FillRoundedRectangle(&roundedRect, pBgBrush);
4081 pBgBrush->SetOpacity(1.0f); // Reset opacity after drawing
4082
4083 // --- Draw small circles for pocketed balls inside the bar ---
4084
4085 // Calculate dimensions based on the bar's height for better scaling
4086 float barHeight = pocketedBallsBarRect.bottom - pocketedBallsBarRect.top;
4087 float ballDisplayRadius = barHeight * 0.30f; // Make balls slightly smaller relative to bar height
4088 float spacing = ballDisplayRadius * 2.2f; // Adjust spacing slightly
4089 float padding = spacing * 0.75f; // Add padding from the edges
4090 float center_Y = pocketedBallsBarRect.top + barHeight / 2.0f; // Vertical center
4091
4092 // Starting X positions with padding
4093 float currentX_P1 = pocketedBallsBarRect.left + padding;
4094 float currentX_P2 = pocketedBallsBarRect.right - padding; // Start from right edge minus padding
4095
4096 int p1DrawnCount = 0;
4097 int p2DrawnCount = 0;
4098 const int maxBallsToShow = 7; // Max balls per player in the bar
4099
4100 for (const auto& b : balls) {
4101 if (b.isPocketed) {
4102 // Skip cue ball and 8-ball in this indicator
4103 if (b.id == 0 || b.id == 8) continue;
4104
4105 bool isPlayer1Ball = (player1Info.assignedType != BallType::NONE && b.type == player1Info.assignedType);
4106 bool isPlayer2Ball = (player2Info.assignedType != BallType::NONE && b.type == player2Info.assignedType);
4107
4108 if (isPlayer1Ball && p1DrawnCount < maxBallsToShow) {
4109 pBallBrush->SetColor(b.color);
4110 // Draw P1 balls from left to right
4111 D2D1_ELLIPSE ballEllipse = D2D1::Ellipse(D2D1::Point2F(currentX_P1 + p1DrawnCount * spacing, center_Y), ballDisplayRadius, ballDisplayRadius);
4112 pRT->FillEllipse(&ballEllipse, pBallBrush);
4113 p1DrawnCount++;
4114 }
4115 else if (isPlayer2Ball && p2DrawnCount < maxBallsToShow) {
4116 pBallBrush->SetColor(b.color);
4117 // Draw P2 balls from right to left
4118 D2D1_ELLIPSE ballEllipse = D2D1::Ellipse(D2D1::Point2F(currentX_P2 - p2DrawnCount * spacing, center_Y), ballDisplayRadius, ballDisplayRadius);
4119 pRT->FillEllipse(&ballEllipse, pBallBrush);
4120 p2DrawnCount++;
4121 }
4122 // Note: Balls pocketed before assignment or opponent balls are intentionally not shown here.
4123 // You could add logic here to display them differently if needed (e.g., smaller, grayed out).
4124 }
4125 }
4126
4127 SafeRelease(&pBgBrush);
4128 SafeRelease(&pBallBrush);
4129}
4130
4131void DrawBallInHandIndicator(ID2D1RenderTarget* pRT) {
4132 if (!isDraggingCueBall && (currentGameState != BALL_IN_HAND_P1 && currentGameState != BALL_IN_HAND_P2 && currentGameState != PRE_BREAK_PLACEMENT)) {
4133 return; // Only show when placing/dragging
4134 }
4135
4136 Ball* cueBall = GetCueBall();
4137 if (!cueBall) return;
4138
4139 ID2D1SolidColorBrush* pGhostBrush = nullptr;
4140 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.6f), &pGhostBrush); // Semi-transparent white
4141
4142 if (pGhostBrush) {
4143 D2D1_POINT_2F drawPos;
4144 if (isDraggingCueBall) {
4145 drawPos = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y);
4146 }
4147 else {
4148 // If not dragging but in placement state, show at current ball pos
4149 drawPos = D2D1::Point2F(cueBall->x, cueBall->y);
4150 }
4151
4152 // Check if the placement is valid before drawing differently?
4153 bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
4154 bool isValid = IsValidCueBallPosition(drawPos.x, drawPos.y, behindHeadstring);
4155
4156 if (!isValid) {
4157 // Maybe draw red outline if invalid placement?
4158 pGhostBrush->SetColor(D2D1::ColorF(D2D1::ColorF::Red, 0.6f));
4159 }
4160
4161
4162 D2D1_ELLIPSE ghostEllipse = D2D1::Ellipse(drawPos, BALL_RADIUS, BALL_RADIUS);
4163 pRT->FillEllipse(&ghostEllipse, pGhostBrush);
4164 pRT->DrawEllipse(&ghostEllipse, pGhostBrush, 1.0f); // Outline
4165
4166 SafeRelease(&pGhostBrush);
4167 }
4168}