diff --git a/.gitignore b/.gitignore index 6676cf31..98ae1432 100644 --- a/.gitignore +++ b/.gitignore @@ -95,3 +95,8 @@ DerivedData/ .swiftpm/configuration/registries.json .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata .netrc + + +# nodejs +node_modules + diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..1908b9ca --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,138 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Project Overview + +Deckster is a multi-platform card game framework built with .NET 9. It provides a WebSocket-based server architecture for hosting multiplayer card games with clients available in C# (.NET), Swift (iOS), and Kotlin (Android). + +## Commands + +### Building +```bash +# Build the entire solution +build.bat +# Or manually: +cd src/Deckster.Server +dotnet restore +dotnet build +``` + +### Running the Server +```bash +# Run the server +server.bat +# Or manually: +cd src/Deckster.Server +dotnet run +``` + +### Running Tests +```bash +# Run all tests +dotnet test src/Deckster.UnitTests/Deckster.UnitTests.csproj + +# Run tests with detailed output +dotnet test src/Deckster.UnitTests/Deckster.UnitTests.csproj --logger "console;verbosity=detailed" +``` + +### Running Sample Clients +Sample clients for different games can be run using the provided shell scripts or directly: +```bash +# Using convenience scripts (bash): +./crazyeights.sh +./chatroom.sh +./idiot.sh +./bullshit.sh + +# Or manually: +cd src/Deckster.[GameName].SampleClient +dotnet run +``` + +### Code Generation +The project uses OpenAPI/Swagger for code generation: +```bash +# Server generates OpenAPI spec at runtime +# Check decksterapi.yml and generated/ directory for OpenAPI outputs + +# Run code generator +cd src/Deckster.CodeGenerator +dotnet run +``` + +## Architecture + +### Multi-Layered Solution Structure + +The solution is organized into logical folders: +- **10. Server**: `Deckster.Server` - ASP.NET Core WebSocket server +- **15. Sample clients**: Multiple `Deckster.[GameName].SampleClient` projects demonstrating client implementation +- **20. Libs**: Core libraries (`Deckster.Core`, `Deckster.Client`, `Deckster.Games`) +- **30. Code generation**: `Deckster.CodeGenerator` and generated client code +- **90. Tests**: `Deckster.UnitTests` with NUnit + +### Core Components + +**Deckster.Core**: Shared data models, protocol definitions, serialization, and authentication models. Used by both server and clients. + +**Deckster.Server**: ASP.NET Core server hosting multiple card games. Contains: +- WebSocket communication layer (`Communication/IServerChannel`, `Communication/WebSocketServerChannel`) +- Game implementations in `Games/` directory +- Controllers for REST API endpoints +- Authentication middleware +- Swagger/OpenAPI integration + +**Deckster.Client**: .NET client library for connecting to Deckster servers. Provides: +- `DecksterClient` - Main client class with authentication +- `GameClient` - Base class for game-specific clients +- Generated game clients (`.g.cs` files) in `Games/` subdirectories + +**Deckster.Games**: Game logic and state management, shared between server and clients. Each game (CrazyEights, Uno, ChatRoom, Gabong, Idiot, Yaniv, TexasHoldEm, Bullshit) has its own subdirectory. + +### Communication Protocol + +The server uses a dual WebSocket architecture: +1. **Action Socket**: Request/response pattern for client actions +2. **Notification Socket**: Asynchronous push notifications from server + +Connection handshake: +1. Client initiates join (establishes action socket) +2. Client sends finish join (establishes notification socket) + +Disconnect procedures differ based on who initiates: +- **Client disconnect**: Client closes action socket with "Client disconnected" message +- **Server disconnect**: Server closes notification socket with "Server disconnected" message + +See README.md diagrams for detailed connection/disconnection flows. + +### Multi-Platform Support + +- **.NET**: `Deckster.Client` NuGet package +- **iOS**: Swift package defined in `Package.swift`, source in `ios/Sources/` +- **Android**: Kotlin library in `android/decksterlib/`, built with Gradle + +Code generation from OpenAPI spec creates platform-specific clients. + +### Code Generation + +- `Deckster.CodeGenerator` generates client code from the server's API +- Generated code appears in `generated/` directory +- The `Deckster.Generated.Client` project contains generated .NET clients +- Mobile platforms have their own generation scripts (`android/generate-code-from-openapi.sh`) + +## Dependencies + +- **.NET 9.0** +- **NUnit** (testing) +- **Marten** (document database for server) +- **Swashbuckle.AspNetCore** (OpenAPI/Swagger) +- **System.Text.Json** (serialization) + +## Project References + +The server references all sample clients for demonstration purposes. When adding new games: +1. Create game logic in `Deckster.Games` +2. Add server-side implementation in `Deckster.Server/Games` +3. Generate client code using `Deckster.CodeGenerator` +4. Create sample client project following naming pattern `Deckster.[GameName].SampleClient` diff --git a/decksterapi.yml b/decksterapi.yml index 45a55671..f6c85ce4 100644 --- a/decksterapi.yml +++ b/decksterapi.yml @@ -1,4 +1,4 @@ -openapi: 3.0.1 +openapi: 3.0.4 info: title: Deckster.Server version: '1.0' @@ -1547,48 +1547,17 @@ paths: responses: '200': description: OK - /: - get: - tags: - - Home - responses: - '200': - description: OK - /login: - get: - tags: - - Home - responses: - '200': - description: OK - post: - tags: - - Home - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/Controllers.LoginModel' - text/json: - schema: - $ref: '#/components/schemas/Controllers.LoginModel' - application/*+json: - schema: - $ref: '#/components/schemas/Controllers.LoginModel' - responses: - '200': - description: OK - /idiot/description: + /hearts/description: get: tags: - - Idiot + - Hearts responses: '200': description: OK - /idiot/metadata: + /hearts/metadata: get: tags: - - Idiot + - Hearts responses: '200': description: OK @@ -1602,10 +1571,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Meta.GameMeta' - /idiot: + /hearts: get: tags: - - Idiot + - Hearts responses: '200': description: OK @@ -1619,10 +1588,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.GameOverviewVm' - /idiot/games: + /hearts/games: get: tags: - - Idiot + - Hearts responses: '200': description: OK @@ -1642,10 +1611,10 @@ paths: type: array items: $ref: '#/components/schemas/Controllers.GameVm' - '/idiot/games/{name}': + '/hearts/games/{name}': get: tags: - - Idiot + - Hearts parameters: - name: name in: path @@ -1679,7 +1648,7 @@ paths: $ref: '#/components/schemas/Controllers.ResponseMessage' delete: tags: - - Idiot + - Hearts parameters: - name: name in: path @@ -1711,10 +1680,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - '/idiot/games/{name}/bot': + '/hearts/games/{name}/bot': post: tags: - - Idiot + - Hearts parameters: - name: name in: path @@ -1734,10 +1703,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - /idiot/previousgames: + /hearts/previousgames: get: tags: - - Idiot + - Hearts responses: '200': description: OK @@ -1746,21 +1715,21 @@ paths: schema: type: array items: - $ref: '#/components/schemas/Idiot.IdiotGame' + $ref: '#/components/schemas/Hearts.HeartsGame' application/json: schema: type: array items: - $ref: '#/components/schemas/Idiot.IdiotGame' + $ref: '#/components/schemas/Hearts.HeartsGame' text/json: schema: type: array items: - $ref: '#/components/schemas/Idiot.IdiotGame' - '/idiot/previousgames/{id}': + $ref: '#/components/schemas/Hearts.HeartsGame' + '/hearts/previousgames/{id}': get: tags: - - Idiot + - Hearts parameters: - name: id in: path @@ -1774,17 +1743,17 @@ paths: content: text/plain: schema: - $ref: '#/components/schemas/Data.HistoricIdiotGame' + $ref: '#/components/schemas/Data.HistoricHeartsGame' application/json: schema: - $ref: '#/components/schemas/Data.HistoricIdiotGame' + $ref: '#/components/schemas/Data.HistoricHeartsGame' text/json: schema: - $ref: '#/components/schemas/Data.HistoricIdiotGame' - '/idiot/previousgames/{id}/{version}': + $ref: '#/components/schemas/Data.HistoricHeartsGame' + '/hearts/previousgames/{id}/{version}': get: tags: - - Idiot + - Hearts parameters: - name: id in: path @@ -1804,17 +1773,17 @@ paths: content: text/plain: schema: - $ref: '#/components/schemas/Data.HistoricIdiotGame' + $ref: '#/components/schemas/Data.HistoricHeartsGame' application/json: schema: - $ref: '#/components/schemas/Data.HistoricIdiotGame' + $ref: '#/components/schemas/Data.HistoricHeartsGame' text/json: schema: - $ref: '#/components/schemas/Data.HistoricIdiotGame' - '/idiot/create/{name}': + $ref: '#/components/schemas/Data.HistoricHeartsGame' + '/hearts/create/{name}': post: tags: - - Idiot + - Hearts parameters: - name: name in: path @@ -1846,10 +1815,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - /idiot/create: + /hearts/create: post: tags: - - Idiot + - Hearts responses: '200': description: OK @@ -1875,10 +1844,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - '/idiot/games/{name}/start': + '/hearts/games/{name}/start': post: tags: - - Idiot + - Hearts parameters: - name: name in: path @@ -1910,10 +1879,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - '/idiot/join/{gameName}': + '/hearts/join/{gameName}': get: tags: - - Idiot + - Hearts parameters: - name: gameName in: path @@ -1923,10 +1892,10 @@ paths: responses: '200': description: OK - '/idiot/join/{connectionId}/finish': + '/hearts/join/{connectionId}/finish': get: tags: - - Idiot + - Hearts parameters: - name: connectionId in: path @@ -1937,10 +1906,10 @@ paths: responses: '200': description: OK - '/idiot/spectate/{gameName}': + '/hearts/spectate/{gameName}': get: tags: - - Idiot + - Hearts parameters: - name: gameName in: path @@ -1950,10 +1919,10 @@ paths: responses: '200': description: OK - '/idiot/spectate/{connectionId}/finish': + '/hearts/spectate/{connectionId}/finish': get: tags: - - Idiot + - Hearts parameters: - name: connectionId in: path @@ -1964,24 +1933,48 @@ paths: responses: '200': description: OK - /meta/messages: + /: get: tags: - - Meta + - Home responses: '200': description: OK - /texasholdem/description: + /login: get: tags: - - TexasHoldEm + - Home responses: '200': description: OK - /texasholdem/metadata: + post: + tags: + - Home + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Controllers.LoginModel' + text/json: + schema: + $ref: '#/components/schemas/Controllers.LoginModel' + application/*+json: + schema: + $ref: '#/components/schemas/Controllers.LoginModel' + responses: + '200': + description: OK + /idiot/description: get: tags: - - TexasHoldEm + - Idiot + responses: + '200': + description: OK + /idiot/metadata: + get: + tags: + - Idiot responses: '200': description: OK @@ -1995,10 +1988,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Meta.GameMeta' - /texasholdem: + /idiot: get: tags: - - TexasHoldEm + - Idiot responses: '200': description: OK @@ -2012,10 +2005,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.GameOverviewVm' - /texasholdem/games: + /idiot/games: get: tags: - - TexasHoldEm + - Idiot responses: '200': description: OK @@ -2035,10 +2028,10 @@ paths: type: array items: $ref: '#/components/schemas/Controllers.GameVm' - '/texasholdem/games/{name}': + '/idiot/games/{name}': get: tags: - - TexasHoldEm + - Idiot parameters: - name: name in: path @@ -2072,7 +2065,7 @@ paths: $ref: '#/components/schemas/Controllers.ResponseMessage' delete: tags: - - TexasHoldEm + - Idiot parameters: - name: name in: path @@ -2104,10 +2097,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - '/texasholdem/games/{name}/bot': + '/idiot/games/{name}/bot': post: tags: - - TexasHoldEm + - Idiot parameters: - name: name in: path @@ -2127,10 +2120,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - /texasholdem/previousgames: + /idiot/previousgames: get: tags: - - TexasHoldEm + - Idiot responses: '200': description: OK @@ -2139,21 +2132,21 @@ paths: schema: type: array items: - $ref: '#/components/schemas/TexasHoldEm.TexasHoldEmGame' + $ref: '#/components/schemas/Idiot.IdiotGame' application/json: schema: type: array items: - $ref: '#/components/schemas/TexasHoldEm.TexasHoldEmGame' + $ref: '#/components/schemas/Idiot.IdiotGame' text/json: schema: type: array items: - $ref: '#/components/schemas/TexasHoldEm.TexasHoldEmGame' - '/texasholdem/previousgames/{id}': + $ref: '#/components/schemas/Idiot.IdiotGame' + '/idiot/previousgames/{id}': get: tags: - - TexasHoldEm + - Idiot parameters: - name: id in: path @@ -2167,17 +2160,17 @@ paths: content: text/plain: schema: - $ref: '#/components/schemas/Data.HistoricTexasHoldEmGame' + $ref: '#/components/schemas/Data.HistoricIdiotGame' application/json: schema: - $ref: '#/components/schemas/Data.HistoricTexasHoldEmGame' + $ref: '#/components/schemas/Data.HistoricIdiotGame' text/json: schema: - $ref: '#/components/schemas/Data.HistoricTexasHoldEmGame' - '/texasholdem/previousgames/{id}/{version}': + $ref: '#/components/schemas/Data.HistoricIdiotGame' + '/idiot/previousgames/{id}/{version}': get: tags: - - TexasHoldEm + - Idiot parameters: - name: id in: path @@ -2197,17 +2190,17 @@ paths: content: text/plain: schema: - $ref: '#/components/schemas/Data.HistoricTexasHoldEmGame' + $ref: '#/components/schemas/Data.HistoricIdiotGame' application/json: schema: - $ref: '#/components/schemas/Data.HistoricTexasHoldEmGame' + $ref: '#/components/schemas/Data.HistoricIdiotGame' text/json: schema: - $ref: '#/components/schemas/Data.HistoricTexasHoldEmGame' - '/texasholdem/create/{name}': + $ref: '#/components/schemas/Data.HistoricIdiotGame' + '/idiot/create/{name}': post: tags: - - TexasHoldEm + - Idiot parameters: - name: name in: path @@ -2239,10 +2232,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - /texasholdem/create: + /idiot/create: post: tags: - - TexasHoldEm + - Idiot responses: '200': description: OK @@ -2268,10 +2261,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - '/texasholdem/games/{name}/start': + '/idiot/games/{name}/start': post: tags: - - TexasHoldEm + - Idiot parameters: - name: name in: path @@ -2303,10 +2296,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - '/texasholdem/join/{gameName}': + '/idiot/join/{gameName}': get: tags: - - TexasHoldEm + - Idiot parameters: - name: gameName in: path @@ -2316,10 +2309,10 @@ paths: responses: '200': description: OK - '/texasholdem/join/{connectionId}/finish': + '/idiot/join/{connectionId}/finish': get: tags: - - TexasHoldEm + - Idiot parameters: - name: connectionId in: path @@ -2330,10 +2323,10 @@ paths: responses: '200': description: OK - '/texasholdem/spectate/{gameName}': + '/idiot/spectate/{gameName}': get: tags: - - TexasHoldEm + - Idiot parameters: - name: gameName in: path @@ -2343,10 +2336,10 @@ paths: responses: '200': description: OK - '/texasholdem/spectate/{connectionId}/finish': + '/idiot/spectate/{connectionId}/finish': get: tags: - - TexasHoldEm + - Idiot parameters: - name: connectionId in: path @@ -2357,17 +2350,24 @@ paths: responses: '200': description: OK - /uno/description: + /meta/messages: get: tags: - - Uno + - Meta responses: '200': description: OK - /uno/metadata: + /texasholdem/description: get: tags: - - Uno + - TexasHoldEm + responses: + '200': + description: OK + /texasholdem/metadata: + get: + tags: + - TexasHoldEm responses: '200': description: OK @@ -2381,10 +2381,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Meta.GameMeta' - /uno: + /texasholdem: get: tags: - - Uno + - TexasHoldEm responses: '200': description: OK @@ -2398,10 +2398,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.GameOverviewVm' - /uno/games: + /texasholdem/games: get: tags: - - Uno + - TexasHoldEm responses: '200': description: OK @@ -2421,10 +2421,10 @@ paths: type: array items: $ref: '#/components/schemas/Controllers.GameVm' - '/uno/games/{name}': + '/texasholdem/games/{name}': get: tags: - - Uno + - TexasHoldEm parameters: - name: name in: path @@ -2458,7 +2458,7 @@ paths: $ref: '#/components/schemas/Controllers.ResponseMessage' delete: tags: - - Uno + - TexasHoldEm parameters: - name: name in: path @@ -2490,10 +2490,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - '/uno/games/{name}/bot': + '/texasholdem/games/{name}/bot': post: tags: - - Uno + - TexasHoldEm parameters: - name: name in: path @@ -2513,10 +2513,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - /uno/previousgames: + /texasholdem/previousgames: get: tags: - - Uno + - TexasHoldEm responses: '200': description: OK @@ -2525,21 +2525,21 @@ paths: schema: type: array items: - $ref: '#/components/schemas/Uno.UnoGame' + $ref: '#/components/schemas/TexasHoldEm.TexasHoldEmGame' application/json: schema: type: array items: - $ref: '#/components/schemas/Uno.UnoGame' + $ref: '#/components/schemas/TexasHoldEm.TexasHoldEmGame' text/json: schema: type: array items: - $ref: '#/components/schemas/Uno.UnoGame' - '/uno/previousgames/{id}': + $ref: '#/components/schemas/TexasHoldEm.TexasHoldEmGame' + '/texasholdem/previousgames/{id}': get: tags: - - Uno + - TexasHoldEm parameters: - name: id in: path @@ -2553,17 +2553,17 @@ paths: content: text/plain: schema: - $ref: '#/components/schemas/Data.HistoricUnoGame' + $ref: '#/components/schemas/Data.HistoricTexasHoldEmGame' application/json: schema: - $ref: '#/components/schemas/Data.HistoricUnoGame' + $ref: '#/components/schemas/Data.HistoricTexasHoldEmGame' text/json: schema: - $ref: '#/components/schemas/Data.HistoricUnoGame' - '/uno/previousgames/{id}/{version}': - get: + $ref: '#/components/schemas/Data.HistoricTexasHoldEmGame' + '/texasholdem/previousgames/{id}/{version}': + get: tags: - - Uno + - TexasHoldEm parameters: - name: id in: path @@ -2583,17 +2583,17 @@ paths: content: text/plain: schema: - $ref: '#/components/schemas/Data.HistoricUnoGame' + $ref: '#/components/schemas/Data.HistoricTexasHoldEmGame' application/json: schema: - $ref: '#/components/schemas/Data.HistoricUnoGame' + $ref: '#/components/schemas/Data.HistoricTexasHoldEmGame' text/json: schema: - $ref: '#/components/schemas/Data.HistoricUnoGame' - '/uno/create/{name}': + $ref: '#/components/schemas/Data.HistoricTexasHoldEmGame' + '/texasholdem/create/{name}': post: tags: - - Uno + - TexasHoldEm parameters: - name: name in: path @@ -2625,10 +2625,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - /uno/create: + /texasholdem/create: post: tags: - - Uno + - TexasHoldEm responses: '200': description: OK @@ -2654,10 +2654,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - '/uno/games/{name}/start': + '/texasholdem/games/{name}/start': post: tags: - - Uno + - TexasHoldEm parameters: - name: name in: path @@ -2689,10 +2689,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - '/uno/join/{gameName}': + '/texasholdem/join/{gameName}': get: tags: - - Uno + - TexasHoldEm parameters: - name: gameName in: path @@ -2702,10 +2702,10 @@ paths: responses: '200': description: OK - '/uno/join/{connectionId}/finish': + '/texasholdem/join/{connectionId}/finish': get: tags: - - Uno + - TexasHoldEm parameters: - name: connectionId in: path @@ -2716,10 +2716,10 @@ paths: responses: '200': description: OK - '/uno/spectate/{gameName}': + '/texasholdem/spectate/{gameName}': get: tags: - - Uno + - TexasHoldEm parameters: - name: gameName in: path @@ -2729,10 +2729,10 @@ paths: responses: '200': description: OK - '/uno/spectate/{connectionId}/finish': + '/texasholdem/spectate/{connectionId}/finish': get: tags: - - Uno + - TexasHoldEm parameters: - name: connectionId in: path @@ -2743,24 +2743,17 @@ paths: responses: '200': description: OK - /me: - get: - tags: - - User - responses: - '200': - description: OK - /yaniv/description: + /uno/description: get: tags: - - Yaniv + - Uno responses: '200': description: OK - /yaniv/metadata: + /uno/metadata: get: tags: - - Yaniv + - Uno responses: '200': description: OK @@ -2774,10 +2767,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Meta.GameMeta' - /yaniv: + /uno: get: tags: - - Yaniv + - Uno responses: '200': description: OK @@ -2791,10 +2784,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.GameOverviewVm' - /yaniv/games: + /uno/games: get: tags: - - Yaniv + - Uno responses: '200': description: OK @@ -2814,10 +2807,10 @@ paths: type: array items: $ref: '#/components/schemas/Controllers.GameVm' - '/yaniv/games/{name}': + '/uno/games/{name}': get: tags: - - Yaniv + - Uno parameters: - name: name in: path @@ -2851,7 +2844,7 @@ paths: $ref: '#/components/schemas/Controllers.ResponseMessage' delete: tags: - - Yaniv + - Uno parameters: - name: name in: path @@ -2883,10 +2876,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - '/yaniv/games/{name}/bot': + '/uno/games/{name}/bot': post: tags: - - Yaniv + - Uno parameters: - name: name in: path @@ -2906,10 +2899,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - /yaniv/previousgames: + /uno/previousgames: get: tags: - - Yaniv + - Uno responses: '200': description: OK @@ -2918,21 +2911,21 @@ paths: schema: type: array items: - $ref: '#/components/schemas/Yaniv.YanivGame' + $ref: '#/components/schemas/Uno.UnoGame' application/json: schema: type: array items: - $ref: '#/components/schemas/Yaniv.YanivGame' + $ref: '#/components/schemas/Uno.UnoGame' text/json: schema: type: array items: - $ref: '#/components/schemas/Yaniv.YanivGame' - '/yaniv/previousgames/{id}': + $ref: '#/components/schemas/Uno.UnoGame' + '/uno/previousgames/{id}': get: tags: - - Yaniv + - Uno parameters: - name: id in: path @@ -2946,17 +2939,17 @@ paths: content: text/plain: schema: - $ref: '#/components/schemas/Data.HistoricYanivGame' + $ref: '#/components/schemas/Data.HistoricUnoGame' application/json: schema: - $ref: '#/components/schemas/Data.HistoricYanivGame' + $ref: '#/components/schemas/Data.HistoricUnoGame' text/json: schema: - $ref: '#/components/schemas/Data.HistoricYanivGame' - '/yaniv/previousgames/{id}/{version}': + $ref: '#/components/schemas/Data.HistoricUnoGame' + '/uno/previousgames/{id}/{version}': get: tags: - - Yaniv + - Uno parameters: - name: id in: path @@ -2976,17 +2969,17 @@ paths: content: text/plain: schema: - $ref: '#/components/schemas/Data.HistoricYanivGame' + $ref: '#/components/schemas/Data.HistoricUnoGame' application/json: schema: - $ref: '#/components/schemas/Data.HistoricYanivGame' + $ref: '#/components/schemas/Data.HistoricUnoGame' text/json: schema: - $ref: '#/components/schemas/Data.HistoricYanivGame' - '/yaniv/create/{name}': + $ref: '#/components/schemas/Data.HistoricUnoGame' + '/uno/create/{name}': post: tags: - - Yaniv + - Uno parameters: - name: name in: path @@ -3018,10 +3011,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - /yaniv/create: + /uno/create: post: tags: - - Yaniv + - Uno responses: '200': description: OK @@ -3047,10 +3040,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - '/yaniv/games/{name}/start': + '/uno/games/{name}/start': post: tags: - - Yaniv + - Uno parameters: - name: name in: path @@ -3082,10 +3075,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - '/yaniv/join/{gameName}': + '/uno/join/{gameName}': get: tags: - - Yaniv + - Uno parameters: - name: gameName in: path @@ -3095,10 +3088,10 @@ paths: responses: '200': description: OK - '/yaniv/join/{connectionId}/finish': + '/uno/join/{connectionId}/finish': get: tags: - - Yaniv + - Uno parameters: - name: connectionId in: path @@ -3109,10 +3102,10 @@ paths: responses: '200': description: OK - '/yaniv/spectate/{gameName}': + '/uno/spectate/{gameName}': get: tags: - - Yaniv + - Uno parameters: - name: gameName in: path @@ -3122,10 +3115,10 @@ paths: responses: '200': description: OK - '/yaniv/spectate/{connectionId}/finish': + '/uno/spectate/{connectionId}/finish': get: tags: - - Yaniv + - Uno parameters: - name: connectionId in: path @@ -3136,132 +3129,877 @@ paths: responses: '200': description: OK -components: - schemas: - Bullshit.BullshitBroadcastNotification: - allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' - - required: - - actualCard - - claimedToBeCard - - playerId - - punishmentCardCount - type: object - properties: - playerId: - type: string - format: uuid - claimedToBeCard: - $ref: '#/components/schemas/Common.Card' - actualCard: - $ref: '#/components/schemas/Common.Card' - punishmentCardCount: - type: integer - format: int32 - additionalProperties: false - Bullshit.BullshitGame: - allOf: - - $ref: '#/components/schemas/Games.GameObject' - - required: - - cardsDrawn - - currentPlayer - - currentPlayerIndex - - deck - - discardPile - - donePlayers - - players - - stockPile - type: object - properties: - deck: - type: array - items: - $ref: '#/components/schemas/Common.Card' - stockPile: - type: array - items: - $ref: '#/components/schemas/Common.Card' - discardPile: - type: array - items: - $ref: '#/components/schemas/Common.Card' - players: - type: array - items: - $ref: '#/components/schemas/Bullshit.BullshitPlayer' - donePlayers: - type: array - items: - $ref: '#/components/schemas/Bullshit.BullshitPlayer' - currentPlayerIndex: - type: integer - format: int32 - claimedTopOfPile: - $ref: '#/components/schemas/Common.Card' - actualTopOfPile: - $ref: '#/components/schemas/Common.Card' - cardsDrawn: - type: integer - format: int32 - potentialBullshit: - $ref: '#/components/schemas/Bullshit.PotentialBullshit' - currentPlayer: - $ref: '#/components/schemas/Bullshit.BullshitPlayer' - additionalProperties: false - Bullshit.BullshitPlayer: - required: - - cards - - id - - name - type: object - properties: - id: - type: string - format: uuid - name: - type: string - cards: - type: array - items: - $ref: '#/components/schemas/Common.Card' - additionalProperties: false - Bullshit.BullshitPlayerNotification: - allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' - - required: - - calledByPlayerId - - card - - punishmentCards - type: object - properties: - calledByPlayerId: - type: string - format: uuid - card: - $ref: '#/components/schemas/Common.Card' - punishmentCards: - type: array - items: - $ref: '#/components/schemas/Common.Card' - additionalProperties: false - Bullshit.BullshitRequest: - allOf: - - $ref: '#/components/schemas/Protocol.DecksterRequest' - - type: object - additionalProperties: false - Bullshit.BullshitResponse: - allOf: - - $ref: '#/components/schemas/Protocol.DecksterResponse' - - required: - - punishmentCards - type: object - properties: - punishmentCards: - type: array - items: - $ref: '#/components/schemas/Common.Card' - additionalProperties: false - Bullshit.CardResponse: + /me: + get: + tags: + - User + responses: + '200': + description: OK + /yaniv/description: + get: + tags: + - Yaniv + responses: + '200': + description: OK + /yaniv/metadata: + get: + tags: + - Yaniv + responses: + '200': + description: OK + content: + text/plain: + schema: + $ref: '#/components/schemas/Meta.GameMeta' + application/json: + schema: + $ref: '#/components/schemas/Meta.GameMeta' + text/json: + schema: + $ref: '#/components/schemas/Meta.GameMeta' + /yaniv: + get: + tags: + - Yaniv + responses: + '200': + description: OK + content: + text/plain: + schema: + $ref: '#/components/schemas/Controllers.GameOverviewVm' + application/json: + schema: + $ref: '#/components/schemas/Controllers.GameOverviewVm' + text/json: + schema: + $ref: '#/components/schemas/Controllers.GameOverviewVm' + /yaniv/games: + get: + tags: + - Yaniv + responses: + '200': + description: OK + content: + text/plain: + schema: + type: array + items: + $ref: '#/components/schemas/Controllers.GameVm' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Controllers.GameVm' + text/json: + schema: + type: array + items: + $ref: '#/components/schemas/Controllers.GameVm' + '/yaniv/games/{name}': + get: + tags: + - Yaniv + parameters: + - name: name + in: path + required: true + schema: + type: string + responses: + '200': + description: OK + content: + text/plain: + schema: + $ref: '#/components/schemas/Controllers.GameVm' + application/json: + schema: + $ref: '#/components/schemas/Controllers.GameVm' + text/json: + schema: + $ref: '#/components/schemas/Controllers.GameVm' + '404': + description: Not Found + content: + text/plain: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + application/json: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + text/json: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + delete: + tags: + - Yaniv + parameters: + - name: name + in: path + required: true + schema: + type: string + responses: + '200': + description: OK + content: + text/plain: + schema: + $ref: '#/components/schemas/Controllers.GameVm' + application/json: + schema: + $ref: '#/components/schemas/Controllers.GameVm' + text/json: + schema: + $ref: '#/components/schemas/Controllers.GameVm' + '404': + description: Not Found + content: + text/plain: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + application/json: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + text/json: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + '/yaniv/games/{name}/bot': + post: + tags: + - Yaniv + parameters: + - name: name + in: path + required: true + schema: + type: string + responses: + '200': + description: OK + content: + text/plain: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + application/json: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + text/json: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + /yaniv/previousgames: + get: + tags: + - Yaniv + responses: + '200': + description: OK + content: + text/plain: + schema: + type: array + items: + $ref: '#/components/schemas/Yaniv.YanivGame' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Yaniv.YanivGame' + text/json: + schema: + type: array + items: + $ref: '#/components/schemas/Yaniv.YanivGame' + '/yaniv/previousgames/{id}': + get: + tags: + - Yaniv + parameters: + - name: id + in: path + required: true + schema: + type: string + format: uuid + responses: + '200': + description: OK + content: + text/plain: + schema: + $ref: '#/components/schemas/Data.HistoricYanivGame' + application/json: + schema: + $ref: '#/components/schemas/Data.HistoricYanivGame' + text/json: + schema: + $ref: '#/components/schemas/Data.HistoricYanivGame' + '/yaniv/previousgames/{id}/{version}': + get: + tags: + - Yaniv + parameters: + - name: id + in: path + required: true + schema: + type: string + format: uuid + - name: version + in: path + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: OK + content: + text/plain: + schema: + $ref: '#/components/schemas/Data.HistoricYanivGame' + application/json: + schema: + $ref: '#/components/schemas/Data.HistoricYanivGame' + text/json: + schema: + $ref: '#/components/schemas/Data.HistoricYanivGame' + '/yaniv/create/{name}': + post: + tags: + - Yaniv + parameters: + - name: name + in: path + required: true + schema: + type: string + responses: + '200': + description: OK + content: + text/plain: + schema: + $ref: '#/components/schemas/Core.GameInfo' + application/json: + schema: + $ref: '#/components/schemas/Core.GameInfo' + text/json: + schema: + $ref: '#/components/schemas/Core.GameInfo' + '400': + description: Bad Request + content: + text/plain: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + application/json: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + text/json: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + /yaniv/create: + post: + tags: + - Yaniv + responses: + '200': + description: OK + content: + text/plain: + schema: + $ref: '#/components/schemas/Core.GameInfo' + application/json: + schema: + $ref: '#/components/schemas/Core.GameInfo' + text/json: + schema: + $ref: '#/components/schemas/Core.GameInfo' + '400': + description: Bad Request + content: + text/plain: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + application/json: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + text/json: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + '/yaniv/games/{name}/start': + post: + tags: + - Yaniv + parameters: + - name: name + in: path + required: true + schema: + type: string + responses: + '200': + description: OK + content: + text/plain: + schema: + $ref: '#/components/schemas/Core.GameInfo' + application/json: + schema: + $ref: '#/components/schemas/Core.GameInfo' + text/json: + schema: + $ref: '#/components/schemas/Core.GameInfo' + '404': + description: Not Found + content: + text/plain: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + application/json: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + text/json: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + '/yaniv/join/{gameName}': + get: + tags: + - Yaniv + parameters: + - name: gameName + in: path + required: true + schema: + type: string + responses: + '200': + description: OK + '/yaniv/join/{connectionId}/finish': + get: + tags: + - Yaniv + parameters: + - name: connectionId + in: path + required: true + schema: + type: string + format: uuid + responses: + '200': + description: OK + '/yaniv/spectate/{gameName}': + get: + tags: + - Yaniv + parameters: + - name: gameName + in: path + required: true + schema: + type: string + responses: + '200': + description: OK + '/yaniv/spectate/{connectionId}/finish': + get: + tags: + - Yaniv + parameters: + - name: connectionId + in: path + required: true + schema: + type: string + format: uuid + responses: + '200': + description: OK +components: + schemas: + Bullshit.BullshitBroadcastNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - required: + - actualCard + - claimedToBeCard + - playerId + - punishmentCardCount + type: object + properties: + playerId: + type: string + format: uuid + claimedToBeCard: + $ref: '#/components/schemas/Common.Card' + actualCard: + $ref: '#/components/schemas/Common.Card' + punishmentCardCount: + type: integer + format: int32 + additionalProperties: false + Bullshit.BullshitGame: + allOf: + - $ref: '#/components/schemas/Games.GameObject' + - required: + - cardsDrawn + - currentPlayer + - currentPlayerIndex + - deck + - discardPile + - donePlayers + - players + - stockPile + type: object + properties: + deck: + type: array + items: + $ref: '#/components/schemas/Common.Card' + stockPile: + type: array + items: + $ref: '#/components/schemas/Common.Card' + discardPile: + type: array + items: + $ref: '#/components/schemas/Common.Card' + players: + type: array + items: + $ref: '#/components/schemas/Bullshit.BullshitPlayer' + donePlayers: + type: array + items: + $ref: '#/components/schemas/Bullshit.BullshitPlayer' + currentPlayerIndex: + type: integer + format: int32 + claimedTopOfPile: + $ref: '#/components/schemas/Common.Card' + actualTopOfPile: + $ref: '#/components/schemas/Common.Card' + cardsDrawn: + type: integer + format: int32 + potentialBullshit: + $ref: '#/components/schemas/Bullshit.PotentialBullshit' + currentPlayer: + $ref: '#/components/schemas/Bullshit.BullshitPlayer' + additionalProperties: false + Bullshit.BullshitPlayer: + required: + - cards + - id + - name + type: object + properties: + id: + type: string + format: uuid + name: + type: string + cards: + type: array + items: + $ref: '#/components/schemas/Common.Card' + additionalProperties: false + Bullshit.BullshitPlayerNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - required: + - calledByPlayerId + - card + - punishmentCards + type: object + properties: + calledByPlayerId: + type: string + format: uuid + card: + $ref: '#/components/schemas/Common.Card' + punishmentCards: + type: array + items: + $ref: '#/components/schemas/Common.Card' + additionalProperties: false + Bullshit.BullshitRequest: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterRequest' + - type: object + additionalProperties: false + Bullshit.BullshitResponse: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterResponse' + - required: + - punishmentCards + type: object + properties: + punishmentCards: + type: array + items: + $ref: '#/components/schemas/Common.Card' + additionalProperties: false + Bullshit.CardResponse: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterResponse' + - required: + - card + type: object + properties: + card: + $ref: '#/components/schemas/Common.Card' + additionalProperties: false + Bullshit.DiscardPileShuffledNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - type: object + additionalProperties: false + Bullshit.DrawCardRequest: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterRequest' + - type: object + additionalProperties: false + Bullshit.FalseBullshitCallNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - required: + - accusedPlayerId + - playerId + - punishmentCardCount + type: object + properties: + playerId: + type: string + format: uuid + accusedPlayerId: + type: string + format: uuid + punishmentCardCount: + type: integer + format: int32 + additionalProperties: false + Bullshit.GameEndedNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - required: + - loserId + - loserName + - players + type: object + properties: + players: + type: array + items: + $ref: '#/components/schemas/Common.PlayerData' + loserId: + type: string + format: uuid + loserName: + type: string + additionalProperties: false + Bullshit.GameStartedNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - required: + - gameId + - playerViewOfGame + type: object + properties: + gameId: + type: string + format: uuid + playerViewOfGame: + $ref: '#/components/schemas/Bullshit.PlayerViewOfGame' + additionalProperties: false + Bullshit.ItsPlayersTurnNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - required: + - playerId + type: object + properties: + playerId: + type: string + format: uuid + additionalProperties: false + Bullshit.ItsYourTurnNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - type: object + additionalProperties: false + Bullshit.OtherBullshitPlayer: + required: + - name + - numberOfCards + - playerId + type: object + properties: + playerId: + type: string + format: uuid + name: + type: string + numberOfCards: + type: integer + format: int32 + additionalProperties: false + Bullshit.PassRequest: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterRequest' + - type: object + additionalProperties: false + Bullshit.PlayerDrewCardNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - required: + - playerId + type: object + properties: + playerId: + type: string + format: uuid + additionalProperties: false + Bullshit.PlayerIsDoneNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - required: + - playerId + type: object + properties: + playerId: + type: string + format: uuid + additionalProperties: false + Bullshit.PlayerPassedNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - required: + - playerId + type: object + properties: + playerId: + type: string + format: uuid + additionalProperties: false + Bullshit.PlayerPutCardNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - required: + - claimedToBeCard + - playerId + type: object + properties: + playerId: + type: string + format: uuid + claimedToBeCard: + $ref: '#/components/schemas/Common.Card' + additionalProperties: false + Bullshit.PlayerViewOfGame: + required: + - cards + - discardPileCount + - otherPlayers + - stockPileCount + type: object + properties: + cards: + type: array + items: + $ref: '#/components/schemas/Common.Card' + claimedTopOfPile: + $ref: '#/components/schemas/Common.Card' + stockPileCount: + type: integer + format: int32 + discardPileCount: + type: integer + format: int32 + otherPlayers: + type: array + items: + $ref: '#/components/schemas/Bullshit.OtherBullshitPlayer' + additionalProperties: false + Bullshit.PotentialBullshit: + required: + - claimedToBeCard + - playerId + type: object + properties: + playerId: + type: string + format: uuid + claimedToBeCard: + $ref: '#/components/schemas/Common.Card' + additionalProperties: false + Bullshit.PutCardRequest: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterRequest' + - required: + - actualCard + - claimedToBeCard + type: object + properties: + actualCard: + $ref: '#/components/schemas/Common.Card' + claimedToBeCard: + $ref: '#/components/schemas/Common.Card' + additionalProperties: false + ChatRoom.ChatNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - required: + - message + - sender + type: object + properties: + sender: + type: string + message: + type: string + additionalProperties: false + ChatRoom.ChatResponse: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterResponse' + - type: object + additionalProperties: false + ChatRoom.ChatRoom: + allOf: + - $ref: '#/components/schemas/Games.GameObject' + - required: + - transcript + type: object + properties: + transcript: + type: array + items: + $ref: '#/components/schemas/ChatRoom.SendChatRequest' + additionalProperties: false + ChatRoom.SendChatRequest: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterRequest' + - required: + - message + type: object + properties: + message: + type: string + additionalProperties: false + Common.Card: + required: + - rank + - suit + type: object + properties: + rank: + type: integer + format: int32 + suit: + $ref: '#/components/schemas/Common.Suit' + additionalProperties: false + Common.EmptyResponse: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterResponse' + - type: object + additionalProperties: false + Common.PlayerData: + required: + - cardsInHand + - id + - info + - name + - points + type: object + properties: + name: + type: string + points: + type: number + format: double + cardsInHand: + type: integer + format: int32 + id: + type: string + format: uuid + info: + type: object + additionalProperties: + type: string + additionalProperties: false + Common.Suit: + enum: + - Clubs + - Diamonds + - Hearts + - Spades + type: string + Controllers.GameOverviewVm: + required: + - games + - gameType + type: object + properties: + gameType: + type: string + games: + type: array + items: + $ref: '#/components/schemas/Controllers.GameVm' + additionalProperties: false + Controllers.GameVm: + required: + - gameType + - name + - players + - state + type: object + properties: + gameType: + type: string + name: + type: string + state: + $ref: '#/components/schemas/Games.GameState' + players: + type: array + items: + $ref: '#/components/schemas/Common.PlayerData' + additionalProperties: false + Controllers.LoginModel: + type: object + properties: + username: + type: string + nullable: true + password: + type: string + nullable: true + additionalProperties: false + Controllers.ResponseMessage: + type: object + properties: + message: + type: string + nullable: true + additionalProperties: false + Core.GameInfo: + required: + - id + type: object + properties: + id: + type: string + additionalProperties: false + CrazyEights.CardResponse: allOf: - $ref: '#/components/schemas/Protocol.DecksterResponse' - required: @@ -3271,36 +4009,106 @@ components: card: $ref: '#/components/schemas/Common.Card' additionalProperties: false - Bullshit.DiscardPileShuffledNotification: + CrazyEights.CrazyEightsGame: + allOf: + - $ref: '#/components/schemas/Games.GameObject' + - required: + - cardsDrawn + - currentPlayer + - currentPlayerIndex + - currentSuit + - deck + - discardPile + - donePlayers + - initialCardsPerPlayer + - players + - spectators + - stockPile + - topOfPile + type: object + properties: + initialCardsPerPlayer: + type: integer + format: int32 + currentPlayerIndex: + type: integer + format: int32 + cardsDrawn: + type: integer + format: int32 + donePlayers: + type: array + items: + $ref: '#/components/schemas/CrazyEights.CrazyEightsPlayer' + deck: + type: array + items: + $ref: '#/components/schemas/Common.Card' + stockPile: + type: array + items: + $ref: '#/components/schemas/Common.Card' + discardPile: + type: array + items: + $ref: '#/components/schemas/Common.Card' + players: + type: array + items: + $ref: '#/components/schemas/CrazyEights.CrazyEightsPlayer' + spectators: + type: array + items: + $ref: '#/components/schemas/CrazyEights.CrazyEightsSpectator' + newSuit: + $ref: '#/components/schemas/Common.Suit' + topOfPile: + $ref: '#/components/schemas/Common.Card' + currentSuit: + $ref: '#/components/schemas/Common.Suit' + currentPlayer: + $ref: '#/components/schemas/CrazyEights.CrazyEightsPlayer' + additionalProperties: false + CrazyEights.CrazyEightsPlayer: + required: + - cards + - id + - name + type: object + properties: + id: + type: string + format: uuid + name: + type: string + cards: + type: array + items: + $ref: '#/components/schemas/Common.Card' + additionalProperties: false + CrazyEights.CrazyEightsSpectator: + required: + - id + - name + type: object + properties: + id: + type: string + format: uuid + name: + type: string + additionalProperties: false + CrazyEights.DiscardPileShuffledNotification: allOf: - $ref: '#/components/schemas/Protocol.DecksterNotification' - type: object additionalProperties: false - Bullshit.DrawCardRequest: + CrazyEights.DrawCardRequest: allOf: - $ref: '#/components/schemas/Protocol.DecksterRequest' - type: object additionalProperties: false - Bullshit.FalseBullshitCallNotification: - allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' - - required: - - accusedPlayerId - - playerId - - punishmentCardCount - type: object - properties: - playerId: - type: string - format: uuid - accusedPlayerId: - type: string - format: uuid - punishmentCardCount: - type: integer - format: int32 - additionalProperties: false - Bullshit.GameEndedNotification: + CrazyEights.GameEndedNotification: allOf: - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: @@ -3319,7 +4127,7 @@ components: loserName: type: string additionalProperties: false - Bullshit.GameStartedNotification: + CrazyEights.GameStartedNotification: allOf: - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: @@ -3331,9 +4139,9 @@ components: type: string format: uuid playerViewOfGame: - $ref: '#/components/schemas/Bullshit.PlayerViewOfGame' + $ref: '#/components/schemas/CrazyEights.PlayerViewOfGame' additionalProperties: false - Bullshit.ItsPlayersTurnNotification: + CrazyEights.ItsPlayersTurnNotification: allOf: - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: @@ -3344,12 +4152,17 @@ components: type: string format: uuid additionalProperties: false - Bullshit.ItsYourTurnNotification: + CrazyEights.ItsYourTurnNotification: allOf: - $ref: '#/components/schemas/Protocol.DecksterNotification' - - type: object + - required: + - playerViewOfGame + type: object + properties: + playerViewOfGame: + $ref: '#/components/schemas/CrazyEights.PlayerViewOfGame' additionalProperties: false - Bullshit.OtherBullshitPlayer: + CrazyEights.OtherCrazyEightsPlayer: required: - name - numberOfCards @@ -3365,34 +4178,12 @@ components: type: integer format: int32 additionalProperties: false - Bullshit.PassRequest: + CrazyEights.PassRequest: allOf: - $ref: '#/components/schemas/Protocol.DecksterRequest' - type: object additionalProperties: false - Bullshit.PlayerDrewCardNotification: - allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' - - required: - - playerId - type: object - properties: - playerId: - type: string - format: uuid - additionalProperties: false - Bullshit.PlayerIsDoneNotification: - allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' - - required: - - playerId - type: object - properties: - playerId: - type: string - format: uuid - additionalProperties: false - Bullshit.PlayerPassedNotification: + CrazyEights.PlayerDrewCardNotification: allOf: - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: @@ -3403,219 +4194,206 @@ components: type: string format: uuid additionalProperties: false - Bullshit.PlayerPutCardNotification: + CrazyEights.PlayerIsDoneNotification: allOf: - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: - - claimedToBeCard - playerId type: object properties: - playerId: - type: string - format: uuid - claimedToBeCard: - $ref: '#/components/schemas/Common.Card' - additionalProperties: false - Bullshit.PlayerViewOfGame: - required: - - cards - - discardPileCount - - otherPlayers - - stockPileCount - type: object - properties: - cards: - type: array - items: - $ref: '#/components/schemas/Common.Card' - claimedTopOfPile: - $ref: '#/components/schemas/Common.Card' - stockPileCount: - type: integer - format: int32 - discardPileCount: - type: integer - format: int32 - otherPlayers: - type: array - items: - $ref: '#/components/schemas/Bullshit.OtherBullshitPlayer' - additionalProperties: false - Bullshit.PotentialBullshit: - required: - - claimedToBeCard - - playerId - type: object - properties: - playerId: - type: string - format: uuid - claimedToBeCard: - $ref: '#/components/schemas/Common.Card' - additionalProperties: false - Bullshit.PutCardRequest: + playerId: + type: string + format: uuid + additionalProperties: false + CrazyEights.PlayerPassedNotification: allOf: - - $ref: '#/components/schemas/Protocol.DecksterRequest' + - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: - - actualCard - - claimedToBeCard + - playerId type: object properties: - actualCard: - $ref: '#/components/schemas/Common.Card' - claimedToBeCard: - $ref: '#/components/schemas/Common.Card' + playerId: + type: string + format: uuid additionalProperties: false - ChatRoom.ChatNotification: + CrazyEights.PlayerPutCardNotification: allOf: - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: - - message - - sender + - card + - playerId type: object properties: - sender: - type: string - message: + playerId: type: string + format: uuid + card: + $ref: '#/components/schemas/Common.Card' additionalProperties: false - ChatRoom.ChatResponse: + CrazyEights.PlayerPutEightNotification: allOf: - - $ref: '#/components/schemas/Protocol.DecksterResponse' - - type: object + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - required: + - card + - newSuit + - playerId + type: object + properties: + playerId: + type: string + format: uuid + card: + $ref: '#/components/schemas/Common.Card' + newSuit: + $ref: '#/components/schemas/Common.Suit' additionalProperties: false - ChatRoom.ChatRoom: + CrazyEights.PlayerViewOfGame: allOf: - - $ref: '#/components/schemas/Games.GameObject' + - $ref: '#/components/schemas/Protocol.DecksterResponse' - required: - - transcript + - cards + - currentSuit + - discardPileCount + - otherPlayers + - stockPileCount + - topOfPile type: object properties: - transcript: + cards: type: array items: - $ref: '#/components/schemas/ChatRoom.SendChatRequest' + $ref: '#/components/schemas/Common.Card' + topOfPile: + $ref: '#/components/schemas/Common.Card' + currentSuit: + $ref: '#/components/schemas/Common.Suit' + stockPileCount: + type: integer + format: int32 + discardPileCount: + type: integer + format: int32 + otherPlayers: + type: array + items: + $ref: '#/components/schemas/CrazyEights.OtherCrazyEightsPlayer' additionalProperties: false - ChatRoom.SendChatRequest: + CrazyEights.PutCardRequest: allOf: - $ref: '#/components/schemas/Protocol.DecksterRequest' - required: - - message + - card type: object properties: - message: - type: string + card: + $ref: '#/components/schemas/Common.Card' additionalProperties: false - Common.Card: - required: - - rank - - suit - type: object - properties: - rank: - type: integer - format: int32 - suit: - $ref: '#/components/schemas/Common.Suit' - additionalProperties: false - Common.EmptyResponse: + CrazyEights.PutEightRequest: allOf: - - $ref: '#/components/schemas/Protocol.DecksterResponse' - - type: object + - $ref: '#/components/schemas/Protocol.DecksterRequest' + - required: + - card + - newSuit + type: object + properties: + card: + $ref: '#/components/schemas/Common.Card' + newSuit: + $ref: '#/components/schemas/Common.Suit' additionalProperties: false - Common.PlayerData: + Data.DatabaseObject: required: - - cardsInHand - id - - info - - name - - points + - type type: object properties: - name: + type: type: string - points: - type: number - format: double - cardsInHand: - type: integer - format: int32 + readOnly: true id: type: string format: uuid - info: - type: object - additionalProperties: - type: string additionalProperties: false - Common.Suit: - enum: - - Clubs - - Diamonds - - Hearts - - Spades - type: string - Controllers.GameOverviewVm: - required: - - games - - gameType + discriminator: + propertyName: type + mapping: + Games.GameObject: '#/components/schemas/Games.GameObject' + Yaniv.YanivGame: '#/components/schemas/Yaniv.YanivGame' + Uno.UnoGame: '#/components/schemas/Uno.UnoGame' + TexasHoldEm.TexasHoldEmGame: '#/components/schemas/TexasHoldEm.TexasHoldEmGame' + Idiot.IdiotGame: '#/components/schemas/Idiot.IdiotGame' + Hearts.HeartsGame: '#/components/schemas/Hearts.HeartsGame' + Gabong.GabongGame: '#/components/schemas/Gabong.GabongGame' + CrazyEights.CrazyEightsGame: '#/components/schemas/CrazyEights.CrazyEightsGame' + ChatRoom.ChatRoom: '#/components/schemas/ChatRoom.ChatRoom' + Bullshit.BullshitGame: '#/components/schemas/Bullshit.BullshitGame' + Data.HistoricBullshitGame: type: object properties: - gameType: - type: string - games: - type: array - items: - $ref: '#/components/schemas/Controllers.GameVm' + game: + $ref: '#/components/schemas/Bullshit.BullshitGame' additionalProperties: false - Controllers.GameVm: - required: - - gameType - - name - - players - - state + Data.HistoricChatRoom: type: object properties: - gameType: - type: string - name: - type: string - state: - $ref: '#/components/schemas/Games.GameState' - players: - type: array - items: - $ref: '#/components/schemas/Common.PlayerData' + game: + $ref: '#/components/schemas/ChatRoom.ChatRoom' additionalProperties: false - Controllers.LoginModel: + Data.HistoricCrazyEightsGame: type: object properties: - username: - type: string - nullable: true - password: - type: string - nullable: true + game: + $ref: '#/components/schemas/CrazyEights.CrazyEightsGame' additionalProperties: false - Controllers.ResponseMessage: + Data.HistoricGabongGame: type: object properties: - message: - type: string - nullable: true + game: + $ref: '#/components/schemas/Gabong.GabongGame' additionalProperties: false - Core.GameInfo: - required: - - id + Data.HistoricHeartsGame: type: object properties: - id: - type: string + game: + $ref: '#/components/schemas/Hearts.HeartsGame' additionalProperties: false - CrazyEights.CardResponse: + Data.HistoricIdiotGame: + type: object + properties: + game: + $ref: '#/components/schemas/Idiot.IdiotGame' + additionalProperties: false + Data.HistoricTexasHoldEmGame: + type: object + properties: + game: + $ref: '#/components/schemas/TexasHoldEm.TexasHoldEmGame' + additionalProperties: false + Data.HistoricUnoGame: + type: object + properties: + game: + $ref: '#/components/schemas/Uno.UnoGame' + additionalProperties: false + Data.HistoricYanivGame: + type: object + properties: + game: + $ref: '#/components/schemas/Yaniv.YanivGame' + additionalProperties: false + Gabong.ActionResponse: allOf: - $ref: '#/components/schemas/Protocol.DecksterResponse' + - type: object + additionalProperties: false + Gabong.DrawCardRequest: + allOf: + - $ref: '#/components/schemas/Gabong.GabongRequest' + - type: object + additionalProperties: false + Gabong.GabongCardResponse: + allOf: + - $ref: '#/components/schemas/Gabong.GabongResponse' - required: - card type: object @@ -3623,37 +4401,42 @@ components: card: $ref: '#/components/schemas/Common.Card' additionalProperties: false - CrazyEights.CrazyEightsGame: + Gabong.GabongGame: allOf: - $ref: '#/components/schemas/Games.GameObject' - required: - cardsDrawn + - cardsToDraw - currentPlayer - - currentPlayerIndex - currentSuit - deck - discardPile - - donePlayers - - initialCardsPerPlayer + - gabongMasterId + - gameDirection + - isBetweenRounds + - lastPlayMadeByPlayerIndex - players - - spectators - stockPile - topOfPile type: object properties: - initialCardsPerPlayer: + lastPlayMadeByPlayerIndex: type: integer format: int32 - currentPlayerIndex: + cardsToDraw: type: integer format: int32 cardsDrawn: type: integer format: int32 - donePlayers: - type: array - items: - $ref: '#/components/schemas/CrazyEights.CrazyEightsPlayer' + gameDirection: + type: integer + format: int32 + gabongMasterId: + type: string + format: uuid + isBetweenRounds: + type: boolean deck: type: array items: @@ -3669,11 +4452,7 @@ components: players: type: array items: - $ref: '#/components/schemas/CrazyEights.CrazyEightsPlayer' - spectators: - type: array - items: - $ref: '#/components/schemas/CrazyEights.CrazyEightsSpectator' + $ref: '#/components/schemas/Gabong.GabongPlayer' newSuit: $ref: '#/components/schemas/Common.Suit' topOfPile: @@ -3681,13 +4460,47 @@ components: currentSuit: $ref: '#/components/schemas/Common.Suit' currentPlayer: - $ref: '#/components/schemas/CrazyEights.CrazyEightsPlayer' + $ref: '#/components/schemas/Gabong.GabongPlayer' additionalProperties: false - CrazyEights.CrazyEightsPlayer: + Gabong.GabongGameNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - type: object + additionalProperties: false + discriminator: + propertyName: type + mapping: + Gabong.GabongPlayerNotification: '#/components/schemas/Gabong.GabongPlayerNotification' + Gabong.PlayerPutCardNotification: '#/components/schemas/Gabong.PlayerPutCardNotification' + Gabong.PlayerDrewCardNotification: '#/components/schemas/Gabong.PlayerDrewCardNotification' + Gabong.PlayerDrewPenaltyCardNotification: '#/components/schemas/Gabong.PlayerDrewPenaltyCardNotification' + Gabong.GameStartedNotification: '#/components/schemas/Gabong.GameStartedNotification' + Gabong.GameEndedNotification: '#/components/schemas/Gabong.GameEndedNotification' + Gabong.RoundStartedNotification: '#/components/schemas/Gabong.RoundStartedNotification' + Gabong.RoundEndedNotification: '#/components/schemas/Gabong.RoundEndedNotification' + Gabong.PlayerLostTheirTurnNotification: '#/components/schemas/Gabong.PlayerLostTheirTurnNotification' + Gabong.GabongPlay: + enum: + - CardPlayed + - TurnLost + - RoundStarted + type: string + Gabong.GabongPlayer: required: + - bongas - cards + - cardsPlayed + - debtDrawn + - gabongs + - hasWon - id - name + - passes + - penalties + - roundsWon + - score + - shots + - turnsLost type: object properties: id: @@ -3699,35 +4512,93 @@ components: type: array items: $ref: '#/components/schemas/Common.Card' + readOnly: true + score: + type: integer + format: int32 + hasWon: + type: boolean + readOnly: true + penalties: + type: integer + format: int32 + gabongs: + type: integer + format: int32 + bongas: + type: integer + format: int32 + shots: + type: integer + format: int32 + cardsPlayed: + type: integer + format: int32 + debtDrawn: + type: integer + format: int32 + passes: + type: integer + format: int32 + turnsLost: + type: integer + format: int32 + roundsWon: + type: integer + format: int32 additionalProperties: false - CrazyEights.CrazyEightsSpectator: - required: - - id - - name - type: object - properties: - id: - type: string - format: uuid - name: - type: string - additionalProperties: false - CrazyEights.DiscardPileShuffledNotification: + Gabong.GabongPlayerNotification: allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' - - type: object + - $ref: '#/components/schemas/Gabong.GabongGameNotification' + - required: + - playerId + type: object + properties: + playerId: + type: string + format: uuid additionalProperties: false - CrazyEights.DrawCardRequest: + discriminator: + propertyName: type + mapping: + Gabong.PlayerPutCardNotification: '#/components/schemas/Gabong.PlayerPutCardNotification' + Gabong.PlayerDrewCardNotification: '#/components/schemas/Gabong.PlayerDrewCardNotification' + Gabong.PlayerDrewPenaltyCardNotification: '#/components/schemas/Gabong.PlayerDrewPenaltyCardNotification' + Gabong.PlayerLostTheirTurnNotification: '#/components/schemas/Gabong.PlayerLostTheirTurnNotification' + Gabong.GabongRequest: allOf: - $ref: '#/components/schemas/Protocol.DecksterRequest' - type: object additionalProperties: false - CrazyEights.GameEndedNotification: + discriminator: + propertyName: type + mapping: + Gabong.PutCardRequest: '#/components/schemas/Gabong.PutCardRequest' + Gabong.DrawCardRequest: '#/components/schemas/Gabong.DrawCardRequest' + Gabong.PassRequest: '#/components/schemas/Gabong.PassRequest' + Gabong.PlayGabongRequest: '#/components/schemas/Gabong.PlayGabongRequest' + Gabong.PlayBongaRequest: '#/components/schemas/Gabong.PlayBongaRequest' + Gabong.GabongResponse: allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' + - $ref: '#/components/schemas/Protocol.DecksterResponse' + - required: + - cardsAdded + type: object + properties: + cardsAdded: + type: array + items: + $ref: '#/components/schemas/Common.Card' + additionalProperties: false + discriminator: + propertyName: type + mapping: + Gabong.GabongCardResponse: '#/components/schemas/Gabong.GabongCardResponse' + Gabong.PlayerViewOfGame: '#/components/schemas/Gabong.PlayerViewOfGame' + Gabong.GameEndedNotification: + allOf: + - $ref: '#/components/schemas/Gabong.GabongGameNotification' - required: - - loserId - - loserName - players type: object properties: @@ -3735,140 +4606,110 @@ components: type: array items: $ref: '#/components/schemas/Common.PlayerData' - loserId: - type: string - format: uuid - loserName: - type: string additionalProperties: false - CrazyEights.GameStartedNotification: + Gabong.GameStartedNotification: allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' + - $ref: '#/components/schemas/Gabong.GabongGameNotification' - required: - gameId - - playerViewOfGame type: object properties: gameId: type: string format: uuid - playerViewOfGame: - $ref: '#/components/schemas/CrazyEights.PlayerViewOfGame' additionalProperties: false - CrazyEights.ItsPlayersTurnNotification: + Gabong.PassRequest: allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' - - required: - - playerId - type: object - properties: - playerId: - type: string - format: uuid + - $ref: '#/components/schemas/Gabong.GabongRequest' + - type: object additionalProperties: false - CrazyEights.ItsYourTurnNotification: + Gabong.PenalizePlayerForTakingTooLongRequest: allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' - - required: - - playerViewOfGame - type: object - properties: - playerViewOfGame: - $ref: '#/components/schemas/CrazyEights.PlayerViewOfGame' + - $ref: '#/components/schemas/Protocol.DecksterRequest' + - type: object additionalProperties: false - CrazyEights.OtherCrazyEightsPlayer: - required: - - name - - numberOfCards - - playerId - type: object - properties: - playerId: - type: string - format: uuid - name: - type: string - numberOfCards: - type: integer - format: int32 - additionalProperties: false - CrazyEights.PassRequest: + Gabong.PenalizePlayerForTooManyCardsRequest: allOf: - $ref: '#/components/schemas/Protocol.DecksterRequest' - type: object additionalProperties: false - CrazyEights.PlayerDrewCardNotification: + Gabong.PenaltyReason: + enum: + - PlayOutOfTurn + - TookTooLong + - WrongPlay + - WrongGabong + - WrongBonga + - UnpaidDebt + - PassWithoutDrawing + type: string + Gabong.PlayBongaRequest: allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' - - required: - - playerId - type: object - properties: - playerId: - type: string - format: uuid + - $ref: '#/components/schemas/Gabong.GabongRequest' + - type: object additionalProperties: false - CrazyEights.PlayerIsDoneNotification: + Gabong.PlayGabongRequest: allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' - - required: - - playerId - type: object - properties: - playerId: - type: string - format: uuid + - $ref: '#/components/schemas/Gabong.GabongRequest' + - type: object additionalProperties: false - CrazyEights.PlayerPassedNotification: + Gabong.PlayerDrewCardNotification: allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' + - $ref: '#/components/schemas/Gabong.GabongPlayerNotification' + - type: object + additionalProperties: false + Gabong.PlayerDrewPenaltyCardNotification: + allOf: + - $ref: '#/components/schemas/Gabong.GabongPlayerNotification' - required: - - playerId + - penaltyReason type: object properties: - playerId: - type: string - format: uuid + penaltyReason: + $ref: '#/components/schemas/Gabong.PenaltyReason' additionalProperties: false - CrazyEights.PlayerPutCardNotification: + Gabong.PlayerLostTheirTurnNotification: allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' + - $ref: '#/components/schemas/Gabong.GabongPlayerNotification' - required: - - card - - playerId + - lostTurnReason type: object properties: - playerId: - type: string - format: uuid - card: - $ref: '#/components/schemas/Common.Card' + lostTurnReason: + $ref: '#/components/schemas/Gabong.PlayerLostTurnReason' additionalProperties: false - CrazyEights.PlayerPutEightNotification: + Gabong.PlayerLostTurnReason: + enum: + - Passed + - WrongPlay + - TookTooLong + - FinishedDrawingCardDebt + type: string + Gabong.PlayerPutCardNotification: allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' + - $ref: '#/components/schemas/Gabong.GabongPlayerNotification' - required: - card - - newSuit - - playerId type: object properties: - playerId: - type: string - format: uuid card: $ref: '#/components/schemas/Common.Card' newSuit: $ref: '#/components/schemas/Common.Suit' additionalProperties: false - CrazyEights.PlayerViewOfGame: + Gabong.PlayerViewOfGame: allOf: - - $ref: '#/components/schemas/Protocol.DecksterResponse' + - $ref: '#/components/schemas/Gabong.GabongResponse' - required: + - cardDebtToDraw - cards - currentSuit - discardPileCount - - otherPlayers + - lastPlay + - lastPlayMadeByPlayerId + - players + - playersOrder + - roundStarted - stockPileCount - topOfPile type: object @@ -3887,27 +4728,31 @@ components: discardPileCount: type: integer format: int32 - otherPlayers: + roundStarted: + type: boolean + lastPlayMadeByPlayerId: + type: string + format: uuid + lastPlay: + $ref: '#/components/schemas/Gabong.GabongPlay' + players: type: array items: - $ref: '#/components/schemas/CrazyEights.OtherCrazyEightsPlayer' - additionalProperties: false - CrazyEights.PutCardRequest: - allOf: - - $ref: '#/components/schemas/Protocol.DecksterRequest' - - required: - - card - type: object - properties: - card: - $ref: '#/components/schemas/Common.Card' + $ref: '#/components/schemas/Gabong.SlimGabongPlayer' + playersOrder: + type: array + items: + type: string + format: uuid + cardDebtToDraw: + type: integer + format: int32 additionalProperties: false - CrazyEights.PutEightRequest: + Gabong.PutCardRequest: allOf: - - $ref: '#/components/schemas/Protocol.DecksterRequest' + - $ref: '#/components/schemas/Gabong.GabongRequest' - required: - card - - newSuit type: object properties: card: @@ -3915,199 +4760,37 @@ components: newSuit: $ref: '#/components/schemas/Common.Suit' additionalProperties: false - Data.DatabaseObject: - required: - - id - - type - type: object - properties: - type: - type: string - readOnly: true - id: - type: string - format: uuid - additionalProperties: false - discriminator: - propertyName: type - mapping: - Games.GameObject: '#/components/schemas/Games.GameObject' - Yaniv.YanivGame: '#/components/schemas/Yaniv.YanivGame' - Uno.UnoGame: '#/components/schemas/Uno.UnoGame' - TexasHoldEm.TexasHoldEmGame: '#/components/schemas/TexasHoldEm.TexasHoldEmGame' - Idiot.IdiotGame: '#/components/schemas/Idiot.IdiotGame' - Gabong.GabongGame: '#/components/schemas/Gabong.GabongGame' - CrazyEights.CrazyEightsGame: '#/components/schemas/CrazyEights.CrazyEightsGame' - ChatRoom.ChatRoom: '#/components/schemas/ChatRoom.ChatRoom' - Bullshit.BullshitGame: '#/components/schemas/Bullshit.BullshitGame' - Data.HistoricBullshitGame: - type: object - properties: - game: - $ref: '#/components/schemas/Bullshit.BullshitGame' - additionalProperties: false - Data.HistoricChatRoom: - type: object - properties: - game: - $ref: '#/components/schemas/ChatRoom.ChatRoom' - additionalProperties: false - Data.HistoricCrazyEightsGame: - type: object - properties: - game: - $ref: '#/components/schemas/CrazyEights.CrazyEightsGame' - additionalProperties: false - Data.HistoricGabongGame: - type: object - properties: - game: - $ref: '#/components/schemas/Gabong.GabongGame' - additionalProperties: false - Data.HistoricIdiotGame: - type: object - properties: - game: - $ref: '#/components/schemas/Idiot.IdiotGame' - additionalProperties: false - Data.HistoricTexasHoldEmGame: - type: object - properties: - game: - $ref: '#/components/schemas/TexasHoldEm.TexasHoldEmGame' - additionalProperties: false - Data.HistoricUnoGame: - type: object - properties: - game: - $ref: '#/components/schemas/Uno.UnoGame' - additionalProperties: false - Data.HistoricYanivGame: - type: object - properties: - game: - $ref: '#/components/schemas/Yaniv.YanivGame' - additionalProperties: false - Gabong.ActionResponse: - allOf: - - $ref: '#/components/schemas/Protocol.DecksterResponse' - - type: object - additionalProperties: false - Gabong.DrawCardRequest: - allOf: - - $ref: '#/components/schemas/Gabong.GabongRequest' - - type: object - additionalProperties: false - Gabong.GabongCardResponse: - allOf: - - $ref: '#/components/schemas/Gabong.GabongResponse' - - required: - - card - type: object - properties: - card: - $ref: '#/components/schemas/Common.Card' - additionalProperties: false - Gabong.GabongGame: + Gabong.RoundEndedNotification: allOf: - - $ref: '#/components/schemas/Games.GameObject' + - $ref: '#/components/schemas/Gabong.GabongGameNotification' - required: - - cardsDrawn - - cardsToDraw - - currentPlayer - - currentSuit - - deck - - discardPile - - gabongMasterId - - gameDirection - - isBetweenRounds - - lastPlayMadeByPlayerIndex - players - - stockPile - - topOfPile type: object properties: - lastPlayMadeByPlayerIndex: - type: integer - format: int32 - cardsToDraw: - type: integer - format: int32 - cardsDrawn: - type: integer - format: int32 - gameDirection: - type: integer - format: int32 - gabongMasterId: - type: string - format: uuid - isBetweenRounds: - type: boolean - deck: - type: array - items: - $ref: '#/components/schemas/Common.Card' - stockPile: - type: array - items: - $ref: '#/components/schemas/Common.Card' - discardPile: - type: array - items: - $ref: '#/components/schemas/Common.Card' players: type: array items: - $ref: '#/components/schemas/Gabong.GabongPlayer' - newSuit: - $ref: '#/components/schemas/Common.Suit' - topOfPile: - $ref: '#/components/schemas/Common.Card' - currentSuit: - $ref: '#/components/schemas/Common.Suit' - currentPlayer: - $ref: '#/components/schemas/Gabong.GabongPlayer' + $ref: '#/components/schemas/Common.PlayerData' additionalProperties: false - Gabong.GabongGameNotification: + Gabong.RoundStartedNotification: allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' - - type: object - additionalProperties: false - discriminator: - propertyName: type - mapping: - Gabong.GabongPlayerNotification: '#/components/schemas/Gabong.GabongPlayerNotification' - Gabong.PlayerPutCardNotification: '#/components/schemas/Gabong.PlayerPutCardNotification' - Gabong.PlayerDrewCardNotification: '#/components/schemas/Gabong.PlayerDrewCardNotification' - Gabong.PlayerDrewPenaltyCardNotification: '#/components/schemas/Gabong.PlayerDrewPenaltyCardNotification' - Gabong.GameStartedNotification: '#/components/schemas/Gabong.GameStartedNotification' - Gabong.GameEndedNotification: '#/components/schemas/Gabong.GameEndedNotification' - Gabong.RoundStartedNotification: '#/components/schemas/Gabong.RoundStartedNotification' - Gabong.RoundEndedNotification: '#/components/schemas/Gabong.RoundEndedNotification' - Gabong.PlayerLostTheirTurnNotification: '#/components/schemas/Gabong.PlayerLostTheirTurnNotification' - Gabong.GabongPlay: - enum: - - CardPlayed - - TurnLost - - RoundStarted - type: string - Gabong.GabongPlayer: + - $ref: '#/components/schemas/Gabong.GabongGameNotification' + - required: + - playerViewOfGame + - startingPlayerId + type: object + properties: + playerViewOfGame: + $ref: '#/components/schemas/Gabong.PlayerViewOfGame' + startingPlayerId: + type: string + format: uuid + additionalProperties: false + Gabong.SlimGabongPlayer: required: - - bongas - - cards - - cardsPlayed - - debtDrawn - - gabongs - - hasWon - id - name - - passes - - penalties - - roundsWon - - score - - shots - - turnsLost + - numberOfCards type: object properties: id: @@ -4115,382 +4798,476 @@ components: format: uuid name: type: string - cards: - type: array - items: - $ref: '#/components/schemas/Common.Card' - readOnly: true - score: - type: integer - format: int32 - hasWon: - type: boolean - readOnly: true - penalties: - type: integer - format: int32 - gabongs: - type: integer - format: int32 - bongas: - type: integer - format: int32 - shots: - type: integer - format: int32 - cardsPlayed: - type: integer - format: int32 - debtDrawn: - type: integer - format: int32 - passes: - type: integer - format: int32 - turnsLost: - type: integer - format: int32 - roundsWon: + numberOfCards: type: integer format: int32 additionalProperties: false - Gabong.GabongPlayerNotification: + Games.GameObject: allOf: - - $ref: '#/components/schemas/Gabong.GabongGameNotification' + - $ref: '#/components/schemas/Data.DatabaseObject' - required: - - playerId + - name + - seed + - startedTime + - state + - version type: object properties: - playerId: + name: type: string - format: uuid + startedTime: + type: string + format: date-time + state: + $ref: '#/components/schemas/Games.GameState' + version: + type: integer + format: int32 + seed: + type: integer + format: int32 additionalProperties: false discriminator: propertyName: type mapping: - Gabong.PlayerPutCardNotification: '#/components/schemas/Gabong.PlayerPutCardNotification' - Gabong.PlayerDrewCardNotification: '#/components/schemas/Gabong.PlayerDrewCardNotification' - Gabong.PlayerDrewPenaltyCardNotification: '#/components/schemas/Gabong.PlayerDrewPenaltyCardNotification' - Gabong.PlayerLostTheirTurnNotification: '#/components/schemas/Gabong.PlayerLostTheirTurnNotification' - Gabong.GabongRequest: + Yaniv.YanivGame: '#/components/schemas/Yaniv.YanivGame' + Uno.UnoGame: '#/components/schemas/Uno.UnoGame' + TexasHoldEm.TexasHoldEmGame: '#/components/schemas/TexasHoldEm.TexasHoldEmGame' + Idiot.IdiotGame: '#/components/schemas/Idiot.IdiotGame' + Hearts.HeartsGame: '#/components/schemas/Hearts.HeartsGame' + Gabong.GabongGame: '#/components/schemas/Gabong.GabongGame' + CrazyEights.CrazyEightsGame: '#/components/schemas/CrazyEights.CrazyEightsGame' + ChatRoom.ChatRoom: '#/components/schemas/ChatRoom.ChatRoom' + Bullshit.BullshitGame: '#/components/schemas/Bullshit.BullshitGame' + Games.GameState: + enum: + - Waiting + - Running + - Finished + - RoundFinished + type: string + Handshake.ConnectFailureMessage: allOf: - - $ref: '#/components/schemas/Protocol.DecksterRequest' + - $ref: '#/components/schemas/Handshake.ConnectMessage' + - required: + - errorMessage + type: object + properties: + errorMessage: + type: string + additionalProperties: false + Handshake.ConnectMessage: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterMessage' - type: object additionalProperties: false discriminator: propertyName: type mapping: - Gabong.PutCardRequest: '#/components/schemas/Gabong.PutCardRequest' - Gabong.DrawCardRequest: '#/components/schemas/Gabong.DrawCardRequest' - Gabong.PassRequest: '#/components/schemas/Gabong.PassRequest' - Gabong.PlayGabongRequest: '#/components/schemas/Gabong.PlayGabongRequest' - Gabong.PlayBongaRequest: '#/components/schemas/Gabong.PlayBongaRequest' - Gabong.GabongResponse: + Handshake.HelloSuccessMessage: '#/components/schemas/Handshake.HelloSuccessMessage' + Handshake.ConnectSuccessMessage: '#/components/schemas/Handshake.ConnectSuccessMessage' + Handshake.ConnectFailureMessage: '#/components/schemas/Handshake.ConnectFailureMessage' + Handshake.ConnectSuccessMessage: allOf: - - $ref: '#/components/schemas/Protocol.DecksterResponse' + - $ref: '#/components/schemas/Handshake.ConnectMessage' + - type: object + additionalProperties: false + Handshake.HelloSuccessMessage: + allOf: + - $ref: '#/components/schemas/Handshake.ConnectMessage' - required: - - cardsAdded + - connectionId + - player type: object properties: - cardsAdded: + player: + $ref: '#/components/schemas/Common.PlayerData' + connectionId: + type: string + format: uuid + additionalProperties: false + Hearts.AllPlayersPassedNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - required: + - receivedCards + type: object + properties: + receivedCards: type: array items: $ref: '#/components/schemas/Common.Card' additionalProperties: false - discriminator: - propertyName: type - mapping: - Gabong.GabongCardResponse: '#/components/schemas/Gabong.GabongCardResponse' - Gabong.PlayerViewOfGame: '#/components/schemas/Gabong.PlayerViewOfGame' - Gabong.GameEndedNotification: + Hearts.CardPlay: + required: + - card + - playerId + - playerName + type: object + properties: + playerId: + type: string + format: uuid + playerName: + type: string + card: + $ref: '#/components/schemas/Common.Card' + additionalProperties: false + Hearts.GameEndedNotification: allOf: - - $ref: '#/components/schemas/Gabong.GabongGameNotification' + - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: - - players + - finalScores + - winnerId + - winnerName type: object properties: - players: + finalScores: type: array items: - $ref: '#/components/schemas/Common.PlayerData' + $ref: '#/components/schemas/Hearts.PlayerScore' + winnerId: + type: string + format: uuid + winnerName: + type: string additionalProperties: false - Gabong.GameStartedNotification: + Hearts.GamePhase: + enum: + - Passing + - Playing + type: string + Hearts.GameStartedNotification: allOf: - - $ref: '#/components/schemas/Gabong.GabongGameNotification' + - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: - gameId + - playerViewOfGame type: object properties: gameId: type: string format: uuid + playerViewOfGame: + $ref: '#/components/schemas/Hearts.PlayerViewOfGame' additionalProperties: false - Gabong.PassRequest: - allOf: - - $ref: '#/components/schemas/Gabong.GabongRequest' - - type: object - additionalProperties: false - Gabong.PenalizePlayerForTakingTooLongRequest: - allOf: - - $ref: '#/components/schemas/Protocol.DecksterRequest' - - type: object - additionalProperties: false - Gabong.PenalizePlayerForTooManyCardsRequest: - allOf: - - $ref: '#/components/schemas/Protocol.DecksterRequest' - - type: object - additionalProperties: false - Gabong.PenaltyReason: - enum: - - PlayOutOfTurn - - TookTooLong - - WrongPlay - - WrongGabong - - WrongBonga - - UnpaidDebt - - PassWithoutDrawing - type: string - Gabong.PlayBongaRequest: - allOf: - - $ref: '#/components/schemas/Gabong.GabongRequest' - - type: object - additionalProperties: false - Gabong.PlayGabongRequest: + Hearts.HeartsAreBrokenNotification: allOf: - - $ref: '#/components/schemas/Gabong.GabongRequest' + - $ref: '#/components/schemas/Protocol.DecksterNotification' - type: object additionalProperties: false - Gabong.PlayerDrewCardNotification: + Hearts.HeartsGame: allOf: - - $ref: '#/components/schemas/Gabong.GabongPlayerNotification' - - type: object + - $ref: '#/components/schemas/Games.GameObject' + - required: + - currentPassDirection + - currentPlayer + - currentPlayerIndex + - currentTrick + - deck + - heartsAreBroken + - isFirstTrick + - phase + - players + - roundNumber + type: object + properties: + deck: + type: array + items: + $ref: '#/components/schemas/Common.Card' + players: + type: array + items: + $ref: '#/components/schemas/Hearts.HeartsPlayer' + currentPlayerIndex: + type: integer + format: int32 + roundNumber: + type: integer + format: int32 + heartsAreBroken: + type: boolean + currentTrick: + type: array + items: + $ref: '#/components/schemas/Hearts.CardPlay' + leadSuit: + $ref: '#/components/schemas/Common.Suit' + isFirstTrick: + type: boolean + phase: + $ref: '#/components/schemas/Hearts.GamePhase' + currentPlayer: + $ref: '#/components/schemas/Hearts.HeartsPlayer' + currentPassDirection: + $ref: '#/components/schemas/Hearts.PassDirection' additionalProperties: false - Gabong.PlayerDrewPenaltyCardNotification: + Hearts.HeartsPlayer: + required: + - cards + - cardsToPass + - hasPassed + - id + - name + - roundScore + - totalScore + type: object + properties: + id: + type: string + format: uuid + name: + type: string + cards: + type: array + items: + $ref: '#/components/schemas/Common.Card' + cardsToPass: + type: array + items: + $ref: '#/components/schemas/Common.Card' + hasPassed: + type: boolean + roundScore: + type: integer + format: int32 + totalScore: + type: integer + format: int32 + playedCard: + $ref: '#/components/schemas/Common.Card' + additionalProperties: false + Hearts.ItsPlayersTurnNotification: allOf: - - $ref: '#/components/schemas/Gabong.GabongPlayerNotification' + - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: - - penaltyReason + - playerId type: object properties: - penaltyReason: - $ref: '#/components/schemas/Gabong.PenaltyReason' + playerId: + type: string + format: uuid additionalProperties: false - Gabong.PlayerLostTheirTurnNotification: + Hearts.ItsYourTurnNotification: allOf: - - $ref: '#/components/schemas/Gabong.GabongPlayerNotification' + - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: - - lostTurnReason + - playerViewOfGame type: object properties: - lostTurnReason: - $ref: '#/components/schemas/Gabong.PlayerLostTurnReason' + playerViewOfGame: + $ref: '#/components/schemas/Hearts.PlayerViewOfGame' additionalProperties: false - Gabong.PlayerLostTurnReason: - enum: - - Passed - - WrongPlay - - TookTooLong - - FinishedDrawingCardDebt - type: string - Gabong.PlayerPutCardNotification: + Hearts.OtherHeartsPlayer: + required: + - name + - numberOfCards + - playerId + - roundScore + - totalScore + type: object + properties: + playerId: + type: string + format: uuid + name: + type: string + numberOfCards: + type: integer + format: int32 + totalScore: + type: integer + format: int32 + roundScore: + type: integer + format: int32 + playedCard: + $ref: '#/components/schemas/Common.Card' + additionalProperties: false + Hearts.PassCardsRequest: allOf: - - $ref: '#/components/schemas/Gabong.GabongPlayerNotification' + - $ref: '#/components/schemas/Protocol.DecksterRequest' - required: - - card + - cards type: object properties: - card: - $ref: '#/components/schemas/Common.Card' - newSuit: - $ref: '#/components/schemas/Common.Suit' + cards: + type: array + items: + $ref: '#/components/schemas/Common.Card' additionalProperties: false - Gabong.PlayerViewOfGame: + Hearts.PassCardsResponse: allOf: - - $ref: '#/components/schemas/Gabong.GabongResponse' + - $ref: '#/components/schemas/Protocol.DecksterResponse' - required: - - cardDebtToDraw - - cards - - currentSuit - - discardPileCount - - lastPlay - - lastPlayMadeByPlayerId - - players - - playersOrder - - roundStarted - - stockPileCount - - topOfPile + - receivedCards type: object properties: - cards: + receivedCards: type: array items: $ref: '#/components/schemas/Common.Card' - topOfPile: - $ref: '#/components/schemas/Common.Card' - currentSuit: - $ref: '#/components/schemas/Common.Suit' - stockPileCount: - type: integer - format: int32 - discardPileCount: - type: integer - format: int32 - roundStarted: - type: boolean - lastPlayMadeByPlayerId: - type: string - format: uuid - lastPlay: - $ref: '#/components/schemas/Gabong.GabongPlay' - players: - type: array - items: - $ref: '#/components/schemas/Gabong.SlimGabongPlayer' - playersOrder: - type: array - items: - type: string - format: uuid - cardDebtToDraw: - type: integer - format: int32 additionalProperties: false - Gabong.PutCardRequest: + Hearts.PassDirection: + enum: + - None + - Left + - Right + - Across + type: string + Hearts.PassingPhaseStartedNotification: allOf: - - $ref: '#/components/schemas/Gabong.GabongRequest' + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - required: + - passDirection + type: object + properties: + passDirection: + $ref: '#/components/schemas/Hearts.PassDirection' + additionalProperties: false + Hearts.PlayCardRequest: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterRequest' - required: - card type: object properties: card: $ref: '#/components/schemas/Common.Card' - newSuit: - $ref: '#/components/schemas/Common.Suit' additionalProperties: false - Gabong.RoundEndedNotification: + Hearts.PlayerPassedCardsNotification: allOf: - - $ref: '#/components/schemas/Gabong.GabongGameNotification' + - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: - - players + - playerId type: object properties: - players: - type: array - items: - $ref: '#/components/schemas/Common.PlayerData' + playerId: + type: string + format: uuid additionalProperties: false - Gabong.RoundStartedNotification: + Hearts.PlayerPlayedCardNotification: allOf: - - $ref: '#/components/schemas/Gabong.GabongGameNotification' + - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: - - playerViewOfGame - - startingPlayerId + - card + - playerId type: object properties: - playerViewOfGame: - $ref: '#/components/schemas/Gabong.PlayerViewOfGame' - startingPlayerId: + playerId: type: string format: uuid + card: + $ref: '#/components/schemas/Common.Card' additionalProperties: false - Gabong.SlimGabongPlayer: + Hearts.PlayerScore: required: - - id - - name - - numberOfCards + - playerId + - playerName + - roundScore + - totalScore type: object properties: - id: + playerId: type: string format: uuid - name: + playerName: type: string - numberOfCards: + roundScore: + type: integer + format: int32 + totalScore: type: integer format: int32 additionalProperties: false - Games.GameObject: + Hearts.PlayerViewOfGame: allOf: - - $ref: '#/components/schemas/Data.DatabaseObject' + - $ref: '#/components/schemas/Protocol.DecksterResponse' - required: - - name - - seed - - startedTime - - state - - version + - cards + - currentTrick + - hasPassed + - heartsAreBroken + - isMyTurn + - otherPlayers + - passDirection + - roundNumber + - roundScore + - totalScore type: object properties: - name: - type: string - startedTime: - type: string - format: date-time - state: - $ref: '#/components/schemas/Games.GameState' - version: + cards: + type: array + items: + $ref: '#/components/schemas/Common.Card' + otherPlayers: + type: array + items: + $ref: '#/components/schemas/Hearts.OtherHeartsPlayer' + roundNumber: type: integer format: int32 - seed: + passDirection: + $ref: '#/components/schemas/Hearts.PassDirection' + hasPassed: + type: boolean + currentTrick: + type: array + items: + $ref: '#/components/schemas/Hearts.CardPlay' + totalScore: type: integer format: int32 + roundScore: + type: integer + format: int32 + heartsAreBroken: + type: boolean + isMyTurn: + type: boolean additionalProperties: false - discriminator: - propertyName: type - mapping: - Yaniv.YanivGame: '#/components/schemas/Yaniv.YanivGame' - Uno.UnoGame: '#/components/schemas/Uno.UnoGame' - TexasHoldEm.TexasHoldEmGame: '#/components/schemas/TexasHoldEm.TexasHoldEmGame' - Idiot.IdiotGame: '#/components/schemas/Idiot.IdiotGame' - Gabong.GabongGame: '#/components/schemas/Gabong.GabongGame' - CrazyEights.CrazyEightsGame: '#/components/schemas/CrazyEights.CrazyEightsGame' - ChatRoom.ChatRoom: '#/components/schemas/ChatRoom.ChatRoom' - Bullshit.BullshitGame: '#/components/schemas/Bullshit.BullshitGame' - Games.GameState: - enum: - - Waiting - - Running - - Finished - - RoundFinished - type: string - Handshake.ConnectFailureMessage: + Hearts.RoundEndedNotification: allOf: - - $ref: '#/components/schemas/Handshake.ConnectMessage' + - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: - - errorMessage + - scores type: object properties: - errorMessage: + scores: + type: array + items: + $ref: '#/components/schemas/Hearts.PlayerScore' + moonShooterId: type: string + format: uuid + nullable: true + moonShooterName: + type: string + nullable: true additionalProperties: false - Handshake.ConnectMessage: - allOf: - - $ref: '#/components/schemas/Protocol.DecksterMessage' - - type: object - additionalProperties: false - discriminator: - propertyName: type - mapping: - Handshake.HelloSuccessMessage: '#/components/schemas/Handshake.HelloSuccessMessage' - Handshake.ConnectSuccessMessage: '#/components/schemas/Handshake.ConnectSuccessMessage' - Handshake.ConnectFailureMessage: '#/components/schemas/Handshake.ConnectFailureMessage' - Handshake.ConnectSuccessMessage: - allOf: - - $ref: '#/components/schemas/Handshake.ConnectMessage' - - type: object - additionalProperties: false - Handshake.HelloSuccessMessage: + Hearts.TrickCompletedNotification: allOf: - - $ref: '#/components/schemas/Handshake.ConnectMessage' + - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: - - connectionId - - player + - points + - trickCards + - winnerId + - winnerName type: object properties: - player: - $ref: '#/components/schemas/Common.PlayerData' - connectionId: + winnerId: type: string format: uuid + winnerName: + type: string + trickCards: + type: array + items: + $ref: '#/components/schemas/Hearts.CardPlay' + points: + type: integer + format: int32 additionalProperties: false Idiot.DiscardPileFlushedNotification: allOf: @@ -5047,6 +5824,21 @@ components: Idiot.GameStartedNotification: '#/components/schemas/Idiot.GameStartedNotification' Idiot.GameEndedNotification: '#/components/schemas/Idiot.GameEndedNotification' Idiot.ItsTimeToSwapCardsNotification: '#/components/schemas/Idiot.ItsTimeToSwapCardsNotification' + Hearts.PassCardsRequest: '#/components/schemas/Hearts.PassCardsRequest' + Hearts.PlayCardRequest: '#/components/schemas/Hearts.PlayCardRequest' + Hearts.PassCardsResponse: '#/components/schemas/Hearts.PassCardsResponse' + Hearts.GameStartedNotification: '#/components/schemas/Hearts.GameStartedNotification' + Hearts.PassingPhaseStartedNotification: '#/components/schemas/Hearts.PassingPhaseStartedNotification' + Hearts.AllPlayersPassedNotification: '#/components/schemas/Hearts.AllPlayersPassedNotification' + Hearts.PlayerPassedCardsNotification: '#/components/schemas/Hearts.PlayerPassedCardsNotification' + Hearts.ItsYourTurnNotification: '#/components/schemas/Hearts.ItsYourTurnNotification' + Hearts.ItsPlayersTurnNotification: '#/components/schemas/Hearts.ItsPlayersTurnNotification' + Hearts.PlayerPlayedCardNotification: '#/components/schemas/Hearts.PlayerPlayedCardNotification' + Hearts.TrickCompletedNotification: '#/components/schemas/Hearts.TrickCompletedNotification' + Hearts.RoundEndedNotification: '#/components/schemas/Hearts.RoundEndedNotification' + Hearts.GameEndedNotification: '#/components/schemas/Hearts.GameEndedNotification' + Hearts.HeartsAreBrokenNotification: '#/components/schemas/Hearts.HeartsAreBrokenNotification' + Hearts.PlayerViewOfGame: '#/components/schemas/Hearts.PlayerViewOfGame' Gabong.GabongGameNotification: '#/components/schemas/Gabong.GabongGameNotification' Gabong.GabongPlayerNotification: '#/components/schemas/Gabong.GabongPlayerNotification' Gabong.PlayerPutCardNotification: '#/components/schemas/Gabong.PlayerPutCardNotification' @@ -5158,6 +5950,17 @@ components: Idiot.GameStartedNotification: '#/components/schemas/Idiot.GameStartedNotification' Idiot.GameEndedNotification: '#/components/schemas/Idiot.GameEndedNotification' Idiot.ItsTimeToSwapCardsNotification: '#/components/schemas/Idiot.ItsTimeToSwapCardsNotification' + Hearts.GameStartedNotification: '#/components/schemas/Hearts.GameStartedNotification' + Hearts.PassingPhaseStartedNotification: '#/components/schemas/Hearts.PassingPhaseStartedNotification' + Hearts.AllPlayersPassedNotification: '#/components/schemas/Hearts.AllPlayersPassedNotification' + Hearts.PlayerPassedCardsNotification: '#/components/schemas/Hearts.PlayerPassedCardsNotification' + Hearts.ItsYourTurnNotification: '#/components/schemas/Hearts.ItsYourTurnNotification' + Hearts.ItsPlayersTurnNotification: '#/components/schemas/Hearts.ItsPlayersTurnNotification' + Hearts.PlayerPlayedCardNotification: '#/components/schemas/Hearts.PlayerPlayedCardNotification' + Hearts.TrickCompletedNotification: '#/components/schemas/Hearts.TrickCompletedNotification' + Hearts.RoundEndedNotification: '#/components/schemas/Hearts.RoundEndedNotification' + Hearts.GameEndedNotification: '#/components/schemas/Hearts.GameEndedNotification' + Hearts.HeartsAreBrokenNotification: '#/components/schemas/Hearts.HeartsAreBrokenNotification' Gabong.GabongGameNotification: '#/components/schemas/Gabong.GabongGameNotification' Gabong.GabongPlayerNotification: '#/components/schemas/Gabong.GabongPlayerNotification' Gabong.PlayerPutCardNotification: '#/components/schemas/Gabong.PlayerPutCardNotification' @@ -5223,6 +6026,8 @@ components: Idiot.DrawCardsRequest: '#/components/schemas/Idiot.DrawCardsRequest' Idiot.PullInDiscardPileRequest: '#/components/schemas/Idiot.PullInDiscardPileRequest' Idiot.PutChanceCardRequest: '#/components/schemas/Idiot.PutChanceCardRequest' + Hearts.PassCardsRequest: '#/components/schemas/Hearts.PassCardsRequest' + Hearts.PlayCardRequest: '#/components/schemas/Hearts.PlayCardRequest' Gabong.PenalizePlayerForTakingTooLongRequest: '#/components/schemas/Gabong.PenalizePlayerForTakingTooLongRequest' Gabong.PenalizePlayerForTooManyCardsRequest: '#/components/schemas/Gabong.PenalizePlayerForTooManyCardsRequest' Gabong.GabongRequest: '#/components/schemas/Gabong.GabongRequest' @@ -5265,6 +6070,8 @@ components: Idiot.PullInResponse: '#/components/schemas/Idiot.PullInResponse' Idiot.DrawCardsResponse: '#/components/schemas/Idiot.DrawCardsResponse' Idiot.PutBlindCardResponse: '#/components/schemas/Idiot.PutBlindCardResponse' + Hearts.PassCardsResponse: '#/components/schemas/Hearts.PassCardsResponse' + Hearts.PlayerViewOfGame: '#/components/schemas/Hearts.PlayerViewOfGame' Gabong.GabongResponse: '#/components/schemas/Gabong.GabongResponse' Gabong.GabongCardResponse: '#/components/schemas/Gabong.GabongCardResponse' Gabong.ActionResponse: '#/components/schemas/Gabong.ActionResponse' diff --git a/generated/deckster.opeanpi.json b/generated/deckster.opeanpi.json index e6889130..f4412858 100644 --- a/generated/deckster.opeanpi.json +++ b/generated/deckster.opeanpi.json @@ -1,5 +1,5 @@ { - "openapi": "3.0.1", + "openapi": "3.0.4", "info": { "title": "Deckster", "description": "Deckster", @@ -91,6 +91,21 @@ "Idiot.GameStartedNotification": "#/components/schemas/Idiot.GameStartedNotification", "Idiot.GameEndedNotification": "#/components/schemas/Idiot.GameEndedNotification", "Idiot.ItsTimeToSwapCardsNotification": "#/components/schemas/Idiot.ItsTimeToSwapCardsNotification", + "Hearts.PassCardsRequest": "#/components/schemas/Hearts.PassCardsRequest", + "Hearts.PlayCardRequest": "#/components/schemas/Hearts.PlayCardRequest", + "Hearts.PassCardsResponse": "#/components/schemas/Hearts.PassCardsResponse", + "Hearts.GameStartedNotification": "#/components/schemas/Hearts.GameStartedNotification", + "Hearts.PlayerViewOfGame": "#/components/schemas/Hearts.PlayerViewOfGame", + "Hearts.PassingPhaseStartedNotification": "#/components/schemas/Hearts.PassingPhaseStartedNotification", + "Hearts.AllPlayersPassedNotification": "#/components/schemas/Hearts.AllPlayersPassedNotification", + "Hearts.PlayerPassedCardsNotification": "#/components/schemas/Hearts.PlayerPassedCardsNotification", + "Hearts.ItsYourTurnNotification": "#/components/schemas/Hearts.ItsYourTurnNotification", + "Hearts.ItsPlayersTurnNotification": "#/components/schemas/Hearts.ItsPlayersTurnNotification", + "Hearts.PlayerPlayedCardNotification": "#/components/schemas/Hearts.PlayerPlayedCardNotification", + "Hearts.TrickCompletedNotification": "#/components/schemas/Hearts.TrickCompletedNotification", + "Hearts.RoundEndedNotification": "#/components/schemas/Hearts.RoundEndedNotification", + "Hearts.GameEndedNotification": "#/components/schemas/Hearts.GameEndedNotification", + "Hearts.HeartsAreBrokenNotification": "#/components/schemas/Hearts.HeartsAreBrokenNotification", "Gabong.PenalizePlayerForTakingTooLongRequest": "#/components/schemas/Gabong.PenalizePlayerForTakingTooLongRequest", "Gabong.PenalizePlayerForTooManyCardsRequest": "#/components/schemas/Gabong.PenalizePlayerForTooManyCardsRequest", "Gabong.ActionResponse": "#/components/schemas/Gabong.ActionResponse", @@ -191,6 +206,8 @@ "Idiot.DrawCardsRequest": "#/components/schemas/Idiot.DrawCardsRequest", "Idiot.PullInDiscardPileRequest": "#/components/schemas/Idiot.PullInDiscardPileRequest", "Idiot.PutChanceCardRequest": "#/components/schemas/Idiot.PutChanceCardRequest", + "Hearts.PassCardsRequest": "#/components/schemas/Hearts.PassCardsRequest", + "Hearts.PlayCardRequest": "#/components/schemas/Hearts.PlayCardRequest", "Gabong.PenalizePlayerForTakingTooLongRequest": "#/components/schemas/Gabong.PenalizePlayerForTakingTooLongRequest", "Gabong.PenalizePlayerForTooManyCardsRequest": "#/components/schemas/Gabong.PenalizePlayerForTooManyCardsRequest", "CrazyEights.PutCardRequest": "#/components/schemas/CrazyEights.PutCardRequest", @@ -264,6 +281,17 @@ "Idiot.GameStartedNotification": "#/components/schemas/Idiot.GameStartedNotification", "Idiot.GameEndedNotification": "#/components/schemas/Idiot.GameEndedNotification", "Idiot.ItsTimeToSwapCardsNotification": "#/components/schemas/Idiot.ItsTimeToSwapCardsNotification", + "Hearts.GameStartedNotification": "#/components/schemas/Hearts.GameStartedNotification", + "Hearts.PassingPhaseStartedNotification": "#/components/schemas/Hearts.PassingPhaseStartedNotification", + "Hearts.AllPlayersPassedNotification": "#/components/schemas/Hearts.AllPlayersPassedNotification", + "Hearts.PlayerPassedCardsNotification": "#/components/schemas/Hearts.PlayerPassedCardsNotification", + "Hearts.ItsYourTurnNotification": "#/components/schemas/Hearts.ItsYourTurnNotification", + "Hearts.ItsPlayersTurnNotification": "#/components/schemas/Hearts.ItsPlayersTurnNotification", + "Hearts.PlayerPlayedCardNotification": "#/components/schemas/Hearts.PlayerPlayedCardNotification", + "Hearts.TrickCompletedNotification": "#/components/schemas/Hearts.TrickCompletedNotification", + "Hearts.RoundEndedNotification": "#/components/schemas/Hearts.RoundEndedNotification", + "Hearts.GameEndedNotification": "#/components/schemas/Hearts.GameEndedNotification", + "Hearts.HeartsAreBrokenNotification": "#/components/schemas/Hearts.HeartsAreBrokenNotification", "CrazyEights.PlayerPutCardNotification": "#/components/schemas/CrazyEights.PlayerPutCardNotification", "CrazyEights.PlayerPutEightNotification": "#/components/schemas/CrazyEights.PlayerPutEightNotification", "CrazyEights.PlayerDrewCardNotification": "#/components/schemas/CrazyEights.PlayerDrewCardNotification", @@ -328,6 +356,8 @@ "Idiot.PullInResponse": "#/components/schemas/Idiot.PullInResponse", "Idiot.DrawCardsResponse": "#/components/schemas/Idiot.DrawCardsResponse", "Idiot.PutBlindCardResponse": "#/components/schemas/Idiot.PutBlindCardResponse", + "Hearts.PassCardsResponse": "#/components/schemas/Hearts.PassCardsResponse", + "Hearts.PlayerViewOfGame": "#/components/schemas/Hearts.PlayerViewOfGame", "Gabong.ActionResponse": "#/components/schemas/Gabong.ActionResponse", "CrazyEights.CardResponse": "#/components/schemas/CrazyEights.CardResponse", "CrazyEights.PlayerViewOfGame": "#/components/schemas/CrazyEights.PlayerViewOfGame", @@ -2375,6 +2405,539 @@ } } }, + "Hearts.PassCardsRequest": { + "type": "object", + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterRequest" + }, + { + "type": "object", + "properties": { + "cards": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Common.Card" + } + } + } + } + ] + }, + "Hearts.PlayCardRequest": { + "type": "object", + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterRequest" + }, + { + "type": "object", + "properties": { + "card": { + "type": "object", + "properties": { + "rank": { + "type": "integer", + "format": "int32" + }, + "suit": { + "type": "string" + } + } + } + } + } + ] + }, + "Hearts.PassCardsResponse": { + "type": "object", + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterResponse" + }, + { + "type": "object", + "properties": { + "receivedCards": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Common.Card" + } + } + } + } + ] + }, + "Hearts.GameStartedNotification": { + "type": "object", + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterNotification" + }, + { + "type": "object", + "properties": { + "gameId": { + "type": "string", + "format": "uuid" + }, + "playerViewOfGame": { + "type": "object", + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterResponse" + }, + { + "type": "object", + "properties": { + "cards": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Common.Card" + } + }, + "otherPlayers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Hearts.OtherHeartsPlayer" + } + }, + "roundNumber": { + "type": "integer", + "format": "int32" + }, + "passDirection": { + "type": "string" + }, + "hasPassed": { + "type": "boolean" + }, + "currentTrick": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Hearts.CardPlay" + } + }, + "totalScore": { + "type": "integer", + "format": "int32" + }, + "roundScore": { + "type": "integer", + "format": "int32" + }, + "heartsAreBroken": { + "type": "boolean" + }, + "isMyTurn": { + "type": "boolean" + } + } + } + ] + } + } + } + ] + }, + "Hearts.PlayerViewOfGame": { + "type": "object", + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterResponse" + }, + { + "type": "object", + "properties": { + "cards": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Common.Card" + } + }, + "otherPlayers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Hearts.OtherHeartsPlayer" + } + }, + "roundNumber": { + "type": "integer", + "format": "int32" + }, + "passDirection": { + "type": "string" + }, + "hasPassed": { + "type": "boolean" + }, + "currentTrick": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Hearts.CardPlay" + } + }, + "totalScore": { + "type": "integer", + "format": "int32" + }, + "roundScore": { + "type": "integer", + "format": "int32" + }, + "heartsAreBroken": { + "type": "boolean" + }, + "isMyTurn": { + "type": "boolean" + } + } + } + ] + }, + "Hearts.OtherHeartsPlayer": { + "type": "object", + "properties": { + "playerId": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "numberOfCards": { + "type": "integer", + "format": "int32" + }, + "totalScore": { + "type": "integer", + "format": "int32" + }, + "roundScore": { + "type": "integer", + "format": "int32" + }, + "playedCard": { + "type": "object", + "properties": { + "rank": { + "type": "integer", + "format": "int32" + }, + "suit": { + "type": "string" + } + }, + "nullable": true + } + } + }, + "Hearts.CardPlay": { + "type": "object", + "properties": { + "playerId": { + "type": "string", + "format": "uuid" + }, + "playerName": { + "type": "string" + }, + "card": { + "type": "object", + "properties": { + "rank": { + "type": "integer", + "format": "int32" + }, + "suit": { + "type": "string" + } + }, + "nullable": true + } + } + }, + "Hearts.PassingPhaseStartedNotification": { + "type": "object", + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterNotification" + }, + { + "type": "object", + "properties": { + "passDirection": { + "type": "string" + } + } + } + ] + }, + "Hearts.AllPlayersPassedNotification": { + "type": "object", + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterNotification" + }, + { + "type": "object", + "properties": { + "receivedCards": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Common.Card" + } + } + } + } + ] + }, + "Hearts.PlayerPassedCardsNotification": { + "type": "object", + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterNotification" + }, + { + "type": "object", + "properties": { + "playerId": { + "type": "string", + "format": "uuid" + } + } + } + ] + }, + "Hearts.ItsYourTurnNotification": { + "type": "object", + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterNotification" + }, + { + "type": "object", + "properties": { + "playerViewOfGame": { + "type": "object", + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterResponse" + }, + { + "type": "object", + "properties": { + "cards": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Common.Card" + } + }, + "otherPlayers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Hearts.OtherHeartsPlayer" + } + }, + "roundNumber": { + "type": "integer", + "format": "int32" + }, + "passDirection": { + "type": "string" + }, + "hasPassed": { + "type": "boolean" + }, + "currentTrick": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Hearts.CardPlay" + } + }, + "totalScore": { + "type": "integer", + "format": "int32" + }, + "roundScore": { + "type": "integer", + "format": "int32" + }, + "heartsAreBroken": { + "type": "boolean" + }, + "isMyTurn": { + "type": "boolean" + } + } + } + ] + } + } + } + ] + }, + "Hearts.ItsPlayersTurnNotification": { + "type": "object", + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterNotification" + }, + { + "type": "object", + "properties": { + "playerId": { + "type": "string", + "format": "uuid" + } + } + } + ] + }, + "Hearts.PlayerPlayedCardNotification": { + "type": "object", + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterNotification" + }, + { + "type": "object", + "properties": { + "playerId": { + "type": "string", + "format": "uuid" + }, + "card": { + "type": "object", + "properties": { + "rank": { + "type": "integer", + "format": "int32" + }, + "suit": { + "type": "string" + } + }, + "nullable": true + } + } + } + ] + }, + "Hearts.TrickCompletedNotification": { + "type": "object", + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterNotification" + }, + { + "type": "object", + "properties": { + "winnerId": { + "type": "string", + "format": "uuid" + }, + "winnerName": { + "type": "string" + }, + "trickCards": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Hearts.CardPlay" + } + }, + "points": { + "type": "integer", + "format": "int32" + } + } + } + ] + }, + "Hearts.RoundEndedNotification": { + "type": "object", + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterNotification" + }, + { + "type": "object", + "properties": { + "scores": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Hearts.PlayerScore" + } + }, + "moonShooterId": { + "type": "string", + "format": "uuid", + "nullable": true + }, + "moonShooterName": { + "type": "string" + } + } + } + ] + }, + "Hearts.PlayerScore": { + "type": "object", + "properties": { + "playerId": { + "type": "string", + "format": "uuid" + }, + "playerName": { + "type": "string" + }, + "roundScore": { + "type": "integer", + "format": "int32" + }, + "totalScore": { + "type": "integer", + "format": "int32" + } + } + }, + "Hearts.GameEndedNotification": { + "type": "object", + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterNotification" + }, + { + "type": "object", + "properties": { + "finalScores": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Hearts.PlayerScore" + } + }, + "winnerId": { + "type": "string", + "format": "uuid" + }, + "winnerName": { + "type": "string" + } + } + } + ] + }, + "Hearts.HeartsAreBrokenNotification": { + "type": "object", + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterNotification" + }, + { + "type": "object" + } + ] + }, "Gabong.PenalizePlayerForTakingTooLongRequest": { "type": "object", "allOf": [ @@ -2427,7 +2990,8 @@ "suit": { "type": "string" } - } + }, + "nullable": true } } } @@ -2452,7 +3016,8 @@ "suit": { "type": "string" } - } + }, + "nullable": true }, "newSuit": { "type": "string" @@ -2502,7 +3067,8 @@ "suit": { "type": "string" } - } + }, + "nullable": true } } } @@ -2531,7 +3097,8 @@ "suit": { "type": "string" } - } + }, + "nullable": true } } } @@ -2560,7 +3127,8 @@ "suit": { "type": "string" } - } + }, + "nullable": true }, "newSuit": { "type": "string" @@ -2637,7 +3205,8 @@ "suit": { "type": "string" } - } + }, + "nullable": true }, "currentSuit": { "type": "string" @@ -2689,7 +3258,8 @@ "suit": { "type": "string" } - } + }, + "nullable": true }, "currentSuit": { "type": "string" @@ -2783,7 +3353,8 @@ "suit": { "type": "string" } - } + }, + "nullable": true }, "currentSuit": { "type": "string" @@ -2940,7 +3511,8 @@ "suit": { "type": "string" } - } + }, + "nullable": true }, "claimedToBeCard": { "type": "object", @@ -2952,7 +3524,8 @@ "suit": { "type": "string" } - } + }, + "nullable": true } } } @@ -2981,7 +3554,8 @@ "suit": { "type": "string" } - } + }, + "nullable": true } } } @@ -3058,7 +3632,8 @@ "suit": { "type": "string" } - } + }, + "nullable": true } } } diff --git a/generated/deckster.opeanpi.yaml b/generated/deckster.opeanpi.yaml index 44c5ae90..ccce77eb 100644 --- a/generated/deckster.opeanpi.yaml +++ b/generated/deckster.opeanpi.yaml @@ -1,4 +1,4 @@ -openapi: 3.0.1 +openapi: 3.0.4 info: title: Deckster description: Deckster @@ -87,6 +87,21 @@ components: Idiot.GameStartedNotification: '#/components/schemas/Idiot.GameStartedNotification' Idiot.GameEndedNotification: '#/components/schemas/Idiot.GameEndedNotification' Idiot.ItsTimeToSwapCardsNotification: '#/components/schemas/Idiot.ItsTimeToSwapCardsNotification' + Hearts.PassCardsRequest: '#/components/schemas/Hearts.PassCardsRequest' + Hearts.PlayCardRequest: '#/components/schemas/Hearts.PlayCardRequest' + Hearts.PassCardsResponse: '#/components/schemas/Hearts.PassCardsResponse' + Hearts.GameStartedNotification: '#/components/schemas/Hearts.GameStartedNotification' + Hearts.PlayerViewOfGame: '#/components/schemas/Hearts.PlayerViewOfGame' + Hearts.PassingPhaseStartedNotification: '#/components/schemas/Hearts.PassingPhaseStartedNotification' + Hearts.AllPlayersPassedNotification: '#/components/schemas/Hearts.AllPlayersPassedNotification' + Hearts.PlayerPassedCardsNotification: '#/components/schemas/Hearts.PlayerPassedCardsNotification' + Hearts.ItsYourTurnNotification: '#/components/schemas/Hearts.ItsYourTurnNotification' + Hearts.ItsPlayersTurnNotification: '#/components/schemas/Hearts.ItsPlayersTurnNotification' + Hearts.PlayerPlayedCardNotification: '#/components/schemas/Hearts.PlayerPlayedCardNotification' + Hearts.TrickCompletedNotification: '#/components/schemas/Hearts.TrickCompletedNotification' + Hearts.RoundEndedNotification: '#/components/schemas/Hearts.RoundEndedNotification' + Hearts.GameEndedNotification: '#/components/schemas/Hearts.GameEndedNotification' + Hearts.HeartsAreBrokenNotification: '#/components/schemas/Hearts.HeartsAreBrokenNotification' Gabong.PenalizePlayerForTakingTooLongRequest: '#/components/schemas/Gabong.PenalizePlayerForTakingTooLongRequest' Gabong.PenalizePlayerForTooManyCardsRequest: '#/components/schemas/Gabong.PenalizePlayerForTooManyCardsRequest' Gabong.ActionResponse: '#/components/schemas/Gabong.ActionResponse' @@ -177,6 +192,8 @@ components: Idiot.DrawCardsRequest: '#/components/schemas/Idiot.DrawCardsRequest' Idiot.PullInDiscardPileRequest: '#/components/schemas/Idiot.PullInDiscardPileRequest' Idiot.PutChanceCardRequest: '#/components/schemas/Idiot.PutChanceCardRequest' + Hearts.PassCardsRequest: '#/components/schemas/Hearts.PassCardsRequest' + Hearts.PlayCardRequest: '#/components/schemas/Hearts.PlayCardRequest' Gabong.PenalizePlayerForTakingTooLongRequest: '#/components/schemas/Gabong.PenalizePlayerForTakingTooLongRequest' Gabong.PenalizePlayerForTooManyCardsRequest: '#/components/schemas/Gabong.PenalizePlayerForTooManyCardsRequest' CrazyEights.PutCardRequest: '#/components/schemas/CrazyEights.PutCardRequest' @@ -242,6 +259,17 @@ components: Idiot.GameStartedNotification: '#/components/schemas/Idiot.GameStartedNotification' Idiot.GameEndedNotification: '#/components/schemas/Idiot.GameEndedNotification' Idiot.ItsTimeToSwapCardsNotification: '#/components/schemas/Idiot.ItsTimeToSwapCardsNotification' + Hearts.GameStartedNotification: '#/components/schemas/Hearts.GameStartedNotification' + Hearts.PassingPhaseStartedNotification: '#/components/schemas/Hearts.PassingPhaseStartedNotification' + Hearts.AllPlayersPassedNotification: '#/components/schemas/Hearts.AllPlayersPassedNotification' + Hearts.PlayerPassedCardsNotification: '#/components/schemas/Hearts.PlayerPassedCardsNotification' + Hearts.ItsYourTurnNotification: '#/components/schemas/Hearts.ItsYourTurnNotification' + Hearts.ItsPlayersTurnNotification: '#/components/schemas/Hearts.ItsPlayersTurnNotification' + Hearts.PlayerPlayedCardNotification: '#/components/schemas/Hearts.PlayerPlayedCardNotification' + Hearts.TrickCompletedNotification: '#/components/schemas/Hearts.TrickCompletedNotification' + Hearts.RoundEndedNotification: '#/components/schemas/Hearts.RoundEndedNotification' + Hearts.GameEndedNotification: '#/components/schemas/Hearts.GameEndedNotification' + Hearts.HeartsAreBrokenNotification: '#/components/schemas/Hearts.HeartsAreBrokenNotification' CrazyEights.PlayerPutCardNotification: '#/components/schemas/CrazyEights.PlayerPutCardNotification' CrazyEights.PlayerPutEightNotification: '#/components/schemas/CrazyEights.PlayerPutEightNotification' CrazyEights.PlayerDrewCardNotification: '#/components/schemas/CrazyEights.PlayerDrewCardNotification' @@ -295,6 +323,8 @@ components: Idiot.PullInResponse: '#/components/schemas/Idiot.PullInResponse' Idiot.DrawCardsResponse: '#/components/schemas/Idiot.DrawCardsResponse' Idiot.PutBlindCardResponse: '#/components/schemas/Idiot.PutBlindCardResponse' + Hearts.PassCardsResponse: '#/components/schemas/Hearts.PassCardsResponse' + Hearts.PlayerViewOfGame: '#/components/schemas/Hearts.PlayerViewOfGame' Gabong.ActionResponse: '#/components/schemas/Gabong.ActionResponse' CrazyEights.CardResponse: '#/components/schemas/CrazyEights.CardResponse' CrazyEights.PlayerViewOfGame: '#/components/schemas/CrazyEights.PlayerViewOfGame' @@ -1494,6 +1524,325 @@ components: cardsFacingDownCount: type: integer format: int32 + Hearts.PassCardsRequest: + type: object + allOf: + - $ref: '#/components/schemas/Protocol.DecksterRequest' + - type: object + properties: + cards: + type: array + items: + $ref: '#/components/schemas/Common.Card' + Hearts.PlayCardRequest: + type: object + allOf: + - $ref: '#/components/schemas/Protocol.DecksterRequest' + - type: object + properties: + card: + type: object + properties: + rank: + type: integer + format: int32 + suit: + type: string + Hearts.PassCardsResponse: + type: object + allOf: + - $ref: '#/components/schemas/Protocol.DecksterResponse' + - type: object + properties: + receivedCards: + type: array + items: + $ref: '#/components/schemas/Common.Card' + Hearts.GameStartedNotification: + type: object + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - type: object + properties: + gameId: + type: string + format: uuid + playerViewOfGame: + type: object + allOf: + - $ref: '#/components/schemas/Protocol.DecksterResponse' + - type: object + properties: + cards: + type: array + items: + $ref: '#/components/schemas/Common.Card' + otherPlayers: + type: array + items: + $ref: '#/components/schemas/Hearts.OtherHeartsPlayer' + roundNumber: + type: integer + format: int32 + passDirection: + type: string + hasPassed: + type: boolean + currentTrick: + type: array + items: + $ref: '#/components/schemas/Hearts.CardPlay' + totalScore: + type: integer + format: int32 + roundScore: + type: integer + format: int32 + heartsAreBroken: + type: boolean + isMyTurn: + type: boolean + Hearts.PlayerViewOfGame: + type: object + allOf: + - $ref: '#/components/schemas/Protocol.DecksterResponse' + - type: object + properties: + cards: + type: array + items: + $ref: '#/components/schemas/Common.Card' + otherPlayers: + type: array + items: + $ref: '#/components/schemas/Hearts.OtherHeartsPlayer' + roundNumber: + type: integer + format: int32 + passDirection: + type: string + hasPassed: + type: boolean + currentTrick: + type: array + items: + $ref: '#/components/schemas/Hearts.CardPlay' + totalScore: + type: integer + format: int32 + roundScore: + type: integer + format: int32 + heartsAreBroken: + type: boolean + isMyTurn: + type: boolean + Hearts.OtherHeartsPlayer: + type: object + properties: + playerId: + type: string + format: uuid + name: + type: string + numberOfCards: + type: integer + format: int32 + totalScore: + type: integer + format: int32 + roundScore: + type: integer + format: int32 + playedCard: + type: object + properties: + rank: + type: integer + format: int32 + suit: + type: string + nullable: true + Hearts.CardPlay: + type: object + properties: + playerId: + type: string + format: uuid + playerName: + type: string + card: + type: object + properties: + rank: + type: integer + format: int32 + suit: + type: string + nullable: true + Hearts.PassingPhaseStartedNotification: + type: object + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - type: object + properties: + passDirection: + type: string + Hearts.AllPlayersPassedNotification: + type: object + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - type: object + properties: + receivedCards: + type: array + items: + $ref: '#/components/schemas/Common.Card' + Hearts.PlayerPassedCardsNotification: + type: object + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - type: object + properties: + playerId: + type: string + format: uuid + Hearts.ItsYourTurnNotification: + type: object + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - type: object + properties: + playerViewOfGame: + type: object + allOf: + - $ref: '#/components/schemas/Protocol.DecksterResponse' + - type: object + properties: + cards: + type: array + items: + $ref: '#/components/schemas/Common.Card' + otherPlayers: + type: array + items: + $ref: '#/components/schemas/Hearts.OtherHeartsPlayer' + roundNumber: + type: integer + format: int32 + passDirection: + type: string + hasPassed: + type: boolean + currentTrick: + type: array + items: + $ref: '#/components/schemas/Hearts.CardPlay' + totalScore: + type: integer + format: int32 + roundScore: + type: integer + format: int32 + heartsAreBroken: + type: boolean + isMyTurn: + type: boolean + Hearts.ItsPlayersTurnNotification: + type: object + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - type: object + properties: + playerId: + type: string + format: uuid + Hearts.PlayerPlayedCardNotification: + type: object + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - type: object + properties: + playerId: + type: string + format: uuid + card: + type: object + properties: + rank: + type: integer + format: int32 + suit: + type: string + nullable: true + Hearts.TrickCompletedNotification: + type: object + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - type: object + properties: + winnerId: + type: string + format: uuid + winnerName: + type: string + trickCards: + type: array + items: + $ref: '#/components/schemas/Hearts.CardPlay' + points: + type: integer + format: int32 + Hearts.RoundEndedNotification: + type: object + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - type: object + properties: + scores: + type: array + items: + $ref: '#/components/schemas/Hearts.PlayerScore' + moonShooterId: + type: string + format: uuid + nullable: true + moonShooterName: + type: string + Hearts.PlayerScore: + type: object + properties: + playerId: + type: string + format: uuid + playerName: + type: string + roundScore: + type: integer + format: int32 + totalScore: + type: integer + format: int32 + Hearts.GameEndedNotification: + type: object + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - type: object + properties: + finalScores: + type: array + items: + $ref: '#/components/schemas/Hearts.PlayerScore' + winnerId: + type: string + format: uuid + winnerName: + type: string + Hearts.HeartsAreBrokenNotification: + type: object + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - type: object Gabong.PenalizePlayerForTakingTooLongRequest: type: object allOf: @@ -1523,6 +1872,7 @@ components: format: int32 suit: type: string + nullable: true CrazyEights.PutEightRequest: type: object allOf: @@ -1537,6 +1887,7 @@ components: format: int32 suit: type: string + nullable: true newSuit: type: string CrazyEights.DrawCardRequest: @@ -1563,6 +1914,7 @@ components: format: int32 suit: type: string + nullable: true CrazyEights.PlayerPutCardNotification: type: object allOf: @@ -1580,6 +1932,7 @@ components: format: int32 suit: type: string + nullable: true CrazyEights.PlayerPutEightNotification: type: object allOf: @@ -1597,6 +1950,7 @@ components: format: int32 suit: type: string + nullable: true newSuit: type: string CrazyEights.PlayerDrewCardNotification: @@ -1641,6 +1995,7 @@ components: format: int32 suit: type: string + nullable: true currentSuit: type: string stockPileCount: @@ -1671,6 +2026,7 @@ components: format: int32 suit: type: string + nullable: true currentSuit: type: string stockPileCount: @@ -1730,6 +2086,7 @@ components: format: int32 suit: type: string + nullable: true currentSuit: type: string stockPileCount: @@ -1813,6 +2170,7 @@ components: format: int32 suit: type: string + nullable: true claimedToBeCard: type: object properties: @@ -1821,6 +2179,7 @@ components: format: int32 suit: type: string + nullable: true Bullshit.PlayerPutCardNotification: type: object allOf: @@ -1838,6 +2197,7 @@ components: format: int32 suit: type: string + nullable: true Bullshit.BullshitRequest: type: object allOf: @@ -1877,6 +2237,7 @@ components: format: int32 suit: type: string + nullable: true Bullshit.PlayerDrewCardNotification: type: object allOf: diff --git a/generated/godot/bullshit/BullshitClient.gd b/generated/godot/bullshit/BullshitClient.gd new file mode 100644 index 00000000..260e80ac --- /dev/null +++ b/generated/godot/bullshit/BullshitClient.gd @@ -0,0 +1,173 @@ +## +## Autogenerated by really, really eager small hamsters. +## +## Bullshit Game Client for Godot Engine +## +## Notifications (events) for this game: +## - GameStarted: GameStartedNotification +## - PlayerDrewCard: PlayerDrewCardNotification +## - ItsYourTurn: ItsYourTurnNotification +## - ItsPlayersTurn: ItsPlayersTurnNotification +## - PlayerPassed: PlayerPassedNotification +## - PlayerPutCard: PlayerPutCardNotification +## - GameEnded: GameEndedNotification +## - PlayerIsDone: PlayerIsDoneNotification +## - DiscardPileShuffled: DiscardPileShuffledNotification +## - PlayersBullshitHasBeenCalled: BullshitBroadcastNotification +## - YourBullshitHasBeenCalled: BullshitPlayerNotification +## - PlayerAccusedFalseBullshit: FalseBullshitCallNotification +## + +class_name BullshitClient +extends RefCounted + +## Signals for game notifications +signal gameStarted(data: Dictionary) +signal playerDrewCard(data: Dictionary) +signal itsYourTurn(data: Dictionary) +signal itsPlayersTurn(data: Dictionary) +signal playerPassed(data: Dictionary) +signal playerPutCard(data: Dictionary) +signal gameEnded(data: Dictionary) +signal playerIsDone(data: Dictionary) +signal discardPileShuffled(data: Dictionary) +signal playersBullshitHasBeenCalled(data: Dictionary) +signal yourBullshitHasBeenCalled(data: Dictionary) +signal playerAccusedFalseBullshit(data: Dictionary) + +## WebSocket connections +var _action_socket: WebSocketPeer +var _notification_socket: WebSocketPeer +var _pending_requests: Dictionary = {} +var _request_id_counter: int = 0 + +## Constructor +func _init(action_socket: WebSocketPeer, notification_socket: WebSocketPeer) -> void: + _action_socket = action_socket + _notification_socket = notification_socket + +## Poll sockets for new messages. Call this regularly (e.g., in _process) +func poll() -> void: + _action_socket.poll() + _notification_socket.poll() + + # Process action socket responses + while _action_socket.get_available_packet_count() > 0: + var packet = _action_socket.get_packet() + var json_string = packet.get_string_from_utf8() + var response = JSON.parse_string(json_string) + _handle_action_response(response) + + # Process notification socket messages + while _notification_socket.get_available_packet_count() > 0: + var packet = _notification_socket.get_packet() + var json_string = packet.get_string_from_utf8() + var notification = JSON.parse_string(json_string) + _handle_notification(notification) + +## Internal: Handle responses from action socket +func _handle_action_response(response: Dictionary) -> void: + if response.has("_request_id"): + var request_id = response["_request_id"] + if _pending_requests.has(request_id): + var callback = _pending_requests[request_id] + _pending_requests.erase(request_id) + callback.call(response) + +## Internal: Handle notifications from notification socket +func _handle_notification(notification: Dictionary) -> void: + if not notification.has("type"): + push_warning("Notification missing 'type' field") + return + + var msg_type = notification["type"] + match msg_type: + "Bullshit.GameStartedNotification": + gameStarted.emit(notification) + "Bullshit.PlayerDrewCardNotification": + playerDrewCard.emit(notification) + "Bullshit.ItsYourTurnNotification": + itsYourTurn.emit(notification) + "Bullshit.ItsPlayersTurnNotification": + itsPlayersTurn.emit(notification) + "Bullshit.PlayerPassedNotification": + playerPassed.emit(notification) + "Bullshit.PlayerPutCardNotification": + playerPutCard.emit(notification) + "Bullshit.GameEndedNotification": + gameEnded.emit(notification) + "Bullshit.PlayerIsDoneNotification": + playerIsDone.emit(notification) + "Bullshit.DiscardPileShuffledNotification": + discardPileShuffled.emit(notification) + "Bullshit.BullshitBroadcastNotification": + playersBullshitHasBeenCalled.emit(notification) + "Bullshit.BullshitPlayerNotification": + yourBullshitHasBeenCalled.emit(notification) + "Bullshit.FalseBullshitCallNotification": + playerAccusedFalseBullshit.emit(notification) + _: + push_warning("Unknown notification type: " + msg_type) + +## Internal: Send a request and wait for response +func _send_request(request_data: Dictionary) -> Dictionary: + var request_id = _request_id_counter + _request_id_counter += 1 + request_data["_request_id"] = request_id + + var response_received = false + var response_data: Dictionary = {} + + var callback = func(response: Dictionary): + response_received = true + response_data = response + + _pending_requests[request_id] = callback + + var json_string = JSON.stringify(request_data) + _action_socket.send_text(json_string) + + # Wait for response (polling) + var timeout = 30.0 # 30 seconds timeout + var elapsed = 0.0 + while not response_received and elapsed < timeout: + poll() + await Engine.get_main_loop().process_frame + elapsed += Engine.get_main_loop().root.get_process_delta_time() + + if not response_received: + _pending_requests.erase(request_id) + push_error("Request timeout") + return {"hasError": true, "error": "Request timeout"} + + return response_data + +## ============================================ +## Game Action Methods +## ============================================ + +## PutCard +func putCard(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "Bullshit.PutCardRequest" + return await _send_request(request_data) + +## DrawCard +func drawCard(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "Bullshit.DrawCardRequest" + return await _send_request(request_data) + +## Pass +func pass(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "Bullshit.PassRequest" + return await _send_request(request_data) + +## CallBullshit +func callBullshit(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "Bullshit.BullshitRequest" + return await _send_request(request_data) + +## End of generated client diff --git a/generated/godot/chatroom/ChatRoomClient.gd b/generated/godot/chatroom/ChatRoomClient.gd new file mode 100644 index 00000000..fb76c27b --- /dev/null +++ b/generated/godot/chatroom/ChatRoomClient.gd @@ -0,0 +1,111 @@ +## +## Autogenerated by really, really eager small hamsters. +## +## ChatRoom Game Client for Godot Engine +## +## Notifications (events) for this game: +## - PlayerSaid: ChatNotification +## + +class_name ChatRoomClient +extends RefCounted + +## Signals for game notifications +signal playerSaid(data: Dictionary) + +## WebSocket connections +var _action_socket: WebSocketPeer +var _notification_socket: WebSocketPeer +var _pending_requests: Dictionary = {} +var _request_id_counter: int = 0 + +## Constructor +func _init(action_socket: WebSocketPeer, notification_socket: WebSocketPeer) -> void: + _action_socket = action_socket + _notification_socket = notification_socket + +## Poll sockets for new messages. Call this regularly (e.g., in _process) +func poll() -> void: + _action_socket.poll() + _notification_socket.poll() + + # Process action socket responses + while _action_socket.get_available_packet_count() > 0: + var packet = _action_socket.get_packet() + var json_string = packet.get_string_from_utf8() + var response = JSON.parse_string(json_string) + _handle_action_response(response) + + # Process notification socket messages + while _notification_socket.get_available_packet_count() > 0: + var packet = _notification_socket.get_packet() + var json_string = packet.get_string_from_utf8() + var notification = JSON.parse_string(json_string) + _handle_notification(notification) + +## Internal: Handle responses from action socket +func _handle_action_response(response: Dictionary) -> void: + if response.has("_request_id"): + var request_id = response["_request_id"] + if _pending_requests.has(request_id): + var callback = _pending_requests[request_id] + _pending_requests.erase(request_id) + callback.call(response) + +## Internal: Handle notifications from notification socket +func _handle_notification(notification: Dictionary) -> void: + if not notification.has("type"): + push_warning("Notification missing 'type' field") + return + + var msg_type = notification["type"] + match msg_type: + "ChatRoom.ChatNotification": + playerSaid.emit(notification) + _: + push_warning("Unknown notification type: " + msg_type) + +## Internal: Send a request and wait for response +func _send_request(request_data: Dictionary) -> Dictionary: + var request_id = _request_id_counter + _request_id_counter += 1 + request_data["_request_id"] = request_id + + var response_received = false + var response_data: Dictionary = {} + + var callback = func(response: Dictionary): + response_received = true + response_data = response + + _pending_requests[request_id] = callback + + var json_string = JSON.stringify(request_data) + _action_socket.send_text(json_string) + + # Wait for response (polling) + var timeout = 30.0 # 30 seconds timeout + var elapsed = 0.0 + while not response_received and elapsed < timeout: + poll() + await Engine.get_main_loop().process_frame + elapsed += Engine.get_main_loop().root.get_process_delta_time() + + if not response_received: + _pending_requests.erase(request_id) + push_error("Request timeout") + return {"hasError": true, "error": "Request timeout"} + + return response_data + +## ============================================ +## Game Action Methods +## ============================================ + +## ChatAsync +func chatAsync(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "ChatRoom.SendChatRequest" + return await _send_request(request_data) + +## End of generated client diff --git a/generated/godot/crazyeights/CrazyEightsClient.gd b/generated/godot/crazyeights/CrazyEightsClient.gd new file mode 100644 index 00000000..360b3fc3 --- /dev/null +++ b/generated/godot/crazyeights/CrazyEightsClient.gd @@ -0,0 +1,165 @@ +## +## Autogenerated by really, really eager small hamsters. +## +## CrazyEights Game Client for Godot Engine +## +## Notifications (events) for this game: +## - GameStarted: GameStartedNotification +## - PlayerDrewCard: PlayerDrewCardNotification +## - ItsYourTurn: ItsYourTurnNotification +## - ItsPlayersTurn: ItsPlayersTurnNotification +## - PlayerPassed: PlayerPassedNotification +## - PlayerPutCard: PlayerPutCardNotification +## - PlayerPutEight: PlayerPutEightNotification +## - GameEnded: GameEndedNotification +## - PlayerIsDone: PlayerIsDoneNotification +## - DiscardPileShuffled: DiscardPileShuffledNotification +## + +class_name CrazyEightsClient +extends RefCounted + +## Signals for game notifications +signal gameStarted(data: Dictionary) +signal playerDrewCard(data: Dictionary) +signal itsYourTurn(data: Dictionary) +signal itsPlayersTurn(data: Dictionary) +signal playerPassed(data: Dictionary) +signal playerPutCard(data: Dictionary) +signal playerPutEight(data: Dictionary) +signal gameEnded(data: Dictionary) +signal playerIsDone(data: Dictionary) +signal discardPileShuffled(data: Dictionary) + +## WebSocket connections +var _action_socket: WebSocketPeer +var _notification_socket: WebSocketPeer +var _pending_requests: Dictionary = {} +var _request_id_counter: int = 0 + +## Constructor +func _init(action_socket: WebSocketPeer, notification_socket: WebSocketPeer) -> void: + _action_socket = action_socket + _notification_socket = notification_socket + +## Poll sockets for new messages. Call this regularly (e.g., in _process) +func poll() -> void: + _action_socket.poll() + _notification_socket.poll() + + # Process action socket responses + while _action_socket.get_available_packet_count() > 0: + var packet = _action_socket.get_packet() + var json_string = packet.get_string_from_utf8() + var response = JSON.parse_string(json_string) + _handle_action_response(response) + + # Process notification socket messages + while _notification_socket.get_available_packet_count() > 0: + var packet = _notification_socket.get_packet() + var json_string = packet.get_string_from_utf8() + var notification = JSON.parse_string(json_string) + _handle_notification(notification) + +## Internal: Handle responses from action socket +func _handle_action_response(response: Dictionary) -> void: + if response.has("_request_id"): + var request_id = response["_request_id"] + if _pending_requests.has(request_id): + var callback = _pending_requests[request_id] + _pending_requests.erase(request_id) + callback.call(response) + +## Internal: Handle notifications from notification socket +func _handle_notification(notification: Dictionary) -> void: + if not notification.has("type"): + push_warning("Notification missing 'type' field") + return + + var msg_type = notification["type"] + match msg_type: + "CrazyEights.GameStartedNotification": + gameStarted.emit(notification) + "CrazyEights.PlayerDrewCardNotification": + playerDrewCard.emit(notification) + "CrazyEights.ItsYourTurnNotification": + itsYourTurn.emit(notification) + "CrazyEights.ItsPlayersTurnNotification": + itsPlayersTurn.emit(notification) + "CrazyEights.PlayerPassedNotification": + playerPassed.emit(notification) + "CrazyEights.PlayerPutCardNotification": + playerPutCard.emit(notification) + "CrazyEights.PlayerPutEightNotification": + playerPutEight.emit(notification) + "CrazyEights.GameEndedNotification": + gameEnded.emit(notification) + "CrazyEights.PlayerIsDoneNotification": + playerIsDone.emit(notification) + "CrazyEights.DiscardPileShuffledNotification": + discardPileShuffled.emit(notification) + _: + push_warning("Unknown notification type: " + msg_type) + +## Internal: Send a request and wait for response +func _send_request(request_data: Dictionary) -> Dictionary: + var request_id = _request_id_counter + _request_id_counter += 1 + request_data["_request_id"] = request_id + + var response_received = false + var response_data: Dictionary = {} + + var callback = func(response: Dictionary): + response_received = true + response_data = response + + _pending_requests[request_id] = callback + + var json_string = JSON.stringify(request_data) + _action_socket.send_text(json_string) + + # Wait for response (polling) + var timeout = 30.0 # 30 seconds timeout + var elapsed = 0.0 + while not response_received and elapsed < timeout: + poll() + await Engine.get_main_loop().process_frame + elapsed += Engine.get_main_loop().root.get_process_delta_time() + + if not response_received: + _pending_requests.erase(request_id) + push_error("Request timeout") + return {"hasError": true, "error": "Request timeout"} + + return response_data + +## ============================================ +## Game Action Methods +## ============================================ + +## PutCard +func putCard(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "CrazyEights.PutCardRequest" + return await _send_request(request_data) + +## PutEight +func putEight(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "CrazyEights.PutEightRequest" + return await _send_request(request_data) + +## DrawCard +func drawCard(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "CrazyEights.DrawCardRequest" + return await _send_request(request_data) + +## Pass +func pass(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "CrazyEights.PassRequest" + return await _send_request(request_data) + +## End of generated client diff --git a/generated/godot/gabong/GabongClient.gd b/generated/godot/gabong/GabongClient.gd new file mode 100644 index 00000000..1020ae2f --- /dev/null +++ b/generated/godot/gabong/GabongClient.gd @@ -0,0 +1,163 @@ +## +## Autogenerated by really, really eager small hamsters. +## +## Gabong Game Client for Godot Engine +## +## Notifications (events) for this game: +## - GameStarted: GameStartedNotification +## - PlayerPutCard: PlayerPutCardNotification +## - PlayerDrewCard: PlayerDrewCardNotification +## - PlayerDrewPenaltyCard: PlayerDrewPenaltyCardNotification +## - GameEnded: GameEndedNotification +## - RoundStarted: RoundStartedNotification +## - RoundEnded: RoundEndedNotification +## - PlayerLostTheirTurn: PlayerLostTheirTurnNotification +## + +class_name GabongClient +extends RefCounted + +## Signals for game notifications +signal gameStarted(data: Dictionary) +signal playerPutCard(data: Dictionary) +signal playerDrewCard(data: Dictionary) +signal playerDrewPenaltyCard(data: Dictionary) +signal gameEnded(data: Dictionary) +signal roundStarted(data: Dictionary) +signal roundEnded(data: Dictionary) +signal playerLostTheirTurn(data: Dictionary) + +## WebSocket connections +var _action_socket: WebSocketPeer +var _notification_socket: WebSocketPeer +var _pending_requests: Dictionary = {} +var _request_id_counter: int = 0 + +## Constructor +func _init(action_socket: WebSocketPeer, notification_socket: WebSocketPeer) -> void: + _action_socket = action_socket + _notification_socket = notification_socket + +## Poll sockets for new messages. Call this regularly (e.g., in _process) +func poll() -> void: + _action_socket.poll() + _notification_socket.poll() + + # Process action socket responses + while _action_socket.get_available_packet_count() > 0: + var packet = _action_socket.get_packet() + var json_string = packet.get_string_from_utf8() + var response = JSON.parse_string(json_string) + _handle_action_response(response) + + # Process notification socket messages + while _notification_socket.get_available_packet_count() > 0: + var packet = _notification_socket.get_packet() + var json_string = packet.get_string_from_utf8() + var notification = JSON.parse_string(json_string) + _handle_notification(notification) + +## Internal: Handle responses from action socket +func _handle_action_response(response: Dictionary) -> void: + if response.has("_request_id"): + var request_id = response["_request_id"] + if _pending_requests.has(request_id): + var callback = _pending_requests[request_id] + _pending_requests.erase(request_id) + callback.call(response) + +## Internal: Handle notifications from notification socket +func _handle_notification(notification: Dictionary) -> void: + if not notification.has("type"): + push_warning("Notification missing 'type' field") + return + + var msg_type = notification["type"] + match msg_type: + "Gabong.GameStartedNotification": + gameStarted.emit(notification) + "Gabong.PlayerPutCardNotification": + playerPutCard.emit(notification) + "Gabong.PlayerDrewCardNotification": + playerDrewCard.emit(notification) + "Gabong.PlayerDrewPenaltyCardNotification": + playerDrewPenaltyCard.emit(notification) + "Gabong.GameEndedNotification": + gameEnded.emit(notification) + "Gabong.RoundStartedNotification": + roundStarted.emit(notification) + "Gabong.RoundEndedNotification": + roundEnded.emit(notification) + "Gabong.PlayerLostTheirTurnNotification": + playerLostTheirTurn.emit(notification) + _: + push_warning("Unknown notification type: " + msg_type) + +## Internal: Send a request and wait for response +func _send_request(request_data: Dictionary) -> Dictionary: + var request_id = _request_id_counter + _request_id_counter += 1 + request_data["_request_id"] = request_id + + var response_received = false + var response_data: Dictionary = {} + + var callback = func(response: Dictionary): + response_received = true + response_data = response + + _pending_requests[request_id] = callback + + var json_string = JSON.stringify(request_data) + _action_socket.send_text(json_string) + + # Wait for response (polling) + var timeout = 30.0 # 30 seconds timeout + var elapsed = 0.0 + while not response_received and elapsed < timeout: + poll() + await Engine.get_main_loop().process_frame + elapsed += Engine.get_main_loop().root.get_process_delta_time() + + if not response_received: + _pending_requests.erase(request_id) + push_error("Request timeout") + return {"hasError": true, "error": "Request timeout"} + + return response_data + +## ============================================ +## Game Action Methods +## ============================================ + +## DrawCard +func drawCard(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "Gabong.DrawCardRequest" + return await _send_request(request_data) + +## PlayGabong +func playGabong(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "Gabong.PlayGabongRequest" + return await _send_request(request_data) + +## PlayBonga +func playBonga(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "Gabong.PlayBongaRequest" + return await _send_request(request_data) + +## Pass +func pass(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "Gabong.PassRequest" + return await _send_request(request_data) + +## PutCard +func putCard(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "Gabong.PutCardRequest" + return await _send_request(request_data) + +## End of generated client diff --git a/generated/godot/hearts/HeartsClient.gd b/generated/godot/hearts/HeartsClient.gd new file mode 100644 index 00000000..109b0f47 --- /dev/null +++ b/generated/godot/hearts/HeartsClient.gd @@ -0,0 +1,157 @@ +## +## Autogenerated by really, really eager small hamsters. +## +## Hearts Game Client for Godot Engine +## +## Notifications (events) for this game: +## - GameStarted: GameStartedNotification +## - PassingPhaseStarted: PassingPhaseStartedNotification +## - AllPlayersPassed: AllPlayersPassedNotification +## - PlayerPassedCards: PlayerPassedCardsNotification +## - ItsYourTurn: ItsYourTurnNotification +## - ItsPlayersTurn: ItsPlayersTurnNotification +## - PlayerPlayedCard: PlayerPlayedCardNotification +## - TrickCompleted: TrickCompletedNotification +## - RoundEnded: RoundEndedNotification +## - GameEnded: GameEndedNotification +## - HeartsWereBroken: HeartsAreBrokenNotification +## + +class_name HeartsClient +extends RefCounted + +## Signals for game notifications +signal gameStarted(data: Dictionary) +signal passingPhaseStarted(data: Dictionary) +signal allPlayersPassed(data: Dictionary) +signal playerPassedCards(data: Dictionary) +signal itsYourTurn(data: Dictionary) +signal itsPlayersTurn(data: Dictionary) +signal playerPlayedCard(data: Dictionary) +signal trickCompleted(data: Dictionary) +signal roundEnded(data: Dictionary) +signal gameEnded(data: Dictionary) +signal heartsWereBroken(data: Dictionary) + +## WebSocket connections +var _action_socket: WebSocketPeer +var _notification_socket: WebSocketPeer +var _pending_requests: Dictionary = {} +var _request_id_counter: int = 0 + +## Constructor +func _init(action_socket: WebSocketPeer, notification_socket: WebSocketPeer) -> void: + _action_socket = action_socket + _notification_socket = notification_socket + +## Poll sockets for new messages. Call this regularly (e.g., in _process) +func poll() -> void: + _action_socket.poll() + _notification_socket.poll() + + # Process action socket responses + while _action_socket.get_available_packet_count() > 0: + var packet = _action_socket.get_packet() + var json_string = packet.get_string_from_utf8() + var response = JSON.parse_string(json_string) + _handle_action_response(response) + + # Process notification socket messages + while _notification_socket.get_available_packet_count() > 0: + var packet = _notification_socket.get_packet() + var json_string = packet.get_string_from_utf8() + var notification = JSON.parse_string(json_string) + _handle_notification(notification) + +## Internal: Handle responses from action socket +func _handle_action_response(response: Dictionary) -> void: + if response.has("_request_id"): + var request_id = response["_request_id"] + if _pending_requests.has(request_id): + var callback = _pending_requests[request_id] + _pending_requests.erase(request_id) + callback.call(response) + +## Internal: Handle notifications from notification socket +func _handle_notification(notification: Dictionary) -> void: + if not notification.has("type"): + push_warning("Notification missing 'type' field") + return + + var msg_type = notification["type"] + match msg_type: + "Hearts.GameStartedNotification": + gameStarted.emit(notification) + "Hearts.PassingPhaseStartedNotification": + passingPhaseStarted.emit(notification) + "Hearts.AllPlayersPassedNotification": + allPlayersPassed.emit(notification) + "Hearts.PlayerPassedCardsNotification": + playerPassedCards.emit(notification) + "Hearts.ItsYourTurnNotification": + itsYourTurn.emit(notification) + "Hearts.ItsPlayersTurnNotification": + itsPlayersTurn.emit(notification) + "Hearts.PlayerPlayedCardNotification": + playerPlayedCard.emit(notification) + "Hearts.TrickCompletedNotification": + trickCompleted.emit(notification) + "Hearts.RoundEndedNotification": + roundEnded.emit(notification) + "Hearts.GameEndedNotification": + gameEnded.emit(notification) + "Hearts.HeartsAreBrokenNotification": + heartsWereBroken.emit(notification) + _: + push_warning("Unknown notification type: " + msg_type) + +## Internal: Send a request and wait for response +func _send_request(request_data: Dictionary) -> Dictionary: + var request_id = _request_id_counter + _request_id_counter += 1 + request_data["_request_id"] = request_id + + var response_received = false + var response_data: Dictionary = {} + + var callback = func(response: Dictionary): + response_received = true + response_data = response + + _pending_requests[request_id] = callback + + var json_string = JSON.stringify(request_data) + _action_socket.send_text(json_string) + + # Wait for response (polling) + var timeout = 30.0 # 30 seconds timeout + var elapsed = 0.0 + while not response_received and elapsed < timeout: + poll() + await Engine.get_main_loop().process_frame + elapsed += Engine.get_main_loop().root.get_process_delta_time() + + if not response_received: + _pending_requests.erase(request_id) + push_error("Request timeout") + return {"hasError": true, "error": "Request timeout"} + + return response_data + +## ============================================ +## Game Action Methods +## ============================================ + +## PassCards +func passCards(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "Hearts.PassCardsRequest" + return await _send_request(request_data) + +## PlayCard +func playCard(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "Hearts.PlayCardRequest" + return await _send_request(request_data) + +## End of generated client diff --git a/generated/godot/idiot/IdiotClient.gd b/generated/godot/idiot/IdiotClient.gd new file mode 100644 index 00000000..52a2855c --- /dev/null +++ b/generated/godot/idiot/IdiotClient.gd @@ -0,0 +1,191 @@ +## +## Autogenerated by really, really eager small hamsters. +## +## Idiot Game Client for Godot Engine +## +## Notifications (events) for this game: +## - ItsTimeToSwapCards: ItsTimeToSwapCardsNotification +## - PlayerIsReady: PlayerIsReadyNotification +## - GameHasStarted: GameStartedNotification +## - GameEnded: GameEndedNotification +## - ItsYourTurn: ItsYourTurnNotification +## - PlayerDrewCards: PlayerDrewCardsNotification +## - PlayerPutCards: PlayerPutCardsNotification +## - DiscardPileFlushed: DiscardPileFlushedNotification +## - PlayerIsDone: PlayerIsDoneNotification +## - PlayerSwappedCards: PlayerSwappedCardsNotification +## - PlayerAttemptedPuttingCard: PlayerAttemptedPuttingCardNotification +## - PlayerPulledInDiscardPile: PlayerPulledInDiscardPileNotification +## + +class_name IdiotClient +extends RefCounted + +## Signals for game notifications +signal itsTimeToSwapCards(data: Dictionary) +signal playerIsReady(data: Dictionary) +signal gameHasStarted(data: Dictionary) +signal gameEnded(data: Dictionary) +signal itsYourTurn(data: Dictionary) +signal playerDrewCards(data: Dictionary) +signal playerPutCards(data: Dictionary) +signal discardPileFlushed(data: Dictionary) +signal playerIsDone(data: Dictionary) +signal playerSwappedCards(data: Dictionary) +signal playerAttemptedPuttingCard(data: Dictionary) +signal playerPulledInDiscardPile(data: Dictionary) + +## WebSocket connections +var _action_socket: WebSocketPeer +var _notification_socket: WebSocketPeer +var _pending_requests: Dictionary = {} +var _request_id_counter: int = 0 + +## Constructor +func _init(action_socket: WebSocketPeer, notification_socket: WebSocketPeer) -> void: + _action_socket = action_socket + _notification_socket = notification_socket + +## Poll sockets for new messages. Call this regularly (e.g., in _process) +func poll() -> void: + _action_socket.poll() + _notification_socket.poll() + + # Process action socket responses + while _action_socket.get_available_packet_count() > 0: + var packet = _action_socket.get_packet() + var json_string = packet.get_string_from_utf8() + var response = JSON.parse_string(json_string) + _handle_action_response(response) + + # Process notification socket messages + while _notification_socket.get_available_packet_count() > 0: + var packet = _notification_socket.get_packet() + var json_string = packet.get_string_from_utf8() + var notification = JSON.parse_string(json_string) + _handle_notification(notification) + +## Internal: Handle responses from action socket +func _handle_action_response(response: Dictionary) -> void: + if response.has("_request_id"): + var request_id = response["_request_id"] + if _pending_requests.has(request_id): + var callback = _pending_requests[request_id] + _pending_requests.erase(request_id) + callback.call(response) + +## Internal: Handle notifications from notification socket +func _handle_notification(notification: Dictionary) -> void: + if not notification.has("type"): + push_warning("Notification missing 'type' field") + return + + var msg_type = notification["type"] + match msg_type: + "Idiot.ItsTimeToSwapCardsNotification": + itsTimeToSwapCards.emit(notification) + "Idiot.PlayerIsReadyNotification": + playerIsReady.emit(notification) + "Idiot.GameStartedNotification": + gameHasStarted.emit(notification) + "Idiot.GameEndedNotification": + gameEnded.emit(notification) + "Idiot.ItsYourTurnNotification": + itsYourTurn.emit(notification) + "Idiot.PlayerDrewCardsNotification": + playerDrewCards.emit(notification) + "Idiot.PlayerPutCardsNotification": + playerPutCards.emit(notification) + "Idiot.DiscardPileFlushedNotification": + discardPileFlushed.emit(notification) + "Idiot.PlayerIsDoneNotification": + playerIsDone.emit(notification) + "Idiot.PlayerSwappedCardsNotification": + playerSwappedCards.emit(notification) + "Idiot.PlayerAttemptedPuttingCardNotification": + playerAttemptedPuttingCard.emit(notification) + "Idiot.PlayerPulledInDiscardPileNotification": + playerPulledInDiscardPile.emit(notification) + _: + push_warning("Unknown notification type: " + msg_type) + +## Internal: Send a request and wait for response +func _send_request(request_data: Dictionary) -> Dictionary: + var request_id = _request_id_counter + _request_id_counter += 1 + request_data["_request_id"] = request_id + + var response_received = false + var response_data: Dictionary = {} + + var callback = func(response: Dictionary): + response_received = true + response_data = response + + _pending_requests[request_id] = callback + + var json_string = JSON.stringify(request_data) + _action_socket.send_text(json_string) + + # Wait for response (polling) + var timeout = 30.0 # 30 seconds timeout + var elapsed = 0.0 + while not response_received and elapsed < timeout: + poll() + await Engine.get_main_loop().process_frame + elapsed += Engine.get_main_loop().root.get_process_delta_time() + + if not response_received: + _pending_requests.erase(request_id) + push_error("Request timeout") + return {"hasError": true, "error": "Request timeout"} + + return response_data + +## ============================================ +## Game Action Methods +## ============================================ + +## IamReady +func iamReady(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "Idiot.IamReadyRequest" + return await _send_request(request_data) + +## SwapCards +func swapCards(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "Idiot.SwapCardsRequest" + return await _send_request(request_data) + +## PutCardsFromHand +func putCardsFromHand(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "Idiot.PutCardsFromHandRequest" + return await _send_request(request_data) + +## PutCardsFacingUp +func putCardsFacingUp(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "Idiot.PutCardsFacingUpRequest" + return await _send_request(request_data) + +## PutCardFacingDown +func putCardFacingDown(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "Idiot.PutCardFacingDownRequest" + return await _send_request(request_data) + +## PutChanceCard +func putChanceCard(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "Idiot.PutChanceCardRequest" + return await _send_request(request_data) + +## PullInDiscardPile +func pullInDiscardPile(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "Idiot.PullInDiscardPileRequest" + return await _send_request(request_data) + +## End of generated client diff --git a/generated/godot/texasholdem/TexasHoldEmClient.gd b/generated/godot/texasholdem/TexasHoldEmClient.gd new file mode 100644 index 00000000..7769d607 --- /dev/null +++ b/generated/godot/texasholdem/TexasHoldEmClient.gd @@ -0,0 +1,169 @@ +## +## Autogenerated by really, really eager small hamsters. +## +## TexasHoldEm Game Client for Godot Engine +## +## Notifications (events) for this game: +## - GameStarted: GameStartedNotification +## - ItsYourTurn: ItsYourTurnNotification +## - RoundStarted: NewRoundStartedNotification +## - RoundEnded: RoundEndedNotification +## - PlayerBetted: PlayerBettedNotification +## - PlayerAllIn: PlayerAllInNotification +## - PlayerChecked: PlayerCheckedNotification +## - PlayerFolded: PlayerFoldedNotification +## - PlayerCalled: PlayerCalledNotification +## - NewCardsRevealed: NewCardsRevealed +## - GameEnded: GameEndedNotification +## + +class_name TexasHoldEmClient +extends RefCounted + +## Signals for game notifications +signal gameStarted(data: Dictionary) +signal itsYourTurn(data: Dictionary) +signal roundStarted(data: Dictionary) +signal roundEnded(data: Dictionary) +signal playerBetted(data: Dictionary) +signal playerAllIn(data: Dictionary) +signal playerChecked(data: Dictionary) +signal playerFolded(data: Dictionary) +signal playerCalled(data: Dictionary) +signal newCardsRevealed(data: Dictionary) +signal gameEnded(data: Dictionary) + +## WebSocket connections +var _action_socket: WebSocketPeer +var _notification_socket: WebSocketPeer +var _pending_requests: Dictionary = {} +var _request_id_counter: int = 0 + +## Constructor +func _init(action_socket: WebSocketPeer, notification_socket: WebSocketPeer) -> void: + _action_socket = action_socket + _notification_socket = notification_socket + +## Poll sockets for new messages. Call this regularly (e.g., in _process) +func poll() -> void: + _action_socket.poll() + _notification_socket.poll() + + # Process action socket responses + while _action_socket.get_available_packet_count() > 0: + var packet = _action_socket.get_packet() + var json_string = packet.get_string_from_utf8() + var response = JSON.parse_string(json_string) + _handle_action_response(response) + + # Process notification socket messages + while _notification_socket.get_available_packet_count() > 0: + var packet = _notification_socket.get_packet() + var json_string = packet.get_string_from_utf8() + var notification = JSON.parse_string(json_string) + _handle_notification(notification) + +## Internal: Handle responses from action socket +func _handle_action_response(response: Dictionary) -> void: + if response.has("_request_id"): + var request_id = response["_request_id"] + if _pending_requests.has(request_id): + var callback = _pending_requests[request_id] + _pending_requests.erase(request_id) + callback.call(response) + +## Internal: Handle notifications from notification socket +func _handle_notification(notification: Dictionary) -> void: + if not notification.has("type"): + push_warning("Notification missing 'type' field") + return + + var msg_type = notification["type"] + match msg_type: + "TexasHoldEm.GameStartedNotification": + gameStarted.emit(notification) + "TexasHoldEm.ItsYourTurnNotification": + itsYourTurn.emit(notification) + "TexasHoldEm.NewRoundStartedNotification": + roundStarted.emit(notification) + "TexasHoldEm.RoundEndedNotification": + roundEnded.emit(notification) + "TexasHoldEm.PlayerBettedNotification": + playerBetted.emit(notification) + "TexasHoldEm.PlayerAllInNotification": + playerAllIn.emit(notification) + "TexasHoldEm.PlayerCheckedNotification": + playerChecked.emit(notification) + "TexasHoldEm.PlayerFoldedNotification": + playerFolded.emit(notification) + "TexasHoldEm.PlayerCalledNotification": + playerCalled.emit(notification) + "TexasHoldEm.NewCardsRevealed": + newCardsRevealed.emit(notification) + "TexasHoldEm.GameEndedNotification": + gameEnded.emit(notification) + _: + push_warning("Unknown notification type: " + msg_type) + +## Internal: Send a request and wait for response +func _send_request(request_data: Dictionary) -> Dictionary: + var request_id = _request_id_counter + _request_id_counter += 1 + request_data["_request_id"] = request_id + + var response_received = false + var response_data: Dictionary = {} + + var callback = func(response: Dictionary): + response_received = true + response_data = response + + _pending_requests[request_id] = callback + + var json_string = JSON.stringify(request_data) + _action_socket.send_text(json_string) + + # Wait for response (polling) + var timeout = 30.0 # 30 seconds timeout + var elapsed = 0.0 + while not response_received and elapsed < timeout: + poll() + await Engine.get_main_loop().process_frame + elapsed += Engine.get_main_loop().root.get_process_delta_time() + + if not response_received: + _pending_requests.erase(request_id) + push_error("Request timeout") + return {"hasError": true, "error": "Request timeout"} + + return response_data + +## ============================================ +## Game Action Methods +## ============================================ + +## PlayerBetRequest +func playerBetRequest(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "TexasHoldEm.BetRequest" + return await _send_request(request_data) + +## PlayerFoldRequest +func playerFoldRequest(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "TexasHoldEm.FoldRequest" + return await _send_request(request_data) + +## PlayerCheckRequest +func playerCheckRequest(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "TexasHoldEm.CheckRequest" + return await _send_request(request_data) + +## PlayerCallRequest +func playerCallRequest(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "TexasHoldEm.CallRequest" + return await _send_request(request_data) + +## End of generated client diff --git a/generated/godot/uno/UnoClient.gd b/generated/godot/uno/UnoClient.gd new file mode 100644 index 00000000..3315a2d6 --- /dev/null +++ b/generated/godot/uno/UnoClient.gd @@ -0,0 +1,153 @@ +## +## Autogenerated by really, really eager small hamsters. +## +## Uno Game Client for Godot Engine +## +## Notifications (events) for this game: +## - GameStarted: GameStartedNotification +## - PlayerPutCard: PlayerPutCardNotification +## - PlayerPutWild: PlayerPutWildNotification +## - PlayerDrewCard: PlayerDrewCardNotification +## - PlayerPassed: PlayerPassedNotification +## - GameEnded: GameEndedNotification +## - ItsYourTurn: ItsYourTurnNotification +## + +class_name UnoClient +extends RefCounted + +## Signals for game notifications +signal gameStarted(data: Dictionary) +signal playerPutCard(data: Dictionary) +signal playerPutWild(data: Dictionary) +signal playerDrewCard(data: Dictionary) +signal playerPassed(data: Dictionary) +signal gameEnded(data: Dictionary) +signal itsYourTurn(data: Dictionary) + +## WebSocket connections +var _action_socket: WebSocketPeer +var _notification_socket: WebSocketPeer +var _pending_requests: Dictionary = {} +var _request_id_counter: int = 0 + +## Constructor +func _init(action_socket: WebSocketPeer, notification_socket: WebSocketPeer) -> void: + _action_socket = action_socket + _notification_socket = notification_socket + +## Poll sockets for new messages. Call this regularly (e.g., in _process) +func poll() -> void: + _action_socket.poll() + _notification_socket.poll() + + # Process action socket responses + while _action_socket.get_available_packet_count() > 0: + var packet = _action_socket.get_packet() + var json_string = packet.get_string_from_utf8() + var response = JSON.parse_string(json_string) + _handle_action_response(response) + + # Process notification socket messages + while _notification_socket.get_available_packet_count() > 0: + var packet = _notification_socket.get_packet() + var json_string = packet.get_string_from_utf8() + var notification = JSON.parse_string(json_string) + _handle_notification(notification) + +## Internal: Handle responses from action socket +func _handle_action_response(response: Dictionary) -> void: + if response.has("_request_id"): + var request_id = response["_request_id"] + if _pending_requests.has(request_id): + var callback = _pending_requests[request_id] + _pending_requests.erase(request_id) + callback.call(response) + +## Internal: Handle notifications from notification socket +func _handle_notification(notification: Dictionary) -> void: + if not notification.has("type"): + push_warning("Notification missing 'type' field") + return + + var msg_type = notification["type"] + match msg_type: + "Uno.GameStartedNotification": + gameStarted.emit(notification) + "Uno.PlayerPutCardNotification": + playerPutCard.emit(notification) + "Uno.PlayerPutWildNotification": + playerPutWild.emit(notification) + "Uno.PlayerDrewCardNotification": + playerDrewCard.emit(notification) + "Uno.PlayerPassedNotification": + playerPassed.emit(notification) + "Uno.GameEndedNotification": + gameEnded.emit(notification) + "Uno.ItsYourTurnNotification": + itsYourTurn.emit(notification) + _: + push_warning("Unknown notification type: " + msg_type) + +## Internal: Send a request and wait for response +func _send_request(request_data: Dictionary) -> Dictionary: + var request_id = _request_id_counter + _request_id_counter += 1 + request_data["_request_id"] = request_id + + var response_received = false + var response_data: Dictionary = {} + + var callback = func(response: Dictionary): + response_received = true + response_data = response + + _pending_requests[request_id] = callback + + var json_string = JSON.stringify(request_data) + _action_socket.send_text(json_string) + + # Wait for response (polling) + var timeout = 30.0 # 30 seconds timeout + var elapsed = 0.0 + while not response_received and elapsed < timeout: + poll() + await Engine.get_main_loop().process_frame + elapsed += Engine.get_main_loop().root.get_process_delta_time() + + if not response_received: + _pending_requests.erase(request_id) + push_error("Request timeout") + return {"hasError": true, "error": "Request timeout"} + + return response_data + +## ============================================ +## Game Action Methods +## ============================================ + +## PutCard +func putCard(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "Uno.PutCardRequest" + return await _send_request(request_data) + +## PutWild +func putWild(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "Uno.PutWildRequest" + return await _send_request(request_data) + +## DrawCard +func drawCard(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "Uno.DrawCardRequest" + return await _send_request(request_data) + +## Pass +func pass(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "Uno.PassRequest" + return await _send_request(request_data) + +## End of generated client diff --git a/generated/godot/yaniv/YanivClient.gd b/generated/godot/yaniv/YanivClient.gd new file mode 100644 index 00000000..4355f4e6 --- /dev/null +++ b/generated/godot/yaniv/YanivClient.gd @@ -0,0 +1,137 @@ +## +## Autogenerated by really, really eager small hamsters. +## +## Yaniv Game Client for Godot Engine +## +## Notifications (events) for this game: +## - PlayerPutCards: PlayerPutCardsNotification +## - ItsYourTurn: ItsYourTurnNotification +## - RoundStarted: RoundStartedNotification +## - RoundEnded: RoundEndedNotification +## - GameEnded: GameEndedNotification +## - DiscardPileShuffled: DiscardPileShuffledNotification +## + +class_name YanivClient +extends RefCounted + +## Signals for game notifications +signal playerPutCards(data: Dictionary) +signal itsYourTurn(data: Dictionary) +signal roundStarted(data: Dictionary) +signal roundEnded(data: Dictionary) +signal gameEnded(data: Dictionary) +signal discardPileShuffled(data: Dictionary) + +## WebSocket connections +var _action_socket: WebSocketPeer +var _notification_socket: WebSocketPeer +var _pending_requests: Dictionary = {} +var _request_id_counter: int = 0 + +## Constructor +func _init(action_socket: WebSocketPeer, notification_socket: WebSocketPeer) -> void: + _action_socket = action_socket + _notification_socket = notification_socket + +## Poll sockets for new messages. Call this regularly (e.g., in _process) +func poll() -> void: + _action_socket.poll() + _notification_socket.poll() + + # Process action socket responses + while _action_socket.get_available_packet_count() > 0: + var packet = _action_socket.get_packet() + var json_string = packet.get_string_from_utf8() + var response = JSON.parse_string(json_string) + _handle_action_response(response) + + # Process notification socket messages + while _notification_socket.get_available_packet_count() > 0: + var packet = _notification_socket.get_packet() + var json_string = packet.get_string_from_utf8() + var notification = JSON.parse_string(json_string) + _handle_notification(notification) + +## Internal: Handle responses from action socket +func _handle_action_response(response: Dictionary) -> void: + if response.has("_request_id"): + var request_id = response["_request_id"] + if _pending_requests.has(request_id): + var callback = _pending_requests[request_id] + _pending_requests.erase(request_id) + callback.call(response) + +## Internal: Handle notifications from notification socket +func _handle_notification(notification: Dictionary) -> void: + if not notification.has("type"): + push_warning("Notification missing 'type' field") + return + + var msg_type = notification["type"] + match msg_type: + "Yaniv.PlayerPutCardsNotification": + playerPutCards.emit(notification) + "Yaniv.ItsYourTurnNotification": + itsYourTurn.emit(notification) + "Yaniv.RoundStartedNotification": + roundStarted.emit(notification) + "Yaniv.RoundEndedNotification": + roundEnded.emit(notification) + "Yaniv.GameEndedNotification": + gameEnded.emit(notification) + "Yaniv.DiscardPileShuffledNotification": + discardPileShuffled.emit(notification) + _: + push_warning("Unknown notification type: " + msg_type) + +## Internal: Send a request and wait for response +func _send_request(request_data: Dictionary) -> Dictionary: + var request_id = _request_id_counter + _request_id_counter += 1 + request_data["_request_id"] = request_id + + var response_received = false + var response_data: Dictionary = {} + + var callback = func(response: Dictionary): + response_received = true + response_data = response + + _pending_requests[request_id] = callback + + var json_string = JSON.stringify(request_data) + _action_socket.send_text(json_string) + + # Wait for response (polling) + var timeout = 30.0 # 30 seconds timeout + var elapsed = 0.0 + while not response_received and elapsed < timeout: + poll() + await Engine.get_main_loop().process_frame + elapsed += Engine.get_main_loop().root.get_process_delta_time() + + if not response_received: + _pending_requests.erase(request_id) + push_error("Request timeout") + return {"hasError": true, "error": "Request timeout"} + + return response_data + +## ============================================ +## Game Action Methods +## ============================================ + +## CallYaniv +func callYaniv(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "Yaniv.CallYanivRequest" + return await _send_request(request_data) + +## PutCards +func putCards(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "Yaniv.PutCardsRequest" + return await _send_request(request_data) + +## End of generated client diff --git a/generated/kotlin/no.forse.decksterlib/hearts/HeartsClient.kt b/generated/kotlin/no.forse.decksterlib/hearts/HeartsClient.kt new file mode 100644 index 00000000..7c8b7d23 --- /dev/null +++ b/generated/kotlin/no.forse.decksterlib/hearts/HeartsClient.kt @@ -0,0 +1,23 @@ +/** + * Autogenerated by really, really eager small hamsters. + * + * Notifications (events) for this game: + * GameStarted: GameStartedNotification + * PassingPhaseStarted: PassingPhaseStartedNotification + * AllPlayersPassed: AllPlayersPassedNotification + * PlayerPassedCards: PlayerPassedCardsNotification + * ItsYourTurn: ItsYourTurnNotification + * ItsPlayersTurn: ItsPlayersTurnNotification + * PlayerPlayedCard: PlayerPlayedCardNotification + * TrickCompleted: TrickCompletedNotification + * RoundEnded: RoundEndedNotification + * GameEnded: GameEndedNotification + * HeartsWereBroken: HeartsAreBrokenNotification + * +*/ +package no.forse.decksterlib.hearts + +interface HeartsClient { + suspend fun passCards(request: PassCardsRequest): PassCardsResponse + suspend fun playCard(request: PlayCardRequest): PlayerViewOfGame +} diff --git a/generated/kotlin/no.forse.decksterlib/uno/UnoClient.kt b/generated/kotlin/no.forse.decksterlib/uno/UnoClient.kt index 4295864b..feb23fac 100644 --- a/generated/kotlin/no.forse.decksterlib/uno/UnoClient.kt +++ b/generated/kotlin/no.forse.decksterlib/uno/UnoClient.kt @@ -9,8 +9,6 @@ * PlayerPassed: PlayerPassedNotification * GameEnded: GameEndedNotification * ItsYourTurn: ItsYourTurnNotification - * RoundStarted: RoundStartedNotification - * RoundEnded: RoundEndedNotification * */ package no.forse.decksterlib.uno diff --git a/generated/shebang.opeanpi.json b/generated/shebang.opeanpi.json index 8839cdd9..b7ed2a07 100644 --- a/generated/shebang.opeanpi.json +++ b/generated/shebang.opeanpi.json @@ -1,5 +1,5 @@ { - "openapi": "3.0.1", + "openapi": "3.0.4", "info": { "title": "Deckster.Server", "version": "1.0" @@ -2593,63 +2593,10 @@ } } }, - "/": { - "get": { - "tags": [ - "Home" - ], - "responses": { - "200": { - "description": "OK" - } - } - } - }, - "/login": { - "get": { - "tags": [ - "Home" - ], - "responses": { - "200": { - "description": "OK" - } - } - }, - "post": { - "tags": [ - "Home" - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Controllers.LoginModel" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/Controllers.LoginModel" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/Controllers.LoginModel" - } - } - } - }, - "responses": { - "200": { - "description": "OK" - } - } - } - }, - "/idiot/description": { + "/hearts/description": { "get": { "tags": [ - "Idiot" + "Hearts" ], "responses": { "200": { @@ -2658,10 +2605,10 @@ } } }, - "/idiot/metadata": { + "/hearts/metadata": { "get": { "tags": [ - "Idiot" + "Hearts" ], "responses": { "200": { @@ -2687,10 +2634,10 @@ } } }, - "/idiot": { + "/hearts": { "get": { "tags": [ - "Idiot" + "Hearts" ], "responses": { "200": { @@ -2716,10 +2663,10 @@ } } }, - "/idiot/games": { + "/hearts/games": { "get": { "tags": [ - "Idiot" + "Hearts" ], "responses": { "200": { @@ -2754,10 +2701,10 @@ } } }, - "/idiot/games/{name}": { + "/hearts/games/{name}": { "get": { "tags": [ - "Idiot" + "Hearts" ], "parameters": [ { @@ -2814,7 +2761,7 @@ }, "delete": { "tags": [ - "Idiot" + "Hearts" ], "parameters": [ { @@ -2870,10 +2817,10 @@ } } }, - "/idiot/games/{name}/bot": { + "/hearts/games/{name}/bot": { "post": { "tags": [ - "Idiot" + "Hearts" ], "parameters": [ { @@ -2909,10 +2856,10 @@ } } }, - "/idiot/previousgames": { + "/hearts/previousgames": { "get": { "tags": [ - "Idiot" + "Hearts" ], "responses": { "200": { @@ -2922,7 +2869,7 @@ "schema": { "type": "array", "items": { - "$ref": "#/components/schemas/Idiot.IdiotGame" + "$ref": "#/components/schemas/Hearts.HeartsGame" } } }, @@ -2930,7 +2877,7 @@ "schema": { "type": "array", "items": { - "$ref": "#/components/schemas/Idiot.IdiotGame" + "$ref": "#/components/schemas/Hearts.HeartsGame" } } }, @@ -2938,7 +2885,7 @@ "schema": { "type": "array", "items": { - "$ref": "#/components/schemas/Idiot.IdiotGame" + "$ref": "#/components/schemas/Hearts.HeartsGame" } } } @@ -2947,10 +2894,10 @@ } } }, - "/idiot/previousgames/{id}": { + "/hearts/previousgames/{id}": { "get": { "tags": [ - "Idiot" + "Hearts" ], "parameters": [ { @@ -2969,17 +2916,17 @@ "content": { "text/plain": { "schema": { - "$ref": "#/components/schemas/Data.HistoricIdiotGame" + "$ref": "#/components/schemas/Data.HistoricHeartsGame" } }, "application/json": { "schema": { - "$ref": "#/components/schemas/Data.HistoricIdiotGame" + "$ref": "#/components/schemas/Data.HistoricHeartsGame" } }, "text/json": { "schema": { - "$ref": "#/components/schemas/Data.HistoricIdiotGame" + "$ref": "#/components/schemas/Data.HistoricHeartsGame" } } } @@ -2987,10 +2934,10 @@ } } }, - "/idiot/previousgames/{id}/{version}": { + "/hearts/previousgames/{id}/{version}": { "get": { "tags": [ - "Idiot" + "Hearts" ], "parameters": [ { @@ -3018,17 +2965,17 @@ "content": { "text/plain": { "schema": { - "$ref": "#/components/schemas/Data.HistoricIdiotGame" + "$ref": "#/components/schemas/Data.HistoricHeartsGame" } }, "application/json": { "schema": { - "$ref": "#/components/schemas/Data.HistoricIdiotGame" + "$ref": "#/components/schemas/Data.HistoricHeartsGame" } }, "text/json": { "schema": { - "$ref": "#/components/schemas/Data.HistoricIdiotGame" + "$ref": "#/components/schemas/Data.HistoricHeartsGame" } } } @@ -3036,10 +2983,10 @@ } } }, - "/idiot/create/{name}": { + "/hearts/create/{name}": { "post": { "tags": [ - "Idiot" + "Hearts" ], "parameters": [ { @@ -3095,10 +3042,10 @@ } } }, - "/idiot/create": { + "/hearts/create": { "post": { "tags": [ - "Idiot" + "Hearts" ], "responses": { "200": { @@ -3144,10 +3091,10 @@ } } }, - "/idiot/games/{name}/start": { + "/hearts/games/{name}/start": { "post": { "tags": [ - "Idiot" + "Hearts" ], "parameters": [ { @@ -3203,10 +3150,10 @@ } } }, - "/idiot/join/{gameName}": { + "/hearts/join/{gameName}": { "get": { "tags": [ - "Idiot" + "Hearts" ], "parameters": [ { @@ -3225,10 +3172,10 @@ } } }, - "/idiot/join/{connectionId}/finish": { + "/hearts/join/{connectionId}/finish": { "get": { "tags": [ - "Idiot" + "Hearts" ], "parameters": [ { @@ -3248,10 +3195,10 @@ } } }, - "/idiot/spectate/{gameName}": { + "/hearts/spectate/{gameName}": { "get": { "tags": [ - "Idiot" + "Hearts" ], "parameters": [ { @@ -3270,10 +3217,10 @@ } } }, - "/idiot/spectate/{connectionId}/finish": { + "/hearts/spectate/{connectionId}/finish": { "get": { "tags": [ - "Idiot" + "Hearts" ], "parameters": [ { @@ -3293,10 +3240,10 @@ } } }, - "/meta/messages": { + "/": { "get": { "tags": [ - "Meta" + "Home" ], "responses": { "200": { @@ -3305,10 +3252,51 @@ } } }, - "/texasholdem/description": { + "/login": { "get": { "tags": [ - "TexasHoldEm" + "Home" + ], + "responses": { + "200": { + "description": "OK" + } + } + }, + "post": { + "tags": [ + "Home" + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Controllers.LoginModel" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/Controllers.LoginModel" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/Controllers.LoginModel" + } + } + } + }, + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/idiot/description": { + "get": { + "tags": [ + "Idiot" ], "responses": { "200": { @@ -3317,10 +3305,10 @@ } } }, - "/texasholdem/metadata": { + "/idiot/metadata": { "get": { "tags": [ - "TexasHoldEm" + "Idiot" ], "responses": { "200": { @@ -3346,10 +3334,10 @@ } } }, - "/texasholdem": { + "/idiot": { "get": { "tags": [ - "TexasHoldEm" + "Idiot" ], "responses": { "200": { @@ -3375,10 +3363,10 @@ } } }, - "/texasholdem/games": { + "/idiot/games": { "get": { "tags": [ - "TexasHoldEm" + "Idiot" ], "responses": { "200": { @@ -3413,10 +3401,10 @@ } } }, - "/texasholdem/games/{name}": { + "/idiot/games/{name}": { "get": { "tags": [ - "TexasHoldEm" + "Idiot" ], "parameters": [ { @@ -3473,7 +3461,7 @@ }, "delete": { "tags": [ - "TexasHoldEm" + "Idiot" ], "parameters": [ { @@ -3529,10 +3517,10 @@ } } }, - "/texasholdem/games/{name}/bot": { + "/idiot/games/{name}/bot": { "post": { "tags": [ - "TexasHoldEm" + "Idiot" ], "parameters": [ { @@ -3568,10 +3556,10 @@ } } }, - "/texasholdem/previousgames": { + "/idiot/previousgames": { "get": { "tags": [ - "TexasHoldEm" + "Idiot" ], "responses": { "200": { @@ -3581,7 +3569,7 @@ "schema": { "type": "array", "items": { - "$ref": "#/components/schemas/TexasHoldEm.TexasHoldEmGame" + "$ref": "#/components/schemas/Idiot.IdiotGame" } } }, @@ -3589,7 +3577,7 @@ "schema": { "type": "array", "items": { - "$ref": "#/components/schemas/TexasHoldEm.TexasHoldEmGame" + "$ref": "#/components/schemas/Idiot.IdiotGame" } } }, @@ -3597,7 +3585,7 @@ "schema": { "type": "array", "items": { - "$ref": "#/components/schemas/TexasHoldEm.TexasHoldEmGame" + "$ref": "#/components/schemas/Idiot.IdiotGame" } } } @@ -3606,10 +3594,10 @@ } } }, - "/texasholdem/previousgames/{id}": { + "/idiot/previousgames/{id}": { "get": { "tags": [ - "TexasHoldEm" + "Idiot" ], "parameters": [ { @@ -3628,17 +3616,17 @@ "content": { "text/plain": { "schema": { - "$ref": "#/components/schemas/Data.HistoricTexasHoldEmGame" + "$ref": "#/components/schemas/Data.HistoricIdiotGame" } }, "application/json": { "schema": { - "$ref": "#/components/schemas/Data.HistoricTexasHoldEmGame" + "$ref": "#/components/schemas/Data.HistoricIdiotGame" } }, "text/json": { "schema": { - "$ref": "#/components/schemas/Data.HistoricTexasHoldEmGame" + "$ref": "#/components/schemas/Data.HistoricIdiotGame" } } } @@ -3646,10 +3634,10 @@ } } }, - "/texasholdem/previousgames/{id}/{version}": { + "/idiot/previousgames/{id}/{version}": { "get": { "tags": [ - "TexasHoldEm" + "Idiot" ], "parameters": [ { @@ -3677,17 +3665,17 @@ "content": { "text/plain": { "schema": { - "$ref": "#/components/schemas/Data.HistoricTexasHoldEmGame" + "$ref": "#/components/schemas/Data.HistoricIdiotGame" } }, "application/json": { "schema": { - "$ref": "#/components/schemas/Data.HistoricTexasHoldEmGame" + "$ref": "#/components/schemas/Data.HistoricIdiotGame" } }, "text/json": { "schema": { - "$ref": "#/components/schemas/Data.HistoricTexasHoldEmGame" + "$ref": "#/components/schemas/Data.HistoricIdiotGame" } } } @@ -3695,10 +3683,10 @@ } } }, - "/texasholdem/create/{name}": { + "/idiot/create/{name}": { "post": { "tags": [ - "TexasHoldEm" + "Idiot" ], "parameters": [ { @@ -3754,10 +3742,10 @@ } } }, - "/texasholdem/create": { + "/idiot/create": { "post": { "tags": [ - "TexasHoldEm" + "Idiot" ], "responses": { "200": { @@ -3803,10 +3791,10 @@ } } }, - "/texasholdem/games/{name}/start": { + "/idiot/games/{name}/start": { "post": { "tags": [ - "TexasHoldEm" + "Idiot" ], "parameters": [ { @@ -3862,10 +3850,10 @@ } } }, - "/texasholdem/join/{gameName}": { + "/idiot/join/{gameName}": { "get": { "tags": [ - "TexasHoldEm" + "Idiot" ], "parameters": [ { @@ -3884,10 +3872,10 @@ } } }, - "/texasholdem/join/{connectionId}/finish": { + "/idiot/join/{connectionId}/finish": { "get": { "tags": [ - "TexasHoldEm" + "Idiot" ], "parameters": [ { @@ -3907,10 +3895,10 @@ } } }, - "/texasholdem/spectate/{gameName}": { + "/idiot/spectate/{gameName}": { "get": { "tags": [ - "TexasHoldEm" + "Idiot" ], "parameters": [ { @@ -3929,10 +3917,10 @@ } } }, - "/texasholdem/spectate/{connectionId}/finish": { + "/idiot/spectate/{connectionId}/finish": { "get": { "tags": [ - "TexasHoldEm" + "Idiot" ], "parameters": [ { @@ -3952,10 +3940,10 @@ } } }, - "/uno/description": { + "/meta/messages": { "get": { "tags": [ - "Uno" + "Meta" ], "responses": { "200": { @@ -3964,10 +3952,22 @@ } } }, - "/uno/metadata": { + "/texasholdem/description": { "get": { "tags": [ - "Uno" + "TexasHoldEm" + ], + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/texasholdem/metadata": { + "get": { + "tags": [ + "TexasHoldEm" ], "responses": { "200": { @@ -3993,10 +3993,10 @@ } } }, - "/uno": { + "/texasholdem": { "get": { "tags": [ - "Uno" + "TexasHoldEm" ], "responses": { "200": { @@ -4022,10 +4022,10 @@ } } }, - "/uno/games": { + "/texasholdem/games": { "get": { "tags": [ - "Uno" + "TexasHoldEm" ], "responses": { "200": { @@ -4060,10 +4060,10 @@ } } }, - "/uno/games/{name}": { + "/texasholdem/games/{name}": { "get": { "tags": [ - "Uno" + "TexasHoldEm" ], "parameters": [ { @@ -4120,7 +4120,7 @@ }, "delete": { "tags": [ - "Uno" + "TexasHoldEm" ], "parameters": [ { @@ -4176,10 +4176,10 @@ } } }, - "/uno/games/{name}/bot": { + "/texasholdem/games/{name}/bot": { "post": { "tags": [ - "Uno" + "TexasHoldEm" ], "parameters": [ { @@ -4215,10 +4215,10 @@ } } }, - "/uno/previousgames": { + "/texasholdem/previousgames": { "get": { "tags": [ - "Uno" + "TexasHoldEm" ], "responses": { "200": { @@ -4228,7 +4228,7 @@ "schema": { "type": "array", "items": { - "$ref": "#/components/schemas/Uno.UnoGame" + "$ref": "#/components/schemas/TexasHoldEm.TexasHoldEmGame" } } }, @@ -4236,7 +4236,7 @@ "schema": { "type": "array", "items": { - "$ref": "#/components/schemas/Uno.UnoGame" + "$ref": "#/components/schemas/TexasHoldEm.TexasHoldEmGame" } } }, @@ -4244,7 +4244,7 @@ "schema": { "type": "array", "items": { - "$ref": "#/components/schemas/Uno.UnoGame" + "$ref": "#/components/schemas/TexasHoldEm.TexasHoldEmGame" } } } @@ -4253,10 +4253,10 @@ } } }, - "/uno/previousgames/{id}": { + "/texasholdem/previousgames/{id}": { "get": { "tags": [ - "Uno" + "TexasHoldEm" ], "parameters": [ { @@ -4275,17 +4275,17 @@ "content": { "text/plain": { "schema": { - "$ref": "#/components/schemas/Data.HistoricUnoGame" + "$ref": "#/components/schemas/Data.HistoricTexasHoldEmGame" } }, "application/json": { "schema": { - "$ref": "#/components/schemas/Data.HistoricUnoGame" + "$ref": "#/components/schemas/Data.HistoricTexasHoldEmGame" } }, "text/json": { "schema": { - "$ref": "#/components/schemas/Data.HistoricUnoGame" + "$ref": "#/components/schemas/Data.HistoricTexasHoldEmGame" } } } @@ -4293,10 +4293,10 @@ } } }, - "/uno/previousgames/{id}/{version}": { + "/texasholdem/previousgames/{id}/{version}": { "get": { "tags": [ - "Uno" + "TexasHoldEm" ], "parameters": [ { @@ -4324,17 +4324,17 @@ "content": { "text/plain": { "schema": { - "$ref": "#/components/schemas/Data.HistoricUnoGame" + "$ref": "#/components/schemas/Data.HistoricTexasHoldEmGame" } }, "application/json": { "schema": { - "$ref": "#/components/schemas/Data.HistoricUnoGame" + "$ref": "#/components/schemas/Data.HistoricTexasHoldEmGame" } }, "text/json": { "schema": { - "$ref": "#/components/schemas/Data.HistoricUnoGame" + "$ref": "#/components/schemas/Data.HistoricTexasHoldEmGame" } } } @@ -4342,10 +4342,10 @@ } } }, - "/uno/create/{name}": { + "/texasholdem/create/{name}": { "post": { "tags": [ - "Uno" + "TexasHoldEm" ], "parameters": [ { @@ -4401,10 +4401,10 @@ } } }, - "/uno/create": { + "/texasholdem/create": { "post": { "tags": [ - "Uno" + "TexasHoldEm" ], "responses": { "200": { @@ -4450,10 +4450,10 @@ } } }, - "/uno/games/{name}/start": { + "/texasholdem/games/{name}/start": { "post": { "tags": [ - "Uno" + "TexasHoldEm" ], "parameters": [ { @@ -4509,10 +4509,10 @@ } } }, - "/uno/join/{gameName}": { + "/texasholdem/join/{gameName}": { "get": { "tags": [ - "Uno" + "TexasHoldEm" ], "parameters": [ { @@ -4531,10 +4531,10 @@ } } }, - "/uno/join/{connectionId}/finish": { + "/texasholdem/join/{connectionId}/finish": { "get": { "tags": [ - "Uno" + "TexasHoldEm" ], "parameters": [ { @@ -4554,10 +4554,10 @@ } } }, - "/uno/spectate/{gameName}": { + "/texasholdem/spectate/{gameName}": { "get": { "tags": [ - "Uno" + "TexasHoldEm" ], "parameters": [ { @@ -4576,10 +4576,10 @@ } } }, - "/uno/spectate/{connectionId}/finish": { + "/texasholdem/spectate/{connectionId}/finish": { "get": { "tags": [ - "Uno" + "TexasHoldEm" ], "parameters": [ { @@ -4599,22 +4599,10 @@ } } }, - "/me": { - "get": { - "tags": [ - "User" - ], - "responses": { - "200": { - "description": "OK" - } - } - } - }, - "/yaniv/description": { + "/uno/description": { "get": { "tags": [ - "Yaniv" + "Uno" ], "responses": { "200": { @@ -4623,10 +4611,10 @@ } } }, - "/yaniv/metadata": { + "/uno/metadata": { "get": { "tags": [ - "Yaniv" + "Uno" ], "responses": { "200": { @@ -4652,10 +4640,10 @@ } } }, - "/yaniv": { + "/uno": { "get": { "tags": [ - "Yaniv" + "Uno" ], "responses": { "200": { @@ -4681,10 +4669,10 @@ } } }, - "/yaniv/games": { + "/uno/games": { "get": { "tags": [ - "Yaniv" + "Uno" ], "responses": { "200": { @@ -4719,10 +4707,10 @@ } } }, - "/yaniv/games/{name}": { + "/uno/games/{name}": { "get": { "tags": [ - "Yaniv" + "Uno" ], "parameters": [ { @@ -4779,7 +4767,7 @@ }, "delete": { "tags": [ - "Yaniv" + "Uno" ], "parameters": [ { @@ -4835,10 +4823,10 @@ } } }, - "/yaniv/games/{name}/bot": { + "/uno/games/{name}/bot": { "post": { "tags": [ - "Yaniv" + "Uno" ], "parameters": [ { @@ -4874,10 +4862,10 @@ } } }, - "/yaniv/previousgames": { + "/uno/previousgames": { "get": { "tags": [ - "Yaniv" + "Uno" ], "responses": { "200": { @@ -4887,7 +4875,7 @@ "schema": { "type": "array", "items": { - "$ref": "#/components/schemas/Yaniv.YanivGame" + "$ref": "#/components/schemas/Uno.UnoGame" } } }, @@ -4895,7 +4883,7 @@ "schema": { "type": "array", "items": { - "$ref": "#/components/schemas/Yaniv.YanivGame" + "$ref": "#/components/schemas/Uno.UnoGame" } } }, @@ -4903,7 +4891,7 @@ "schema": { "type": "array", "items": { - "$ref": "#/components/schemas/Yaniv.YanivGame" + "$ref": "#/components/schemas/Uno.UnoGame" } } } @@ -4912,10 +4900,10 @@ } } }, - "/yaniv/previousgames/{id}": { + "/uno/previousgames/{id}": { "get": { "tags": [ - "Yaniv" + "Uno" ], "parameters": [ { @@ -4934,17 +4922,17 @@ "content": { "text/plain": { "schema": { - "$ref": "#/components/schemas/Data.HistoricYanivGame" + "$ref": "#/components/schemas/Data.HistoricUnoGame" } }, "application/json": { "schema": { - "$ref": "#/components/schemas/Data.HistoricYanivGame" + "$ref": "#/components/schemas/Data.HistoricUnoGame" } }, "text/json": { "schema": { - "$ref": "#/components/schemas/Data.HistoricYanivGame" + "$ref": "#/components/schemas/Data.HistoricUnoGame" } } } @@ -4952,10 +4940,10 @@ } } }, - "/yaniv/previousgames/{id}/{version}": { + "/uno/previousgames/{id}/{version}": { "get": { "tags": [ - "Yaniv" + "Uno" ], "parameters": [ { @@ -4983,17 +4971,17 @@ "content": { "text/plain": { "schema": { - "$ref": "#/components/schemas/Data.HistoricYanivGame" + "$ref": "#/components/schemas/Data.HistoricUnoGame" } }, "application/json": { "schema": { - "$ref": "#/components/schemas/Data.HistoricYanivGame" + "$ref": "#/components/schemas/Data.HistoricUnoGame" } }, "text/json": { "schema": { - "$ref": "#/components/schemas/Data.HistoricYanivGame" + "$ref": "#/components/schemas/Data.HistoricUnoGame" } } } @@ -5001,10 +4989,10 @@ } } }, - "/yaniv/create/{name}": { + "/uno/create/{name}": { "post": { "tags": [ - "Yaniv" + "Uno" ], "parameters": [ { @@ -5060,10 +5048,10 @@ } } }, - "/yaniv/create": { + "/uno/create": { "post": { "tags": [ - "Yaniv" + "Uno" ], "responses": { "200": { @@ -5109,10 +5097,10 @@ } } }, - "/yaniv/games/{name}/start": { + "/uno/games/{name}/start": { "post": { "tags": [ - "Yaniv" + "Uno" ], "parameters": [ { @@ -5168,10 +5156,10 @@ } } }, - "/yaniv/join/{gameName}": { + "/uno/join/{gameName}": { "get": { "tags": [ - "Yaniv" + "Uno" ], "parameters": [ { @@ -5190,10 +5178,10 @@ } } }, - "/yaniv/join/{connectionId}/finish": { + "/uno/join/{connectionId}/finish": { "get": { "tags": [ - "Yaniv" + "Uno" ], "parameters": [ { @@ -5213,10 +5201,10 @@ } } }, - "/yaniv/spectate/{gameName}": { + "/uno/spectate/{gameName}": { "get": { "tags": [ - "Yaniv" + "Uno" ], "parameters": [ { @@ -5235,10 +5223,10 @@ } } }, - "/yaniv/spectate/{connectionId}/finish": { + "/uno/spectate/{connectionId}/finish": { "get": { "tags": [ - "Yaniv" + "Uno" ], "parameters": [ { @@ -5257,61 +5245,1499 @@ } } } - } - }, - "components": { - "schemas": { - "Bullshit.BullshitBroadcastNotification": { - "allOf": [ - { - "$ref": "#/components/schemas/Protocol.DecksterNotification" - }, - { - "required": [ - "actualCard", - "claimedToBeCard", - "playerId", - "punishmentCardCount" - ], - "type": "object", - "properties": { - "playerId": { - "type": "string", - "format": "uuid" - }, - "claimedToBeCard": { - "$ref": "#/components/schemas/Common.Card" + }, + "/me": { + "get": { + "tags": [ + "User" + ], + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/yaniv/description": { + "get": { + "tags": [ + "Yaniv" + ], + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/yaniv/metadata": { + "get": { + "tags": [ + "Yaniv" + ], + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/Meta.GameMeta" + } }, - "actualCard": { - "$ref": "#/components/schemas/Common.Card" + "application/json": { + "schema": { + "$ref": "#/components/schemas/Meta.GameMeta" + } }, - "punishmentCardCount": { - "type": "integer", - "format": "int32" + "text/json": { + "schema": { + "$ref": "#/components/schemas/Meta.GameMeta" + } } - }, - "additionalProperties": false + } } - ] - }, - "Bullshit.BullshitGame": { - "allOf": [ - { - "$ref": "#/components/schemas/Games.GameObject" - }, - { - "required": [ - "cardsDrawn", - "currentPlayer", - "currentPlayerIndex", - "deck", - "discardPile", - "donePlayers", - "players", - "stockPile" - ], + } + } + }, + "/yaniv": { + "get": { + "tags": [ + "Yaniv" + ], + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/Controllers.GameOverviewVm" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/Controllers.GameOverviewVm" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/Controllers.GameOverviewVm" + } + } + } + } + } + } + }, + "/yaniv/games": { + "get": { + "tags": [ + "Yaniv" + ], + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Controllers.GameVm" + } + } + }, + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Controllers.GameVm" + } + } + }, + "text/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Controllers.GameVm" + } + } + } + } + } + } + } + }, + "/yaniv/games/{name}": { + "get": { + "tags": [ + "Yaniv" + ], + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/Controllers.GameVm" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/Controllers.GameVm" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/Controllers.GameVm" + } + } + } + }, + "404": { + "description": "Not Found", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/Controllers.ResponseMessage" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/Controllers.ResponseMessage" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/Controllers.ResponseMessage" + } + } + } + } + } + }, + "delete": { + "tags": [ + "Yaniv" + ], + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/Controllers.GameVm" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/Controllers.GameVm" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/Controllers.GameVm" + } + } + } + }, + "404": { + "description": "Not Found", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/Controllers.ResponseMessage" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/Controllers.ResponseMessage" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/Controllers.ResponseMessage" + } + } + } + } + } + } + }, + "/yaniv/games/{name}/bot": { + "post": { + "tags": [ + "Yaniv" + ], + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/Controllers.ResponseMessage" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/Controllers.ResponseMessage" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/Controllers.ResponseMessage" + } + } + } + } + } + } + }, + "/yaniv/previousgames": { + "get": { + "tags": [ + "Yaniv" + ], + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Yaniv.YanivGame" + } + } + }, + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Yaniv.YanivGame" + } + } + }, + "text/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Yaniv.YanivGame" + } + } + } + } + } + } + } + }, + "/yaniv/previousgames/{id}": { + "get": { + "tags": [ + "Yaniv" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/Data.HistoricYanivGame" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/Data.HistoricYanivGame" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/Data.HistoricYanivGame" + } + } + } + } + } + } + }, + "/yaniv/previousgames/{id}/{version}": { + "get": { + "tags": [ + "Yaniv" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "version", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "format": "int64" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/Data.HistoricYanivGame" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/Data.HistoricYanivGame" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/Data.HistoricYanivGame" + } + } + } + } + } + } + }, + "/yaniv/create/{name}": { + "post": { + "tags": [ + "Yaniv" + ], + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/Core.GameInfo" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/Core.GameInfo" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/Core.GameInfo" + } + } + } + }, + "400": { + "description": "Bad Request", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/Controllers.ResponseMessage" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/Controllers.ResponseMessage" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/Controllers.ResponseMessage" + } + } + } + } + } + } + }, + "/yaniv/create": { + "post": { + "tags": [ + "Yaniv" + ], + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/Core.GameInfo" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/Core.GameInfo" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/Core.GameInfo" + } + } + } + }, + "400": { + "description": "Bad Request", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/Controllers.ResponseMessage" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/Controllers.ResponseMessage" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/Controllers.ResponseMessage" + } + } + } + } + } + } + }, + "/yaniv/games/{name}/start": { + "post": { + "tags": [ + "Yaniv" + ], + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/Core.GameInfo" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/Core.GameInfo" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/Core.GameInfo" + } + } + } + }, + "404": { + "description": "Not Found", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/Controllers.ResponseMessage" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/Controllers.ResponseMessage" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/Controllers.ResponseMessage" + } + } + } + } + } + } + }, + "/yaniv/join/{gameName}": { + "get": { + "tags": [ + "Yaniv" + ], + "parameters": [ + { + "name": "gameName", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/yaniv/join/{connectionId}/finish": { + "get": { + "tags": [ + "Yaniv" + ], + "parameters": [ + { + "name": "connectionId", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/yaniv/spectate/{gameName}": { + "get": { + "tags": [ + "Yaniv" + ], + "parameters": [ + { + "name": "gameName", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/yaniv/spectate/{connectionId}/finish": { + "get": { + "tags": [ + "Yaniv" + ], + "parameters": [ + { + "name": "connectionId", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + } + } + }, + "components": { + "schemas": { + "Bullshit.BullshitBroadcastNotification": { + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterNotification" + }, + { + "required": [ + "actualCard", + "claimedToBeCard", + "playerId", + "punishmentCardCount" + ], + "type": "object", + "properties": { + "playerId": { + "type": "string", + "format": "uuid" + }, + "claimedToBeCard": { + "$ref": "#/components/schemas/Common.Card" + }, + "actualCard": { + "$ref": "#/components/schemas/Common.Card" + }, + "punishmentCardCount": { + "type": "integer", + "format": "int32" + } + }, + "additionalProperties": false + } + ] + }, + "Bullshit.BullshitGame": { + "allOf": [ + { + "$ref": "#/components/schemas/Games.GameObject" + }, + { + "required": [ + "cardsDrawn", + "currentPlayer", + "currentPlayerIndex", + "deck", + "discardPile", + "donePlayers", + "players", + "stockPile" + ], + "type": "object", + "properties": { + "deck": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Common.Card" + } + }, + "stockPile": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Common.Card" + } + }, + "discardPile": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Common.Card" + } + }, + "players": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Bullshit.BullshitPlayer" + } + }, + "donePlayers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Bullshit.BullshitPlayer" + } + }, + "currentPlayerIndex": { + "type": "integer", + "format": "int32" + }, + "claimedTopOfPile": { + "$ref": "#/components/schemas/Common.Card" + }, + "actualTopOfPile": { + "$ref": "#/components/schemas/Common.Card" + }, + "cardsDrawn": { + "type": "integer", + "format": "int32" + }, + "potentialBullshit": { + "$ref": "#/components/schemas/Bullshit.PotentialBullshit" + }, + "currentPlayer": { + "$ref": "#/components/schemas/Bullshit.BullshitPlayer" + } + }, + "additionalProperties": false + } + ] + }, + "Bullshit.BullshitPlayer": { + "required": [ + "cards", + "id", + "name" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "cards": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Common.Card" + } + } + }, + "additionalProperties": false + }, + "Bullshit.BullshitPlayerNotification": { + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterNotification" + }, + { + "required": [ + "calledByPlayerId", + "card", + "punishmentCards" + ], + "type": "object", + "properties": { + "calledByPlayerId": { + "type": "string", + "format": "uuid" + }, + "card": { + "$ref": "#/components/schemas/Common.Card" + }, + "punishmentCards": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Common.Card" + } + } + }, + "additionalProperties": false + } + ] + }, + "Bullshit.BullshitRequest": { + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterRequest" + }, + { + "type": "object", + "additionalProperties": false + } + ] + }, + "Bullshit.BullshitResponse": { + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterResponse" + }, + { + "required": [ + "punishmentCards" + ], + "type": "object", + "properties": { + "punishmentCards": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Common.Card" + } + } + }, + "additionalProperties": false + } + ] + }, + "Bullshit.CardResponse": { + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterResponse" + }, + { + "required": [ + "card" + ], + "type": "object", + "properties": { + "card": { + "$ref": "#/components/schemas/Common.Card" + } + }, + "additionalProperties": false + } + ] + }, + "Bullshit.DiscardPileShuffledNotification": { + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterNotification" + }, + { + "type": "object", + "additionalProperties": false + } + ] + }, + "Bullshit.DrawCardRequest": { + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterRequest" + }, + { + "type": "object", + "additionalProperties": false + } + ] + }, + "Bullshit.FalseBullshitCallNotification": { + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterNotification" + }, + { + "required": [ + "accusedPlayerId", + "playerId", + "punishmentCardCount" + ], + "type": "object", + "properties": { + "playerId": { + "type": "string", + "format": "uuid" + }, + "accusedPlayerId": { + "type": "string", + "format": "uuid" + }, + "punishmentCardCount": { + "type": "integer", + "format": "int32" + } + }, + "additionalProperties": false + } + ] + }, + "Bullshit.GameEndedNotification": { + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterNotification" + }, + { + "required": [ + "loserId", + "loserName", + "players" + ], + "type": "object", + "properties": { + "players": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Common.PlayerData" + } + }, + "loserId": { + "type": "string", + "format": "uuid" + }, + "loserName": { + "type": "string" + } + }, + "additionalProperties": false + } + ] + }, + "Bullshit.GameStartedNotification": { + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterNotification" + }, + { + "required": [ + "gameId", + "playerViewOfGame" + ], + "type": "object", + "properties": { + "gameId": { + "type": "string", + "format": "uuid" + }, + "playerViewOfGame": { + "$ref": "#/components/schemas/Bullshit.PlayerViewOfGame" + } + }, + "additionalProperties": false + } + ] + }, + "Bullshit.ItsPlayersTurnNotification": { + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterNotification" + }, + { + "required": [ + "playerId" + ], + "type": "object", + "properties": { + "playerId": { + "type": "string", + "format": "uuid" + } + }, + "additionalProperties": false + } + ] + }, + "Bullshit.ItsYourTurnNotification": { + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterNotification" + }, + { + "type": "object", + "additionalProperties": false + } + ] + }, + "Bullshit.OtherBullshitPlayer": { + "required": [ + "name", + "numberOfCards", + "playerId" + ], + "type": "object", + "properties": { + "playerId": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "numberOfCards": { + "type": "integer", + "format": "int32" + } + }, + "additionalProperties": false + }, + "Bullshit.PassRequest": { + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterRequest" + }, + { + "type": "object", + "additionalProperties": false + } + ] + }, + "Bullshit.PlayerDrewCardNotification": { + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterNotification" + }, + { + "required": [ + "playerId" + ], + "type": "object", + "properties": { + "playerId": { + "type": "string", + "format": "uuid" + } + }, + "additionalProperties": false + } + ] + }, + "Bullshit.PlayerIsDoneNotification": { + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterNotification" + }, + { + "required": [ + "playerId" + ], + "type": "object", + "properties": { + "playerId": { + "type": "string", + "format": "uuid" + } + }, + "additionalProperties": false + } + ] + }, + "Bullshit.PlayerPassedNotification": { + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterNotification" + }, + { + "required": [ + "playerId" + ], + "type": "object", + "properties": { + "playerId": { + "type": "string", + "format": "uuid" + } + }, + "additionalProperties": false + } + ] + }, + "Bullshit.PlayerPutCardNotification": { + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterNotification" + }, + { + "required": [ + "claimedToBeCard", + "playerId" + ], + "type": "object", + "properties": { + "playerId": { + "type": "string", + "format": "uuid" + }, + "claimedToBeCard": { + "$ref": "#/components/schemas/Common.Card" + } + }, + "additionalProperties": false + } + ] + }, + "Bullshit.PlayerViewOfGame": { + "required": [ + "cards", + "discardPileCount", + "otherPlayers", + "stockPileCount" + ], + "type": "object", + "properties": { + "cards": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Common.Card" + } + }, + "claimedTopOfPile": { + "$ref": "#/components/schemas/Common.Card" + }, + "stockPileCount": { + "type": "integer", + "format": "int32" + }, + "discardPileCount": { + "type": "integer", + "format": "int32" + }, + "otherPlayers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Bullshit.OtherBullshitPlayer" + } + } + }, + "additionalProperties": false + }, + "Bullshit.PotentialBullshit": { + "required": [ + "claimedToBeCard", + "playerId" + ], + "type": "object", + "properties": { + "playerId": { + "type": "string", + "format": "uuid" + }, + "claimedToBeCard": { + "$ref": "#/components/schemas/Common.Card" + } + }, + "additionalProperties": false + }, + "Bullshit.PutCardRequest": { + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterRequest" + }, + { + "required": [ + "actualCard", + "claimedToBeCard" + ], + "type": "object", + "properties": { + "actualCard": { + "$ref": "#/components/schemas/Common.Card" + }, + "claimedToBeCard": { + "$ref": "#/components/schemas/Common.Card" + } + }, + "additionalProperties": false + } + ] + }, + "ChatRoom.ChatNotification": { + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterNotification" + }, + { + "required": [ + "message", + "sender" + ], + "type": "object", + "properties": { + "sender": { + "type": "string" + }, + "message": { + "type": "string" + } + }, + "additionalProperties": false + } + ] + }, + "ChatRoom.ChatResponse": { + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterResponse" + }, + { + "type": "object", + "additionalProperties": false + } + ] + }, + "ChatRoom.ChatRoom": { + "allOf": [ + { + "$ref": "#/components/schemas/Games.GameObject" + }, + { + "required": [ + "transcript" + ], + "type": "object", + "properties": { + "transcript": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ChatRoom.SendChatRequest" + } + } + }, + "additionalProperties": false + } + ] + }, + "ChatRoom.SendChatRequest": { + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterRequest" + }, + { + "required": [ + "message" + ], + "type": "object", + "properties": { + "message": { + "type": "string" + } + }, + "additionalProperties": false + } + ] + }, + "Common.Card": { + "required": [ + "rank", + "suit" + ], + "type": "object", + "properties": { + "rank": { + "type": "integer", + "format": "int32" + }, + "suit": { + "$ref": "#/components/schemas/Common.Suit" + } + }, + "additionalProperties": false + }, + "Common.EmptyResponse": { + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterResponse" + }, + { + "type": "object", + "additionalProperties": false + } + ] + }, + "Common.PlayerData": { + "required": [ + "cardsInHand", + "id", + "info", + "name", + "points" + ], + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "points": { + "type": "number", + "format": "double" + }, + "cardsInHand": { + "type": "integer", + "format": "int32" + }, + "id": { + "type": "string", + "format": "uuid" + }, + "info": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "additionalProperties": false + }, + "Common.Suit": { + "enum": [ + "Clubs", + "Diamonds", + "Hearts", + "Spades" + ], + "type": "string" + }, + "Controllers.GameOverviewVm": { + "required": [ + "games", + "gameType" + ], + "type": "object", + "properties": { + "gameType": { + "type": "string" + }, + "games": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Controllers.GameVm" + } + } + }, + "additionalProperties": false + }, + "Controllers.GameVm": { + "required": [ + "gameType", + "name", + "players", + "state" + ], + "type": "object", + "properties": { + "gameType": { + "type": "string" + }, + "name": { + "type": "string" + }, + "state": { + "$ref": "#/components/schemas/Games.GameState" + }, + "players": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Common.PlayerData" + } + } + }, + "additionalProperties": false + }, + "Controllers.LoginModel": { + "type": "object", + "properties": { + "username": { + "type": "string", + "nullable": true + }, + "password": { + "type": "string", + "nullable": true + } + }, + "additionalProperties": false + }, + "Controllers.ResponseMessage": { + "type": "object", + "properties": { + "message": { + "type": "string", + "nullable": true + } + }, + "additionalProperties": false + }, + "Core.GameInfo": { + "required": [ + "id" + ], + "type": "object", + "properties": { + "id": { + "type": "string" + } + }, + "additionalProperties": false + }, + "CrazyEights.CardResponse": { + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterResponse" + }, + { + "required": [ + "card" + ], + "type": "object", + "properties": { + "card": { + "$ref": "#/components/schemas/Common.Card" + } + }, + "additionalProperties": false + } + ] + }, + "CrazyEights.CrazyEightsGame": { + "allOf": [ + { + "$ref": "#/components/schemas/Games.GameObject" + }, + { + "required": [ + "cardsDrawn", + "currentPlayer", + "currentPlayerIndex", + "currentSuit", + "deck", + "discardPile", + "donePlayers", + "initialCardsPerPlayer", + "players", + "spectators", + "stockPile", + "topOfPile" + ], "type": "object", "properties": { + "initialCardsPerPlayer": { + "type": "integer", + "format": "int32" + }, + "currentPlayerIndex": { + "type": "integer", + "format": "int32" + }, + "cardsDrawn": { + "type": "integer", + "format": "int32" + }, + "donePlayers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CrazyEights.CrazyEightsPlayer" + } + }, "deck": { "type": "array", "items": { @@ -5333,41 +6759,33 @@ "players": { "type": "array", "items": { - "$ref": "#/components/schemas/Bullshit.BullshitPlayer" + "$ref": "#/components/schemas/CrazyEights.CrazyEightsPlayer" } }, - "donePlayers": { + "spectators": { "type": "array", "items": { - "$ref": "#/components/schemas/Bullshit.BullshitPlayer" + "$ref": "#/components/schemas/CrazyEights.CrazyEightsSpectator" } }, - "currentPlayerIndex": { - "type": "integer", - "format": "int32" - }, - "claimedTopOfPile": { - "$ref": "#/components/schemas/Common.Card" + "newSuit": { + "$ref": "#/components/schemas/Common.Suit" }, - "actualTopOfPile": { + "topOfPile": { "$ref": "#/components/schemas/Common.Card" }, - "cardsDrawn": { - "type": "integer", - "format": "int32" - }, - "potentialBullshit": { - "$ref": "#/components/schemas/Bullshit.PotentialBullshit" + "currentSuit": { + "$ref": "#/components/schemas/Common.Suit" }, "currentPlayer": { - "$ref": "#/components/schemas/Bullshit.BullshitPlayer" + "$ref": "#/components/schemas/CrazyEights.CrazyEightsPlayer" } }, "additionalProperties": false } ] }, - "Bullshit.BullshitPlayer": { + "CrazyEights.CrazyEightsPlayer": { "required": [ "cards", "id", @@ -5391,90 +6809,24 @@ }, "additionalProperties": false }, - "Bullshit.BullshitPlayerNotification": { - "allOf": [ - { - "$ref": "#/components/schemas/Protocol.DecksterNotification" - }, - { - "required": [ - "calledByPlayerId", - "card", - "punishmentCards" - ], - "type": "object", - "properties": { - "calledByPlayerId": { - "type": "string", - "format": "uuid" - }, - "card": { - "$ref": "#/components/schemas/Common.Card" - }, - "punishmentCards": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Common.Card" - } - } - }, - "additionalProperties": false - } - ] - }, - "Bullshit.BullshitRequest": { - "allOf": [ - { - "$ref": "#/components/schemas/Protocol.DecksterRequest" - }, - { - "type": "object", - "additionalProperties": false - } - ] - }, - "Bullshit.BullshitResponse": { - "allOf": [ - { - "$ref": "#/components/schemas/Protocol.DecksterResponse" - }, - { - "required": [ - "punishmentCards" - ], - "type": "object", - "properties": { - "punishmentCards": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Common.Card" - } - } - }, - "additionalProperties": false - } - ] - }, - "Bullshit.CardResponse": { - "allOf": [ - { - "$ref": "#/components/schemas/Protocol.DecksterResponse" + "CrazyEights.CrazyEightsSpectator": { + "required": [ + "id", + "name" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" }, - { - "required": [ - "card" - ], - "type": "object", - "properties": { - "card": { - "$ref": "#/components/schemas/Common.Card" - } - }, - "additionalProperties": false + "name": { + "type": "string" } - ] + }, + "additionalProperties": false }, - "Bullshit.DiscardPileShuffledNotification": { + "CrazyEights.DiscardPileShuffledNotification": { "allOf": [ { "$ref": "#/components/schemas/Protocol.DecksterNotification" @@ -5485,7 +6837,7 @@ } ] }, - "Bullshit.DrawCardRequest": { + "CrazyEights.DrawCardRequest": { "allOf": [ { "$ref": "#/components/schemas/Protocol.DecksterRequest" @@ -5496,37 +6848,7 @@ } ] }, - "Bullshit.FalseBullshitCallNotification": { - "allOf": [ - { - "$ref": "#/components/schemas/Protocol.DecksterNotification" - }, - { - "required": [ - "accusedPlayerId", - "playerId", - "punishmentCardCount" - ], - "type": "object", - "properties": { - "playerId": { - "type": "string", - "format": "uuid" - }, - "accusedPlayerId": { - "type": "string", - "format": "uuid" - }, - "punishmentCardCount": { - "type": "integer", - "format": "int32" - } - }, - "additionalProperties": false - } - ] - }, - "Bullshit.GameEndedNotification": { + "CrazyEights.GameEndedNotification": { "allOf": [ { "$ref": "#/components/schemas/Protocol.DecksterNotification" @@ -5557,7 +6879,7 @@ } ] }, - "Bullshit.GameStartedNotification": { + "CrazyEights.GameStartedNotification": { "allOf": [ { "$ref": "#/components/schemas/Protocol.DecksterNotification" @@ -5574,14 +6896,14 @@ "format": "uuid" }, "playerViewOfGame": { - "$ref": "#/components/schemas/Bullshit.PlayerViewOfGame" + "$ref": "#/components/schemas/CrazyEights.PlayerViewOfGame" } }, "additionalProperties": false } ] }, - "Bullshit.ItsPlayersTurnNotification": { + "CrazyEights.ItsPlayersTurnNotification": { "allOf": [ { "$ref": "#/components/schemas/Protocol.DecksterNotification" @@ -5601,18 +6923,26 @@ } ] }, - "Bullshit.ItsYourTurnNotification": { + "CrazyEights.ItsYourTurnNotification": { "allOf": [ { "$ref": "#/components/schemas/Protocol.DecksterNotification" }, { + "required": [ + "playerViewOfGame" + ], "type": "object", + "properties": { + "playerViewOfGame": { + "$ref": "#/components/schemas/CrazyEights.PlayerViewOfGame" + } + }, "additionalProperties": false } ] }, - "Bullshit.OtherBullshitPlayer": { + "CrazyEights.OtherCrazyEightsPlayer": { "required": [ "name", "numberOfCards", @@ -5634,7 +6964,7 @@ }, "additionalProperties": false }, - "Bullshit.PassRequest": { + "CrazyEights.PassRequest": { "allOf": [ { "$ref": "#/components/schemas/Protocol.DecksterRequest" @@ -5645,7 +6975,7 @@ } ] }, - "Bullshit.PlayerDrewCardNotification": { + "CrazyEights.PlayerDrewCardNotification": { "allOf": [ { "$ref": "#/components/schemas/Protocol.DecksterNotification" @@ -5665,7 +6995,7 @@ } ] }, - "Bullshit.PlayerIsDoneNotification": { + "CrazyEights.PlayerIsDoneNotification": { "allOf": [ { "$ref": "#/components/schemas/Protocol.DecksterNotification" @@ -5685,7 +7015,7 @@ } ] }, - "Bullshit.PlayerPassedNotification": { + "CrazyEights.PlayerPassedNotification": { "allOf": [ { "$ref": "#/components/schemas/Protocol.DecksterNotification" @@ -5705,14 +7035,14 @@ } ] }, - "Bullshit.PlayerPutCardNotification": { + "CrazyEights.PlayerPutCardNotification": { "allOf": [ { "$ref": "#/components/schemas/Protocol.DecksterNotification" }, { "required": [ - "claimedToBeCard", + "card", "playerId" ], "type": "object", @@ -5721,7 +7051,7 @@ "type": "string", "format": "uuid" }, - "claimedToBeCard": { + "card": { "$ref": "#/components/schemas/Common.Card" } }, @@ -5729,314 +7059,264 @@ } ] }, - "Bullshit.PlayerViewOfGame": { - "required": [ - "cards", - "discardPileCount", - "otherPlayers", - "stockPileCount" - ], - "type": "object", - "properties": { - "cards": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Common.Card" - } - }, - "claimedTopOfPile": { - "$ref": "#/components/schemas/Common.Card" - }, - "stockPileCount": { - "type": "integer", - "format": "int32" - }, - "discardPileCount": { - "type": "integer", - "format": "int32" - }, - "otherPlayers": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Bullshit.OtherBullshitPlayer" - } - } - }, - "additionalProperties": false - }, - "Bullshit.PotentialBullshit": { - "required": [ - "claimedToBeCard", - "playerId" - ], - "type": "object", - "properties": { - "playerId": { - "type": "string", - "format": "uuid" - }, - "claimedToBeCard": { - "$ref": "#/components/schemas/Common.Card" - } - }, - "additionalProperties": false - }, - "Bullshit.PutCardRequest": { + "CrazyEights.PlayerPutEightNotification": { "allOf": [ { - "$ref": "#/components/schemas/Protocol.DecksterRequest" + "$ref": "#/components/schemas/Protocol.DecksterNotification" }, { "required": [ - "actualCard", - "claimedToBeCard" + "card", + "newSuit", + "playerId" ], "type": "object", "properties": { - "actualCard": { - "$ref": "#/components/schemas/Common.Card" + "playerId": { + "type": "string", + "format": "uuid" }, - "claimedToBeCard": { + "card": { "$ref": "#/components/schemas/Common.Card" + }, + "newSuit": { + "$ref": "#/components/schemas/Common.Suit" } }, "additionalProperties": false } ] }, - "ChatRoom.ChatNotification": { + "CrazyEights.PlayerViewOfGame": { "allOf": [ { - "$ref": "#/components/schemas/Protocol.DecksterNotification" + "$ref": "#/components/schemas/Protocol.DecksterResponse" }, { "required": [ - "message", - "sender" + "cards", + "currentSuit", + "discardPileCount", + "otherPlayers", + "stockPileCount", + "topOfPile" ], "type": "object", "properties": { - "sender": { - "type": "string" + "cards": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Common.Card" + } }, - "message": { - "type": "string" + "topOfPile": { + "$ref": "#/components/schemas/Common.Card" + }, + "currentSuit": { + "$ref": "#/components/schemas/Common.Suit" + }, + "stockPileCount": { + "type": "integer", + "format": "int32" + }, + "discardPileCount": { + "type": "integer", + "format": "int32" + }, + "otherPlayers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CrazyEights.OtherCrazyEightsPlayer" + } } }, "additionalProperties": false } ] }, - "ChatRoom.ChatResponse": { - "allOf": [ - { - "$ref": "#/components/schemas/Protocol.DecksterResponse" - }, - { - "type": "object", - "additionalProperties": false - } - ] - }, - "ChatRoom.ChatRoom": { + "CrazyEights.PutCardRequest": { "allOf": [ { - "$ref": "#/components/schemas/Games.GameObject" + "$ref": "#/components/schemas/Protocol.DecksterRequest" }, { "required": [ - "transcript" + "card" ], "type": "object", "properties": { - "transcript": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ChatRoom.SendChatRequest" - } + "card": { + "$ref": "#/components/schemas/Common.Card" } }, "additionalProperties": false } ] }, - "ChatRoom.SendChatRequest": { + "CrazyEights.PutEightRequest": { "allOf": [ { "$ref": "#/components/schemas/Protocol.DecksterRequest" }, { "required": [ - "message" + "card", + "newSuit" ], "type": "object", "properties": { - "message": { - "type": "string" + "card": { + "$ref": "#/components/schemas/Common.Card" + }, + "newSuit": { + "$ref": "#/components/schemas/Common.Suit" } }, "additionalProperties": false } ] }, - "Common.Card": { + "Data.DatabaseObject": { "required": [ - "rank", - "suit" + "id", + "type" ], "type": "object", "properties": { - "rank": { - "type": "integer", - "format": "int32" + "type": { + "type": "string", + "readOnly": true }, - "suit": { - "$ref": "#/components/schemas/Common.Suit" + "id": { + "type": "string", + "format": "uuid" + } + }, + "additionalProperties": false, + "discriminator": { + "propertyName": "type", + "mapping": { + "Games.GameObject": "#/components/schemas/Games.GameObject", + "Yaniv.YanivGame": "#/components/schemas/Yaniv.YanivGame", + "Uno.UnoGame": "#/components/schemas/Uno.UnoGame", + "TexasHoldEm.TexasHoldEmGame": "#/components/schemas/TexasHoldEm.TexasHoldEmGame", + "Idiot.IdiotGame": "#/components/schemas/Idiot.IdiotGame", + "Hearts.HeartsGame": "#/components/schemas/Hearts.HeartsGame", + "Gabong.GabongGame": "#/components/schemas/Gabong.GabongGame", + "CrazyEights.CrazyEightsGame": "#/components/schemas/CrazyEights.CrazyEightsGame", + "ChatRoom.ChatRoom": "#/components/schemas/ChatRoom.ChatRoom", + "Bullshit.BullshitGame": "#/components/schemas/Bullshit.BullshitGame" + } + } + }, + "Data.HistoricBullshitGame": { + "type": "object", + "properties": { + "game": { + "$ref": "#/components/schemas/Bullshit.BullshitGame" } }, "additionalProperties": false }, - "Common.EmptyResponse": { - "allOf": [ - { - "$ref": "#/components/schemas/Protocol.DecksterResponse" - }, - { - "type": "object", - "additionalProperties": false + "Data.HistoricChatRoom": { + "type": "object", + "properties": { + "game": { + "$ref": "#/components/schemas/ChatRoom.ChatRoom" } - ] + }, + "additionalProperties": false }, - "Common.PlayerData": { - "required": [ - "cardsInHand", - "id", - "info", - "name", - "points" - ], + "Data.HistoricCrazyEightsGame": { "type": "object", "properties": { - "name": { - "type": "string" - }, - "points": { - "type": "number", - "format": "double" - }, - "cardsInHand": { - "type": "integer", - "format": "int32" - }, - "id": { - "type": "string", - "format": "uuid" - }, - "info": { - "type": "object", - "additionalProperties": { - "type": "string" - } + "game": { + "$ref": "#/components/schemas/CrazyEights.CrazyEightsGame" } }, "additionalProperties": false }, - "Common.Suit": { - "enum": [ - "Clubs", - "Diamonds", - "Hearts", - "Spades" - ], - "type": "string" + "Data.HistoricGabongGame": { + "type": "object", + "properties": { + "game": { + "$ref": "#/components/schemas/Gabong.GabongGame" + } + }, + "additionalProperties": false }, - "Controllers.GameOverviewVm": { - "required": [ - "games", - "gameType" - ], + "Data.HistoricHeartsGame": { "type": "object", "properties": { - "gameType": { - "type": "string" - }, - "games": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Controllers.GameVm" - } + "game": { + "$ref": "#/components/schemas/Hearts.HeartsGame" } }, "additionalProperties": false }, - "Controllers.GameVm": { - "required": [ - "gameType", - "name", - "players", - "state" - ], + "Data.HistoricIdiotGame": { "type": "object", "properties": { - "gameType": { - "type": "string" - }, - "name": { - "type": "string" - }, - "state": { - "$ref": "#/components/schemas/Games.GameState" - }, - "players": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Common.PlayerData" - } + "game": { + "$ref": "#/components/schemas/Idiot.IdiotGame" } }, "additionalProperties": false }, - "Controllers.LoginModel": { + "Data.HistoricTexasHoldEmGame": { "type": "object", "properties": { - "username": { - "type": "string", - "nullable": true - }, - "password": { - "type": "string", - "nullable": true + "game": { + "$ref": "#/components/schemas/TexasHoldEm.TexasHoldEmGame" } }, "additionalProperties": false }, - "Controllers.ResponseMessage": { + "Data.HistoricUnoGame": { "type": "object", "properties": { - "message": { - "type": "string", - "nullable": true + "game": { + "$ref": "#/components/schemas/Uno.UnoGame" } }, "additionalProperties": false }, - "Core.GameInfo": { - "required": [ - "id" - ], + "Data.HistoricYanivGame": { "type": "object", "properties": { - "id": { - "type": "string" + "game": { + "$ref": "#/components/schemas/Yaniv.YanivGame" } }, "additionalProperties": false }, - "CrazyEights.CardResponse": { + "Gabong.ActionResponse": { "allOf": [ { "$ref": "#/components/schemas/Protocol.DecksterResponse" }, + { + "type": "object", + "additionalProperties": false + } + ] + }, + "Gabong.DrawCardRequest": { + "allOf": [ + { + "$ref": "#/components/schemas/Gabong.GabongRequest" + }, + { + "type": "object", + "additionalProperties": false + } + ] + }, + "Gabong.GabongCardResponse": { + "allOf": [ + { + "$ref": "#/components/schemas/Gabong.GabongResponse" + }, { "required": [ "card" @@ -6051,7 +7331,7 @@ } ] }, - "CrazyEights.CrazyEightsGame": { + "Gabong.GabongGame": { "allOf": [ { "$ref": "#/components/schemas/Games.GameObject" @@ -6059,25 +7339,26 @@ { "required": [ "cardsDrawn", + "cardsToDraw", "currentPlayer", - "currentPlayerIndex", "currentSuit", "deck", "discardPile", - "donePlayers", - "initialCardsPerPlayer", + "gabongMasterId", + "gameDirection", + "isBetweenRounds", + "lastPlayMadeByPlayerIndex", "players", - "spectators", "stockPile", "topOfPile" ], "type": "object", "properties": { - "initialCardsPerPlayer": { + "lastPlayMadeByPlayerIndex": { "type": "integer", "format": "int32" }, - "currentPlayerIndex": { + "cardsToDraw": { "type": "integer", "format": "int32" }, @@ -6085,11 +7366,16 @@ "type": "integer", "format": "int32" }, - "donePlayers": { - "type": "array", - "items": { - "$ref": "#/components/schemas/CrazyEights.CrazyEightsPlayer" - } + "gameDirection": { + "type": "integer", + "format": "int32" + }, + "gabongMasterId": { + "type": "string", + "format": "uuid" + }, + "isBetweenRounds": { + "type": "boolean" }, "deck": { "type": "array", @@ -6112,13 +7398,7 @@ "players": { "type": "array", "items": { - "$ref": "#/components/schemas/CrazyEights.CrazyEightsPlayer" - } - }, - "spectators": { - "type": "array", - "items": { - "$ref": "#/components/schemas/CrazyEights.CrazyEightsSpectator" + "$ref": "#/components/schemas/Gabong.GabongPlayer" } }, "newSuit": { @@ -6131,18 +7411,62 @@ "$ref": "#/components/schemas/Common.Suit" }, "currentPlayer": { - "$ref": "#/components/schemas/CrazyEights.CrazyEightsPlayer" + "$ref": "#/components/schemas/Gabong.GabongPlayer" } }, "additionalProperties": false } ] }, - "CrazyEights.CrazyEightsPlayer": { + "Gabong.GabongGameNotification": { + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterNotification" + }, + { + "type": "object", + "additionalProperties": false, + "discriminator": { + "propertyName": "type", + "mapping": { + "Gabong.GabongPlayerNotification": "#/components/schemas/Gabong.GabongPlayerNotification", + "Gabong.PlayerPutCardNotification": "#/components/schemas/Gabong.PlayerPutCardNotification", + "Gabong.PlayerDrewCardNotification": "#/components/schemas/Gabong.PlayerDrewCardNotification", + "Gabong.PlayerDrewPenaltyCardNotification": "#/components/schemas/Gabong.PlayerDrewPenaltyCardNotification", + "Gabong.GameStartedNotification": "#/components/schemas/Gabong.GameStartedNotification", + "Gabong.GameEndedNotification": "#/components/schemas/Gabong.GameEndedNotification", + "Gabong.RoundStartedNotification": "#/components/schemas/Gabong.RoundStartedNotification", + "Gabong.RoundEndedNotification": "#/components/schemas/Gabong.RoundEndedNotification", + "Gabong.PlayerLostTheirTurnNotification": "#/components/schemas/Gabong.PlayerLostTheirTurnNotification" + } + } + } + ] + }, + "Gabong.GabongPlay": { + "enum": [ + "CardPlayed", + "TurnLost", + "RoundStarted" + ], + "type": "string" + }, + "Gabong.GabongPlayer": { "required": [ + "bongas", "cards", + "cardsPlayed", + "debtDrawn", + "gabongs", + "hasWon", "id", - "name" + "name", + "passes", + "penalties", + "roundsWon", + "score", + "shots", + "turnsLost" ], "type": "object", "properties": { @@ -6157,109 +7481,60 @@ "type": "array", "items": { "$ref": "#/components/schemas/Common.Card" - } - } - }, - "additionalProperties": false - }, - "CrazyEights.CrazyEightsSpectator": { - "required": [ - "id", - "name" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" + }, + "readOnly": true }, - "name": { - "type": "string" - } - }, - "additionalProperties": false - }, - "CrazyEights.DiscardPileShuffledNotification": { - "allOf": [ - { - "$ref": "#/components/schemas/Protocol.DecksterNotification" + "score": { + "type": "integer", + "format": "int32" }, - { - "type": "object", - "additionalProperties": false - } - ] - }, - "CrazyEights.DrawCardRequest": { - "allOf": [ - { - "$ref": "#/components/schemas/Protocol.DecksterRequest" + "hasWon": { + "type": "boolean", + "readOnly": true }, - { - "type": "object", - "additionalProperties": false - } - ] - }, - "CrazyEights.GameEndedNotification": { - "allOf": [ - { - "$ref": "#/components/schemas/Protocol.DecksterNotification" + "penalties": { + "type": "integer", + "format": "int32" + }, + "gabongs": { + "type": "integer", + "format": "int32" + }, + "bongas": { + "type": "integer", + "format": "int32" + }, + "shots": { + "type": "integer", + "format": "int32" + }, + "cardsPlayed": { + "type": "integer", + "format": "int32" + }, + "debtDrawn": { + "type": "integer", + "format": "int32" + }, + "passes": { + "type": "integer", + "format": "int32" }, - { - "required": [ - "loserId", - "loserName", - "players" - ], - "type": "object", - "properties": { - "players": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Common.PlayerData" - } - }, - "loserId": { - "type": "string", - "format": "uuid" - }, - "loserName": { - "type": "string" - } - }, - "additionalProperties": false - } - ] - }, - "CrazyEights.GameStartedNotification": { - "allOf": [ - { - "$ref": "#/components/schemas/Protocol.DecksterNotification" + "turnsLost": { + "type": "integer", + "format": "int32" }, - { - "required": [ - "gameId", - "playerViewOfGame" - ], - "type": "object", - "properties": { - "gameId": { - "type": "string", - "format": "uuid" - }, - "playerViewOfGame": { - "$ref": "#/components/schemas/CrazyEights.PlayerViewOfGame" - } - }, - "additionalProperties": false + "roundsWon": { + "type": "integer", + "format": "int32" } - ] + }, + "additionalProperties": false }, - "CrazyEights.ItsPlayersTurnNotification": { + "Gabong.GabongPlayerNotification": { "allOf": [ { - "$ref": "#/components/schemas/Protocol.DecksterNotification" + "$ref": "#/components/schemas/Gabong.GabongGameNotification" }, { "required": [ @@ -6272,114 +7547,103 @@ "format": "uuid" } }, - "additionalProperties": false - } - ] - }, - "CrazyEights.ItsYourTurnNotification": { - "allOf": [ - { - "$ref": "#/components/schemas/Protocol.DecksterNotification" - }, - { - "required": [ - "playerViewOfGame" - ], - "type": "object", - "properties": { - "playerViewOfGame": { - "$ref": "#/components/schemas/CrazyEights.PlayerViewOfGame" + "additionalProperties": false, + "discriminator": { + "propertyName": "type", + "mapping": { + "Gabong.PlayerPutCardNotification": "#/components/schemas/Gabong.PlayerPutCardNotification", + "Gabong.PlayerDrewCardNotification": "#/components/schemas/Gabong.PlayerDrewCardNotification", + "Gabong.PlayerDrewPenaltyCardNotification": "#/components/schemas/Gabong.PlayerDrewPenaltyCardNotification", + "Gabong.PlayerLostTheirTurnNotification": "#/components/schemas/Gabong.PlayerLostTheirTurnNotification" } - }, - "additionalProperties": false + } } ] }, - "CrazyEights.OtherCrazyEightsPlayer": { - "required": [ - "name", - "numberOfCards", - "playerId" - ], - "type": "object", - "properties": { - "playerId": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "numberOfCards": { - "type": "integer", - "format": "int32" - } - }, - "additionalProperties": false - }, - "CrazyEights.PassRequest": { + "Gabong.GabongRequest": { "allOf": [ { "$ref": "#/components/schemas/Protocol.DecksterRequest" }, { "type": "object", - "additionalProperties": false + "additionalProperties": false, + "discriminator": { + "propertyName": "type", + "mapping": { + "Gabong.PutCardRequest": "#/components/schemas/Gabong.PutCardRequest", + "Gabong.DrawCardRequest": "#/components/schemas/Gabong.DrawCardRequest", + "Gabong.PassRequest": "#/components/schemas/Gabong.PassRequest", + "Gabong.PlayGabongRequest": "#/components/schemas/Gabong.PlayGabongRequest", + "Gabong.PlayBongaRequest": "#/components/schemas/Gabong.PlayBongaRequest" + } + } } ] }, - "CrazyEights.PlayerDrewCardNotification": { + "Gabong.GabongResponse": { "allOf": [ { - "$ref": "#/components/schemas/Protocol.DecksterNotification" + "$ref": "#/components/schemas/Protocol.DecksterResponse" }, { "required": [ - "playerId" + "cardsAdded" ], "type": "object", "properties": { - "playerId": { - "type": "string", - "format": "uuid" + "cardsAdded": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Common.Card" + } } }, - "additionalProperties": false + "additionalProperties": false, + "discriminator": { + "propertyName": "type", + "mapping": { + "Gabong.GabongCardResponse": "#/components/schemas/Gabong.GabongCardResponse", + "Gabong.PlayerViewOfGame": "#/components/schemas/Gabong.PlayerViewOfGame" + } + } } ] }, - "CrazyEights.PlayerIsDoneNotification": { + "Gabong.GameEndedNotification": { "allOf": [ { - "$ref": "#/components/schemas/Protocol.DecksterNotification" + "$ref": "#/components/schemas/Gabong.GabongGameNotification" }, { "required": [ - "playerId" + "players" ], "type": "object", "properties": { - "playerId": { - "type": "string", - "format": "uuid" + "players": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Common.PlayerData" + } } }, "additionalProperties": false } ] }, - "CrazyEights.PlayerPassedNotification": { + "Gabong.GameStartedNotification": { "allOf": [ { - "$ref": "#/components/schemas/Protocol.DecksterNotification" + "$ref": "#/components/schemas/Gabong.GabongGameNotification" }, { "required": [ - "playerId" + "gameId" ], "type": "object", "properties": { - "playerId": { + "gameId": { "type": "string", "format": "uuid" } @@ -6388,277 +7652,135 @@ } ] }, - "CrazyEights.PlayerPutCardNotification": { + "Gabong.PassRequest": { "allOf": [ { - "$ref": "#/components/schemas/Protocol.DecksterNotification" + "$ref": "#/components/schemas/Gabong.GabongRequest" }, { - "required": [ - "card", - "playerId" - ], "type": "object", - "properties": { - "playerId": { - "type": "string", - "format": "uuid" - }, - "card": { - "$ref": "#/components/schemas/Common.Card" - } - }, "additionalProperties": false } ] }, - "CrazyEights.PlayerPutEightNotification": { + "Gabong.PenalizePlayerForTakingTooLongRequest": { "allOf": [ { - "$ref": "#/components/schemas/Protocol.DecksterNotification" + "$ref": "#/components/schemas/Protocol.DecksterRequest" }, { - "required": [ - "card", - "newSuit", - "playerId" - ], "type": "object", - "properties": { - "playerId": { - "type": "string", - "format": "uuid" - }, - "card": { - "$ref": "#/components/schemas/Common.Card" - }, - "newSuit": { - "$ref": "#/components/schemas/Common.Suit" - } - }, "additionalProperties": false } ] }, - "CrazyEights.PlayerViewOfGame": { + "Gabong.PenalizePlayerForTooManyCardsRequest": { "allOf": [ { - "$ref": "#/components/schemas/Protocol.DecksterResponse" + "$ref": "#/components/schemas/Protocol.DecksterRequest" }, { - "required": [ - "cards", - "currentSuit", - "discardPileCount", - "otherPlayers", - "stockPileCount", - "topOfPile" - ], "type": "object", - "properties": { - "cards": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Common.Card" - } - }, - "topOfPile": { - "$ref": "#/components/schemas/Common.Card" - }, - "currentSuit": { - "$ref": "#/components/schemas/Common.Suit" - }, - "stockPileCount": { - "type": "integer", - "format": "int32" - }, - "discardPileCount": { - "type": "integer", - "format": "int32" - }, - "otherPlayers": { - "type": "array", - "items": { - "$ref": "#/components/schemas/CrazyEights.OtherCrazyEightsPlayer" - } - } - }, "additionalProperties": false } ] }, - "CrazyEights.PutCardRequest": { + "Gabong.PenaltyReason": { + "enum": [ + "PlayOutOfTurn", + "TookTooLong", + "WrongPlay", + "WrongGabong", + "WrongBonga", + "UnpaidDebt", + "PassWithoutDrawing" + ], + "type": "string" + }, + "Gabong.PlayBongaRequest": { "allOf": [ { - "$ref": "#/components/schemas/Protocol.DecksterRequest" + "$ref": "#/components/schemas/Gabong.GabongRequest" }, { - "required": [ - "card" - ], "type": "object", - "properties": { - "card": { - "$ref": "#/components/schemas/Common.Card" - } - }, "additionalProperties": false } ] }, - "CrazyEights.PutEightRequest": { + "Gabong.PlayGabongRequest": { "allOf": [ { - "$ref": "#/components/schemas/Protocol.DecksterRequest" + "$ref": "#/components/schemas/Gabong.GabongRequest" }, { - "required": [ - "card", - "newSuit" - ], "type": "object", - "properties": { - "card": { - "$ref": "#/components/schemas/Common.Card" - }, - "newSuit": { - "$ref": "#/components/schemas/Common.Suit" - } - }, "additionalProperties": false } ] }, - "Data.DatabaseObject": { - "required": [ - "id", - "type" - ], - "type": "object", - "properties": { - "type": { - "type": "string", - "readOnly": true + "Gabong.PlayerDrewCardNotification": { + "allOf": [ + { + "$ref": "#/components/schemas/Gabong.GabongPlayerNotification" }, - "id": { - "type": "string", - "format": "uuid" - } - }, - "additionalProperties": false, - "discriminator": { - "propertyName": "type", - "mapping": { - "Games.GameObject": "#/components/schemas/Games.GameObject", - "Yaniv.YanivGame": "#/components/schemas/Yaniv.YanivGame", - "Uno.UnoGame": "#/components/schemas/Uno.UnoGame", - "TexasHoldEm.TexasHoldEmGame": "#/components/schemas/TexasHoldEm.TexasHoldEmGame", - "Idiot.IdiotGame": "#/components/schemas/Idiot.IdiotGame", - "Gabong.GabongGame": "#/components/schemas/Gabong.GabongGame", - "CrazyEights.CrazyEightsGame": "#/components/schemas/CrazyEights.CrazyEightsGame", - "ChatRoom.ChatRoom": "#/components/schemas/ChatRoom.ChatRoom", - "Bullshit.BullshitGame": "#/components/schemas/Bullshit.BullshitGame" - } - } - }, - "Data.HistoricBullshitGame": { - "type": "object", - "properties": { - "game": { - "$ref": "#/components/schemas/Bullshit.BullshitGame" - } - }, - "additionalProperties": false - }, - "Data.HistoricChatRoom": { - "type": "object", - "properties": { - "game": { - "$ref": "#/components/schemas/ChatRoom.ChatRoom" - } - }, - "additionalProperties": false - }, - "Data.HistoricCrazyEightsGame": { - "type": "object", - "properties": { - "game": { - "$ref": "#/components/schemas/CrazyEights.CrazyEightsGame" - } - }, - "additionalProperties": false - }, - "Data.HistoricGabongGame": { - "type": "object", - "properties": { - "game": { - "$ref": "#/components/schemas/Gabong.GabongGame" - } - }, - "additionalProperties": false - }, - "Data.HistoricIdiotGame": { - "type": "object", - "properties": { - "game": { - "$ref": "#/components/schemas/Idiot.IdiotGame" - } - }, - "additionalProperties": false - }, - "Data.HistoricTexasHoldEmGame": { - "type": "object", - "properties": { - "game": { - "$ref": "#/components/schemas/TexasHoldEm.TexasHoldEmGame" - } - }, - "additionalProperties": false - }, - "Data.HistoricUnoGame": { - "type": "object", - "properties": { - "game": { - "$ref": "#/components/schemas/Uno.UnoGame" - } - }, - "additionalProperties": false - }, - "Data.HistoricYanivGame": { - "type": "object", - "properties": { - "game": { - "$ref": "#/components/schemas/Yaniv.YanivGame" + { + "type": "object", + "additionalProperties": false } - }, - "additionalProperties": false + ] }, - "Gabong.ActionResponse": { + "Gabong.PlayerDrewPenaltyCardNotification": { "allOf": [ { - "$ref": "#/components/schemas/Protocol.DecksterResponse" + "$ref": "#/components/schemas/Gabong.GabongPlayerNotification" }, { + "required": [ + "penaltyReason" + ], "type": "object", + "properties": { + "penaltyReason": { + "$ref": "#/components/schemas/Gabong.PenaltyReason" + } + }, "additionalProperties": false } ] }, - "Gabong.DrawCardRequest": { + "Gabong.PlayerLostTheirTurnNotification": { "allOf": [ { - "$ref": "#/components/schemas/Gabong.GabongRequest" + "$ref": "#/components/schemas/Gabong.GabongPlayerNotification" }, { + "required": [ + "lostTurnReason" + ], "type": "object", + "properties": { + "lostTurnReason": { + "$ref": "#/components/schemas/Gabong.PlayerLostTurnReason" + } + }, "additionalProperties": false } ] }, - "Gabong.GabongCardResponse": { + "Gabong.PlayerLostTurnReason": { + "enum": [ + "Passed", + "WrongPlay", + "TookTooLong", + "FinishedDrawingCardDebt" + ], + "type": "string" + }, + "Gabong.PlayerPutCardNotification": { "allOf": [ { - "$ref": "#/components/schemas/Gabong.GabongResponse" + "$ref": "#/components/schemas/Gabong.GabongPlayerNotification" }, { "required": [ @@ -6668,148 +7790,161 @@ "properties": { "card": { "$ref": "#/components/schemas/Common.Card" + }, + "newSuit": { + "$ref": "#/components/schemas/Common.Suit" } }, "additionalProperties": false } ] }, - "Gabong.GabongGame": { + "Gabong.PlayerViewOfGame": { "allOf": [ { - "$ref": "#/components/schemas/Games.GameObject" + "$ref": "#/components/schemas/Gabong.GabongResponse" }, { "required": [ - "cardsDrawn", - "cardsToDraw", - "currentPlayer", + "cardDebtToDraw", + "cards", "currentSuit", - "deck", - "discardPile", - "gabongMasterId", - "gameDirection", - "isBetweenRounds", - "lastPlayMadeByPlayerIndex", + "discardPileCount", + "lastPlay", + "lastPlayMadeByPlayerId", "players", - "stockPile", + "playersOrder", + "roundStarted", + "stockPileCount", "topOfPile" ], "type": "object", "properties": { - "lastPlayMadeByPlayerIndex": { - "type": "integer", - "format": "int32" + "cards": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Common.Card" + } }, - "cardsToDraw": { - "type": "integer", - "format": "int32" + "topOfPile": { + "$ref": "#/components/schemas/Common.Card" }, - "cardsDrawn": { + "currentSuit": { + "$ref": "#/components/schemas/Common.Suit" + }, + "stockPileCount": { "type": "integer", "format": "int32" }, - "gameDirection": { + "discardPileCount": { "type": "integer", "format": "int32" }, - "gabongMasterId": { + "roundStarted": { + "type": "boolean" + }, + "lastPlayMadeByPlayerId": { "type": "string", "format": "uuid" }, - "isBetweenRounds": { - "type": "boolean" + "lastPlay": { + "$ref": "#/components/schemas/Gabong.GabongPlay" }, - "deck": { + "players": { "type": "array", "items": { - "$ref": "#/components/schemas/Common.Card" + "$ref": "#/components/schemas/Gabong.SlimGabongPlayer" } }, - "stockPile": { + "playersOrder": { "type": "array", "items": { - "$ref": "#/components/schemas/Common.Card" + "type": "string", + "format": "uuid" } }, - "discardPile": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Common.Card" - } + "cardDebtToDraw": { + "type": "integer", + "format": "int32" + } + }, + "additionalProperties": false + } + ] + }, + "Gabong.PutCardRequest": { + "allOf": [ + { + "$ref": "#/components/schemas/Gabong.GabongRequest" + }, + { + "required": [ + "card" + ], + "type": "object", + "properties": { + "card": { + "$ref": "#/components/schemas/Common.Card" }, + "newSuit": { + "$ref": "#/components/schemas/Common.Suit" + } + }, + "additionalProperties": false + } + ] + }, + "Gabong.RoundEndedNotification": { + "allOf": [ + { + "$ref": "#/components/schemas/Gabong.GabongGameNotification" + }, + { + "required": [ + "players" + ], + "type": "object", + "properties": { "players": { "type": "array", "items": { - "$ref": "#/components/schemas/Gabong.GabongPlayer" + "$ref": "#/components/schemas/Common.PlayerData" } - }, - "newSuit": { - "$ref": "#/components/schemas/Common.Suit" - }, - "topOfPile": { - "$ref": "#/components/schemas/Common.Card" - }, - "currentSuit": { - "$ref": "#/components/schemas/Common.Suit" - }, - "currentPlayer": { - "$ref": "#/components/schemas/Gabong.GabongPlayer" } }, "additionalProperties": false } ] }, - "Gabong.GabongGameNotification": { + "Gabong.RoundStartedNotification": { "allOf": [ { - "$ref": "#/components/schemas/Protocol.DecksterNotification" + "$ref": "#/components/schemas/Gabong.GabongGameNotification" }, { + "required": [ + "playerViewOfGame", + "startingPlayerId" + ], "type": "object", - "additionalProperties": false, - "discriminator": { - "propertyName": "type", - "mapping": { - "Gabong.GabongPlayerNotification": "#/components/schemas/Gabong.GabongPlayerNotification", - "Gabong.PlayerPutCardNotification": "#/components/schemas/Gabong.PlayerPutCardNotification", - "Gabong.PlayerDrewCardNotification": "#/components/schemas/Gabong.PlayerDrewCardNotification", - "Gabong.PlayerDrewPenaltyCardNotification": "#/components/schemas/Gabong.PlayerDrewPenaltyCardNotification", - "Gabong.GameStartedNotification": "#/components/schemas/Gabong.GameStartedNotification", - "Gabong.GameEndedNotification": "#/components/schemas/Gabong.GameEndedNotification", - "Gabong.RoundStartedNotification": "#/components/schemas/Gabong.RoundStartedNotification", - "Gabong.RoundEndedNotification": "#/components/schemas/Gabong.RoundEndedNotification", - "Gabong.PlayerLostTheirTurnNotification": "#/components/schemas/Gabong.PlayerLostTheirTurnNotification" + "properties": { + "playerViewOfGame": { + "$ref": "#/components/schemas/Gabong.PlayerViewOfGame" + }, + "startingPlayerId": { + "type": "string", + "format": "uuid" } - } + }, + "additionalProperties": false } ] }, - "Gabong.GabongPlay": { - "enum": [ - "CardPlayed", - "TurnLost", - "RoundStarted" - ], - "type": "string" - }, - "Gabong.GabongPlayer": { + "Gabong.SlimGabongPlayer": { "required": [ - "bongas", - "cards", - "cardsPlayed", - "debtDrawn", - "gabongs", - "hasWon", "id", "name", - "passes", - "penalties", - "roundsWon", - "score", - "shots", - "turnsLost" + "numberOfCards" ], "type": "object", "properties": { @@ -6820,93 +7955,97 @@ "name": { "type": "string" }, - "cards": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Common.Card" - }, - "readOnly": true - }, - "score": { - "type": "integer", - "format": "int32" - }, - "hasWon": { - "type": "boolean", - "readOnly": true - }, - "penalties": { - "type": "integer", - "format": "int32" - }, - "gabongs": { - "type": "integer", - "format": "int32" - }, - "bongas": { - "type": "integer", - "format": "int32" - }, - "shots": { - "type": "integer", - "format": "int32" - }, - "cardsPlayed": { - "type": "integer", - "format": "int32" - }, - "debtDrawn": { - "type": "integer", - "format": "int32" - }, - "passes": { - "type": "integer", - "format": "int32" - }, - "turnsLost": { - "type": "integer", - "format": "int32" - }, - "roundsWon": { + "numberOfCards": { "type": "integer", "format": "int32" } }, "additionalProperties": false }, - "Gabong.GabongPlayerNotification": { + "Games.GameObject": { "allOf": [ { - "$ref": "#/components/schemas/Gabong.GabongGameNotification" + "$ref": "#/components/schemas/Data.DatabaseObject" }, { "required": [ - "playerId" + "name", + "seed", + "startedTime", + "state", + "version" ], "type": "object", "properties": { - "playerId": { + "name": { + "type": "string" + }, + "startedTime": { "type": "string", - "format": "uuid" + "format": "date-time" + }, + "state": { + "$ref": "#/components/schemas/Games.GameState" + }, + "version": { + "type": "integer", + "format": "int32" + }, + "seed": { + "type": "integer", + "format": "int32" } }, "additionalProperties": false, "discriminator": { "propertyName": "type", "mapping": { - "Gabong.PlayerPutCardNotification": "#/components/schemas/Gabong.PlayerPutCardNotification", - "Gabong.PlayerDrewCardNotification": "#/components/schemas/Gabong.PlayerDrewCardNotification", - "Gabong.PlayerDrewPenaltyCardNotification": "#/components/schemas/Gabong.PlayerDrewPenaltyCardNotification", - "Gabong.PlayerLostTheirTurnNotification": "#/components/schemas/Gabong.PlayerLostTheirTurnNotification" + "Yaniv.YanivGame": "#/components/schemas/Yaniv.YanivGame", + "Uno.UnoGame": "#/components/schemas/Uno.UnoGame", + "TexasHoldEm.TexasHoldEmGame": "#/components/schemas/TexasHoldEm.TexasHoldEmGame", + "Idiot.IdiotGame": "#/components/schemas/Idiot.IdiotGame", + "Hearts.HeartsGame": "#/components/schemas/Hearts.HeartsGame", + "Gabong.GabongGame": "#/components/schemas/Gabong.GabongGame", + "CrazyEights.CrazyEightsGame": "#/components/schemas/CrazyEights.CrazyEightsGame", + "ChatRoom.ChatRoom": "#/components/schemas/ChatRoom.ChatRoom", + "Bullshit.BullshitGame": "#/components/schemas/Bullshit.BullshitGame" } } } ] }, - "Gabong.GabongRequest": { + "Games.GameState": { + "enum": [ + "Waiting", + "Running", + "Finished", + "RoundFinished" + ], + "type": "string" + }, + "Handshake.ConnectFailureMessage": { "allOf": [ { - "$ref": "#/components/schemas/Protocol.DecksterRequest" + "$ref": "#/components/schemas/Handshake.ConnectMessage" + }, + { + "required": [ + "errorMessage" + ], + "type": "object", + "properties": { + "errorMessage": { + "type": "string" + } + }, + "additionalProperties": false + } + ] + }, + "Handshake.ConnectMessage": { + "allOf": [ + { + "$ref": "#/components/schemas/Protocol.DecksterMessage" }, { "type": "object", @@ -6914,102 +8053,158 @@ "discriminator": { "propertyName": "type", "mapping": { - "Gabong.PutCardRequest": "#/components/schemas/Gabong.PutCardRequest", - "Gabong.DrawCardRequest": "#/components/schemas/Gabong.DrawCardRequest", - "Gabong.PassRequest": "#/components/schemas/Gabong.PassRequest", - "Gabong.PlayGabongRequest": "#/components/schemas/Gabong.PlayGabongRequest", - "Gabong.PlayBongaRequest": "#/components/schemas/Gabong.PlayBongaRequest" + "Handshake.HelloSuccessMessage": "#/components/schemas/Handshake.HelloSuccessMessage", + "Handshake.ConnectSuccessMessage": "#/components/schemas/Handshake.ConnectSuccessMessage", + "Handshake.ConnectFailureMessage": "#/components/schemas/Handshake.ConnectFailureMessage" + } + } + } + ] + }, + "Handshake.ConnectSuccessMessage": { + "allOf": [ + { + "$ref": "#/components/schemas/Handshake.ConnectMessage" + }, + { + "type": "object", + "additionalProperties": false + } + ] + }, + "Handshake.HelloSuccessMessage": { + "allOf": [ + { + "$ref": "#/components/schemas/Handshake.ConnectMessage" + }, + { + "required": [ + "connectionId", + "player" + ], + "type": "object", + "properties": { + "player": { + "$ref": "#/components/schemas/Common.PlayerData" + }, + "connectionId": { + "type": "string", + "format": "uuid" } - } + }, + "additionalProperties": false } ] }, - "Gabong.GabongResponse": { + "Hearts.AllPlayersPassedNotification": { "allOf": [ { - "$ref": "#/components/schemas/Protocol.DecksterResponse" + "$ref": "#/components/schemas/Protocol.DecksterNotification" }, { "required": [ - "cardsAdded" + "receivedCards" ], "type": "object", "properties": { - "cardsAdded": { + "receivedCards": { "type": "array", "items": { "$ref": "#/components/schemas/Common.Card" } } }, - "additionalProperties": false, - "discriminator": { - "propertyName": "type", - "mapping": { - "Gabong.GabongCardResponse": "#/components/schemas/Gabong.GabongCardResponse", - "Gabong.PlayerViewOfGame": "#/components/schemas/Gabong.PlayerViewOfGame" - } - } + "additionalProperties": false } ] }, - "Gabong.GameEndedNotification": { + "Hearts.CardPlay": { + "required": [ + "card", + "playerId", + "playerName" + ], + "type": "object", + "properties": { + "playerId": { + "type": "string", + "format": "uuid" + }, + "playerName": { + "type": "string" + }, + "card": { + "$ref": "#/components/schemas/Common.Card" + } + }, + "additionalProperties": false + }, + "Hearts.GameEndedNotification": { "allOf": [ { - "$ref": "#/components/schemas/Gabong.GabongGameNotification" + "$ref": "#/components/schemas/Protocol.DecksterNotification" }, { "required": [ - "players" + "finalScores", + "winnerId", + "winnerName" ], "type": "object", "properties": { - "players": { + "finalScores": { "type": "array", "items": { - "$ref": "#/components/schemas/Common.PlayerData" + "$ref": "#/components/schemas/Hearts.PlayerScore" } + }, + "winnerId": { + "type": "string", + "format": "uuid" + }, + "winnerName": { + "type": "string" } }, "additionalProperties": false } ] }, - "Gabong.GameStartedNotification": { + "Hearts.GamePhase": { + "enum": [ + "Passing", + "Playing" + ], + "type": "string" + }, + "Hearts.GameStartedNotification": { "allOf": [ { - "$ref": "#/components/schemas/Gabong.GabongGameNotification" + "$ref": "#/components/schemas/Protocol.DecksterNotification" }, { "required": [ - "gameId" + "gameId", + "playerViewOfGame" ], "type": "object", "properties": { "gameId": { "type": "string", "format": "uuid" + }, + "playerViewOfGame": { + "$ref": "#/components/schemas/Hearts.PlayerViewOfGame" } }, "additionalProperties": false } ] }, - "Gabong.PassRequest": { - "allOf": [ - { - "$ref": "#/components/schemas/Gabong.GabongRequest" - }, - { - "type": "object", - "additionalProperties": false - } - ] - }, - "Gabong.PenalizePlayerForTakingTooLongRequest": { + "Hearts.HeartsAreBrokenNotification": { "allOf": [ { - "$ref": "#/components/schemas/Protocol.DecksterRequest" + "$ref": "#/components/schemas/Protocol.DecksterNotification" }, { "type": "object", @@ -7017,208 +8212,273 @@ } ] }, - "Gabong.PenalizePlayerForTooManyCardsRequest": { + "Hearts.HeartsGame": { "allOf": [ { - "$ref": "#/components/schemas/Protocol.DecksterRequest" + "$ref": "#/components/schemas/Games.GameObject" }, { + "required": [ + "currentPassDirection", + "currentPlayer", + "currentPlayerIndex", + "currentTrick", + "deck", + "heartsAreBroken", + "isFirstTrick", + "phase", + "players", + "roundNumber" + ], "type": "object", + "properties": { + "deck": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Common.Card" + } + }, + "players": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Hearts.HeartsPlayer" + } + }, + "currentPlayerIndex": { + "type": "integer", + "format": "int32" + }, + "roundNumber": { + "type": "integer", + "format": "int32" + }, + "heartsAreBroken": { + "type": "boolean" + }, + "currentTrick": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Hearts.CardPlay" + } + }, + "leadSuit": { + "$ref": "#/components/schemas/Common.Suit" + }, + "isFirstTrick": { + "type": "boolean" + }, + "phase": { + "$ref": "#/components/schemas/Hearts.GamePhase" + }, + "currentPlayer": { + "$ref": "#/components/schemas/Hearts.HeartsPlayer" + }, + "currentPassDirection": { + "$ref": "#/components/schemas/Hearts.PassDirection" + } + }, "additionalProperties": false } ] }, - "Gabong.PenaltyReason": { - "enum": [ - "PlayOutOfTurn", - "TookTooLong", - "WrongPlay", - "WrongGabong", - "WrongBonga", - "UnpaidDebt", - "PassWithoutDrawing" + "Hearts.HeartsPlayer": { + "required": [ + "cards", + "cardsToPass", + "hasPassed", + "id", + "name", + "roundScore", + "totalScore" ], - "type": "string" - }, - "Gabong.PlayBongaRequest": { - "allOf": [ - { - "$ref": "#/components/schemas/Gabong.GabongRequest" + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" }, - { - "type": "object", - "additionalProperties": false - } - ] - }, - "Gabong.PlayGabongRequest": { - "allOf": [ - { - "$ref": "#/components/schemas/Gabong.GabongRequest" + "name": { + "type": "string" }, - { - "type": "object", - "additionalProperties": false + "cards": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Common.Card" + } + }, + "cardsToPass": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Common.Card" + } + }, + "hasPassed": { + "type": "boolean" + }, + "roundScore": { + "type": "integer", + "format": "int32" + }, + "totalScore": { + "type": "integer", + "format": "int32" + }, + "playedCard": { + "$ref": "#/components/schemas/Common.Card" } - ] + }, + "additionalProperties": false }, - "Gabong.PlayerDrewCardNotification": { + "Hearts.ItsPlayersTurnNotification": { "allOf": [ { - "$ref": "#/components/schemas/Gabong.GabongPlayerNotification" + "$ref": "#/components/schemas/Protocol.DecksterNotification" }, { + "required": [ + "playerId" + ], "type": "object", + "properties": { + "playerId": { + "type": "string", + "format": "uuid" + } + }, "additionalProperties": false } ] }, - "Gabong.PlayerDrewPenaltyCardNotification": { + "Hearts.ItsYourTurnNotification": { "allOf": [ { - "$ref": "#/components/schemas/Gabong.GabongPlayerNotification" + "$ref": "#/components/schemas/Protocol.DecksterNotification" }, { "required": [ - "penaltyReason" + "playerViewOfGame" ], "type": "object", "properties": { - "penaltyReason": { - "$ref": "#/components/schemas/Gabong.PenaltyReason" + "playerViewOfGame": { + "$ref": "#/components/schemas/Hearts.PlayerViewOfGame" } }, "additionalProperties": false } ] }, - "Gabong.PlayerLostTheirTurnNotification": { + "Hearts.OtherHeartsPlayer": { + "required": [ + "name", + "numberOfCards", + "playerId", + "roundScore", + "totalScore" + ], + "type": "object", + "properties": { + "playerId": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "numberOfCards": { + "type": "integer", + "format": "int32" + }, + "totalScore": { + "type": "integer", + "format": "int32" + }, + "roundScore": { + "type": "integer", + "format": "int32" + }, + "playedCard": { + "$ref": "#/components/schemas/Common.Card" + } + }, + "additionalProperties": false + }, + "Hearts.PassCardsRequest": { "allOf": [ { - "$ref": "#/components/schemas/Gabong.GabongPlayerNotification" + "$ref": "#/components/schemas/Protocol.DecksterRequest" }, { "required": [ - "lostTurnReason" + "cards" ], "type": "object", "properties": { - "lostTurnReason": { - "$ref": "#/components/schemas/Gabong.PlayerLostTurnReason" + "cards": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Common.Card" + } } }, "additionalProperties": false } - ] - }, - "Gabong.PlayerLostTurnReason": { - "enum": [ - "Passed", - "WrongPlay", - "TookTooLong", - "FinishedDrawingCardDebt" - ], - "type": "string" + ] }, - "Gabong.PlayerPutCardNotification": { + "Hearts.PassCardsResponse": { "allOf": [ { - "$ref": "#/components/schemas/Gabong.GabongPlayerNotification" + "$ref": "#/components/schemas/Protocol.DecksterResponse" }, { "required": [ - "card" + "receivedCards" ], "type": "object", "properties": { - "card": { - "$ref": "#/components/schemas/Common.Card" - }, - "newSuit": { - "$ref": "#/components/schemas/Common.Suit" + "receivedCards": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Common.Card" + } } }, "additionalProperties": false } ] }, - "Gabong.PlayerViewOfGame": { + "Hearts.PassDirection": { + "enum": [ + "None", + "Left", + "Right", + "Across" + ], + "type": "string" + }, + "Hearts.PassingPhaseStartedNotification": { "allOf": [ { - "$ref": "#/components/schemas/Gabong.GabongResponse" + "$ref": "#/components/schemas/Protocol.DecksterNotification" }, { "required": [ - "cardDebtToDraw", - "cards", - "currentSuit", - "discardPileCount", - "lastPlay", - "lastPlayMadeByPlayerId", - "players", - "playersOrder", - "roundStarted", - "stockPileCount", - "topOfPile" + "passDirection" ], "type": "object", "properties": { - "cards": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Common.Card" - } - }, - "topOfPile": { - "$ref": "#/components/schemas/Common.Card" - }, - "currentSuit": { - "$ref": "#/components/schemas/Common.Suit" - }, - "stockPileCount": { - "type": "integer", - "format": "int32" - }, - "discardPileCount": { - "type": "integer", - "format": "int32" - }, - "roundStarted": { - "type": "boolean" - }, - "lastPlayMadeByPlayerId": { - "type": "string", - "format": "uuid" - }, - "lastPlay": { - "$ref": "#/components/schemas/Gabong.GabongPlay" - }, - "players": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Gabong.SlimGabongPlayer" - } - }, - "playersOrder": { - "type": "array", - "items": { - "type": "string", - "format": "uuid" - } - }, - "cardDebtToDraw": { - "type": "integer", - "format": "int32" + "passDirection": { + "$ref": "#/components/schemas/Hearts.PassDirection" } }, "additionalProperties": false } ] }, - "Gabong.PutCardRequest": { + "Hearts.PlayCardRequest": { "allOf": [ { - "$ref": "#/components/schemas/Gabong.GabongRequest" + "$ref": "#/components/schemas/Protocol.DecksterRequest" }, { "required": [ @@ -7228,210 +8488,211 @@ "properties": { "card": { "$ref": "#/components/schemas/Common.Card" - }, - "newSuit": { - "$ref": "#/components/schemas/Common.Suit" } }, "additionalProperties": false } ] }, - "Gabong.RoundEndedNotification": { + "Hearts.PlayerPassedCardsNotification": { "allOf": [ { - "$ref": "#/components/schemas/Gabong.GabongGameNotification" + "$ref": "#/components/schemas/Protocol.DecksterNotification" }, { "required": [ - "players" + "playerId" ], "type": "object", "properties": { - "players": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Common.PlayerData" - } + "playerId": { + "type": "string", + "format": "uuid" } }, "additionalProperties": false } ] }, - "Gabong.RoundStartedNotification": { + "Hearts.PlayerPlayedCardNotification": { "allOf": [ { - "$ref": "#/components/schemas/Gabong.GabongGameNotification" + "$ref": "#/components/schemas/Protocol.DecksterNotification" }, { "required": [ - "playerViewOfGame", - "startingPlayerId" + "card", + "playerId" ], "type": "object", "properties": { - "playerViewOfGame": { - "$ref": "#/components/schemas/Gabong.PlayerViewOfGame" - }, - "startingPlayerId": { + "playerId": { "type": "string", "format": "uuid" + }, + "card": { + "$ref": "#/components/schemas/Common.Card" } }, "additionalProperties": false } ] }, - "Gabong.SlimGabongPlayer": { + "Hearts.PlayerScore": { "required": [ - "id", - "name", - "numberOfCards" + "playerId", + "playerName", + "roundScore", + "totalScore" ], "type": "object", "properties": { - "id": { + "playerId": { "type": "string", "format": "uuid" }, - "name": { + "playerName": { "type": "string" }, - "numberOfCards": { + "roundScore": { + "type": "integer", + "format": "int32" + }, + "totalScore": { "type": "integer", "format": "int32" } }, "additionalProperties": false }, - "Games.GameObject": { + "Hearts.PlayerViewOfGame": { "allOf": [ { - "$ref": "#/components/schemas/Data.DatabaseObject" + "$ref": "#/components/schemas/Protocol.DecksterResponse" }, { "required": [ - "name", - "seed", - "startedTime", - "state", - "version" + "cards", + "currentTrick", + "hasPassed", + "heartsAreBroken", + "isMyTurn", + "otherPlayers", + "passDirection", + "roundNumber", + "roundScore", + "totalScore" ], "type": "object", "properties": { - "name": { - "type": "string" + "cards": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Common.Card" + } }, - "startedTime": { - "type": "string", - "format": "date-time" + "otherPlayers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Hearts.OtherHeartsPlayer" + } }, - "state": { - "$ref": "#/components/schemas/Games.GameState" + "roundNumber": { + "type": "integer", + "format": "int32" }, - "version": { + "passDirection": { + "$ref": "#/components/schemas/Hearts.PassDirection" + }, + "hasPassed": { + "type": "boolean" + }, + "currentTrick": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Hearts.CardPlay" + } + }, + "totalScore": { "type": "integer", "format": "int32" }, - "seed": { + "roundScore": { "type": "integer", "format": "int32" + }, + "heartsAreBroken": { + "type": "boolean" + }, + "isMyTurn": { + "type": "boolean" } }, - "additionalProperties": false, - "discriminator": { - "propertyName": "type", - "mapping": { - "Yaniv.YanivGame": "#/components/schemas/Yaniv.YanivGame", - "Uno.UnoGame": "#/components/schemas/Uno.UnoGame", - "TexasHoldEm.TexasHoldEmGame": "#/components/schemas/TexasHoldEm.TexasHoldEmGame", - "Idiot.IdiotGame": "#/components/schemas/Idiot.IdiotGame", - "Gabong.GabongGame": "#/components/schemas/Gabong.GabongGame", - "CrazyEights.CrazyEightsGame": "#/components/schemas/CrazyEights.CrazyEightsGame", - "ChatRoom.ChatRoom": "#/components/schemas/ChatRoom.ChatRoom", - "Bullshit.BullshitGame": "#/components/schemas/Bullshit.BullshitGame" - } - } + "additionalProperties": false } ] }, - "Games.GameState": { - "enum": [ - "Waiting", - "Running", - "Finished", - "RoundFinished" - ], - "type": "string" - }, - "Handshake.ConnectFailureMessage": { + "Hearts.RoundEndedNotification": { "allOf": [ { - "$ref": "#/components/schemas/Handshake.ConnectMessage" + "$ref": "#/components/schemas/Protocol.DecksterNotification" }, { "required": [ - "errorMessage" + "scores" ], "type": "object", "properties": { - "errorMessage": { - "type": "string" + "scores": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Hearts.PlayerScore" + } + }, + "moonShooterId": { + "type": "string", + "format": "uuid", + "nullable": true + }, + "moonShooterName": { + "type": "string", + "nullable": true } }, "additionalProperties": false } ] }, - "Handshake.ConnectMessage": { - "allOf": [ - { - "$ref": "#/components/schemas/Protocol.DecksterMessage" - }, - { - "type": "object", - "additionalProperties": false, - "discriminator": { - "propertyName": "type", - "mapping": { - "Handshake.HelloSuccessMessage": "#/components/schemas/Handshake.HelloSuccessMessage", - "Handshake.ConnectSuccessMessage": "#/components/schemas/Handshake.ConnectSuccessMessage", - "Handshake.ConnectFailureMessage": "#/components/schemas/Handshake.ConnectFailureMessage" - } - } - } - ] - }, - "Handshake.ConnectSuccessMessage": { - "allOf": [ - { - "$ref": "#/components/schemas/Handshake.ConnectMessage" - }, - { - "type": "object", - "additionalProperties": false - } - ] - }, - "Handshake.HelloSuccessMessage": { + "Hearts.TrickCompletedNotification": { "allOf": [ { - "$ref": "#/components/schemas/Handshake.ConnectMessage" + "$ref": "#/components/schemas/Protocol.DecksterNotification" }, { "required": [ - "connectionId", - "player" + "points", + "trickCards", + "winnerId", + "winnerName" ], "type": "object", "properties": { - "player": { - "$ref": "#/components/schemas/Common.PlayerData" - }, - "connectionId": { + "winnerId": { "type": "string", "format": "uuid" + }, + "winnerName": { + "type": "string" + }, + "trickCards": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Hearts.CardPlay" + } + }, + "points": { + "type": "integer", + "format": "int32" } }, "additionalProperties": false @@ -8301,6 +9562,21 @@ "Idiot.GameStartedNotification": "#/components/schemas/Idiot.GameStartedNotification", "Idiot.GameEndedNotification": "#/components/schemas/Idiot.GameEndedNotification", "Idiot.ItsTimeToSwapCardsNotification": "#/components/schemas/Idiot.ItsTimeToSwapCardsNotification", + "Hearts.PassCardsRequest": "#/components/schemas/Hearts.PassCardsRequest", + "Hearts.PlayCardRequest": "#/components/schemas/Hearts.PlayCardRequest", + "Hearts.PassCardsResponse": "#/components/schemas/Hearts.PassCardsResponse", + "Hearts.GameStartedNotification": "#/components/schemas/Hearts.GameStartedNotification", + "Hearts.PassingPhaseStartedNotification": "#/components/schemas/Hearts.PassingPhaseStartedNotification", + "Hearts.AllPlayersPassedNotification": "#/components/schemas/Hearts.AllPlayersPassedNotification", + "Hearts.PlayerPassedCardsNotification": "#/components/schemas/Hearts.PlayerPassedCardsNotification", + "Hearts.ItsYourTurnNotification": "#/components/schemas/Hearts.ItsYourTurnNotification", + "Hearts.ItsPlayersTurnNotification": "#/components/schemas/Hearts.ItsPlayersTurnNotification", + "Hearts.PlayerPlayedCardNotification": "#/components/schemas/Hearts.PlayerPlayedCardNotification", + "Hearts.TrickCompletedNotification": "#/components/schemas/Hearts.TrickCompletedNotification", + "Hearts.RoundEndedNotification": "#/components/schemas/Hearts.RoundEndedNotification", + "Hearts.GameEndedNotification": "#/components/schemas/Hearts.GameEndedNotification", + "Hearts.HeartsAreBrokenNotification": "#/components/schemas/Hearts.HeartsAreBrokenNotification", + "Hearts.PlayerViewOfGame": "#/components/schemas/Hearts.PlayerViewOfGame", "Gabong.GabongGameNotification": "#/components/schemas/Gabong.GabongGameNotification", "Gabong.GabongPlayerNotification": "#/components/schemas/Gabong.GabongPlayerNotification", "Gabong.PlayerPutCardNotification": "#/components/schemas/Gabong.PlayerPutCardNotification", @@ -8418,6 +9694,17 @@ "Idiot.GameStartedNotification": "#/components/schemas/Idiot.GameStartedNotification", "Idiot.GameEndedNotification": "#/components/schemas/Idiot.GameEndedNotification", "Idiot.ItsTimeToSwapCardsNotification": "#/components/schemas/Idiot.ItsTimeToSwapCardsNotification", + "Hearts.GameStartedNotification": "#/components/schemas/Hearts.GameStartedNotification", + "Hearts.PassingPhaseStartedNotification": "#/components/schemas/Hearts.PassingPhaseStartedNotification", + "Hearts.AllPlayersPassedNotification": "#/components/schemas/Hearts.AllPlayersPassedNotification", + "Hearts.PlayerPassedCardsNotification": "#/components/schemas/Hearts.PlayerPassedCardsNotification", + "Hearts.ItsYourTurnNotification": "#/components/schemas/Hearts.ItsYourTurnNotification", + "Hearts.ItsPlayersTurnNotification": "#/components/schemas/Hearts.ItsPlayersTurnNotification", + "Hearts.PlayerPlayedCardNotification": "#/components/schemas/Hearts.PlayerPlayedCardNotification", + "Hearts.TrickCompletedNotification": "#/components/schemas/Hearts.TrickCompletedNotification", + "Hearts.RoundEndedNotification": "#/components/schemas/Hearts.RoundEndedNotification", + "Hearts.GameEndedNotification": "#/components/schemas/Hearts.GameEndedNotification", + "Hearts.HeartsAreBrokenNotification": "#/components/schemas/Hearts.HeartsAreBrokenNotification", "Gabong.GabongGameNotification": "#/components/schemas/Gabong.GabongGameNotification", "Gabong.GabongPlayerNotification": "#/components/schemas/Gabong.GabongPlayerNotification", "Gabong.PlayerPutCardNotification": "#/components/schemas/Gabong.PlayerPutCardNotification", @@ -8494,6 +9781,8 @@ "Idiot.DrawCardsRequest": "#/components/schemas/Idiot.DrawCardsRequest", "Idiot.PullInDiscardPileRequest": "#/components/schemas/Idiot.PullInDiscardPileRequest", "Idiot.PutChanceCardRequest": "#/components/schemas/Idiot.PutChanceCardRequest", + "Hearts.PassCardsRequest": "#/components/schemas/Hearts.PassCardsRequest", + "Hearts.PlayCardRequest": "#/components/schemas/Hearts.PlayCardRequest", "Gabong.PenalizePlayerForTakingTooLongRequest": "#/components/schemas/Gabong.PenalizePlayerForTakingTooLongRequest", "Gabong.PenalizePlayerForTooManyCardsRequest": "#/components/schemas/Gabong.PenalizePlayerForTooManyCardsRequest", "Gabong.GabongRequest": "#/components/schemas/Gabong.GabongRequest", @@ -8548,6 +9837,8 @@ "Idiot.PullInResponse": "#/components/schemas/Idiot.PullInResponse", "Idiot.DrawCardsResponse": "#/components/schemas/Idiot.DrawCardsResponse", "Idiot.PutBlindCardResponse": "#/components/schemas/Idiot.PutBlindCardResponse", + "Hearts.PassCardsResponse": "#/components/schemas/Hearts.PassCardsResponse", + "Hearts.PlayerViewOfGame": "#/components/schemas/Hearts.PlayerViewOfGame", "Gabong.GabongResponse": "#/components/schemas/Gabong.GabongResponse", "Gabong.GabongCardResponse": "#/components/schemas/Gabong.GabongCardResponse", "Gabong.ActionResponse": "#/components/schemas/Gabong.ActionResponse", diff --git a/generated/shebang.opeanpi.yaml b/generated/shebang.opeanpi.yaml index 45a55671..f6c85ce4 100644 --- a/generated/shebang.opeanpi.yaml +++ b/generated/shebang.opeanpi.yaml @@ -1,4 +1,4 @@ -openapi: 3.0.1 +openapi: 3.0.4 info: title: Deckster.Server version: '1.0' @@ -1547,48 +1547,17 @@ paths: responses: '200': description: OK - /: - get: - tags: - - Home - responses: - '200': - description: OK - /login: - get: - tags: - - Home - responses: - '200': - description: OK - post: - tags: - - Home - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/Controllers.LoginModel' - text/json: - schema: - $ref: '#/components/schemas/Controllers.LoginModel' - application/*+json: - schema: - $ref: '#/components/schemas/Controllers.LoginModel' - responses: - '200': - description: OK - /idiot/description: + /hearts/description: get: tags: - - Idiot + - Hearts responses: '200': description: OK - /idiot/metadata: + /hearts/metadata: get: tags: - - Idiot + - Hearts responses: '200': description: OK @@ -1602,10 +1571,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Meta.GameMeta' - /idiot: + /hearts: get: tags: - - Idiot + - Hearts responses: '200': description: OK @@ -1619,10 +1588,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.GameOverviewVm' - /idiot/games: + /hearts/games: get: tags: - - Idiot + - Hearts responses: '200': description: OK @@ -1642,10 +1611,10 @@ paths: type: array items: $ref: '#/components/schemas/Controllers.GameVm' - '/idiot/games/{name}': + '/hearts/games/{name}': get: tags: - - Idiot + - Hearts parameters: - name: name in: path @@ -1679,7 +1648,7 @@ paths: $ref: '#/components/schemas/Controllers.ResponseMessage' delete: tags: - - Idiot + - Hearts parameters: - name: name in: path @@ -1711,10 +1680,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - '/idiot/games/{name}/bot': + '/hearts/games/{name}/bot': post: tags: - - Idiot + - Hearts parameters: - name: name in: path @@ -1734,10 +1703,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - /idiot/previousgames: + /hearts/previousgames: get: tags: - - Idiot + - Hearts responses: '200': description: OK @@ -1746,21 +1715,21 @@ paths: schema: type: array items: - $ref: '#/components/schemas/Idiot.IdiotGame' + $ref: '#/components/schemas/Hearts.HeartsGame' application/json: schema: type: array items: - $ref: '#/components/schemas/Idiot.IdiotGame' + $ref: '#/components/schemas/Hearts.HeartsGame' text/json: schema: type: array items: - $ref: '#/components/schemas/Idiot.IdiotGame' - '/idiot/previousgames/{id}': + $ref: '#/components/schemas/Hearts.HeartsGame' + '/hearts/previousgames/{id}': get: tags: - - Idiot + - Hearts parameters: - name: id in: path @@ -1774,17 +1743,17 @@ paths: content: text/plain: schema: - $ref: '#/components/schemas/Data.HistoricIdiotGame' + $ref: '#/components/schemas/Data.HistoricHeartsGame' application/json: schema: - $ref: '#/components/schemas/Data.HistoricIdiotGame' + $ref: '#/components/schemas/Data.HistoricHeartsGame' text/json: schema: - $ref: '#/components/schemas/Data.HistoricIdiotGame' - '/idiot/previousgames/{id}/{version}': + $ref: '#/components/schemas/Data.HistoricHeartsGame' + '/hearts/previousgames/{id}/{version}': get: tags: - - Idiot + - Hearts parameters: - name: id in: path @@ -1804,17 +1773,17 @@ paths: content: text/plain: schema: - $ref: '#/components/schemas/Data.HistoricIdiotGame' + $ref: '#/components/schemas/Data.HistoricHeartsGame' application/json: schema: - $ref: '#/components/schemas/Data.HistoricIdiotGame' + $ref: '#/components/schemas/Data.HistoricHeartsGame' text/json: schema: - $ref: '#/components/schemas/Data.HistoricIdiotGame' - '/idiot/create/{name}': + $ref: '#/components/schemas/Data.HistoricHeartsGame' + '/hearts/create/{name}': post: tags: - - Idiot + - Hearts parameters: - name: name in: path @@ -1846,10 +1815,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - /idiot/create: + /hearts/create: post: tags: - - Idiot + - Hearts responses: '200': description: OK @@ -1875,10 +1844,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - '/idiot/games/{name}/start': + '/hearts/games/{name}/start': post: tags: - - Idiot + - Hearts parameters: - name: name in: path @@ -1910,10 +1879,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - '/idiot/join/{gameName}': + '/hearts/join/{gameName}': get: tags: - - Idiot + - Hearts parameters: - name: gameName in: path @@ -1923,10 +1892,10 @@ paths: responses: '200': description: OK - '/idiot/join/{connectionId}/finish': + '/hearts/join/{connectionId}/finish': get: tags: - - Idiot + - Hearts parameters: - name: connectionId in: path @@ -1937,10 +1906,10 @@ paths: responses: '200': description: OK - '/idiot/spectate/{gameName}': + '/hearts/spectate/{gameName}': get: tags: - - Idiot + - Hearts parameters: - name: gameName in: path @@ -1950,10 +1919,10 @@ paths: responses: '200': description: OK - '/idiot/spectate/{connectionId}/finish': + '/hearts/spectate/{connectionId}/finish': get: tags: - - Idiot + - Hearts parameters: - name: connectionId in: path @@ -1964,24 +1933,48 @@ paths: responses: '200': description: OK - /meta/messages: + /: get: tags: - - Meta + - Home responses: '200': description: OK - /texasholdem/description: + /login: get: tags: - - TexasHoldEm + - Home responses: '200': description: OK - /texasholdem/metadata: + post: + tags: + - Home + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Controllers.LoginModel' + text/json: + schema: + $ref: '#/components/schemas/Controllers.LoginModel' + application/*+json: + schema: + $ref: '#/components/schemas/Controllers.LoginModel' + responses: + '200': + description: OK + /idiot/description: get: tags: - - TexasHoldEm + - Idiot + responses: + '200': + description: OK + /idiot/metadata: + get: + tags: + - Idiot responses: '200': description: OK @@ -1995,10 +1988,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Meta.GameMeta' - /texasholdem: + /idiot: get: tags: - - TexasHoldEm + - Idiot responses: '200': description: OK @@ -2012,10 +2005,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.GameOverviewVm' - /texasholdem/games: + /idiot/games: get: tags: - - TexasHoldEm + - Idiot responses: '200': description: OK @@ -2035,10 +2028,10 @@ paths: type: array items: $ref: '#/components/schemas/Controllers.GameVm' - '/texasholdem/games/{name}': + '/idiot/games/{name}': get: tags: - - TexasHoldEm + - Idiot parameters: - name: name in: path @@ -2072,7 +2065,7 @@ paths: $ref: '#/components/schemas/Controllers.ResponseMessage' delete: tags: - - TexasHoldEm + - Idiot parameters: - name: name in: path @@ -2104,10 +2097,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - '/texasholdem/games/{name}/bot': + '/idiot/games/{name}/bot': post: tags: - - TexasHoldEm + - Idiot parameters: - name: name in: path @@ -2127,10 +2120,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - /texasholdem/previousgames: + /idiot/previousgames: get: tags: - - TexasHoldEm + - Idiot responses: '200': description: OK @@ -2139,21 +2132,21 @@ paths: schema: type: array items: - $ref: '#/components/schemas/TexasHoldEm.TexasHoldEmGame' + $ref: '#/components/schemas/Idiot.IdiotGame' application/json: schema: type: array items: - $ref: '#/components/schemas/TexasHoldEm.TexasHoldEmGame' + $ref: '#/components/schemas/Idiot.IdiotGame' text/json: schema: type: array items: - $ref: '#/components/schemas/TexasHoldEm.TexasHoldEmGame' - '/texasholdem/previousgames/{id}': + $ref: '#/components/schemas/Idiot.IdiotGame' + '/idiot/previousgames/{id}': get: tags: - - TexasHoldEm + - Idiot parameters: - name: id in: path @@ -2167,17 +2160,17 @@ paths: content: text/plain: schema: - $ref: '#/components/schemas/Data.HistoricTexasHoldEmGame' + $ref: '#/components/schemas/Data.HistoricIdiotGame' application/json: schema: - $ref: '#/components/schemas/Data.HistoricTexasHoldEmGame' + $ref: '#/components/schemas/Data.HistoricIdiotGame' text/json: schema: - $ref: '#/components/schemas/Data.HistoricTexasHoldEmGame' - '/texasholdem/previousgames/{id}/{version}': + $ref: '#/components/schemas/Data.HistoricIdiotGame' + '/idiot/previousgames/{id}/{version}': get: tags: - - TexasHoldEm + - Idiot parameters: - name: id in: path @@ -2197,17 +2190,17 @@ paths: content: text/plain: schema: - $ref: '#/components/schemas/Data.HistoricTexasHoldEmGame' + $ref: '#/components/schemas/Data.HistoricIdiotGame' application/json: schema: - $ref: '#/components/schemas/Data.HistoricTexasHoldEmGame' + $ref: '#/components/schemas/Data.HistoricIdiotGame' text/json: schema: - $ref: '#/components/schemas/Data.HistoricTexasHoldEmGame' - '/texasholdem/create/{name}': + $ref: '#/components/schemas/Data.HistoricIdiotGame' + '/idiot/create/{name}': post: tags: - - TexasHoldEm + - Idiot parameters: - name: name in: path @@ -2239,10 +2232,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - /texasholdem/create: + /idiot/create: post: tags: - - TexasHoldEm + - Idiot responses: '200': description: OK @@ -2268,10 +2261,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - '/texasholdem/games/{name}/start': + '/idiot/games/{name}/start': post: tags: - - TexasHoldEm + - Idiot parameters: - name: name in: path @@ -2303,10 +2296,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - '/texasholdem/join/{gameName}': + '/idiot/join/{gameName}': get: tags: - - TexasHoldEm + - Idiot parameters: - name: gameName in: path @@ -2316,10 +2309,10 @@ paths: responses: '200': description: OK - '/texasholdem/join/{connectionId}/finish': + '/idiot/join/{connectionId}/finish': get: tags: - - TexasHoldEm + - Idiot parameters: - name: connectionId in: path @@ -2330,10 +2323,10 @@ paths: responses: '200': description: OK - '/texasholdem/spectate/{gameName}': + '/idiot/spectate/{gameName}': get: tags: - - TexasHoldEm + - Idiot parameters: - name: gameName in: path @@ -2343,10 +2336,10 @@ paths: responses: '200': description: OK - '/texasholdem/spectate/{connectionId}/finish': + '/idiot/spectate/{connectionId}/finish': get: tags: - - TexasHoldEm + - Idiot parameters: - name: connectionId in: path @@ -2357,17 +2350,24 @@ paths: responses: '200': description: OK - /uno/description: + /meta/messages: get: tags: - - Uno + - Meta responses: '200': description: OK - /uno/metadata: + /texasholdem/description: get: tags: - - Uno + - TexasHoldEm + responses: + '200': + description: OK + /texasholdem/metadata: + get: + tags: + - TexasHoldEm responses: '200': description: OK @@ -2381,10 +2381,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Meta.GameMeta' - /uno: + /texasholdem: get: tags: - - Uno + - TexasHoldEm responses: '200': description: OK @@ -2398,10 +2398,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.GameOverviewVm' - /uno/games: + /texasholdem/games: get: tags: - - Uno + - TexasHoldEm responses: '200': description: OK @@ -2421,10 +2421,10 @@ paths: type: array items: $ref: '#/components/schemas/Controllers.GameVm' - '/uno/games/{name}': + '/texasholdem/games/{name}': get: tags: - - Uno + - TexasHoldEm parameters: - name: name in: path @@ -2458,7 +2458,7 @@ paths: $ref: '#/components/schemas/Controllers.ResponseMessage' delete: tags: - - Uno + - TexasHoldEm parameters: - name: name in: path @@ -2490,10 +2490,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - '/uno/games/{name}/bot': + '/texasholdem/games/{name}/bot': post: tags: - - Uno + - TexasHoldEm parameters: - name: name in: path @@ -2513,10 +2513,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - /uno/previousgames: + /texasholdem/previousgames: get: tags: - - Uno + - TexasHoldEm responses: '200': description: OK @@ -2525,21 +2525,21 @@ paths: schema: type: array items: - $ref: '#/components/schemas/Uno.UnoGame' + $ref: '#/components/schemas/TexasHoldEm.TexasHoldEmGame' application/json: schema: type: array items: - $ref: '#/components/schemas/Uno.UnoGame' + $ref: '#/components/schemas/TexasHoldEm.TexasHoldEmGame' text/json: schema: type: array items: - $ref: '#/components/schemas/Uno.UnoGame' - '/uno/previousgames/{id}': + $ref: '#/components/schemas/TexasHoldEm.TexasHoldEmGame' + '/texasholdem/previousgames/{id}': get: tags: - - Uno + - TexasHoldEm parameters: - name: id in: path @@ -2553,17 +2553,17 @@ paths: content: text/plain: schema: - $ref: '#/components/schemas/Data.HistoricUnoGame' + $ref: '#/components/schemas/Data.HistoricTexasHoldEmGame' application/json: schema: - $ref: '#/components/schemas/Data.HistoricUnoGame' + $ref: '#/components/schemas/Data.HistoricTexasHoldEmGame' text/json: schema: - $ref: '#/components/schemas/Data.HistoricUnoGame' - '/uno/previousgames/{id}/{version}': - get: + $ref: '#/components/schemas/Data.HistoricTexasHoldEmGame' + '/texasholdem/previousgames/{id}/{version}': + get: tags: - - Uno + - TexasHoldEm parameters: - name: id in: path @@ -2583,17 +2583,17 @@ paths: content: text/plain: schema: - $ref: '#/components/schemas/Data.HistoricUnoGame' + $ref: '#/components/schemas/Data.HistoricTexasHoldEmGame' application/json: schema: - $ref: '#/components/schemas/Data.HistoricUnoGame' + $ref: '#/components/schemas/Data.HistoricTexasHoldEmGame' text/json: schema: - $ref: '#/components/schemas/Data.HistoricUnoGame' - '/uno/create/{name}': + $ref: '#/components/schemas/Data.HistoricTexasHoldEmGame' + '/texasholdem/create/{name}': post: tags: - - Uno + - TexasHoldEm parameters: - name: name in: path @@ -2625,10 +2625,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - /uno/create: + /texasholdem/create: post: tags: - - Uno + - TexasHoldEm responses: '200': description: OK @@ -2654,10 +2654,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - '/uno/games/{name}/start': + '/texasholdem/games/{name}/start': post: tags: - - Uno + - TexasHoldEm parameters: - name: name in: path @@ -2689,10 +2689,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - '/uno/join/{gameName}': + '/texasholdem/join/{gameName}': get: tags: - - Uno + - TexasHoldEm parameters: - name: gameName in: path @@ -2702,10 +2702,10 @@ paths: responses: '200': description: OK - '/uno/join/{connectionId}/finish': + '/texasholdem/join/{connectionId}/finish': get: tags: - - Uno + - TexasHoldEm parameters: - name: connectionId in: path @@ -2716,10 +2716,10 @@ paths: responses: '200': description: OK - '/uno/spectate/{gameName}': + '/texasholdem/spectate/{gameName}': get: tags: - - Uno + - TexasHoldEm parameters: - name: gameName in: path @@ -2729,10 +2729,10 @@ paths: responses: '200': description: OK - '/uno/spectate/{connectionId}/finish': + '/texasholdem/spectate/{connectionId}/finish': get: tags: - - Uno + - TexasHoldEm parameters: - name: connectionId in: path @@ -2743,24 +2743,17 @@ paths: responses: '200': description: OK - /me: - get: - tags: - - User - responses: - '200': - description: OK - /yaniv/description: + /uno/description: get: tags: - - Yaniv + - Uno responses: '200': description: OK - /yaniv/metadata: + /uno/metadata: get: tags: - - Yaniv + - Uno responses: '200': description: OK @@ -2774,10 +2767,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Meta.GameMeta' - /yaniv: + /uno: get: tags: - - Yaniv + - Uno responses: '200': description: OK @@ -2791,10 +2784,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.GameOverviewVm' - /yaniv/games: + /uno/games: get: tags: - - Yaniv + - Uno responses: '200': description: OK @@ -2814,10 +2807,10 @@ paths: type: array items: $ref: '#/components/schemas/Controllers.GameVm' - '/yaniv/games/{name}': + '/uno/games/{name}': get: tags: - - Yaniv + - Uno parameters: - name: name in: path @@ -2851,7 +2844,7 @@ paths: $ref: '#/components/schemas/Controllers.ResponseMessage' delete: tags: - - Yaniv + - Uno parameters: - name: name in: path @@ -2883,10 +2876,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - '/yaniv/games/{name}/bot': + '/uno/games/{name}/bot': post: tags: - - Yaniv + - Uno parameters: - name: name in: path @@ -2906,10 +2899,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - /yaniv/previousgames: + /uno/previousgames: get: tags: - - Yaniv + - Uno responses: '200': description: OK @@ -2918,21 +2911,21 @@ paths: schema: type: array items: - $ref: '#/components/schemas/Yaniv.YanivGame' + $ref: '#/components/schemas/Uno.UnoGame' application/json: schema: type: array items: - $ref: '#/components/schemas/Yaniv.YanivGame' + $ref: '#/components/schemas/Uno.UnoGame' text/json: schema: type: array items: - $ref: '#/components/schemas/Yaniv.YanivGame' - '/yaniv/previousgames/{id}': + $ref: '#/components/schemas/Uno.UnoGame' + '/uno/previousgames/{id}': get: tags: - - Yaniv + - Uno parameters: - name: id in: path @@ -2946,17 +2939,17 @@ paths: content: text/plain: schema: - $ref: '#/components/schemas/Data.HistoricYanivGame' + $ref: '#/components/schemas/Data.HistoricUnoGame' application/json: schema: - $ref: '#/components/schemas/Data.HistoricYanivGame' + $ref: '#/components/schemas/Data.HistoricUnoGame' text/json: schema: - $ref: '#/components/schemas/Data.HistoricYanivGame' - '/yaniv/previousgames/{id}/{version}': + $ref: '#/components/schemas/Data.HistoricUnoGame' + '/uno/previousgames/{id}/{version}': get: tags: - - Yaniv + - Uno parameters: - name: id in: path @@ -2976,17 +2969,17 @@ paths: content: text/plain: schema: - $ref: '#/components/schemas/Data.HistoricYanivGame' + $ref: '#/components/schemas/Data.HistoricUnoGame' application/json: schema: - $ref: '#/components/schemas/Data.HistoricYanivGame' + $ref: '#/components/schemas/Data.HistoricUnoGame' text/json: schema: - $ref: '#/components/schemas/Data.HistoricYanivGame' - '/yaniv/create/{name}': + $ref: '#/components/schemas/Data.HistoricUnoGame' + '/uno/create/{name}': post: tags: - - Yaniv + - Uno parameters: - name: name in: path @@ -3018,10 +3011,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - /yaniv/create: + /uno/create: post: tags: - - Yaniv + - Uno responses: '200': description: OK @@ -3047,10 +3040,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - '/yaniv/games/{name}/start': + '/uno/games/{name}/start': post: tags: - - Yaniv + - Uno parameters: - name: name in: path @@ -3082,10 +3075,10 @@ paths: text/json: schema: $ref: '#/components/schemas/Controllers.ResponseMessage' - '/yaniv/join/{gameName}': + '/uno/join/{gameName}': get: tags: - - Yaniv + - Uno parameters: - name: gameName in: path @@ -3095,10 +3088,10 @@ paths: responses: '200': description: OK - '/yaniv/join/{connectionId}/finish': + '/uno/join/{connectionId}/finish': get: tags: - - Yaniv + - Uno parameters: - name: connectionId in: path @@ -3109,10 +3102,10 @@ paths: responses: '200': description: OK - '/yaniv/spectate/{gameName}': + '/uno/spectate/{gameName}': get: tags: - - Yaniv + - Uno parameters: - name: gameName in: path @@ -3122,10 +3115,10 @@ paths: responses: '200': description: OK - '/yaniv/spectate/{connectionId}/finish': + '/uno/spectate/{connectionId}/finish': get: tags: - - Yaniv + - Uno parameters: - name: connectionId in: path @@ -3136,132 +3129,877 @@ paths: responses: '200': description: OK -components: - schemas: - Bullshit.BullshitBroadcastNotification: - allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' - - required: - - actualCard - - claimedToBeCard - - playerId - - punishmentCardCount - type: object - properties: - playerId: - type: string - format: uuid - claimedToBeCard: - $ref: '#/components/schemas/Common.Card' - actualCard: - $ref: '#/components/schemas/Common.Card' - punishmentCardCount: - type: integer - format: int32 - additionalProperties: false - Bullshit.BullshitGame: - allOf: - - $ref: '#/components/schemas/Games.GameObject' - - required: - - cardsDrawn - - currentPlayer - - currentPlayerIndex - - deck - - discardPile - - donePlayers - - players - - stockPile - type: object - properties: - deck: - type: array - items: - $ref: '#/components/schemas/Common.Card' - stockPile: - type: array - items: - $ref: '#/components/schemas/Common.Card' - discardPile: - type: array - items: - $ref: '#/components/schemas/Common.Card' - players: - type: array - items: - $ref: '#/components/schemas/Bullshit.BullshitPlayer' - donePlayers: - type: array - items: - $ref: '#/components/schemas/Bullshit.BullshitPlayer' - currentPlayerIndex: - type: integer - format: int32 - claimedTopOfPile: - $ref: '#/components/schemas/Common.Card' - actualTopOfPile: - $ref: '#/components/schemas/Common.Card' - cardsDrawn: - type: integer - format: int32 - potentialBullshit: - $ref: '#/components/schemas/Bullshit.PotentialBullshit' - currentPlayer: - $ref: '#/components/schemas/Bullshit.BullshitPlayer' - additionalProperties: false - Bullshit.BullshitPlayer: - required: - - cards - - id - - name - type: object - properties: - id: - type: string - format: uuid - name: - type: string - cards: - type: array - items: - $ref: '#/components/schemas/Common.Card' - additionalProperties: false - Bullshit.BullshitPlayerNotification: - allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' - - required: - - calledByPlayerId - - card - - punishmentCards - type: object - properties: - calledByPlayerId: - type: string - format: uuid - card: - $ref: '#/components/schemas/Common.Card' - punishmentCards: - type: array - items: - $ref: '#/components/schemas/Common.Card' - additionalProperties: false - Bullshit.BullshitRequest: - allOf: - - $ref: '#/components/schemas/Protocol.DecksterRequest' - - type: object - additionalProperties: false - Bullshit.BullshitResponse: - allOf: - - $ref: '#/components/schemas/Protocol.DecksterResponse' - - required: - - punishmentCards - type: object - properties: - punishmentCards: - type: array - items: - $ref: '#/components/schemas/Common.Card' - additionalProperties: false - Bullshit.CardResponse: + /me: + get: + tags: + - User + responses: + '200': + description: OK + /yaniv/description: + get: + tags: + - Yaniv + responses: + '200': + description: OK + /yaniv/metadata: + get: + tags: + - Yaniv + responses: + '200': + description: OK + content: + text/plain: + schema: + $ref: '#/components/schemas/Meta.GameMeta' + application/json: + schema: + $ref: '#/components/schemas/Meta.GameMeta' + text/json: + schema: + $ref: '#/components/schemas/Meta.GameMeta' + /yaniv: + get: + tags: + - Yaniv + responses: + '200': + description: OK + content: + text/plain: + schema: + $ref: '#/components/schemas/Controllers.GameOverviewVm' + application/json: + schema: + $ref: '#/components/schemas/Controllers.GameOverviewVm' + text/json: + schema: + $ref: '#/components/schemas/Controllers.GameOverviewVm' + /yaniv/games: + get: + tags: + - Yaniv + responses: + '200': + description: OK + content: + text/plain: + schema: + type: array + items: + $ref: '#/components/schemas/Controllers.GameVm' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Controllers.GameVm' + text/json: + schema: + type: array + items: + $ref: '#/components/schemas/Controllers.GameVm' + '/yaniv/games/{name}': + get: + tags: + - Yaniv + parameters: + - name: name + in: path + required: true + schema: + type: string + responses: + '200': + description: OK + content: + text/plain: + schema: + $ref: '#/components/schemas/Controllers.GameVm' + application/json: + schema: + $ref: '#/components/schemas/Controllers.GameVm' + text/json: + schema: + $ref: '#/components/schemas/Controllers.GameVm' + '404': + description: Not Found + content: + text/plain: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + application/json: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + text/json: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + delete: + tags: + - Yaniv + parameters: + - name: name + in: path + required: true + schema: + type: string + responses: + '200': + description: OK + content: + text/plain: + schema: + $ref: '#/components/schemas/Controllers.GameVm' + application/json: + schema: + $ref: '#/components/schemas/Controllers.GameVm' + text/json: + schema: + $ref: '#/components/schemas/Controllers.GameVm' + '404': + description: Not Found + content: + text/plain: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + application/json: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + text/json: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + '/yaniv/games/{name}/bot': + post: + tags: + - Yaniv + parameters: + - name: name + in: path + required: true + schema: + type: string + responses: + '200': + description: OK + content: + text/plain: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + application/json: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + text/json: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + /yaniv/previousgames: + get: + tags: + - Yaniv + responses: + '200': + description: OK + content: + text/plain: + schema: + type: array + items: + $ref: '#/components/schemas/Yaniv.YanivGame' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Yaniv.YanivGame' + text/json: + schema: + type: array + items: + $ref: '#/components/schemas/Yaniv.YanivGame' + '/yaniv/previousgames/{id}': + get: + tags: + - Yaniv + parameters: + - name: id + in: path + required: true + schema: + type: string + format: uuid + responses: + '200': + description: OK + content: + text/plain: + schema: + $ref: '#/components/schemas/Data.HistoricYanivGame' + application/json: + schema: + $ref: '#/components/schemas/Data.HistoricYanivGame' + text/json: + schema: + $ref: '#/components/schemas/Data.HistoricYanivGame' + '/yaniv/previousgames/{id}/{version}': + get: + tags: + - Yaniv + parameters: + - name: id + in: path + required: true + schema: + type: string + format: uuid + - name: version + in: path + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: OK + content: + text/plain: + schema: + $ref: '#/components/schemas/Data.HistoricYanivGame' + application/json: + schema: + $ref: '#/components/schemas/Data.HistoricYanivGame' + text/json: + schema: + $ref: '#/components/schemas/Data.HistoricYanivGame' + '/yaniv/create/{name}': + post: + tags: + - Yaniv + parameters: + - name: name + in: path + required: true + schema: + type: string + responses: + '200': + description: OK + content: + text/plain: + schema: + $ref: '#/components/schemas/Core.GameInfo' + application/json: + schema: + $ref: '#/components/schemas/Core.GameInfo' + text/json: + schema: + $ref: '#/components/schemas/Core.GameInfo' + '400': + description: Bad Request + content: + text/plain: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + application/json: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + text/json: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + /yaniv/create: + post: + tags: + - Yaniv + responses: + '200': + description: OK + content: + text/plain: + schema: + $ref: '#/components/schemas/Core.GameInfo' + application/json: + schema: + $ref: '#/components/schemas/Core.GameInfo' + text/json: + schema: + $ref: '#/components/schemas/Core.GameInfo' + '400': + description: Bad Request + content: + text/plain: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + application/json: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + text/json: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + '/yaniv/games/{name}/start': + post: + tags: + - Yaniv + parameters: + - name: name + in: path + required: true + schema: + type: string + responses: + '200': + description: OK + content: + text/plain: + schema: + $ref: '#/components/schemas/Core.GameInfo' + application/json: + schema: + $ref: '#/components/schemas/Core.GameInfo' + text/json: + schema: + $ref: '#/components/schemas/Core.GameInfo' + '404': + description: Not Found + content: + text/plain: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + application/json: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + text/json: + schema: + $ref: '#/components/schemas/Controllers.ResponseMessage' + '/yaniv/join/{gameName}': + get: + tags: + - Yaniv + parameters: + - name: gameName + in: path + required: true + schema: + type: string + responses: + '200': + description: OK + '/yaniv/join/{connectionId}/finish': + get: + tags: + - Yaniv + parameters: + - name: connectionId + in: path + required: true + schema: + type: string + format: uuid + responses: + '200': + description: OK + '/yaniv/spectate/{gameName}': + get: + tags: + - Yaniv + parameters: + - name: gameName + in: path + required: true + schema: + type: string + responses: + '200': + description: OK + '/yaniv/spectate/{connectionId}/finish': + get: + tags: + - Yaniv + parameters: + - name: connectionId + in: path + required: true + schema: + type: string + format: uuid + responses: + '200': + description: OK +components: + schemas: + Bullshit.BullshitBroadcastNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - required: + - actualCard + - claimedToBeCard + - playerId + - punishmentCardCount + type: object + properties: + playerId: + type: string + format: uuid + claimedToBeCard: + $ref: '#/components/schemas/Common.Card' + actualCard: + $ref: '#/components/schemas/Common.Card' + punishmentCardCount: + type: integer + format: int32 + additionalProperties: false + Bullshit.BullshitGame: + allOf: + - $ref: '#/components/schemas/Games.GameObject' + - required: + - cardsDrawn + - currentPlayer + - currentPlayerIndex + - deck + - discardPile + - donePlayers + - players + - stockPile + type: object + properties: + deck: + type: array + items: + $ref: '#/components/schemas/Common.Card' + stockPile: + type: array + items: + $ref: '#/components/schemas/Common.Card' + discardPile: + type: array + items: + $ref: '#/components/schemas/Common.Card' + players: + type: array + items: + $ref: '#/components/schemas/Bullshit.BullshitPlayer' + donePlayers: + type: array + items: + $ref: '#/components/schemas/Bullshit.BullshitPlayer' + currentPlayerIndex: + type: integer + format: int32 + claimedTopOfPile: + $ref: '#/components/schemas/Common.Card' + actualTopOfPile: + $ref: '#/components/schemas/Common.Card' + cardsDrawn: + type: integer + format: int32 + potentialBullshit: + $ref: '#/components/schemas/Bullshit.PotentialBullshit' + currentPlayer: + $ref: '#/components/schemas/Bullshit.BullshitPlayer' + additionalProperties: false + Bullshit.BullshitPlayer: + required: + - cards + - id + - name + type: object + properties: + id: + type: string + format: uuid + name: + type: string + cards: + type: array + items: + $ref: '#/components/schemas/Common.Card' + additionalProperties: false + Bullshit.BullshitPlayerNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - required: + - calledByPlayerId + - card + - punishmentCards + type: object + properties: + calledByPlayerId: + type: string + format: uuid + card: + $ref: '#/components/schemas/Common.Card' + punishmentCards: + type: array + items: + $ref: '#/components/schemas/Common.Card' + additionalProperties: false + Bullshit.BullshitRequest: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterRequest' + - type: object + additionalProperties: false + Bullshit.BullshitResponse: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterResponse' + - required: + - punishmentCards + type: object + properties: + punishmentCards: + type: array + items: + $ref: '#/components/schemas/Common.Card' + additionalProperties: false + Bullshit.CardResponse: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterResponse' + - required: + - card + type: object + properties: + card: + $ref: '#/components/schemas/Common.Card' + additionalProperties: false + Bullshit.DiscardPileShuffledNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - type: object + additionalProperties: false + Bullshit.DrawCardRequest: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterRequest' + - type: object + additionalProperties: false + Bullshit.FalseBullshitCallNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - required: + - accusedPlayerId + - playerId + - punishmentCardCount + type: object + properties: + playerId: + type: string + format: uuid + accusedPlayerId: + type: string + format: uuid + punishmentCardCount: + type: integer + format: int32 + additionalProperties: false + Bullshit.GameEndedNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - required: + - loserId + - loserName + - players + type: object + properties: + players: + type: array + items: + $ref: '#/components/schemas/Common.PlayerData' + loserId: + type: string + format: uuid + loserName: + type: string + additionalProperties: false + Bullshit.GameStartedNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - required: + - gameId + - playerViewOfGame + type: object + properties: + gameId: + type: string + format: uuid + playerViewOfGame: + $ref: '#/components/schemas/Bullshit.PlayerViewOfGame' + additionalProperties: false + Bullshit.ItsPlayersTurnNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - required: + - playerId + type: object + properties: + playerId: + type: string + format: uuid + additionalProperties: false + Bullshit.ItsYourTurnNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - type: object + additionalProperties: false + Bullshit.OtherBullshitPlayer: + required: + - name + - numberOfCards + - playerId + type: object + properties: + playerId: + type: string + format: uuid + name: + type: string + numberOfCards: + type: integer + format: int32 + additionalProperties: false + Bullshit.PassRequest: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterRequest' + - type: object + additionalProperties: false + Bullshit.PlayerDrewCardNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - required: + - playerId + type: object + properties: + playerId: + type: string + format: uuid + additionalProperties: false + Bullshit.PlayerIsDoneNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - required: + - playerId + type: object + properties: + playerId: + type: string + format: uuid + additionalProperties: false + Bullshit.PlayerPassedNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - required: + - playerId + type: object + properties: + playerId: + type: string + format: uuid + additionalProperties: false + Bullshit.PlayerPutCardNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - required: + - claimedToBeCard + - playerId + type: object + properties: + playerId: + type: string + format: uuid + claimedToBeCard: + $ref: '#/components/schemas/Common.Card' + additionalProperties: false + Bullshit.PlayerViewOfGame: + required: + - cards + - discardPileCount + - otherPlayers + - stockPileCount + type: object + properties: + cards: + type: array + items: + $ref: '#/components/schemas/Common.Card' + claimedTopOfPile: + $ref: '#/components/schemas/Common.Card' + stockPileCount: + type: integer + format: int32 + discardPileCount: + type: integer + format: int32 + otherPlayers: + type: array + items: + $ref: '#/components/schemas/Bullshit.OtherBullshitPlayer' + additionalProperties: false + Bullshit.PotentialBullshit: + required: + - claimedToBeCard + - playerId + type: object + properties: + playerId: + type: string + format: uuid + claimedToBeCard: + $ref: '#/components/schemas/Common.Card' + additionalProperties: false + Bullshit.PutCardRequest: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterRequest' + - required: + - actualCard + - claimedToBeCard + type: object + properties: + actualCard: + $ref: '#/components/schemas/Common.Card' + claimedToBeCard: + $ref: '#/components/schemas/Common.Card' + additionalProperties: false + ChatRoom.ChatNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - required: + - message + - sender + type: object + properties: + sender: + type: string + message: + type: string + additionalProperties: false + ChatRoom.ChatResponse: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterResponse' + - type: object + additionalProperties: false + ChatRoom.ChatRoom: + allOf: + - $ref: '#/components/schemas/Games.GameObject' + - required: + - transcript + type: object + properties: + transcript: + type: array + items: + $ref: '#/components/schemas/ChatRoom.SendChatRequest' + additionalProperties: false + ChatRoom.SendChatRequest: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterRequest' + - required: + - message + type: object + properties: + message: + type: string + additionalProperties: false + Common.Card: + required: + - rank + - suit + type: object + properties: + rank: + type: integer + format: int32 + suit: + $ref: '#/components/schemas/Common.Suit' + additionalProperties: false + Common.EmptyResponse: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterResponse' + - type: object + additionalProperties: false + Common.PlayerData: + required: + - cardsInHand + - id + - info + - name + - points + type: object + properties: + name: + type: string + points: + type: number + format: double + cardsInHand: + type: integer + format: int32 + id: + type: string + format: uuid + info: + type: object + additionalProperties: + type: string + additionalProperties: false + Common.Suit: + enum: + - Clubs + - Diamonds + - Hearts + - Spades + type: string + Controllers.GameOverviewVm: + required: + - games + - gameType + type: object + properties: + gameType: + type: string + games: + type: array + items: + $ref: '#/components/schemas/Controllers.GameVm' + additionalProperties: false + Controllers.GameVm: + required: + - gameType + - name + - players + - state + type: object + properties: + gameType: + type: string + name: + type: string + state: + $ref: '#/components/schemas/Games.GameState' + players: + type: array + items: + $ref: '#/components/schemas/Common.PlayerData' + additionalProperties: false + Controllers.LoginModel: + type: object + properties: + username: + type: string + nullable: true + password: + type: string + nullable: true + additionalProperties: false + Controllers.ResponseMessage: + type: object + properties: + message: + type: string + nullable: true + additionalProperties: false + Core.GameInfo: + required: + - id + type: object + properties: + id: + type: string + additionalProperties: false + CrazyEights.CardResponse: allOf: - $ref: '#/components/schemas/Protocol.DecksterResponse' - required: @@ -3271,36 +4009,106 @@ components: card: $ref: '#/components/schemas/Common.Card' additionalProperties: false - Bullshit.DiscardPileShuffledNotification: + CrazyEights.CrazyEightsGame: + allOf: + - $ref: '#/components/schemas/Games.GameObject' + - required: + - cardsDrawn + - currentPlayer + - currentPlayerIndex + - currentSuit + - deck + - discardPile + - donePlayers + - initialCardsPerPlayer + - players + - spectators + - stockPile + - topOfPile + type: object + properties: + initialCardsPerPlayer: + type: integer + format: int32 + currentPlayerIndex: + type: integer + format: int32 + cardsDrawn: + type: integer + format: int32 + donePlayers: + type: array + items: + $ref: '#/components/schemas/CrazyEights.CrazyEightsPlayer' + deck: + type: array + items: + $ref: '#/components/schemas/Common.Card' + stockPile: + type: array + items: + $ref: '#/components/schemas/Common.Card' + discardPile: + type: array + items: + $ref: '#/components/schemas/Common.Card' + players: + type: array + items: + $ref: '#/components/schemas/CrazyEights.CrazyEightsPlayer' + spectators: + type: array + items: + $ref: '#/components/schemas/CrazyEights.CrazyEightsSpectator' + newSuit: + $ref: '#/components/schemas/Common.Suit' + topOfPile: + $ref: '#/components/schemas/Common.Card' + currentSuit: + $ref: '#/components/schemas/Common.Suit' + currentPlayer: + $ref: '#/components/schemas/CrazyEights.CrazyEightsPlayer' + additionalProperties: false + CrazyEights.CrazyEightsPlayer: + required: + - cards + - id + - name + type: object + properties: + id: + type: string + format: uuid + name: + type: string + cards: + type: array + items: + $ref: '#/components/schemas/Common.Card' + additionalProperties: false + CrazyEights.CrazyEightsSpectator: + required: + - id + - name + type: object + properties: + id: + type: string + format: uuid + name: + type: string + additionalProperties: false + CrazyEights.DiscardPileShuffledNotification: allOf: - $ref: '#/components/schemas/Protocol.DecksterNotification' - type: object additionalProperties: false - Bullshit.DrawCardRequest: + CrazyEights.DrawCardRequest: allOf: - $ref: '#/components/schemas/Protocol.DecksterRequest' - type: object additionalProperties: false - Bullshit.FalseBullshitCallNotification: - allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' - - required: - - accusedPlayerId - - playerId - - punishmentCardCount - type: object - properties: - playerId: - type: string - format: uuid - accusedPlayerId: - type: string - format: uuid - punishmentCardCount: - type: integer - format: int32 - additionalProperties: false - Bullshit.GameEndedNotification: + CrazyEights.GameEndedNotification: allOf: - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: @@ -3319,7 +4127,7 @@ components: loserName: type: string additionalProperties: false - Bullshit.GameStartedNotification: + CrazyEights.GameStartedNotification: allOf: - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: @@ -3331,9 +4139,9 @@ components: type: string format: uuid playerViewOfGame: - $ref: '#/components/schemas/Bullshit.PlayerViewOfGame' + $ref: '#/components/schemas/CrazyEights.PlayerViewOfGame' additionalProperties: false - Bullshit.ItsPlayersTurnNotification: + CrazyEights.ItsPlayersTurnNotification: allOf: - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: @@ -3344,12 +4152,17 @@ components: type: string format: uuid additionalProperties: false - Bullshit.ItsYourTurnNotification: + CrazyEights.ItsYourTurnNotification: allOf: - $ref: '#/components/schemas/Protocol.DecksterNotification' - - type: object + - required: + - playerViewOfGame + type: object + properties: + playerViewOfGame: + $ref: '#/components/schemas/CrazyEights.PlayerViewOfGame' additionalProperties: false - Bullshit.OtherBullshitPlayer: + CrazyEights.OtherCrazyEightsPlayer: required: - name - numberOfCards @@ -3365,34 +4178,12 @@ components: type: integer format: int32 additionalProperties: false - Bullshit.PassRequest: + CrazyEights.PassRequest: allOf: - $ref: '#/components/schemas/Protocol.DecksterRequest' - type: object additionalProperties: false - Bullshit.PlayerDrewCardNotification: - allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' - - required: - - playerId - type: object - properties: - playerId: - type: string - format: uuid - additionalProperties: false - Bullshit.PlayerIsDoneNotification: - allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' - - required: - - playerId - type: object - properties: - playerId: - type: string - format: uuid - additionalProperties: false - Bullshit.PlayerPassedNotification: + CrazyEights.PlayerDrewCardNotification: allOf: - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: @@ -3403,219 +4194,206 @@ components: type: string format: uuid additionalProperties: false - Bullshit.PlayerPutCardNotification: + CrazyEights.PlayerIsDoneNotification: allOf: - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: - - claimedToBeCard - playerId type: object properties: - playerId: - type: string - format: uuid - claimedToBeCard: - $ref: '#/components/schemas/Common.Card' - additionalProperties: false - Bullshit.PlayerViewOfGame: - required: - - cards - - discardPileCount - - otherPlayers - - stockPileCount - type: object - properties: - cards: - type: array - items: - $ref: '#/components/schemas/Common.Card' - claimedTopOfPile: - $ref: '#/components/schemas/Common.Card' - stockPileCount: - type: integer - format: int32 - discardPileCount: - type: integer - format: int32 - otherPlayers: - type: array - items: - $ref: '#/components/schemas/Bullshit.OtherBullshitPlayer' - additionalProperties: false - Bullshit.PotentialBullshit: - required: - - claimedToBeCard - - playerId - type: object - properties: - playerId: - type: string - format: uuid - claimedToBeCard: - $ref: '#/components/schemas/Common.Card' - additionalProperties: false - Bullshit.PutCardRequest: + playerId: + type: string + format: uuid + additionalProperties: false + CrazyEights.PlayerPassedNotification: allOf: - - $ref: '#/components/schemas/Protocol.DecksterRequest' + - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: - - actualCard - - claimedToBeCard + - playerId type: object properties: - actualCard: - $ref: '#/components/schemas/Common.Card' - claimedToBeCard: - $ref: '#/components/schemas/Common.Card' + playerId: + type: string + format: uuid additionalProperties: false - ChatRoom.ChatNotification: + CrazyEights.PlayerPutCardNotification: allOf: - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: - - message - - sender + - card + - playerId type: object properties: - sender: - type: string - message: + playerId: type: string + format: uuid + card: + $ref: '#/components/schemas/Common.Card' additionalProperties: false - ChatRoom.ChatResponse: + CrazyEights.PlayerPutEightNotification: allOf: - - $ref: '#/components/schemas/Protocol.DecksterResponse' - - type: object + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - required: + - card + - newSuit + - playerId + type: object + properties: + playerId: + type: string + format: uuid + card: + $ref: '#/components/schemas/Common.Card' + newSuit: + $ref: '#/components/schemas/Common.Suit' additionalProperties: false - ChatRoom.ChatRoom: + CrazyEights.PlayerViewOfGame: allOf: - - $ref: '#/components/schemas/Games.GameObject' + - $ref: '#/components/schemas/Protocol.DecksterResponse' - required: - - transcript + - cards + - currentSuit + - discardPileCount + - otherPlayers + - stockPileCount + - topOfPile type: object properties: - transcript: + cards: type: array items: - $ref: '#/components/schemas/ChatRoom.SendChatRequest' + $ref: '#/components/schemas/Common.Card' + topOfPile: + $ref: '#/components/schemas/Common.Card' + currentSuit: + $ref: '#/components/schemas/Common.Suit' + stockPileCount: + type: integer + format: int32 + discardPileCount: + type: integer + format: int32 + otherPlayers: + type: array + items: + $ref: '#/components/schemas/CrazyEights.OtherCrazyEightsPlayer' additionalProperties: false - ChatRoom.SendChatRequest: + CrazyEights.PutCardRequest: allOf: - $ref: '#/components/schemas/Protocol.DecksterRequest' - required: - - message + - card type: object properties: - message: - type: string + card: + $ref: '#/components/schemas/Common.Card' additionalProperties: false - Common.Card: - required: - - rank - - suit - type: object - properties: - rank: - type: integer - format: int32 - suit: - $ref: '#/components/schemas/Common.Suit' - additionalProperties: false - Common.EmptyResponse: + CrazyEights.PutEightRequest: allOf: - - $ref: '#/components/schemas/Protocol.DecksterResponse' - - type: object + - $ref: '#/components/schemas/Protocol.DecksterRequest' + - required: + - card + - newSuit + type: object + properties: + card: + $ref: '#/components/schemas/Common.Card' + newSuit: + $ref: '#/components/schemas/Common.Suit' additionalProperties: false - Common.PlayerData: + Data.DatabaseObject: required: - - cardsInHand - id - - info - - name - - points + - type type: object properties: - name: + type: type: string - points: - type: number - format: double - cardsInHand: - type: integer - format: int32 + readOnly: true id: type: string format: uuid - info: - type: object - additionalProperties: - type: string additionalProperties: false - Common.Suit: - enum: - - Clubs - - Diamonds - - Hearts - - Spades - type: string - Controllers.GameOverviewVm: - required: - - games - - gameType + discriminator: + propertyName: type + mapping: + Games.GameObject: '#/components/schemas/Games.GameObject' + Yaniv.YanivGame: '#/components/schemas/Yaniv.YanivGame' + Uno.UnoGame: '#/components/schemas/Uno.UnoGame' + TexasHoldEm.TexasHoldEmGame: '#/components/schemas/TexasHoldEm.TexasHoldEmGame' + Idiot.IdiotGame: '#/components/schemas/Idiot.IdiotGame' + Hearts.HeartsGame: '#/components/schemas/Hearts.HeartsGame' + Gabong.GabongGame: '#/components/schemas/Gabong.GabongGame' + CrazyEights.CrazyEightsGame: '#/components/schemas/CrazyEights.CrazyEightsGame' + ChatRoom.ChatRoom: '#/components/schemas/ChatRoom.ChatRoom' + Bullshit.BullshitGame: '#/components/schemas/Bullshit.BullshitGame' + Data.HistoricBullshitGame: type: object properties: - gameType: - type: string - games: - type: array - items: - $ref: '#/components/schemas/Controllers.GameVm' + game: + $ref: '#/components/schemas/Bullshit.BullshitGame' additionalProperties: false - Controllers.GameVm: - required: - - gameType - - name - - players - - state + Data.HistoricChatRoom: type: object properties: - gameType: - type: string - name: - type: string - state: - $ref: '#/components/schemas/Games.GameState' - players: - type: array - items: - $ref: '#/components/schemas/Common.PlayerData' + game: + $ref: '#/components/schemas/ChatRoom.ChatRoom' additionalProperties: false - Controllers.LoginModel: + Data.HistoricCrazyEightsGame: type: object properties: - username: - type: string - nullable: true - password: - type: string - nullable: true + game: + $ref: '#/components/schemas/CrazyEights.CrazyEightsGame' additionalProperties: false - Controllers.ResponseMessage: + Data.HistoricGabongGame: type: object properties: - message: - type: string - nullable: true + game: + $ref: '#/components/schemas/Gabong.GabongGame' additionalProperties: false - Core.GameInfo: - required: - - id + Data.HistoricHeartsGame: type: object properties: - id: - type: string + game: + $ref: '#/components/schemas/Hearts.HeartsGame' additionalProperties: false - CrazyEights.CardResponse: + Data.HistoricIdiotGame: + type: object + properties: + game: + $ref: '#/components/schemas/Idiot.IdiotGame' + additionalProperties: false + Data.HistoricTexasHoldEmGame: + type: object + properties: + game: + $ref: '#/components/schemas/TexasHoldEm.TexasHoldEmGame' + additionalProperties: false + Data.HistoricUnoGame: + type: object + properties: + game: + $ref: '#/components/schemas/Uno.UnoGame' + additionalProperties: false + Data.HistoricYanivGame: + type: object + properties: + game: + $ref: '#/components/schemas/Yaniv.YanivGame' + additionalProperties: false + Gabong.ActionResponse: allOf: - $ref: '#/components/schemas/Protocol.DecksterResponse' + - type: object + additionalProperties: false + Gabong.DrawCardRequest: + allOf: + - $ref: '#/components/schemas/Gabong.GabongRequest' + - type: object + additionalProperties: false + Gabong.GabongCardResponse: + allOf: + - $ref: '#/components/schemas/Gabong.GabongResponse' - required: - card type: object @@ -3623,37 +4401,42 @@ components: card: $ref: '#/components/schemas/Common.Card' additionalProperties: false - CrazyEights.CrazyEightsGame: + Gabong.GabongGame: allOf: - $ref: '#/components/schemas/Games.GameObject' - required: - cardsDrawn + - cardsToDraw - currentPlayer - - currentPlayerIndex - currentSuit - deck - discardPile - - donePlayers - - initialCardsPerPlayer + - gabongMasterId + - gameDirection + - isBetweenRounds + - lastPlayMadeByPlayerIndex - players - - spectators - stockPile - topOfPile type: object properties: - initialCardsPerPlayer: + lastPlayMadeByPlayerIndex: type: integer format: int32 - currentPlayerIndex: + cardsToDraw: type: integer format: int32 cardsDrawn: type: integer format: int32 - donePlayers: - type: array - items: - $ref: '#/components/schemas/CrazyEights.CrazyEightsPlayer' + gameDirection: + type: integer + format: int32 + gabongMasterId: + type: string + format: uuid + isBetweenRounds: + type: boolean deck: type: array items: @@ -3669,11 +4452,7 @@ components: players: type: array items: - $ref: '#/components/schemas/CrazyEights.CrazyEightsPlayer' - spectators: - type: array - items: - $ref: '#/components/schemas/CrazyEights.CrazyEightsSpectator' + $ref: '#/components/schemas/Gabong.GabongPlayer' newSuit: $ref: '#/components/schemas/Common.Suit' topOfPile: @@ -3681,13 +4460,47 @@ components: currentSuit: $ref: '#/components/schemas/Common.Suit' currentPlayer: - $ref: '#/components/schemas/CrazyEights.CrazyEightsPlayer' + $ref: '#/components/schemas/Gabong.GabongPlayer' additionalProperties: false - CrazyEights.CrazyEightsPlayer: + Gabong.GabongGameNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - type: object + additionalProperties: false + discriminator: + propertyName: type + mapping: + Gabong.GabongPlayerNotification: '#/components/schemas/Gabong.GabongPlayerNotification' + Gabong.PlayerPutCardNotification: '#/components/schemas/Gabong.PlayerPutCardNotification' + Gabong.PlayerDrewCardNotification: '#/components/schemas/Gabong.PlayerDrewCardNotification' + Gabong.PlayerDrewPenaltyCardNotification: '#/components/schemas/Gabong.PlayerDrewPenaltyCardNotification' + Gabong.GameStartedNotification: '#/components/schemas/Gabong.GameStartedNotification' + Gabong.GameEndedNotification: '#/components/schemas/Gabong.GameEndedNotification' + Gabong.RoundStartedNotification: '#/components/schemas/Gabong.RoundStartedNotification' + Gabong.RoundEndedNotification: '#/components/schemas/Gabong.RoundEndedNotification' + Gabong.PlayerLostTheirTurnNotification: '#/components/schemas/Gabong.PlayerLostTheirTurnNotification' + Gabong.GabongPlay: + enum: + - CardPlayed + - TurnLost + - RoundStarted + type: string + Gabong.GabongPlayer: required: + - bongas - cards + - cardsPlayed + - debtDrawn + - gabongs + - hasWon - id - name + - passes + - penalties + - roundsWon + - score + - shots + - turnsLost type: object properties: id: @@ -3699,35 +4512,93 @@ components: type: array items: $ref: '#/components/schemas/Common.Card' + readOnly: true + score: + type: integer + format: int32 + hasWon: + type: boolean + readOnly: true + penalties: + type: integer + format: int32 + gabongs: + type: integer + format: int32 + bongas: + type: integer + format: int32 + shots: + type: integer + format: int32 + cardsPlayed: + type: integer + format: int32 + debtDrawn: + type: integer + format: int32 + passes: + type: integer + format: int32 + turnsLost: + type: integer + format: int32 + roundsWon: + type: integer + format: int32 additionalProperties: false - CrazyEights.CrazyEightsSpectator: - required: - - id - - name - type: object - properties: - id: - type: string - format: uuid - name: - type: string - additionalProperties: false - CrazyEights.DiscardPileShuffledNotification: + Gabong.GabongPlayerNotification: allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' - - type: object + - $ref: '#/components/schemas/Gabong.GabongGameNotification' + - required: + - playerId + type: object + properties: + playerId: + type: string + format: uuid additionalProperties: false - CrazyEights.DrawCardRequest: + discriminator: + propertyName: type + mapping: + Gabong.PlayerPutCardNotification: '#/components/schemas/Gabong.PlayerPutCardNotification' + Gabong.PlayerDrewCardNotification: '#/components/schemas/Gabong.PlayerDrewCardNotification' + Gabong.PlayerDrewPenaltyCardNotification: '#/components/schemas/Gabong.PlayerDrewPenaltyCardNotification' + Gabong.PlayerLostTheirTurnNotification: '#/components/schemas/Gabong.PlayerLostTheirTurnNotification' + Gabong.GabongRequest: allOf: - $ref: '#/components/schemas/Protocol.DecksterRequest' - type: object additionalProperties: false - CrazyEights.GameEndedNotification: + discriminator: + propertyName: type + mapping: + Gabong.PutCardRequest: '#/components/schemas/Gabong.PutCardRequest' + Gabong.DrawCardRequest: '#/components/schemas/Gabong.DrawCardRequest' + Gabong.PassRequest: '#/components/schemas/Gabong.PassRequest' + Gabong.PlayGabongRequest: '#/components/schemas/Gabong.PlayGabongRequest' + Gabong.PlayBongaRequest: '#/components/schemas/Gabong.PlayBongaRequest' + Gabong.GabongResponse: allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' + - $ref: '#/components/schemas/Protocol.DecksterResponse' + - required: + - cardsAdded + type: object + properties: + cardsAdded: + type: array + items: + $ref: '#/components/schemas/Common.Card' + additionalProperties: false + discriminator: + propertyName: type + mapping: + Gabong.GabongCardResponse: '#/components/schemas/Gabong.GabongCardResponse' + Gabong.PlayerViewOfGame: '#/components/schemas/Gabong.PlayerViewOfGame' + Gabong.GameEndedNotification: + allOf: + - $ref: '#/components/schemas/Gabong.GabongGameNotification' - required: - - loserId - - loserName - players type: object properties: @@ -3735,140 +4606,110 @@ components: type: array items: $ref: '#/components/schemas/Common.PlayerData' - loserId: - type: string - format: uuid - loserName: - type: string additionalProperties: false - CrazyEights.GameStartedNotification: + Gabong.GameStartedNotification: allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' + - $ref: '#/components/schemas/Gabong.GabongGameNotification' - required: - gameId - - playerViewOfGame type: object properties: gameId: type: string format: uuid - playerViewOfGame: - $ref: '#/components/schemas/CrazyEights.PlayerViewOfGame' additionalProperties: false - CrazyEights.ItsPlayersTurnNotification: + Gabong.PassRequest: allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' - - required: - - playerId - type: object - properties: - playerId: - type: string - format: uuid + - $ref: '#/components/schemas/Gabong.GabongRequest' + - type: object additionalProperties: false - CrazyEights.ItsYourTurnNotification: + Gabong.PenalizePlayerForTakingTooLongRequest: allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' - - required: - - playerViewOfGame - type: object - properties: - playerViewOfGame: - $ref: '#/components/schemas/CrazyEights.PlayerViewOfGame' + - $ref: '#/components/schemas/Protocol.DecksterRequest' + - type: object additionalProperties: false - CrazyEights.OtherCrazyEightsPlayer: - required: - - name - - numberOfCards - - playerId - type: object - properties: - playerId: - type: string - format: uuid - name: - type: string - numberOfCards: - type: integer - format: int32 - additionalProperties: false - CrazyEights.PassRequest: + Gabong.PenalizePlayerForTooManyCardsRequest: allOf: - $ref: '#/components/schemas/Protocol.DecksterRequest' - type: object additionalProperties: false - CrazyEights.PlayerDrewCardNotification: + Gabong.PenaltyReason: + enum: + - PlayOutOfTurn + - TookTooLong + - WrongPlay + - WrongGabong + - WrongBonga + - UnpaidDebt + - PassWithoutDrawing + type: string + Gabong.PlayBongaRequest: allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' - - required: - - playerId - type: object - properties: - playerId: - type: string - format: uuid + - $ref: '#/components/schemas/Gabong.GabongRequest' + - type: object additionalProperties: false - CrazyEights.PlayerIsDoneNotification: + Gabong.PlayGabongRequest: allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' - - required: - - playerId - type: object - properties: - playerId: - type: string - format: uuid + - $ref: '#/components/schemas/Gabong.GabongRequest' + - type: object additionalProperties: false - CrazyEights.PlayerPassedNotification: + Gabong.PlayerDrewCardNotification: allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' + - $ref: '#/components/schemas/Gabong.GabongPlayerNotification' + - type: object + additionalProperties: false + Gabong.PlayerDrewPenaltyCardNotification: + allOf: + - $ref: '#/components/schemas/Gabong.GabongPlayerNotification' - required: - - playerId + - penaltyReason type: object properties: - playerId: - type: string - format: uuid + penaltyReason: + $ref: '#/components/schemas/Gabong.PenaltyReason' additionalProperties: false - CrazyEights.PlayerPutCardNotification: + Gabong.PlayerLostTheirTurnNotification: allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' + - $ref: '#/components/schemas/Gabong.GabongPlayerNotification' - required: - - card - - playerId + - lostTurnReason type: object properties: - playerId: - type: string - format: uuid - card: - $ref: '#/components/schemas/Common.Card' + lostTurnReason: + $ref: '#/components/schemas/Gabong.PlayerLostTurnReason' additionalProperties: false - CrazyEights.PlayerPutEightNotification: + Gabong.PlayerLostTurnReason: + enum: + - Passed + - WrongPlay + - TookTooLong + - FinishedDrawingCardDebt + type: string + Gabong.PlayerPutCardNotification: allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' + - $ref: '#/components/schemas/Gabong.GabongPlayerNotification' - required: - card - - newSuit - - playerId type: object properties: - playerId: - type: string - format: uuid card: $ref: '#/components/schemas/Common.Card' newSuit: $ref: '#/components/schemas/Common.Suit' additionalProperties: false - CrazyEights.PlayerViewOfGame: + Gabong.PlayerViewOfGame: allOf: - - $ref: '#/components/schemas/Protocol.DecksterResponse' + - $ref: '#/components/schemas/Gabong.GabongResponse' - required: + - cardDebtToDraw - cards - currentSuit - discardPileCount - - otherPlayers + - lastPlay + - lastPlayMadeByPlayerId + - players + - playersOrder + - roundStarted - stockPileCount - topOfPile type: object @@ -3887,27 +4728,31 @@ components: discardPileCount: type: integer format: int32 - otherPlayers: + roundStarted: + type: boolean + lastPlayMadeByPlayerId: + type: string + format: uuid + lastPlay: + $ref: '#/components/schemas/Gabong.GabongPlay' + players: type: array items: - $ref: '#/components/schemas/CrazyEights.OtherCrazyEightsPlayer' - additionalProperties: false - CrazyEights.PutCardRequest: - allOf: - - $ref: '#/components/schemas/Protocol.DecksterRequest' - - required: - - card - type: object - properties: - card: - $ref: '#/components/schemas/Common.Card' + $ref: '#/components/schemas/Gabong.SlimGabongPlayer' + playersOrder: + type: array + items: + type: string + format: uuid + cardDebtToDraw: + type: integer + format: int32 additionalProperties: false - CrazyEights.PutEightRequest: + Gabong.PutCardRequest: allOf: - - $ref: '#/components/schemas/Protocol.DecksterRequest' + - $ref: '#/components/schemas/Gabong.GabongRequest' - required: - card - - newSuit type: object properties: card: @@ -3915,199 +4760,37 @@ components: newSuit: $ref: '#/components/schemas/Common.Suit' additionalProperties: false - Data.DatabaseObject: - required: - - id - - type - type: object - properties: - type: - type: string - readOnly: true - id: - type: string - format: uuid - additionalProperties: false - discriminator: - propertyName: type - mapping: - Games.GameObject: '#/components/schemas/Games.GameObject' - Yaniv.YanivGame: '#/components/schemas/Yaniv.YanivGame' - Uno.UnoGame: '#/components/schemas/Uno.UnoGame' - TexasHoldEm.TexasHoldEmGame: '#/components/schemas/TexasHoldEm.TexasHoldEmGame' - Idiot.IdiotGame: '#/components/schemas/Idiot.IdiotGame' - Gabong.GabongGame: '#/components/schemas/Gabong.GabongGame' - CrazyEights.CrazyEightsGame: '#/components/schemas/CrazyEights.CrazyEightsGame' - ChatRoom.ChatRoom: '#/components/schemas/ChatRoom.ChatRoom' - Bullshit.BullshitGame: '#/components/schemas/Bullshit.BullshitGame' - Data.HistoricBullshitGame: - type: object - properties: - game: - $ref: '#/components/schemas/Bullshit.BullshitGame' - additionalProperties: false - Data.HistoricChatRoom: - type: object - properties: - game: - $ref: '#/components/schemas/ChatRoom.ChatRoom' - additionalProperties: false - Data.HistoricCrazyEightsGame: - type: object - properties: - game: - $ref: '#/components/schemas/CrazyEights.CrazyEightsGame' - additionalProperties: false - Data.HistoricGabongGame: - type: object - properties: - game: - $ref: '#/components/schemas/Gabong.GabongGame' - additionalProperties: false - Data.HistoricIdiotGame: - type: object - properties: - game: - $ref: '#/components/schemas/Idiot.IdiotGame' - additionalProperties: false - Data.HistoricTexasHoldEmGame: - type: object - properties: - game: - $ref: '#/components/schemas/TexasHoldEm.TexasHoldEmGame' - additionalProperties: false - Data.HistoricUnoGame: - type: object - properties: - game: - $ref: '#/components/schemas/Uno.UnoGame' - additionalProperties: false - Data.HistoricYanivGame: - type: object - properties: - game: - $ref: '#/components/schemas/Yaniv.YanivGame' - additionalProperties: false - Gabong.ActionResponse: - allOf: - - $ref: '#/components/schemas/Protocol.DecksterResponse' - - type: object - additionalProperties: false - Gabong.DrawCardRequest: - allOf: - - $ref: '#/components/schemas/Gabong.GabongRequest' - - type: object - additionalProperties: false - Gabong.GabongCardResponse: - allOf: - - $ref: '#/components/schemas/Gabong.GabongResponse' - - required: - - card - type: object - properties: - card: - $ref: '#/components/schemas/Common.Card' - additionalProperties: false - Gabong.GabongGame: + Gabong.RoundEndedNotification: allOf: - - $ref: '#/components/schemas/Games.GameObject' + - $ref: '#/components/schemas/Gabong.GabongGameNotification' - required: - - cardsDrawn - - cardsToDraw - - currentPlayer - - currentSuit - - deck - - discardPile - - gabongMasterId - - gameDirection - - isBetweenRounds - - lastPlayMadeByPlayerIndex - players - - stockPile - - topOfPile type: object properties: - lastPlayMadeByPlayerIndex: - type: integer - format: int32 - cardsToDraw: - type: integer - format: int32 - cardsDrawn: - type: integer - format: int32 - gameDirection: - type: integer - format: int32 - gabongMasterId: - type: string - format: uuid - isBetweenRounds: - type: boolean - deck: - type: array - items: - $ref: '#/components/schemas/Common.Card' - stockPile: - type: array - items: - $ref: '#/components/schemas/Common.Card' - discardPile: - type: array - items: - $ref: '#/components/schemas/Common.Card' players: type: array items: - $ref: '#/components/schemas/Gabong.GabongPlayer' - newSuit: - $ref: '#/components/schemas/Common.Suit' - topOfPile: - $ref: '#/components/schemas/Common.Card' - currentSuit: - $ref: '#/components/schemas/Common.Suit' - currentPlayer: - $ref: '#/components/schemas/Gabong.GabongPlayer' + $ref: '#/components/schemas/Common.PlayerData' additionalProperties: false - Gabong.GabongGameNotification: + Gabong.RoundStartedNotification: allOf: - - $ref: '#/components/schemas/Protocol.DecksterNotification' - - type: object - additionalProperties: false - discriminator: - propertyName: type - mapping: - Gabong.GabongPlayerNotification: '#/components/schemas/Gabong.GabongPlayerNotification' - Gabong.PlayerPutCardNotification: '#/components/schemas/Gabong.PlayerPutCardNotification' - Gabong.PlayerDrewCardNotification: '#/components/schemas/Gabong.PlayerDrewCardNotification' - Gabong.PlayerDrewPenaltyCardNotification: '#/components/schemas/Gabong.PlayerDrewPenaltyCardNotification' - Gabong.GameStartedNotification: '#/components/schemas/Gabong.GameStartedNotification' - Gabong.GameEndedNotification: '#/components/schemas/Gabong.GameEndedNotification' - Gabong.RoundStartedNotification: '#/components/schemas/Gabong.RoundStartedNotification' - Gabong.RoundEndedNotification: '#/components/schemas/Gabong.RoundEndedNotification' - Gabong.PlayerLostTheirTurnNotification: '#/components/schemas/Gabong.PlayerLostTheirTurnNotification' - Gabong.GabongPlay: - enum: - - CardPlayed - - TurnLost - - RoundStarted - type: string - Gabong.GabongPlayer: + - $ref: '#/components/schemas/Gabong.GabongGameNotification' + - required: + - playerViewOfGame + - startingPlayerId + type: object + properties: + playerViewOfGame: + $ref: '#/components/schemas/Gabong.PlayerViewOfGame' + startingPlayerId: + type: string + format: uuid + additionalProperties: false + Gabong.SlimGabongPlayer: required: - - bongas - - cards - - cardsPlayed - - debtDrawn - - gabongs - - hasWon - id - name - - passes - - penalties - - roundsWon - - score - - shots - - turnsLost + - numberOfCards type: object properties: id: @@ -4115,382 +4798,476 @@ components: format: uuid name: type: string - cards: - type: array - items: - $ref: '#/components/schemas/Common.Card' - readOnly: true - score: - type: integer - format: int32 - hasWon: - type: boolean - readOnly: true - penalties: - type: integer - format: int32 - gabongs: - type: integer - format: int32 - bongas: - type: integer - format: int32 - shots: - type: integer - format: int32 - cardsPlayed: - type: integer - format: int32 - debtDrawn: - type: integer - format: int32 - passes: - type: integer - format: int32 - turnsLost: - type: integer - format: int32 - roundsWon: + numberOfCards: type: integer format: int32 additionalProperties: false - Gabong.GabongPlayerNotification: + Games.GameObject: allOf: - - $ref: '#/components/schemas/Gabong.GabongGameNotification' + - $ref: '#/components/schemas/Data.DatabaseObject' - required: - - playerId + - name + - seed + - startedTime + - state + - version type: object properties: - playerId: + name: type: string - format: uuid + startedTime: + type: string + format: date-time + state: + $ref: '#/components/schemas/Games.GameState' + version: + type: integer + format: int32 + seed: + type: integer + format: int32 additionalProperties: false discriminator: propertyName: type mapping: - Gabong.PlayerPutCardNotification: '#/components/schemas/Gabong.PlayerPutCardNotification' - Gabong.PlayerDrewCardNotification: '#/components/schemas/Gabong.PlayerDrewCardNotification' - Gabong.PlayerDrewPenaltyCardNotification: '#/components/schemas/Gabong.PlayerDrewPenaltyCardNotification' - Gabong.PlayerLostTheirTurnNotification: '#/components/schemas/Gabong.PlayerLostTheirTurnNotification' - Gabong.GabongRequest: + Yaniv.YanivGame: '#/components/schemas/Yaniv.YanivGame' + Uno.UnoGame: '#/components/schemas/Uno.UnoGame' + TexasHoldEm.TexasHoldEmGame: '#/components/schemas/TexasHoldEm.TexasHoldEmGame' + Idiot.IdiotGame: '#/components/schemas/Idiot.IdiotGame' + Hearts.HeartsGame: '#/components/schemas/Hearts.HeartsGame' + Gabong.GabongGame: '#/components/schemas/Gabong.GabongGame' + CrazyEights.CrazyEightsGame: '#/components/schemas/CrazyEights.CrazyEightsGame' + ChatRoom.ChatRoom: '#/components/schemas/ChatRoom.ChatRoom' + Bullshit.BullshitGame: '#/components/schemas/Bullshit.BullshitGame' + Games.GameState: + enum: + - Waiting + - Running + - Finished + - RoundFinished + type: string + Handshake.ConnectFailureMessage: allOf: - - $ref: '#/components/schemas/Protocol.DecksterRequest' + - $ref: '#/components/schemas/Handshake.ConnectMessage' + - required: + - errorMessage + type: object + properties: + errorMessage: + type: string + additionalProperties: false + Handshake.ConnectMessage: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterMessage' - type: object additionalProperties: false discriminator: propertyName: type mapping: - Gabong.PutCardRequest: '#/components/schemas/Gabong.PutCardRequest' - Gabong.DrawCardRequest: '#/components/schemas/Gabong.DrawCardRequest' - Gabong.PassRequest: '#/components/schemas/Gabong.PassRequest' - Gabong.PlayGabongRequest: '#/components/schemas/Gabong.PlayGabongRequest' - Gabong.PlayBongaRequest: '#/components/schemas/Gabong.PlayBongaRequest' - Gabong.GabongResponse: + Handshake.HelloSuccessMessage: '#/components/schemas/Handshake.HelloSuccessMessage' + Handshake.ConnectSuccessMessage: '#/components/schemas/Handshake.ConnectSuccessMessage' + Handshake.ConnectFailureMessage: '#/components/schemas/Handshake.ConnectFailureMessage' + Handshake.ConnectSuccessMessage: allOf: - - $ref: '#/components/schemas/Protocol.DecksterResponse' + - $ref: '#/components/schemas/Handshake.ConnectMessage' + - type: object + additionalProperties: false + Handshake.HelloSuccessMessage: + allOf: + - $ref: '#/components/schemas/Handshake.ConnectMessage' - required: - - cardsAdded + - connectionId + - player type: object properties: - cardsAdded: + player: + $ref: '#/components/schemas/Common.PlayerData' + connectionId: + type: string + format: uuid + additionalProperties: false + Hearts.AllPlayersPassedNotification: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - required: + - receivedCards + type: object + properties: + receivedCards: type: array items: $ref: '#/components/schemas/Common.Card' additionalProperties: false - discriminator: - propertyName: type - mapping: - Gabong.GabongCardResponse: '#/components/schemas/Gabong.GabongCardResponse' - Gabong.PlayerViewOfGame: '#/components/schemas/Gabong.PlayerViewOfGame' - Gabong.GameEndedNotification: + Hearts.CardPlay: + required: + - card + - playerId + - playerName + type: object + properties: + playerId: + type: string + format: uuid + playerName: + type: string + card: + $ref: '#/components/schemas/Common.Card' + additionalProperties: false + Hearts.GameEndedNotification: allOf: - - $ref: '#/components/schemas/Gabong.GabongGameNotification' + - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: - - players + - finalScores + - winnerId + - winnerName type: object properties: - players: + finalScores: type: array items: - $ref: '#/components/schemas/Common.PlayerData' + $ref: '#/components/schemas/Hearts.PlayerScore' + winnerId: + type: string + format: uuid + winnerName: + type: string additionalProperties: false - Gabong.GameStartedNotification: + Hearts.GamePhase: + enum: + - Passing + - Playing + type: string + Hearts.GameStartedNotification: allOf: - - $ref: '#/components/schemas/Gabong.GabongGameNotification' + - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: - gameId + - playerViewOfGame type: object properties: gameId: type: string format: uuid + playerViewOfGame: + $ref: '#/components/schemas/Hearts.PlayerViewOfGame' additionalProperties: false - Gabong.PassRequest: - allOf: - - $ref: '#/components/schemas/Gabong.GabongRequest' - - type: object - additionalProperties: false - Gabong.PenalizePlayerForTakingTooLongRequest: - allOf: - - $ref: '#/components/schemas/Protocol.DecksterRequest' - - type: object - additionalProperties: false - Gabong.PenalizePlayerForTooManyCardsRequest: - allOf: - - $ref: '#/components/schemas/Protocol.DecksterRequest' - - type: object - additionalProperties: false - Gabong.PenaltyReason: - enum: - - PlayOutOfTurn - - TookTooLong - - WrongPlay - - WrongGabong - - WrongBonga - - UnpaidDebt - - PassWithoutDrawing - type: string - Gabong.PlayBongaRequest: - allOf: - - $ref: '#/components/schemas/Gabong.GabongRequest' - - type: object - additionalProperties: false - Gabong.PlayGabongRequest: + Hearts.HeartsAreBrokenNotification: allOf: - - $ref: '#/components/schemas/Gabong.GabongRequest' + - $ref: '#/components/schemas/Protocol.DecksterNotification' - type: object additionalProperties: false - Gabong.PlayerDrewCardNotification: + Hearts.HeartsGame: allOf: - - $ref: '#/components/schemas/Gabong.GabongPlayerNotification' - - type: object + - $ref: '#/components/schemas/Games.GameObject' + - required: + - currentPassDirection + - currentPlayer + - currentPlayerIndex + - currentTrick + - deck + - heartsAreBroken + - isFirstTrick + - phase + - players + - roundNumber + type: object + properties: + deck: + type: array + items: + $ref: '#/components/schemas/Common.Card' + players: + type: array + items: + $ref: '#/components/schemas/Hearts.HeartsPlayer' + currentPlayerIndex: + type: integer + format: int32 + roundNumber: + type: integer + format: int32 + heartsAreBroken: + type: boolean + currentTrick: + type: array + items: + $ref: '#/components/schemas/Hearts.CardPlay' + leadSuit: + $ref: '#/components/schemas/Common.Suit' + isFirstTrick: + type: boolean + phase: + $ref: '#/components/schemas/Hearts.GamePhase' + currentPlayer: + $ref: '#/components/schemas/Hearts.HeartsPlayer' + currentPassDirection: + $ref: '#/components/schemas/Hearts.PassDirection' additionalProperties: false - Gabong.PlayerDrewPenaltyCardNotification: + Hearts.HeartsPlayer: + required: + - cards + - cardsToPass + - hasPassed + - id + - name + - roundScore + - totalScore + type: object + properties: + id: + type: string + format: uuid + name: + type: string + cards: + type: array + items: + $ref: '#/components/schemas/Common.Card' + cardsToPass: + type: array + items: + $ref: '#/components/schemas/Common.Card' + hasPassed: + type: boolean + roundScore: + type: integer + format: int32 + totalScore: + type: integer + format: int32 + playedCard: + $ref: '#/components/schemas/Common.Card' + additionalProperties: false + Hearts.ItsPlayersTurnNotification: allOf: - - $ref: '#/components/schemas/Gabong.GabongPlayerNotification' + - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: - - penaltyReason + - playerId type: object properties: - penaltyReason: - $ref: '#/components/schemas/Gabong.PenaltyReason' + playerId: + type: string + format: uuid additionalProperties: false - Gabong.PlayerLostTheirTurnNotification: + Hearts.ItsYourTurnNotification: allOf: - - $ref: '#/components/schemas/Gabong.GabongPlayerNotification' + - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: - - lostTurnReason + - playerViewOfGame type: object properties: - lostTurnReason: - $ref: '#/components/schemas/Gabong.PlayerLostTurnReason' + playerViewOfGame: + $ref: '#/components/schemas/Hearts.PlayerViewOfGame' additionalProperties: false - Gabong.PlayerLostTurnReason: - enum: - - Passed - - WrongPlay - - TookTooLong - - FinishedDrawingCardDebt - type: string - Gabong.PlayerPutCardNotification: + Hearts.OtherHeartsPlayer: + required: + - name + - numberOfCards + - playerId + - roundScore + - totalScore + type: object + properties: + playerId: + type: string + format: uuid + name: + type: string + numberOfCards: + type: integer + format: int32 + totalScore: + type: integer + format: int32 + roundScore: + type: integer + format: int32 + playedCard: + $ref: '#/components/schemas/Common.Card' + additionalProperties: false + Hearts.PassCardsRequest: allOf: - - $ref: '#/components/schemas/Gabong.GabongPlayerNotification' + - $ref: '#/components/schemas/Protocol.DecksterRequest' - required: - - card + - cards type: object properties: - card: - $ref: '#/components/schemas/Common.Card' - newSuit: - $ref: '#/components/schemas/Common.Suit' + cards: + type: array + items: + $ref: '#/components/schemas/Common.Card' additionalProperties: false - Gabong.PlayerViewOfGame: + Hearts.PassCardsResponse: allOf: - - $ref: '#/components/schemas/Gabong.GabongResponse' + - $ref: '#/components/schemas/Protocol.DecksterResponse' - required: - - cardDebtToDraw - - cards - - currentSuit - - discardPileCount - - lastPlay - - lastPlayMadeByPlayerId - - players - - playersOrder - - roundStarted - - stockPileCount - - topOfPile + - receivedCards type: object properties: - cards: + receivedCards: type: array items: $ref: '#/components/schemas/Common.Card' - topOfPile: - $ref: '#/components/schemas/Common.Card' - currentSuit: - $ref: '#/components/schemas/Common.Suit' - stockPileCount: - type: integer - format: int32 - discardPileCount: - type: integer - format: int32 - roundStarted: - type: boolean - lastPlayMadeByPlayerId: - type: string - format: uuid - lastPlay: - $ref: '#/components/schemas/Gabong.GabongPlay' - players: - type: array - items: - $ref: '#/components/schemas/Gabong.SlimGabongPlayer' - playersOrder: - type: array - items: - type: string - format: uuid - cardDebtToDraw: - type: integer - format: int32 additionalProperties: false - Gabong.PutCardRequest: + Hearts.PassDirection: + enum: + - None + - Left + - Right + - Across + type: string + Hearts.PassingPhaseStartedNotification: allOf: - - $ref: '#/components/schemas/Gabong.GabongRequest' + - $ref: '#/components/schemas/Protocol.DecksterNotification' + - required: + - passDirection + type: object + properties: + passDirection: + $ref: '#/components/schemas/Hearts.PassDirection' + additionalProperties: false + Hearts.PlayCardRequest: + allOf: + - $ref: '#/components/schemas/Protocol.DecksterRequest' - required: - card type: object properties: card: $ref: '#/components/schemas/Common.Card' - newSuit: - $ref: '#/components/schemas/Common.Suit' additionalProperties: false - Gabong.RoundEndedNotification: + Hearts.PlayerPassedCardsNotification: allOf: - - $ref: '#/components/schemas/Gabong.GabongGameNotification' + - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: - - players + - playerId type: object properties: - players: - type: array - items: - $ref: '#/components/schemas/Common.PlayerData' + playerId: + type: string + format: uuid additionalProperties: false - Gabong.RoundStartedNotification: + Hearts.PlayerPlayedCardNotification: allOf: - - $ref: '#/components/schemas/Gabong.GabongGameNotification' + - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: - - playerViewOfGame - - startingPlayerId + - card + - playerId type: object properties: - playerViewOfGame: - $ref: '#/components/schemas/Gabong.PlayerViewOfGame' - startingPlayerId: + playerId: type: string format: uuid + card: + $ref: '#/components/schemas/Common.Card' additionalProperties: false - Gabong.SlimGabongPlayer: + Hearts.PlayerScore: required: - - id - - name - - numberOfCards + - playerId + - playerName + - roundScore + - totalScore type: object properties: - id: + playerId: type: string format: uuid - name: + playerName: type: string - numberOfCards: + roundScore: + type: integer + format: int32 + totalScore: type: integer format: int32 additionalProperties: false - Games.GameObject: + Hearts.PlayerViewOfGame: allOf: - - $ref: '#/components/schemas/Data.DatabaseObject' + - $ref: '#/components/schemas/Protocol.DecksterResponse' - required: - - name - - seed - - startedTime - - state - - version + - cards + - currentTrick + - hasPassed + - heartsAreBroken + - isMyTurn + - otherPlayers + - passDirection + - roundNumber + - roundScore + - totalScore type: object properties: - name: - type: string - startedTime: - type: string - format: date-time - state: - $ref: '#/components/schemas/Games.GameState' - version: + cards: + type: array + items: + $ref: '#/components/schemas/Common.Card' + otherPlayers: + type: array + items: + $ref: '#/components/schemas/Hearts.OtherHeartsPlayer' + roundNumber: type: integer format: int32 - seed: + passDirection: + $ref: '#/components/schemas/Hearts.PassDirection' + hasPassed: + type: boolean + currentTrick: + type: array + items: + $ref: '#/components/schemas/Hearts.CardPlay' + totalScore: type: integer format: int32 + roundScore: + type: integer + format: int32 + heartsAreBroken: + type: boolean + isMyTurn: + type: boolean additionalProperties: false - discriminator: - propertyName: type - mapping: - Yaniv.YanivGame: '#/components/schemas/Yaniv.YanivGame' - Uno.UnoGame: '#/components/schemas/Uno.UnoGame' - TexasHoldEm.TexasHoldEmGame: '#/components/schemas/TexasHoldEm.TexasHoldEmGame' - Idiot.IdiotGame: '#/components/schemas/Idiot.IdiotGame' - Gabong.GabongGame: '#/components/schemas/Gabong.GabongGame' - CrazyEights.CrazyEightsGame: '#/components/schemas/CrazyEights.CrazyEightsGame' - ChatRoom.ChatRoom: '#/components/schemas/ChatRoom.ChatRoom' - Bullshit.BullshitGame: '#/components/schemas/Bullshit.BullshitGame' - Games.GameState: - enum: - - Waiting - - Running - - Finished - - RoundFinished - type: string - Handshake.ConnectFailureMessage: + Hearts.RoundEndedNotification: allOf: - - $ref: '#/components/schemas/Handshake.ConnectMessage' + - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: - - errorMessage + - scores type: object properties: - errorMessage: + scores: + type: array + items: + $ref: '#/components/schemas/Hearts.PlayerScore' + moonShooterId: type: string + format: uuid + nullable: true + moonShooterName: + type: string + nullable: true additionalProperties: false - Handshake.ConnectMessage: - allOf: - - $ref: '#/components/schemas/Protocol.DecksterMessage' - - type: object - additionalProperties: false - discriminator: - propertyName: type - mapping: - Handshake.HelloSuccessMessage: '#/components/schemas/Handshake.HelloSuccessMessage' - Handshake.ConnectSuccessMessage: '#/components/schemas/Handshake.ConnectSuccessMessage' - Handshake.ConnectFailureMessage: '#/components/schemas/Handshake.ConnectFailureMessage' - Handshake.ConnectSuccessMessage: - allOf: - - $ref: '#/components/schemas/Handshake.ConnectMessage' - - type: object - additionalProperties: false - Handshake.HelloSuccessMessage: + Hearts.TrickCompletedNotification: allOf: - - $ref: '#/components/schemas/Handshake.ConnectMessage' + - $ref: '#/components/schemas/Protocol.DecksterNotification' - required: - - connectionId - - player + - points + - trickCards + - winnerId + - winnerName type: object properties: - player: - $ref: '#/components/schemas/Common.PlayerData' - connectionId: + winnerId: type: string format: uuid + winnerName: + type: string + trickCards: + type: array + items: + $ref: '#/components/schemas/Hearts.CardPlay' + points: + type: integer + format: int32 additionalProperties: false Idiot.DiscardPileFlushedNotification: allOf: @@ -5047,6 +5824,21 @@ components: Idiot.GameStartedNotification: '#/components/schemas/Idiot.GameStartedNotification' Idiot.GameEndedNotification: '#/components/schemas/Idiot.GameEndedNotification' Idiot.ItsTimeToSwapCardsNotification: '#/components/schemas/Idiot.ItsTimeToSwapCardsNotification' + Hearts.PassCardsRequest: '#/components/schemas/Hearts.PassCardsRequest' + Hearts.PlayCardRequest: '#/components/schemas/Hearts.PlayCardRequest' + Hearts.PassCardsResponse: '#/components/schemas/Hearts.PassCardsResponse' + Hearts.GameStartedNotification: '#/components/schemas/Hearts.GameStartedNotification' + Hearts.PassingPhaseStartedNotification: '#/components/schemas/Hearts.PassingPhaseStartedNotification' + Hearts.AllPlayersPassedNotification: '#/components/schemas/Hearts.AllPlayersPassedNotification' + Hearts.PlayerPassedCardsNotification: '#/components/schemas/Hearts.PlayerPassedCardsNotification' + Hearts.ItsYourTurnNotification: '#/components/schemas/Hearts.ItsYourTurnNotification' + Hearts.ItsPlayersTurnNotification: '#/components/schemas/Hearts.ItsPlayersTurnNotification' + Hearts.PlayerPlayedCardNotification: '#/components/schemas/Hearts.PlayerPlayedCardNotification' + Hearts.TrickCompletedNotification: '#/components/schemas/Hearts.TrickCompletedNotification' + Hearts.RoundEndedNotification: '#/components/schemas/Hearts.RoundEndedNotification' + Hearts.GameEndedNotification: '#/components/schemas/Hearts.GameEndedNotification' + Hearts.HeartsAreBrokenNotification: '#/components/schemas/Hearts.HeartsAreBrokenNotification' + Hearts.PlayerViewOfGame: '#/components/schemas/Hearts.PlayerViewOfGame' Gabong.GabongGameNotification: '#/components/schemas/Gabong.GabongGameNotification' Gabong.GabongPlayerNotification: '#/components/schemas/Gabong.GabongPlayerNotification' Gabong.PlayerPutCardNotification: '#/components/schemas/Gabong.PlayerPutCardNotification' @@ -5158,6 +5950,17 @@ components: Idiot.GameStartedNotification: '#/components/schemas/Idiot.GameStartedNotification' Idiot.GameEndedNotification: '#/components/schemas/Idiot.GameEndedNotification' Idiot.ItsTimeToSwapCardsNotification: '#/components/schemas/Idiot.ItsTimeToSwapCardsNotification' + Hearts.GameStartedNotification: '#/components/schemas/Hearts.GameStartedNotification' + Hearts.PassingPhaseStartedNotification: '#/components/schemas/Hearts.PassingPhaseStartedNotification' + Hearts.AllPlayersPassedNotification: '#/components/schemas/Hearts.AllPlayersPassedNotification' + Hearts.PlayerPassedCardsNotification: '#/components/schemas/Hearts.PlayerPassedCardsNotification' + Hearts.ItsYourTurnNotification: '#/components/schemas/Hearts.ItsYourTurnNotification' + Hearts.ItsPlayersTurnNotification: '#/components/schemas/Hearts.ItsPlayersTurnNotification' + Hearts.PlayerPlayedCardNotification: '#/components/schemas/Hearts.PlayerPlayedCardNotification' + Hearts.TrickCompletedNotification: '#/components/schemas/Hearts.TrickCompletedNotification' + Hearts.RoundEndedNotification: '#/components/schemas/Hearts.RoundEndedNotification' + Hearts.GameEndedNotification: '#/components/schemas/Hearts.GameEndedNotification' + Hearts.HeartsAreBrokenNotification: '#/components/schemas/Hearts.HeartsAreBrokenNotification' Gabong.GabongGameNotification: '#/components/schemas/Gabong.GabongGameNotification' Gabong.GabongPlayerNotification: '#/components/schemas/Gabong.GabongPlayerNotification' Gabong.PlayerPutCardNotification: '#/components/schemas/Gabong.PlayerPutCardNotification' @@ -5223,6 +6026,8 @@ components: Idiot.DrawCardsRequest: '#/components/schemas/Idiot.DrawCardsRequest' Idiot.PullInDiscardPileRequest: '#/components/schemas/Idiot.PullInDiscardPileRequest' Idiot.PutChanceCardRequest: '#/components/schemas/Idiot.PutChanceCardRequest' + Hearts.PassCardsRequest: '#/components/schemas/Hearts.PassCardsRequest' + Hearts.PlayCardRequest: '#/components/schemas/Hearts.PlayCardRequest' Gabong.PenalizePlayerForTakingTooLongRequest: '#/components/schemas/Gabong.PenalizePlayerForTakingTooLongRequest' Gabong.PenalizePlayerForTooManyCardsRequest: '#/components/schemas/Gabong.PenalizePlayerForTooManyCardsRequest' Gabong.GabongRequest: '#/components/schemas/Gabong.GabongRequest' @@ -5265,6 +6070,8 @@ components: Idiot.PullInResponse: '#/components/schemas/Idiot.PullInResponse' Idiot.DrawCardsResponse: '#/components/schemas/Idiot.DrawCardsResponse' Idiot.PutBlindCardResponse: '#/components/schemas/Idiot.PutBlindCardResponse' + Hearts.PassCardsResponse: '#/components/schemas/Hearts.PassCardsResponse' + Hearts.PlayerViewOfGame: '#/components/schemas/Hearts.PlayerViewOfGame' Gabong.GabongResponse: '#/components/schemas/Gabong.GabongResponse' Gabong.GabongCardResponse: '#/components/schemas/Gabong.GabongCardResponse' Gabong.ActionResponse: '#/components/schemas/Gabong.ActionResponse' diff --git a/generated/typescript/bullshit/BullshitClient.ts b/generated/typescript/bullshit/BullshitClient.ts new file mode 100644 index 00000000..5da193b3 --- /dev/null +++ b/generated/typescript/bullshit/BullshitClient.ts @@ -0,0 +1,356 @@ +/** + * Autogenerated by really, really eager small hamsters. + * + * Bullshit Game Client + * + * Notifications (events) for this game: + * - GameStarted: GameStartedNotification + * - PlayerDrewCard: PlayerDrewCardNotification + * - ItsYourTurn: ItsYourTurnNotification + * - ItsPlayersTurn: ItsPlayersTurnNotification + * - PlayerPassed: PlayerPassedNotification + * - PlayerPutCard: PlayerPutCardNotification + * - GameEnded: GameEndedNotification + * - PlayerIsDone: PlayerIsDoneNotification + * - DiscardPileShuffled: DiscardPileShuffledNotification + * - PlayersBullshitHasBeenCalled: BullshitBroadcastNotification + * - YourBullshitHasBeenCalled: BullshitPlayerNotification + * - PlayerAccusedFalseBullshit: FalseBullshitCallNotification + */ + +import type { EmptyResponse } from '../types'; +import type { BullshitBroadcastNotification, BullshitPlayerNotification, BullshitRequest, BullshitResponse, CardResponse, DiscardPileShuffledNotification, DrawCardRequest, FalseBullshitCallNotification, GameEndedNotification, GameStartedNotification, ItsPlayersTurnNotification, ItsYourTurnNotification, PassRequest, PlayerDrewCardNotification, PlayerIsDoneNotification, PlayerPassedNotification, PlayerPutCardNotification, PutCardRequest } from './types'; + +// Event handler types +export type GameStartedHandler = (data: GameStartedNotification) => void; +export type PlayerDrewCardHandler = (data: PlayerDrewCardNotification) => void; +export type ItsYourTurnHandler = (data: ItsYourTurnNotification) => void; +export type ItsPlayersTurnHandler = (data: ItsPlayersTurnNotification) => void; +export type PlayerPassedHandler = (data: PlayerPassedNotification) => void; +export type PlayerPutCardHandler = (data: PlayerPutCardNotification) => void; +export type GameEndedHandler = (data: GameEndedNotification) => void; +export type PlayerIsDoneHandler = (data: PlayerIsDoneNotification) => void; +export type DiscardPileShuffledHandler = (data: DiscardPileShuffledNotification) => void; +export type PlayersBullshitHasBeenCalledHandler = (data: BullshitBroadcastNotification) => void; +export type YourBullshitHasBeenCalledHandler = (data: BullshitPlayerNotification) => void; +export type PlayerAccusedFalseBullshitHandler = (data: FalseBullshitCallNotification) => void; + +export interface BullshitClient { + onGameStarted(handler: GameStartedHandler): void; + offGameStarted(handler: GameStartedHandler): void; + onPlayerDrewCard(handler: PlayerDrewCardHandler): void; + offPlayerDrewCard(handler: PlayerDrewCardHandler): void; + onItsYourTurn(handler: ItsYourTurnHandler): void; + offItsYourTurn(handler: ItsYourTurnHandler): void; + onItsPlayersTurn(handler: ItsPlayersTurnHandler): void; + offItsPlayersTurn(handler: ItsPlayersTurnHandler): void; + onPlayerPassed(handler: PlayerPassedHandler): void; + offPlayerPassed(handler: PlayerPassedHandler): void; + onPlayerPutCard(handler: PlayerPutCardHandler): void; + offPlayerPutCard(handler: PlayerPutCardHandler): void; + onGameEnded(handler: GameEndedHandler): void; + offGameEnded(handler: GameEndedHandler): void; + onPlayerIsDone(handler: PlayerIsDoneHandler): void; + offPlayerIsDone(handler: PlayerIsDoneHandler): void; + onDiscardPileShuffled(handler: DiscardPileShuffledHandler): void; + offDiscardPileShuffled(handler: DiscardPileShuffledHandler): void; + onPlayersBullshitHasBeenCalled(handler: PlayersBullshitHasBeenCalledHandler): void; + offPlayersBullshitHasBeenCalled(handler: PlayersBullshitHasBeenCalledHandler): void; + onYourBullshitHasBeenCalled(handler: YourBullshitHasBeenCalledHandler): void; + offYourBullshitHasBeenCalled(handler: YourBullshitHasBeenCalledHandler): void; + onPlayerAccusedFalseBullshit(handler: PlayerAccusedFalseBullshitHandler): void; + offPlayerAccusedFalseBullshit(handler: PlayerAccusedFalseBullshitHandler): void; + + putCard(request: PutCardRequest): Promise; + drawCard(request: DrawCardRequest): Promise; + pass(request: PassRequest): Promise; + callBullshit(request: BullshitRequest): Promise; +} + +export class BullshitClientImpl implements BullshitClient { + private gameStartedHandlers: GameStartedHandler[] = []; + private playerDrewCardHandlers: PlayerDrewCardHandler[] = []; + private itsYourTurnHandlers: ItsYourTurnHandler[] = []; + private itsPlayersTurnHandlers: ItsPlayersTurnHandler[] = []; + private playerPassedHandlers: PlayerPassedHandler[] = []; + private playerPutCardHandlers: PlayerPutCardHandler[] = []; + private gameEndedHandlers: GameEndedHandler[] = []; + private playerIsDoneHandlers: PlayerIsDoneHandler[] = []; + private discardPileShuffledHandlers: DiscardPileShuffledHandler[] = []; + private playersBullshitHasBeenCalledHandlers: PlayersBullshitHasBeenCalledHandler[] = []; + private yourBullshitHasBeenCalledHandlers: YourBullshitHasBeenCalledHandler[] = []; + private playerAccusedFalseBullshitHandlers: PlayerAccusedFalseBullshitHandler[] = []; + + constructor(private actionSocket: WebSocket, private notificationSocket: WebSocket) { + this.setupNotificationHandlers(); + } + + private setupNotificationHandlers(): void { + this.notificationSocket.onmessage = (event) => { + const notification = JSON.parse(event.data); + this.handleNotification(notification); + }; + } + + private handleNotification(notification: any): void { + switch (notification.type) { + case 'Bullshit.GameStartedNotification': + this.gameStartedHandlers.forEach(h => h(notification)); + break; + case 'Bullshit.PlayerDrewCardNotification': + this.playerDrewCardHandlers.forEach(h => h(notification)); + break; + case 'Bullshit.ItsYourTurnNotification': + this.itsYourTurnHandlers.forEach(h => h(notification)); + break; + case 'Bullshit.ItsPlayersTurnNotification': + this.itsPlayersTurnHandlers.forEach(h => h(notification)); + break; + case 'Bullshit.PlayerPassedNotification': + this.playerPassedHandlers.forEach(h => h(notification)); + break; + case 'Bullshit.PlayerPutCardNotification': + this.playerPutCardHandlers.forEach(h => h(notification)); + break; + case 'Bullshit.GameEndedNotification': + this.gameEndedHandlers.forEach(h => h(notification)); + break; + case 'Bullshit.PlayerIsDoneNotification': + this.playerIsDoneHandlers.forEach(h => h(notification)); + break; + case 'Bullshit.DiscardPileShuffledNotification': + this.discardPileShuffledHandlers.forEach(h => h(notification)); + break; + case 'Bullshit.BullshitBroadcastNotification': + this.playersBullshitHasBeenCalledHandlers.forEach(h => h(notification)); + break; + case 'Bullshit.BullshitPlayerNotification': + this.yourBullshitHasBeenCalledHandlers.forEach(h => h(notification)); + break; + case 'Bullshit.FalseBullshitCallNotification': + this.playerAccusedFalseBullshitHandlers.forEach(h => h(notification)); + break; + } + } + + onGameStarted(handler: GameStartedHandler): void { + this.gameStartedHandlers.push(handler); + } + + offGameStarted(handler: GameStartedHandler): void { + const index = this.gameStartedHandlers.indexOf(handler); + if (index > -1) { + this.gameStartedHandlers.splice(index, 1); + } + } + + onPlayerDrewCard(handler: PlayerDrewCardHandler): void { + this.playerDrewCardHandlers.push(handler); + } + + offPlayerDrewCard(handler: PlayerDrewCardHandler): void { + const index = this.playerDrewCardHandlers.indexOf(handler); + if (index > -1) { + this.playerDrewCardHandlers.splice(index, 1); + } + } + + onItsYourTurn(handler: ItsYourTurnHandler): void { + this.itsYourTurnHandlers.push(handler); + } + + offItsYourTurn(handler: ItsYourTurnHandler): void { + const index = this.itsYourTurnHandlers.indexOf(handler); + if (index > -1) { + this.itsYourTurnHandlers.splice(index, 1); + } + } + + onItsPlayersTurn(handler: ItsPlayersTurnHandler): void { + this.itsPlayersTurnHandlers.push(handler); + } + + offItsPlayersTurn(handler: ItsPlayersTurnHandler): void { + const index = this.itsPlayersTurnHandlers.indexOf(handler); + if (index > -1) { + this.itsPlayersTurnHandlers.splice(index, 1); + } + } + + onPlayerPassed(handler: PlayerPassedHandler): void { + this.playerPassedHandlers.push(handler); + } + + offPlayerPassed(handler: PlayerPassedHandler): void { + const index = this.playerPassedHandlers.indexOf(handler); + if (index > -1) { + this.playerPassedHandlers.splice(index, 1); + } + } + + onPlayerPutCard(handler: PlayerPutCardHandler): void { + this.playerPutCardHandlers.push(handler); + } + + offPlayerPutCard(handler: PlayerPutCardHandler): void { + const index = this.playerPutCardHandlers.indexOf(handler); + if (index > -1) { + this.playerPutCardHandlers.splice(index, 1); + } + } + + onGameEnded(handler: GameEndedHandler): void { + this.gameEndedHandlers.push(handler); + } + + offGameEnded(handler: GameEndedHandler): void { + const index = this.gameEndedHandlers.indexOf(handler); + if (index > -1) { + this.gameEndedHandlers.splice(index, 1); + } + } + + onPlayerIsDone(handler: PlayerIsDoneHandler): void { + this.playerIsDoneHandlers.push(handler); + } + + offPlayerIsDone(handler: PlayerIsDoneHandler): void { + const index = this.playerIsDoneHandlers.indexOf(handler); + if (index > -1) { + this.playerIsDoneHandlers.splice(index, 1); + } + } + + onDiscardPileShuffled(handler: DiscardPileShuffledHandler): void { + this.discardPileShuffledHandlers.push(handler); + } + + offDiscardPileShuffled(handler: DiscardPileShuffledHandler): void { + const index = this.discardPileShuffledHandlers.indexOf(handler); + if (index > -1) { + this.discardPileShuffledHandlers.splice(index, 1); + } + } + + onPlayersBullshitHasBeenCalled(handler: PlayersBullshitHasBeenCalledHandler): void { + this.playersBullshitHasBeenCalledHandlers.push(handler); + } + + offPlayersBullshitHasBeenCalled(handler: PlayersBullshitHasBeenCalledHandler): void { + const index = this.playersBullshitHasBeenCalledHandlers.indexOf(handler); + if (index > -1) { + this.playersBullshitHasBeenCalledHandlers.splice(index, 1); + } + } + + onYourBullshitHasBeenCalled(handler: YourBullshitHasBeenCalledHandler): void { + this.yourBullshitHasBeenCalledHandlers.push(handler); + } + + offYourBullshitHasBeenCalled(handler: YourBullshitHasBeenCalledHandler): void { + const index = this.yourBullshitHasBeenCalledHandlers.indexOf(handler); + if (index > -1) { + this.yourBullshitHasBeenCalledHandlers.splice(index, 1); + } + } + + onPlayerAccusedFalseBullshit(handler: PlayerAccusedFalseBullshitHandler): void { + this.playerAccusedFalseBullshitHandlers.push(handler); + } + + offPlayerAccusedFalseBullshit(handler: PlayerAccusedFalseBullshitHandler): void { + const index = this.playerAccusedFalseBullshitHandlers.indexOf(handler); + if (index > -1) { + this.playerAccusedFalseBullshitHandlers.splice(index, 1); + } + } + + async putCard(request: PutCardRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'Bullshit.PutCardRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + + async drawCard(request: DrawCardRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'Bullshit.DrawCardRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + + async pass(request: PassRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'Bullshit.PassRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + + async callBullshit(request: BullshitRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'Bullshit.BullshitRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + +} diff --git a/generated/typescript/bullshit/types.ts b/generated/typescript/bullshit/types.ts new file mode 100644 index 00000000..83051419 --- /dev/null +++ b/generated/typescript/bullshit/types.ts @@ -0,0 +1,160 @@ +/** + * Autogenerated by really, really eager small hamsters. + * Shared type definitions for Deckster game clients. + */ + +export interface GameStartedNotification { + gameId: string; + playerViewOfGame?: PlayerViewOfGame; + type?: string; +} + +export interface PlayerViewOfGame { + cards?: Card[]; + claimedTopOfPile?: Card; + stockPileCount: number; + discardPileCount: number; + otherPlayers?: OtherBullshitPlayer[]; +} + +export interface Card { + rank: number; + suit: Suit; +} + +export enum Suit { + Clubs = 0, + Diamonds = 1, + Hearts = 2, + Spades = 3, +} + +export interface PlayerDrewCardNotification { + playerId: string; + type?: string; +} + +export interface ItsYourTurnNotification { + type?: string; +} + +export interface ItsPlayersTurnNotification { + playerId: string; + type?: string; +} + +export interface PlayerPassedNotification { + playerId: string; + type?: string; +} + +export interface PlayerPutCardNotification { + playerId: string; + claimedToBeCard: Card; + type?: string; +} + +export interface GameEndedNotification { + players?: PlayerData[]; + loserId: string; + loserName?: string; + type?: string; +} + +export interface PlayerData { + name?: string; + points: number; + cardsInHand: number; + id: string; + info?: Record; +} + +export interface Dictionary { + comparer?: IEqualityComparer; + count: number; + capacity: number; + keys?: KeyCollection; + values?: ValueCollection; +} + +export interface ValueCollection { + count: number; +} + +export interface KeyCollection { + count: number; +} + +export interface PlayerIsDoneNotification { + playerId: string; + type?: string; +} + +export interface DiscardPileShuffledNotification { + type?: string; +} + +export interface BullshitBroadcastNotification { + playerId: string; + claimedToBeCard: Card; + actualCard: Card; + punishmentCardCount: number; + type?: string; +} + +export interface BullshitPlayerNotification { + calledByPlayerId: string; + card: Card; + punishmentCards?: Card[]; + type?: string; +} + +export interface FalseBullshitCallNotification { + playerId: string; + accusedPlayerId: string; + punishmentCardCount: number; + type?: string; +} + +export interface PutCardRequest { + actualCard: Card; + claimedToBeCard: Card; + playerId: string; + type?: string; +} + +export interface DrawCardRequest { + playerId: string; + type?: string; +} + +export interface CardResponse { + card: Card; + hasError: boolean; + error?: string; + type?: string; +} + +export interface PassRequest { + playerId: string; + type?: string; +} + +export interface BullshitRequest { + playerId: string; + type?: string; +} + +export interface BullshitResponse { + punishmentCards?: Card[]; + hasError: boolean; + error?: string; + type?: string; +} + +export interface OtherBullshitPlayer { + playerId: string; + name?: string; + numberOfCards: number; +} + diff --git a/generated/typescript/chatroom/ChatRoomClient.ts b/generated/typescript/chatroom/ChatRoomClient.ts new file mode 100644 index 00000000..20a7d0fe --- /dev/null +++ b/generated/typescript/chatroom/ChatRoomClient.ts @@ -0,0 +1,77 @@ +/** + * Autogenerated by really, really eager small hamsters. + * + * ChatRoom Game Client + * + * Notifications (events) for this game: + * - PlayerSaid: ChatNotification + */ + +import type { ChatNotification, ChatResponse, SendChatRequest } from './types'; + +// Event handler types +export type PlayerSaidHandler = (data: ChatNotification) => void; + +export interface ChatRoomClient { + onPlayerSaid(handler: PlayerSaidHandler): void; + offPlayerSaid(handler: PlayerSaidHandler): void; + + chatAsync(request: SendChatRequest): Promise; +} + +export class ChatRoomClientImpl implements ChatRoomClient { + private playerSaidHandlers: PlayerSaidHandler[] = []; + + constructor(private actionSocket: WebSocket, private notificationSocket: WebSocket) { + this.setupNotificationHandlers(); + } + + private setupNotificationHandlers(): void { + this.notificationSocket.onmessage = (event) => { + const notification = JSON.parse(event.data); + this.handleNotification(notification); + }; + } + + private handleNotification(notification: any): void { + switch (notification.type) { + case 'ChatRoom.ChatNotification': + this.playerSaidHandlers.forEach(h => h(notification)); + break; + } + } + + onPlayerSaid(handler: PlayerSaidHandler): void { + this.playerSaidHandlers.push(handler); + } + + offPlayerSaid(handler: PlayerSaidHandler): void { + const index = this.playerSaidHandlers.indexOf(handler); + if (index > -1) { + this.playerSaidHandlers.splice(index, 1); + } + } + + async chatAsync(request: SendChatRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'ChatRoom.SendChatRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + +} diff --git a/generated/typescript/chatroom/types.ts b/generated/typescript/chatroom/types.ts new file mode 100644 index 00000000..77164cb7 --- /dev/null +++ b/generated/typescript/chatroom/types.ts @@ -0,0 +1,23 @@ +/** + * Autogenerated by really, really eager small hamsters. + * Shared type definitions for Deckster game clients. + */ + +export interface ChatNotification { + sender?: string; + message?: string; + type?: string; +} + +export interface SendChatRequest { + message?: string; + playerId: string; + type?: string; +} + +export interface ChatResponse { + hasError: boolean; + error?: string; + type?: string; +} + diff --git a/generated/typescript/crazyeights/CrazyEightsClient.ts b/generated/typescript/crazyeights/CrazyEightsClient.ts new file mode 100644 index 00000000..cc35b54a --- /dev/null +++ b/generated/typescript/crazyeights/CrazyEightsClient.ts @@ -0,0 +1,318 @@ +/** + * Autogenerated by really, really eager small hamsters. + * + * CrazyEights Game Client + * + * Notifications (events) for this game: + * - GameStarted: GameStartedNotification + * - PlayerDrewCard: PlayerDrewCardNotification + * - ItsYourTurn: ItsYourTurnNotification + * - ItsPlayersTurn: ItsPlayersTurnNotification + * - PlayerPassed: PlayerPassedNotification + * - PlayerPutCard: PlayerPutCardNotification + * - PlayerPutEight: PlayerPutEightNotification + * - GameEnded: GameEndedNotification + * - PlayerIsDone: PlayerIsDoneNotification + * - DiscardPileShuffled: DiscardPileShuffledNotification + */ + +import type { EmptyResponse } from '../types'; +import type { CardResponse, DiscardPileShuffledNotification, DrawCardRequest, GameEndedNotification, GameStartedNotification, ItsPlayersTurnNotification, ItsYourTurnNotification, PassRequest, PlayerDrewCardNotification, PlayerIsDoneNotification, PlayerPassedNotification, PlayerPutCardNotification, PlayerPutEightNotification, PlayerViewOfGame, PutCardRequest, PutEightRequest } from './types'; + +// Event handler types +export type GameStartedHandler = (data: GameStartedNotification) => void; +export type PlayerDrewCardHandler = (data: PlayerDrewCardNotification) => void; +export type ItsYourTurnHandler = (data: ItsYourTurnNotification) => void; +export type ItsPlayersTurnHandler = (data: ItsPlayersTurnNotification) => void; +export type PlayerPassedHandler = (data: PlayerPassedNotification) => void; +export type PlayerPutCardHandler = (data: PlayerPutCardNotification) => void; +export type PlayerPutEightHandler = (data: PlayerPutEightNotification) => void; +export type GameEndedHandler = (data: GameEndedNotification) => void; +export type PlayerIsDoneHandler = (data: PlayerIsDoneNotification) => void; +export type DiscardPileShuffledHandler = (data: DiscardPileShuffledNotification) => void; + +export interface CrazyEightsClient { + onGameStarted(handler: GameStartedHandler): void; + offGameStarted(handler: GameStartedHandler): void; + onPlayerDrewCard(handler: PlayerDrewCardHandler): void; + offPlayerDrewCard(handler: PlayerDrewCardHandler): void; + onItsYourTurn(handler: ItsYourTurnHandler): void; + offItsYourTurn(handler: ItsYourTurnHandler): void; + onItsPlayersTurn(handler: ItsPlayersTurnHandler): void; + offItsPlayersTurn(handler: ItsPlayersTurnHandler): void; + onPlayerPassed(handler: PlayerPassedHandler): void; + offPlayerPassed(handler: PlayerPassedHandler): void; + onPlayerPutCard(handler: PlayerPutCardHandler): void; + offPlayerPutCard(handler: PlayerPutCardHandler): void; + onPlayerPutEight(handler: PlayerPutEightHandler): void; + offPlayerPutEight(handler: PlayerPutEightHandler): void; + onGameEnded(handler: GameEndedHandler): void; + offGameEnded(handler: GameEndedHandler): void; + onPlayerIsDone(handler: PlayerIsDoneHandler): void; + offPlayerIsDone(handler: PlayerIsDoneHandler): void; + onDiscardPileShuffled(handler: DiscardPileShuffledHandler): void; + offDiscardPileShuffled(handler: DiscardPileShuffledHandler): void; + + putCard(request: PutCardRequest): Promise; + putEight(request: PutEightRequest): Promise; + drawCard(request: DrawCardRequest): Promise; + pass(request: PassRequest): Promise; +} + +export class CrazyEightsClientImpl implements CrazyEightsClient { + private gameStartedHandlers: GameStartedHandler[] = []; + private playerDrewCardHandlers: PlayerDrewCardHandler[] = []; + private itsYourTurnHandlers: ItsYourTurnHandler[] = []; + private itsPlayersTurnHandlers: ItsPlayersTurnHandler[] = []; + private playerPassedHandlers: PlayerPassedHandler[] = []; + private playerPutCardHandlers: PlayerPutCardHandler[] = []; + private playerPutEightHandlers: PlayerPutEightHandler[] = []; + private gameEndedHandlers: GameEndedHandler[] = []; + private playerIsDoneHandlers: PlayerIsDoneHandler[] = []; + private discardPileShuffledHandlers: DiscardPileShuffledHandler[] = []; + + constructor(private actionSocket: WebSocket, private notificationSocket: WebSocket) { + this.setupNotificationHandlers(); + } + + private setupNotificationHandlers(): void { + this.notificationSocket.onmessage = (event) => { + const notification = JSON.parse(event.data); + this.handleNotification(notification); + }; + } + + private handleNotification(notification: any): void { + switch (notification.type) { + case 'CrazyEights.GameStartedNotification': + this.gameStartedHandlers.forEach(h => h(notification)); + break; + case 'CrazyEights.PlayerDrewCardNotification': + this.playerDrewCardHandlers.forEach(h => h(notification)); + break; + case 'CrazyEights.ItsYourTurnNotification': + this.itsYourTurnHandlers.forEach(h => h(notification)); + break; + case 'CrazyEights.ItsPlayersTurnNotification': + this.itsPlayersTurnHandlers.forEach(h => h(notification)); + break; + case 'CrazyEights.PlayerPassedNotification': + this.playerPassedHandlers.forEach(h => h(notification)); + break; + case 'CrazyEights.PlayerPutCardNotification': + this.playerPutCardHandlers.forEach(h => h(notification)); + break; + case 'CrazyEights.PlayerPutEightNotification': + this.playerPutEightHandlers.forEach(h => h(notification)); + break; + case 'CrazyEights.GameEndedNotification': + this.gameEndedHandlers.forEach(h => h(notification)); + break; + case 'CrazyEights.PlayerIsDoneNotification': + this.playerIsDoneHandlers.forEach(h => h(notification)); + break; + case 'CrazyEights.DiscardPileShuffledNotification': + this.discardPileShuffledHandlers.forEach(h => h(notification)); + break; + } + } + + onGameStarted(handler: GameStartedHandler): void { + this.gameStartedHandlers.push(handler); + } + + offGameStarted(handler: GameStartedHandler): void { + const index = this.gameStartedHandlers.indexOf(handler); + if (index > -1) { + this.gameStartedHandlers.splice(index, 1); + } + } + + onPlayerDrewCard(handler: PlayerDrewCardHandler): void { + this.playerDrewCardHandlers.push(handler); + } + + offPlayerDrewCard(handler: PlayerDrewCardHandler): void { + const index = this.playerDrewCardHandlers.indexOf(handler); + if (index > -1) { + this.playerDrewCardHandlers.splice(index, 1); + } + } + + onItsYourTurn(handler: ItsYourTurnHandler): void { + this.itsYourTurnHandlers.push(handler); + } + + offItsYourTurn(handler: ItsYourTurnHandler): void { + const index = this.itsYourTurnHandlers.indexOf(handler); + if (index > -1) { + this.itsYourTurnHandlers.splice(index, 1); + } + } + + onItsPlayersTurn(handler: ItsPlayersTurnHandler): void { + this.itsPlayersTurnHandlers.push(handler); + } + + offItsPlayersTurn(handler: ItsPlayersTurnHandler): void { + const index = this.itsPlayersTurnHandlers.indexOf(handler); + if (index > -1) { + this.itsPlayersTurnHandlers.splice(index, 1); + } + } + + onPlayerPassed(handler: PlayerPassedHandler): void { + this.playerPassedHandlers.push(handler); + } + + offPlayerPassed(handler: PlayerPassedHandler): void { + const index = this.playerPassedHandlers.indexOf(handler); + if (index > -1) { + this.playerPassedHandlers.splice(index, 1); + } + } + + onPlayerPutCard(handler: PlayerPutCardHandler): void { + this.playerPutCardHandlers.push(handler); + } + + offPlayerPutCard(handler: PlayerPutCardHandler): void { + const index = this.playerPutCardHandlers.indexOf(handler); + if (index > -1) { + this.playerPutCardHandlers.splice(index, 1); + } + } + + onPlayerPutEight(handler: PlayerPutEightHandler): void { + this.playerPutEightHandlers.push(handler); + } + + offPlayerPutEight(handler: PlayerPutEightHandler): void { + const index = this.playerPutEightHandlers.indexOf(handler); + if (index > -1) { + this.playerPutEightHandlers.splice(index, 1); + } + } + + onGameEnded(handler: GameEndedHandler): void { + this.gameEndedHandlers.push(handler); + } + + offGameEnded(handler: GameEndedHandler): void { + const index = this.gameEndedHandlers.indexOf(handler); + if (index > -1) { + this.gameEndedHandlers.splice(index, 1); + } + } + + onPlayerIsDone(handler: PlayerIsDoneHandler): void { + this.playerIsDoneHandlers.push(handler); + } + + offPlayerIsDone(handler: PlayerIsDoneHandler): void { + const index = this.playerIsDoneHandlers.indexOf(handler); + if (index > -1) { + this.playerIsDoneHandlers.splice(index, 1); + } + } + + onDiscardPileShuffled(handler: DiscardPileShuffledHandler): void { + this.discardPileShuffledHandlers.push(handler); + } + + offDiscardPileShuffled(handler: DiscardPileShuffledHandler): void { + const index = this.discardPileShuffledHandlers.indexOf(handler); + if (index > -1) { + this.discardPileShuffledHandlers.splice(index, 1); + } + } + + async putCard(request: PutCardRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'CrazyEights.PutCardRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + + async putEight(request: PutEightRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'CrazyEights.PutEightRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + + async drawCard(request: DrawCardRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'CrazyEights.DrawCardRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + + async pass(request: PassRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'CrazyEights.PassRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + +} diff --git a/generated/typescript/crazyeights/types.ts b/generated/typescript/crazyeights/types.ts new file mode 100644 index 00000000..8726583b --- /dev/null +++ b/generated/typescript/crazyeights/types.ts @@ -0,0 +1,144 @@ +/** + * Autogenerated by really, really eager small hamsters. + * Shared type definitions for Deckster game clients. + */ + +export interface GameStartedNotification { + gameId: string; + playerViewOfGame?: PlayerViewOfGame; + type?: string; +} + +export interface PlayerDrewCardNotification { + playerId: string; + type?: string; +} + +export interface ItsYourTurnNotification { + playerViewOfGame?: PlayerViewOfGame; + type?: string; +} + +export interface ItsPlayersTurnNotification { + playerId: string; + type?: string; +} + +export interface PlayerPassedNotification { + playerId: string; + type?: string; +} + +export interface PlayerPutCardNotification { + playerId: string; + card: Card; + type?: string; +} + +export interface Card { + rank: number; + suit: Suit; +} + +export enum Suit { + Clubs = 0, + Diamonds = 1, + Hearts = 2, + Spades = 3, +} + +export interface PlayerPutEightNotification { + playerId: string; + card: Card; + newSuit: Suit; + type?: string; +} + +export interface GameEndedNotification { + players?: PlayerData[]; + loserId: string; + loserName?: string; + type?: string; +} + +export interface PlayerData { + name?: string; + points: number; + cardsInHand: number; + id: string; + info?: Record; +} + +export interface Dictionary { + comparer?: IEqualityComparer; + count: number; + capacity: number; + keys?: KeyCollection; + values?: ValueCollection; +} + +export interface ValueCollection { + count: number; +} + +export interface KeyCollection { + count: number; +} + +export interface PlayerIsDoneNotification { + playerId: string; + type?: string; +} + +export interface DiscardPileShuffledNotification { + type?: string; +} + +export interface PutCardRequest { + card: Card; + playerId: string; + type?: string; +} + +export interface PlayerViewOfGame { + cards?: Card[]; + topOfPile: Card; + currentSuit: Suit; + stockPileCount: number; + discardPileCount: number; + otherPlayers?: OtherCrazyEightsPlayer[]; + hasError: boolean; + error?: string; + type?: string; +} + +export interface OtherCrazyEightsPlayer { + playerId: string; + name?: string; + numberOfCards: number; +} + +export interface PutEightRequest { + card: Card; + newSuit: Suit; + playerId: string; + type?: string; +} + +export interface DrawCardRequest { + playerId: string; + type?: string; +} + +export interface CardResponse { + card: Card; + hasError: boolean; + error?: string; + type?: string; +} + +export interface PassRequest { + playerId: string; + type?: string; +} + diff --git a/generated/typescript/gabong/GabongClient.ts b/generated/typescript/gabong/GabongClient.ts new file mode 100644 index 00000000..d56cb900 --- /dev/null +++ b/generated/typescript/gabong/GabongClient.ts @@ -0,0 +1,302 @@ +/** + * Autogenerated by really, really eager small hamsters. + * + * Gabong Game Client + * + * Notifications (events) for this game: + * - GameStarted: GameStartedNotification + * - PlayerPutCard: PlayerPutCardNotification + * - PlayerDrewCard: PlayerDrewCardNotification + * - PlayerDrewPenaltyCard: PlayerDrewPenaltyCardNotification + * - GameEnded: GameEndedNotification + * - RoundStarted: RoundStartedNotification + * - RoundEnded: RoundEndedNotification + * - PlayerLostTheirTurn: PlayerLostTheirTurnNotification + */ + +import type { DrawCardRequest, GameEndedNotification, GameStartedNotification, PassRequest, PlayBongaRequest, PlayerDrewCardNotification, PlayerDrewPenaltyCardNotification, PlayerLostTheirTurnNotification, PlayerPutCardNotification, PlayerViewOfGame, PlayGabongRequest, PutCardRequest, RoundEndedNotification, RoundStartedNotification } from './types'; + +// Event handler types +export type GameStartedHandler = (data: GameStartedNotification) => void; +export type PlayerPutCardHandler = (data: PlayerPutCardNotification) => void; +export type PlayerDrewCardHandler = (data: PlayerDrewCardNotification) => void; +export type PlayerDrewPenaltyCardHandler = (data: PlayerDrewPenaltyCardNotification) => void; +export type GameEndedHandler = (data: GameEndedNotification) => void; +export type RoundStartedHandler = (data: RoundStartedNotification) => void; +export type RoundEndedHandler = (data: RoundEndedNotification) => void; +export type PlayerLostTheirTurnHandler = (data: PlayerLostTheirTurnNotification) => void; + +export interface GabongClient { + onGameStarted(handler: GameStartedHandler): void; + offGameStarted(handler: GameStartedHandler): void; + onPlayerPutCard(handler: PlayerPutCardHandler): void; + offPlayerPutCard(handler: PlayerPutCardHandler): void; + onPlayerDrewCard(handler: PlayerDrewCardHandler): void; + offPlayerDrewCard(handler: PlayerDrewCardHandler): void; + onPlayerDrewPenaltyCard(handler: PlayerDrewPenaltyCardHandler): void; + offPlayerDrewPenaltyCard(handler: PlayerDrewPenaltyCardHandler): void; + onGameEnded(handler: GameEndedHandler): void; + offGameEnded(handler: GameEndedHandler): void; + onRoundStarted(handler: RoundStartedHandler): void; + offRoundStarted(handler: RoundStartedHandler): void; + onRoundEnded(handler: RoundEndedHandler): void; + offRoundEnded(handler: RoundEndedHandler): void; + onPlayerLostTheirTurn(handler: PlayerLostTheirTurnHandler): void; + offPlayerLostTheirTurn(handler: PlayerLostTheirTurnHandler): void; + + drawCard(request: DrawCardRequest): Promise; + playGabong(request: PlayGabongRequest): Promise; + playBonga(request: PlayBongaRequest): Promise; + pass(request: PassRequest): Promise; + putCard(request: PutCardRequest): Promise; +} + +export class GabongClientImpl implements GabongClient { + private gameStartedHandlers: GameStartedHandler[] = []; + private playerPutCardHandlers: PlayerPutCardHandler[] = []; + private playerDrewCardHandlers: PlayerDrewCardHandler[] = []; + private playerDrewPenaltyCardHandlers: PlayerDrewPenaltyCardHandler[] = []; + private gameEndedHandlers: GameEndedHandler[] = []; + private roundStartedHandlers: RoundStartedHandler[] = []; + private roundEndedHandlers: RoundEndedHandler[] = []; + private playerLostTheirTurnHandlers: PlayerLostTheirTurnHandler[] = []; + + constructor(private actionSocket: WebSocket, private notificationSocket: WebSocket) { + this.setupNotificationHandlers(); + } + + private setupNotificationHandlers(): void { + this.notificationSocket.onmessage = (event) => { + const notification = JSON.parse(event.data); + this.handleNotification(notification); + }; + } + + private handleNotification(notification: any): void { + switch (notification.type) { + case 'Gabong.GameStartedNotification': + this.gameStartedHandlers.forEach(h => h(notification)); + break; + case 'Gabong.PlayerPutCardNotification': + this.playerPutCardHandlers.forEach(h => h(notification)); + break; + case 'Gabong.PlayerDrewCardNotification': + this.playerDrewCardHandlers.forEach(h => h(notification)); + break; + case 'Gabong.PlayerDrewPenaltyCardNotification': + this.playerDrewPenaltyCardHandlers.forEach(h => h(notification)); + break; + case 'Gabong.GameEndedNotification': + this.gameEndedHandlers.forEach(h => h(notification)); + break; + case 'Gabong.RoundStartedNotification': + this.roundStartedHandlers.forEach(h => h(notification)); + break; + case 'Gabong.RoundEndedNotification': + this.roundEndedHandlers.forEach(h => h(notification)); + break; + case 'Gabong.PlayerLostTheirTurnNotification': + this.playerLostTheirTurnHandlers.forEach(h => h(notification)); + break; + } + } + + onGameStarted(handler: GameStartedHandler): void { + this.gameStartedHandlers.push(handler); + } + + offGameStarted(handler: GameStartedHandler): void { + const index = this.gameStartedHandlers.indexOf(handler); + if (index > -1) { + this.gameStartedHandlers.splice(index, 1); + } + } + + onPlayerPutCard(handler: PlayerPutCardHandler): void { + this.playerPutCardHandlers.push(handler); + } + + offPlayerPutCard(handler: PlayerPutCardHandler): void { + const index = this.playerPutCardHandlers.indexOf(handler); + if (index > -1) { + this.playerPutCardHandlers.splice(index, 1); + } + } + + onPlayerDrewCard(handler: PlayerDrewCardHandler): void { + this.playerDrewCardHandlers.push(handler); + } + + offPlayerDrewCard(handler: PlayerDrewCardHandler): void { + const index = this.playerDrewCardHandlers.indexOf(handler); + if (index > -1) { + this.playerDrewCardHandlers.splice(index, 1); + } + } + + onPlayerDrewPenaltyCard(handler: PlayerDrewPenaltyCardHandler): void { + this.playerDrewPenaltyCardHandlers.push(handler); + } + + offPlayerDrewPenaltyCard(handler: PlayerDrewPenaltyCardHandler): void { + const index = this.playerDrewPenaltyCardHandlers.indexOf(handler); + if (index > -1) { + this.playerDrewPenaltyCardHandlers.splice(index, 1); + } + } + + onGameEnded(handler: GameEndedHandler): void { + this.gameEndedHandlers.push(handler); + } + + offGameEnded(handler: GameEndedHandler): void { + const index = this.gameEndedHandlers.indexOf(handler); + if (index > -1) { + this.gameEndedHandlers.splice(index, 1); + } + } + + onRoundStarted(handler: RoundStartedHandler): void { + this.roundStartedHandlers.push(handler); + } + + offRoundStarted(handler: RoundStartedHandler): void { + const index = this.roundStartedHandlers.indexOf(handler); + if (index > -1) { + this.roundStartedHandlers.splice(index, 1); + } + } + + onRoundEnded(handler: RoundEndedHandler): void { + this.roundEndedHandlers.push(handler); + } + + offRoundEnded(handler: RoundEndedHandler): void { + const index = this.roundEndedHandlers.indexOf(handler); + if (index > -1) { + this.roundEndedHandlers.splice(index, 1); + } + } + + onPlayerLostTheirTurn(handler: PlayerLostTheirTurnHandler): void { + this.playerLostTheirTurnHandlers.push(handler); + } + + offPlayerLostTheirTurn(handler: PlayerLostTheirTurnHandler): void { + const index = this.playerLostTheirTurnHandlers.indexOf(handler); + if (index > -1) { + this.playerLostTheirTurnHandlers.splice(index, 1); + } + } + + async drawCard(request: DrawCardRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'Gabong.DrawCardRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + + async playGabong(request: PlayGabongRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'Gabong.PlayGabongRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + + async playBonga(request: PlayBongaRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'Gabong.PlayBongaRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + + async pass(request: PassRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'Gabong.PassRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + + async putCard(request: PutCardRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'Gabong.PutCardRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + +} diff --git a/generated/typescript/gabong/types.ts b/generated/typescript/gabong/types.ts new file mode 100644 index 00000000..9c7b20e6 --- /dev/null +++ b/generated/typescript/gabong/types.ts @@ -0,0 +1,160 @@ +/** + * Autogenerated by really, really eager small hamsters. + * Shared type definitions for Deckster game clients. + */ + +export interface GameStartedNotification { + gameId: string; + type?: string; +} + +export interface PlayerPutCardNotification { + card: Card; + newSuit?: Suit; + playerId: string; + type?: string; +} + +export enum Suit { + Clubs = 0, + Diamonds = 1, + Hearts = 2, + Spades = 3, +} + +export interface Card { + rank: number; + suit: Suit; +} + +export interface PlayerDrewCardNotification { + playerId: string; + type?: string; +} + +export interface PlayerDrewPenaltyCardNotification { + penaltyReason: PenaltyReason; + playerId: string; + type?: string; +} + +export enum PenaltyReason { + PlayOutOfTurn = 0, + TookTooLong = 1, + WrongPlay = 2, + WrongGabong = 3, + WrongBonga = 4, + UnpaidDebt = 5, + PassWithoutDrawing = 6, +} + +export interface GameEndedNotification { + players?: PlayerData[]; + type?: string; +} + +export interface PlayerData { + name?: string; + points: number; + cardsInHand: number; + id: string; + info?: Record; +} + +export interface Dictionary { + comparer?: IEqualityComparer; + count: number; + capacity: number; + keys?: KeyCollection; + values?: ValueCollection; +} + +export interface ValueCollection { + count: number; +} + +export interface KeyCollection { + count: number; +} + +export interface RoundStartedNotification { + playerViewOfGame?: PlayerViewOfGame; + startingPlayerId: string; + type?: string; +} + +export interface RoundEndedNotification { + players?: PlayerData[]; + type?: string; +} + +export interface PlayerLostTheirTurnNotification { + lostTurnReason: PlayerLostTurnReason; + playerId: string; + type?: string; +} + +export enum PlayerLostTurnReason { + Passed = 0, + WrongPlay = 1, + TookTooLong = 2, + FinishedDrawingCardDebt = 3, +} + +export interface DrawCardRequest { + playerId: string; + type?: string; +} + +export interface PlayerViewOfGame { + cards?: Card[]; + topOfPile: Card; + currentSuit: Suit; + stockPileCount: number; + discardPileCount: number; + roundStarted: boolean; + lastPlayMadeByPlayerId: string; + lastPlay: GabongPlay; + players?: SlimGabongPlayer[]; + playersOrder?: string[]; + cardDebtToDraw: number; + cardsAdded?: Card[]; + hasError: boolean; + error?: string; + type?: string; +} + +export interface SlimGabongPlayer { + id: string; + name?: string; + numberOfCards: number; +} + +export enum GabongPlay { + CardPlayed = 0, + TurnLost = 1, + RoundStarted = 2, +} + +export interface PlayGabongRequest { + playerId: string; + type?: string; +} + +export interface PlayBongaRequest { + playerId: string; + type?: string; +} + +export interface PassRequest { + playerId: string; + type?: string; +} + +export interface PutCardRequest { + card: Card; + newSuit?: Suit; + playerId: string; + type?: string; +} + diff --git a/generated/typescript/hearts/HeartsClient.ts b/generated/typescript/hearts/HeartsClient.ts new file mode 100644 index 00000000..8b822116 --- /dev/null +++ b/generated/typescript/hearts/HeartsClient.ts @@ -0,0 +1,290 @@ +/** + * Autogenerated by really, really eager small hamsters. + * + * Hearts Game Client + * + * Notifications (events) for this game: + * - GameStarted: GameStartedNotification + * - PassingPhaseStarted: PassingPhaseStartedNotification + * - AllPlayersPassed: AllPlayersPassedNotification + * - PlayerPassedCards: PlayerPassedCardsNotification + * - ItsYourTurn: ItsYourTurnNotification + * - ItsPlayersTurn: ItsPlayersTurnNotification + * - PlayerPlayedCard: PlayerPlayedCardNotification + * - TrickCompleted: TrickCompletedNotification + * - RoundEnded: RoundEndedNotification + * - GameEnded: GameEndedNotification + * - HeartsWereBroken: HeartsAreBrokenNotification + */ + +import type { AllPlayersPassedNotification, GameEndedNotification, GameStartedNotification, HeartsAreBrokenNotification, ItsPlayersTurnNotification, ItsYourTurnNotification, PassCardsRequest, PassCardsResponse, PassingPhaseStartedNotification, PlayCardRequest, PlayerPassedCardsNotification, PlayerPlayedCardNotification, PlayerViewOfGame, RoundEndedNotification, TrickCompletedNotification } from './types'; + +// Event handler types +export type GameStartedHandler = (data: GameStartedNotification) => void; +export type PassingPhaseStartedHandler = (data: PassingPhaseStartedNotification) => void; +export type AllPlayersPassedHandler = (data: AllPlayersPassedNotification) => void; +export type PlayerPassedCardsHandler = (data: PlayerPassedCardsNotification) => void; +export type ItsYourTurnHandler = (data: ItsYourTurnNotification) => void; +export type ItsPlayersTurnHandler = (data: ItsPlayersTurnNotification) => void; +export type PlayerPlayedCardHandler = (data: PlayerPlayedCardNotification) => void; +export type TrickCompletedHandler = (data: TrickCompletedNotification) => void; +export type RoundEndedHandler = (data: RoundEndedNotification) => void; +export type GameEndedHandler = (data: GameEndedNotification) => void; +export type HeartsWereBrokenHandler = (data: HeartsAreBrokenNotification) => void; + +export interface HeartsClient { + onGameStarted(handler: GameStartedHandler): void; + offGameStarted(handler: GameStartedHandler): void; + onPassingPhaseStarted(handler: PassingPhaseStartedHandler): void; + offPassingPhaseStarted(handler: PassingPhaseStartedHandler): void; + onAllPlayersPassed(handler: AllPlayersPassedHandler): void; + offAllPlayersPassed(handler: AllPlayersPassedHandler): void; + onPlayerPassedCards(handler: PlayerPassedCardsHandler): void; + offPlayerPassedCards(handler: PlayerPassedCardsHandler): void; + onItsYourTurn(handler: ItsYourTurnHandler): void; + offItsYourTurn(handler: ItsYourTurnHandler): void; + onItsPlayersTurn(handler: ItsPlayersTurnHandler): void; + offItsPlayersTurn(handler: ItsPlayersTurnHandler): void; + onPlayerPlayedCard(handler: PlayerPlayedCardHandler): void; + offPlayerPlayedCard(handler: PlayerPlayedCardHandler): void; + onTrickCompleted(handler: TrickCompletedHandler): void; + offTrickCompleted(handler: TrickCompletedHandler): void; + onRoundEnded(handler: RoundEndedHandler): void; + offRoundEnded(handler: RoundEndedHandler): void; + onGameEnded(handler: GameEndedHandler): void; + offGameEnded(handler: GameEndedHandler): void; + onHeartsWereBroken(handler: HeartsWereBrokenHandler): void; + offHeartsWereBroken(handler: HeartsWereBrokenHandler): void; + + passCards(request: PassCardsRequest): Promise; + playCard(request: PlayCardRequest): Promise; +} + +export class HeartsClientImpl implements HeartsClient { + private gameStartedHandlers: GameStartedHandler[] = []; + private passingPhaseStartedHandlers: PassingPhaseStartedHandler[] = []; + private allPlayersPassedHandlers: AllPlayersPassedHandler[] = []; + private playerPassedCardsHandlers: PlayerPassedCardsHandler[] = []; + private itsYourTurnHandlers: ItsYourTurnHandler[] = []; + private itsPlayersTurnHandlers: ItsPlayersTurnHandler[] = []; + private playerPlayedCardHandlers: PlayerPlayedCardHandler[] = []; + private trickCompletedHandlers: TrickCompletedHandler[] = []; + private roundEndedHandlers: RoundEndedHandler[] = []; + private gameEndedHandlers: GameEndedHandler[] = []; + private heartsWereBrokenHandlers: HeartsWereBrokenHandler[] = []; + + constructor(private actionSocket: WebSocket, private notificationSocket: WebSocket) { + this.setupNotificationHandlers(); + } + + private setupNotificationHandlers(): void { + this.notificationSocket.onmessage = (event) => { + const notification = JSON.parse(event.data); + this.handleNotification(notification); + }; + } + + private handleNotification(notification: any): void { + switch (notification.type) { + case 'Hearts.GameStartedNotification': + this.gameStartedHandlers.forEach(h => h(notification)); + break; + case 'Hearts.PassingPhaseStartedNotification': + this.passingPhaseStartedHandlers.forEach(h => h(notification)); + break; + case 'Hearts.AllPlayersPassedNotification': + this.allPlayersPassedHandlers.forEach(h => h(notification)); + break; + case 'Hearts.PlayerPassedCardsNotification': + this.playerPassedCardsHandlers.forEach(h => h(notification)); + break; + case 'Hearts.ItsYourTurnNotification': + this.itsYourTurnHandlers.forEach(h => h(notification)); + break; + case 'Hearts.ItsPlayersTurnNotification': + this.itsPlayersTurnHandlers.forEach(h => h(notification)); + break; + case 'Hearts.PlayerPlayedCardNotification': + this.playerPlayedCardHandlers.forEach(h => h(notification)); + break; + case 'Hearts.TrickCompletedNotification': + this.trickCompletedHandlers.forEach(h => h(notification)); + break; + case 'Hearts.RoundEndedNotification': + this.roundEndedHandlers.forEach(h => h(notification)); + break; + case 'Hearts.GameEndedNotification': + this.gameEndedHandlers.forEach(h => h(notification)); + break; + case 'Hearts.HeartsAreBrokenNotification': + this.heartsWereBrokenHandlers.forEach(h => h(notification)); + break; + } + } + + onGameStarted(handler: GameStartedHandler): void { + this.gameStartedHandlers.push(handler); + } + + offGameStarted(handler: GameStartedHandler): void { + const index = this.gameStartedHandlers.indexOf(handler); + if (index > -1) { + this.gameStartedHandlers.splice(index, 1); + } + } + + onPassingPhaseStarted(handler: PassingPhaseStartedHandler): void { + this.passingPhaseStartedHandlers.push(handler); + } + + offPassingPhaseStarted(handler: PassingPhaseStartedHandler): void { + const index = this.passingPhaseStartedHandlers.indexOf(handler); + if (index > -1) { + this.passingPhaseStartedHandlers.splice(index, 1); + } + } + + onAllPlayersPassed(handler: AllPlayersPassedHandler): void { + this.allPlayersPassedHandlers.push(handler); + } + + offAllPlayersPassed(handler: AllPlayersPassedHandler): void { + const index = this.allPlayersPassedHandlers.indexOf(handler); + if (index > -1) { + this.allPlayersPassedHandlers.splice(index, 1); + } + } + + onPlayerPassedCards(handler: PlayerPassedCardsHandler): void { + this.playerPassedCardsHandlers.push(handler); + } + + offPlayerPassedCards(handler: PlayerPassedCardsHandler): void { + const index = this.playerPassedCardsHandlers.indexOf(handler); + if (index > -1) { + this.playerPassedCardsHandlers.splice(index, 1); + } + } + + onItsYourTurn(handler: ItsYourTurnHandler): void { + this.itsYourTurnHandlers.push(handler); + } + + offItsYourTurn(handler: ItsYourTurnHandler): void { + const index = this.itsYourTurnHandlers.indexOf(handler); + if (index > -1) { + this.itsYourTurnHandlers.splice(index, 1); + } + } + + onItsPlayersTurn(handler: ItsPlayersTurnHandler): void { + this.itsPlayersTurnHandlers.push(handler); + } + + offItsPlayersTurn(handler: ItsPlayersTurnHandler): void { + const index = this.itsPlayersTurnHandlers.indexOf(handler); + if (index > -1) { + this.itsPlayersTurnHandlers.splice(index, 1); + } + } + + onPlayerPlayedCard(handler: PlayerPlayedCardHandler): void { + this.playerPlayedCardHandlers.push(handler); + } + + offPlayerPlayedCard(handler: PlayerPlayedCardHandler): void { + const index = this.playerPlayedCardHandlers.indexOf(handler); + if (index > -1) { + this.playerPlayedCardHandlers.splice(index, 1); + } + } + + onTrickCompleted(handler: TrickCompletedHandler): void { + this.trickCompletedHandlers.push(handler); + } + + offTrickCompleted(handler: TrickCompletedHandler): void { + const index = this.trickCompletedHandlers.indexOf(handler); + if (index > -1) { + this.trickCompletedHandlers.splice(index, 1); + } + } + + onRoundEnded(handler: RoundEndedHandler): void { + this.roundEndedHandlers.push(handler); + } + + offRoundEnded(handler: RoundEndedHandler): void { + const index = this.roundEndedHandlers.indexOf(handler); + if (index > -1) { + this.roundEndedHandlers.splice(index, 1); + } + } + + onGameEnded(handler: GameEndedHandler): void { + this.gameEndedHandlers.push(handler); + } + + offGameEnded(handler: GameEndedHandler): void { + const index = this.gameEndedHandlers.indexOf(handler); + if (index > -1) { + this.gameEndedHandlers.splice(index, 1); + } + } + + onHeartsWereBroken(handler: HeartsWereBrokenHandler): void { + this.heartsWereBrokenHandlers.push(handler); + } + + offHeartsWereBroken(handler: HeartsWereBrokenHandler): void { + const index = this.heartsWereBrokenHandlers.indexOf(handler); + if (index > -1) { + this.heartsWereBrokenHandlers.splice(index, 1); + } + } + + async passCards(request: PassCardsRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'Hearts.PassCardsRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + + async playCard(request: PlayCardRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'Hearts.PlayCardRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + +} diff --git a/generated/typescript/hearts/types.ts b/generated/typescript/hearts/types.ts new file mode 100644 index 00000000..fafd9370 --- /dev/null +++ b/generated/typescript/hearts/types.ts @@ -0,0 +1,144 @@ +/** + * Autogenerated by really, really eager small hamsters. + * Shared type definitions for Deckster game clients. + */ + +export interface GameStartedNotification { + gameId: string; + playerViewOfGame?: PlayerViewOfGame; + type?: string; +} + +export interface PassingPhaseStartedNotification { + passDirection: PassDirection; + type?: string; +} + +export enum PassDirection { + None = 0, + Left = 1, + Right = 2, + Across = 3, +} + +export interface AllPlayersPassedNotification { + receivedCards?: Card[]; + type?: string; +} + +export interface Card { + rank: number; + suit: Suit; +} + +export enum Suit { + Clubs = 0, + Diamonds = 1, + Hearts = 2, + Spades = 3, +} + +export interface PlayerPassedCardsNotification { + playerId: string; + type?: string; +} + +export interface ItsYourTurnNotification { + playerViewOfGame?: PlayerViewOfGame; + type?: string; +} + +export interface ItsPlayersTurnNotification { + playerId: string; + type?: string; +} + +export interface PlayerPlayedCardNotification { + playerId: string; + card: Card; + type?: string; +} + +export interface TrickCompletedNotification { + winnerId: string; + winnerName?: string; + trickCards?: CardPlay[]; + points: number; + type?: string; +} + +export interface CardPlay { + playerId: string; + playerName?: string; + card: Card; +} + +export interface RoundEndedNotification { + scores?: PlayerScore[]; + moonShooterId?: string; + moonShooterName?: string; + type?: string; +} + +export interface PlayerScore { + playerId: string; + playerName?: string; + roundScore: number; + totalScore: number; +} + +export interface GameEndedNotification { + finalScores?: PlayerScore[]; + winnerId: string; + winnerName?: string; + type?: string; +} + +export interface HeartsAreBrokenNotification { + type?: string; +} + +export interface PassCardsRequest { + cards?: Card[]; + playerId: string; + type?: string; +} + +export interface PassCardsResponse { + receivedCards?: Card[]; + hasError: boolean; + error?: string; + type?: string; +} + +export interface PlayCardRequest { + card: Card; + playerId: string; + type?: string; +} + +export interface PlayerViewOfGame { + cards?: Card[]; + otherPlayers?: OtherHeartsPlayer[]; + roundNumber: number; + passDirection: PassDirection; + hasPassed: boolean; + currentTrick?: CardPlay[]; + totalScore: number; + roundScore: number; + heartsAreBroken: boolean; + isMyTurn: boolean; + hasError: boolean; + error?: string; + type?: string; +} + +export interface OtherHeartsPlayer { + playerId: string; + name?: string; + numberOfCards: number; + totalScore: number; + roundScore: number; + playedCard?: Card; +} + diff --git a/generated/typescript/idiot/IdiotClient.ts b/generated/typescript/idiot/IdiotClient.ts new file mode 100644 index 00000000..92ffc463 --- /dev/null +++ b/generated/typescript/idiot/IdiotClient.ts @@ -0,0 +1,425 @@ +/** + * Autogenerated by really, really eager small hamsters. + * + * Idiot Game Client + * + * Notifications (events) for this game: + * - ItsTimeToSwapCards: ItsTimeToSwapCardsNotification + * - PlayerIsReady: PlayerIsReadyNotification + * - GameHasStarted: GameStartedNotification + * - GameEnded: GameEndedNotification + * - ItsYourTurn: ItsYourTurnNotification + * - PlayerDrewCards: PlayerDrewCardsNotification + * - PlayerPutCards: PlayerPutCardsNotification + * - DiscardPileFlushed: DiscardPileFlushedNotification + * - PlayerIsDone: PlayerIsDoneNotification + * - PlayerSwappedCards: PlayerSwappedCardsNotification + * - PlayerAttemptedPuttingCard: PlayerAttemptedPuttingCardNotification + * - PlayerPulledInDiscardPile: PlayerPulledInDiscardPileNotification + */ + +import type { EmptyResponse } from '../types'; +import type { DiscardPileFlushedNotification, DrawCardsResponse, GameEndedNotification, GameStartedNotification, IamReadyRequest, ItsTimeToSwapCardsNotification, ItsYourTurnNotification, PlayerAttemptedPuttingCardNotification, PlayerDrewCardsNotification, PlayerIsDoneNotification, PlayerIsReadyNotification, PlayerPulledInDiscardPileNotification, PlayerPutCardsNotification, PlayerSwappedCardsNotification, PullInDiscardPileRequest, PullInResponse, PutBlindCardResponse, PutCardFacingDownRequest, PutCardsFacingUpRequest, PutCardsFromHandRequest, PutChanceCardRequest, SwapCardsRequest, SwapCardsResponse } from './types'; + +// Event handler types +export type ItsTimeToSwapCardsHandler = (data: ItsTimeToSwapCardsNotification) => void; +export type PlayerIsReadyHandler = (data: PlayerIsReadyNotification) => void; +export type GameHasStartedHandler = (data: GameStartedNotification) => void; +export type GameEndedHandler = (data: GameEndedNotification) => void; +export type ItsYourTurnHandler = (data: ItsYourTurnNotification) => void; +export type PlayerDrewCardsHandler = (data: PlayerDrewCardsNotification) => void; +export type PlayerPutCardsHandler = (data: PlayerPutCardsNotification) => void; +export type DiscardPileFlushedHandler = (data: DiscardPileFlushedNotification) => void; +export type PlayerIsDoneHandler = (data: PlayerIsDoneNotification) => void; +export type PlayerSwappedCardsHandler = (data: PlayerSwappedCardsNotification) => void; +export type PlayerAttemptedPuttingCardHandler = (data: PlayerAttemptedPuttingCardNotification) => void; +export type PlayerPulledInDiscardPileHandler = (data: PlayerPulledInDiscardPileNotification) => void; + +export interface IdiotClient { + onItsTimeToSwapCards(handler: ItsTimeToSwapCardsHandler): void; + offItsTimeToSwapCards(handler: ItsTimeToSwapCardsHandler): void; + onPlayerIsReady(handler: PlayerIsReadyHandler): void; + offPlayerIsReady(handler: PlayerIsReadyHandler): void; + onGameHasStarted(handler: GameHasStartedHandler): void; + offGameHasStarted(handler: GameHasStartedHandler): void; + onGameEnded(handler: GameEndedHandler): void; + offGameEnded(handler: GameEndedHandler): void; + onItsYourTurn(handler: ItsYourTurnHandler): void; + offItsYourTurn(handler: ItsYourTurnHandler): void; + onPlayerDrewCards(handler: PlayerDrewCardsHandler): void; + offPlayerDrewCards(handler: PlayerDrewCardsHandler): void; + onPlayerPutCards(handler: PlayerPutCardsHandler): void; + offPlayerPutCards(handler: PlayerPutCardsHandler): void; + onDiscardPileFlushed(handler: DiscardPileFlushedHandler): void; + offDiscardPileFlushed(handler: DiscardPileFlushedHandler): void; + onPlayerIsDone(handler: PlayerIsDoneHandler): void; + offPlayerIsDone(handler: PlayerIsDoneHandler): void; + onPlayerSwappedCards(handler: PlayerSwappedCardsHandler): void; + offPlayerSwappedCards(handler: PlayerSwappedCardsHandler): void; + onPlayerAttemptedPuttingCard(handler: PlayerAttemptedPuttingCardHandler): void; + offPlayerAttemptedPuttingCard(handler: PlayerAttemptedPuttingCardHandler): void; + onPlayerPulledInDiscardPile(handler: PlayerPulledInDiscardPileHandler): void; + offPlayerPulledInDiscardPile(handler: PlayerPulledInDiscardPileHandler): void; + + iamReady(request: IamReadyRequest): Promise; + swapCards(request: SwapCardsRequest): Promise; + putCardsFromHand(request: PutCardsFromHandRequest): Promise; + putCardsFacingUp(request: PutCardsFacingUpRequest): Promise; + putCardFacingDown(request: PutCardFacingDownRequest): Promise; + putChanceCard(request: PutChanceCardRequest): Promise; + pullInDiscardPile(request: PullInDiscardPileRequest): Promise; +} + +export class IdiotClientImpl implements IdiotClient { + private itsTimeToSwapCardsHandlers: ItsTimeToSwapCardsHandler[] = []; + private playerIsReadyHandlers: PlayerIsReadyHandler[] = []; + private gameHasStartedHandlers: GameHasStartedHandler[] = []; + private gameEndedHandlers: GameEndedHandler[] = []; + private itsYourTurnHandlers: ItsYourTurnHandler[] = []; + private playerDrewCardsHandlers: PlayerDrewCardsHandler[] = []; + private playerPutCardsHandlers: PlayerPutCardsHandler[] = []; + private discardPileFlushedHandlers: DiscardPileFlushedHandler[] = []; + private playerIsDoneHandlers: PlayerIsDoneHandler[] = []; + private playerSwappedCardsHandlers: PlayerSwappedCardsHandler[] = []; + private playerAttemptedPuttingCardHandlers: PlayerAttemptedPuttingCardHandler[] = []; + private playerPulledInDiscardPileHandlers: PlayerPulledInDiscardPileHandler[] = []; + + constructor(private actionSocket: WebSocket, private notificationSocket: WebSocket) { + this.setupNotificationHandlers(); + } + + private setupNotificationHandlers(): void { + this.notificationSocket.onmessage = (event) => { + const notification = JSON.parse(event.data); + this.handleNotification(notification); + }; + } + + private handleNotification(notification: any): void { + switch (notification.type) { + case 'Idiot.ItsTimeToSwapCardsNotification': + this.itsTimeToSwapCardsHandlers.forEach(h => h(notification)); + break; + case 'Idiot.PlayerIsReadyNotification': + this.playerIsReadyHandlers.forEach(h => h(notification)); + break; + case 'Idiot.GameStartedNotification': + this.gameHasStartedHandlers.forEach(h => h(notification)); + break; + case 'Idiot.GameEndedNotification': + this.gameEndedHandlers.forEach(h => h(notification)); + break; + case 'Idiot.ItsYourTurnNotification': + this.itsYourTurnHandlers.forEach(h => h(notification)); + break; + case 'Idiot.PlayerDrewCardsNotification': + this.playerDrewCardsHandlers.forEach(h => h(notification)); + break; + case 'Idiot.PlayerPutCardsNotification': + this.playerPutCardsHandlers.forEach(h => h(notification)); + break; + case 'Idiot.DiscardPileFlushedNotification': + this.discardPileFlushedHandlers.forEach(h => h(notification)); + break; + case 'Idiot.PlayerIsDoneNotification': + this.playerIsDoneHandlers.forEach(h => h(notification)); + break; + case 'Idiot.PlayerSwappedCardsNotification': + this.playerSwappedCardsHandlers.forEach(h => h(notification)); + break; + case 'Idiot.PlayerAttemptedPuttingCardNotification': + this.playerAttemptedPuttingCardHandlers.forEach(h => h(notification)); + break; + case 'Idiot.PlayerPulledInDiscardPileNotification': + this.playerPulledInDiscardPileHandlers.forEach(h => h(notification)); + break; + } + } + + onItsTimeToSwapCards(handler: ItsTimeToSwapCardsHandler): void { + this.itsTimeToSwapCardsHandlers.push(handler); + } + + offItsTimeToSwapCards(handler: ItsTimeToSwapCardsHandler): void { + const index = this.itsTimeToSwapCardsHandlers.indexOf(handler); + if (index > -1) { + this.itsTimeToSwapCardsHandlers.splice(index, 1); + } + } + + onPlayerIsReady(handler: PlayerIsReadyHandler): void { + this.playerIsReadyHandlers.push(handler); + } + + offPlayerIsReady(handler: PlayerIsReadyHandler): void { + const index = this.playerIsReadyHandlers.indexOf(handler); + if (index > -1) { + this.playerIsReadyHandlers.splice(index, 1); + } + } + + onGameHasStarted(handler: GameHasStartedHandler): void { + this.gameHasStartedHandlers.push(handler); + } + + offGameHasStarted(handler: GameHasStartedHandler): void { + const index = this.gameHasStartedHandlers.indexOf(handler); + if (index > -1) { + this.gameHasStartedHandlers.splice(index, 1); + } + } + + onGameEnded(handler: GameEndedHandler): void { + this.gameEndedHandlers.push(handler); + } + + offGameEnded(handler: GameEndedHandler): void { + const index = this.gameEndedHandlers.indexOf(handler); + if (index > -1) { + this.gameEndedHandlers.splice(index, 1); + } + } + + onItsYourTurn(handler: ItsYourTurnHandler): void { + this.itsYourTurnHandlers.push(handler); + } + + offItsYourTurn(handler: ItsYourTurnHandler): void { + const index = this.itsYourTurnHandlers.indexOf(handler); + if (index > -1) { + this.itsYourTurnHandlers.splice(index, 1); + } + } + + onPlayerDrewCards(handler: PlayerDrewCardsHandler): void { + this.playerDrewCardsHandlers.push(handler); + } + + offPlayerDrewCards(handler: PlayerDrewCardsHandler): void { + const index = this.playerDrewCardsHandlers.indexOf(handler); + if (index > -1) { + this.playerDrewCardsHandlers.splice(index, 1); + } + } + + onPlayerPutCards(handler: PlayerPutCardsHandler): void { + this.playerPutCardsHandlers.push(handler); + } + + offPlayerPutCards(handler: PlayerPutCardsHandler): void { + const index = this.playerPutCardsHandlers.indexOf(handler); + if (index > -1) { + this.playerPutCardsHandlers.splice(index, 1); + } + } + + onDiscardPileFlushed(handler: DiscardPileFlushedHandler): void { + this.discardPileFlushedHandlers.push(handler); + } + + offDiscardPileFlushed(handler: DiscardPileFlushedHandler): void { + const index = this.discardPileFlushedHandlers.indexOf(handler); + if (index > -1) { + this.discardPileFlushedHandlers.splice(index, 1); + } + } + + onPlayerIsDone(handler: PlayerIsDoneHandler): void { + this.playerIsDoneHandlers.push(handler); + } + + offPlayerIsDone(handler: PlayerIsDoneHandler): void { + const index = this.playerIsDoneHandlers.indexOf(handler); + if (index > -1) { + this.playerIsDoneHandlers.splice(index, 1); + } + } + + onPlayerSwappedCards(handler: PlayerSwappedCardsHandler): void { + this.playerSwappedCardsHandlers.push(handler); + } + + offPlayerSwappedCards(handler: PlayerSwappedCardsHandler): void { + const index = this.playerSwappedCardsHandlers.indexOf(handler); + if (index > -1) { + this.playerSwappedCardsHandlers.splice(index, 1); + } + } + + onPlayerAttemptedPuttingCard(handler: PlayerAttemptedPuttingCardHandler): void { + this.playerAttemptedPuttingCardHandlers.push(handler); + } + + offPlayerAttemptedPuttingCard(handler: PlayerAttemptedPuttingCardHandler): void { + const index = this.playerAttemptedPuttingCardHandlers.indexOf(handler); + if (index > -1) { + this.playerAttemptedPuttingCardHandlers.splice(index, 1); + } + } + + onPlayerPulledInDiscardPile(handler: PlayerPulledInDiscardPileHandler): void { + this.playerPulledInDiscardPileHandlers.push(handler); + } + + offPlayerPulledInDiscardPile(handler: PlayerPulledInDiscardPileHandler): void { + const index = this.playerPulledInDiscardPileHandlers.indexOf(handler); + if (index > -1) { + this.playerPulledInDiscardPileHandlers.splice(index, 1); + } + } + + async iamReady(request: IamReadyRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'Idiot.IamReadyRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + + async swapCards(request: SwapCardsRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'Idiot.SwapCardsRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + + async putCardsFromHand(request: PutCardsFromHandRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'Idiot.PutCardsFromHandRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + + async putCardsFacingUp(request: PutCardsFacingUpRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'Idiot.PutCardsFacingUpRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + + async putCardFacingDown(request: PutCardFacingDownRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'Idiot.PutCardFacingDownRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + + async putChanceCard(request: PutChanceCardRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'Idiot.PutChanceCardRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + + async pullInDiscardPile(request: PullInDiscardPileRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'Idiot.PullInDiscardPileRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + +} diff --git a/generated/typescript/idiot/types.ts b/generated/typescript/idiot/types.ts new file mode 100644 index 00000000..90d4bed1 --- /dev/null +++ b/generated/typescript/idiot/types.ts @@ -0,0 +1,173 @@ +/** + * Autogenerated by really, really eager small hamsters. + * Shared type definitions for Deckster game clients. + */ + +export interface ItsTimeToSwapCardsNotification { + playerViewOfGame?: PlayerViewOfGame; + type?: string; +} + +export interface PlayerViewOfGame { + cardsOnHand?: Card[]; + cardsFacingUp?: Card[]; + stockPileCount: number; + otherPlayers?: OtherIdiotPlayer[]; + cardsFacingDownCount: number; +} + +export interface Card { + rank: number; + suit: Suit; +} + +export enum Suit { + Clubs = 0, + Diamonds = 1, + Hearts = 2, + Spades = 3, +} + +export interface PlayerIsReadyNotification { + playerId: string; + type?: string; +} + +export interface GameStartedNotification { + type?: string; +} + +export interface GameEndedNotification { + loserId: string; + type?: string; +} + +export interface ItsYourTurnNotification { + type?: string; +} + +export interface PlayerDrewCardsNotification { + playerId: string; + numberOfCards: number; + type?: string; +} + +export interface PlayerPutCardsNotification { + playerId: string; + cards?: Card[]; + from: PutCardFrom; + type?: string; +} + +export enum PutCardFrom { + Hand = 0, + FacingUp = 1, + FacingDown = 2, +} + +export interface DiscardPileFlushedNotification { + playerId: string; + type?: string; +} + +export interface PlayerIsDoneNotification { + playerId: string; + type?: string; +} + +export interface PlayerSwappedCardsNotification { + playerId: string; + cardNowOnHand: Card; + cardNowFacingUp: Card; + type?: string; +} + +export interface PlayerAttemptedPuttingCardNotification { + playerId: string; + card: Card; + type?: string; +} + +export interface PlayerPulledInDiscardPileNotification { + playerId: string; + type?: string; +} + +export interface IamReadyRequest { + playerId: string; + type?: string; +} + +export interface SwapCardsRequest { + cardOnHand: Card; + cardFacingUp: Card; + playerId: string; + type?: string; +} + +export interface SwapCardsResponse { + cardNowOnHand: Card; + cardNowFacingUp: Card; + hasError: boolean; + error?: string; + type?: string; +} + +export interface PutCardsFromHandRequest { + cards?: Card[]; + playerId: string; + type?: string; +} + +export interface DrawCardsResponse { + cards?: Card[]; + hasError: boolean; + error?: string; + type?: string; +} + +export interface PutCardsFacingUpRequest { + cards?: Card[]; + playerId: string; + type?: string; +} + +export interface PutCardFacingDownRequest { + index: number; + playerId: string; + type?: string; +} + +export interface PutBlindCardResponse { + attemptedCard: Card; + pullInCards?: Card[]; + hasError: boolean; + error?: string; + type?: string; +} + +export interface PutChanceCardRequest { + playerId: string; + type?: string; +} + +export interface PullInDiscardPileRequest { + playerId: string; + type?: string; +} + +export interface PullInResponse { + cards?: Card[]; + hasError: boolean; + error?: string; + type?: string; +} + +export interface OtherIdiotPlayer { + id: string; + name?: string; + cardsOnHandCount: number; + cardsFacingUp?: Card[]; + cardsFacingDownCount: number; +} + diff --git a/generated/typescript/texasholdem/TexasHoldEmClient.ts b/generated/typescript/texasholdem/TexasHoldEmClient.ts new file mode 100644 index 00000000..479f5f90 --- /dev/null +++ b/generated/typescript/texasholdem/TexasHoldEmClient.ts @@ -0,0 +1,336 @@ +/** + * Autogenerated by really, really eager small hamsters. + * + * TexasHoldEm Game Client + * + * Notifications (events) for this game: + * - GameStarted: GameStartedNotification + * - ItsYourTurn: ItsYourTurnNotification + * - RoundStarted: NewRoundStartedNotification + * - RoundEnded: RoundEndedNotification + * - PlayerBetted: PlayerBettedNotification + * - PlayerAllIn: PlayerAllInNotification + * - PlayerChecked: PlayerCheckedNotification + * - PlayerFolded: PlayerFoldedNotification + * - PlayerCalled: PlayerCalledNotification + * - NewCardsRevealed: NewCardsRevealed + * - GameEnded: GameEndedNotification + */ + +import type { BetRequest, CallRequest, CheckRequest, FoldRequest, GameEndedNotification, GameStartedNotification, ItsYourTurnNotification, NewCardsRevealed, NewRoundStartedNotification, PlayerAllInNotification, PlayerBettedNotification, PlayerCalledNotification, PlayerCheckedNotification, PlayerFoldedNotification, PlayerViewOfGame, RoundEndedNotification } from './types'; + +// Event handler types +export type GameStartedHandler = (data: GameStartedNotification) => void; +export type ItsYourTurnHandler = (data: ItsYourTurnNotification) => void; +export type RoundStartedHandler = (data: NewRoundStartedNotification) => void; +export type RoundEndedHandler = (data: RoundEndedNotification) => void; +export type PlayerBettedHandler = (data: PlayerBettedNotification) => void; +export type PlayerAllInHandler = (data: PlayerAllInNotification) => void; +export type PlayerCheckedHandler = (data: PlayerCheckedNotification) => void; +export type PlayerFoldedHandler = (data: PlayerFoldedNotification) => void; +export type PlayerCalledHandler = (data: PlayerCalledNotification) => void; +export type NewCardsRevealedHandler = (data: NewCardsRevealed) => void; +export type GameEndedHandler = (data: GameEndedNotification) => void; + +export interface TexasHoldEmClient { + onGameStarted(handler: GameStartedHandler): void; + offGameStarted(handler: GameStartedHandler): void; + onItsYourTurn(handler: ItsYourTurnHandler): void; + offItsYourTurn(handler: ItsYourTurnHandler): void; + onRoundStarted(handler: RoundStartedHandler): void; + offRoundStarted(handler: RoundStartedHandler): void; + onRoundEnded(handler: RoundEndedHandler): void; + offRoundEnded(handler: RoundEndedHandler): void; + onPlayerBetted(handler: PlayerBettedHandler): void; + offPlayerBetted(handler: PlayerBettedHandler): void; + onPlayerAllIn(handler: PlayerAllInHandler): void; + offPlayerAllIn(handler: PlayerAllInHandler): void; + onPlayerChecked(handler: PlayerCheckedHandler): void; + offPlayerChecked(handler: PlayerCheckedHandler): void; + onPlayerFolded(handler: PlayerFoldedHandler): void; + offPlayerFolded(handler: PlayerFoldedHandler): void; + onPlayerCalled(handler: PlayerCalledHandler): void; + offPlayerCalled(handler: PlayerCalledHandler): void; + onNewCardsRevealed(handler: NewCardsRevealedHandler): void; + offNewCardsRevealed(handler: NewCardsRevealedHandler): void; + onGameEnded(handler: GameEndedHandler): void; + offGameEnded(handler: GameEndedHandler): void; + + playerBetRequest(request: BetRequest): Promise; + playerFoldRequest(request: FoldRequest): Promise; + playerCheckRequest(request: CheckRequest): Promise; + playerCallRequest(request: CallRequest): Promise; +} + +export class TexasHoldEmClientImpl implements TexasHoldEmClient { + private gameStartedHandlers: GameStartedHandler[] = []; + private itsYourTurnHandlers: ItsYourTurnHandler[] = []; + private roundStartedHandlers: RoundStartedHandler[] = []; + private roundEndedHandlers: RoundEndedHandler[] = []; + private playerBettedHandlers: PlayerBettedHandler[] = []; + private playerAllInHandlers: PlayerAllInHandler[] = []; + private playerCheckedHandlers: PlayerCheckedHandler[] = []; + private playerFoldedHandlers: PlayerFoldedHandler[] = []; + private playerCalledHandlers: PlayerCalledHandler[] = []; + private newCardsRevealedHandlers: NewCardsRevealedHandler[] = []; + private gameEndedHandlers: GameEndedHandler[] = []; + + constructor(private actionSocket: WebSocket, private notificationSocket: WebSocket) { + this.setupNotificationHandlers(); + } + + private setupNotificationHandlers(): void { + this.notificationSocket.onmessage = (event) => { + const notification = JSON.parse(event.data); + this.handleNotification(notification); + }; + } + + private handleNotification(notification: any): void { + switch (notification.type) { + case 'TexasHoldEm.GameStartedNotification': + this.gameStartedHandlers.forEach(h => h(notification)); + break; + case 'TexasHoldEm.ItsYourTurnNotification': + this.itsYourTurnHandlers.forEach(h => h(notification)); + break; + case 'TexasHoldEm.NewRoundStartedNotification': + this.roundStartedHandlers.forEach(h => h(notification)); + break; + case 'TexasHoldEm.RoundEndedNotification': + this.roundEndedHandlers.forEach(h => h(notification)); + break; + case 'TexasHoldEm.PlayerBettedNotification': + this.playerBettedHandlers.forEach(h => h(notification)); + break; + case 'TexasHoldEm.PlayerAllInNotification': + this.playerAllInHandlers.forEach(h => h(notification)); + break; + case 'TexasHoldEm.PlayerCheckedNotification': + this.playerCheckedHandlers.forEach(h => h(notification)); + break; + case 'TexasHoldEm.PlayerFoldedNotification': + this.playerFoldedHandlers.forEach(h => h(notification)); + break; + case 'TexasHoldEm.PlayerCalledNotification': + this.playerCalledHandlers.forEach(h => h(notification)); + break; + case 'TexasHoldEm.NewCardsRevealed': + this.newCardsRevealedHandlers.forEach(h => h(notification)); + break; + case 'TexasHoldEm.GameEndedNotification': + this.gameEndedHandlers.forEach(h => h(notification)); + break; + } + } + + onGameStarted(handler: GameStartedHandler): void { + this.gameStartedHandlers.push(handler); + } + + offGameStarted(handler: GameStartedHandler): void { + const index = this.gameStartedHandlers.indexOf(handler); + if (index > -1) { + this.gameStartedHandlers.splice(index, 1); + } + } + + onItsYourTurn(handler: ItsYourTurnHandler): void { + this.itsYourTurnHandlers.push(handler); + } + + offItsYourTurn(handler: ItsYourTurnHandler): void { + const index = this.itsYourTurnHandlers.indexOf(handler); + if (index > -1) { + this.itsYourTurnHandlers.splice(index, 1); + } + } + + onRoundStarted(handler: RoundStartedHandler): void { + this.roundStartedHandlers.push(handler); + } + + offRoundStarted(handler: RoundStartedHandler): void { + const index = this.roundStartedHandlers.indexOf(handler); + if (index > -1) { + this.roundStartedHandlers.splice(index, 1); + } + } + + onRoundEnded(handler: RoundEndedHandler): void { + this.roundEndedHandlers.push(handler); + } + + offRoundEnded(handler: RoundEndedHandler): void { + const index = this.roundEndedHandlers.indexOf(handler); + if (index > -1) { + this.roundEndedHandlers.splice(index, 1); + } + } + + onPlayerBetted(handler: PlayerBettedHandler): void { + this.playerBettedHandlers.push(handler); + } + + offPlayerBetted(handler: PlayerBettedHandler): void { + const index = this.playerBettedHandlers.indexOf(handler); + if (index > -1) { + this.playerBettedHandlers.splice(index, 1); + } + } + + onPlayerAllIn(handler: PlayerAllInHandler): void { + this.playerAllInHandlers.push(handler); + } + + offPlayerAllIn(handler: PlayerAllInHandler): void { + const index = this.playerAllInHandlers.indexOf(handler); + if (index > -1) { + this.playerAllInHandlers.splice(index, 1); + } + } + + onPlayerChecked(handler: PlayerCheckedHandler): void { + this.playerCheckedHandlers.push(handler); + } + + offPlayerChecked(handler: PlayerCheckedHandler): void { + const index = this.playerCheckedHandlers.indexOf(handler); + if (index > -1) { + this.playerCheckedHandlers.splice(index, 1); + } + } + + onPlayerFolded(handler: PlayerFoldedHandler): void { + this.playerFoldedHandlers.push(handler); + } + + offPlayerFolded(handler: PlayerFoldedHandler): void { + const index = this.playerFoldedHandlers.indexOf(handler); + if (index > -1) { + this.playerFoldedHandlers.splice(index, 1); + } + } + + onPlayerCalled(handler: PlayerCalledHandler): void { + this.playerCalledHandlers.push(handler); + } + + offPlayerCalled(handler: PlayerCalledHandler): void { + const index = this.playerCalledHandlers.indexOf(handler); + if (index > -1) { + this.playerCalledHandlers.splice(index, 1); + } + } + + onNewCardsRevealed(handler: NewCardsRevealedHandler): void { + this.newCardsRevealedHandlers.push(handler); + } + + offNewCardsRevealed(handler: NewCardsRevealedHandler): void { + const index = this.newCardsRevealedHandlers.indexOf(handler); + if (index > -1) { + this.newCardsRevealedHandlers.splice(index, 1); + } + } + + onGameEnded(handler: GameEndedHandler): void { + this.gameEndedHandlers.push(handler); + } + + offGameEnded(handler: GameEndedHandler): void { + const index = this.gameEndedHandlers.indexOf(handler); + if (index > -1) { + this.gameEndedHandlers.splice(index, 1); + } + } + + async playerBetRequest(request: BetRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'TexasHoldEm.BetRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + + async playerFoldRequest(request: FoldRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'TexasHoldEm.FoldRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + + async playerCheckRequest(request: CheckRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'TexasHoldEm.CheckRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + + async playerCallRequest(request: CallRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'TexasHoldEm.CallRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + +} diff --git a/generated/typescript/texasholdem/types.ts b/generated/typescript/texasholdem/types.ts new file mode 100644 index 00000000..db88f7fa --- /dev/null +++ b/generated/typescript/texasholdem/types.ts @@ -0,0 +1,146 @@ +/** + * Autogenerated by really, really eager small hamsters. + * Shared type definitions for Deckster game clients. + */ + +export interface GameStartedNotification { + gameId: string; + playerViewOfGame?: PlayerViewOfGame; + type?: string; +} + +export interface ItsYourTurnNotification { + playerViewOfGame?: PlayerViewOfGame; + type?: string; +} + +export interface NewRoundStartedNotification { + gameId: string; + playerViewOfGame?: PlayerViewOfGame; + type?: string; +} + +export interface RoundEndedNotification { + winnerId: string; + winnings: number; + type?: string; +} + +export interface PlayerBettedNotification { + playerId: string; + betSize: number; + type?: string; +} + +export interface PlayerAllInNotification { + playerId: string; + type?: string; +} + +export interface PlayerCheckedNotification { + playerId: string; + type?: string; +} + +export interface PlayerFoldedNotification { + playerId: string; + type?: string; +} + +export interface PlayerCalledNotification { + playerId: string; + type?: string; +} + +export interface NewCardsRevealed { + cards?: Card[]; + type?: string; +} + +export interface Card { + rank: number; + suit: Suit; +} + +export enum Suit { + Clubs = 0, + Diamonds = 1, + Hearts = 2, + Spades = 3, +} + +export interface GameEndedNotification { + players?: PlayerData[]; + type?: string; +} + +export interface PlayerData { + name?: string; + points: number; + cardsInHand: number; + id: string; + info?: Record; +} + +export interface Dictionary { + comparer?: IEqualityComparer; + count: number; + capacity: number; + keys?: KeyCollection; + values?: ValueCollection; +} + +export interface ValueCollection { + count: number; +} + +export interface KeyCollection { + count: number; +} + +export interface BetRequest { + bet: number; + playerId: string; + type?: string; +} + +export interface PlayerViewOfGame { + cards?: Card[]; + cardsOnTable?: Card[]; + stackSize: number; + currentBet: number; + potSize: number; + bigBlind: number; + numberOfRoundsUntilBigBlindIncreases: number; + otherPlayers?: OtherPokerPlayers[]; + nextRoundStartingPlayerId: string; + hasError: boolean; + error?: string; + type?: string; +} + +export interface OtherPokerPlayers { + playerId: string; + name?: string; + stackSize: number; + currentBet: number; + hasChecked: boolean; + isAllIn: boolean; + hasFolded: boolean; +} + +export interface FoldRequest { + playerId: string; + type?: string; +} + +export interface CheckRequest { + playerId: string; + type?: string; +} + +export interface CallRequest { + playerId: string; + type?: string; +} + diff --git a/generated/typescript/types.ts b/generated/typescript/types.ts new file mode 100644 index 00000000..44509d42 --- /dev/null +++ b/generated/typescript/types.ts @@ -0,0 +1,11 @@ +/** + * Autogenerated by really, really eager small hamsters. + * Shared type definitions for Deckster game clients. + */ + +export interface EmptyResponse { + hasError: boolean; + error?: string; + type?: string; +} + diff --git a/generated/typescript/uno/UnoClient.ts b/generated/typescript/uno/UnoClient.ts new file mode 100644 index 00000000..71861557 --- /dev/null +++ b/generated/typescript/uno/UnoClient.ts @@ -0,0 +1,261 @@ +/** + * Autogenerated by really, really eager small hamsters. + * + * Uno Game Client + * + * Notifications (events) for this game: + * - GameStarted: GameStartedNotification + * - PlayerPutCard: PlayerPutCardNotification + * - PlayerPutWild: PlayerPutWildNotification + * - PlayerDrewCard: PlayerDrewCardNotification + * - PlayerPassed: PlayerPassedNotification + * - GameEnded: GameEndedNotification + * - ItsYourTurn: ItsYourTurnNotification + */ + +import type { EmptyResponse } from '../types'; +import type { DrawCardRequest, GameEndedNotification, GameStartedNotification, ItsYourTurnNotification, PassRequest, PlayerDrewCardNotification, PlayerPassedNotification, PlayerPutCardNotification, PlayerPutWildNotification, PlayerViewOfGame, PutCardRequest, PutWildRequest, UnoCardResponse } from './types'; + +// Event handler types +export type GameStartedHandler = (data: GameStartedNotification) => void; +export type PlayerPutCardHandler = (data: PlayerPutCardNotification) => void; +export type PlayerPutWildHandler = (data: PlayerPutWildNotification) => void; +export type PlayerDrewCardHandler = (data: PlayerDrewCardNotification) => void; +export type PlayerPassedHandler = (data: PlayerPassedNotification) => void; +export type GameEndedHandler = (data: GameEndedNotification) => void; +export type ItsYourTurnHandler = (data: ItsYourTurnNotification) => void; + +export interface UnoClient { + onGameStarted(handler: GameStartedHandler): void; + offGameStarted(handler: GameStartedHandler): void; + onPlayerPutCard(handler: PlayerPutCardHandler): void; + offPlayerPutCard(handler: PlayerPutCardHandler): void; + onPlayerPutWild(handler: PlayerPutWildHandler): void; + offPlayerPutWild(handler: PlayerPutWildHandler): void; + onPlayerDrewCard(handler: PlayerDrewCardHandler): void; + offPlayerDrewCard(handler: PlayerDrewCardHandler): void; + onPlayerPassed(handler: PlayerPassedHandler): void; + offPlayerPassed(handler: PlayerPassedHandler): void; + onGameEnded(handler: GameEndedHandler): void; + offGameEnded(handler: GameEndedHandler): void; + onItsYourTurn(handler: ItsYourTurnHandler): void; + offItsYourTurn(handler: ItsYourTurnHandler): void; + + putCard(request: PutCardRequest): Promise; + putWild(request: PutWildRequest): Promise; + drawCard(request: DrawCardRequest): Promise; + pass(request: PassRequest): Promise; +} + +export class UnoClientImpl implements UnoClient { + private gameStartedHandlers: GameStartedHandler[] = []; + private playerPutCardHandlers: PlayerPutCardHandler[] = []; + private playerPutWildHandlers: PlayerPutWildHandler[] = []; + private playerDrewCardHandlers: PlayerDrewCardHandler[] = []; + private playerPassedHandlers: PlayerPassedHandler[] = []; + private gameEndedHandlers: GameEndedHandler[] = []; + private itsYourTurnHandlers: ItsYourTurnHandler[] = []; + + constructor(private actionSocket: WebSocket, private notificationSocket: WebSocket) { + this.setupNotificationHandlers(); + } + + private setupNotificationHandlers(): void { + this.notificationSocket.onmessage = (event) => { + const notification = JSON.parse(event.data); + this.handleNotification(notification); + }; + } + + private handleNotification(notification: any): void { + switch (notification.type) { + case 'Uno.GameStartedNotification': + this.gameStartedHandlers.forEach(h => h(notification)); + break; + case 'Uno.PlayerPutCardNotification': + this.playerPutCardHandlers.forEach(h => h(notification)); + break; + case 'Uno.PlayerPutWildNotification': + this.playerPutWildHandlers.forEach(h => h(notification)); + break; + case 'Uno.PlayerDrewCardNotification': + this.playerDrewCardHandlers.forEach(h => h(notification)); + break; + case 'Uno.PlayerPassedNotification': + this.playerPassedHandlers.forEach(h => h(notification)); + break; + case 'Uno.GameEndedNotification': + this.gameEndedHandlers.forEach(h => h(notification)); + break; + case 'Uno.ItsYourTurnNotification': + this.itsYourTurnHandlers.forEach(h => h(notification)); + break; + } + } + + onGameStarted(handler: GameStartedHandler): void { + this.gameStartedHandlers.push(handler); + } + + offGameStarted(handler: GameStartedHandler): void { + const index = this.gameStartedHandlers.indexOf(handler); + if (index > -1) { + this.gameStartedHandlers.splice(index, 1); + } + } + + onPlayerPutCard(handler: PlayerPutCardHandler): void { + this.playerPutCardHandlers.push(handler); + } + + offPlayerPutCard(handler: PlayerPutCardHandler): void { + const index = this.playerPutCardHandlers.indexOf(handler); + if (index > -1) { + this.playerPutCardHandlers.splice(index, 1); + } + } + + onPlayerPutWild(handler: PlayerPutWildHandler): void { + this.playerPutWildHandlers.push(handler); + } + + offPlayerPutWild(handler: PlayerPutWildHandler): void { + const index = this.playerPutWildHandlers.indexOf(handler); + if (index > -1) { + this.playerPutWildHandlers.splice(index, 1); + } + } + + onPlayerDrewCard(handler: PlayerDrewCardHandler): void { + this.playerDrewCardHandlers.push(handler); + } + + offPlayerDrewCard(handler: PlayerDrewCardHandler): void { + const index = this.playerDrewCardHandlers.indexOf(handler); + if (index > -1) { + this.playerDrewCardHandlers.splice(index, 1); + } + } + + onPlayerPassed(handler: PlayerPassedHandler): void { + this.playerPassedHandlers.push(handler); + } + + offPlayerPassed(handler: PlayerPassedHandler): void { + const index = this.playerPassedHandlers.indexOf(handler); + if (index > -1) { + this.playerPassedHandlers.splice(index, 1); + } + } + + onGameEnded(handler: GameEndedHandler): void { + this.gameEndedHandlers.push(handler); + } + + offGameEnded(handler: GameEndedHandler): void { + const index = this.gameEndedHandlers.indexOf(handler); + if (index > -1) { + this.gameEndedHandlers.splice(index, 1); + } + } + + onItsYourTurn(handler: ItsYourTurnHandler): void { + this.itsYourTurnHandlers.push(handler); + } + + offItsYourTurn(handler: ItsYourTurnHandler): void { + const index = this.itsYourTurnHandlers.indexOf(handler); + if (index > -1) { + this.itsYourTurnHandlers.splice(index, 1); + } + } + + async putCard(request: PutCardRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'Uno.PutCardRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + + async putWild(request: PutWildRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'Uno.PutWildRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + + async drawCard(request: DrawCardRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'Uno.DrawCardRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + + async pass(request: PassRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'Uno.PassRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + +} diff --git a/generated/typescript/uno/types.ts b/generated/typescript/uno/types.ts new file mode 100644 index 00000000..e277cf16 --- /dev/null +++ b/generated/typescript/uno/types.ts @@ -0,0 +1,147 @@ +/** + * Autogenerated by really, really eager small hamsters. + * Shared type definitions for Deckster game clients. + */ + +export interface GameStartedNotification { + gameId: string; + playerViewOfGame?: PlayerViewOfGame; + type?: string; +} + +export interface PlayerPutCardNotification { + playerId: string; + card?: UnoCard; + type?: string; +} + +export interface UnoCard { + color: UnoColor; + value: UnoValue; +} + +export enum UnoValue { + Zero = 0, + One = 1, + Two = 2, + Three = 3, + Four = 4, + Five = 5, + Six = 6, + Seven = 7, + Eight = 8, + Nine = 9, + Skip = 21, + Reverse = 22, + DrawTwo = 23, + Wild = 51, + WildDrawFour = 52, +} + +export enum UnoColor { + Red = 0, + Yellow = 1, + Green = 2, + Blue = 3, + Wild = 4, +} + +export interface PlayerPutWildNotification { + playerId: string; + card?: UnoCard; + newColor: UnoColor; + type?: string; +} + +export interface PlayerDrewCardNotification { + playerId: string; + type?: string; +} + +export interface PlayerPassedNotification { + playerId: string; + type?: string; +} + +export interface GameEndedNotification { + players?: PlayerData[]; + type?: string; +} + +export interface PlayerData { + name?: string; + points: number; + cardsInHand: number; + id: string; + info?: Record; +} + +export interface Dictionary { + comparer?: IEqualityComparer; + count: number; + capacity: number; + keys?: KeyCollection; + values?: ValueCollection; +} + +export interface ValueCollection { + count: number; +} + +export interface KeyCollection { + count: number; +} + +export interface ItsYourTurnNotification { + playerViewOfGame?: PlayerViewOfGame; + type?: string; +} + +export interface PutCardRequest { + card?: UnoCard; + playerId: string; + type?: string; +} + +export interface PlayerViewOfGame { + cards?: UnoCard[]; + topOfPile?: UnoCard; + currentColor: UnoColor; + stockPileCount: number; + discardPileCount: number; + otherPlayers?: OtherUnoPlayer[]; + hasError: boolean; + error?: string; + type?: string; +} + +export interface OtherUnoPlayer { + id: string; + name?: string; + numberOfCards: number; +} + +export interface PutWildRequest { + card?: UnoCard; + newColor: UnoColor; + playerId: string; + type?: string; +} + +export interface DrawCardRequest { + playerId: string; + type?: string; +} + +export interface UnoCardResponse { + card?: UnoCard; + hasError: boolean; + error?: string; + type?: string; +} + +export interface PassRequest { + playerId: string; + type?: string; +} + diff --git a/generated/typescript/yaniv/YanivClient.ts b/generated/typescript/yaniv/YanivClient.ts new file mode 100644 index 00000000..de3e723d --- /dev/null +++ b/generated/typescript/yaniv/YanivClient.ts @@ -0,0 +1,196 @@ +/** + * Autogenerated by really, really eager small hamsters. + * + * Yaniv Game Client + * + * Notifications (events) for this game: + * - PlayerPutCards: PlayerPutCardsNotification + * - ItsYourTurn: ItsYourTurnNotification + * - RoundStarted: RoundStartedNotification + * - RoundEnded: RoundEndedNotification + * - GameEnded: GameEndedNotification + * - DiscardPileShuffled: DiscardPileShuffledNotification + */ + +import type { EmptyResponse } from '../types'; +import type { CallYanivRequest, DiscardPileShuffledNotification, GameEndedNotification, ItsYourTurnNotification, PlayerPutCardsNotification, PutCardsRequest, PutCardsResponse, RoundEndedNotification, RoundStartedNotification } from './types'; + +// Event handler types +export type PlayerPutCardsHandler = (data: PlayerPutCardsNotification) => void; +export type ItsYourTurnHandler = (data: ItsYourTurnNotification) => void; +export type RoundStartedHandler = (data: RoundStartedNotification) => void; +export type RoundEndedHandler = (data: RoundEndedNotification) => void; +export type GameEndedHandler = (data: GameEndedNotification) => void; +export type DiscardPileShuffledHandler = (data: DiscardPileShuffledNotification) => void; + +export interface YanivClient { + onPlayerPutCards(handler: PlayerPutCardsHandler): void; + offPlayerPutCards(handler: PlayerPutCardsHandler): void; + onItsYourTurn(handler: ItsYourTurnHandler): void; + offItsYourTurn(handler: ItsYourTurnHandler): void; + onRoundStarted(handler: RoundStartedHandler): void; + offRoundStarted(handler: RoundStartedHandler): void; + onRoundEnded(handler: RoundEndedHandler): void; + offRoundEnded(handler: RoundEndedHandler): void; + onGameEnded(handler: GameEndedHandler): void; + offGameEnded(handler: GameEndedHandler): void; + onDiscardPileShuffled(handler: DiscardPileShuffledHandler): void; + offDiscardPileShuffled(handler: DiscardPileShuffledHandler): void; + + callYaniv(request: CallYanivRequest): Promise; + putCards(request: PutCardsRequest): Promise; +} + +export class YanivClientImpl implements YanivClient { + private playerPutCardsHandlers: PlayerPutCardsHandler[] = []; + private itsYourTurnHandlers: ItsYourTurnHandler[] = []; + private roundStartedHandlers: RoundStartedHandler[] = []; + private roundEndedHandlers: RoundEndedHandler[] = []; + private gameEndedHandlers: GameEndedHandler[] = []; + private discardPileShuffledHandlers: DiscardPileShuffledHandler[] = []; + + constructor(private actionSocket: WebSocket, private notificationSocket: WebSocket) { + this.setupNotificationHandlers(); + } + + private setupNotificationHandlers(): void { + this.notificationSocket.onmessage = (event) => { + const notification = JSON.parse(event.data); + this.handleNotification(notification); + }; + } + + private handleNotification(notification: any): void { + switch (notification.type) { + case 'Yaniv.PlayerPutCardsNotification': + this.playerPutCardsHandlers.forEach(h => h(notification)); + break; + case 'Yaniv.ItsYourTurnNotification': + this.itsYourTurnHandlers.forEach(h => h(notification)); + break; + case 'Yaniv.RoundStartedNotification': + this.roundStartedHandlers.forEach(h => h(notification)); + break; + case 'Yaniv.RoundEndedNotification': + this.roundEndedHandlers.forEach(h => h(notification)); + break; + case 'Yaniv.GameEndedNotification': + this.gameEndedHandlers.forEach(h => h(notification)); + break; + case 'Yaniv.DiscardPileShuffledNotification': + this.discardPileShuffledHandlers.forEach(h => h(notification)); + break; + } + } + + onPlayerPutCards(handler: PlayerPutCardsHandler): void { + this.playerPutCardsHandlers.push(handler); + } + + offPlayerPutCards(handler: PlayerPutCardsHandler): void { + const index = this.playerPutCardsHandlers.indexOf(handler); + if (index > -1) { + this.playerPutCardsHandlers.splice(index, 1); + } + } + + onItsYourTurn(handler: ItsYourTurnHandler): void { + this.itsYourTurnHandlers.push(handler); + } + + offItsYourTurn(handler: ItsYourTurnHandler): void { + const index = this.itsYourTurnHandlers.indexOf(handler); + if (index > -1) { + this.itsYourTurnHandlers.splice(index, 1); + } + } + + onRoundStarted(handler: RoundStartedHandler): void { + this.roundStartedHandlers.push(handler); + } + + offRoundStarted(handler: RoundStartedHandler): void { + const index = this.roundStartedHandlers.indexOf(handler); + if (index > -1) { + this.roundStartedHandlers.splice(index, 1); + } + } + + onRoundEnded(handler: RoundEndedHandler): void { + this.roundEndedHandlers.push(handler); + } + + offRoundEnded(handler: RoundEndedHandler): void { + const index = this.roundEndedHandlers.indexOf(handler); + if (index > -1) { + this.roundEndedHandlers.splice(index, 1); + } + } + + onGameEnded(handler: GameEndedHandler): void { + this.gameEndedHandlers.push(handler); + } + + offGameEnded(handler: GameEndedHandler): void { + const index = this.gameEndedHandlers.indexOf(handler); + if (index > -1) { + this.gameEndedHandlers.splice(index, 1); + } + } + + onDiscardPileShuffled(handler: DiscardPileShuffledHandler): void { + this.discardPileShuffledHandlers.push(handler); + } + + offDiscardPileShuffled(handler: DiscardPileShuffledHandler): void { + const index = this.discardPileShuffledHandlers.indexOf(handler); + if (index > -1) { + this.discardPileShuffledHandlers.splice(index, 1); + } + } + + async callYaniv(request: CallYanivRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'Yaniv.CallYanivRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + + async putCards(request: PutCardsRequest): Promise { + return new Promise((resolve, reject) => { + const requestPayload = { + ...request, + type: 'Yaniv.PutCardsRequest' + }; + + const messageHandler = (event: MessageEvent) => { + const response = JSON.parse(event.data); + if (response.hasError) { + reject(new Error(response.error || 'Unknown error')); + } else { + resolve(response); + } + this.actionSocket.removeEventListener('message', messageHandler); + }; + + this.actionSocket.addEventListener('message', messageHandler); + this.actionSocket.send(JSON.stringify(requestPayload)); + }); + } + +} diff --git a/generated/typescript/yaniv/types.ts b/generated/typescript/yaniv/types.ts new file mode 100644 index 00000000..85a4daca --- /dev/null +++ b/generated/typescript/yaniv/types.ts @@ -0,0 +1,104 @@ +/** + * Autogenerated by really, really eager small hamsters. + * Shared type definitions for Deckster game clients. + */ + +export interface PlayerPutCardsNotification { + playerId: string; + cards?: Card[]; + drewCardFrom: DrawCardFrom; + type?: string; +} + +export interface Card { + rank: number; + suit: Suit; +} + +export enum Suit { + Clubs = 0, + Diamonds = 1, + Hearts = 2, + Spades = 3, +} + +export interface ItsYourTurnNotification { + type?: string; +} + +export interface RoundStartedNotification { + playerViewOfGame?: PlayerViewOfGame; + type?: string; +} + +export interface PlayerViewOfGame { + deckSize: number; + topOfPile: Card; + cardsOnHand?: Card[]; + otherPlayers?: OtherYanivPlayer[]; +} + +export interface OtherYanivPlayer { + id: string; + numberOfCards: number; + name?: string; +} + +export interface RoundEndedNotification { + winnerPlayerId: string; + playerScores?: PlayerRoundScore[]; + type?: string; +} + +export interface PlayerRoundScore { + playerId: string; + cards?: Card[]; + points: number; + penalty: number; + totalPoints: number; +} + +export interface GameEndedNotification { + winnerPlayerId: string; + playerScores?: PlayerFinalScore[]; + type?: string; +} + +export interface PlayerFinalScore { + playerId: string; + points: number; + penalty: number; + totalPoints: number; + finalPoints: number; +} + +export interface DiscardPileShuffledNotification { + stockPileSize: number; + discardPileSize: number; + type?: string; +} + +export interface CallYanivRequest { + playerId: string; + type?: string; +} + +export interface PutCardsRequest { + cards?: Card[]; + drawCardFrom: DrawCardFrom; + playerId: string; + type?: string; +} + +export interface PutCardsResponse { + drawnCard: Card; + hasError: boolean; + error?: string; + type?: string; +} + +export enum DrawCardFrom { + StockPile = 0, + DiscardPile = 1, +} + diff --git a/godot_clients/.gitignore b/godot_clients/.gitignore new file mode 100644 index 00000000..d42f8f90 --- /dev/null +++ b/godot_clients/.gitignore @@ -0,0 +1,6 @@ + +# Godot-specific +.godot/ +export_presets.cfg +*.import +*.translation \ No newline at end of file diff --git a/godot_clients/chat-sample-client/.editorconfig b/godot_clients/chat-sample-client/.editorconfig new file mode 100644 index 00000000..f28239ba --- /dev/null +++ b/godot_clients/chat-sample-client/.editorconfig @@ -0,0 +1,4 @@ +root = true + +[*] +charset = utf-8 diff --git a/godot_clients/chat-sample-client/.gitattributes b/godot_clients/chat-sample-client/.gitattributes new file mode 100644 index 00000000..8ad74f78 --- /dev/null +++ b/godot_clients/chat-sample-client/.gitattributes @@ -0,0 +1,2 @@ +# Normalize EOL for all files that Git considers text files. +* text=auto eol=lf diff --git a/godot_clients/chat-sample-client/.gitignore b/godot_clients/chat-sample-client/.gitignore new file mode 100644 index 00000000..0af181cf --- /dev/null +++ b/godot_clients/chat-sample-client/.gitignore @@ -0,0 +1,3 @@ +# Godot 4+ specific ignores +.godot/ +/android/ diff --git a/godot_clients/chat-sample-client/ChatRoomClient.gd b/godot_clients/chat-sample-client/ChatRoomClient.gd new file mode 100644 index 00000000..cc314924 --- /dev/null +++ b/godot_clients/chat-sample-client/ChatRoomClient.gd @@ -0,0 +1,111 @@ +## +## Autogenerated by really, really eager small hamsters. +## +## ChatRoom Game Client for Godot Engine +## +## Notifications (events) for this game: +## - PlayerSaid: ChatNotification +## + +class_name ChatRoomClient +extends RefCounted + +## Signals for game notifications +signal playerSaid(data: Dictionary) + +## WebSocket connections +var _action_socket: WebSocketPeer +var _notification_socket: WebSocketPeer +var _pending_requests: Dictionary = {} +var _request_id_counter: int = 0 + +## Constructor +func _init(action_socket: WebSocketPeer, notification_socket: WebSocketPeer) -> void: + _action_socket = action_socket + _notification_socket = notification_socket + +## Poll sockets for new messages. Call this regularly (e.g., in _process) +func poll() -> void: + _action_socket.poll() + _notification_socket.poll() + + # Process action socket responses + while _action_socket.get_available_packet_count() > 0: + var packet = _action_socket.get_packet() + var json_string = packet.get_string_from_utf8() + var response = JSON.parse_string(json_string) + _handle_action_response(response) + + # Process notification socket messages + while _notification_socket.get_available_packet_count() > 0: + var packet = _notification_socket.get_packet() + var json_string = packet.get_string_from_utf8() + var notification = JSON.parse_string(json_string) + _handle_notification(notification) + +## Internal: Handle responses from action socket +func _handle_action_response(response: Dictionary) -> void: + if response.has("_request_id"): + var request_id = response["_request_id"] + if _pending_requests.has(request_id): + var callback = _pending_requests[request_id] + _pending_requests.erase(request_id) + callback.call(response) + +## Internal: Handle notifications from notification socket +func _handle_notification(notification: Dictionary) -> void: + if not notification.has("type"): + push_warning("Notification missing 'type' field") + return + + var msg_type = notification["type"] + match msg_type: + "ChatRoom.ChatNotification": + playerSaid.emit(notification) + _: + push_warning("Unknown notification type: " + msg_type) + +## Internal: Send a request and wait for response +func _send_request(request_data: Dictionary) -> Dictionary: + var request_id = _request_id_counter + _request_id_counter += 1 + request_data["_request_id"] = request_id + + var response_received = false + var response_data: Dictionary = {} + + var callback = func(response: Dictionary): + response_received = true + response_data = response + + _pending_requests[request_id] = callback + + var json_string = JSON.stringify(request_data) + _action_socket.send_text(json_string) + + # Wait for response (polling) + var timeout = 30.0 # 30 seconds timeout + var elapsed = 0.0 + while not response_received and elapsed < timeout: + poll() + await Engine.get_main_loop().process_frame + elapsed += Engine.get_main_loop().root.get_process_delta_time() + + if not response_received: + _pending_requests.erase(request_id) + push_error("Request timeout") + return {"hasError": true, "error": "Request timeout"} + + return response_data + +## ============================================ +## Game Action Methods +## ============================================ + +## ChatAsync +func chatAsync(request: Dictionary) -> Dictionary: + var request_data = request.duplicate() + request_data["type"] = "ChatRoom.SendChatRequest" + return await _send_request(request_data) + +## End of generated client diff --git a/godot_clients/chat-sample-client/ChatRoomClient.gd.uid b/godot_clients/chat-sample-client/ChatRoomClient.gd.uid new file mode 100644 index 00000000..1fefebae --- /dev/null +++ b/godot_clients/chat-sample-client/ChatRoomClient.gd.uid @@ -0,0 +1 @@ +uid://dnvplhooe10a7 diff --git a/godot_clients/chat-sample-client/QUICKSTART.md b/godot_clients/chat-sample-client/QUICKSTART.md new file mode 100644 index 00000000..bd1e994b --- /dev/null +++ b/godot_clients/chat-sample-client/QUICKSTART.md @@ -0,0 +1,105 @@ +# Quick Start Guide + +## Step 1: Start the Deckster Server + +Open a terminal and run: + +```bash +cd src/Deckster.Server +dotnet run +``` + +Wait for the message: +``` +info: Microsoft.Hosting.Lifetime[14] + Now listening on: http://localhost:13992 +``` + +Note: The default port is 13992, not 5000! + +## Step 2: Run the Godot Client + +### Option A: Double-click +- Double-click `run.bat` in this folder + +### Option B: Command line +```bash +cd godot_clients/chat-sample-client +C:\godot\godot.exe --path . +``` + +### Option C: Open in Godot Editor +1. Open `C:\godot\godot.exe` +2. Click "Import" +3. Browse to this folder and select `project.godot` +4. Press F5 to run + +## Step 3: Browse Rooms and Connect + +1. The client opens with default settings: + - Server URL: `ws://localhost:13992` + - Room name: `godot-room` + +2. Connect to a room: + + **Option A: Browse and Join Existing Room** + - Click **Refresh** to see all active rooms + - Click **Join** next to any room to connect directly + - This joins the existing room (no creation attempt) + + **Option B: Create or Join Manually** + - Enter a room name to join/create + - Click **Connect** + - Creates the room if it doesn't exist + +3. Once connected, the client will: + - Authenticate with the server + - Create/join the specified game room + - Connect via WebSockets + +4. You'll see: "Connected! You can now send messages." + +5. Type a message and press Enter or click **Send** + +## Step 4: Test with Multiple Clients + +### Option A: Run another Godot client +- Run `run.bat` again in a new window +- Or run the client again from Godot +- **Important**: Join the same room (use Refresh and Join, or enter the same room name) + +### Option B: Run the .NET sample client +```bash +cd src/Deckster.ChatRoom.SampleClient +dotnet run +# When prompted, enter the same room name (e.g., "godot-room") +``` + +Now send messages from either client - they'll appear in both! + +## What You'll See + +``` +Welcome to Deckster Chat Room! +Your name: Player123 +Click 'Connect' to join the chat room +Connecting to ws://localhost:5000... +Connected! You can now send messages. +Player123: Hello from Godot! +Player456: Hello from .NET! +``` + +## Troubleshooting + +**Can't connect?** +- Make sure the server is running (`dotnet run` in `src/Deckster.Server`) +- Check that nothing else is using port 13992 +- The client will show which step failed (Authentication, Create Room, or WebSocket connection) + +**Godot won't open?** +- Verify Godot is installed at `C:\godot\godot.exe` +- Or edit `run.bat` to point to your Godot installation + +**Messages not showing?** +- Check the Godot console (F12) for errors +- Verify you clicked "Connect" first diff --git a/godot_clients/chat-sample-client/README.md b/godot_clients/chat-sample-client/README.md new file mode 100644 index 00000000..46d8b27d --- /dev/null +++ b/godot_clients/chat-sample-client/README.md @@ -0,0 +1,284 @@ +# Deckster Chat Room Sample Client (Godot) + +A sample Godot 4.5 client demonstrating how to use the auto-generated `ChatRoomClient.gd` to connect to a Deckster chat room server. + +## Prerequisites + +- Godot 4.5 (located at `C:\godot\godot.exe`) +- Deckster server running on `http://localhost:13992` (or another address) + +## Project Structure + +``` +chat-sample-client/ +├── ChatRoomClient.gd # Auto-generated client from Deckster.CodeGenerator +├── main.tscn # Main UI scene +├── main.gd # Main script that uses ChatRoomClient +├── project.godot # Godot project file +└── README.md # This file +``` + +## Running the Server + +Before running the client, start the Deckster server: + +```bash +# From the deckster repository root +cd src/Deckster.Server +dotnet run +``` + +The server should start on `http://localhost:13992` (WebSocket at `ws://localhost:13992`). + +## Running the Client + +### Option 1: Using Godot Editor + +1. Open Godot (`C:\godot\godot.exe`) +2. Click "Import" +3. Browse to this directory and select `project.godot` +4. Click "Import & Edit" +5. Press F5 to run the project + +### Option 2: Using Command Line + +```bash +cd godot_clients/chat-sample-client +C:\godot\godot.exe --path . --debug +``` + +### Option 3: Running Without Editor + +```bash +cd godot_clients/chat-sample-client +C:\godot\godot.exe --headless --path . --main-pack . +``` + +## Using the Client + +1. **Browse and Join Existing Rooms**: + - Click "Refresh" to see a list of available rooms + - Each room shows the room name and number of players + - Click "Join" next to any room to connect directly + - This joins the existing room without trying to create it + +2. **Create or Join Room Manually** (Alternative): + - The default server URL is `ws://localhost:13992` + - Change it if your server is running on a different address + - Enter a room name (default is `godot-room`) + - If the room doesn't exist, it will be created + - If it already exists, you'll join it + - Click "Connect" - this will automatically: + - Authenticate you with a random username + - Create/join the specified game room + - Connect via WebSockets + +3. **Send Messages**: + - Type your message in the input field + - Press Enter or click "Send" + - Your messages will appear in the chat log + +4. **Receive Messages**: + - Messages from other players appear in the chat log + - Your own messages are shown in light blue + - Other players' messages are shown in white + +5. **Disconnect**: + - Click "Disconnect" to close the connection + +## How It Works + +### ChatRoomClient.gd + +The `ChatRoomClient.gd` file is auto-generated from the Deckster server's API. It provides: + +**Signals (Notifications)**: +- `playerSaid(data: Dictionary)` - Emitted when any player sends a message + +**Methods (Actions)**: +- `chatAsync(request: Dictionary) -> Dictionary` - Send a message to the chat room +- `poll()` - Process incoming WebSocket messages (must be called regularly) + +### Authentication via Headers + +The client uses Godot 4's `set_handshake_headers()` method to send the Bearer token during the WebSocket handshake: + +```gdscript +var headers = PackedStringArray(["Authorization: Bearer " + auth_token]) +action_socket.set_handshake_headers(headers) +action_socket.connect_to_url(server_url + "/chatroom/join/" + game_id) +``` + +This works with the standard Deckster authentication that expects tokens in the `Authorization` header. + +### main.gd + +The main script demonstrates: + +1. **Authentication**: + ```gdscript + # POST to /login to get auth token + var response = await http.request(server_url + "/login", headers, POST, body) + auth_token = json["accessToken"] + ``` + +2. **Game Creation**: + ```gdscript + # POST to /chatroom/create/{roomname} with Bearer token + var response = await http.request(server_url + "/chatroom/create/godot-room", ...) + game_id = json["id"] + ``` + +3. **WebSocket Handshake**: + ```gdscript + # Set Authorization header for WebSocket handshake + var headers = PackedStringArray(["Authorization: Bearer " + auth_token]) + action_socket.set_handshake_headers(headers) + + # Connect to /chatroom/join/{game_id} + action_socket.connect_to_url(server_url + "/chatroom/join/" + game_id) + + # Wait for HelloSuccessMessage with connectionId + var hello = JSON.parse_string(action_socket.get_packet().get_string_from_utf8()) + connection_id = hello["connectionId"] + + # Connect notification socket with same auth header + notification_socket.set_handshake_headers(headers) + notification_socket.connect_to_url(server_url + "/chatroom/join/" + connection_id + "/finish") + + # Wait for ConnectSuccessMessage + # Now ready to use! + + client = ChatRoomClient.new(action_socket, notification_socket) + ``` + +4. **Listening for Notifications**: + ```gdscript + client.playerSaid.connect(_on_player_said) + + func _on_player_said(data: Dictionary): + var sender = data.get("sender", "Unknown") + var message = data.get("message", "") + add_to_chat("%s: %s" % [sender, message]) + ``` + +5. **Sending Messages**: + ```gdscript + var request = { + "message": message + } + var response = await client.chatAsync(request) + + if response.get("hasError", false): + print("Error: ", response.get("error")) + ``` + +6. **Polling for Messages**: + ```gdscript + func _process(_delta): + if client: + client.poll() + ``` + +7. **Browsing Available Rooms**: + ```gdscript + # Fetch rooms from the server + http.request(server_url + "/chatroom/games") + var response = await http.request_completed + var rooms = JSON.parse_string(response_body.get_string_from_utf8()) + + # Display each room with a join button + for room in rooms: + var room_name = room.get("name", "Unknown") + var player_count = room["players"].size() + add_room_to_list(room_name, player_count) + ``` + +8. **Two Connection Flows**: + + **Join Existing Room** (from room list): + ```gdscript + func join_existing_room(room_name: String): + await login(server_url) # Authenticate + game_id = room_name # Use room name directly + await connect_websockets(server_url) # Connect (no create) + initialize_client() + ``` + + **Create/Join Room** (manual entry): + ```gdscript + func connect_to_server(): + await login(server_url) # Authenticate + await create_game(server_url, room_name) # Create or join + await connect_websockets(server_url) # Connect + initialize_client() + ``` + +## Key Features Demonstrated + +- ✅ HTTP authentication with bearer tokens +- ✅ RESTful game room creation +- ✅ WebSocket handshake protocol (HelloSuccessMessage, ConnectSuccessMessage) +- ✅ WebSocket connection management (dual sockets) +- ✅ Using auto-generated client class +- ✅ Signal-based event handling +- ✅ Async/await for sending actions +- ✅ Error handling with detailed step feedback +- ✅ Connection state management +- ✅ UI integration with RichTextLabel for chat +- ✅ Room browsing and discovery (fetching active rooms from server) +- ✅ Dynamic UI updates with room lists +- ✅ Two connection flows: join existing vs create/join + +## Testing with Multiple Clients + +To test the chat functionality: + +1. Run the Deckster server +2. Launch this Godot client +3. Run another instance: + - Open another terminal and run the client again, OR + - Run a .NET sample client: `cd src/Deckster.ChatRoom.SampleClient && dotnet run` + +Messages sent from any client will be broadcast to all connected clients! + +## Troubleshooting + +**"Authentication failed"**: +- Make sure the Deckster server is running +- Check the server URL is correct (should be `ws://localhost:13992`) +- Verify the server is listening on port 13992 + +**"Failed to create game"**: +- The server might not have the ChatRoom game registered +- Check server logs for errors + +**"Connection Failed"**: +- The server might take a moment to start accepting connections +- Try clicking Connect again after a few seconds + +**Messages not appearing**: +- Ensure `client.poll()` is being called in `_process()` +- Check the console for any error messages + +## Regenerating ChatRoomClient.gd + +If the server API changes, regenerate the client: + +```bash +cd src/Deckster.CodeGenerator +dotnet run +``` + +Then copy the updated file: + +```bash +cp generated/godot/chatroom/ChatRoomClient.gd godot_clients/chat-sample-client/ +``` + +## Notes + +- Player names are randomly generated on startup +- Connection state is maintained throughout the session +- WebSocket connections are properly cleaned up on exit +- The client uses Godot's built-in `WebSocketPeer` (Godot 4.x) diff --git a/godot_clients/chat-sample-client/TESTING.md b/godot_clients/chat-sample-client/TESTING.md new file mode 100644 index 00000000..3838314b --- /dev/null +++ b/godot_clients/chat-sample-client/TESTING.md @@ -0,0 +1,139 @@ +# Testing Guide + +## Recent Fixes Applied + +### Issue 1: WebSocket Connection Error +**Problem**: WebSocket connection was failing due to missing authentication. +**Solution**: Used Godot 4's `set_handshake_headers()` method to send the `Authorization: Bearer {token}` header during the WebSocket handshake. + +### Issue 2: Room Name Selection +**Problem**: All clients joined the same hardcoded room. +**Solution**: Added a room name input field so users can specify which room to join or create. + +## How to Test + +### Step 1: Ensure the Deckster Server is Running + +Make sure the server is running: + +```bash +cd src/Deckster.Server +dotnet run +``` + +Wait for the server to start and show: +``` +info: Microsoft.Hosting.Lifetime[14] + Now listening on: http://localhost:13992 +``` + +### Step 2: Run the Godot Client + +#### Option A: Using the batch file +```bash +cd godot_clients/chat-sample-client +run.bat +``` + +#### Option B: Using Godot directly +```bash +cd godot_clients/chat-sample-client +C:\godot\godot.exe --path . +``` + +### Step 3: Test the Connection + +1. **Verify Settings**: + - Server URL: `ws://localhost:13992` (default) + - Room name: `godot-room` (default, or enter a custom room name) +2. **Click Connect**: Watch the status messages: + - `Step 1: Authenticating...` - Should succeed + - `Step 2: Joining room '...'...` - Should succeed + - `Step 3: Connecting to game...` - Should succeed +3. **Send a Message**: Type a message and press Enter +4. **Verify Receipt**: Your message should appear in the chat log + +### Step 4: Test with Multiple Clients + +#### Option A: Run another Godot instance +1. Run `run.bat` again in a new terminal window +2. **Important**: Enter the same room name in both clients to chat together +3. Click Connect in the second client + +#### Option B: Run the .NET sample client +```bash +cd src/Deckster.ChatRoom.SampleClient +dotnet run +# When prompted, enter the same room name (e.g., "godot-room") +``` + +Send messages from both clients and verify they appear in both chat windows. + +## Expected Behavior + +### Successful Connection +``` +Your name: GodotPlayer123 +Click 'Connect' to join the chat room +Step 1: Authenticating... +Authenticated as GodotPlayer123 +Step 2: Joining room 'godot-room'... +Game room created: godot-room +Step 3: Connecting to game... +Action socket connected (ID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) +Notification socket connected +Connected! You can now send messages. +Status: Connected to 'godot-room' as GodotPlayer123 +``` + +### Successful Message Exchange +``` +GodotPlayer123: Hello from Godot! +GodotPlayer456: Hello from another client! +``` + +## Troubleshooting + +### Authentication Fails +- Ensure the server is running on port 13992 +- Check server logs for errors +- Verify the server has been restarted after the authentication changes + +### Connection Timeout +- Check firewall settings +- Ensure no other process is using port 13992 +- Try restarting both server and client + +### Messages Not Appearing +- Verify `client.poll()` is being called in `_process()` +- Check the Godot console (View → Tool Windows → Output) for errors +- Ensure both sockets connected successfully + +## Technical Details + +### Authentication Flow +1. **HTTP Login** (`POST /login`) + - Sends: `{"username": "GodotPlayerXXX", "password": "godot123"}` + - Receives: `{"accessToken": "..."}` + +2. **Game Creation** (`POST /chatroom/create/godot-room`) + - Header: `Authorization: Bearer {token}` + - Receives: `{"id": "godot-room"}` + +3. **WebSocket Handshake** + - Set authentication header: + ```gdscript + var headers = PackedStringArray(["Authorization: Bearer " + auth_token]) + action_socket.set_handshake_headers(headers) + ``` + - Action Socket: `ws://localhost:13992/chatroom/join/godot-room` + - Receives: `HelloSuccessMessage` with `connectionId` + - Notification Socket: `ws://localhost:13992/chatroom/join/{connectionId}/finish` + - Receives: `ConnectSuccessMessage` + +4. **Ready to Play** + - Send actions via action socket + - Receive notifications via notification socket + +### Authentication Method +The client uses Godot 4's `set_handshake_headers()` method to send the Bearer token in the `Authorization` header during the WebSocket handshake. This works with the standard Deckster server authentication without any server-side modifications. diff --git a/godot_clients/chat-sample-client/icon.svg b/godot_clients/chat-sample-client/icon.svg new file mode 100644 index 00000000..c6bbb7d8 --- /dev/null +++ b/godot_clients/chat-sample-client/icon.svg @@ -0,0 +1 @@ + diff --git a/godot_clients/chat-sample-client/main.gd b/godot_clients/chat-sample-client/main.gd new file mode 100644 index 00000000..72850b1e --- /dev/null +++ b/godot_clients/chat-sample-client/main.gd @@ -0,0 +1,476 @@ +extends Control + +## WebSocket connections +var action_socket: WebSocketPeer +var notification_socket: WebSocketPeer + +## Chat client +var client: ChatRoomClient + +## Auth and game info +var auth_token: String = "" +var connection_id: String = "" +var player_id: String = "" +var player_name: String = "" +var game_id: String = "" +var is_connected: bool = false + +## UI References +@onready var server_input: LineEdit = $VBoxContainer/ConnectionContainer/ServerInput +@onready var room_input: LineEdit = $VBoxContainer/ConnectionContainer/RoomInput +@onready var connect_button: Button = $VBoxContainer/ConnectionContainer/ConnectButton +@onready var status_label: Label = $VBoxContainer/StatusLabel +@onready var refresh_button: Button = $VBoxContainer/RoomListContainer/RoomListHeader/RefreshButton +@onready var room_list_container: VBoxContainer = $VBoxContainer/RoomListContainer/RoomListScroll/RoomList +@onready var chat_log: RichTextLabel = $VBoxContainer/ChatLog +@onready var message_input: LineEdit = $VBoxContainer/InputContainer/MessageInput +@onready var send_button: Button = $VBoxContainer/InputContainer/SendButton + +func _ready(): + # Generate random player name + player_name = "GodotPlayer" + str(randi() % 1000) + + # Connect UI signals + connect_button.pressed.connect(_on_connect_button_pressed) + send_button.pressed.connect(_on_send_button_pressed) + message_input.text_submitted.connect(_on_message_submitted) + refresh_button.pressed.connect(_on_refresh_rooms_pressed) + + # Disable send controls initially + message_input.editable = false + send_button.disabled = true + + add_to_chat("[color=yellow]Your name: %s[/color]" % player_name) + add_to_chat("[color=gray]Click 'Connect' to join the chat room[/color]") + add_to_chat("[color=gray]Click 'Refresh' to see available rooms[/color]") + +func _process(_delta): + # Poll the client every frame to process messages + if client and is_connected: + client.poll() + + # Check WebSocket states + if action_socket: + action_socket.poll() + var state = action_socket.get_ready_state() + if state == WebSocketPeer.STATE_CLOSED: + _handle_disconnection() + + if notification_socket: + notification_socket.poll() + +func _on_connect_button_pressed(): + if is_connected: + disconnect_from_server() + else: + connect_to_server() + +func connect_to_server(): + var server_url = server_input.text + if server_url.is_empty(): + add_to_chat("[color=red]Error: Please enter a server URL[/color]") + return + + var room_name = room_input.text.strip_edges() + if room_name.is_empty(): + add_to_chat("[color=red]Error: Please enter a room name[/color]") + return + + add_to_chat("[color=cyan]Step 1: Authenticating...[/color]") + status_label.text = "Status: Authenticating..." + connect_button.disabled = true + + # Step 1: Login to get auth token + if not await login(server_url): + connect_button.disabled = false + return + + add_to_chat("[color=cyan]Step 2: Creating/Joining room '%s'...[/color]" % room_name) + status_label.text = "Status: Creating/Joining room..." + + # Step 2: Create a game room (or join if it exists) + if not await create_game(server_url, room_name): + connect_button.disabled = false + return + + add_to_chat("[color=cyan]Step 3: Connecting to game...[/color]") + status_label.text = "Status: Connecting..." + + # Step 3: Connect to the game via WebSocket + if not await connect_websockets(server_url): + connect_button.disabled = false + return + + # Success! + initialize_client() + +func login(server_url: String) -> bool: + # Convert ws:// to http:// + var http_url = server_url.replace("ws://", "http://").replace("wss://", "https://") + + var http = HTTPRequest.new() + add_child(http) + + var body = JSON.stringify({ + "username": player_name, + "password": "godot123" + }) + + var headers = ["Content-Type: application/json"] + http.request(http_url + "/login", headers, HTTPClient.METHOD_POST, body) + + var response = await http.request_completed + http.queue_free() + + var result = response[0] + var response_code = response[1] + var response_body = response[3] + + if result != HTTPRequest.RESULT_SUCCESS or response_code != 200: + add_to_chat("[color=red]Authentication failed: %d[/color]" % response_code) + status_label.text = "Status: Auth Failed" + return false + + var json = JSON.parse_string(response_body.get_string_from_utf8()) + if json == null or not json.has("accessToken"): + add_to_chat("[color=red]Invalid auth response[/color]") + status_label.text = "Status: Auth Failed" + return false + + auth_token = json["accessToken"] + add_to_chat("[color=green]Authenticated as %s[/color]" % player_name) + return true + +func create_game(server_url: String, room_name: String) -> bool: + var http_url = server_url.replace("ws://", "http://").replace("wss://", "https://") + + var http = HTTPRequest.new() + add_child(http) + + var headers = [ + "Content-Type: application/json", + "Authorization: Bearer " + auth_token + ] + + http.request(http_url + "/chatroom/create/" + room_name, headers, HTTPClient.METHOD_POST, "") + + var response = await http.request_completed + http.queue_free() + + var result = response[0] + var response_code = response[1] + var response_body = response[3] + + if result != HTTPRequest.RESULT_SUCCESS or response_code != 200: + add_to_chat("[color=red]Failed to create game: %d[/color]" % response_code) + add_to_chat("[color=gray]%s[/color]" % response_body.get_string_from_utf8()) + status_label.text = "Status: Create Failed" + return false + + var json = JSON.parse_string(response_body.get_string_from_utf8()) + if json == null or not json.has("id"): + add_to_chat("[color=red]Invalid create game response[/color]") + status_label.text = "Status: Create Failed" + return false + + game_id = json["id"] + add_to_chat("[color=green]Game room created: %s[/color]" % game_id) + return true + +func connect_websockets(server_url: String) -> bool: + # Step 3a: Connect action socket + action_socket = WebSocketPeer.new() + + # Set the Authorization header for the WebSocket handshake + var headers = PackedStringArray(["Authorization: Bearer " + auth_token]) + action_socket.set_handshake_headers(headers) + + var action_url = server_url + "/chatroom/join/" + game_id + print("DEBUG: Connecting to WebSocket URL: ", action_url) + print("DEBUG: Using game_id: ", game_id) + var err = action_socket.connect_to_url(action_url) + + if err != OK: + add_to_chat("[color=red]Failed to connect action socket: %d[/color]" % err) + status_label.text = "Status: Connection Failed" + return false + + # Wait for connection + for i in range(50): # 5 second timeout + action_socket.poll() + if action_socket.get_ready_state() == WebSocketPeer.STATE_OPEN: + break + await get_tree().create_timer(0.1).timeout + + if action_socket.get_ready_state() != WebSocketPeer.STATE_OPEN: + add_to_chat("[color=red]Action socket failed to connect[/color]") + status_label.text = "Status: Connection Failed" + return false + + # Wait for HelloSuccessMessage + for i in range(50): + action_socket.poll() + if action_socket.get_available_packet_count() > 0: + break + await get_tree().create_timer(0.1).timeout + + if action_socket.get_available_packet_count() == 0: + add_to_chat("[color=red]No hello message received[/color]") + status_label.text = "Status: Handshake Failed" + return false + + var packet = action_socket.get_packet() + var hello_json = JSON.parse_string(packet.get_string_from_utf8()) + + if hello_json == null or not hello_json.has("connectionId"): + add_to_chat("[color=red]Invalid hello message[/color]") + status_label.text = "Status: Handshake Failed" + return false + + connection_id = hello_json["connectionId"] + if hello_json.has("player"): + player_id = hello_json["player"].get("id", "") + + add_to_chat("[color=green]Action socket connected (ID: %s)[/color]" % connection_id) + + # Step 3b: Connect notification socket + notification_socket = WebSocketPeer.new() + + # Set the Authorization header for the notification socket as well + notification_socket.set_handshake_headers(headers) + + var notification_url = server_url + "/chatroom/join/" + connection_id + "/finish" + err = notification_socket.connect_to_url(notification_url) + + if err != OK: + add_to_chat("[color=red]Failed to connect notification socket: %d[/color]" % err) + status_label.text = "Status: Connection Failed" + return false + + # Wait for connection + for i in range(50): + notification_socket.poll() + if notification_socket.get_ready_state() == WebSocketPeer.STATE_OPEN: + break + await get_tree().create_timer(0.1).timeout + + if notification_socket.get_ready_state() != WebSocketPeer.STATE_OPEN: + add_to_chat("[color=red]Notification socket failed to connect[/color]") + status_label.text = "Status: Connection Failed" + return false + + # Wait for ConnectSuccessMessage + for i in range(50): + notification_socket.poll() + if notification_socket.get_available_packet_count() > 0: + break + await get_tree().create_timer(0.1).timeout + + if notification_socket.get_available_packet_count() > 0: + var _finish_packet = notification_socket.get_packet() + # Just consume the finish message + + add_to_chat("[color=green]Notification socket connected[/color]") + return true + +func initialize_client(): + # Create the chat client + client = ChatRoomClient.new(action_socket, notification_socket) + + # Connect to game notification signals + client.playerSaid.connect(_on_player_said) + + is_connected = true + status_label.text = "Status: Connected to '%s' as %s" % [game_id, player_name] + connect_button.text = "Disconnect" + connect_button.disabled = false + server_input.editable = false + room_input.editable = false + + # Enable send controls + message_input.editable = true + send_button.disabled = false + message_input.grab_focus() + + add_to_chat("[color=green]Connected! You can now send messages.[/color]") + +func disconnect_from_server(): + if action_socket: + action_socket.close() + if notification_socket: + notification_socket.close() + + _handle_disconnection() + +func _handle_disconnection(): + is_connected = false + status_label.text = "Status: Disconnected" + connect_button.text = "Connect" + connect_button.disabled = false + server_input.editable = true + room_input.editable = true + + # Disable send controls + message_input.editable = false + send_button.disabled = true + + add_to_chat("[color=yellow]Disconnected from server[/color]") + +## ==================================================== +## Signal Handlers (Game Notifications) +## ==================================================== + +func _on_player_said(data: Dictionary): + var sender = data.get("sender", "Unknown") + var message = data.get("message", "") + + # Color our own messages differently + if sender == player_name: + add_to_chat("[color=lightblue][b]%s:[/b] %s[/color]" % [sender, message]) + else: + add_to_chat("[b]%s:[/b] %s" % [sender, message]) + +## ==================================================== +## Game Action Methods +## ==================================================== + +func send_message(message: String): + if not is_connected or not client: + add_to_chat("[color=red]Error: Not connected to server[/color]") + return + + if message.is_empty(): + return + + var request = { + "message": message + } + + # All action methods are async and return a response + var response = await client.chatAsync(request) + + # Check for errors + if response.get("hasError", false): + var error = response.get("error", "Unknown error") + add_to_chat("[color=red]Failed to send message: %s[/color]" % error) + # Note: We don't need to add our message to chat here because + # the server will broadcast it back to us via the playerSaid notification + +## ==================================================== +## UI Event Handlers +## ==================================================== + +func _on_send_button_pressed(): + var message = message_input.text.strip_edges() + if message.is_empty(): + return + + send_message(message) + message_input.clear() + +func _on_message_submitted(text: String): + _on_send_button_pressed() + +## ==================================================== +## Helper Methods +## ==================================================== + +func add_to_chat(text: String): + chat_log.append_text(text + "\n") + # Auto-scroll is enabled in the scene + +## ==================================================== +## Room List Methods +## ==================================================== + +func _on_refresh_rooms_pressed(): + refresh_rooms() + +func refresh_rooms(): + var server_url = server_input.text + if server_url.is_empty(): + add_to_chat("[color=red]Error: Please enter a server URL first[/color]") + return + + var http_url = server_url.replace("ws://", "http://").replace("wss://", "https://") + + var http = HTTPRequest.new() + add_child(http) + + # Fetch the list of chat rooms + http.request(http_url + "/chatroom/games") + + var response = await http.request_completed + http.queue_free() + + var result = response[0] + var response_code = response[1] + var response_body = response[3] + + if result != HTTPRequest.RESULT_SUCCESS or response_code != 200: + add_to_chat("[color=red]Failed to fetch rooms: %d[/color]" % response_code) + return + + var json = JSON.parse_string(response_body.get_string_from_utf8()) + if json == null: + add_to_chat("[color=red]Invalid response from server[/color]") + return + + # Clear existing room list + for child in room_list_container.get_children(): + child.queue_free() + + # Add rooms to the list + if json is Array and json.size() > 0: + for room in json: + print("DEBUG: Room data: ", JSON.stringify(room)) + # Try both camelCase and PascalCase + var room_name = room.get("name", room.get("Name", "Unknown")) + var player_count = 0 + var players = room.get("players", room.get("Players", [])) + if players is Array: + player_count = players.size() + + print("DEBUG: Extracted room_name: ", room_name, ", player_count: ", player_count) + add_room_to_list(room_name, player_count) + + add_to_chat("[color=cyan]Found %d room(s)[/color]" % json.size()) + else: + var no_rooms_label = Label.new() + no_rooms_label.text = "No rooms available" + no_rooms_label.add_theme_color_override("font_color", Color(0.6, 0.6, 0.6)) + room_list_container.add_child(no_rooms_label) + add_to_chat("[color=gray]No rooms found[/color]") + +func add_room_to_list(room_name: String, player_count: int): + var room_item = HBoxContainer.new() + + var room_label = Label.new() + room_label.text = "%s (%d player%s)" % [room_name, player_count, "s" if player_count != 1 else ""] + room_label.size_flags_horizontal = Control.SIZE_EXPAND_FILL + room_item.add_child(room_label) + + var join_button = Button.new() + join_button.text = "Join" + join_button.pressed.connect(_on_join_room_pressed.bind(room_name)) + room_item.add_child(join_button) + + room_list_container.add_child(room_item) + +func _on_join_room_pressed(room_name: String): + if is_connected: + add_to_chat("[color=yellow]Already connected. Disconnect first to join another room.[/color]") + return + + # Fill the room name and use the normal connect flow + # This will attempt to create/join the room + room_input.text = room_name + add_to_chat("[color=cyan]Joining room: %s[/color]" % room_name) + connect_to_server() + +## ==================================================== +## Cleanup +## ==================================================== + +func _exit_tree(): + disconnect_from_server() diff --git a/godot_clients/chat-sample-client/main.gd.uid b/godot_clients/chat-sample-client/main.gd.uid new file mode 100644 index 00000000..3b9106a4 --- /dev/null +++ b/godot_clients/chat-sample-client/main.gd.uid @@ -0,0 +1 @@ +uid://bucwnm6rme4mu diff --git a/godot_clients/chat-sample-client/main.tscn b/godot_clients/chat-sample-client/main.tscn new file mode 100644 index 00000000..27a8b3e6 --- /dev/null +++ b/godot_clients/chat-sample-client/main.tscn @@ -0,0 +1,114 @@ +[gd_scene load_steps=2 format=3 uid="uid://b3wyhyakr8f7c"] + +[ext_resource type="Script" path="res://main.gd" id="1_3vkqp"] + +[node name="Main" type="Control"] +layout_mode = 3 +anchors_preset = 15 +anchor_right = 1.0 +anchor_bottom = 1.0 +grow_horizontal = 2 +grow_vertical = 2 +script = ExtResource("1_3vkqp") + +[node name="VBoxContainer" type="VBoxContainer" parent="."] +layout_mode = 1 +anchors_preset = 15 +anchor_right = 1.0 +anchor_bottom = 1.0 +offset_left = 20.0 +offset_top = 20.0 +offset_right = -20.0 +offset_bottom = -20.0 +grow_horizontal = 2 +grow_vertical = 2 + +[node name="TitleLabel" type="Label" parent="VBoxContainer"] +layout_mode = 2 +theme_override_font_sizes/font_size = 24 +text = "Deckster Chat Room Client" +horizontal_alignment = 1 + +[node name="HSeparator" type="HSeparator" parent="VBoxContainer"] +layout_mode = 2 + +[node name="ConnectionContainer" type="HBoxContainer" parent="VBoxContainer"] +layout_mode = 2 + +[node name="ServerLabel" type="Label" parent="VBoxContainer/ConnectionContainer"] +layout_mode = 2 +text = "Server:" + +[node name="ServerInput" type="LineEdit" parent="VBoxContainer/ConnectionContainer"] +custom_minimum_size = Vector2(200, 0) +layout_mode = 2 +text = "ws://localhost:13992" +placeholder_text = "ws://localhost:13992" + +[node name="RoomLabel" type="Label" parent="VBoxContainer/ConnectionContainer"] +layout_mode = 2 +text = "Room:" + +[node name="RoomInput" type="LineEdit" parent="VBoxContainer/ConnectionContainer"] +custom_minimum_size = Vector2(150, 0) +layout_mode = 2 +text = "godot-room" +placeholder_text = "room name" + +[node name="ConnectButton" type="Button" parent="VBoxContainer/ConnectionContainer"] +layout_mode = 2 +text = "Connect" + +[node name="StatusLabel" type="Label" parent="VBoxContainer"] +layout_mode = 2 +text = "Status: Disconnected" + +[node name="HSeparator2" type="HSeparator" parent="VBoxContainer"] +layout_mode = 2 + +[node name="RoomListContainer" type="VBoxContainer" parent="VBoxContainer"] +layout_mode = 2 + +[node name="RoomListHeader" type="HBoxContainer" parent="VBoxContainer/RoomListContainer"] +layout_mode = 2 + +[node name="RoomListLabel" type="Label" parent="VBoxContainer/RoomListContainer/RoomListHeader"] +layout_mode = 2 +text = "Available Rooms:" + +[node name="RefreshButton" type="Button" parent="VBoxContainer/RoomListContainer/RoomListHeader"] +layout_mode = 2 +text = "Refresh" + +[node name="RoomListScroll" type="ScrollContainer" parent="VBoxContainer/RoomListContainer"] +custom_minimum_size = Vector2(0, 100) +layout_mode = 2 + +[node name="RoomList" type="VBoxContainer" parent="VBoxContainer/RoomListContainer/RoomListScroll"] +layout_mode = 2 +size_flags_horizontal = 3 + +[node name="HSeparator3" type="HSeparator" parent="VBoxContainer"] +layout_mode = 2 + +[node name="ChatLog" type="RichTextLabel" parent="VBoxContainer"] +layout_mode = 2 +size_flags_vertical = 3 +bbcode_enabled = true +text = "[color=gray]Welcome to Deckster Chat Room![/color]" +scroll_following = true + +[node name="HSeparator4" type="HSeparator" parent="VBoxContainer"] +layout_mode = 2 + +[node name="InputContainer" type="HBoxContainer" parent="VBoxContainer"] +layout_mode = 2 + +[node name="MessageInput" type="LineEdit" parent="VBoxContainer/InputContainer"] +layout_mode = 2 +size_flags_horizontal = 3 +placeholder_text = "Type your message here..." + +[node name="SendButton" type="Button" parent="VBoxContainer/InputContainer"] +layout_mode = 2 +text = "Send" diff --git a/godot_clients/chat-sample-client/project.godot b/godot_clients/chat-sample-client/project.godot new file mode 100644 index 00000000..edfa1e38 --- /dev/null +++ b/godot_clients/chat-sample-client/project.godot @@ -0,0 +1,16 @@ +; Engine configuration file. +; It's best edited using the editor UI and not directly, +; since the parameters that go here are not all obvious. +; +; Format: +; [section] ; section goes between [] +; param=value ; assign values to parameters + +config_version=5 + +[application] + +config/name="ChatSampleClient" +run/main_scene="res://main.tscn" +config/features=PackedStringArray("4.5", "Forward Plus") +config/icon="res://icon.svg" diff --git a/godot_clients/chat-sample-client/run.bat b/godot_clients/chat-sample-client/run.bat new file mode 100644 index 00000000..597d1f6f --- /dev/null +++ b/godot_clients/chat-sample-client/run.bat @@ -0,0 +1,3 @@ +@echo off +echo Starting Deckster Chat Room Client... +C:\godot\godot.exe --path . %* diff --git a/hearts.sh b/hearts.sh new file mode 100644 index 00000000..74fb7629 --- /dev/null +++ b/hearts.sh @@ -0,0 +1,3 @@ +#!/bin/bash +cd src/Deckster.Hearts.SampleClient +dotnet run diff --git a/hearts_game_instructions.txt b/hearts_game_instructions.txt new file mode 100644 index 00000000..13862036 --- /dev/null +++ b/hearts_game_instructions.txt @@ -0,0 +1,82 @@ +Of course 👍 +Here’s the English version of the same instructions — written clearly and precisely so another AI or engine can use it to recreate the classic Windows Hearts card game logic: + +🧭 Summary for AI Instructions: + +Create a digital card game that follows the rules of Microsoft Hearts (Windows 95–XP version). + +Basic Rules + +4 players (1 human + 3 computer opponents) + +Standard 52-card deck, 13 cards dealt to each player + +Goal: finish with the lowest total score + +Game ends when any player reaches 100 points — lowest total wins + +Passing Cards + +Round 1: pass 3 cards to the left + +Round 2: pass 3 cards to the right + +Round 3: pass 3 cards across (opposite player) + +Round 4: no passing + +Then repeat this 4-round cycle + +Gameplay + +Player holding ♣2 (Two of Clubs) starts the first trick + +Players must follow suit if possible + +If unable to follow suit: + +They may play any other card + +But hearts (♥) cannot be played until hearts are “broken” + +Breaking Hearts + +Hearts are “broken” the first time any heart is played because a player couldn’t follow suit + +After that, hearts can be played at any time + +Scoring + +Each heart (♥) = 1 point + +Queen of Spades (♠Q) = 13 points + +Total possible points per hand: 26 + +Shooting the Moon + +If a player captures all 13 hearts + the Queen of Spades, then: + +All other players receive +26 points (default Windows rule) + +(Optional alternative rule: the shooter gets −26 points) + +Trick Resolution + +Highest card of the lead suit wins the trick + +Trick winner leads the next round + +Round End + +After 13 tricks, total up points for each player + +Continue with the next round (apply the next pass direction) + +Game End + +When a player’s total score ≥ 100, the game ends + +The player with the lowest total score wins + +Would you like me to make a technical spec version next — something formatted like a design document or pseudocode outline for implementing the logic? \ No newline at end of file diff --git a/src/Deckster.Client/Games/Bullshit/BullshitClient.g.cs b/src/Deckster.Client/Games/Bullshit/BullshitClient.g.cs index 39f7bebe..755db2b3 100644 --- a/src/Deckster.Client/Games/Bullshit/BullshitClient.g.cs +++ b/src/Deckster.Client/Games/Bullshit/BullshitClient.g.cs @@ -109,7 +109,7 @@ public static class BullshitClientConveniences /// public static Task PutCardAsync(this BullshitClient self, Card actualCard, Card claimedToBeCard, CancellationToken cancellationToken = default) { - var request = new PutCardRequest{ ActualCard = actualCard, ClaimedToBeCard = claimedToBeCard }; + var request = new PutCardRequest{ PlayerId = self.PlayerData.Id, ActualCard = actualCard, ClaimedToBeCard = claimedToBeCard }; return self.SendAsync(request, false, cancellationToken); } /// @@ -117,7 +117,7 @@ public static Task PutCardAsync(this BullshitClient self, Card ac /// public static async Task PutCardOrThrowAsync(this BullshitClient self, Card actualCard, Card claimedToBeCard, CancellationToken cancellationToken = default) { - var request = new PutCardRequest{ ActualCard = actualCard, ClaimedToBeCard = claimedToBeCard }; + var request = new PutCardRequest{ PlayerId = self.PlayerData.Id, ActualCard = actualCard, ClaimedToBeCard = claimedToBeCard }; var response = await self.SendAsync(request, true, cancellationToken); } /// @@ -125,7 +125,7 @@ public static async Task PutCardOrThrowAsync(this BullshitClient self, Card actu /// public static Task DrawCardAsync(this BullshitClient self, CancellationToken cancellationToken = default) { - var request = new DrawCardRequest{ }; + var request = new DrawCardRequest{ PlayerId = self.PlayerData.Id }; return self.SendAsync(request, false, cancellationToken); } /// @@ -133,7 +133,7 @@ public static Task DrawCardAsync(this BullshitClient self, Cancell /// public static async Task DrawCardOrThrowAsync(this BullshitClient self, CancellationToken cancellationToken = default) { - var request = new DrawCardRequest{ }; + var request = new DrawCardRequest{ PlayerId = self.PlayerData.Id }; var response = await self.SendAsync(request, true, cancellationToken); return response.Card; } @@ -142,7 +142,7 @@ public static async Task DrawCardOrThrowAsync(this BullshitClient self, Ca /// public static Task PassAsync(this BullshitClient self, CancellationToken cancellationToken = default) { - var request = new PassRequest{ }; + var request = new PassRequest{ PlayerId = self.PlayerData.Id }; return self.SendAsync(request, false, cancellationToken); } /// @@ -150,7 +150,7 @@ public static Task PassAsync(this BullshitClient self, Cancellati /// public static async Task PassOrThrowAsync(this BullshitClient self, CancellationToken cancellationToken = default) { - var request = new PassRequest{ }; + var request = new PassRequest{ PlayerId = self.PlayerData.Id }; var response = await self.SendAsync(request, true, cancellationToken); } /// @@ -158,7 +158,7 @@ public static async Task PassOrThrowAsync(this BullshitClient self, Cancellation /// public static Task CallBullshitAsync(this BullshitClient self, CancellationToken cancellationToken = default) { - var request = new BullshitRequest{ }; + var request = new BullshitRequest{ PlayerId = self.PlayerData.Id }; return self.SendAsync(request, false, cancellationToken); } /// @@ -166,7 +166,7 @@ public static Task CallBullshitAsync(this BullshitClient self, /// public static async Task CallBullshitOrThrowAsync(this BullshitClient self, CancellationToken cancellationToken = default) { - var request = new BullshitRequest{ }; + var request = new BullshitRequest{ PlayerId = self.PlayerData.Id }; var response = await self.SendAsync(request, true, cancellationToken); return response.PunishmentCards; } diff --git a/src/Deckster.Client/Games/ChatRoom/ChatRoomClient.g.cs b/src/Deckster.Client/Games/ChatRoom/ChatRoomClient.g.cs index 7eb3be91..a5f89e92 100644 --- a/src/Deckster.Client/Games/ChatRoom/ChatRoomClient.g.cs +++ b/src/Deckster.Client/Games/ChatRoom/ChatRoomClient.g.cs @@ -51,7 +51,7 @@ public static class ChatRoomClientConveniences /// public static Task ChatAsync(this ChatRoomClient self, string message, CancellationToken cancellationToken = default) { - var request = new SendChatRequest{ Message = message }; + var request = new SendChatRequest{ PlayerId = self.PlayerData.Id, Message = message }; return self.SendAsync(request, false, cancellationToken); } /// @@ -59,7 +59,7 @@ public static Task ChatAsync(this ChatRoomClient self, string mess /// public static async Task ChatOrThrowAsync(this ChatRoomClient self, string message, CancellationToken cancellationToken = default) { - var request = new SendChatRequest{ Message = message }; + var request = new SendChatRequest{ PlayerId = self.PlayerData.Id, Message = message }; var response = await self.SendAsync(request, true, cancellationToken); } } diff --git a/src/Deckster.Client/Games/CrazyEights/CrazyEightsClient.g.cs b/src/Deckster.Client/Games/CrazyEights/CrazyEightsClient.g.cs index 359f4b3e..736d0906 100644 --- a/src/Deckster.Client/Games/CrazyEights/CrazyEightsClient.g.cs +++ b/src/Deckster.Client/Games/CrazyEights/CrazyEightsClient.g.cs @@ -101,7 +101,7 @@ public static class CrazyEightsClientConveniences /// public static Task PutCardAsync(this CrazyEightsClient self, Card card, CancellationToken cancellationToken = default) { - var request = new PutCardRequest{ Card = card }; + var request = new PutCardRequest{ PlayerId = self.PlayerData.Id, Card = card }; return self.SendAsync(request, false, cancellationToken); } /// @@ -109,7 +109,7 @@ public static Task PutCardAsync(this CrazyEightsClient self, C /// public static async Task<(List cards, Card topOfPile, Suit currentSuit, int stockPileCount, int discardPileCount, List otherPlayers)> PutCardOrThrowAsync(this CrazyEightsClient self, Card card, CancellationToken cancellationToken = default) { - var request = new PutCardRequest{ Card = card }; + var request = new PutCardRequest{ PlayerId = self.PlayerData.Id, Card = card }; var response = await self.SendAsync(request, true, cancellationToken); return (response.Cards, response.TopOfPile, response.CurrentSuit, response.StockPileCount, response.DiscardPileCount, response.OtherPlayers); } @@ -118,7 +118,7 @@ public static Task PutCardAsync(this CrazyEightsClient self, C /// public static Task PutEightAsync(this CrazyEightsClient self, Card card, Suit newSuit, CancellationToken cancellationToken = default) { - var request = new PutEightRequest{ Card = card, NewSuit = newSuit }; + var request = new PutEightRequest{ PlayerId = self.PlayerData.Id, Card = card, NewSuit = newSuit }; return self.SendAsync(request, false, cancellationToken); } /// @@ -126,7 +126,7 @@ public static Task PutEightAsync(this CrazyEightsClient self, /// public static async Task<(List cards, Card topOfPile, Suit currentSuit, int stockPileCount, int discardPileCount, List otherPlayers)> PutEightOrThrowAsync(this CrazyEightsClient self, Card card, Suit newSuit, CancellationToken cancellationToken = default) { - var request = new PutEightRequest{ Card = card, NewSuit = newSuit }; + var request = new PutEightRequest{ PlayerId = self.PlayerData.Id, Card = card, NewSuit = newSuit }; var response = await self.SendAsync(request, true, cancellationToken); return (response.Cards, response.TopOfPile, response.CurrentSuit, response.StockPileCount, response.DiscardPileCount, response.OtherPlayers); } @@ -135,7 +135,7 @@ public static Task PutEightAsync(this CrazyEightsClient self, /// public static Task DrawCardAsync(this CrazyEightsClient self, CancellationToken cancellationToken = default) { - var request = new DrawCardRequest{ }; + var request = new DrawCardRequest{ PlayerId = self.PlayerData.Id }; return self.SendAsync(request, false, cancellationToken); } /// @@ -143,7 +143,7 @@ public static Task DrawCardAsync(this CrazyEightsClient self, Canc /// public static async Task DrawCardOrThrowAsync(this CrazyEightsClient self, CancellationToken cancellationToken = default) { - var request = new DrawCardRequest{ }; + var request = new DrawCardRequest{ PlayerId = self.PlayerData.Id }; var response = await self.SendAsync(request, true, cancellationToken); return response.Card; } @@ -152,7 +152,7 @@ public static async Task DrawCardOrThrowAsync(this CrazyEightsClient self, /// public static Task PassAsync(this CrazyEightsClient self, CancellationToken cancellationToken = default) { - var request = new PassRequest{ }; + var request = new PassRequest{ PlayerId = self.PlayerData.Id }; return self.SendAsync(request, false, cancellationToken); } /// @@ -160,7 +160,7 @@ public static Task PassAsync(this CrazyEightsClient self, Cancell /// public static async Task PassOrThrowAsync(this CrazyEightsClient self, CancellationToken cancellationToken = default) { - var request = new PassRequest{ }; + var request = new PassRequest{ PlayerId = self.PlayerData.Id }; var response = await self.SendAsync(request, true, cancellationToken); } } diff --git a/src/Deckster.Client/Games/Gabong/GabongClient.g.cs b/src/Deckster.Client/Games/Gabong/GabongClient.g.cs index 17100bca..bf634e2b 100644 --- a/src/Deckster.Client/Games/Gabong/GabongClient.g.cs +++ b/src/Deckster.Client/Games/Gabong/GabongClient.g.cs @@ -99,7 +99,7 @@ public static class GabongClientConveniences /// public static Task DrawCardAsync(this GabongClient self, CancellationToken cancellationToken = default) { - var request = new DrawCardRequest{ }; + var request = new DrawCardRequest{ PlayerId = self.PlayerData.Id }; return self.SendAsync(request, false, cancellationToken); } /// @@ -107,7 +107,7 @@ public static Task DrawCardAsync(this GabongClient self, Cance /// public static async Task<(List cards, Card topOfPile, Suit currentSuit, int stockPileCount, int discardPileCount, bool roundStarted, Guid lastPlayMadeByPlayerId, GabongPlay lastPlay, List players, List playersOrder, int cardDebtToDraw, List cardsAdded)> DrawCardOrThrowAsync(this GabongClient self, CancellationToken cancellationToken = default) { - var request = new DrawCardRequest{ }; + var request = new DrawCardRequest{ PlayerId = self.PlayerData.Id }; var response = await self.SendAsync(request, true, cancellationToken); return (response.Cards, response.TopOfPile, response.CurrentSuit, response.StockPileCount, response.DiscardPileCount, response.RoundStarted, response.LastPlayMadeByPlayerId, response.LastPlay, response.Players, response.PlayersOrder, response.CardDebtToDraw, response.CardsAdded); } @@ -116,7 +116,7 @@ public static Task DrawCardAsync(this GabongClient self, Cance /// public static Task PlayGabongAsync(this GabongClient self, CancellationToken cancellationToken = default) { - var request = new PlayGabongRequest{ }; + var request = new PlayGabongRequest{ PlayerId = self.PlayerData.Id }; return self.SendAsync(request, false, cancellationToken); } /// @@ -124,7 +124,7 @@ public static Task PlayGabongAsync(this GabongClient self, Can /// public static async Task<(List cards, Card topOfPile, Suit currentSuit, int stockPileCount, int discardPileCount, bool roundStarted, Guid lastPlayMadeByPlayerId, GabongPlay lastPlay, List players, List playersOrder, int cardDebtToDraw, List cardsAdded)> PlayGabongOrThrowAsync(this GabongClient self, CancellationToken cancellationToken = default) { - var request = new PlayGabongRequest{ }; + var request = new PlayGabongRequest{ PlayerId = self.PlayerData.Id }; var response = await self.SendAsync(request, true, cancellationToken); return (response.Cards, response.TopOfPile, response.CurrentSuit, response.StockPileCount, response.DiscardPileCount, response.RoundStarted, response.LastPlayMadeByPlayerId, response.LastPlay, response.Players, response.PlayersOrder, response.CardDebtToDraw, response.CardsAdded); } @@ -133,7 +133,7 @@ public static Task PlayGabongAsync(this GabongClient self, Can /// public static Task PlayBongaAsync(this GabongClient self, CancellationToken cancellationToken = default) { - var request = new PlayBongaRequest{ }; + var request = new PlayBongaRequest{ PlayerId = self.PlayerData.Id }; return self.SendAsync(request, false, cancellationToken); } /// @@ -141,7 +141,7 @@ public static Task PlayBongaAsync(this GabongClient self, Canc /// public static async Task<(List cards, Card topOfPile, Suit currentSuit, int stockPileCount, int discardPileCount, bool roundStarted, Guid lastPlayMadeByPlayerId, GabongPlay lastPlay, List players, List playersOrder, int cardDebtToDraw, List cardsAdded)> PlayBongaOrThrowAsync(this GabongClient self, CancellationToken cancellationToken = default) { - var request = new PlayBongaRequest{ }; + var request = new PlayBongaRequest{ PlayerId = self.PlayerData.Id }; var response = await self.SendAsync(request, true, cancellationToken); return (response.Cards, response.TopOfPile, response.CurrentSuit, response.StockPileCount, response.DiscardPileCount, response.RoundStarted, response.LastPlayMadeByPlayerId, response.LastPlay, response.Players, response.PlayersOrder, response.CardDebtToDraw, response.CardsAdded); } @@ -150,7 +150,7 @@ public static Task PlayBongaAsync(this GabongClient self, Canc /// public static Task PassAsync(this GabongClient self, CancellationToken cancellationToken = default) { - var request = new PassRequest{ }; + var request = new PassRequest{ PlayerId = self.PlayerData.Id }; return self.SendAsync(request, false, cancellationToken); } /// @@ -158,7 +158,7 @@ public static Task PassAsync(this GabongClient self, Cancellat /// public static async Task<(List cards, Card topOfPile, Suit currentSuit, int stockPileCount, int discardPileCount, bool roundStarted, Guid lastPlayMadeByPlayerId, GabongPlay lastPlay, List players, List playersOrder, int cardDebtToDraw, List cardsAdded)> PassOrThrowAsync(this GabongClient self, CancellationToken cancellationToken = default) { - var request = new PassRequest{ }; + var request = new PassRequest{ PlayerId = self.PlayerData.Id }; var response = await self.SendAsync(request, true, cancellationToken); return (response.Cards, response.TopOfPile, response.CurrentSuit, response.StockPileCount, response.DiscardPileCount, response.RoundStarted, response.LastPlayMadeByPlayerId, response.LastPlay, response.Players, response.PlayersOrder, response.CardDebtToDraw, response.CardsAdded); } @@ -167,7 +167,7 @@ public static Task PassAsync(this GabongClient self, Cancellat /// public static Task PutCardAsync(this GabongClient self, Card card, Nullable newSuit, CancellationToken cancellationToken = default) { - var request = new PutCardRequest{ Card = card, NewSuit = newSuit }; + var request = new PutCardRequest{ PlayerId = self.PlayerData.Id, Card = card, NewSuit = newSuit }; return self.SendAsync(request, false, cancellationToken); } /// @@ -175,7 +175,7 @@ public static Task PutCardAsync(this GabongClient self, Card c /// public static async Task<(List cards, Card topOfPile, Suit currentSuit, int stockPileCount, int discardPileCount, bool roundStarted, Guid lastPlayMadeByPlayerId, GabongPlay lastPlay, List players, List playersOrder, int cardDebtToDraw, List cardsAdded)> PutCardOrThrowAsync(this GabongClient self, Card card, Nullable newSuit, CancellationToken cancellationToken = default) { - var request = new PutCardRequest{ Card = card, NewSuit = newSuit }; + var request = new PutCardRequest{ PlayerId = self.PlayerData.Id, Card = card, NewSuit = newSuit }; var response = await self.SendAsync(request, true, cancellationToken); return (response.Cards, response.TopOfPile, response.CurrentSuit, response.StockPileCount, response.DiscardPileCount, response.RoundStarted, response.LastPlayMadeByPlayerId, response.LastPlay, response.Players, response.PlayersOrder, response.CardDebtToDraw, response.CardsAdded); } diff --git a/src/Deckster.Client/Games/Hearts/HeartsClient.g.cs b/src/Deckster.Client/Games/Hearts/HeartsClient.g.cs new file mode 100644 index 00000000..61ea14c8 --- /dev/null +++ b/src/Deckster.Client/Games/Hearts/HeartsClient.g.cs @@ -0,0 +1,136 @@ +#nullable enable + +using Deckster.Core.Games.Hearts; +using System.Collections.Generic; +using Deckster.Core.Games.Common; +using System.Diagnostics; +using Deckster.Core.Communication; +using Deckster.Core.Protocol; +using Deckster.Core.Extensions; + +namespace Deckster.Client.Games.Hearts; + +/** + * Autogenerated by really, really eager small hamsters. +*/ + +[DebuggerDisplay("HeartsClient {PlayerData}")] +public class HeartsClient(IClientChannel channel) : GameClient(channel) +{ + public event Action? GameStarted; + public event Action? PassingPhaseStarted; + public event Action? AllPlayersPassed; + public event Action? PlayerPassedCards; + public event Action? ItsYourTurn; + public event Action? ItsPlayersTurn; + public event Action? PlayerPlayedCard; + public event Action? TrickCompleted; + public event Action? RoundEnded; + public event Action? GameEnded; + public event Action? HeartsWereBroken; + + public Task PassCardsAsync(PassCardsRequest request, CancellationToken cancellationToken = default) + { + return SendAsync(request, false, cancellationToken); + } + + public Task PlayCardAsync(PlayCardRequest request, CancellationToken cancellationToken = default) + { + return SendAsync(request, false, cancellationToken); + } + + protected override void OnNotification(DecksterNotification notification) + { + try + { + switch (notification) + { + case GameStartedNotification m: + GameStarted?.Invoke(m); + return; + case PassingPhaseStartedNotification m: + PassingPhaseStarted?.Invoke(m); + return; + case AllPlayersPassedNotification m: + AllPlayersPassed?.Invoke(m); + return; + case PlayerPassedCardsNotification m: + PlayerPassedCards?.Invoke(m); + return; + case ItsYourTurnNotification m: + ItsYourTurn?.Invoke(m); + return; + case ItsPlayersTurnNotification m: + ItsPlayersTurn?.Invoke(m); + return; + case PlayerPlayedCardNotification m: + PlayerPlayedCard?.Invoke(m); + return; + case TrickCompletedNotification m: + TrickCompleted?.Invoke(m); + return; + case RoundEndedNotification m: + RoundEnded?.Invoke(m); + return; + case GameEndedNotification m: + GameEnded?.Invoke(m); + return; + case HeartsAreBrokenNotification m: + HeartsWereBroken?.Invoke(m); + return; + default: + return; + } + } + catch (Exception e) + { + Console.WriteLine(e); + } + } +} + +public static class HeartsClientConveniences +{ + /// + /// does not throw exception on error + /// + public static Task PassCardsAsync(this HeartsClient self, List cards, CancellationToken cancellationToken = default) + { + var request = new PassCardsRequest{ PlayerId = self.PlayerData.Id, Cards = cards }; + return self.SendAsync(request, false, cancellationToken); + } + /// + /// throws exception on error + /// + public static async Task> PassCardsOrThrowAsync(this HeartsClient self, List cards, CancellationToken cancellationToken = default) + { + var request = new PassCardsRequest{ PlayerId = self.PlayerData.Id, Cards = cards }; + var response = await self.SendAsync(request, true, cancellationToken); + return response.ReceivedCards; + } + /// + /// does not throw exception on error + /// + public static Task PlayCardAsync(this HeartsClient self, Card card, CancellationToken cancellationToken = default) + { + var request = new PlayCardRequest{ PlayerId = self.PlayerData.Id, Card = card }; + return self.SendAsync(request, false, cancellationToken); + } + /// + /// throws exception on error + /// + public static async Task<(List cards, List otherPlayers, int roundNumber, PassDirection passDirection, bool hasPassed, List currentTrick, int totalScore, int roundScore, bool heartsAreBroken, bool isMyTurn)> PlayCardOrThrowAsync(this HeartsClient self, Card card, CancellationToken cancellationToken = default) + { + var request = new PlayCardRequest{ PlayerId = self.PlayerData.Id, Card = card }; + var response = await self.SendAsync(request, true, cancellationToken); + return (response.Cards, response.OtherPlayers, response.RoundNumber, response.PassDirection, response.HasPassed, response.CurrentTrick, response.TotalScore, response.RoundScore, response.HeartsAreBroken, response.IsMyTurn); + } +} + +public static class HeartsClientDecksterClientExtensions +{ + public static GameApi Hearts(this DecksterClient client) + { + return new GameApi(client.BaseUri.Append("hearts"), client.Token, c => new HeartsClient(c)); + } +} diff --git a/src/Deckster.Client/Games/Idiot/IdiotClient.g.cs b/src/Deckster.Client/Games/Idiot/IdiotClient.g.cs index c533e0d2..dcbfa40a 100644 --- a/src/Deckster.Client/Games/Idiot/IdiotClient.g.cs +++ b/src/Deckster.Client/Games/Idiot/IdiotClient.g.cs @@ -125,7 +125,7 @@ public static class IdiotClientConveniences /// public static Task IamReadyAsync(this IdiotClient self, CancellationToken cancellationToken = default) { - var request = new IamReadyRequest{ }; + var request = new IamReadyRequest{ PlayerId = self.PlayerData.Id }; return self.SendAsync(request, false, cancellationToken); } /// @@ -133,7 +133,7 @@ public static Task IamReadyAsync(this IdiotClient self, Cancellat /// public static async Task IamReadyOrThrowAsync(this IdiotClient self, CancellationToken cancellationToken = default) { - var request = new IamReadyRequest{ }; + var request = new IamReadyRequest{ PlayerId = self.PlayerData.Id }; var response = await self.SendAsync(request, true, cancellationToken); } /// @@ -141,7 +141,7 @@ public static async Task IamReadyOrThrowAsync(this IdiotClient self, Cancellatio /// public static Task SwapCardsAsync(this IdiotClient self, Card cardOnHand, Card cardFacingUp, CancellationToken cancellationToken = default) { - var request = new SwapCardsRequest{ CardOnHand = cardOnHand, CardFacingUp = cardFacingUp }; + var request = new SwapCardsRequest{ PlayerId = self.PlayerData.Id, CardOnHand = cardOnHand, CardFacingUp = cardFacingUp }; return self.SendAsync(request, false, cancellationToken); } /// @@ -149,7 +149,7 @@ public static Task SwapCardsAsync(this IdiotClient self, Card /// public static async Task<(Card cardNowOnHand, Card cardNowFacingUp)> SwapCardsOrThrowAsync(this IdiotClient self, Card cardOnHand, Card cardFacingUp, CancellationToken cancellationToken = default) { - var request = new SwapCardsRequest{ CardOnHand = cardOnHand, CardFacingUp = cardFacingUp }; + var request = new SwapCardsRequest{ PlayerId = self.PlayerData.Id, CardOnHand = cardOnHand, CardFacingUp = cardFacingUp }; var response = await self.SendAsync(request, true, cancellationToken); return (response.CardNowOnHand, response.CardNowFacingUp); } @@ -158,7 +158,7 @@ public static Task SwapCardsAsync(this IdiotClient self, Card /// public static Task PutCardsFromHandAsync(this IdiotClient self, Card[] cards, CancellationToken cancellationToken = default) { - var request = new PutCardsFromHandRequest{ Cards = cards }; + var request = new PutCardsFromHandRequest{ PlayerId = self.PlayerData.Id, Cards = cards }; return self.SendAsync(request, false, cancellationToken); } /// @@ -166,7 +166,7 @@ public static Task PutCardsFromHandAsync(this IdiotClient sel /// public static async Task PutCardsFromHandOrThrowAsync(this IdiotClient self, Card[] cards, CancellationToken cancellationToken = default) { - var request = new PutCardsFromHandRequest{ Cards = cards }; + var request = new PutCardsFromHandRequest{ PlayerId = self.PlayerData.Id, Cards = cards }; var response = await self.SendAsync(request, true, cancellationToken); return response.Cards; } @@ -175,7 +175,7 @@ public static async Task PutCardsFromHandOrThrowAsync(this IdiotClient s /// public static Task PutCardsFacingUpAsync(this IdiotClient self, Card[] cards, CancellationToken cancellationToken = default) { - var request = new PutCardsFacingUpRequest{ Cards = cards }; + var request = new PutCardsFacingUpRequest{ PlayerId = self.PlayerData.Id, Cards = cards }; return self.SendAsync(request, false, cancellationToken); } /// @@ -183,7 +183,7 @@ public static Task PutCardsFacingUpAsync(this IdiotClient self, C /// public static async Task PutCardsFacingUpOrThrowAsync(this IdiotClient self, Card[] cards, CancellationToken cancellationToken = default) { - var request = new PutCardsFacingUpRequest{ Cards = cards }; + var request = new PutCardsFacingUpRequest{ PlayerId = self.PlayerData.Id, Cards = cards }; var response = await self.SendAsync(request, true, cancellationToken); } /// @@ -191,7 +191,7 @@ public static async Task PutCardsFacingUpOrThrowAsync(this IdiotClient self, Car /// public static Task PutCardFacingDownAsync(this IdiotClient self, int index, CancellationToken cancellationToken = default) { - var request = new PutCardFacingDownRequest{ Index = index }; + var request = new PutCardFacingDownRequest{ PlayerId = self.PlayerData.Id, Index = index }; return self.SendAsync(request, false, cancellationToken); } /// @@ -199,7 +199,7 @@ public static Task PutCardFacingDownAsync(this IdiotClient /// public static async Task<(Card attemptedCard, Card[] pullInCards)> PutCardFacingDownOrThrowAsync(this IdiotClient self, int index, CancellationToken cancellationToken = default) { - var request = new PutCardFacingDownRequest{ Index = index }; + var request = new PutCardFacingDownRequest{ PlayerId = self.PlayerData.Id, Index = index }; var response = await self.SendAsync(request, true, cancellationToken); return (response.AttemptedCard, response.PullInCards); } @@ -208,7 +208,7 @@ public static Task PutCardFacingDownAsync(this IdiotClient /// public static Task PutChanceCardAsync(this IdiotClient self, CancellationToken cancellationToken = default) { - var request = new PutChanceCardRequest{ }; + var request = new PutChanceCardRequest{ PlayerId = self.PlayerData.Id }; return self.SendAsync(request, false, cancellationToken); } /// @@ -216,7 +216,7 @@ public static Task PutChanceCardAsync(this IdiotClient sel /// public static async Task<(Card attemptedCard, Card[] pullInCards)> PutChanceCardOrThrowAsync(this IdiotClient self, CancellationToken cancellationToken = default) { - var request = new PutChanceCardRequest{ }; + var request = new PutChanceCardRequest{ PlayerId = self.PlayerData.Id }; var response = await self.SendAsync(request, true, cancellationToken); return (response.AttemptedCard, response.PullInCards); } @@ -225,7 +225,7 @@ public static Task PutChanceCardAsync(this IdiotClient sel /// public static Task PullInDiscardPileAsync(this IdiotClient self, CancellationToken cancellationToken = default) { - var request = new PullInDiscardPileRequest{ }; + var request = new PullInDiscardPileRequest{ PlayerId = self.PlayerData.Id }; return self.SendAsync(request, false, cancellationToken); } /// @@ -233,7 +233,7 @@ public static Task PullInDiscardPileAsync(this IdiotClient self, /// public static async Task PullInDiscardPileOrThrowAsync(this IdiotClient self, CancellationToken cancellationToken = default) { - var request = new PullInDiscardPileRequest{ }; + var request = new PullInDiscardPileRequest{ PlayerId = self.PlayerData.Id }; var response = await self.SendAsync(request, true, cancellationToken); return response.Cards; } diff --git a/src/Deckster.Client/Games/TexasHoldEm/TexasHoldEmClient.g.cs b/src/Deckster.Client/Games/TexasHoldEm/TexasHoldEmClient.g.cs index 619c4fd0..56cebb58 100644 --- a/src/Deckster.Client/Games/TexasHoldEm/TexasHoldEmClient.g.cs +++ b/src/Deckster.Client/Games/TexasHoldEm/TexasHoldEmClient.g.cs @@ -106,7 +106,7 @@ public static class TexasHoldEmClientConveniences /// public static Task PlayerBetRequestAsync(this TexasHoldEmClient self, int bet, CancellationToken cancellationToken = default) { - var request = new BetRequest{ Bet = bet }; + var request = new BetRequest{ PlayerId = self.PlayerData.Id, Bet = bet }; return self.SendAsync(request, false, cancellationToken); } /// @@ -114,7 +114,7 @@ public static Task PlayerBetRequestAsync(this TexasHoldEmClien /// public static async Task<(List cards, List cardsOnTable, int stackSize, int currentBet, int potSize, int bigBlind, int numberOfRoundsUntilBigBlindIncreases, List otherPlayers, Guid nextRoundStartingPlayerId)> PlayerBetRequestOrThrowAsync(this TexasHoldEmClient self, int bet, CancellationToken cancellationToken = default) { - var request = new BetRequest{ Bet = bet }; + var request = new BetRequest{ PlayerId = self.PlayerData.Id, Bet = bet }; var response = await self.SendAsync(request, true, cancellationToken); return (response.Cards, response.CardsOnTable, response.StackSize, response.CurrentBet, response.PotSize, response.BigBlind, response.NumberOfRoundsUntilBigBlindIncreases, response.OtherPlayers, response.NextRoundStartingPlayerId); } @@ -123,7 +123,7 @@ public static Task PlayerBetRequestAsync(this TexasHoldEmClien /// public static Task PlayerFoldRequestAsync(this TexasHoldEmClient self, CancellationToken cancellationToken = default) { - var request = new FoldRequest{ }; + var request = new FoldRequest{ PlayerId = self.PlayerData.Id }; return self.SendAsync(request, false, cancellationToken); } /// @@ -131,7 +131,7 @@ public static Task PlayerFoldRequestAsync(this TexasHoldEmClie /// public static async Task<(List cards, List cardsOnTable, int stackSize, int currentBet, int potSize, int bigBlind, int numberOfRoundsUntilBigBlindIncreases, List otherPlayers, Guid nextRoundStartingPlayerId)> PlayerFoldRequestOrThrowAsync(this TexasHoldEmClient self, CancellationToken cancellationToken = default) { - var request = new FoldRequest{ }; + var request = new FoldRequest{ PlayerId = self.PlayerData.Id }; var response = await self.SendAsync(request, true, cancellationToken); return (response.Cards, response.CardsOnTable, response.StackSize, response.CurrentBet, response.PotSize, response.BigBlind, response.NumberOfRoundsUntilBigBlindIncreases, response.OtherPlayers, response.NextRoundStartingPlayerId); } @@ -140,7 +140,7 @@ public static Task PlayerFoldRequestAsync(this TexasHoldEmClie /// public static Task PlayerCheckRequestAsync(this TexasHoldEmClient self, CancellationToken cancellationToken = default) { - var request = new CheckRequest{ }; + var request = new CheckRequest{ PlayerId = self.PlayerData.Id }; return self.SendAsync(request, false, cancellationToken); } /// @@ -148,7 +148,7 @@ public static Task PlayerCheckRequestAsync(this TexasHoldEmCli /// public static async Task<(List cards, List cardsOnTable, int stackSize, int currentBet, int potSize, int bigBlind, int numberOfRoundsUntilBigBlindIncreases, List otherPlayers, Guid nextRoundStartingPlayerId)> PlayerCheckRequestOrThrowAsync(this TexasHoldEmClient self, CancellationToken cancellationToken = default) { - var request = new CheckRequest{ }; + var request = new CheckRequest{ PlayerId = self.PlayerData.Id }; var response = await self.SendAsync(request, true, cancellationToken); return (response.Cards, response.CardsOnTable, response.StackSize, response.CurrentBet, response.PotSize, response.BigBlind, response.NumberOfRoundsUntilBigBlindIncreases, response.OtherPlayers, response.NextRoundStartingPlayerId); } @@ -157,7 +157,7 @@ public static Task PlayerCheckRequestAsync(this TexasHoldEmCli /// public static Task PlayerCallRequestAsync(this TexasHoldEmClient self, CancellationToken cancellationToken = default) { - var request = new CallRequest{ }; + var request = new CallRequest{ PlayerId = self.PlayerData.Id }; return self.SendAsync(request, false, cancellationToken); } /// @@ -165,7 +165,7 @@ public static Task PlayerCallRequestAsync(this TexasHoldEmClie /// public static async Task<(List cards, List cardsOnTable, int stackSize, int currentBet, int potSize, int bigBlind, int numberOfRoundsUntilBigBlindIncreases, List otherPlayers, Guid nextRoundStartingPlayerId)> PlayerCallRequestOrThrowAsync(this TexasHoldEmClient self, CancellationToken cancellationToken = default) { - var request = new CallRequest{ }; + var request = new CallRequest{ PlayerId = self.PlayerData.Id }; var response = await self.SendAsync(request, true, cancellationToken); return (response.Cards, response.CardsOnTable, response.StackSize, response.CurrentBet, response.PotSize, response.BigBlind, response.NumberOfRoundsUntilBigBlindIncreases, response.OtherPlayers, response.NextRoundStartingPlayerId); } diff --git a/src/Deckster.Client/Games/Uno/UnoClient.g.cs b/src/Deckster.Client/Games/Uno/UnoClient.g.cs index f7351dc7..609a756b 100644 --- a/src/Deckster.Client/Games/Uno/UnoClient.g.cs +++ b/src/Deckster.Client/Games/Uno/UnoClient.g.cs @@ -23,8 +23,6 @@ public class UnoClient(IClientChannel channel) : GameClient(channel) public event Action? PlayerPassed; public event Action? GameEnded; public event Action? ItsYourTurn; - public event Action? RoundStarted; - public event Action? RoundEnded; public Task PutCardAsync(PutCardRequest request, CancellationToken cancellationToken = default) { @@ -73,12 +71,6 @@ protected override void OnNotification(DecksterNotification notification) case ItsYourTurnNotification m: ItsYourTurn?.Invoke(m); return; - case RoundStartedNotification m: - RoundStarted?.Invoke(m); - return; - case RoundEndedNotification m: - RoundEnded?.Invoke(m); - return; default: return; } @@ -97,7 +89,7 @@ public static class UnoClientConveniences /// public static Task PutCardAsync(this UnoClient self, UnoCard card, CancellationToken cancellationToken = default) { - var request = new PutCardRequest{ Card = card }; + var request = new PutCardRequest{ PlayerId = self.PlayerData.Id, Card = card }; return self.SendAsync(request, false, cancellationToken); } /// @@ -105,7 +97,7 @@ public static Task PutCardAsync(this UnoClient self, UnoCard c /// public static async Task<(List cards, UnoCard topOfPile, UnoColor currentColor, int stockPileCount, int discardPileCount, List otherPlayers)> PutCardOrThrowAsync(this UnoClient self, UnoCard card, CancellationToken cancellationToken = default) { - var request = new PutCardRequest{ Card = card }; + var request = new PutCardRequest{ PlayerId = self.PlayerData.Id, Card = card }; var response = await self.SendAsync(request, true, cancellationToken); return (response.Cards, response.TopOfPile, response.CurrentColor, response.StockPileCount, response.DiscardPileCount, response.OtherPlayers); } @@ -114,7 +106,7 @@ public static Task PutCardAsync(this UnoClient self, UnoCard c /// public static Task PutWildAsync(this UnoClient self, UnoCard card, UnoColor newColor, CancellationToken cancellationToken = default) { - var request = new PutWildRequest{ Card = card, NewColor = newColor }; + var request = new PutWildRequest{ PlayerId = self.PlayerData.Id, Card = card, NewColor = newColor }; return self.SendAsync(request, false, cancellationToken); } /// @@ -122,7 +114,7 @@ public static Task PutWildAsync(this UnoClient self, UnoCard c /// public static async Task<(List cards, UnoCard topOfPile, UnoColor currentColor, int stockPileCount, int discardPileCount, List otherPlayers)> PutWildOrThrowAsync(this UnoClient self, UnoCard card, UnoColor newColor, CancellationToken cancellationToken = default) { - var request = new PutWildRequest{ Card = card, NewColor = newColor }; + var request = new PutWildRequest{ PlayerId = self.PlayerData.Id, Card = card, NewColor = newColor }; var response = await self.SendAsync(request, true, cancellationToken); return (response.Cards, response.TopOfPile, response.CurrentColor, response.StockPileCount, response.DiscardPileCount, response.OtherPlayers); } @@ -131,7 +123,7 @@ public static Task PutWildAsync(this UnoClient self, UnoCard c /// public static Task DrawCardAsync(this UnoClient self, CancellationToken cancellationToken = default) { - var request = new DrawCardRequest{ }; + var request = new DrawCardRequest{ PlayerId = self.PlayerData.Id }; return self.SendAsync(request, false, cancellationToken); } /// @@ -139,7 +131,7 @@ public static Task DrawCardAsync(this UnoClient self, Cancellat /// public static async Task DrawCardOrThrowAsync(this UnoClient self, CancellationToken cancellationToken = default) { - var request = new DrawCardRequest{ }; + var request = new DrawCardRequest{ PlayerId = self.PlayerData.Id }; var response = await self.SendAsync(request, true, cancellationToken); return response.Card; } @@ -148,7 +140,7 @@ public static async Task DrawCardOrThrowAsync(this UnoClient self, Canc /// public static Task PassAsync(this UnoClient self, CancellationToken cancellationToken = default) { - var request = new PassRequest{ }; + var request = new PassRequest{ PlayerId = self.PlayerData.Id }; return self.SendAsync(request, false, cancellationToken); } /// @@ -156,7 +148,7 @@ public static Task PassAsync(this UnoClient self, CancellationTok /// public static async Task PassOrThrowAsync(this UnoClient self, CancellationToken cancellationToken = default) { - var request = new PassRequest{ }; + var request = new PassRequest{ PlayerId = self.PlayerData.Id }; var response = await self.SendAsync(request, true, cancellationToken); } } diff --git a/src/Deckster.Client/Games/Yaniv/YanivClient.g.cs b/src/Deckster.Client/Games/Yaniv/YanivClient.g.cs index b4060725..c940d574 100644 --- a/src/Deckster.Client/Games/Yaniv/YanivClient.g.cs +++ b/src/Deckster.Client/Games/Yaniv/YanivClient.g.cs @@ -75,7 +75,7 @@ public static class YanivClientConveniences /// public static Task CallYanivAsync(this YanivClient self, CancellationToken cancellationToken = default) { - var request = new CallYanivRequest{ }; + var request = new CallYanivRequest{ PlayerId = self.PlayerData.Id }; return self.SendAsync(request, false, cancellationToken); } /// @@ -83,7 +83,7 @@ public static Task CallYanivAsync(this YanivClient self, Cancella /// public static async Task CallYanivOrThrowAsync(this YanivClient self, CancellationToken cancellationToken = default) { - var request = new CallYanivRequest{ }; + var request = new CallYanivRequest{ PlayerId = self.PlayerData.Id }; var response = await self.SendAsync(request, true, cancellationToken); } /// @@ -91,7 +91,7 @@ public static async Task CallYanivOrThrowAsync(this YanivClient self, Cancellati /// public static Task PutCardsAsync(this YanivClient self, Card[] cards, DrawCardFrom drawCardFrom, CancellationToken cancellationToken = default) { - var request = new PutCardsRequest{ Cards = cards, DrawCardFrom = drawCardFrom }; + var request = new PutCardsRequest{ PlayerId = self.PlayerData.Id, Cards = cards, DrawCardFrom = drawCardFrom }; return self.SendAsync(request, false, cancellationToken); } /// @@ -99,7 +99,7 @@ public static Task PutCardsAsync(this YanivClient self, Card[] /// public static async Task PutCardsOrThrowAsync(this YanivClient self, Card[] cards, DrawCardFrom drawCardFrom, CancellationToken cancellationToken = default) { - var request = new PutCardsRequest{ Cards = cards, DrawCardFrom = drawCardFrom }; + var request = new PutCardsRequest{ PlayerId = self.PlayerData.Id, Cards = cards, DrawCardFrom = drawCardFrom }; var response = await self.SendAsync(request, true, cancellationToken); return response.DrawnCard; } diff --git a/src/Deckster.CodeGenerator/Generators/CsharpClientGenerator.cs b/src/Deckster.CodeGenerator/Generators/CsharpClientGenerator.cs index d41e1944..b7fc5d2e 100644 --- a/src/Deckster.CodeGenerator/Generators/CsharpClientGenerator.cs +++ b/src/Deckster.CodeGenerator/Generators/CsharpClientGenerator.cs @@ -118,7 +118,7 @@ public CsharpClientGenerator(CSharpGameMeta meta, string ns) Source.AppendLine($"public static Task<{extension.ReturnType.ToDisplayString()}> {extension.Name}Async(this {ClientName} self, {parameters})"); using(Source.CodeBlock()) { - var properties = extension.Parameters.Select(p => $"{p.Name.ToPascalCase()} = {p.Name}").StringJoined(", "); + var properties = extension.Parameters.Select(p => $"{p.Name.ToPascalCase()} = {p.Name}").Prepend("PlayerId = self.PlayerData.Id").StringJoined(", "); Source.AppendLine($"var request = new {extension.Method.Request.ParameterType.ToDisplayString()}{{ {properties} }};"); Source.AppendLine($"return self.SendAsync<{extension.ReturnType.ToDisplayString()}>(request, false, cancellationToken);"); } @@ -141,7 +141,7 @@ public CsharpClientGenerator(CSharpGameMeta meta, string ns) "/// throws exception on error", "/// ", ]); - Source.AppendLine($"public static async Task<{extension.ReturnParameters[0].ParameterType.Name}> {extension.Name}OrThrowAsync(this {ClientName} self, {parameters})"); + Source.AppendLine($"public static async Task<{extension.ReturnParameters[0].ParameterType.ToDisplayString()}> {extension.Name}OrThrowAsync(this {ClientName} self, {parameters})"); break; default: var returnTuple = extension.ReturnParameters.Select(p => $"{p.ParameterType.ToDisplayString()} {p.Name}").StringJoined(", "); @@ -156,7 +156,7 @@ public CsharpClientGenerator(CSharpGameMeta meta, string ns) using (Source.CodeBlock()) { - var properties = extension.Parameters.Select(p => $"{p.Name.ToPascalCase()} = {p.Name}").StringJoined(", "); + var properties = extension.Parameters.Select(p => $"{p.Name.ToPascalCase()} = {p.Name}").Prepend("PlayerId = self.PlayerData.Id").StringJoined(", "); Source.AppendLine($"var request = new {extension.Method.Request.ParameterType.ToDisplayString()}{{ {properties} }};"); Source.AppendLine($"var response = await self.SendAsync<{extension.Method.ResponseType.ToDisplayString()}>(request, true, cancellationToken);"); diff --git a/src/Deckster.CodeGenerator/Generators/GodotClientGenerator.cs b/src/Deckster.CodeGenerator/Generators/GodotClientGenerator.cs new file mode 100644 index 00000000..46793dc9 --- /dev/null +++ b/src/Deckster.CodeGenerator/Generators/GodotClientGenerator.cs @@ -0,0 +1,250 @@ +using Deckster.Core.Extensions; +using Deckster.Games.CodeGeneration.Meta; + +namespace Deckster.CodeGenerator.Generators; + +public class GodotClientGenerator : ClientGenerator +{ + public GodotClientGenerator(GameMeta meta, string className) + { + Source + .AppendLine("##") + .AppendLine("## Autogenerated by really, really eager small hamsters.") + .AppendLine("##") + .AppendLine($"## {meta.Name} Game Client for Godot Engine") + .AppendLine("##") + .AppendLine("## Notifications (events) for this game:") + .AppendLines(meta.Notifications.Select(n => $"## - {n.Name}: {n.Message.Name}")) + .AppendLine("##") + .AppendLine() + .AppendLine($"class_name {className}") + .AppendLine("extends RefCounted") + .AppendLine(); + + // Signals (events) for notifications + if (meta.Notifications.Any()) + { + Source.AppendLine("## Signals for game notifications"); + foreach (var notification in meta.Notifications) + { + Source.AppendLine($"signal {notification.Name.ToCamelCase()}(data: Dictionary)"); + } + Source.AppendLine(); + } + + // Member variables + Source + .AppendLine("## WebSocket connections") + .AppendLine("var _action_socket: WebSocketPeer") + .AppendLine("var _notification_socket: WebSocketPeer") + .AppendLine("var _pending_requests: Dictionary = {}") + .AppendLine("var _request_id_counter: int = 0") + .AppendLine(); + + // Constructor + Source.AppendLine("## Constructor"); + Source.AppendLine("func _init(action_socket: WebSocketPeer, notification_socket: WebSocketPeer) -> void:"); + using (Source.Indent()) + { + Source + .AppendLine("_action_socket = action_socket") + .AppendLine("_notification_socket = notification_socket"); + } + Source.AppendLine(); + + // Poll method (should be called regularly) + Source.AppendLine("## Poll sockets for new messages. Call this regularly (e.g., in _process)"); + Source.AppendLine("func poll() -> void:"); + using (Source.Indent()) + { + Source + .AppendLine("_action_socket.poll()") + .AppendLine("_notification_socket.poll()") + .AppendLine() + .AppendLine("# Process action socket responses") + .AppendLine("while _action_socket.get_available_packet_count() > 0:"); + using (Source.Indent()) + { + Source + .AppendLine("var packet = _action_socket.get_packet()") + .AppendLine("var json_string = packet.get_string_from_utf8()") + .AppendLine("var response = JSON.parse_string(json_string)") + .AppendLine("_handle_action_response(response)"); + } + Source.AppendLine() + .AppendLine("# Process notification socket messages") + .AppendLine("while _notification_socket.get_available_packet_count() > 0:"); + using (Source.Indent()) + { + Source + .AppendLine("var packet = _notification_socket.get_packet()") + .AppendLine("var json_string = packet.get_string_from_utf8()") + .AppendLine("var notification = JSON.parse_string(json_string)") + .AppendLine("_handle_notification(notification)"); + } + } + Source.AppendLine(); + + // Handle action response + Source.AppendLine("## Internal: Handle responses from action socket"); + Source.AppendLine("func _handle_action_response(response: Dictionary) -> void:"); + using (Source.Indent()) + { + Source.AppendLine("if response.has(\"_request_id\"):"); + using (Source.Indent()) + { + Source + .AppendLine("var request_id = response[\"_request_id\"]") + .AppendLine("if _pending_requests.has(request_id):"); + using (Source.Indent()) + { + Source + .AppendLine("var callback = _pending_requests[request_id]") + .AppendLine("_pending_requests.erase(request_id)") + .AppendLine("callback.call(response)"); + } + } + } + Source.AppendLine(); + + // Handle notification + Source.AppendLine("## Internal: Handle notifications from notification socket"); + Source.AppendLine("func _handle_notification(notification: Dictionary) -> void:"); + using (Source.Indent()) + { + Source.AppendLine("if not notification.has(\"type\"):"); + using (Source.Indent()) + { + Source.AppendLine("push_warning(\"Notification missing 'type' field\")"); + Source.AppendLine("return"); + } + Source.AppendLine(); + Source.AppendLine("var msg_type = notification[\"type\"]"); + Source.AppendLine("match msg_type:"); + using (Source.Indent()) + { + foreach (var notification in meta.Notifications) + { + Source.AppendLine($"\"{notification.Message.Type}\":"); + using (Source.Indent()) + { + Source.AppendLine($"{notification.Name.ToCamelCase()}.emit(notification)"); + } + } + Source.AppendLine("_:"); + using (Source.Indent()) + { + Source.AppendLine("push_warning(\"Unknown notification type: \" + msg_type)"); + } + } + } + Source.AppendLine(); + + // Send request helper + Source.AppendLine("## Internal: Send a request and wait for response"); + Source.AppendLine("func _send_request(request_data: Dictionary) -> Dictionary:"); + using (Source.Indent()) + { + Source + .AppendLine("var request_id = _request_id_counter") + .AppendLine("_request_id_counter += 1") + .AppendLine("request_data[\"_request_id\"] = request_id") + .AppendLine() + .AppendLine("var response_received = false") + .AppendLine("var response_data: Dictionary = {}") + .AppendLine() + .AppendLine("var callback = func(response: Dictionary):"); + using (Source.Indent()) + { + Source + .AppendLine("response_received = true") + .AppendLine("response_data = response"); + } + Source + .AppendLine() + .AppendLine("_pending_requests[request_id] = callback") + .AppendLine() + .AppendLine("var json_string = JSON.stringify(request_data)") + .AppendLine("_action_socket.send_text(json_string)") + .AppendLine() + .AppendLine("# Wait for response (polling)") + .AppendLine("var timeout = 30.0 # 30 seconds timeout") + .AppendLine("var elapsed = 0.0") + .AppendLine("while not response_received and elapsed < timeout:"); + using (Source.Indent()) + { + Source + .AppendLine("poll()") + .AppendLine("await Engine.get_main_loop().process_frame") + .AppendLine("elapsed += Engine.get_main_loop().root.get_process_delta_time()"); + } + Source + .AppendLine() + .AppendLine("if not response_received:"); + using (Source.Indent()) + { + Source + .AppendLine("_pending_requests.erase(request_id)") + .AppendLine("push_error(\"Request timeout\")") + .AppendLine("return {\"hasError\": true, \"error\": \"Request timeout\"}"); + } + Source + .AppendLine() + .AppendLine("return response_data"); + } + Source.AppendLine(); + + // Game methods + if (meta.Methods.Any()) + { + Source.AppendLine("## ============================================"); + Source.AppendLine("## Game Action Methods"); + Source.AppendLine("## ============================================"); + Source.AppendLine(); + + foreach (var method in meta.Methods) + { + var parameters = string.Join(", ", method.Parameters.Select(p => $"{p.Name}: Dictionary")); + var methodName = method.Name.ToCamelCase(); + + Source.AppendLine($"## {method.Name}"); + Source.AppendLine($"func {methodName}({parameters}) -> Dictionary:"); + using (Source.Indent()) + { + // Build request payload + if (method.Parameters.Count() == 1) + { + var param = method.Parameters.First(); + Source + .AppendLine($"var request_data = {param.Name}.duplicate()") + .AppendLine($"request_data[\"type\"] = \"{param.Type.Type}\""); + } + else if (method.Parameters.Any()) + { + Source.AppendLine("var request_data = {"); + using (Source.Indent()) + { + foreach (var param in method.Parameters) + { + Source.AppendLine($"\"{param.Name}\": {param.Name},"); + } + Source.AppendLine("\"type\": \"Unknown\""); + } + Source.AppendLine("}"); + } + else + { + Source.AppendLine("var request_data = {\"type\": \"Unknown\"}"); + } + + Source + .AppendLine("return await _send_request(request_data)"); + } + Source.AppendLine(); + } + } + + // Close class (implicit in GDScript, just add comment) + Source.AppendLine("## End of generated client"); + } +} diff --git a/src/Deckster.CodeGenerator/Generators/TypeScriptClientGenerator.cs b/src/Deckster.CodeGenerator/Generators/TypeScriptClientGenerator.cs new file mode 100644 index 00000000..e830df7f --- /dev/null +++ b/src/Deckster.CodeGenerator/Generators/TypeScriptClientGenerator.cs @@ -0,0 +1,289 @@ +using Deckster.Core.Extensions; +using Deckster.Games.CodeGeneration.Meta; + +namespace Deckster.CodeGenerator.Generators; + +public class TypeScriptClientGenerator : ClientGenerator +{ + public HashSet SharedTypeNames { get; } = new(); + public HashSet GameSpecificTypeNames { get; } = new(); + + public TypeScriptClientGenerator(GameMeta meta, string moduleName, HashSet gameSpecificTypeNames) + { + Source + .AppendLine("/**") + .AppendLine(" * Autogenerated by really, really eager small hamsters.") + .AppendLine(" *") + .AppendLine($" * {meta.Name} Game Client") + .AppendLine(" *") + .AppendLine(" * Notifications (events) for this game:") + .AppendLines(meta.Notifications.Select(n => $" * - {n.Name}: {n.Message}")) + .AppendLine(" */") + .AppendLine(); + + // Collect and categorize type names for import + var allTypeNames = new HashSet(); + + foreach (var method in meta.Methods) + { + foreach (var param in method.Parameters) + { + allTypeNames.Add(param.Type.Name); + } + if (method.ReturnType.Name != "void") + { + allTypeNames.Add(method.ReturnType.Name); + } + } + + foreach (var notification in meta.Notifications) + { + allTypeNames.Add(notification.Message.Name); + } + + // Separate shared types from game-specific types + foreach (var typeName in allTypeNames) + { + if (gameSpecificTypeNames.Contains(typeName)) + { + GameSpecificTypeNames.Add(typeName); + } + else + { + SharedTypeNames.Add(typeName); + } + } + + // Import types from shared types file + if (SharedTypeNames.Any()) + { + Source.Append("import type { "); + Source.Append(string.Join(", ", SharedTypeNames.OrderBy(t => t))); + Source.AppendLine(" } from '../types';"); + } + + // Import types from game-specific types file + if (GameSpecificTypeNames.Any()) + { + Source.Append("import type { "); + Source.Append(string.Join(", ", GameSpecificTypeNames.OrderBy(t => t))); + Source.AppendLine(" } from './types';"); + } + + if (SharedTypeNames.Any() || GameSpecificTypeNames.Any()) + { + Source.AppendLine(); + } + + // Event handler types + Source.AppendLine("// Event handler types"); + foreach (var notification in meta.Notifications) + { + Source.AppendLine($"export type {notification.Name}Handler = (data: {notification.Message.Name}) => void;"); + } + Source.AppendLine(); + + // Main client interface + Source.AppendLine($"export interface {meta.Name}Client {{"); + using (Source.Indent()) + { + // Event listeners + foreach (var notification in meta.Notifications) + { + Source.AppendLine($"on{notification.Name}(handler: {notification.Name}Handler): void;"); + Source.AppendLine($"off{notification.Name}(handler: {notification.Name}Handler): void;"); + } + + if (meta.Notifications.Any()) + { + Source.AppendLine(); + } + + // Methods + foreach (var method in meta.Methods) + { + var parameters = string.Join(", ", method.Parameters.Select(FormatParameter)); + var returnType = method.ReturnType.Name != "void" ? method.ReturnType.Name : "void"; + Source.AppendLine($"{method.Name.ToCamelCase()}({parameters}): Promise<{returnType}>;"); + } + } + Source.AppendLine("}"); + Source.AppendLine(); + + // Implementation class + Source.AppendLine($"export class {meta.Name}ClientImpl implements {meta.Name}Client {{"); + using (Source.Indent()) + { + // Event handler storage + foreach (var notification in meta.Notifications) + { + Source.AppendLine($"private {notification.Name.ToCamelCase()}Handlers: {notification.Name}Handler[] = [];"); + } + + if (meta.Notifications.Any()) + { + Source.AppendLine(); + } + + // Constructor + Source.AppendLine("constructor(private actionSocket: WebSocket, private notificationSocket: WebSocket) {"); + using (Source.Indent()) + { + Source.AppendLine("this.setupNotificationHandlers();"); + } + Source.AppendLine("}"); + Source.AppendLine(); + + // Setup notification handlers + Source.AppendLine("private setupNotificationHandlers(): void {"); + using (Source.Indent()) + { + Source.AppendLine("this.notificationSocket.onmessage = (event) => {"); + using (Source.Indent()) + { + Source.AppendLine("const notification = JSON.parse(event.data);"); + Source.AppendLine("this.handleNotification(notification);"); + } + Source.AppendLine("};"); + } + Source.AppendLine("}"); + Source.AppendLine(); + + // Handle notification + Source.AppendLine("private handleNotification(notification: any): void {"); + using (Source.Indent()) + { + Source.AppendLine("switch (notification.type) {"); + using (Source.Indent()) + { + foreach (var notification in meta.Notifications) + { + Source.AppendLine($"case '{notification.Message.Type}':"); + using (Source.Indent()) + { + Source.AppendLine($"this.{notification.Name.ToCamelCase()}Handlers.forEach(h => h(notification));"); + Source.AppendLine("break;"); + } + } + } + Source.AppendLine("}"); + } + Source.AppendLine("}"); + Source.AppendLine(); + + // Event listener methods + foreach (var notification in meta.Notifications) + { + Source.AppendLine($"on{notification.Name}(handler: {notification.Name}Handler): void {{"); + using (Source.Indent()) + { + Source.AppendLine($"this.{notification.Name.ToCamelCase()}Handlers.push(handler);"); + } + Source.AppendLine("}"); + Source.AppendLine(); + + Source.AppendLine($"off{notification.Name}(handler: {notification.Name}Handler): void {{"); + using (Source.Indent()) + { + Source.AppendLine($"const index = this.{notification.Name.ToCamelCase()}Handlers.indexOf(handler);"); + Source.AppendLine("if (index > -1) {"); + using (Source.Indent()) + { + Source.AppendLine($"this.{notification.Name.ToCamelCase()}Handlers.splice(index, 1);"); + } + Source.AppendLine("}"); + } + Source.AppendLine("}"); + Source.AppendLine(); + } + + // Game methods + foreach (var method in meta.Methods) + { + var parameters = string.Join(", ", method.Parameters.Select(FormatParameter)); + var returnType = method.ReturnType.Name != "void" ? method.ReturnType.Name : "void"; + + Source.AppendLine($"async {method.Name.ToCamelCase()}({parameters}): Promise<{returnType}> {{"); + using (Source.Indent()) + { + Source.AppendLine("return new Promise((resolve, reject) => {"); + using (Source.Indent()) + { + // If there's a single parameter named "request", spread it and add the type + if (method.Parameters.Count() == 1 && method.Parameters.First().Name == "request") + { + Source.AppendLine("const requestPayload = {"); + using (Source.Indent()) + { + Source.AppendLine("...request,"); + Source.AppendLine($"type: '{method.Parameters.First().Type.Type}'"); + } + Source.AppendLine("};"); + } + else + { + Source.AppendLine("const requestPayload = {"); + using (Source.Indent()) + { + foreach (var param in method.Parameters) + { + Source.AppendLine($"{param.Name}: {param.Name},"); + } + Source.AppendLine($"type: 'Unknown'"); + } + Source.AppendLine("};"); + } + Source.AppendLine(); + Source.AppendLine("const messageHandler = (event: MessageEvent) => {"); + using (Source.Indent()) + { + Source.AppendLine("const response = JSON.parse(event.data);"); + if (returnType != "void") + { + Source.AppendLine("if (response.hasError) {"); + using (Source.Indent()) + { + Source.AppendLine("reject(new Error(response.error || 'Unknown error'));"); + } + Source.AppendLine("} else {"); + using (Source.Indent()) + { + Source.AppendLine("resolve(response);"); + } + Source.AppendLine("}"); + } + else + { + Source.AppendLine("if (response.hasError) {"); + using (Source.Indent()) + { + Source.AppendLine("reject(new Error(response.error || 'Unknown error'));"); + } + Source.AppendLine("} else {"); + using (Source.Indent()) + { + Source.AppendLine("resolve();"); + } + Source.AppendLine("}"); + } + Source.AppendLine("this.actionSocket.removeEventListener('message', messageHandler);"); + } + Source.AppendLine("};"); + Source.AppendLine(); + Source.AppendLine("this.actionSocket.addEventListener('message', messageHandler);"); + Source.AppendLine("this.actionSocket.send(JSON.stringify(requestPayload));"); + } + Source.AppendLine("});"); + } + Source.AppendLine("}"); + Source.AppendLine(); + } + } + Source.AppendLine("}"); + } + + private static string FormatParameter(ParameterMeta parameter) + { + return $"{parameter.Name}: {parameter.Type.Name}"; + } +} diff --git a/src/Deckster.CodeGenerator/Generators/TypeScriptTypeGenerator.cs b/src/Deckster.CodeGenerator/Generators/TypeScriptTypeGenerator.cs new file mode 100644 index 00000000..2be3a18f --- /dev/null +++ b/src/Deckster.CodeGenerator/Generators/TypeScriptTypeGenerator.cs @@ -0,0 +1,273 @@ +using System.Reflection; +using Deckster.CodeGenerator.Code; +using Deckster.Core.Extensions; + +namespace Deckster.CodeGenerator.Generators; + +public class TypeScriptTypeGenerator +{ + private readonly HashSet _processedTypes = new(); + private readonly HashSet _typesToProcess = new(); + private readonly SourceWriter _source = new(); + + public void AddType(Type type) + { + if (!_processedTypes.Contains(type) && !_typesToProcess.Contains(type)) + { + _typesToProcess.Add(type); + } + } + + public void GenerateTypes() + { + while (_typesToProcess.Count > 0) + { + var type = _typesToProcess.First(); + _typesToProcess.Remove(type); + + if (_processedTypes.Contains(type)) + { + continue; + } + + ProcessType(type); + _processedTypes.Add(type); + } + } + + private void ProcessType(Type type) + { + // Skip primitive types and common .NET types + if (IsPrimitiveOrKnownType(type)) + { + return; + } + + // Handle nullable types + var underlyingType = Nullable.GetUnderlyingType(type); + if (underlyingType != null) + { + ProcessType(underlyingType); + return; + } + + // Handle arrays and collections + if (type.IsArray) + { + ProcessType(type.GetElementType()!); + return; + } + + if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(List<>) || + type.GetGenericTypeDefinition() == typeof(IEnumerable<>) || + type.GetGenericTypeDefinition() == typeof(ICollection<>))) + { + ProcessType(type.GetGenericArguments()[0]); + return; + } + + // Handle enums + if (type.IsEnum) + { + GenerateEnum(type); + return; + } + + // Handle classes and structs + if (type.IsClass || type.IsValueType) + { + GenerateInterface(type); + } + } + + private void GenerateEnum(Type type) + { + _source.AppendLine($"export enum {GetTypeName(type)} {{"); + using (_source.Indent()) + { + var names = Enum.GetNames(type); + var values = Enum.GetValues(type); + + for (int i = 0; i < names.Length; i++) + { + var name = names[i]; + var value = Convert.ToInt32(values.GetValue(i)); + _source.AppendLine($"{name} = {value},"); + } + } + _source.AppendLine("}"); + _source.AppendLine(); + } + + private void GenerateInterface(Type type) + { + var typeName = GetTypeName(type); + _source.AppendLine($"export interface {typeName} {{"); + + using (_source.Indent()) + { + var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance) + .Where(p => p.CanRead && !p.GetIndexParameters().Any()); + + foreach (var property in properties) + { + var propertyName = property.Name.ToCamelCase(); + var propertyType = GetTypeScriptType(property.PropertyType); + var optional = IsNullable(property.PropertyType) ? "?" : ""; + + _source.AppendLine($"{propertyName}{optional}: {propertyType};"); + + // Queue property types for processing + QueueTypeForProcessing(property.PropertyType); + } + } + + _source.AppendLine("}"); + _source.AppendLine(); + } + + private void QueueTypeForProcessing(Type type) + { + // Handle nullable types + var underlyingType = Nullable.GetUnderlyingType(type); + if (underlyingType != null) + { + QueueTypeForProcessing(underlyingType); + return; + } + + // Handle arrays + if (type.IsArray) + { + QueueTypeForProcessing(type.GetElementType()!); + return; + } + + // Handle generic collections + if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(List<>) || + type.GetGenericTypeDefinition() == typeof(IEnumerable<>) || + type.GetGenericTypeDefinition() == typeof(ICollection<>))) + { + QueueTypeForProcessing(type.GetGenericArguments()[0]); + return; + } + + // Add complex types to the queue + if (!IsPrimitiveOrKnownType(type) && !_processedTypes.Contains(type) && !_typesToProcess.Contains(type)) + { + _typesToProcess.Add(type); + } + } + + private string GetTypeScriptType(Type type) + { + // Handle nullable types + var underlyingType = Nullable.GetUnderlyingType(type); + if (underlyingType != null) + { + return GetTypeScriptType(underlyingType); + } + + // Handle arrays + if (type.IsArray) + { + return $"{GetTypeScriptType(type.GetElementType()!)}[]"; + } + + // Handle generic collections + if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(List<>) || + type.GetGenericTypeDefinition() == typeof(IEnumerable<>) || + type.GetGenericTypeDefinition() == typeof(ICollection<>))) + { + return $"{GetTypeScriptType(type.GetGenericArguments()[0])}[]"; + } + + // Handle dictionaries + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>)) + { + var keyType = GetTypeScriptType(type.GetGenericArguments()[0]); + var valueType = GetTypeScriptType(type.GetGenericArguments()[1]); + return $"Record<{keyType}, {valueType}>"; + } + + // Primitive type mappings + if (type == typeof(string)) return "string"; + if (type == typeof(int) || type == typeof(long) || type == typeof(short) || + type == typeof(byte) || type == typeof(decimal) || type == typeof(double) || + type == typeof(float)) return "number"; + if (type == typeof(bool)) return "boolean"; + if (type == typeof(DateTime) || type == typeof(DateTimeOffset)) return "string"; // ISO date string + if (type == typeof(Guid)) return "string"; + if (type == typeof(object)) return "any"; + if (type == typeof(void)) return "void"; + + // Complex types + return GetTypeName(type); + } + + private string GetTypeName(Type type) + { + if (type.IsGenericType) + { + var backtickIndex = type.Name.IndexOf('`'); + if (backtickIndex > 0) + { + return type.Name.Substring(0, backtickIndex); + } + } + + return type.Name; + } + + private bool IsNullable(Type type) + { + if (Nullable.GetUnderlyingType(type) != null) + { + return true; + } + + if (!type.IsValueType) + { + return true; // Reference types are nullable by default + } + + return false; + } + + private bool IsPrimitiveOrKnownType(Type type) + { + return type.IsPrimitive || + type == typeof(string) || + type == typeof(decimal) || + type == typeof(DateTime) || + type == typeof(DateTimeOffset) || + type == typeof(Guid) || + type == typeof(object) || + type == typeof(void); + } + + public string GetGeneratedCode() + { + return _source.ToString(); + } + + public async Task WriteToAsync(FileInfo file) + { + if (file.Directory is { Exists: false }) + { + file.Directory.Create(); + } + + await using var fileStream = file.Exists ? file.Open(FileMode.Truncate) : file.Open(FileMode.CreateNew); + await using var writer = new StreamWriter(fileStream); + + await writer.WriteLineAsync("/**"); + await writer.WriteLineAsync(" * Autogenerated by really, really eager small hamsters."); + await writer.WriteLineAsync(" * Shared type definitions for Deckster game clients."); + await writer.WriteLineAsync(" */"); + await writer.WriteLineAsync(); + + await writer.WriteAsync(_source.ToString()); + await writer.FlushAsync(); + } +} diff --git a/src/Deckster.CodeGenerator/Program.cs b/src/Deckster.CodeGenerator/Program.cs index dae73b4f..0ca9455e 100644 --- a/src/Deckster.CodeGenerator/Program.cs +++ b/src/Deckster.CodeGenerator/Program.cs @@ -87,21 +87,118 @@ private static async Task GenerateClientsAsync(DirectoryInfo gitDirectory) var types = baseType.Assembly.GetTypes() .Where(t => t is {IsClass: true, IsAbstract: false} && baseType.IsAssignableFrom(t)) .ToArray(); - + var kotlinDirectory = gitDirectory.GetCleanSubDirectory("generated", "kotlin"); - + var godotDirectory = gitDirectory.GetCleanSubDirectory("generated", "godot"); + var typeScriptDirectory = gitDirectory.GetSubDirectory("generated", "typescript"); + if (!typeScriptDirectory.Exists) + { + typeScriptDirectory.Create(); + } + + // Collect types per game for TypeScript generation + var gameTypesMap = new Dictionary>(); + var gameClients = new List<(Type gameType, GameMeta gameMeta, CSharpGameMeta csharpMeta)>(); + foreach (var type in types) { if (CSharpGameMeta.TryGetFor(type, out var gameMeta)) { - await GenerateCsharpAsync(gitDirectory, type, gameMeta); + await GenerateCsharpAsync(gitDirectory, type, gameMeta); + + var gameName = type.Name.Replace("Game", ""); + var gameTypes = new HashSet(); + + // Collect types for this game + foreach (var notification in gameMeta.Notifications) + { + gameTypes.Add(notification.MessageType); + } + + foreach (var method in gameMeta.Methods) + { + gameTypes.Add(method.Request.ParameterType); + gameTypes.Add(method.ResponseType); + } + + gameTypesMap[gameName] = gameTypes; + + if (GameMeta.TryGetFor(type, out var game)) + { + await GenerateKotlinAsync(kotlinDirectory, type, game); + await GenerateGodotAsync(godotDirectory, type, game); + gameClients.Add((type, game, gameMeta)); + } } - - if (GameMeta.TryGetFor(type, out var game)) + } + + // Determine shared vs game-specific types + var allTypes = new HashSet(); + foreach (var gameTypes in gameTypesMap.Values) + { + foreach (var type in gameTypes) + { + allTypes.Add(type); + } + } + + var sharedTypes = new HashSet(); + var gameSpecificTypes = new Dictionary>(); + + foreach (var type in allTypes) + { + var gamesUsingType = gameTypesMap.Where(kvp => kvp.Value.Contains(type)).Select(kvp => kvp.Key).ToList(); + + if (gamesUsingType.Count > 1) + { + sharedTypes.Add(type); + } + else if (gamesUsingType.Count == 1) { - await GenerateKotlinAsync(kotlinDirectory, type, game); + var gameName = gamesUsingType[0]; + if (!gameSpecificTypes.ContainsKey(gameName)) + { + gameSpecificTypes[gameName] = new HashSet(); + } + gameSpecificTypes[gameName].Add(type); } } + + // Generate shared TypeScript types + var sharedTypeGenerator = new TypeScriptTypeGenerator(); + foreach (var type in sharedTypes) + { + sharedTypeGenerator.AddType(type); + } + sharedTypeGenerator.GenerateTypes(); + await sharedTypeGenerator.WriteToAsync(typeScriptDirectory.GetFile("types.ts")); + + // Generate game-specific TypeScript types and clients + foreach (var (gameType, game, csharpMeta) in gameClients) + { + var gameName = gameType.Name.Replace("Game", ""); + var ns = gameType.Namespace?.Split('.').LastOrDefault()?.ToLowerInvariant() ?? throw new Exception($"OMG CANT HAZ NAEMSPAZE OF ITZ TAYP '{gameType.Name}'"); + + // Generate game-specific types + if (gameSpecificTypes.TryGetValue(gameName, out var specificTypes)) + { + var gameTypeGenerator = new TypeScriptTypeGenerator(); + foreach (var type in specificTypes) + { + gameTypeGenerator.AddType(type); + } + gameTypeGenerator.GenerateTypes(); + + var gameTypeFile = typeScriptDirectory.GetFile(ns, "types.ts"); + await gameTypeGenerator.WriteToAsync(gameTypeFile); + } + + // Generate client + var gameSpecificTypeNames = gameSpecificTypes.ContainsKey(gameName) + ? gameSpecificTypes[gameName].Select(t => t.Name).ToHashSet() + : new HashSet(); + await GenerateTypeScriptAsync(typeScriptDirectory, gameType, game, gameSpecificTypeNames); + } } private static async Task GenerateCsharpAsync(DirectoryInfo gitDirectory, Type gameType, CSharpGameMeta game) @@ -117,9 +214,29 @@ private static async Task GenerateKotlinAsync(DirectoryInfo kotlinDirectory, Typ { var ns = type.Namespace?.Split('.').LastOrDefault()?.ToLowerInvariant() ?? throw new Exception($"OMG CANT HAZ NAEMSPAZE OF ITZ TAYP '{type.Name}'"); var file = kotlinDirectory.GetFile("no.forse.decksterlib", ns, $"{game.Name}Client.kt"); - + Console.WriteLine(file); var kotlin = new KotlinClientGenerator(game, $"no.forse.decksterlib.{ns}"); await kotlin.WriteToAsync(file); } + + private static async Task GenerateTypeScriptAsync(DirectoryInfo typeScriptDirectory, Type type, GameMeta game, HashSet gameSpecificTypeNames) + { + var ns = type.Namespace?.Split('.').LastOrDefault()?.ToLowerInvariant() ?? throw new Exception($"OMG CANT HAZ NAEMSPAZE OF ITZ TAYP '{type.Name}'"); + var file = typeScriptDirectory.GetFile(ns, $"{game.Name}Client.ts"); + + Console.WriteLine(file); + var typeScript = new TypeScriptClientGenerator(game, ns, gameSpecificTypeNames); + await typeScript.WriteToAsync(file); + } + + private static async Task GenerateGodotAsync(DirectoryInfo godotDirectory, Type type, GameMeta game) + { + var ns = type.Namespace?.Split('.').LastOrDefault()?.ToLowerInvariant() ?? throw new Exception($"OMG CANT HAZ NAEMSPAZE OF ITZ TAYP '{type.Name}'"); + var file = godotDirectory.GetFile(ns, $"{game.Name}Client.gd"); + + Console.WriteLine(file); + var godot = new GodotClientGenerator(game, $"{game.Name}Client"); + await godot.WriteToAsync(file); + } } diff --git a/src/Deckster.Core/Games/Common/Card.cs b/src/Deckster.Core/Games/Common/Card.cs index f587ee71..f39f1bec 100644 --- a/src/Deckster.Core/Games/Common/Card.cs +++ b/src/Deckster.Core/Games/Common/Card.cs @@ -1,6 +1,6 @@ namespace Deckster.Core.Games.Common; -public readonly struct Card +public readonly struct Card : IComparable { public int Rank { get; init; } public Suit Suit { get; init; } @@ -45,6 +45,13 @@ public override int GetHashCode() return HashCode.Combine(Rank, (int) Suit); } + public int CompareTo(Card other) + { + // Sort by suit first, then by rank + var suitComparison = Suit.CompareTo(other.Suit); + return suitComparison != 0 ? suitComparison : Rank.CompareTo(other.Rank); + } + public override string ToString() { return Rank switch diff --git a/src/Deckster.Core/Games/Hearts/HeartsMessages.cs b/src/Deckster.Core/Games/Hearts/HeartsMessages.cs new file mode 100644 index 00000000..a07f4cc9 --- /dev/null +++ b/src/Deckster.Core/Games/Hearts/HeartsMessages.cs @@ -0,0 +1,19 @@ +using Deckster.Core.Games.Common; +using Deckster.Core.Protocol; + +namespace Deckster.Core.Games.Hearts; + +public class PassCardsRequest : DecksterRequest +{ + public required List Cards { get; set; } +} + +public class PlayCardRequest : DecksterRequest +{ + public required Card Card { get; set; } +} + +public class PassCardsResponse : DecksterResponse +{ + public List ReceivedCards { get; init; } = []; +} diff --git a/src/Deckster.Core/Games/Hearts/HeartsNotifications.cs b/src/Deckster.Core/Games/Hearts/HeartsNotifications.cs new file mode 100644 index 00000000..1534fb51 --- /dev/null +++ b/src/Deckster.Core/Games/Hearts/HeartsNotifications.cs @@ -0,0 +1,73 @@ +using Deckster.Core.Games.Common; +using Deckster.Core.Protocol; + +namespace Deckster.Core.Games.Hearts; + +public class GameStartedNotification : DecksterNotification +{ + public Guid GameId { get; init; } + public PlayerViewOfGame PlayerViewOfGame { get; init; } = new(); +} + +public class PassingPhaseStartedNotification : DecksterNotification +{ + public PassDirection PassDirection { get; init; } +} + +public class AllPlayersPassedNotification : DecksterNotification +{ + public List ReceivedCards { get; init; } = []; +} + +public class PlayerPassedCardsNotification : DecksterNotification +{ + public Guid PlayerId { get; init; } +} + +public class ItsYourTurnNotification : DecksterNotification +{ + public PlayerViewOfGame PlayerViewOfGame { get; init; } = new(); +} + +public class ItsPlayersTurnNotification : DecksterNotification +{ + public Guid PlayerId { get; init; } +} + +public class PlayerPlayedCardNotification : DecksterNotification +{ + public Guid PlayerId { get; init; } + public required Card Card { get; init; } +} + +public class TrickCompletedNotification : DecksterNotification +{ + public Guid WinnerId { get; init; } + public required string WinnerName { get; init; } + public List TrickCards { get; init; } = []; + public int Points { get; init; } +} + +public class RoundEndedNotification : DecksterNotification +{ + public required List Scores { get; init; } + public Guid? MoonShooterId { get; init; } + public string? MoonShooterName { get; init; } +} + +public class GameEndedNotification : DecksterNotification +{ + public required List FinalScores { get; init; } + public Guid WinnerId { get; init; } + public required string WinnerName { get; init; } +} + +public class HeartsAreBrokenNotification : DecksterNotification; + +public class PlayerScore +{ + public Guid PlayerId { get; init; } + public required string PlayerName { get; init; } + public int RoundScore { get; init; } + public int TotalScore { get; init; } +} diff --git a/src/Deckster.Core/Games/Hearts/PlayerViewOfGame.cs b/src/Deckster.Core/Games/Hearts/PlayerViewOfGame.cs new file mode 100644 index 00000000..158791a1 --- /dev/null +++ b/src/Deckster.Core/Games/Hearts/PlayerViewOfGame.cs @@ -0,0 +1,52 @@ +using Deckster.Core.Games.Common; +using Deckster.Core.Protocol; + +namespace Deckster.Core.Games.Hearts; + +public class PlayerViewOfGame : DecksterResponse +{ + public List Cards { get; init; } = []; + public List OtherPlayers { get; init; } = []; + public int RoundNumber { get; init; } + public PassDirection PassDirection { get; init; } + public bool HasPassed { get; init; } + public List CurrentTrick { get; init; } = []; + public int TotalScore { get; init; } + public int RoundScore { get; init; } + public bool HeartsAreBroken { get; init; } + public bool IsMyTurn { get; init; } + + public PlayerViewOfGame() + { + } + + public PlayerViewOfGame(string error) + { + Error = error; + } +} + +public class OtherHeartsPlayer +{ + public Guid PlayerId { get; init; } + public required string Name { get; init; } + public int NumberOfCards { get; init; } + public int TotalScore { get; init; } + public int RoundScore { get; init; } + public Card? PlayedCard { get; init; } +} + +public class CardPlay +{ + public Guid PlayerId { get; init; } + public required string PlayerName { get; init; } + public required Card Card { get; init; } +} + +public enum PassDirection +{ + None, + Left, + Right, + Across +} diff --git a/src/Deckster.Games/Hearts/HeartsGame.cs b/src/Deckster.Games/Hearts/HeartsGame.cs new file mode 100644 index 00000000..5c7a5e98 --- /dev/null +++ b/src/Deckster.Games/Hearts/HeartsGame.cs @@ -0,0 +1,573 @@ +using System.Diagnostics.CodeAnalysis; +using Deckster.Core.Collections; +using Deckster.Core.Games.Common; +using Deckster.Core.Games.Hearts; + +namespace Deckster.Games.Hearts; + +public class HeartsGame : GameObject +{ + public event NotifyPlayer? GameStarted; + public event NotifyAll? PassingPhaseStarted; + public event NotifyPlayer? AllPlayersPassed; + public event NotifyAll? PlayerPassedCards; + public event NotifyPlayer? ItsYourTurn; + public event NotifyAll? ItsPlayersTurn; + public event NotifyAll? PlayerPlayedCard; + public event NotifyAll? TrickCompleted; + public event NotifyAll? RoundEnded; + public event NotifyAll? GameEnded; + public event NotifyAll? HeartsWereBroken; + + public List Deck { get; init; } = []; + public List Players { get; init; } = []; + public int CurrentPlayerIndex { get; set; } + public int RoundNumber { get; set; } = 1; + public bool HeartsAreBroken { get; set; } + public List CurrentTrick { get; init; } = []; + public Suit? LeadSuit { get; set; } + public bool IsFirstTrick { get; set; } = true; + public GamePhase Phase { get; set; } = GamePhase.Passing; + + protected override GameState GetState() + { + return Players.Any(p => p.TotalScore >= 100) ? GameState.Finished : GameState.Running; + } + + public HeartsPlayer CurrentPlayer => Phase == GamePhase.Playing ? Players[CurrentPlayerIndex] : HeartsPlayer.Null; + + public PassDirection CurrentPassDirection => + RoundNumber % 4 == 1 ? PassDirection.Left : + RoundNumber % 4 == 2 ? PassDirection.Right : + RoundNumber % 4 == 3 ? PassDirection.Across : + PassDirection.None; + + public static HeartsGame Instantiate(HeartsGameCreatedEvent created) + { + var game = new HeartsGame + { + Id = created.Id, + Name = created.Name, + StartedTime = created.StartedTime, + Seed = created.InitialSeed, + Deck = created.Deck, + Players = created.Players.Select(p => new HeartsPlayer + { + Id = p.Id, + Name = p.Name + }).ToList() + }; + game.DealCards(); + return game; + } + + private void DealCards() + { + var cardIndex = 0; + foreach (var player in Players) + { + player.Cards.Clear(); + for (var i = 0; i < 13; i++) + { + player.Cards.Add(Deck[cardIndex++]); + } + player.Cards.Sort(); + } + } + + public async Task PassCards(PassCardsRequest request) + { + IncrementSeed(); + var playerId = request.PlayerId; + + if (!TryGetPlayer(playerId, out var player)) + { + var errorResponse = new PassCardsResponse { Error = "Player not found" }; + await RespondAsync(playerId, errorResponse); + return errorResponse; + } + + if (Phase != GamePhase.Passing) + { + var errorResponse = new PassCardsResponse { Error = "Not in passing phase" }; + await RespondAsync(playerId, errorResponse); + return errorResponse; + } + + if (CurrentPassDirection == PassDirection.None) + { + var errorResponse = new PassCardsResponse { Error = "No passing this round" }; + await RespondAsync(playerId, errorResponse); + return errorResponse; + } + + if (player.HasPassed) + { + var errorResponse = new PassCardsResponse { Error = "You have already passed cards" }; + await RespondAsync(playerId, errorResponse); + return errorResponse; + } + + if (request.Cards.Count != 3) + { + var errorResponse = new PassCardsResponse { Error = "You must pass exactly 3 cards" }; + await RespondAsync(playerId, errorResponse); + return errorResponse; + } + + if (request.Cards.Any(c => !player.HasCard(c))) + { + var errorResponse = new PassCardsResponse { Error = "You don't have all those cards" }; + await RespondAsync(playerId, errorResponse); + return errorResponse; + } + + player.CardsToPass.AddRange(request.Cards); + player.HasPassed = true; + + await PlayerPassedCards.InvokeOrDefault(() => new PlayerPassedCardsNotification + { + PlayerId = playerId + }); + + if (Players.All(p => p.HasPassed)) + { + DistributePassedCards(); + + foreach (var p in Players) + { + var receivedCards = p.CardsToPass.ToList(); + var response = new PassCardsResponse { ReceivedCards = receivedCards }; + await RespondAsync(p.Id, response); + await AllPlayersPassed.InvokeOrDefault(p.Id, () => new AllPlayersPassedNotification + { + ReceivedCards = receivedCards + }); + } + + await StartPlayingPhaseAsync(); + } + else + { + var response = new PassCardsResponse(); + await RespondAsync(playerId, response); + } + + return new PassCardsResponse(); + } + + private void DistributePassedCards() + { + var passedCards = Players.Select(p => p.CardsToPass.ToList()).ToList(); + + for (var i = 0; i < Players.Count; i++) + { + var player = Players[i]; + var cardsToReceive = CurrentPassDirection switch + { + PassDirection.Left => passedCards[(i + 1) % Players.Count], + PassDirection.Right => passedCards[(i + Players.Count - 1) % Players.Count], + PassDirection.Across => passedCards[(i + 2) % Players.Count], + _ => [] + }; + + foreach (var card in player.CardsToPass) + { + player.Cards.Remove(card); + } + + player.Cards.AddRange(cardsToReceive); + player.Cards.Sort(); + player.CardsToPass.Clear(); + } + } + + private async Task StartPlayingPhaseAsync() + { + Phase = GamePhase.Playing; + + var startingPlayerIndex = Players.FindIndex(p => p.HasTwoOfClubs()); + if (startingPlayerIndex == -1) + { + startingPlayerIndex = 0; + } + CurrentPlayerIndex = startingPlayerIndex; + + var currentPlayer = CurrentPlayer; + await ItsYourTurn.InvokeOrDefault(currentPlayer.Id, () => new ItsYourTurnNotification + { + PlayerViewOfGame = GetPlayerViewOfGame(currentPlayer) + }); + await ItsPlayersTurn.InvokeOrDefault(() => new ItsPlayersTurnNotification + { + PlayerId = currentPlayer.Id + }); + } + + public async Task PlayCard(PlayCardRequest request) + { + IncrementSeed(); + var playerId = request.PlayerId; + var card = request.Card; + + if (!TryGetPlayer(playerId, out var player)) + { + var errorResponse = new PlayerViewOfGame("Player not found"); + await RespondAsync(playerId, errorResponse); + return errorResponse; + } + + if (Phase != GamePhase.Playing) + { + var errorResponse = new PlayerViewOfGame("Not in playing phase"); + await RespondAsync(playerId, errorResponse); + return errorResponse; + } + + if (CurrentPlayer.Id != playerId) + { + var errorResponse = new PlayerViewOfGame("It is not your turn"); + await RespondAsync(playerId, errorResponse); + return errorResponse; + } + + if (!player.HasCard(card)) + { + var errorResponse = new PlayerViewOfGame($"You don't have '{card}'"); + await RespondAsync(playerId, errorResponse); + return errorResponse; + } + + var validationError = ValidateCardPlay(player, card); + if (validationError != null) + { + var errorResponse = new PlayerViewOfGame(validationError); + await RespondAsync(playerId, errorResponse); + return errorResponse; + } + + player.Cards.Remove(card); + player.PlayedCard = card; + CurrentTrick.Add(new CardPlay + { + PlayerId = player.Id, + PlayerName = player.Name, + Card = card + }); + + if (CurrentTrick.Count == 1) + { + LeadSuit = card.Suit; + } + + // Hearts are broken when a player plays a heart because they couldn't follow suit + if (!HeartsAreBroken && card.Suit == Suit.Hearts && CurrentTrick.Count > 1) + { + // Only break hearts if the player couldn't follow the lead suit + if (LeadSuit.HasValue && LeadSuit.Value != Suit.Hearts && !player.HasSuit(LeadSuit.Value)) + { + HeartsAreBroken = true; + await HeartsWereBroken.InvokeOrDefault(() => new HeartsAreBrokenNotification()); + } + } + + var response = GetPlayerViewOfGame(player); + await RespondAsync(playerId, response); + + await PlayerPlayedCard.InvokeOrDefault(() => new PlayerPlayedCardNotification + { + PlayerId = playerId, + Card = card + }); + + if (CurrentTrick.Count == Players.Count) + { + await CompleteTrickAsync(); + } + else + { + MoveToNextPlayer(); + var nextPlayer = CurrentPlayer; + await ItsYourTurn.InvokeOrDefault(nextPlayer.Id, () => new ItsYourTurnNotification + { + PlayerViewOfGame = GetPlayerViewOfGame(nextPlayer) + }); + await ItsPlayersTurn.InvokeOrDefault(() => new ItsPlayersTurnNotification + { + PlayerId = nextPlayer.Id + }); + } + + return response; + } + + private string? ValidateCardPlay(HeartsPlayer player, Card card) + { + if (IsFirstTrick && player.HasTwoOfClubs() && card is not { Suit: Suit.Clubs, Rank: 2 }) + { + return "You must lead with the Two of Clubs on the first trick"; + } + + if (CurrentTrick.Count == 0) + { + if (!HeartsAreBroken && card.Suit == Suit.Hearts && player.Cards.Any(c => c.Suit != Suit.Hearts)) + { + return "Hearts have not been broken yet"; + } + + if (IsFirstTrick && card.Suit == Suit.Hearts) + { + return "Cannot lead with hearts on the first trick"; + } + + if (IsFirstTrick && card is { Suit: Suit.Spades, Rank: 12 }) + { + return "Cannot lead with Queen of Spades on the first trick"; + } + } + else + { + if (LeadSuit.HasValue && player.HasSuit(LeadSuit.Value) && card.Suit != LeadSuit.Value) + { + return $"You must follow suit ({LeadSuit.Value})"; + } + + if (IsFirstTrick && (card.Suit == Suit.Hearts || card is { Suit: Suit.Spades, Rank: 12 })) + { + if (player.Cards.Any(c => c.Suit != Suit.Hearts && c is not { Suit: Suit.Spades, Rank: 12 })) + { + return "Cannot play points on the first trick unless you only have point cards"; + } + } + } + + return null; + } + + private async Task CompleteTrickAsync() + { + var winningPlay = CurrentTrick + .Where(cp => cp.Card.Suit == LeadSuit) + .OrderByDescending(cp => cp.Card.Rank) + .First(); + + var winnerId = winningPlay.PlayerId; + var winner = Players.First(p => p.Id == winnerId); + + var points = CurrentTrick.Sum(cp => cp.Card.Suit == Suit.Hearts ? 1 : + cp.Card is { Suit: Suit.Spades, Rank: 12 } ? 13 : 0); + winner.RoundScore += points; + + await TrickCompleted.InvokeOrDefault(() => new TrickCompletedNotification + { + WinnerId = winnerId, + WinnerName = winner.Name, + TrickCards = CurrentTrick.ToList(), + Points = points + }); + + foreach (var player in Players) + { + player.ClearPlayedCard(); + } + CurrentTrick.Clear(); + LeadSuit = null; + IsFirstTrick = false; + + CurrentPlayerIndex = Players.FindIndex(p => p.Id == winnerId); + + if (Players.All(p => p.Cards.Count == 0)) + { + await EndRoundAsync(); + } + else + { + var nextPlayer = CurrentPlayer; + await ItsYourTurn.InvokeOrDefault(nextPlayer.Id, () => new ItsYourTurnNotification + { + PlayerViewOfGame = GetPlayerViewOfGame(nextPlayer) + }); + await ItsPlayersTurn.InvokeOrDefault(() => new ItsPlayersTurnNotification + { + PlayerId = nextPlayer.Id + }); + } + } + + private async Task EndRoundAsync() + { + var moonShooter = Players.FirstOrDefault(p => p.RoundScore == 26); + + if (moonShooter != null) + { + foreach (var player in Players.Where(p => p.Id != moonShooter.Id)) + { + player.TotalScore += 26; + } + moonShooter.RoundScore = 0; + } + else + { + foreach (var player in Players) + { + player.TotalScore += player.RoundScore; + } + } + + var scores = Players.Select(p => new PlayerScore + { + PlayerId = p.Id, + PlayerName = p.Name, + RoundScore = p.RoundScore, + TotalScore = p.TotalScore + }).ToList(); + + await RoundEnded.InvokeOrDefault(() => new RoundEndedNotification + { + Scores = scores, + MoonShooterId = moonShooter?.Id, + MoonShooterName = moonShooter?.Name + }); + + if (Players.Any(p => p.TotalScore >= 100)) + { + await EndGameAsync(); + } + else + { + await StartNextRoundAsync(); + } + } + + private async Task StartNextRoundAsync() + { + RoundNumber++; + HeartsAreBroken = false; + IsFirstTrick = true; + Phase = GamePhase.Passing; + + foreach (var player in Players) + { + player.RoundScore = 0; + player.HasPassed = false; + player.CardsToPass.Clear(); + player.PlayedCard = null; + } + + DealCards(); + + if (CurrentPassDirection == PassDirection.None) + { + await StartPlayingPhaseAsync(); + } + else + { + await PassingPhaseStarted.InvokeOrDefault(() => new PassingPhaseStartedNotification + { + PassDirection = CurrentPassDirection + }); + + foreach (var player in Players) + { + await ItsYourTurn.InvokeOrDefault(player.Id, () => new ItsYourTurnNotification + { + PlayerViewOfGame = GetPlayerViewOfGame(player) + }); + } + } + } + + private async Task EndGameAsync() + { + var winner = Players.OrderBy(p => p.TotalScore).First(); + + var finalScores = Players.Select(p => new PlayerScore + { + PlayerId = p.Id, + PlayerName = p.Name, + RoundScore = p.RoundScore, + TotalScore = p.TotalScore + }).ToList(); + + await GameEnded.InvokeOrDefault(() => new GameEndedNotification + { + FinalScores = finalScores, + WinnerId = winner.Id, + WinnerName = winner.Name + }); + } + + private void MoveToNextPlayer() + { + CurrentPlayerIndex = (CurrentPlayerIndex + 1) % Players.Count; + } + + private bool TryGetPlayer(Guid playerId, [MaybeNullWhen(false)] out HeartsPlayer player) + { + player = Players.FirstOrDefault(p => p.Id == playerId); + return player != null; + } + + private PlayerViewOfGame GetPlayerViewOfGame(HeartsPlayer player) + { + return new PlayerViewOfGame + { + Cards = player.Cards.ToList(), + OtherPlayers = Players.Where(p => p.Id != player.Id).Select(p => new OtherHeartsPlayer + { + PlayerId = p.Id, + Name = p.Name, + NumberOfCards = p.Cards.Count, + TotalScore = p.TotalScore, + RoundScore = p.RoundScore, + PlayedCard = p.PlayedCard + }).ToList(), + RoundNumber = RoundNumber, + PassDirection = CurrentPassDirection, + HasPassed = player.HasPassed, + CurrentTrick = CurrentTrick.ToList(), + TotalScore = player.TotalScore, + RoundScore = player.RoundScore, + HeartsAreBroken = HeartsAreBroken, + IsMyTurn = Phase == GamePhase.Playing && CurrentPlayer.Id == player.Id + }; + } + + public override async Task StartAsync() + { + foreach (var player in Players) + { + await GameStarted.InvokeOrDefault(player.Id, () => new GameStartedNotification + { + GameId = Id, + PlayerViewOfGame = GetPlayerViewOfGame(player) + }); + } + + if (CurrentPassDirection == PassDirection.None) + { + await StartPlayingPhaseAsync(); + } + else + { + await PassingPhaseStarted.InvokeOrDefault(() => new PassingPhaseStartedNotification + { + PassDirection = CurrentPassDirection + }); + + foreach (var player in Players) + { + await ItsYourTurn.InvokeOrDefault(player.Id, () => new ItsYourTurnNotification + { + PlayerViewOfGame = GetPlayerViewOfGame(player) + }); + } + } + } +} + +public enum GamePhase +{ + Passing, + Playing +} diff --git a/src/Deckster.Games/Hearts/HeartsGameCreatedEvent.cs b/src/Deckster.Games/Hearts/HeartsGameCreatedEvent.cs new file mode 100644 index 00000000..02130e16 --- /dev/null +++ b/src/Deckster.Games/Hearts/HeartsGameCreatedEvent.cs @@ -0,0 +1,9 @@ +using Deckster.Core.Games.Common; + +namespace Deckster.Games.Hearts; + +public class HeartsGameCreatedEvent : GameCreatedEvent +{ + public required List Players { get; init; } + public required List Deck { get; init; } +} diff --git a/src/Deckster.Games/Hearts/HeartsGameStartedEvent.cs b/src/Deckster.Games/Hearts/HeartsGameStartedEvent.cs new file mode 100644 index 00000000..d374c059 --- /dev/null +++ b/src/Deckster.Games/Hearts/HeartsGameStartedEvent.cs @@ -0,0 +1,6 @@ +namespace Deckster.Games.Hearts; + +public class HeartsGameStartedEvent +{ + public Guid GameId { get; init; } +} diff --git a/src/Deckster.Games/Hearts/HeartsPlayer.cs b/src/Deckster.Games/Hearts/HeartsPlayer.cs new file mode 100644 index 00000000..95c081b2 --- /dev/null +++ b/src/Deckster.Games/Hearts/HeartsPlayer.cs @@ -0,0 +1,31 @@ +using Deckster.Core.Games.Common; + +namespace Deckster.Games.Hearts; + +public class HeartsPlayer +{ + public Guid Id { get; init; } + public string Name { get; init; } = ""; + public List Cards { get; init; } = []; + public List CardsToPass { get; init; } = []; + public bool HasPassed { get; set; } + public int RoundScore { get; set; } + public int TotalScore { get; set; } + public Card? PlayedCard { get; set; } + + public static readonly HeartsPlayer Null = new() + { + Id = Guid.Empty, + Name = "Null Player" + }; + + public bool HasCard(Card card) => Cards.Contains(card); + + public bool HasTwoOfClubs() => Cards.Any(c => c.Suit == Suit.Clubs && c.Rank == 2); + + public bool HasOnlySuit(Suit suit) => Cards.All(c => c.Suit == suit); + + public bool HasSuit(Suit suit) => Cards.Any(c => c.Suit == suit); + + public void ClearPlayedCard() => PlayedCard = null; +} diff --git a/src/Deckster.Hearts.SampleClient/Deckster.Hearts.SampleClient.csproj b/src/Deckster.Hearts.SampleClient/Deckster.Hearts.SampleClient.csproj new file mode 100644 index 00000000..769b9f5e --- /dev/null +++ b/src/Deckster.Hearts.SampleClient/Deckster.Hearts.SampleClient.csproj @@ -0,0 +1,16 @@ + + + + Exe + net9.0 + enable + enable + default + + + + + + + + diff --git a/src/Deckster.Hearts.SampleClient/HeartsPoorAi.cs b/src/Deckster.Hearts.SampleClient/HeartsPoorAi.cs new file mode 100644 index 00000000..446509ed --- /dev/null +++ b/src/Deckster.Hearts.SampleClient/HeartsPoorAi.cs @@ -0,0 +1,228 @@ +using Deckster.Client.Games.Hearts; +using Deckster.Client.Logging; +using Deckster.Core.Games.Common; +using Deckster.Core.Games.Hearts; +using Microsoft.Extensions.Logging; + +namespace Deckster.Hearts.SampleClient; + +public class HeartsPoorAi +{ + private readonly ILogger _logger; + private PlayerViewOfGame _view = new(); + private readonly HeartsClient _client; + private readonly TaskCompletionSource _tcs = new(); + + public HeartsPoorAi(HeartsClient client) + { + _client = client; + _logger = Log.Factory.CreateLogger(client.PlayerData.Name); + + client.GameStarted += OnGameStarted; + client.PassingPhaseStarted += OnPassingPhaseStarted; + client.AllPlayersPassed += OnAllPlayersPassed; + client.PlayerPassedCards += OnPlayerPassedCards; + client.ItsYourTurn += OnItsYourTurn; + client.ItsPlayersTurn += OnItsPlayersTurn; + client.PlayerPlayedCard += OnPlayerPlayedCard; + client.TrickCompleted += OnTrickCompleted; + client.RoundEnded += OnRoundEnded; + client.GameEnded += OnGameEnded; + client.HeartsWereBroken += OnHeartsWereBroken; + } + + private void OnGameStarted(GameStartedNotification notification) + { + _logger.LogInformation("Game started. GameId: {id}", notification.GameId); + _view = notification.PlayerViewOfGame; + } + + private void OnPassingPhaseStarted(PassingPhaseStartedNotification notification) + { + _logger.LogInformation("Passing phase started. Direction: {direction}", notification.PassDirection); + } + + private void OnAllPlayersPassed(AllPlayersPassedNotification notification) + { + _logger.LogInformation("All players passed. Received cards: {cards}", string.Join(", ", notification.ReceivedCards)); + // Cards will be updated in the next ItsYourTurn notification + } + + private void OnPlayerPassedCards(PlayerPassedCardsNotification notification) + { + _logger.LogDebug("Player {playerId} passed cards", notification.PlayerId); + } + + private void OnItsPlayersTurn(ItsPlayersTurnNotification notification) + { + _logger.LogDebug("It's player {playerId}'s turn", notification.PlayerId); + } + + private void OnPlayerPlayedCard(PlayerPlayedCardNotification notification) + { + _logger.LogInformation("Player {playerId} played {card}", notification.PlayerId, notification.Card); + } + + private void OnTrickCompleted(TrickCompletedNotification notification) + { + _logger.LogInformation("Trick completed. Winner: {winner} ({points} points)", + notification.WinnerName, notification.Points); + } + + private void OnRoundEnded(RoundEndedNotification notification) + { + _logger.LogInformation("Round ended. Scores:"); + foreach (var score in notification.Scores) + { + _logger.LogInformation(" {name}: Round={round}, Total={total}", + score.PlayerName, score.RoundScore, score.TotalScore); + } + if (notification.MoonShooterId != null) + { + _logger.LogInformation("Moon shot by {shooter}!", notification.MoonShooterName); + } + } + + private void OnGameEnded(GameEndedNotification notification) + { + _logger.LogInformation("Game ended! Winner: {winner}", notification.WinnerName); + _logger.LogInformation("Final scores:"); + foreach (var score in notification.FinalScores) + { + _logger.LogInformation(" {name}: {total}", score.PlayerName, score.TotalScore); + } + _tcs.SetResult(); + } + + private void OnHeartsWereBroken(HeartsAreBrokenNotification notification) + { + _logger.LogInformation("Hearts are broken!"); + } + + private async void OnItsYourTurn(ItsYourTurnNotification notification) + { + try + { + _view = notification.PlayerViewOfGame; + + // Handle passing phase + if (_view.PassDirection != PassDirection.None && !_view.HasPassed) + { + var cardsToPass = ChooseCardsToPass(); + _logger.LogInformation("Passing cards: {cards}", string.Join(", ", cardsToPass)); + await _client.PassCardsAsync(cardsToPass); + return; + } + + // Handle playing phase + if (_view.IsMyTurn) + { + var cardToPlay = ChooseCardToPlay(); + _logger.LogInformation("Playing card: {card}", cardToPlay); + var result = await _client.PlayCardAsync(cardToPlay); + + if (result.HasError) + { + _logger.LogError("Error playing card: {error}", result.Error); + } + } + } + catch (Exception e) + { + _logger.LogError(e, "Error during turn"); + } + } + + private List ChooseCardsToPass() + { + // Simple strategy: pass highest cards, prioritizing high hearts and Queen of Spades + var cards = _view.Cards.ToList(); + var cardsToPass = new List(); + + // Pass Queen of Spades if we have it + var queenOfSpades = cards.Where(c => c.Suit == Suit.Spades && c.Rank == 12).ToList(); + if (queenOfSpades.Any()) + { + cardsToPass.Add(queenOfSpades.First()); + cards.Remove(queenOfSpades.First()); + } + + // Pass highest hearts + var hearts = cards.Where(c => c.Suit == Suit.Hearts).OrderByDescending(c => c.Rank).ToList(); + foreach (var heart in hearts.Take(3 - cardsToPass.Count)) + { + cardsToPass.Add(heart); + cards.Remove(heart); + } + + // Fill with highest remaining cards + while (cardsToPass.Count < 3) + { + var highCard = cards.OrderByDescending(c => c.Rank).First(); + cardsToPass.Add(highCard); + cards.Remove(highCard); + } + + return cardsToPass; + } + + private Card ChooseCardToPlay() + { + var cards = _view.Cards.ToList(); + var currentTrick = _view.CurrentTrick; + + // If leading (first card in trick) + if (currentTrick.Count == 0) + { + // Must lead with 2 of clubs if we have it (first trick) + var twoOfClubs = cards.Where(c => c.Suit == Suit.Clubs && c.Rank == 2).ToList(); + if (twoOfClubs.Any()) + { + return twoOfClubs.First(); + } + + // Try to lead with a safe card (not hearts unless broken, low cards preferred) + var safeCards = cards.Where(c => c.Suit != Suit.Hearts || _view.HeartsAreBroken).ToList(); + if (safeCards.Any()) + { + // Lead with lowest safe card + return safeCards.OrderBy(c => c.Rank).First(); + } + + // If only hearts, lead with lowest heart + return cards.Where(c => c.Suit == Suit.Hearts).OrderBy(c => c.Rank).First(); + } + + // Following suit + var leadSuit = currentTrick[0].Card.Suit; + var sameSuitCards = cards.Where(c => c.Suit == leadSuit).ToList(); + + if (sameSuitCards.Any()) + { + // Play highest card of lead suit (try to avoid winning) + return sameSuitCards.OrderByDescending(c => c.Rank).First(); + } + + // Can't follow suit - try to dump Queen of Spades or high hearts + var queenOfSpades = cards.Where(c => c.Suit == Suit.Spades && c.Rank == 12).ToList(); + if (queenOfSpades.Any()) + { + return queenOfSpades.First(); + } + + var highHearts = cards.Where(c => c.Suit == Suit.Hearts).OrderByDescending(c => c.Rank).ToList(); + if (highHearts.Any()) + { + return highHearts.First(); + } + + // Otherwise, play highest card to get rid of it + return cards.OrderByDescending(c => c.Rank).First(); + } + + public Task PlayAsync(CancellationToken cancellationToken) + { + cancellationToken.Register(_tcs.SetCanceled); + return _tcs.Task; + } +} diff --git a/src/Deckster.Hearts.SampleClient/Program.cs b/src/Deckster.Hearts.SampleClient/Program.cs new file mode 100644 index 00000000..c569a403 --- /dev/null +++ b/src/Deckster.Hearts.SampleClient/Program.cs @@ -0,0 +1,56 @@ +using Deckster.Client; +using Deckster.Client.Games.Hearts; +using Deckster.Client.Logging; +using Microsoft.Extensions.Logging; + +namespace Deckster.Hearts.SampleClient; + +class Program +{ + public static async Task Main(string[] argz) + { + try + { + var logger = Log.Factory.CreateLogger("Hearts"); + const string gameName = "my-hearts-game"; + using var cts = new CancellationTokenSource(); + Console.CancelKeyPress += (s, e) => + { + if (cts.IsCancellationRequested) + { + return; + } + cts.Cancel(); + }; + + var deckster = await DecksterClient.LogInOrRegisterAsync("http://localhost:13992", "Hearts Player", "hest"); + var client = deckster.Hearts(); + logger.LogInformation("Creating game {name}", gameName); + var info = await client.CreateAsync(gameName, cts.Token); + logger.LogInformation("Adding bots"); + + // Hearts needs exactly 4 players, so add 3 bots + for (var ii = 0; ii < 3; ii++) + { + await client.AddBotAsync(gameName, cts.Token); + } + + logger.LogInformation("Joining game {name}", gameName); + await using var game = await client.JoinAsync(gameName, cts.Token); + + logger.LogInformation("Using ai"); + var ai = new HeartsPoorAi(game); + logger.LogInformation("Starting game"); + await client.StartGameAsync(gameName, cts.Token); + logger.LogInformation("Playing game"); + await ai.PlayAsync(cts.Token); + + return 0; + } + catch (Exception e) + { + Console.WriteLine(e); + return 1; + } + } +} diff --git a/src/Deckster.Server/Controllers/HeartsController.cs b/src/Deckster.Server/Controllers/HeartsController.cs new file mode 100644 index 00000000..63905baf --- /dev/null +++ b/src/Deckster.Server/Controllers/HeartsController.cs @@ -0,0 +1,11 @@ +using Deckster.Games.Hearts; +using Deckster.Server.Data; +using Deckster.Server.Games; +using Deckster.Server.Games.Hearts; +using Microsoft.AspNetCore.Mvc; + +namespace Deckster.Server.Controllers; + +[Route("hearts")] +public class HeartsController(GameHostRegistry hostRegistry, IRepo repo) + : GameController(hostRegistry, repo); diff --git a/src/Deckster.Server/Deckster.Server.csproj b/src/Deckster.Server/Deckster.Server.csproj index 3c362230..63647898 100644 --- a/src/Deckster.Server/Deckster.Server.csproj +++ b/src/Deckster.Server/Deckster.Server.csproj @@ -16,6 +16,7 @@ + diff --git a/src/Deckster.Server/Games/DecksterServiceExtensions.cs b/src/Deckster.Server/Games/DecksterServiceExtensions.cs index 6f0c5785..0808fcba 100644 --- a/src/Deckster.Server/Games/DecksterServiceExtensions.cs +++ b/src/Deckster.Server/Games/DecksterServiceExtensions.cs @@ -2,6 +2,7 @@ using Deckster.Server.Games.ChatRoom; using Deckster.Server.Games.CrazyEights; using Deckster.Server.Games.Gabong; +using Deckster.Server.Games.Hearts; using Deckster.Server.Games.Idiot; using Deckster.Server.Games.TexasHoldEm; using Deckster.Server.Games.Uno; @@ -22,6 +23,7 @@ public static IServiceCollection AddDeckster(this IServiceCollection services) services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); return services; } } \ No newline at end of file diff --git a/src/Deckster.Server/Games/GameHost.cs b/src/Deckster.Server/Games/GameHost.cs index 08be9b3d..dffcad33 100644 --- a/src/Deckster.Server/Games/GameHost.cs +++ b/src/Deckster.Server/Games/GameHost.cs @@ -37,7 +37,7 @@ protected GameHost(int? playerLimit) public abstract Task StartAsync(); - public bool TryAddPlayer(IServerChannel channel, [MaybeNullWhen(true)] out string error) + public virtual bool TryAddPlayer(IServerChannel channel, [MaybeNullWhen(true)] out string error) { if (PlayerLimit.HasValue && Players.Count >= PlayerLimit.Value) { diff --git a/src/Deckster.Server/Games/Hearts/HeartsGameHost.cs b/src/Deckster.Server/Games/Hearts/HeartsGameHost.cs new file mode 100644 index 00000000..7c19b18b --- /dev/null +++ b/src/Deckster.Server/Games/Hearts/HeartsGameHost.cs @@ -0,0 +1,89 @@ +using System.Diagnostics.CodeAnalysis; +using Deckster.Client.Games.Hearts; +using Deckster.Core.Games.Common; +using Deckster.Games; +using Deckster.Games.Hearts; +using Deckster.Hearts.SampleClient; +using Deckster.Server.Communication; +using Deckster.Server.Data; +using Deckster.Server.Games.Common.Fakes; + +namespace Deckster.Server.Games.Hearts; + +public class HeartsGameHost : StandardGameHost +{ + public override string GameType => "Hearts"; + + private readonly List _bots = []; + private bool _hasAutoAddedBots = false; + + public HeartsGameHost(IRepo repo, ILoggerFactory loggerFactory) : base(repo, loggerFactory, new HeartsProjection(), 4) + { + } + + public override bool TryAddPlayer(IServerChannel channel, [MaybeNullWhen(true)] out string error) + { + // Call base method to add the player + if (!base.TryAddPlayer(channel, out error)) + { + return false; + } + + Logger.LogInformation("Player {PlayerName} joined. Current player count: {Count}", channel.Player.Name, Players.Count); + + // Auto-add 3 bots when the first human player joins + if (!_hasAutoAddedBots && Players.Count == 1) + { + _hasAutoAddedBots = true; + Logger.LogInformation("First player joined. Auto-adding 3 bots..."); + + for (int i = 0; i < 3; i++) + { + if (TryAddBot(out var botError)) + { + Logger.LogInformation("Bot {Number} added successfully", i + 1); + } + else + { + Logger.LogError("Failed to add bot {Number}: {Error}", i + 1, botError); + } + } + } + + // Auto-start game when we have 4 players + if (Players.Count == 4 && State == GameState.Waiting) + { + Logger.LogInformation("4 players reached. Auto-starting game..."); + _ = Task.Run(async () => + { + try + { + await Task.Delay(1000); // Small delay to ensure all connections are ready + await StartAsync(); + Logger.LogInformation("Game started successfully"); + } + catch (Exception ex) + { + Logger.LogError(ex, "Failed to auto-start game"); + } + }); + } + + return true; + } + + public override bool TryAddBot([MaybeNullWhen(true)] out string error) + { + var channel = new InMemoryChannel + { + Player = new PlayerData + { + Id = Guid.NewGuid(), + Name = TestUserNames.Random() + } + }; + var bot = new HeartsPoorAi(new HeartsClient(channel)); + _bots.Add(bot); + return base.TryAddPlayer(channel, out error); + } +} diff --git a/src/Deckster.Server/Games/Hearts/HeartsProjection.cs b/src/Deckster.Server/Games/Hearts/HeartsProjection.cs new file mode 100644 index 00000000..8a3815ee --- /dev/null +++ b/src/Deckster.Server/Games/Hearts/HeartsProjection.cs @@ -0,0 +1,32 @@ +using Deckster.Core.Games.Hearts; +using Deckster.Games; +using Deckster.Games.Hearts; + +namespace Deckster.Server.Games.Hearts; + +public class HeartsProjection : GameProjection +{ + public HeartsGame Create(HeartsGameCreatedEvent created) + { + var game = HeartsGame.Instantiate(created); + return game; + } + + public override (HeartsGame game, object startEvent) Create(IGameHost host) + { + var startEvent = new HeartsGameCreatedEvent + { + Id = Guid.NewGuid(), + Name = host.Name, + Players = host.GetPlayers(), + Deck = Decks.Standard().KnuthShuffle(new Random().Next(0, int.MaxValue)), + InitialSeed = new Random().Next(0, int.MaxValue), + StartedTime = DateTimeOffset.UtcNow + }; + var game = Create(startEvent); + return (game, startEvent); + } + + public Task Apply(PassCardsRequest @event, HeartsGame game) => game.PassCards(@event); + public Task Apply(PlayCardRequest @event, HeartsGame game) => game.PlayCard(@event); +} diff --git a/src/Deckster.Server/Startup.cs b/src/Deckster.Server/Startup.cs index 11c3df85..1a3999ce 100644 --- a/src/Deckster.Server/Startup.cs +++ b/src/Deckster.Server/Startup.cs @@ -81,8 +81,19 @@ public static void ConfigureServices(IServiceCollection services, DecksterConfig o.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; }); mvc.AddRazorRuntimeCompilation(); - - + + // Add CORS + services.AddCors(options => + { + options.AddPolicy("AllowWebClient", builder => + { + builder.WithOrigins("http://localhost:3000", "http://localhost:3001") + .AllowAnyMethod() + .AllowAnyHeader() + .AllowCredentials(); + }); + }); + services.AddAuthentication(o => { o.DefaultScheme = AuthenticationSchemes.Cookie; @@ -130,8 +141,12 @@ public static void Configure(IApplicationBuilder app) o.DocumentTitle = "Deckster"; o.RoutePrefix = "swagger"; }); - + app.MapExtensionToAcceptHeader(); + + // Enable CORS + app.UseCors("AllowWebClient"); + app.UseAuthentication(); app.LoadUser(); app.UseWebSockets(); diff --git a/src/Deckster.Uno.SampleClient/UnoInteractive.cs b/src/Deckster.Uno.SampleClient/UnoInteractive.cs index ed00bf31..85cd828a 100644 --- a/src/Deckster.Uno.SampleClient/UnoInteractive.cs +++ b/src/Deckster.Uno.SampleClient/UnoInteractive.cs @@ -14,13 +14,13 @@ public UnoInteractive(UnoClient client) { _client = client; client.GameStarted += OnGameStarted; - client.RoundStarted += OnRoundStarted; + // client.RoundStarted += OnRoundStarted; client.ItsYourTurn += OnItsYourTurn; client.PlayerPutCard += OnPlayerPutCard; client.PlayerPutWild += OnPlayerPutWild; client.PlayerDrewCard += OnPlayerDrewCard; client.PlayerPassed += OnPlayerPassed; - client.RoundEnded += OnRoundEnded; + // client.RoundEnded += OnRoundEnded; client.GameEnded += OnGameEnded; } diff --git a/src/Deckster.Uno.SampleClient/UnoPoorAi.cs b/src/Deckster.Uno.SampleClient/UnoPoorAi.cs index b5fa45b7..b36fd938 100644 --- a/src/Deckster.Uno.SampleClient/UnoPoorAi.cs +++ b/src/Deckster.Uno.SampleClient/UnoPoorAi.cs @@ -20,13 +20,13 @@ public UnoPoorAi(UnoClient client) _client = client; _logger = Log.Factory.CreateLogger(client.PlayerData.Name); client.GameStarted += OnGameStarted; - client.RoundStarted += OnRoundStarted; + // client.RoundStarted += OnRoundStarted; client.ItsYourTurn += OnItsYourTurn; client.PlayerPutCard += OnPlayerPutCard; client.PlayerPutWild += OnPlayerPutWild; client.PlayerDrewCard += OnPlayerDrewCard; client.PlayerPassed += OnPlayerPassed; - client.RoundEnded += OnRoundEnded; + // client.RoundEnded += OnRoundEnded; client.GameEnded += OnGameEnded; } diff --git a/src/Deckster.sln b/src/Deckster.sln index f165adb3..69ade46b 100644 --- a/src/Deckster.sln +++ b/src/Deckster.sln @@ -43,6 +43,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Deckster.TexasHoldEm.Sample EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Deckster.Bullshit.SampleClient", "Deckster.Bullshit.SampleClient\Deckster.Bullshit.SampleClient.csproj", "{15FD6712-AFF7-42EC-BBAD-28E23B77107B}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Deckster.Hearts.SampleClient", "Deckster.Hearts.SampleClient\Deckster.Hearts.SampleClient.csproj", "{31419E3F-8EF3-4D76-AD38-F91CB0C67004}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -109,6 +111,10 @@ Global {15FD6712-AFF7-42EC-BBAD-28E23B77107B}.Debug|Any CPU.Build.0 = Debug|Any CPU {15FD6712-AFF7-42EC-BBAD-28E23B77107B}.Release|Any CPU.ActiveCfg = Release|Any CPU {15FD6712-AFF7-42EC-BBAD-28E23B77107B}.Release|Any CPU.Build.0 = Release|Any CPU + {31419E3F-8EF3-4D76-AD38-F91CB0C67004}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {31419E3F-8EF3-4D76-AD38-F91CB0C67004}.Debug|Any CPU.Build.0 = Debug|Any CPU + {31419E3F-8EF3-4D76-AD38-F91CB0C67004}.Release|Any CPU.ActiveCfg = Release|Any CPU + {31419E3F-8EF3-4D76-AD38-F91CB0C67004}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -129,6 +135,7 @@ Global {38F22734-F7CB-4376-BC86-6623F98F45D0} = {E66EE07A-1B20-4842-A77D-5A71F8FD3E0B} {C69EE4FE-3BF2-41F7-A956-E3A270219DD9} = {E66EE07A-1B20-4842-A77D-5A71F8FD3E0B} {15FD6712-AFF7-42EC-BBAD-28E23B77107B} = {E66EE07A-1B20-4842-A77D-5A71F8FD3E0B} + {31419E3F-8EF3-4D76-AD38-F91CB0C67004} = {E66EE07A-1B20-4842-A77D-5A71F8FD3E0B} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {AE622423-92CC-4E60-ADDA-E76DEFF6CB96} diff --git a/web-clients/hearts/README.md b/web-clients/hearts/README.md new file mode 100644 index 00000000..88041e38 --- /dev/null +++ b/web-clients/hearts/README.md @@ -0,0 +1,138 @@ +# Hearts Web Client + +A 3D web-based client for the Hearts card game built with TypeScript, three.js, and Vite. + +## Features + +- 3D card visualization using three.js +- Real-time WebSocket communication with Deckster server +- Interactive card selection and gameplay +- Visual feedback for game events (passing phase, tricks, scoring) +- Responsive UI with game state tracking + +## Prerequisites + +- Node.js (v18 or higher) +- npm +- Running Deckster Hearts server + +## Installation + +```bash +npm install +``` + +## Development + +Start the development server: + +```bash +npm run dev +``` + +This will start Vite dev server on http://localhost:3000 + +## Building for Production + +Build the project: + +```bash +npm run build +``` + +Preview the production build: + +```bash +npm run preview +``` + +The build output will be in the `dist/` directory. + +## How to Play + +1. **Start the Deckster server** (from the root of the Deckster repository): + ```bash + cd src/Deckster.Server + dotnet run + ``` + +2. **Open the web client** in your browser (if using dev server, it should open automatically) + +3. **Enter connection details**: + - Player Name: Your display name + - Game ID: The Hearts game session ID + + Note: The server URL is automatically set to `ws://localhost:13992` and a unique player ID (GUID) is generated automatically. + +4. **Click Connect** to join the game + +5. **Game Flow**: + - **Passing Phase**: Select 3 cards by clicking on them, they will be highlighted + - **Playing Phase**: Click on a card to play it when it's your turn + - Watch the center area for the current trick + - Monitor your score in the top-left panel + +## Project Structure + +``` +hearts/ +├── src/ +│ ├── main.ts # Application entry point +│ ├── game/ +│ │ └── HeartsGame.ts # Game controller and logic +│ ├── graphics/ +│ │ ├── CardScene.ts # three.js scene management +│ │ └── Card3D.ts # 3D card rendering +│ └── ui/ +│ └── GameUI.ts # DOM UI management +├── index.html # HTML template +├── vite.config.ts # Vite configuration +├── tsconfig.json # TypeScript configuration +└── package.json # Dependencies and scripts +``` + +## Technologies Used + +- **TypeScript**: Type-safe development +- **three.js**: 3D graphics rendering +- **Vite**: Fast build tool and dev server +- **WebSocket**: Real-time bidirectional communication +- Generated TypeScript client from Deckster OpenAPI specification + +## Controls + +- **Mouse hover**: Highlights cards in your hand +- **Click**: Select cards (passing phase) or play cards (your turn) +- **Selected cards**: Elevated and highlighted +- Cards can be deselected by clicking again + +## Known Limitations + +- Card graphics are simplified (geometric shapes representing suits) +- Player positions are not fully mapped (all opponent cards appear at same positions) +- Production version would benefit from actual card textures/images + +## Future Enhancements + +- Add card textures with actual rank and suit designs +- Implement proper player position mapping (North, East, South, West) +- Add animation for card dealing and trick collection +- Implement sound effects +- Add chat functionality +- Mobile touch support optimization +- Better error handling and reconnection logic + +## Troubleshooting + +**Cannot connect to server**: +- Ensure the Deckster server is running on port 13992 +- Verify the game ID exists on the server +- Check browser console for connection errors + +**Cards not displaying**: +- Check browser console for errors +- Ensure WebGL is supported in your browser + +**Build errors**: +- Run `npm install` to ensure all dependencies are installed +- Clear node_modules and reinstall if needed: `rm -rf node_modules && npm install` diff --git a/web-clients/hearts/assets/bg.png b/web-clients/hearts/assets/bg.png new file mode 100644 index 00000000..e818ae49 Binary files /dev/null and b/web-clients/hearts/assets/bg.png differ diff --git a/web-clients/hearts/assets/bg_table.png b/web-clients/hearts/assets/bg_table.png new file mode 100644 index 00000000..3f4ad90c Binary files /dev/null and b/web-clients/hearts/assets/bg_table.png differ diff --git a/web-clients/hearts/assets/club/10_club.png b/web-clients/hearts/assets/club/10_club.png new file mode 100644 index 00000000..ddd0692f Binary files /dev/null and b/web-clients/hearts/assets/club/10_club.png differ diff --git a/web-clients/hearts/assets/club/11_club.png b/web-clients/hearts/assets/club/11_club.png new file mode 100644 index 00000000..0b73d5a1 Binary files /dev/null and b/web-clients/hearts/assets/club/11_club.png differ diff --git a/web-clients/hearts/assets/club/12_club.png b/web-clients/hearts/assets/club/12_club.png new file mode 100644 index 00000000..c2e576d1 Binary files /dev/null and b/web-clients/hearts/assets/club/12_club.png differ diff --git a/web-clients/hearts/assets/club/13_club.png b/web-clients/hearts/assets/club/13_club.png new file mode 100644 index 00000000..a5a0da4d Binary files /dev/null and b/web-clients/hearts/assets/club/13_club.png differ diff --git a/web-clients/hearts/assets/club/1_club.png b/web-clients/hearts/assets/club/1_club.png new file mode 100644 index 00000000..f739465b Binary files /dev/null and b/web-clients/hearts/assets/club/1_club.png differ diff --git a/web-clients/hearts/assets/club/2_club.png b/web-clients/hearts/assets/club/2_club.png new file mode 100644 index 00000000..f8648675 Binary files /dev/null and b/web-clients/hearts/assets/club/2_club.png differ diff --git a/web-clients/hearts/assets/club/3_club.png b/web-clients/hearts/assets/club/3_club.png new file mode 100644 index 00000000..c11c5873 Binary files /dev/null and b/web-clients/hearts/assets/club/3_club.png differ diff --git a/web-clients/hearts/assets/club/4_club.png b/web-clients/hearts/assets/club/4_club.png new file mode 100644 index 00000000..91d2782e Binary files /dev/null and b/web-clients/hearts/assets/club/4_club.png differ diff --git a/web-clients/hearts/assets/club/5_club.png b/web-clients/hearts/assets/club/5_club.png new file mode 100644 index 00000000..a7657959 Binary files /dev/null and b/web-clients/hearts/assets/club/5_club.png differ diff --git a/web-clients/hearts/assets/club/6_club.png b/web-clients/hearts/assets/club/6_club.png new file mode 100644 index 00000000..2170ab11 Binary files /dev/null and b/web-clients/hearts/assets/club/6_club.png differ diff --git a/web-clients/hearts/assets/club/7_club.png b/web-clients/hearts/assets/club/7_club.png new file mode 100644 index 00000000..ee8ac0e5 Binary files /dev/null and b/web-clients/hearts/assets/club/7_club.png differ diff --git a/web-clients/hearts/assets/club/8_club.png b/web-clients/hearts/assets/club/8_club.png new file mode 100644 index 00000000..441ae22d Binary files /dev/null and b/web-clients/hearts/assets/club/8_club.png differ diff --git a/web-clients/hearts/assets/club/9_club.png b/web-clients/hearts/assets/club/9_club.png new file mode 100644 index 00000000..bbf9678c Binary files /dev/null and b/web-clients/hearts/assets/club/9_club.png differ diff --git a/web-clients/hearts/assets/diamond/10_diamond.png b/web-clients/hearts/assets/diamond/10_diamond.png new file mode 100644 index 00000000..92ab7b67 Binary files /dev/null and b/web-clients/hearts/assets/diamond/10_diamond.png differ diff --git a/web-clients/hearts/assets/diamond/11_diamond.png b/web-clients/hearts/assets/diamond/11_diamond.png new file mode 100644 index 00000000..cff7e3c5 Binary files /dev/null and b/web-clients/hearts/assets/diamond/11_diamond.png differ diff --git a/web-clients/hearts/assets/diamond/12_diamond.png b/web-clients/hearts/assets/diamond/12_diamond.png new file mode 100644 index 00000000..f4c7d854 Binary files /dev/null and b/web-clients/hearts/assets/diamond/12_diamond.png differ diff --git a/web-clients/hearts/assets/diamond/13_diamond.png b/web-clients/hearts/assets/diamond/13_diamond.png new file mode 100644 index 00000000..b6426402 Binary files /dev/null and b/web-clients/hearts/assets/diamond/13_diamond.png differ diff --git a/web-clients/hearts/assets/diamond/1_diamond.png b/web-clients/hearts/assets/diamond/1_diamond.png new file mode 100644 index 00000000..50712b20 Binary files /dev/null and b/web-clients/hearts/assets/diamond/1_diamond.png differ diff --git a/web-clients/hearts/assets/diamond/2_diamond.png b/web-clients/hearts/assets/diamond/2_diamond.png new file mode 100644 index 00000000..d3e911dc Binary files /dev/null and b/web-clients/hearts/assets/diamond/2_diamond.png differ diff --git a/web-clients/hearts/assets/diamond/3_diamond.png b/web-clients/hearts/assets/diamond/3_diamond.png new file mode 100644 index 00000000..6d596c52 Binary files /dev/null and b/web-clients/hearts/assets/diamond/3_diamond.png differ diff --git a/web-clients/hearts/assets/diamond/4_diamond.png b/web-clients/hearts/assets/diamond/4_diamond.png new file mode 100644 index 00000000..e6f44bb2 Binary files /dev/null and b/web-clients/hearts/assets/diamond/4_diamond.png differ diff --git a/web-clients/hearts/assets/diamond/5_diamond.png b/web-clients/hearts/assets/diamond/5_diamond.png new file mode 100644 index 00000000..fbc0c39f Binary files /dev/null and b/web-clients/hearts/assets/diamond/5_diamond.png differ diff --git a/web-clients/hearts/assets/diamond/6_diamond.png b/web-clients/hearts/assets/diamond/6_diamond.png new file mode 100644 index 00000000..55511e20 Binary files /dev/null and b/web-clients/hearts/assets/diamond/6_diamond.png differ diff --git a/web-clients/hearts/assets/diamond/7_diamond.png b/web-clients/hearts/assets/diamond/7_diamond.png new file mode 100644 index 00000000..8528daa9 Binary files /dev/null and b/web-clients/hearts/assets/diamond/7_diamond.png differ diff --git a/web-clients/hearts/assets/diamond/8_diamond.png b/web-clients/hearts/assets/diamond/8_diamond.png new file mode 100644 index 00000000..5d7b3af3 Binary files /dev/null and b/web-clients/hearts/assets/diamond/8_diamond.png differ diff --git a/web-clients/hearts/assets/diamond/9_diamond.png b/web-clients/hearts/assets/diamond/9_diamond.png new file mode 100644 index 00000000..52ed6c54 Binary files /dev/null and b/web-clients/hearts/assets/diamond/9_diamond.png differ diff --git a/web-clients/hearts/assets/heart/10_heart.png b/web-clients/hearts/assets/heart/10_heart.png new file mode 100644 index 00000000..0a8623f7 Binary files /dev/null and b/web-clients/hearts/assets/heart/10_heart.png differ diff --git a/web-clients/hearts/assets/heart/11_heart.png b/web-clients/hearts/assets/heart/11_heart.png new file mode 100644 index 00000000..cd5778a1 Binary files /dev/null and b/web-clients/hearts/assets/heart/11_heart.png differ diff --git a/web-clients/hearts/assets/heart/12_heart.png b/web-clients/hearts/assets/heart/12_heart.png new file mode 100644 index 00000000..cc015d2d Binary files /dev/null and b/web-clients/hearts/assets/heart/12_heart.png differ diff --git a/web-clients/hearts/assets/heart/13_heart.png b/web-clients/hearts/assets/heart/13_heart.png new file mode 100644 index 00000000..96ea5c87 Binary files /dev/null and b/web-clients/hearts/assets/heart/13_heart.png differ diff --git a/web-clients/hearts/assets/heart/1_heart.png b/web-clients/hearts/assets/heart/1_heart.png new file mode 100644 index 00000000..6773ef45 Binary files /dev/null and b/web-clients/hearts/assets/heart/1_heart.png differ diff --git a/web-clients/hearts/assets/heart/2_heart.png b/web-clients/hearts/assets/heart/2_heart.png new file mode 100644 index 00000000..0d8be749 Binary files /dev/null and b/web-clients/hearts/assets/heart/2_heart.png differ diff --git a/web-clients/hearts/assets/heart/3_heart.png b/web-clients/hearts/assets/heart/3_heart.png new file mode 100644 index 00000000..5f9df240 Binary files /dev/null and b/web-clients/hearts/assets/heart/3_heart.png differ diff --git a/web-clients/hearts/assets/heart/4_heart.png b/web-clients/hearts/assets/heart/4_heart.png new file mode 100644 index 00000000..1813a6b0 Binary files /dev/null and b/web-clients/hearts/assets/heart/4_heart.png differ diff --git a/web-clients/hearts/assets/heart/5_heart.png b/web-clients/hearts/assets/heart/5_heart.png new file mode 100644 index 00000000..fcbddfba Binary files /dev/null and b/web-clients/hearts/assets/heart/5_heart.png differ diff --git a/web-clients/hearts/assets/heart/6_heart.png b/web-clients/hearts/assets/heart/6_heart.png new file mode 100644 index 00000000..f324522e Binary files /dev/null and b/web-clients/hearts/assets/heart/6_heart.png differ diff --git a/web-clients/hearts/assets/heart/7_heart.png b/web-clients/hearts/assets/heart/7_heart.png new file mode 100644 index 00000000..9519b450 Binary files /dev/null and b/web-clients/hearts/assets/heart/7_heart.png differ diff --git a/web-clients/hearts/assets/heart/8_heart.png b/web-clients/hearts/assets/heart/8_heart.png new file mode 100644 index 00000000..b7d2e474 Binary files /dev/null and b/web-clients/hearts/assets/heart/8_heart.png differ diff --git a/web-clients/hearts/assets/heart/9_heart.png b/web-clients/hearts/assets/heart/9_heart.png new file mode 100644 index 00000000..a6cf5600 Binary files /dev/null and b/web-clients/hearts/assets/heart/9_heart.png differ diff --git a/web-clients/hearts/assets/spade/10_spade.png b/web-clients/hearts/assets/spade/10_spade.png new file mode 100644 index 00000000..b00c992a Binary files /dev/null and b/web-clients/hearts/assets/spade/10_spade.png differ diff --git a/web-clients/hearts/assets/spade/11_spade.png b/web-clients/hearts/assets/spade/11_spade.png new file mode 100644 index 00000000..76460e8c Binary files /dev/null and b/web-clients/hearts/assets/spade/11_spade.png differ diff --git a/web-clients/hearts/assets/spade/12_spade.png b/web-clients/hearts/assets/spade/12_spade.png new file mode 100644 index 00000000..830d2143 Binary files /dev/null and b/web-clients/hearts/assets/spade/12_spade.png differ diff --git a/web-clients/hearts/assets/spade/13_spade.png b/web-clients/hearts/assets/spade/13_spade.png new file mode 100644 index 00000000..4f211073 Binary files /dev/null and b/web-clients/hearts/assets/spade/13_spade.png differ diff --git a/web-clients/hearts/assets/spade/1_spade.png b/web-clients/hearts/assets/spade/1_spade.png new file mode 100644 index 00000000..a639259f Binary files /dev/null and b/web-clients/hearts/assets/spade/1_spade.png differ diff --git a/web-clients/hearts/assets/spade/2_spade.png b/web-clients/hearts/assets/spade/2_spade.png new file mode 100644 index 00000000..537c4238 Binary files /dev/null and b/web-clients/hearts/assets/spade/2_spade.png differ diff --git a/web-clients/hearts/assets/spade/3_spade.png b/web-clients/hearts/assets/spade/3_spade.png new file mode 100644 index 00000000..0e81ef23 Binary files /dev/null and b/web-clients/hearts/assets/spade/3_spade.png differ diff --git a/web-clients/hearts/assets/spade/4_spade.png b/web-clients/hearts/assets/spade/4_spade.png new file mode 100644 index 00000000..e4385924 Binary files /dev/null and b/web-clients/hearts/assets/spade/4_spade.png differ diff --git a/web-clients/hearts/assets/spade/5_spade.png b/web-clients/hearts/assets/spade/5_spade.png new file mode 100644 index 00000000..2660e357 Binary files /dev/null and b/web-clients/hearts/assets/spade/5_spade.png differ diff --git a/web-clients/hearts/assets/spade/6_spade.png b/web-clients/hearts/assets/spade/6_spade.png new file mode 100644 index 00000000..04ead765 Binary files /dev/null and b/web-clients/hearts/assets/spade/6_spade.png differ diff --git a/web-clients/hearts/assets/spade/7_spade.png b/web-clients/hearts/assets/spade/7_spade.png new file mode 100644 index 00000000..804216c1 Binary files /dev/null and b/web-clients/hearts/assets/spade/7_spade.png differ diff --git a/web-clients/hearts/assets/spade/8_spade.png b/web-clients/hearts/assets/spade/8_spade.png new file mode 100644 index 00000000..2362b0c4 Binary files /dev/null and b/web-clients/hearts/assets/spade/8_spade.png differ diff --git a/web-clients/hearts/assets/spade/9_spade.png b/web-clients/hearts/assets/spade/9_spade.png new file mode 100644 index 00000000..26dec16c Binary files /dev/null and b/web-clients/hearts/assets/spade/9_spade.png differ diff --git a/web-clients/hearts/dist/assets/index-AWEoIZL7.js b/web-clients/hearts/dist/assets/index-AWEoIZL7.js new file mode 100644 index 00000000..c752def0 --- /dev/null +++ b/web-clients/hearts/dist/assets/index-AWEoIZL7.js @@ -0,0 +1,3845 @@ +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))n(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const a of s.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&n(a)}).observe(document,{childList:!0,subtree:!0});function t(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function n(r){if(r.ep)return;r.ep=!0;const s=t(r);fetch(r.href,s)}})();/** + * @license + * Copyright 2010-2025 Three.js Authors + * SPDX-License-Identifier: MIT + */const Ls="180",Go=0,ea=1,ko=2,to=1,Vo=2,en=3,mn=0,Et=1,Bt=2,fn=0,Jn=1,ta=2,na=3,ia=4,Wo=5,wn=100,Xo=101,qo=102,Yo=103,$o=104,Ko=200,Zo=201,jo=202,Jo=203,Vr=204,Wr=205,Qo=206,el=207,tl=208,nl=209,il=210,rl=211,sl=212,al=213,ol=214,Xr=0,qr=1,Yr=2,ei=3,$r=4,Kr=5,Zr=6,jr=7,no=0,ll=1,cl=2,pn=0,ul=1,hl=2,dl=3,fl=4,pl=5,ml=6,gl=7,io=300,ti=301,ni=302,Jr=303,Qr=304,ar=306,Cn=1e3,Pn=1001,es=1002,Gt=1003,_l=1004,Di=1005,Ut=1006,ur=1007,Dn=1008,qt=1009,ro=1010,so=1011,_i=1012,Is=1013,Ln=1014,nn=1015,yi=1016,Us=1017,Ns=1018,vi=1020,ao=35902,oo=35899,lo=1021,co=1022,zt=1023,xi=1026,Mi=1027,uo=1028,Fs=1029,ho=1030,Os=1031,Bs=1033,Ji=33776,Qi=33777,er=33778,tr=33779,ts=35840,ns=35841,is=35842,rs=35843,ss=36196,as=37492,os=37496,ls=37808,cs=37809,us=37810,hs=37811,ds=37812,fs=37813,ps=37814,ms=37815,gs=37816,_s=37817,vs=37818,xs=37819,Ms=37820,Ss=37821,Es=36492,ys=36494,Ts=36495,As=36283,bs=36284,ws=36285,Rs=36286,vl=3200,xl=3201,fo=0,Ml=1,dn="",Lt="srgb",ii="srgb-linear",rr="linear",Ye="srgb",Nn=7680,ra=519,Sl=512,El=513,yl=514,po=515,Tl=516,Al=517,bl=518,wl=519,sa=35044,aa="300 es",Wt=2e3,sr=2001;class si{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){const n=this._listeners;return n===void 0?!1:n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){const n=this._listeners;if(n===void 0)return;const r=n[e];if(r!==void 0){const s=r.indexOf(t);s!==-1&&r.splice(s,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const n=t[e.type];if(n!==void 0){e.target=this;const r=n.slice(0);for(let s=0,a=r.length;s>8&255]+pt[i>>16&255]+pt[i>>24&255]+"-"+pt[e&255]+pt[e>>8&255]+"-"+pt[e>>16&15|64]+pt[e>>24&255]+"-"+pt[t&63|128]+pt[t>>8&255]+"-"+pt[t>>16&255]+pt[t>>24&255]+pt[n&255]+pt[n>>8&255]+pt[n>>16&255]+pt[n>>24&255]).toLowerCase()}function He(i,e,t){return Math.max(e,Math.min(t,i))}function Rl(i,e){return(i%e+e)%e}function dr(i,e,t){return(1-t)*i+t*e}function ci(i,e){switch(e.constructor){case Float32Array:return i;case Uint32Array:return i/4294967295;case Uint16Array:return i/65535;case Uint8Array:return i/255;case Int32Array:return Math.max(i/2147483647,-1);case Int16Array:return Math.max(i/32767,-1);case Int8Array:return Math.max(i/127,-1);default:throw new Error("Invalid component type.")}}function St(i,e){switch(e.constructor){case Float32Array:return i;case Uint32Array:return Math.round(i*4294967295);case Uint16Array:return Math.round(i*65535);case Uint8Array:return Math.round(i*255);case Int32Array:return Math.round(i*2147483647);case Int16Array:return Math.round(i*32767);case Int8Array:return Math.round(i*127);default:throw new Error("Invalid component type.")}}class Ge{constructor(e=0,t=0){Ge.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,n=this.y,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6],this.y=r[1]*t+r[4]*n+r[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=He(this.x,e.x,t.x),this.y=He(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=He(this.x,e,t),this.y=He(this.y,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(He(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(He(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const n=Math.cos(t),r=Math.sin(t),s=this.x-e.x,a=this.y-e.y;return this.x=s*n-a*r+e.x,this.y=s*r+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Ai{constructor(e=0,t=0,n=0,r=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=r}static slerpFlat(e,t,n,r,s,a,o){let c=n[r+0],l=n[r+1],h=n[r+2],d=n[r+3];const f=s[a+0],m=s[a+1],_=s[a+2],x=s[a+3];if(o===0){e[t+0]=c,e[t+1]=l,e[t+2]=h,e[t+3]=d;return}if(o===1){e[t+0]=f,e[t+1]=m,e[t+2]=_,e[t+3]=x;return}if(d!==x||c!==f||l!==m||h!==_){let p=1-o;const u=c*f+l*m+h*_+d*x,b=u>=0?1:-1,A=1-u*u;if(A>Number.EPSILON){const D=Math.sqrt(A),R=Math.atan2(D,u*b);p=Math.sin(p*R)/D,o=Math.sin(o*R)/D}const E=o*b;if(c=c*p+f*E,l=l*p+m*E,h=h*p+_*E,d=d*p+x*E,p===1-o){const D=1/Math.sqrt(c*c+l*l+h*h+d*d);c*=D,l*=D,h*=D,d*=D}}e[t]=c,e[t+1]=l,e[t+2]=h,e[t+3]=d}static multiplyQuaternionsFlat(e,t,n,r,s,a){const o=n[r],c=n[r+1],l=n[r+2],h=n[r+3],d=s[a],f=s[a+1],m=s[a+2],_=s[a+3];return e[t]=o*_+h*d+c*m-l*f,e[t+1]=c*_+h*f+l*d-o*m,e[t+2]=l*_+h*m+o*f-c*d,e[t+3]=h*_-o*d-c*f-l*m,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,r){return this._x=e,this._y=t,this._z=n,this._w=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const n=e._x,r=e._y,s=e._z,a=e._order,o=Math.cos,c=Math.sin,l=o(n/2),h=o(r/2),d=o(s/2),f=c(n/2),m=c(r/2),_=c(s/2);switch(a){case"XYZ":this._x=f*h*d+l*m*_,this._y=l*m*d-f*h*_,this._z=l*h*_+f*m*d,this._w=l*h*d-f*m*_;break;case"YXZ":this._x=f*h*d+l*m*_,this._y=l*m*d-f*h*_,this._z=l*h*_-f*m*d,this._w=l*h*d+f*m*_;break;case"ZXY":this._x=f*h*d-l*m*_,this._y=l*m*d+f*h*_,this._z=l*h*_+f*m*d,this._w=l*h*d-f*m*_;break;case"ZYX":this._x=f*h*d-l*m*_,this._y=l*m*d+f*h*_,this._z=l*h*_-f*m*d,this._w=l*h*d+f*m*_;break;case"YZX":this._x=f*h*d+l*m*_,this._y=l*m*d+f*h*_,this._z=l*h*_-f*m*d,this._w=l*h*d-f*m*_;break;case"XZY":this._x=f*h*d-l*m*_,this._y=l*m*d-f*h*_,this._z=l*h*_+f*m*d,this._w=l*h*d+f*m*_;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const n=t/2,r=Math.sin(n);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,n=t[0],r=t[4],s=t[8],a=t[1],o=t[5],c=t[9],l=t[2],h=t[6],d=t[10],f=n+o+d;if(f>0){const m=.5/Math.sqrt(f+1);this._w=.25/m,this._x=(h-c)*m,this._y=(s-l)*m,this._z=(a-r)*m}else if(n>o&&n>d){const m=2*Math.sqrt(1+n-o-d);this._w=(h-c)/m,this._x=.25*m,this._y=(r+a)/m,this._z=(s+l)/m}else if(o>d){const m=2*Math.sqrt(1+o-n-d);this._w=(s-l)/m,this._x=(r+a)/m,this._y=.25*m,this._z=(c+h)/m}else{const m=2*Math.sqrt(1+d-n-o);this._w=(a-r)/m,this._x=(s+l)/m,this._y=(c+h)/m,this._z=.25*m}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(He(this.dot(e),-1,1)))}rotateTowards(e,t){const n=this.angleTo(e);if(n===0)return this;const r=Math.min(1,t/n);return this.slerp(e,r),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const n=e._x,r=e._y,s=e._z,a=e._w,o=t._x,c=t._y,l=t._z,h=t._w;return this._x=n*h+a*o+r*l-s*c,this._y=r*h+a*c+s*o-n*l,this._z=s*h+a*l+n*c-r*o,this._w=a*h-n*o-r*c-s*l,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);const n=this._x,r=this._y,s=this._z,a=this._w;let o=a*e._w+n*e._x+r*e._y+s*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=a,this._x=n,this._y=r,this._z=s,this;const c=1-o*o;if(c<=Number.EPSILON){const m=1-t;return this._w=m*a+t*this._w,this._x=m*n+t*this._x,this._y=m*r+t*this._y,this._z=m*s+t*this._z,this.normalize(),this}const l=Math.sqrt(c),h=Math.atan2(l,o),d=Math.sin((1-t)*h)/l,f=Math.sin(t*h)/l;return this._w=a*d+this._w*f,this._x=n*d+this._x*f,this._y=r*d+this._y*f,this._z=s*d+this._z*f,this._onChangeCallback(),this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),r=Math.sqrt(1-n),s=Math.sqrt(n);return this.set(r*Math.sin(e),r*Math.cos(e),s*Math.sin(t),s*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class F{constructor(e=0,t=0,n=0){F.prototype.isVector3=!0,this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(oa.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(oa.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,n=this.y,r=this.z,s=e.elements;return this.x=s[0]*t+s[3]*n+s[6]*r,this.y=s[1]*t+s[4]*n+s[7]*r,this.z=s[2]*t+s[5]*n+s[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,n=this.y,r=this.z,s=e.elements,a=1/(s[3]*t+s[7]*n+s[11]*r+s[15]);return this.x=(s[0]*t+s[4]*n+s[8]*r+s[12])*a,this.y=(s[1]*t+s[5]*n+s[9]*r+s[13])*a,this.z=(s[2]*t+s[6]*n+s[10]*r+s[14])*a,this}applyQuaternion(e){const t=this.x,n=this.y,r=this.z,s=e.x,a=e.y,o=e.z,c=e.w,l=2*(a*r-o*n),h=2*(o*t-s*r),d=2*(s*n-a*t);return this.x=t+c*l+a*d-o*h,this.y=n+c*h+o*l-s*d,this.z=r+c*d+s*h-a*l,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,n=this.y,r=this.z,s=e.elements;return this.x=s[0]*t+s[4]*n+s[8]*r,this.y=s[1]*t+s[5]*n+s[9]*r,this.z=s[2]*t+s[6]*n+s[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=He(this.x,e.x,t.x),this.y=He(this.y,e.y,t.y),this.z=He(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=He(this.x,e,t),this.y=He(this.y,e,t),this.z=He(this.z,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(He(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const n=e.x,r=e.y,s=e.z,a=t.x,o=t.y,c=t.z;return this.x=r*c-s*o,this.y=s*a-n*c,this.z=n*o-r*a,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return fr.copy(this).projectOnVector(e),this.sub(fr)}reflect(e){return this.sub(fr.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(He(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y,r=this.z-e.z;return t*t+n*n+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){const r=Math.sin(t)*e;return this.x=r*Math.sin(n),this.y=Math.cos(t)*e,this.z=r*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const fr=new F,oa=new Ai;class Ie{constructor(e,t,n,r,s,a,o,c,l){Ie.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,r,s,a,o,c,l)}set(e,t,n,r,s,a,o,c,l){const h=this.elements;return h[0]=e,h[1]=r,h[2]=o,h[3]=t,h[4]=s,h[5]=c,h[6]=n,h[7]=a,h[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,r=t.elements,s=this.elements,a=n[0],o=n[3],c=n[6],l=n[1],h=n[4],d=n[7],f=n[2],m=n[5],_=n[8],x=r[0],p=r[3],u=r[6],b=r[1],A=r[4],E=r[7],D=r[2],R=r[5],w=r[8];return s[0]=a*x+o*b+c*D,s[3]=a*p+o*A+c*R,s[6]=a*u+o*E+c*w,s[1]=l*x+h*b+d*D,s[4]=l*p+h*A+d*R,s[7]=l*u+h*E+d*w,s[2]=f*x+m*b+_*D,s[5]=f*p+m*A+_*R,s[8]=f*u+m*E+_*w,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[1],r=e[2],s=e[3],a=e[4],o=e[5],c=e[6],l=e[7],h=e[8];return t*a*h-t*o*l-n*s*h+n*o*c+r*s*l-r*a*c}invert(){const e=this.elements,t=e[0],n=e[1],r=e[2],s=e[3],a=e[4],o=e[5],c=e[6],l=e[7],h=e[8],d=h*a-o*l,f=o*c-h*s,m=l*s-a*c,_=t*d+n*f+r*m;if(_===0)return this.set(0,0,0,0,0,0,0,0,0);const x=1/_;return e[0]=d*x,e[1]=(r*l-h*n)*x,e[2]=(o*n-r*a)*x,e[3]=f*x,e[4]=(h*t-r*c)*x,e[5]=(r*s-o*t)*x,e[6]=m*x,e[7]=(n*c-l*t)*x,e[8]=(a*t-n*s)*x,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,r,s,a,o){const c=Math.cos(s),l=Math.sin(s);return this.set(n*c,n*l,-n*(c*a+l*o)+a+e,-r*l,r*c,-r*(-l*a+c*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(pr.makeScale(e,t)),this}rotate(e){return this.premultiply(pr.makeRotation(-e)),this}translate(e,t){return this.premultiply(pr.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,n=e.elements;for(let r=0;r<9;r++)if(t[r]!==n[r])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const pr=new Ie;function mo(i){for(let e=i.length-1;e>=0;--e)if(i[e]>=65535)return!0;return!1}function Si(i){return document.createElementNS("http://www.w3.org/1999/xhtml",i)}function Cl(){const i=Si("canvas");return i.style.display="block",i}const la={};function Ei(i){i in la||(la[i]=!0,console.warn(i))}function Pl(i,e,t){return new Promise(function(n,r){function s(){switch(i.clientWaitSync(e,i.SYNC_FLUSH_COMMANDS_BIT,0)){case i.WAIT_FAILED:r();break;case i.TIMEOUT_EXPIRED:setTimeout(s,t);break;default:n()}}setTimeout(s,t)})}const ca=new Ie().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),ua=new Ie().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Dl(){const i={enabled:!0,workingColorSpace:ii,spaces:{},convert:function(r,s,a){return this.enabled===!1||s===a||!s||!a||(this.spaces[s].transfer===Ye&&(r.r=rn(r.r),r.g=rn(r.g),r.b=rn(r.b)),this.spaces[s].primaries!==this.spaces[a].primaries&&(r.applyMatrix3(this.spaces[s].toXYZ),r.applyMatrix3(this.spaces[a].fromXYZ)),this.spaces[a].transfer===Ye&&(r.r=Qn(r.r),r.g=Qn(r.g),r.b=Qn(r.b))),r},workingToColorSpace:function(r,s){return this.convert(r,this.workingColorSpace,s)},colorSpaceToWorking:function(r,s){return this.convert(r,s,this.workingColorSpace)},getPrimaries:function(r){return this.spaces[r].primaries},getTransfer:function(r){return r===dn?rr:this.spaces[r].transfer},getToneMappingMode:function(r){return this.spaces[r].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(r,s=this.workingColorSpace){return r.fromArray(this.spaces[s].luminanceCoefficients)},define:function(r){Object.assign(this.spaces,r)},_getMatrix:function(r,s,a){return r.copy(this.spaces[s].toXYZ).multiply(this.spaces[a].fromXYZ)},_getDrawingBufferColorSpace:function(r){return this.spaces[r].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(r=this.workingColorSpace){return this.spaces[r].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(r,s){return Ei("THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),i.workingToColorSpace(r,s)},toWorkingColorSpace:function(r,s){return Ei("THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),i.colorSpaceToWorking(r,s)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],n=[.3127,.329];return i.define({[ii]:{primaries:e,whitePoint:n,transfer:rr,toXYZ:ca,fromXYZ:ua,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:Lt},outputColorSpaceConfig:{drawingBufferColorSpace:Lt}},[Lt]:{primaries:e,whitePoint:n,transfer:Ye,toXYZ:ca,fromXYZ:ua,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:Lt}}}),i}const Ve=Dl();function rn(i){return i<.04045?i*.0773993808:Math.pow(i*.9478672986+.0521327014,2.4)}function Qn(i){return i<.0031308?i*12.92:1.055*Math.pow(i,.41666)-.055}let Fn;class Ll{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{Fn===void 0&&(Fn=Si("canvas")),Fn.width=e.width,Fn.height=e.height;const r=Fn.getContext("2d");e instanceof ImageData?r.putImageData(e,0,0):r.drawImage(e,0,0,e.width,e.height),n=Fn}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=Si("canvas");t.width=e.width,t.height=e.height;const n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);const r=n.getImageData(0,0,e.width,e.height),s=r.data;for(let a=0;a1),this.pmremVersion=0}get width(){return this.source.getSize(gr).x}get height(){return this.source.getSize(gr).y}get depth(){return this.source.getSize(gr).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const n=e[t];if(n===void 0){console.warn(`THREE.Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const r=this[t];if(r===void 0){console.warn(`THREE.Texture.setValues(): property '${t}' does not exist.`);continue}r&&n&&r.isVector2&&n.isVector2||r&&n&&r.isVector3&&n.isVector3||r&&n&&r.isMatrix3&&n.isMatrix3?r.copy(n):this[t]=n}}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const n={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==io)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Cn:e.x=e.x-Math.floor(e.x);break;case Pn:e.x=e.x<0?0:1;break;case es:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case Cn:e.y=e.y-Math.floor(e.y);break;case Pn:e.y=e.y<0?0:1;break;case es:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}xt.DEFAULT_IMAGE=null;xt.DEFAULT_MAPPING=io;xt.DEFAULT_ANISOTROPY=1;class rt{constructor(e=0,t=0,n=0,r=1){rt.prototype.isVector4=!0,this.x=e,this.y=t,this.z=n,this.w=r}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,r){return this.x=e,this.y=t,this.z=n,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,n=this.y,r=this.z,s=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*r+a[12]*s,this.y=a[1]*t+a[5]*n+a[9]*r+a[13]*s,this.z=a[2]*t+a[6]*n+a[10]*r+a[14]*s,this.w=a[3]*t+a[7]*n+a[11]*r+a[15]*s,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,r,s;const c=e.elements,l=c[0],h=c[4],d=c[8],f=c[1],m=c[5],_=c[9],x=c[2],p=c[6],u=c[10];if(Math.abs(h-f)<.01&&Math.abs(d-x)<.01&&Math.abs(_-p)<.01){if(Math.abs(h+f)<.1&&Math.abs(d+x)<.1&&Math.abs(_+p)<.1&&Math.abs(l+m+u-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const A=(l+1)/2,E=(m+1)/2,D=(u+1)/2,R=(h+f)/4,w=(d+x)/4,U=(_+p)/4;return A>E&&A>D?A<.01?(n=0,r=.707106781,s=.707106781):(n=Math.sqrt(A),r=R/n,s=w/n):E>D?E<.01?(n=.707106781,r=0,s=.707106781):(r=Math.sqrt(E),n=R/r,s=U/r):D<.01?(n=.707106781,r=.707106781,s=0):(s=Math.sqrt(D),n=w/s,r=U/s),this.set(n,r,s,t),this}let b=Math.sqrt((p-_)*(p-_)+(d-x)*(d-x)+(f-h)*(f-h));return Math.abs(b)<.001&&(b=1),this.x=(p-_)/b,this.y=(d-x)/b,this.z=(f-h)/b,this.w=Math.acos((l+m+u-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=He(this.x,e.x,t.x),this.y=He(this.y,e.y,t.y),this.z=He(this.z,e.z,t.z),this.w=He(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=He(this.x,e,t),this.y=He(this.y,e,t),this.z=He(this.z,e,t),this.w=He(this.w,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(He(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class Nl extends si{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Ut,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new rt(0,0,e,t),this.scissorTest=!1,this.viewport=new rt(0,0,e,t);const r={width:e,height:t,depth:n.depth},s=new xt(r);this.textures=[];const a=n.count;for(let o=0;o1;this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Nt),Nt.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(ui),Ii.subVectors(this.max,ui),On.subVectors(e.a,ui),Bn.subVectors(e.b,ui),Hn.subVectors(e.c,ui),an.subVectors(Bn,On),on.subVectors(Hn,Bn),xn.subVectors(On,Hn);let t=[0,-an.z,an.y,0,-on.z,on.y,0,-xn.z,xn.y,an.z,0,-an.x,on.z,0,-on.x,xn.z,0,-xn.x,-an.y,an.x,0,-on.y,on.x,0,-xn.y,xn.x,0];return!_r(t,On,Bn,Hn,Ii)||(t=[1,0,0,0,1,0,0,0,1],!_r(t,On,Bn,Hn,Ii))?!1:(Ui.crossVectors(an,on),t=[Ui.x,Ui.y,Ui.z],_r(t,On,Bn,Hn,Ii))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Nt).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Nt).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(Kt[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Kt[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Kt[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Kt[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Kt[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Kt[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Kt[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Kt[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Kt),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}}const Kt=[new F,new F,new F,new F,new F,new F,new F,new F],Nt=new F,Li=new bi,On=new F,Bn=new F,Hn=new F,an=new F,on=new F,xn=new F,ui=new F,Ii=new F,Ui=new F,Mn=new F;function _r(i,e,t,n,r){for(let s=0,a=i.length-3;s<=a;s+=3){Mn.fromArray(i,s);const o=r.x*Math.abs(Mn.x)+r.y*Math.abs(Mn.y)+r.z*Math.abs(Mn.z),c=e.dot(Mn),l=t.dot(Mn),h=n.dot(Mn);if(Math.max(-Math.max(c,l,h),Math.min(c,l,h))>o)return!1}return!0}const Ol=new bi,hi=new F,vr=new F;class zs{constructor(e=new F,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const n=this.center;t!==void 0?n.copy(t):Ol.setFromPoints(e).getCenter(n);let r=0;for(let s=0,a=e.length;sthis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;hi.subVectors(e,this.center);const t=hi.lengthSq();if(t>this.radius*this.radius){const n=Math.sqrt(t),r=(n-this.radius)*.5;this.center.addScaledVector(hi,r/n),this.radius+=r}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(vr.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(hi.copy(e.center).add(vr)),this.expandByPoint(hi.copy(e.center).sub(vr))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}const Zt=new F,xr=new F,Ni=new F,ln=new F,Mr=new F,Fi=new F,Sr=new F;class _o{constructor(e=new F,t=new F(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,Zt)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Zt.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Zt.copy(this.origin).addScaledVector(this.direction,t),Zt.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){xr.copy(e).add(t).multiplyScalar(.5),Ni.copy(t).sub(e).normalize(),ln.copy(this.origin).sub(xr);const s=e.distanceTo(t)*.5,a=-this.direction.dot(Ni),o=ln.dot(this.direction),c=-ln.dot(Ni),l=ln.lengthSq(),h=Math.abs(1-a*a);let d,f,m,_;if(h>0)if(d=a*c-o,f=a*o-c,_=s*h,d>=0)if(f>=-_)if(f<=_){const x=1/h;d*=x,f*=x,m=d*(d+a*f+2*o)+f*(a*d+f+2*c)+l}else f=s,d=Math.max(0,-(a*f+o)),m=-d*d+f*(f+2*c)+l;else f=-s,d=Math.max(0,-(a*f+o)),m=-d*d+f*(f+2*c)+l;else f<=-_?(d=Math.max(0,-(-a*s+o)),f=d>0?-s:Math.min(Math.max(-s,-c),s),m=-d*d+f*(f+2*c)+l):f<=_?(d=0,f=Math.min(Math.max(-s,-c),s),m=f*(f+2*c)+l):(d=Math.max(0,-(a*s+o)),f=d>0?s:Math.min(Math.max(-s,-c),s),m=-d*d+f*(f+2*c)+l);else f=a>0?-s:s,d=Math.max(0,-(a*f+o)),m=-d*d+f*(f+2*c)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,d),r&&r.copy(xr).addScaledVector(Ni,f),m}intersectSphere(e,t){Zt.subVectors(e.center,this.origin);const n=Zt.dot(this.direction),r=Zt.dot(Zt)-n*n,s=e.radius*e.radius;if(r>s)return null;const a=Math.sqrt(s-r),o=n-a,c=n+a;return c<0?null:o<0?this.at(c,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){const n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,r,s,a,o,c;const l=1/this.direction.x,h=1/this.direction.y,d=1/this.direction.z,f=this.origin;return l>=0?(n=(e.min.x-f.x)*l,r=(e.max.x-f.x)*l):(n=(e.max.x-f.x)*l,r=(e.min.x-f.x)*l),h>=0?(s=(e.min.y-f.y)*h,a=(e.max.y-f.y)*h):(s=(e.max.y-f.y)*h,a=(e.min.y-f.y)*h),n>a||s>r||((s>n||isNaN(n))&&(n=s),(a=0?(o=(e.min.z-f.z)*d,c=(e.max.z-f.z)*d):(o=(e.max.z-f.z)*d,c=(e.min.z-f.z)*d),n>c||o>r)||((o>n||n!==n)&&(n=o),(c=0?n:r,t)}intersectsBox(e){return this.intersectBox(e,Zt)!==null}intersectTriangle(e,t,n,r,s){Mr.subVectors(t,e),Fi.subVectors(n,e),Sr.crossVectors(Mr,Fi);let a=this.direction.dot(Sr),o;if(a>0){if(r)return null;o=1}else if(a<0)o=-1,a=-a;else return null;ln.subVectors(this.origin,e);const c=o*this.direction.dot(Fi.crossVectors(ln,Fi));if(c<0)return null;const l=o*this.direction.dot(Mr.cross(ln));if(l<0||c+l>a)return null;const h=-o*ln.dot(Sr);return h<0?null:this.at(h/a,s)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class st{constructor(e,t,n,r,s,a,o,c,l,h,d,f,m,_,x,p){st.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,n,r,s,a,o,c,l,h,d,f,m,_,x,p)}set(e,t,n,r,s,a,o,c,l,h,d,f,m,_,x,p){const u=this.elements;return u[0]=e,u[4]=t,u[8]=n,u[12]=r,u[1]=s,u[5]=a,u[9]=o,u[13]=c,u[2]=l,u[6]=h,u[10]=d,u[14]=f,u[3]=m,u[7]=_,u[11]=x,u[15]=p,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new st().fromArray(this.elements)}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){const t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,n=e.elements,r=1/zn.setFromMatrixColumn(e,0).length(),s=1/zn.setFromMatrixColumn(e,1).length(),a=1/zn.setFromMatrixColumn(e,2).length();return t[0]=n[0]*r,t[1]=n[1]*r,t[2]=n[2]*r,t[3]=0,t[4]=n[4]*s,t[5]=n[5]*s,t[6]=n[6]*s,t[7]=0,t[8]=n[8]*a,t[9]=n[9]*a,t[10]=n[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,n=e.x,r=e.y,s=e.z,a=Math.cos(n),o=Math.sin(n),c=Math.cos(r),l=Math.sin(r),h=Math.cos(s),d=Math.sin(s);if(e.order==="XYZ"){const f=a*h,m=a*d,_=o*h,x=o*d;t[0]=c*h,t[4]=-c*d,t[8]=l,t[1]=m+_*l,t[5]=f-x*l,t[9]=-o*c,t[2]=x-f*l,t[6]=_+m*l,t[10]=a*c}else if(e.order==="YXZ"){const f=c*h,m=c*d,_=l*h,x=l*d;t[0]=f+x*o,t[4]=_*o-m,t[8]=a*l,t[1]=a*d,t[5]=a*h,t[9]=-o,t[2]=m*o-_,t[6]=x+f*o,t[10]=a*c}else if(e.order==="ZXY"){const f=c*h,m=c*d,_=l*h,x=l*d;t[0]=f-x*o,t[4]=-a*d,t[8]=_+m*o,t[1]=m+_*o,t[5]=a*h,t[9]=x-f*o,t[2]=-a*l,t[6]=o,t[10]=a*c}else if(e.order==="ZYX"){const f=a*h,m=a*d,_=o*h,x=o*d;t[0]=c*h,t[4]=_*l-m,t[8]=f*l+x,t[1]=c*d,t[5]=x*l+f,t[9]=m*l-_,t[2]=-l,t[6]=o*c,t[10]=a*c}else if(e.order==="YZX"){const f=a*c,m=a*l,_=o*c,x=o*l;t[0]=c*h,t[4]=x-f*d,t[8]=_*d+m,t[1]=d,t[5]=a*h,t[9]=-o*h,t[2]=-l*h,t[6]=m*d+_,t[10]=f-x*d}else if(e.order==="XZY"){const f=a*c,m=a*l,_=o*c,x=o*l;t[0]=c*h,t[4]=-d,t[8]=l*h,t[1]=f*d+x,t[5]=a*h,t[9]=m*d-_,t[2]=_*d-m,t[6]=o*h,t[10]=x*d+f}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(Bl,e,Hl)}lookAt(e,t,n){const r=this.elements;return At.subVectors(e,t),At.lengthSq()===0&&(At.z=1),At.normalize(),cn.crossVectors(n,At),cn.lengthSq()===0&&(Math.abs(n.z)===1?At.x+=1e-4:At.z+=1e-4,At.normalize(),cn.crossVectors(n,At)),cn.normalize(),Oi.crossVectors(At,cn),r[0]=cn.x,r[4]=Oi.x,r[8]=At.x,r[1]=cn.y,r[5]=Oi.y,r[9]=At.y,r[2]=cn.z,r[6]=Oi.z,r[10]=At.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,r=t.elements,s=this.elements,a=n[0],o=n[4],c=n[8],l=n[12],h=n[1],d=n[5],f=n[9],m=n[13],_=n[2],x=n[6],p=n[10],u=n[14],b=n[3],A=n[7],E=n[11],D=n[15],R=r[0],w=r[4],U=r[8],S=r[12],M=r[1],C=r[5],O=r[9],z=r[13],q=r[2],W=r[6],X=r[10],Z=r[14],G=r[3],se=r[7],ce=r[11],Ee=r[15];return s[0]=a*R+o*M+c*q+l*G,s[4]=a*w+o*C+c*W+l*se,s[8]=a*U+o*O+c*X+l*ce,s[12]=a*S+o*z+c*Z+l*Ee,s[1]=h*R+d*M+f*q+m*G,s[5]=h*w+d*C+f*W+m*se,s[9]=h*U+d*O+f*X+m*ce,s[13]=h*S+d*z+f*Z+m*Ee,s[2]=_*R+x*M+p*q+u*G,s[6]=_*w+x*C+p*W+u*se,s[10]=_*U+x*O+p*X+u*ce,s[14]=_*S+x*z+p*Z+u*Ee,s[3]=b*R+A*M+E*q+D*G,s[7]=b*w+A*C+E*W+D*se,s[11]=b*U+A*O+E*X+D*ce,s[15]=b*S+A*z+E*Z+D*Ee,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[4],r=e[8],s=e[12],a=e[1],o=e[5],c=e[9],l=e[13],h=e[2],d=e[6],f=e[10],m=e[14],_=e[3],x=e[7],p=e[11],u=e[15];return _*(+s*c*d-r*l*d-s*o*f+n*l*f+r*o*m-n*c*m)+x*(+t*c*m-t*l*f+s*a*f-r*a*m+r*l*h-s*c*h)+p*(+t*l*d-t*o*m-s*a*d+n*a*m+s*o*h-n*l*h)+u*(-r*o*h-t*c*d+t*o*f+r*a*d-n*a*f+n*c*h)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){const r=this.elements;return e.isVector3?(r[12]=e.x,r[13]=e.y,r[14]=e.z):(r[12]=e,r[13]=t,r[14]=n),this}invert(){const e=this.elements,t=e[0],n=e[1],r=e[2],s=e[3],a=e[4],o=e[5],c=e[6],l=e[7],h=e[8],d=e[9],f=e[10],m=e[11],_=e[12],x=e[13],p=e[14],u=e[15],b=d*p*l-x*f*l+x*c*m-o*p*m-d*c*u+o*f*u,A=_*f*l-h*p*l-_*c*m+a*p*m+h*c*u-a*f*u,E=h*x*l-_*d*l+_*o*m-a*x*m-h*o*u+a*d*u,D=_*d*c-h*x*c-_*o*f+a*x*f+h*o*p-a*d*p,R=t*b+n*A+r*E+s*D;if(R===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const w=1/R;return e[0]=b*w,e[1]=(x*f*s-d*p*s-x*r*m+n*p*m+d*r*u-n*f*u)*w,e[2]=(o*p*s-x*c*s+x*r*l-n*p*l-o*r*u+n*c*u)*w,e[3]=(d*c*s-o*f*s-d*r*l+n*f*l+o*r*m-n*c*m)*w,e[4]=A*w,e[5]=(h*p*s-_*f*s+_*r*m-t*p*m-h*r*u+t*f*u)*w,e[6]=(_*c*s-a*p*s-_*r*l+t*p*l+a*r*u-t*c*u)*w,e[7]=(a*f*s-h*c*s+h*r*l-t*f*l-a*r*m+t*c*m)*w,e[8]=E*w,e[9]=(_*d*s-h*x*s-_*n*m+t*x*m+h*n*u-t*d*u)*w,e[10]=(a*x*s-_*o*s+_*n*l-t*x*l-a*n*u+t*o*u)*w,e[11]=(h*o*s-a*d*s-h*n*l+t*d*l+a*n*m-t*o*m)*w,e[12]=D*w,e[13]=(h*x*r-_*d*r+_*n*f-t*x*f-h*n*p+t*d*p)*w,e[14]=(_*o*r-a*x*r-_*n*c+t*x*c+a*n*p-t*o*p)*w,e[15]=(a*d*r-h*o*r+h*n*c-t*d*c-a*n*f+t*o*f)*w,this}scale(e){const t=this.elements,n=e.x,r=e.y,s=e.z;return t[0]*=n,t[4]*=r,t[8]*=s,t[1]*=n,t[5]*=r,t[9]*=s,t[2]*=n,t[6]*=r,t[10]*=s,t[3]*=n,t[7]*=r,t[11]*=s,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],r=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,r))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const n=Math.cos(t),r=Math.sin(t),s=1-n,a=e.x,o=e.y,c=e.z,l=s*a,h=s*o;return this.set(l*a+n,l*o-r*c,l*c+r*o,0,l*o+r*c,h*o+n,h*c-r*a,0,l*c-r*o,h*c+r*a,s*c*c+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,r,s,a){return this.set(1,n,s,0,e,1,a,0,t,r,1,0,0,0,0,1),this}compose(e,t,n){const r=this.elements,s=t._x,a=t._y,o=t._z,c=t._w,l=s+s,h=a+a,d=o+o,f=s*l,m=s*h,_=s*d,x=a*h,p=a*d,u=o*d,b=c*l,A=c*h,E=c*d,D=n.x,R=n.y,w=n.z;return r[0]=(1-(x+u))*D,r[1]=(m+E)*D,r[2]=(_-A)*D,r[3]=0,r[4]=(m-E)*R,r[5]=(1-(f+u))*R,r[6]=(p+b)*R,r[7]=0,r[8]=(_+A)*w,r[9]=(p-b)*w,r[10]=(1-(f+x))*w,r[11]=0,r[12]=e.x,r[13]=e.y,r[14]=e.z,r[15]=1,this}decompose(e,t,n){const r=this.elements;let s=zn.set(r[0],r[1],r[2]).length();const a=zn.set(r[4],r[5],r[6]).length(),o=zn.set(r[8],r[9],r[10]).length();this.determinant()<0&&(s=-s),e.x=r[12],e.y=r[13],e.z=r[14],Ft.copy(this);const l=1/s,h=1/a,d=1/o;return Ft.elements[0]*=l,Ft.elements[1]*=l,Ft.elements[2]*=l,Ft.elements[4]*=h,Ft.elements[5]*=h,Ft.elements[6]*=h,Ft.elements[8]*=d,Ft.elements[9]*=d,Ft.elements[10]*=d,t.setFromRotationMatrix(Ft),n.x=s,n.y=a,n.z=o,this}makePerspective(e,t,n,r,s,a,o=Wt,c=!1){const l=this.elements,h=2*s/(t-e),d=2*s/(n-r),f=(t+e)/(t-e),m=(n+r)/(n-r);let _,x;if(c)_=s/(a-s),x=a*s/(a-s);else if(o===Wt)_=-(a+s)/(a-s),x=-2*a*s/(a-s);else if(o===sr)_=-a/(a-s),x=-a*s/(a-s);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return l[0]=h,l[4]=0,l[8]=f,l[12]=0,l[1]=0,l[5]=d,l[9]=m,l[13]=0,l[2]=0,l[6]=0,l[10]=_,l[14]=x,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(e,t,n,r,s,a,o=Wt,c=!1){const l=this.elements,h=2/(t-e),d=2/(n-r),f=-(t+e)/(t-e),m=-(n+r)/(n-r);let _,x;if(c)_=1/(a-s),x=a/(a-s);else if(o===Wt)_=-2/(a-s),x=-(a+s)/(a-s);else if(o===sr)_=-1/(a-s),x=-s/(a-s);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return l[0]=h,l[4]=0,l[8]=0,l[12]=f,l[1]=0,l[5]=d,l[9]=0,l[13]=m,l[2]=0,l[6]=0,l[10]=_,l[14]=x,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(e){const t=this.elements,n=e.elements;for(let r=0;r<16;r++)if(t[r]!==n[r])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}}const zn=new F,Ft=new st,Bl=new F(0,0,0),Hl=new F(1,1,1),cn=new F,Oi=new F,At=new F,ha=new st,da=new Ai;class Yt{constructor(e=0,t=0,n=0,r=Yt.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,this._order=r}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,r=this._order){return this._x=e,this._y=t,this._z=n,this._order=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){const r=e.elements,s=r[0],a=r[4],o=r[8],c=r[1],l=r[5],h=r[9],d=r[2],f=r[6],m=r[10];switch(t){case"XYZ":this._y=Math.asin(He(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-h,m),this._z=Math.atan2(-a,s)):(this._x=Math.atan2(f,l),this._z=0);break;case"YXZ":this._x=Math.asin(-He(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(o,m),this._z=Math.atan2(c,l)):(this._y=Math.atan2(-d,s),this._z=0);break;case"ZXY":this._x=Math.asin(He(f,-1,1)),Math.abs(f)<.9999999?(this._y=Math.atan2(-d,m),this._z=Math.atan2(-a,l)):(this._y=0,this._z=Math.atan2(c,s));break;case"ZYX":this._y=Math.asin(-He(d,-1,1)),Math.abs(d)<.9999999?(this._x=Math.atan2(f,m),this._z=Math.atan2(c,s)):(this._x=0,this._z=Math.atan2(-a,l));break;case"YZX":this._z=Math.asin(He(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(-h,l),this._y=Math.atan2(-d,s)):(this._x=0,this._y=Math.atan2(o,m));break;case"XZY":this._z=Math.asin(-He(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(f,l),this._y=Math.atan2(o,s)):(this._x=Math.atan2(-h,m),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return ha.makeRotationFromQuaternion(e),this.setFromRotationMatrix(ha,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return da.setFromEuler(this),this.setFromQuaternion(da,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Yt.DEFAULT_ORDER="XYZ";class Gs{constructor(){this.mask=1}set(e){this.mask=(1<>>0}enable(e){this.mask|=1<1){for(let t=0;t1){for(let n=0;n0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(r.matrixAutoUpdate=!1),this.isInstancedMesh&&(r.type="InstancedMesh",r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type="BatchedMesh",r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.geometryInfo=this._geometryInfo.map(o=>({...o,boundingBox:o.boundingBox?o.boundingBox.toJSON():void 0,boundingSphere:o.boundingSphere?o.boundingSphere.toJSON():void 0})),r.instanceInfo=this._instanceInfo.map(o=>({...o})),r.availableInstanceIds=this._availableInstanceIds.slice(),r.availableGeometryIds=this._availableGeometryIds.slice(),r.nextIndexStart=this._nextIndexStart,r.nextVertexStart=this._nextVertexStart,r.geometryCount=this._geometryCount,r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.matricesTexture=this._matricesTexture.toJSON(e),r.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(r.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(r.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(r.boundingBox=this.boundingBox.toJSON()));function s(o,c){return o[c.uuid]===void 0&&(o[c.uuid]=c.toJSON(e)),c.uuid}if(this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=s(e.geometries,this.geometry);const o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){const c=o.shapes;if(Array.isArray(c))for(let l=0,h=c.length;l0){r.children=[];for(let o=0;o0){r.animations=[];for(let o=0;o0&&(n.geometries=o),c.length>0&&(n.materials=c),l.length>0&&(n.textures=l),h.length>0&&(n.images=h),d.length>0&&(n.shapes=d),f.length>0&&(n.skeletons=f),m.length>0&&(n.animations=m),_.length>0&&(n.nodes=_)}return n.object=r,n;function a(o){const c=[];for(const l in o){const h=o[l];delete h.metadata,c.push(h)}return c}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let n=0;n0?r.multiplyScalar(1/Math.sqrt(s)):r.set(0,0,0)}static getBarycoord(e,t,n,r,s){Ot.subVectors(r,t),Jt.subVectors(n,t),yr.subVectors(e,t);const a=Ot.dot(Ot),o=Ot.dot(Jt),c=Ot.dot(yr),l=Jt.dot(Jt),h=Jt.dot(yr),d=a*l-o*o;if(d===0)return s.set(0,0,0),null;const f=1/d,m=(l*c-o*h)*f,_=(a*h-o*c)*f;return s.set(1-m-_,_,m)}static containsPoint(e,t,n,r){return this.getBarycoord(e,t,n,r,Qt)===null?!1:Qt.x>=0&&Qt.y>=0&&Qt.x+Qt.y<=1}static getInterpolation(e,t,n,r,s,a,o,c){return this.getBarycoord(e,t,n,r,Qt)===null?(c.x=0,c.y=0,"z"in c&&(c.z=0),"w"in c&&(c.w=0),null):(c.setScalar(0),c.addScaledVector(s,Qt.x),c.addScaledVector(a,Qt.y),c.addScaledVector(o,Qt.z),c)}static getInterpolatedAttribute(e,t,n,r,s,a){return wr.setScalar(0),Rr.setScalar(0),Cr.setScalar(0),wr.fromBufferAttribute(e,t),Rr.fromBufferAttribute(e,n),Cr.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector(wr,s.x),a.addScaledVector(Rr,s.y),a.addScaledVector(Cr,s.z),a}static isFrontFacing(e,t,n,r){return Ot.subVectors(n,t),Jt.subVectors(e,t),Ot.cross(Jt).dot(r)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,r){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,n,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,r),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Ot.subVectors(this.c,this.b),Jt.subVectors(this.a,this.b),Ot.cross(Jt).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Ht.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Ht.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,r,s){return Ht.getInterpolation(e,this.a,this.b,this.c,t,n,r,s)}containsPoint(e){return Ht.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Ht.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const n=this.a,r=this.b,s=this.c;let a,o;Vn.subVectors(r,n),Wn.subVectors(s,n),Tr.subVectors(e,n);const c=Vn.dot(Tr),l=Wn.dot(Tr);if(c<=0&&l<=0)return t.copy(n);Ar.subVectors(e,r);const h=Vn.dot(Ar),d=Wn.dot(Ar);if(h>=0&&d<=h)return t.copy(r);const f=c*d-h*l;if(f<=0&&c>=0&&h<=0)return a=c/(c-h),t.copy(n).addScaledVector(Vn,a);br.subVectors(e,s);const m=Vn.dot(br),_=Wn.dot(br);if(_>=0&&m<=_)return t.copy(s);const x=m*l-c*_;if(x<=0&&l>=0&&_<=0)return o=l/(l-_),t.copy(n).addScaledVector(Wn,o);const p=h*_-m*d;if(p<=0&&d-h>=0&&m-_>=0)return va.subVectors(s,r),o=(d-h)/(d-h+(m-_)),t.copy(r).addScaledVector(va,o);const u=1/(p+x+f);return a=x*u,o=f*u,t.copy(n).addScaledVector(Vn,a).addScaledVector(Wn,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const vo={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},un={h:0,s:0,l:0},Hi={h:0,s:0,l:0};function Pr(i,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?i+(e-i)*6*t:t<1/2?e:t<2/3?i+(e-i)*6*(2/3-t):i}class Oe{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){const r=e;r&&r.isColor?this.copy(r):typeof r=="number"?this.setHex(r):typeof r=="string"&&this.setStyle(r)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Lt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Ve.colorSpaceToWorking(this,t),this}setRGB(e,t,n,r=Ve.workingColorSpace){return this.r=e,this.g=t,this.b=n,Ve.colorSpaceToWorking(this,r),this}setHSL(e,t,n,r=Ve.workingColorSpace){if(e=Rl(e,1),t=He(t,0,1),n=He(n,0,1),t===0)this.r=this.g=this.b=n;else{const s=n<=.5?n*(1+t):n+t-n*t,a=2*n-s;this.r=Pr(a,s,e+1/3),this.g=Pr(a,s,e),this.b=Pr(a,s,e-1/3)}return Ve.colorSpaceToWorking(this,r),this}setStyle(e,t=Lt){function n(s){s!==void 0&&parseFloat(s)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let s;const a=r[1],o=r[2];switch(a){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,t);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,t);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){const s=r[1],a=s.length;if(a===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,t);if(a===6)return this.setHex(parseInt(s,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Lt){const n=vo[e.toLowerCase()];return n!==void 0?this.setHex(n,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=rn(e.r),this.g=rn(e.g),this.b=rn(e.b),this}copyLinearToSRGB(e){return this.r=Qn(e.r),this.g=Qn(e.g),this.b=Qn(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Lt){return Ve.workingToColorSpace(mt.copy(this),e),Math.round(He(mt.r*255,0,255))*65536+Math.round(He(mt.g*255,0,255))*256+Math.round(He(mt.b*255,0,255))}getHexString(e=Lt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Ve.workingColorSpace){Ve.workingToColorSpace(mt.copy(this),t);const n=mt.r,r=mt.g,s=mt.b,a=Math.max(n,r,s),o=Math.min(n,r,s);let c,l;const h=(o+a)/2;if(o===a)c=0,l=0;else{const d=a-o;switch(l=h<=.5?d/(a+o):d/(2-a-o),a){case n:c=(r-s)/d+(r0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const n=e[t];if(n===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const r=this[t];if(r===void 0){console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);continue}r&&r.isColor?r.set(n):r&&r.isVector3&&n&&n.isVector3?r.copy(n):this[t]=n}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const n={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==Jn&&(n.blending=this.blending),this.side!==mn&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==Vr&&(n.blendSrc=this.blendSrc),this.blendDst!==Wr&&(n.blendDst=this.blendDst),this.blendEquation!==wn&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==ei&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==ra&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Nn&&(n.stencilFail=this.stencilFail),this.stencilZFail!==Nn&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==Nn&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function r(s){const a=[];for(const o in s){const c=s[o];delete c.metadata,a.push(c)}return a}if(t){const s=r(e.textures),a=r(e.images);s.length>0&&(n.textures=s),a.length>0&&(n.images=a)}return n}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let n=null;if(t!==null){const r=t.length;n=new Array(r);for(let s=0;s!==r;++s)n[s]=t[s].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class xo extends wi{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Oe(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Yt,this.combine=no,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const ot=new F,zi=new Ge;let Xl=0;class Xt{constructor(e,t,n=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:Xl++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=n,this.usage=sa,this.updateRanges=[],this.gpuType=nn,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let r=0,s=this.itemSize;rt.count&&console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new bi);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new F(-1/0,-1/0,-1/0),new F(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let n=0,r=t.length;n0&&(e.userData=this.userData),this.parameters!==void 0){const c=this.parameters;for(const l in c)c[l]!==void 0&&(e[l]=c[l]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const n=this.attributes;for(const c in n){const l=n[c];e.data.attributes[c]=l.toJSON(e.data)}const r={};let s=!1;for(const c in this.morphAttributes){const l=this.morphAttributes[c],h=[];for(let d=0,f=l.length;d0&&(r[c]=h,s=!0)}s&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);const a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));const o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const n=e.index;n!==null&&this.setIndex(n.clone());const r=e.attributes;for(const l in r){const h=r[l];this.setAttribute(l,h.clone(t))}const s=e.morphAttributes;for(const l in s){const h=[],d=s[l];for(let f=0,m=d.length;f0){const r=t[n[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,a=r.length;s(e.far-e.near)**2))&&(xa.copy(s).invert(),Sn.copy(e.ray).applyMatrix4(xa),!(n.boundingBox!==null&&Sn.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,Sn)))}_computeIntersections(e,t,n){let r;const s=this.geometry,a=this.material,o=s.index,c=s.attributes.position,l=s.attributes.uv,h=s.attributes.uv1,d=s.attributes.normal,f=s.groups,m=s.drawRange;if(o!==null)if(Array.isArray(a))for(let _=0,x=f.length;_t.far?null:{distance:l,point:qi.clone(),object:i}}function Yi(i,e,t,n,r,s,a,o,c,l){i.getVertexPosition(o,ki),i.getVertexPosition(c,Vi),i.getVertexPosition(l,Wi);const h=Yl(i,e,t,n,ki,Vi,Wi,Sa);if(h){const d=new F;Ht.getBarycoord(Sa,ki,Vi,Wi,d),r&&(h.uv=Ht.getInterpolatedAttribute(r,o,c,l,d,new Ge)),s&&(h.uv1=Ht.getInterpolatedAttribute(s,o,c,l,d,new Ge)),a&&(h.normal=Ht.getInterpolatedAttribute(a,o,c,l,d,new F),h.normal.dot(n.direction)>0&&h.normal.multiplyScalar(-1));const f={a:o,b:c,c:l,normal:new F,materialIndex:0};Ht.getNormal(ki,Vi,Wi,f.normal),h.face=f,h.barycoord=d}return h}class Ri extends sn{constructor(e=1,t=1,n=1,r=1,s=1,a=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:r,heightSegments:s,depthSegments:a};const o=this;r=Math.floor(r),s=Math.floor(s),a=Math.floor(a);const c=[],l=[],h=[],d=[];let f=0,m=0;_("z","y","x",-1,-1,n,t,e,a,s,0),_("z","y","x",1,-1,n,t,-e,a,s,1),_("x","z","y",1,1,e,n,t,r,a,2),_("x","z","y",1,-1,e,n,-t,r,a,3),_("x","y","z",1,-1,e,t,n,r,s,4),_("x","y","z",-1,-1,e,t,-n,r,s,5),this.setIndex(c),this.setAttribute("position",new Rt(l,3)),this.setAttribute("normal",new Rt(h,3)),this.setAttribute("uv",new Rt(d,2));function _(x,p,u,b,A,E,D,R,w,U,S){const M=E/w,C=D/U,O=E/2,z=D/2,q=R/2,W=w+1,X=U+1;let Z=0,G=0;const se=new F;for(let ce=0;ce0?1:-1,h.push(se.x,se.y,se.z),d.push(Fe/w),d.push(1-ce/U),Z+=1}}for(let ce=0;ce0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const n={};for(const r in this.extensions)this.extensions[r]===!0&&(n[r]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}}class yo extends dt{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new st,this.projectionMatrix=new st,this.projectionMatrixInverse=new st,this.coordinateSystem=Wt,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const hn=new F,Ea=new Ge,ya=new Ge;class It extends yo{constructor(e=50,t=1,n=.1,r=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=r,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=Cs*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(hr*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return Cs*2*Math.atan(Math.tan(hr*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){hn.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(hn.x,hn.y).multiplyScalar(-e/hn.z),hn.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(hn.x,hn.y).multiplyScalar(-e/hn.z)}getViewSize(e,t){return this.getViewBounds(e,Ea,ya),t.subVectors(ya,Ea)}setViewOffset(e,t,n,r,s,a){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=s,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(hr*.5*this.fov)/this.zoom,n=2*t,r=this.aspect*n,s=-.5*r;const a=this.view;if(this.view!==null&&this.view.enabled){const c=a.fullWidth,l=a.fullHeight;s+=a.offsetX*r/c,t-=a.offsetY*n/l,r*=a.width/c,n*=a.height/l}const o=this.filmOffset;o!==0&&(s+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(s,s+r,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const qn=-90,Yn=1;class Jl extends dt{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const r=new It(qn,Yn,e,t);r.layers=this.layers,this.add(r);const s=new It(qn,Yn,e,t);s.layers=this.layers,this.add(s);const a=new It(qn,Yn,e,t);a.layers=this.layers,this.add(a);const o=new It(qn,Yn,e,t);o.layers=this.layers,this.add(o);const c=new It(qn,Yn,e,t);c.layers=this.layers,this.add(c);const l=new It(qn,Yn,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[n,r,s,a,o,c]=t;for(const l of t)this.remove(l);if(e===Wt)n.up.set(0,1,0),n.lookAt(1,0,0),r.up.set(0,1,0),r.lookAt(-1,0,0),s.up.set(0,0,-1),s.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),c.up.set(0,1,0),c.lookAt(0,0,-1);else if(e===sr)n.up.set(0,-1,0),n.lookAt(-1,0,0),r.up.set(0,-1,0),r.lookAt(1,0,0),s.up.set(0,0,1),s.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),c.up.set(0,-1,0),c.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const l of t)this.add(l),l.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:n,activeMipmapLevel:r}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[s,a,o,c,l,h]=this.children,d=e.getRenderTarget(),f=e.getActiveCubeFace(),m=e.getActiveMipmapLevel(),_=e.xr.enabled;e.xr.enabled=!1;const x=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0,r),e.render(t,s),e.setRenderTarget(n,1,r),e.render(t,a),e.setRenderTarget(n,2,r),e.render(t,o),e.setRenderTarget(n,3,r),e.render(t,c),e.setRenderTarget(n,4,r),e.render(t,l),n.texture.generateMipmaps=x,e.setRenderTarget(n,5,r),e.render(t,h),e.setRenderTarget(d,f,m),e.xr.enabled=_,n.texture.needsPMREMUpdate=!0}}class To extends xt{constructor(e=[],t=ti,n,r,s,a,o,c,l,h){super(e,t,n,r,s,a,o,c,l,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class Ql extends In{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const n={width:e,height:e,depth:1},r=[n,n,n,n,n,n];this.texture=new To(r),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const n={uniforms:{tEquirect:{value:null}},vertexShader:` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + `,fragmentShader:` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + `},r=new Ri(5,5,5),s=new gn({name:"CubemapFromEquirect",uniforms:ri(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:Et,blending:fn});s.uniforms.tEquirect.value=t;const a=new wt(r,s),o=t.minFilter;return t.minFilter===Dn&&(t.minFilter=Ut),new Jl(1,10,this).update(e,a),t.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(e,t=!0,n=!0,r=!0){const s=e.getRenderTarget();for(let a=0;a<6;a++)e.setRenderTarget(this,a),e.clear(t,n,r);e.setRenderTarget(s)}}class Zn extends dt{constructor(){super(),this.isGroup=!0,this.type="Group"}}const ec={type:"move"};class Ir{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Zn,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new Zn,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new F,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new F),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Zn,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new F,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new F),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,n){let r=null,s=null,a=null;const o=this._targetRay,c=this._grip,l=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(l&&e.hand){a=!0;for(const x of e.hand.values()){const p=t.getJointPose(x,n),u=this._getHandJoint(l,x);p!==null&&(u.matrix.fromArray(p.transform.matrix),u.matrix.decompose(u.position,u.rotation,u.scale),u.matrixWorldNeedsUpdate=!0,u.jointRadius=p.radius),u.visible=p!==null}const h=l.joints["index-finger-tip"],d=l.joints["thumb-tip"],f=h.position.distanceTo(d.position),m=.02,_=.005;l.inputState.pinching&&f>m+_?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&f<=m-_&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else c!==null&&e.gripSpace&&(s=t.getPose(e.gripSpace,n),s!==null&&(c.matrix.fromArray(s.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,s.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(s.linearVelocity)):c.hasLinearVelocity=!1,s.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(s.angularVelocity)):c.hasAngularVelocity=!1));o!==null&&(r=t.getPose(e.targetRaySpace,n),r===null&&s!==null&&(r=s),r!==null&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(ec)))}return o!==null&&(o.visible=r!==null),c!==null&&(c.visible=s!==null),l!==null&&(l.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const n=new Zn;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}}class tc extends dt{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new Yt,this.environmentIntensity=1,this.environmentRotation=new Yt,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}const Ur=new F,nc=new F,ic=new Ie;class An{constructor(e=new F(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,r){return this.normal.set(e,t,n),this.constant=r,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){const r=Ur.subVectors(n,t).cross(nc.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(r,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){const n=e.delta(Ur),r=this.normal.dot(n);if(r===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;const s=-(e.start.dot(this.normal)+this.constant)/r;return s<0||s>1?null:t.copy(e.start).addScaledVector(n,s)}intersectsLine(e){const t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const n=t||ic.getNormalMatrix(e),r=this.coplanarPoint(Ur).applyMatrix4(e),s=this.normal.applyMatrix3(n).normalize();return this.constant=-r.dot(s),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const En=new zs,rc=new Ge(.5,.5),$i=new F;class ks{constructor(e=new An,t=new An,n=new An,r=new An,s=new An,a=new An){this.planes=[e,t,n,r,s,a]}set(e,t,n,r,s,a){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(r),o[4].copy(s),o[5].copy(a),this}copy(e){const t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=Wt,n=!1){const r=this.planes,s=e.elements,a=s[0],o=s[1],c=s[2],l=s[3],h=s[4],d=s[5],f=s[6],m=s[7],_=s[8],x=s[9],p=s[10],u=s[11],b=s[12],A=s[13],E=s[14],D=s[15];if(r[0].setComponents(l-a,m-h,u-_,D-b).normalize(),r[1].setComponents(l+a,m+h,u+_,D+b).normalize(),r[2].setComponents(l+o,m+d,u+x,D+A).normalize(),r[3].setComponents(l-o,m-d,u-x,D-A).normalize(),n)r[4].setComponents(c,f,p,E).normalize(),r[5].setComponents(l-c,m-f,u-p,D-E).normalize();else if(r[4].setComponents(l-c,m-f,u-p,D-E).normalize(),t===Wt)r[5].setComponents(l+c,m+f,u+p,D+E).normalize();else if(t===sr)r[5].setComponents(c,f,p,E).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),En.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),En.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(En)}intersectsSprite(e){En.center.set(0,0,0);const t=rc.distanceTo(e.center);return En.radius=.7071067811865476+t,En.applyMatrix4(e.matrixWorld),this.intersectsSphere(En)}intersectsSphere(e){const t=this.planes,n=e.center,r=-e.radius;for(let s=0;s<6;s++)if(t[s].distanceToPoint(n)0?e.max.x:e.min.x,$i.y=r.normal.y>0?e.max.y:e.min.y,$i.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint($i)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}class Ao extends xt{constructor(e,t,n=Ln,r,s,a,o=Gt,c=Gt,l,h=xi,d=1){if(h!==xi&&h!==Mi)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const f={width:e,height:t,depth:d};super(f,r,s,a,o,c,h,n,l),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Hs(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}class bo extends xt{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class Vs extends sn{constructor(e=1,t=1,n=1,r=32,s=1,a=!1,o=0,c=Math.PI*2){super(),this.type="CylinderGeometry",this.parameters={radiusTop:e,radiusBottom:t,height:n,radialSegments:r,heightSegments:s,openEnded:a,thetaStart:o,thetaLength:c};const l=this;r=Math.floor(r),s=Math.floor(s);const h=[],d=[],f=[],m=[];let _=0;const x=[],p=n/2;let u=0;b(),a===!1&&(e>0&&A(!0),t>0&&A(!1)),this.setIndex(h),this.setAttribute("position",new Rt(d,3)),this.setAttribute("normal",new Rt(f,3)),this.setAttribute("uv",new Rt(m,2));function b(){const E=new F,D=new F;let R=0;const w=(t-e)/n;for(let U=0;U<=s;U++){const S=[],M=U/s,C=M*(t-e)+e;for(let O=0;O<=r;O++){const z=O/r,q=z*c+o,W=Math.sin(q),X=Math.cos(q);D.x=C*W,D.y=-M*n+p,D.z=C*X,d.push(D.x,D.y,D.z),E.set(W,w,X).normalize(),f.push(E.x,E.y,E.z),m.push(z,1-M),S.push(_++)}x.push(S)}for(let U=0;U0||S!==0)&&(h.push(M,C,z),R+=3),(t>0||S!==s-1)&&(h.push(C,O,z),R+=3)}l.addGroup(u,R,0),u+=R}function A(E){const D=_,R=new Ge,w=new F;let U=0;const S=E===!0?e:t,M=E===!0?1:-1;for(let O=1;O<=r;O++)d.push(0,p*M,0),f.push(0,M,0),m.push(.5,.5),_++;const C=_;for(let O=0;O<=r;O++){const q=O/r*c+o,W=Math.cos(q),X=Math.sin(q);w.x=S*X,w.y=p*M,w.z=S*W,d.push(w.x,w.y,w.z),f.push(0,M,0),R.x=W*.5+.5,R.y=X*.5*M+.5,m.push(R.x,R.y),_++}for(let O=0;Om.start-_.start);let f=0;for(let m=1;m 0 + vec4 plane; + #ifdef ALPHA_TO_COVERAGE + float distanceToPlane, distanceGradient; + float clipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + if ( clipOpacity == 0.0 ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + float unionClipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + } + #pragma unroll_loop_end + clipOpacity *= 1.0 - unionClipOpacity; + #endif + diffuseColor.a *= clipOpacity; + if ( diffuseColor.a == 0.0 ) discard; + #else + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + bool clipped = true; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; + } + #pragma unroll_loop_end + if ( clipped ) discard; + #endif + #endif +#endif`,Nc=`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; + uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; +#endif`,Fc=`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; +#endif`,Oc=`#if NUM_CLIPPING_PLANES > 0 + vClipPosition = - mvPosition.xyz; +#endif`,Bc=`#if defined( USE_COLOR_ALPHA ) + diffuseColor *= vColor; +#elif defined( USE_COLOR ) + diffuseColor.rgb *= vColor; +#endif`,Hc=`#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) + varying vec3 vColor; +#endif`,zc=`#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + varying vec3 vColor; +#endif`,Gc=`#if defined( USE_COLOR_ALPHA ) + vColor = vec4( 1.0 ); +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + vColor = vec3( 1.0 ); +#endif +#ifdef USE_COLOR + vColor *= color; +#endif +#ifdef USE_INSTANCING_COLOR + vColor.xyz *= instanceColor.xyz; +#endif +#ifdef USE_BATCHING_COLOR + vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) ); + vColor.xyz *= batchingColor.xyz; +#endif`,kc=`#define PI 3.141592653589793 +#define PI2 6.283185307179586 +#define PI_HALF 1.5707963267948966 +#define RECIPROCAL_PI 0.3183098861837907 +#define RECIPROCAL_PI2 0.15915494309189535 +#define EPSILON 1e-6 +#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +#define whiteComplement( a ) ( 1.0 - saturate( a ) ) +float pow2( const in float x ) { return x*x; } +vec3 pow2( const in vec3 x ) { return x*x; } +float pow3( const in float x ) { return x*x*x; } +float pow4( const in float x ) { float x2 = x*x; return x2*x2; } +float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } +float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } +highp float rand( const in vec2 uv ) { + const highp float a = 12.9898, b = 78.233, c = 43758.5453; + highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); + return fract( sin( sn ) * c ); +} +#ifdef HIGH_PRECISION + float precisionSafeLength( vec3 v ) { return length( v ); } +#else + float precisionSafeLength( vec3 v ) { + float maxComponent = max3( abs( v ) ); + return length( v / maxComponent ) * maxComponent; + } +#endif +struct IncidentLight { + vec3 color; + vec3 direction; + bool visible; +}; +struct ReflectedLight { + vec3 directDiffuse; + vec3 directSpecular; + vec3 indirectDiffuse; + vec3 indirectSpecular; +}; +#ifdef USE_ALPHAHASH + varying vec3 vPosition; +#endif +vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); +} +vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); +} +mat3 transposeMat3( const in mat3 m ) { + mat3 tmp; + tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x ); + tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y ); + tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z ); + return tmp; +} +bool isPerspectiveMatrix( mat4 m ) { + return m[ 2 ][ 3 ] == - 1.0; +} +vec2 equirectUv( in vec3 dir ) { + float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; + float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; + return vec2( u, v ); +} +vec3 BRDF_Lambert( const in vec3 diffuseColor ) { + return RECIPROCAL_PI * diffuseColor; +} +vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} +float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} // validated`,Vc=`#ifdef ENVMAP_TYPE_CUBE_UV + #define cubeUV_minMipLevel 4.0 + #define cubeUV_minTileSize 16.0 + float getFace( vec3 direction ) { + vec3 absDirection = abs( direction ); + float face = - 1.0; + if ( absDirection.x > absDirection.z ) { + if ( absDirection.x > absDirection.y ) + face = direction.x > 0.0 ? 0.0 : 3.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } else { + if ( absDirection.z > absDirection.y ) + face = direction.z > 0.0 ? 2.0 : 5.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } + return face; + } + vec2 getUV( vec3 direction, float face ) { + vec2 uv; + if ( face == 0.0 ) { + uv = vec2( direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 1.0 ) { + uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); + } else if ( face == 2.0 ) { + uv = vec2( - direction.x, direction.y ) / abs( direction.z ); + } else if ( face == 3.0 ) { + uv = vec2( - direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 4.0 ) { + uv = vec2( - direction.x, direction.z ) / abs( direction.y ); + } else { + uv = vec2( direction.x, direction.y ) / abs( direction.z ); + } + return 0.5 * ( uv + 1.0 ); + } + vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { + float face = getFace( direction ); + float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); + mipInt = max( mipInt, cubeUV_minMipLevel ); + float faceSize = exp2( mipInt ); + highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; + if ( face > 2.0 ) { + uv.y += faceSize; + face -= 3.0; + } + uv.x += face * faceSize; + uv.x += filterInt * 3.0 * cubeUV_minTileSize; + uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); + uv.x *= CUBEUV_TEXEL_WIDTH; + uv.y *= CUBEUV_TEXEL_HEIGHT; + #ifdef texture2DGradEXT + return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; + #else + return texture2D( envMap, uv ).rgb; + #endif + } + #define cubeUV_r0 1.0 + #define cubeUV_m0 - 2.0 + #define cubeUV_r1 0.8 + #define cubeUV_m1 - 1.0 + #define cubeUV_r4 0.4 + #define cubeUV_m4 2.0 + #define cubeUV_r5 0.305 + #define cubeUV_m5 3.0 + #define cubeUV_r6 0.21 + #define cubeUV_m6 4.0 + float roughnessToMip( float roughness ) { + float mip = 0.0; + if ( roughness >= cubeUV_r1 ) { + mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; + } else if ( roughness >= cubeUV_r4 ) { + mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; + } else if ( roughness >= cubeUV_r5 ) { + mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; + } else if ( roughness >= cubeUV_r6 ) { + mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; + } else { + mip = - 2.0 * log2( 1.16 * roughness ); } + return mip; + } + vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { + float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); + float mipF = fract( mip ); + float mipInt = floor( mip ); + vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); + if ( mipF == 0.0 ) { + return vec4( color0, 1.0 ); + } else { + vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); + return vec4( mix( color0, color1, mipF ), 1.0 ); + } + } +#endif`,Wc=`vec3 transformedNormal = objectNormal; +#ifdef USE_TANGENT + vec3 transformedTangent = objectTangent; +#endif +#ifdef USE_BATCHING + mat3 bm = mat3( batchingMatrix ); + transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); + transformedNormal = bm * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = bm * transformedTangent; + #endif +#endif +#ifdef USE_INSTANCING + mat3 im = mat3( instanceMatrix ); + transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); + transformedNormal = im * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = im * transformedTangent; + #endif +#endif +transformedNormal = normalMatrix * transformedNormal; +#ifdef FLIP_SIDED + transformedNormal = - transformedNormal; +#endif +#ifdef USE_TANGENT + transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; + #ifdef FLIP_SIDED + transformedTangent = - transformedTangent; + #endif +#endif`,Xc=`#ifdef USE_DISPLACEMENTMAP + uniform sampler2D displacementMap; + uniform float displacementScale; + uniform float displacementBias; +#endif`,qc=`#ifdef USE_DISPLACEMENTMAP + transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); +#endif`,Yc=`#ifdef USE_EMISSIVEMAP + vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); + #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE + emissiveColor = sRGBTransferEOTF( emissiveColor ); + #endif + totalEmissiveRadiance *= emissiveColor.rgb; +#endif`,$c=`#ifdef USE_EMISSIVEMAP + uniform sampler2D emissiveMap; +#endif`,Kc="gl_FragColor = linearToOutputTexel( gl_FragColor );",Zc=`vec4 LinearTransferOETF( in vec4 value ) { + return value; +} +vec4 sRGBTransferEOTF( in vec4 value ) { + return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); +} +vec4 sRGBTransferOETF( in vec4 value ) { + return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); +}`,jc=`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vec3 cameraToFrag; + if ( isOrthographic ) { + cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToFrag = normalize( vWorldPosition - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vec3 reflectVec = reflect( cameraToFrag, worldNormal ); + #else + vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); + #endif + #else + vec3 reflectVec = vReflect; + #endif + #ifdef ENVMAP_TYPE_CUBE + vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); + #else + vec4 envColor = vec4( 0.0 ); + #endif + #ifdef ENVMAP_BLENDING_MULTIPLY + outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_MIX ) + outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_ADD ) + outgoingLight += envColor.xyz * specularStrength * reflectivity; + #endif +#endif`,Jc=`#ifdef USE_ENVMAP + uniform float envMapIntensity; + uniform float flipEnvMap; + uniform mat3 envMapRotation; + #ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; + #else + uniform sampler2D envMap; + #endif + +#endif`,Qc=`#ifdef USE_ENVMAP + uniform float reflectivity; + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + varying vec3 vWorldPosition; + uniform float refractionRatio; + #else + varying vec3 vReflect; + #endif +#endif`,eu=`#ifdef USE_ENVMAP + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + + varying vec3 vWorldPosition; + #else + varying vec3 vReflect; + uniform float refractionRatio; + #endif +#endif`,tu=`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vWorldPosition = worldPosition.xyz; + #else + vec3 cameraToVertex; + if ( isOrthographic ) { + cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vReflect = reflect( cameraToVertex, worldNormal ); + #else + vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); + #endif + #endif +#endif`,nu=`#ifdef USE_FOG + vFogDepth = - mvPosition.z; +#endif`,iu=`#ifdef USE_FOG + varying float vFogDepth; +#endif`,ru=`#ifdef USE_FOG + #ifdef FOG_EXP2 + float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); + #else + float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); + #endif + gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); +#endif`,su=`#ifdef USE_FOG + uniform vec3 fogColor; + varying float vFogDepth; + #ifdef FOG_EXP2 + uniform float fogDensity; + #else + uniform float fogNear; + uniform float fogFar; + #endif +#endif`,au=`#ifdef USE_GRADIENTMAP + uniform sampler2D gradientMap; +#endif +vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { + float dotNL = dot( normal, lightDirection ); + vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); + #ifdef USE_GRADIENTMAP + return vec3( texture2D( gradientMap, coord ).r ); + #else + vec2 fw = fwidth( coord ) * 0.5; + return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); + #endif +}`,ou=`#ifdef USE_LIGHTMAP + uniform sampler2D lightMap; + uniform float lightMapIntensity; +#endif`,lu=`LambertMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularStrength = specularStrength;`,cu=`varying vec3 vViewPosition; +struct LambertMaterial { + vec3 diffuseColor; + float specularStrength; +}; +void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Lambert +#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,uu=`uniform bool receiveShadow; +uniform vec3 ambientLightColor; +#if defined( USE_LIGHT_PROBES ) + uniform vec3 lightProbe[ 9 ]; +#endif +vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { + float x = normal.x, y = normal.y, z = normal.z; + vec3 result = shCoefficients[ 0 ] * 0.886227; + result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; + result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; + result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; + result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; + result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; + result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); + result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; + result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); + return result; +} +vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); + return irradiance; +} +vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { + vec3 irradiance = ambientLightColor; + return irradiance; +} +float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { + float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); + if ( cutoffDistance > 0.0 ) { + distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); + } + return distanceFalloff; +} +float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { + return smoothstep( coneCosine, penumbraCosine, angleCosine ); +} +#if NUM_DIR_LIGHTS > 0 + struct DirectionalLight { + vec3 direction; + vec3 color; + }; + uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; + void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { + light.color = directionalLight.color; + light.direction = directionalLight.direction; + light.visible = true; + } +#endif +#if NUM_POINT_LIGHTS > 0 + struct PointLight { + vec3 position; + vec3 color; + float distance; + float decay; + }; + uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; + void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = pointLight.position - geometryPosition; + light.direction = normalize( lVector ); + float lightDistance = length( lVector ); + light.color = pointLight.color; + light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } +#endif +#if NUM_SPOT_LIGHTS > 0 + struct SpotLight { + vec3 position; + vec3 direction; + vec3 color; + float distance; + float decay; + float coneCos; + float penumbraCos; + }; + uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; + void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = spotLight.position - geometryPosition; + light.direction = normalize( lVector ); + float angleCos = dot( light.direction, spotLight.direction ); + float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); + if ( spotAttenuation > 0.0 ) { + float lightDistance = length( lVector ); + light.color = spotLight.color * spotAttenuation; + light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } else { + light.color = vec3( 0.0 ); + light.visible = false; + } + } +#endif +#if NUM_RECT_AREA_LIGHTS > 0 + struct RectAreaLight { + vec3 color; + vec3 position; + vec3 halfWidth; + vec3 halfHeight; + }; + uniform sampler2D ltc_1; uniform sampler2D ltc_2; + uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; +#endif +#if NUM_HEMI_LIGHTS > 0 + struct HemisphereLight { + vec3 direction; + vec3 skyColor; + vec3 groundColor; + }; + uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; + vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { + float dotNL = dot( normal, hemiLight.direction ); + float hemiDiffuseWeight = 0.5 * dotNL + 0.5; + vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); + return irradiance; + } +#endif`,hu=`#ifdef USE_ENVMAP + vec3 getIBLIrradiance( const in vec3 normal ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); + return PI * envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 reflectVec = reflect( - viewDir, normal ); + reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) ); + reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); + return envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + #ifdef USE_ANISOTROPY + vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 bentNormal = cross( bitangent, viewDir ); + bentNormal = normalize( cross( bentNormal, bitangent ) ); + bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); + return getIBLRadiance( viewDir, bentNormal, roughness ); + #else + return vec3( 0.0 ); + #endif + } + #endif +#endif`,du=`ToonMaterial material; +material.diffuseColor = diffuseColor.rgb;`,fu=`varying vec3 vViewPosition; +struct ToonMaterial { + vec3 diffuseColor; +}; +void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Toon +#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,pu=`BlinnPhongMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularColor = specular; +material.specularShininess = shininess; +material.specularStrength = specularStrength;`,mu=`varying vec3 vViewPosition; +struct BlinnPhongMaterial { + vec3 diffuseColor; + vec3 specularColor; + float specularShininess; + float specularStrength; +}; +void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); + reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; +} +void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_BlinnPhong +#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,gu=`PhysicalMaterial material; +material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); +vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); +float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); +material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; +material.roughness = min( material.roughness, 1.0 ); +#ifdef IOR + material.ior = ior; + #ifdef USE_SPECULAR + float specularIntensityFactor = specularIntensity; + vec3 specularColorFactor = specularColor; + #ifdef USE_SPECULAR_COLORMAP + specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; + #endif + material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); + #else + float specularIntensityFactor = 1.0; + vec3 specularColorFactor = vec3( 1.0 ); + material.specularF90 = 1.0; + #endif + material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor ); +#else + material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor ); + material.specularF90 = 1.0; +#endif +#ifdef USE_CLEARCOAT + material.clearcoat = clearcoat; + material.clearcoatRoughness = clearcoatRoughness; + material.clearcoatF0 = vec3( 0.04 ); + material.clearcoatF90 = 1.0; + #ifdef USE_CLEARCOATMAP + material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; + #endif + #ifdef USE_CLEARCOAT_ROUGHNESSMAP + material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; + #endif + material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); + material.clearcoatRoughness += geometryRoughness; + material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); +#endif +#ifdef USE_DISPERSION + material.dispersion = dispersion; +#endif +#ifdef USE_IRIDESCENCE + material.iridescence = iridescence; + material.iridescenceIOR = iridescenceIOR; + #ifdef USE_IRIDESCENCEMAP + material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; + #endif + #ifdef USE_IRIDESCENCE_THICKNESSMAP + material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; + #else + material.iridescenceThickness = iridescenceThicknessMaximum; + #endif +#endif +#ifdef USE_SHEEN + material.sheenColor = sheenColor; + #ifdef USE_SHEEN_COLORMAP + material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; + #endif + material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 ); + #ifdef USE_SHEEN_ROUGHNESSMAP + material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; + #endif +#endif +#ifdef USE_ANISOTROPY + #ifdef USE_ANISOTROPYMAP + mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); + vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; + vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; + #else + vec2 anisotropyV = anisotropyVector; + #endif + material.anisotropy = length( anisotropyV ); + if( material.anisotropy == 0.0 ) { + anisotropyV = vec2( 1.0, 0.0 ); + } else { + anisotropyV /= material.anisotropy; + material.anisotropy = saturate( material.anisotropy ); + } + material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); + material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; + material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; +#endif`,_u=`struct PhysicalMaterial { + vec3 diffuseColor; + float roughness; + vec3 specularColor; + float specularF90; + float dispersion; + #ifdef USE_CLEARCOAT + float clearcoat; + float clearcoatRoughness; + vec3 clearcoatF0; + float clearcoatF90; + #endif + #ifdef USE_IRIDESCENCE + float iridescence; + float iridescenceIOR; + float iridescenceThickness; + vec3 iridescenceFresnel; + vec3 iridescenceF0; + #endif + #ifdef USE_SHEEN + vec3 sheenColor; + float sheenRoughness; + #endif + #ifdef IOR + float ior; + #endif + #ifdef USE_TRANSMISSION + float transmission; + float transmissionAlpha; + float thickness; + float attenuationDistance; + vec3 attenuationColor; + #endif + #ifdef USE_ANISOTROPY + float anisotropy; + float alphaT; + vec3 anisotropyT; + vec3 anisotropyB; + #endif +}; +vec3 clearcoatSpecularDirect = vec3( 0.0 ); +vec3 clearcoatSpecularIndirect = vec3( 0.0 ); +vec3 sheenSpecularDirect = vec3( 0.0 ); +vec3 sheenSpecularIndirect = vec3(0.0 ); +vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { + float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); + float x2 = x * x; + float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); + return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); +} +float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { + float a2 = pow2( alpha ); + float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); + float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); + return 0.5 / max( gv + gl, EPSILON ); +} +float D_GGX( const in float alpha, const in float dotNH ) { + float a2 = pow2( alpha ); + float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; + return RECIPROCAL_PI * a2 / pow2( denom ); +} +#ifdef USE_ANISOTROPY + float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { + float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); + float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); + float v = 0.5 / ( gv + gl ); + return saturate(v); + } + float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { + float a2 = alphaT * alphaB; + highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); + highp float v2 = dot( v, v ); + float w2 = a2 / v2; + return RECIPROCAL_PI * a2 * pow2 ( w2 ); + } +#endif +#ifdef USE_CLEARCOAT + vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { + vec3 f0 = material.clearcoatF0; + float f90 = material.clearcoatF90; + float roughness = material.clearcoatRoughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + return F * ( V * D ); + } +#endif +vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { + vec3 f0 = material.specularColor; + float f90 = material.specularF90; + float roughness = material.roughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + #ifdef USE_IRIDESCENCE + F = mix( F, material.iridescenceFresnel, material.iridescence ); + #endif + #ifdef USE_ANISOTROPY + float dotTL = dot( material.anisotropyT, lightDir ); + float dotTV = dot( material.anisotropyT, viewDir ); + float dotTH = dot( material.anisotropyT, halfDir ); + float dotBL = dot( material.anisotropyB, lightDir ); + float dotBV = dot( material.anisotropyB, viewDir ); + float dotBH = dot( material.anisotropyB, halfDir ); + float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); + float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); + #else + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + #endif + return F * ( V * D ); +} +vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { + const float LUT_SIZE = 64.0; + const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; + const float LUT_BIAS = 0.5 / LUT_SIZE; + float dotNV = saturate( dot( N, V ) ); + vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); + uv = uv * LUT_SCALE + LUT_BIAS; + return uv; +} +float LTC_ClippedSphereFormFactor( const in vec3 f ) { + float l = length( f ); + return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); +} +vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { + float x = dot( v1, v2 ); + float y = abs( x ); + float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; + float b = 3.4175940 + ( 4.1616724 + y ) * y; + float v = a / b; + float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; + return cross( v1, v2 ) * theta_sintheta; +} +vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { + vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; + vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; + vec3 lightNormal = cross( v1, v2 ); + if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); + vec3 T1, T2; + T1 = normalize( V - N * dot( V, N ) ); + T2 = - cross( N, T1 ); + mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) ); + vec3 coords[ 4 ]; + coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); + coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); + coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); + coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); + coords[ 0 ] = normalize( coords[ 0 ] ); + coords[ 1 ] = normalize( coords[ 1 ] ); + coords[ 2 ] = normalize( coords[ 2 ] ); + coords[ 3 ] = normalize( coords[ 3 ] ); + vec3 vectorFormFactor = vec3( 0.0 ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); + float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); + return vec3( result ); +} +#if defined( USE_SHEEN ) +float D_Charlie( float roughness, float dotNH ) { + float alpha = pow2( roughness ); + float invAlpha = 1.0 / alpha; + float cos2h = dotNH * dotNH; + float sin2h = max( 1.0 - cos2h, 0.0078125 ); + return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); +} +float V_Neubelt( float dotNV, float dotNL ) { + return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); +} +vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float D = D_Charlie( sheenRoughness, dotNH ); + float V = V_Neubelt( dotNV, dotNL ); + return sheenColor * ( D * V ); +} +#endif +float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + float r2 = roughness * roughness; + float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95; + float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72; + float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) ); + return saturate( DG * RECIPROCAL_PI ); +} +vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 ); + const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 ); + vec4 r = roughness * c0 + c1; + float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y; + vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw; + return fab; +} +vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { + vec2 fab = DFGApprox( normal, viewDir, roughness ); + return specularColor * fab.x + specularF90 * fab.y; +} +#ifdef USE_IRIDESCENCE +void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#else +void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#endif + vec2 fab = DFGApprox( normal, viewDir, roughness ); + #ifdef USE_IRIDESCENCE + vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); + #else + vec3 Fr = specularColor; + #endif + vec3 FssEss = Fr * fab.x + specularF90 * fab.y; + float Ess = fab.x + fab.y; + float Ems = 1.0 - Ess; + vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); + singleScatter += FssEss; + multiScatter += Fms * Ems; +} +#if NUM_RECT_AREA_LIGHTS > 0 + void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + vec3 normal = geometryNormal; + vec3 viewDir = geometryViewDir; + vec3 position = geometryPosition; + vec3 lightPos = rectAreaLight.position; + vec3 halfWidth = rectAreaLight.halfWidth; + vec3 halfHeight = rectAreaLight.halfHeight; + vec3 lightColor = rectAreaLight.color; + float roughness = material.roughness; + vec3 rectCoords[ 4 ]; + rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; + rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; + rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; + vec2 uv = LTC_Uv( normal, viewDir, roughness ); + vec4 t1 = texture2D( ltc_1, uv ); + vec4 t2 = texture2D( ltc_2, uv ); + mat3 mInv = mat3( + vec3( t1.x, 0, t1.y ), + vec3( 0, 1, 0 ), + vec3( t1.z, 0, t1.w ) + ); + vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y ); + reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); + reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); + } +#endif +void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + #ifdef USE_CLEARCOAT + float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); + vec3 ccIrradiance = dotNLcc * directLight.color; + clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); + #endif + #ifdef USE_SHEEN + sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); + #endif + reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material ); + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { + #ifdef USE_CLEARCOAT + clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); + #endif + #ifdef USE_SHEEN + sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); + #endif + vec3 singleScattering = vec3( 0.0 ); + vec3 multiScattering = vec3( 0.0 ); + vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; + #ifdef USE_IRIDESCENCE + computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering ); + #else + computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering ); + #endif + vec3 totalScattering = singleScattering + multiScattering; + vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) ); + reflectedLight.indirectSpecular += radiance * singleScattering; + reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance; + reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance; +} +#define RE_Direct RE_Direct_Physical +#define RE_Direct_RectArea RE_Direct_RectArea_Physical +#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical +#define RE_IndirectSpecular RE_IndirectSpecular_Physical +float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { + return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); +}`,vu=` +vec3 geometryPosition = - vViewPosition; +vec3 geometryNormal = normal; +vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); +vec3 geometryClearcoatNormal = vec3( 0.0 ); +#ifdef USE_CLEARCOAT + geometryClearcoatNormal = clearcoatNormal; +#endif +#ifdef USE_IRIDESCENCE + float dotNVi = saturate( dot( normal, geometryViewDir ) ); + if ( material.iridescenceThickness == 0.0 ) { + material.iridescence = 0.0; + } else { + material.iridescence = saturate( material.iridescence ); + } + if ( material.iridescence > 0.0 ) { + material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); + material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); + } +#endif +IncidentLight directLight; +#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + PointLight pointLight; + #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + pointLight = pointLights[ i ]; + getPointLightInfo( pointLight, geometryPosition, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) + pointLightShadow = pointLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + SpotLight spotLight; + vec4 spotColor; + vec3 spotLightCoord; + bool inSpotLightMap; + #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + spotLight = spotLights[ i ]; + getSpotLightInfo( spotLight, geometryPosition, directLight ); + #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX + #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS + #else + #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #endif + #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) + spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; + inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); + spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); + directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; + #endif + #undef SPOT_LIGHT_MAP_INDEX + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + spotLightShadow = spotLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) + DirectionalLight directionalLight; + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) + RectAreaLight rectAreaLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { + rectAreaLight = rectAreaLights[ i ]; + RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if defined( RE_IndirectDiffuse ) + vec3 iblIrradiance = vec3( 0.0 ); + vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + #if defined( USE_LIGHT_PROBES ) + irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); + #endif + #if ( NUM_HEMI_LIGHTS > 0 ) + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); + } + #pragma unroll_loop_end + #endif +#endif +#if defined( RE_IndirectSpecular ) + vec3 radiance = vec3( 0.0 ); + vec3 clearcoatRadiance = vec3( 0.0 ); +#endif`,xu=`#if defined( RE_IndirectDiffuse ) + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; + irradiance += lightMapIrradiance; + #endif + #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV ) + iblIrradiance += getIBLIrradiance( geometryNormal ); + #endif +#endif +#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) + #ifdef USE_ANISOTROPY + radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); + #else + radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); + #endif + #ifdef USE_CLEARCOAT + clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); + #endif +#endif`,Mu=`#if defined( RE_IndirectDiffuse ) + RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif +#if defined( RE_IndirectSpecular ) + RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif`,Su=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) + gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; +#endif`,Eu=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) + uniform float logDepthBufFC; + varying float vFragDepth; + varying float vIsPerspective; +#endif`,yu=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER + varying float vFragDepth; + varying float vIsPerspective; +#endif`,Tu=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER + vFragDepth = 1.0 + gl_Position.w; + vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); +#endif`,Au=`#ifdef USE_MAP + vec4 sampledDiffuseColor = texture2D( map, vMapUv ); + #ifdef DECODE_VIDEO_TEXTURE + sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); + #endif + diffuseColor *= sampledDiffuseColor; +#endif`,bu=`#ifdef USE_MAP + uniform sampler2D map; +#endif`,wu=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + #if defined( USE_POINTS_UV ) + vec2 uv = vUv; + #else + vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; + #endif +#endif +#ifdef USE_MAP + diffuseColor *= texture2D( map, uv ); +#endif +#ifdef USE_ALPHAMAP + diffuseColor.a *= texture2D( alphaMap, uv ).g; +#endif`,Ru=`#if defined( USE_POINTS_UV ) + varying vec2 vUv; +#else + #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + uniform mat3 uvTransform; + #endif +#endif +#ifdef USE_MAP + uniform sampler2D map; +#endif +#ifdef USE_ALPHAMAP + uniform sampler2D alphaMap; +#endif`,Cu=`float metalnessFactor = metalness; +#ifdef USE_METALNESSMAP + vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); + metalnessFactor *= texelMetalness.b; +#endif`,Pu=`#ifdef USE_METALNESSMAP + uniform sampler2D metalnessMap; +#endif`,Du=`#ifdef USE_INSTANCING_MORPH + float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; + } +#endif`,Lu=`#if defined( USE_MORPHCOLORS ) + vColor *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + #if defined( USE_COLOR_ALPHA ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; + #elif defined( USE_COLOR ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; + #endif + } +#endif`,Iu=`#ifdef USE_MORPHNORMALS + objectNormal *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; + } +#endif`,Uu=`#ifdef USE_MORPHTARGETS + #ifndef USE_INSTANCING_MORPH + uniform float morphTargetBaseInfluence; + uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + #endif + uniform sampler2DArray morphTargetsTexture; + uniform ivec2 morphTargetsTextureSize; + vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { + int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; + int y = texelIndex / morphTargetsTextureSize.x; + int x = texelIndex - y * morphTargetsTextureSize.x; + ivec3 morphUV = ivec3( x, y, morphTargetIndex ); + return texelFetch( morphTargetsTexture, morphUV, 0 ); + } +#endif`,Nu=`#ifdef USE_MORPHTARGETS + transformed *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; + } +#endif`,Fu=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; +#ifdef FLAT_SHADED + vec3 fdx = dFdx( vViewPosition ); + vec3 fdy = dFdy( vViewPosition ); + vec3 normal = normalize( cross( fdx, fdy ) ); +#else + vec3 normal = normalize( vNormal ); + #ifdef DOUBLE_SIDED + normal *= faceDirection; + #endif +#endif +#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) + #ifdef USE_TANGENT + mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn = getTangentFrame( - vViewPosition, normal, + #if defined( USE_NORMALMAP ) + vNormalMapUv + #elif defined( USE_CLEARCOAT_NORMALMAP ) + vClearcoatNormalMapUv + #else + vUv + #endif + ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn[0] *= faceDirection; + tbn[1] *= faceDirection; + #endif +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + #ifdef USE_TANGENT + mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn2[0] *= faceDirection; + tbn2[1] *= faceDirection; + #endif +#endif +vec3 nonPerturbedNormal = normal;`,Ou=`#ifdef USE_NORMALMAP_OBJECTSPACE + normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + #ifdef FLIP_SIDED + normal = - normal; + #endif + #ifdef DOUBLE_SIDED + normal = normal * faceDirection; + #endif + normal = normalize( normalMatrix * normal ); +#elif defined( USE_NORMALMAP_TANGENTSPACE ) + vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + mapN.xy *= normalScale; + normal = normalize( tbn * mapN ); +#elif defined( USE_BUMPMAP ) + normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); +#endif`,Bu=`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,Hu=`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,zu=`#ifndef FLAT_SHADED + vNormal = normalize( transformedNormal ); + #ifdef USE_TANGENT + vTangent = normalize( transformedTangent ); + vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); + #endif +#endif`,Gu=`#ifdef USE_NORMALMAP + uniform sampler2D normalMap; + uniform vec2 normalScale; +#endif +#ifdef USE_NORMALMAP_OBJECTSPACE + uniform mat3 normalMatrix; +#endif +#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) + mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { + vec3 q0 = dFdx( eye_pos.xyz ); + vec3 q1 = dFdy( eye_pos.xyz ); + vec2 st0 = dFdx( uv.st ); + vec2 st1 = dFdy( uv.st ); + vec3 N = surf_norm; + vec3 q1perp = cross( q1, N ); + vec3 q0perp = cross( N, q0 ); + vec3 T = q1perp * st0.x + q0perp * st1.x; + vec3 B = q1perp * st0.y + q0perp * st1.y; + float det = max( dot( T, T ), dot( B, B ) ); + float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); + return mat3( T * scale, B * scale, N ); + } +#endif`,ku=`#ifdef USE_CLEARCOAT + vec3 clearcoatNormal = nonPerturbedNormal; +#endif`,Vu=`#ifdef USE_CLEARCOAT_NORMALMAP + vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; + clearcoatMapN.xy *= clearcoatNormalScale; + clearcoatNormal = normalize( tbn2 * clearcoatMapN ); +#endif`,Wu=`#ifdef USE_CLEARCOATMAP + uniform sampler2D clearcoatMap; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform sampler2D clearcoatNormalMap; + uniform vec2 clearcoatNormalScale; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform sampler2D clearcoatRoughnessMap; +#endif`,Xu=`#ifdef USE_IRIDESCENCEMAP + uniform sampler2D iridescenceMap; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform sampler2D iridescenceThicknessMap; +#endif`,qu=`#ifdef OPAQUE +diffuseColor.a = 1.0; +#endif +#ifdef USE_TRANSMISSION +diffuseColor.a *= material.transmissionAlpha; +#endif +gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,Yu=`vec3 packNormalToRGB( const in vec3 normal ) { + return normalize( normal ) * 0.5 + 0.5; +} +vec3 unpackRGBToNormal( const in vec3 rgb ) { + return 2.0 * rgb.xyz - 1.0; +} +const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; +const float Inv255 = 1. / 255.; +const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); +const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); +const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); +const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); +vec4 packDepthToRGBA( const in float v ) { + if( v <= 0.0 ) + return vec4( 0., 0., 0., 0. ); + if( v >= 1.0 ) + return vec4( 1., 1., 1., 1. ); + float vuf; + float af = modf( v * PackFactors.a, vuf ); + float bf = modf( vuf * ShiftRight8, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); +} +vec3 packDepthToRGB( const in float v ) { + if( v <= 0.0 ) + return vec3( 0., 0., 0. ); + if( v >= 1.0 ) + return vec3( 1., 1., 1. ); + float vuf; + float bf = modf( v * PackFactors.b, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec3( vuf * Inv255, gf * PackUpscale, bf ); +} +vec2 packDepthToRG( const in float v ) { + if( v <= 0.0 ) + return vec2( 0., 0. ); + if( v >= 1.0 ) + return vec2( 1., 1. ); + float vuf; + float gf = modf( v * 256., vuf ); + return vec2( vuf * Inv255, gf ); +} +float unpackRGBAToDepth( const in vec4 v ) { + return dot( v, UnpackFactors4 ); +} +float unpackRGBToDepth( const in vec3 v ) { + return dot( v, UnpackFactors3 ); +} +float unpackRGToDepth( const in vec2 v ) { + return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; +} +vec4 pack2HalfToRGBA( const in vec2 v ) { + vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); + return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); +} +vec2 unpackRGBATo2Half( const in vec4 v ) { + return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); +} +float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { + return ( viewZ + near ) / ( near - far ); +} +float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { + return depth * ( near - far ) - near; +} +float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { + return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); +} +float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { + return ( near * far ) / ( ( far - near ) * depth - far ); +}`,$u=`#ifdef PREMULTIPLIED_ALPHA + gl_FragColor.rgb *= gl_FragColor.a; +#endif`,Ku=`vec4 mvPosition = vec4( transformed, 1.0 ); +#ifdef USE_BATCHING + mvPosition = batchingMatrix * mvPosition; +#endif +#ifdef USE_INSTANCING + mvPosition = instanceMatrix * mvPosition; +#endif +mvPosition = modelViewMatrix * mvPosition; +gl_Position = projectionMatrix * mvPosition;`,Zu=`#ifdef DITHERING + gl_FragColor.rgb = dithering( gl_FragColor.rgb ); +#endif`,ju=`#ifdef DITHERING + vec3 dithering( vec3 color ) { + float grid_position = rand( gl_FragCoord.xy ); + vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); + dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); + return color + dither_shift_RGB; + } +#endif`,Ju=`float roughnessFactor = roughness; +#ifdef USE_ROUGHNESSMAP + vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); + roughnessFactor *= texelRoughness.g; +#endif`,Qu=`#ifdef USE_ROUGHNESSMAP + uniform sampler2D roughnessMap; +#endif`,eh=`#if NUM_SPOT_LIGHT_COORDS > 0 + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#if NUM_SPOT_LIGHT_MAPS > 0 + uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif + float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { + float depth = unpackRGBAToDepth( texture2D( depths, uv ) ); + #ifdef USE_REVERSED_DEPTH_BUFFER + return step( depth, compare ); + #else + return step( compare, depth ); + #endif + } + vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) { + return unpackRGBATo2Half( texture2D( shadow, uv ) ); + } + float VSMShadow( sampler2D shadow, vec2 uv, float compare ) { + float occlusion = 1.0; + vec2 distribution = texture2DDistribution( shadow, uv ); + #ifdef USE_REVERSED_DEPTH_BUFFER + float hard_shadow = step( distribution.x, compare ); + #else + float hard_shadow = step( compare, distribution.x ); + #endif + if ( hard_shadow != 1.0 ) { + float distance = compare - distribution.x; + float variance = max( 0.00000, distribution.y * distribution.y ); + float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 ); + } + return occlusion; + } + float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + shadowCoord.z += shadowBias; + bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; + bool frustumTest = inFrustum && shadowCoord.z <= 1.0; + if ( frustumTest ) { + #if defined( SHADOWMAP_TYPE_PCF ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx0 = - texelSize.x * shadowRadius; + float dy0 = - texelSize.y * shadowRadius; + float dx1 = + texelSize.x * shadowRadius; + float dy1 = + texelSize.y * shadowRadius; + float dx2 = dx0 / 2.0; + float dy2 = dy0 / 2.0; + float dx3 = dx1 / 2.0; + float dy3 = dy1 / 2.0; + shadow = ( + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) + ) * ( 1.0 / 17.0 ); + #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx = texelSize.x; + float dy = texelSize.y; + vec2 uv = shadowCoord.xy; + vec2 f = fract( uv * shadowMapSize + 0.5 ); + uv -= f * texelSize; + shadow = ( + texture2DCompare( shadowMap, uv, shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ), + f.x ), + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ), + f.x ), + f.y ) + ) * ( 1.0 / 9.0 ); + #elif defined( SHADOWMAP_TYPE_VSM ) + shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z ); + #else + shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } + vec2 cubeToUV( vec3 v, float texelSizeY ) { + vec3 absV = abs( v ); + float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); + absV *= scaleToCube; + v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); + vec2 planar = v.xy; + float almostATexel = 1.5 * texelSizeY; + float almostOne = 1.0 - almostATexel; + if ( absV.z >= almostOne ) { + if ( v.z > 0.0 ) + planar.x = 4.0 - v.x; + } else if ( absV.x >= almostOne ) { + float signX = sign( v.x ); + planar.x = v.z * signX + 2.0 * signX; + } else if ( absV.y >= almostOne ) { + float signY = sign( v.y ); + planar.x = v.x + 2.0 * signY + 2.0; + planar.y = v.z * signY - 2.0; + } + return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); + } + float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { + float shadow = 1.0; + vec3 lightToPosition = shadowCoord.xyz; + + float lightToPositionLength = length( lightToPosition ); + if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) { + float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias; + vec3 bd3D = normalize( lightToPosition ); + vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); + #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM ) + vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; + shadow = ( + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) + ) * ( 1.0 / 9.0 ); + #else + shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } +#endif`,th=`#if NUM_SPOT_LIGHT_COORDS > 0 + uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif +#endif`,nh=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) + vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + vec4 shadowWorldPosition; +#endif +#if defined( USE_SHADOWMAP ) + #if NUM_DIR_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); + vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); + vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif +#endif +#if NUM_SPOT_LIGHT_COORDS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { + shadowWorldPosition = worldPosition; + #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; + #endif + vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end +#endif`,ih=`float getShadowMask() { + float shadow = 1.0; + #ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + directionalLight = directionalLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { + spotLight = spotLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + pointLight = pointLightShadows[ i ]; + shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; + } + #pragma unroll_loop_end + #endif + #endif + return shadow; +}`,rh=`#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); +#endif`,sh=`#ifdef USE_SKINNING + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + uniform highp sampler2D boneTexture; + mat4 getBoneMatrix( const in float i ) { + int size = textureSize( boneTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } +#endif`,ah=`#ifdef USE_SKINNING + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + transformed = ( bindMatrixInverse * skinned ).xyz; +#endif`,oh=`#ifdef USE_SKINNING + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; + #ifdef USE_TANGENT + objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; + #endif +#endif`,lh=`float specularStrength; +#ifdef USE_SPECULARMAP + vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); + specularStrength = texelSpecular.r; +#else + specularStrength = 1.0; +#endif`,ch=`#ifdef USE_SPECULARMAP + uniform sampler2D specularMap; +#endif`,uh=`#if defined( TONE_MAPPING ) + gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); +#endif`,hh=`#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +uniform float toneMappingExposure; +vec3 LinearToneMapping( vec3 color ) { + return saturate( toneMappingExposure * color ); +} +vec3 ReinhardToneMapping( vec3 color ) { + color *= toneMappingExposure; + return saturate( color / ( vec3( 1.0 ) + color ) ); +} +vec3 CineonToneMapping( vec3 color ) { + color *= toneMappingExposure; + color = max( vec3( 0.0 ), color - 0.004 ); + return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); +} +vec3 RRTAndODTFit( vec3 v ) { + vec3 a = v * ( v + 0.0245786 ) - 0.000090537; + vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; + return a / b; +} +vec3 ACESFilmicToneMapping( vec3 color ) { + const mat3 ACESInputMat = mat3( + vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), + vec3( 0.04823, 0.01566, 0.83777 ) + ); + const mat3 ACESOutputMat = mat3( + vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), + vec3( -0.07367, -0.00605, 1.07602 ) + ); + color *= toneMappingExposure / 0.6; + color = ACESInputMat * color; + color = RRTAndODTFit( color ); + color = ACESOutputMat * color; + return saturate( color ); +} +const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( + vec3( 1.6605, - 0.1246, - 0.0182 ), + vec3( - 0.5876, 1.1329, - 0.1006 ), + vec3( - 0.0728, - 0.0083, 1.1187 ) +); +const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( + vec3( 0.6274, 0.0691, 0.0164 ), + vec3( 0.3293, 0.9195, 0.0880 ), + vec3( 0.0433, 0.0113, 0.8956 ) +); +vec3 agxDefaultContrastApprox( vec3 x ) { + vec3 x2 = x * x; + vec3 x4 = x2 * x2; + return + 15.5 * x4 * x2 + - 40.14 * x4 * x + + 31.96 * x4 + - 6.868 * x2 * x + + 0.4298 * x2 + + 0.1191 * x + - 0.00232; +} +vec3 AgXToneMapping( vec3 color ) { + const mat3 AgXInsetMatrix = mat3( + vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), + vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), + vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) + ); + const mat3 AgXOutsetMatrix = mat3( + vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), + vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), + vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) + ); + const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; + color *= toneMappingExposure; + color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; + color = AgXInsetMatrix * color; + color = max( color, 1e-10 ); color = log2( color ); + color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); + color = clamp( color, 0.0, 1.0 ); + color = agxDefaultContrastApprox( color ); + color = AgXOutsetMatrix * color; + color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); + color = LINEAR_REC2020_TO_LINEAR_SRGB * color; + color = clamp( color, 0.0, 1.0 ); + return color; +} +vec3 NeutralToneMapping( vec3 color ) { + const float StartCompression = 0.8 - 0.04; + const float Desaturation = 0.15; + color *= toneMappingExposure; + float x = min( color.r, min( color.g, color.b ) ); + float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; + color -= offset; + float peak = max( color.r, max( color.g, color.b ) ); + if ( peak < StartCompression ) return color; + float d = 1. - StartCompression; + float newPeak = 1. - d * d / ( peak + d - StartCompression ); + color *= newPeak / peak; + float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); + return mix( color, vec3( newPeak ), g ); +} +vec3 CustomToneMapping( vec3 color ) { return color; }`,dh=`#ifdef USE_TRANSMISSION + material.transmission = transmission; + material.transmissionAlpha = 1.0; + material.thickness = thickness; + material.attenuationDistance = attenuationDistance; + material.attenuationColor = attenuationColor; + #ifdef USE_TRANSMISSIONMAP + material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; + #endif + #ifdef USE_THICKNESSMAP + material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; + #endif + vec3 pos = vWorldPosition; + vec3 v = normalize( cameraPosition - pos ); + vec3 n = inverseTransformDirection( normal, viewMatrix ); + vec4 transmitted = getIBLVolumeRefraction( + n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, + pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, + material.attenuationColor, material.attenuationDistance ); + material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); + totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); +#endif`,fh=`#ifdef USE_TRANSMISSION + uniform float transmission; + uniform float thickness; + uniform float attenuationDistance; + uniform vec3 attenuationColor; + #ifdef USE_TRANSMISSIONMAP + uniform sampler2D transmissionMap; + #endif + #ifdef USE_THICKNESSMAP + uniform sampler2D thicknessMap; + #endif + uniform vec2 transmissionSamplerSize; + uniform sampler2D transmissionSamplerMap; + uniform mat4 modelMatrix; + uniform mat4 projectionMatrix; + varying vec3 vWorldPosition; + float w0( float a ) { + return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); + } + float w1( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); + } + float w2( float a ){ + return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); + } + float w3( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * a ); + } + float g0( float a ) { + return w0( a ) + w1( a ); + } + float g1( float a ) { + return w2( a ) + w3( a ); + } + float h0( float a ) { + return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); + } + float h1( float a ) { + return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); + } + vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { + uv = uv * texelSize.zw + 0.5; + vec2 iuv = floor( uv ); + vec2 fuv = fract( uv ); + float g0x = g0( fuv.x ); + float g1x = g1( fuv.x ); + float h0x = h0( fuv.x ); + float h1x = h1( fuv.x ); + float h0y = h0( fuv.y ); + float h1y = h1( fuv.y ); + vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + + g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); + } + vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { + vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); + vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); + vec2 fLodSizeInv = 1.0 / fLodSize; + vec2 cLodSizeInv = 1.0 / cLodSize; + vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); + vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); + return mix( fSample, cSample, fract( lod ) ); + } + vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { + vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); + vec3 modelScale; + modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); + modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); + modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); + return normalize( refractionVector ) * thickness * modelScale; + } + float applyIorToRoughness( const in float roughness, const in float ior ) { + return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); + } + vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { + float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); + return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); + } + vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { + if ( isinf( attenuationDistance ) ) { + return vec3( 1.0 ); + } else { + vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; + vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; + } + } + vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, + const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, + const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, + const in vec3 attenuationColor, const in float attenuationDistance ) { + vec4 transmittedLight; + vec3 transmittance; + #ifdef USE_DISPERSION + float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; + vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); + for ( int i = 0; i < 3; i ++ ) { + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); + transmittedLight[ i ] = transmissionSample[ i ]; + transmittedLight.a += transmissionSample.a; + transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; + } + transmittedLight.a /= 3.0; + #else + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); + transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); + #endif + vec3 attenuatedColor = transmittance * transmittedLight.rgb; + vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); + float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; + return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); + } +#endif`,ph=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + varying vec2 vNormalMapUv; +#endif +#ifdef USE_EMISSIVEMAP + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_SPECULARMAP + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`,mh=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + uniform mat3 mapTransform; + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + uniform mat3 alphaMapTransform; + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + uniform mat3 lightMapTransform; + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + uniform mat3 aoMapTransform; + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + uniform mat3 bumpMapTransform; + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + uniform mat3 normalMapTransform; + varying vec2 vNormalMapUv; +#endif +#ifdef USE_DISPLACEMENTMAP + uniform mat3 displacementMapTransform; + varying vec2 vDisplacementMapUv; +#endif +#ifdef USE_EMISSIVEMAP + uniform mat3 emissiveMapTransform; + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + uniform mat3 metalnessMapTransform; + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + uniform mat3 roughnessMapTransform; + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + uniform mat3 anisotropyMapTransform; + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + uniform mat3 clearcoatMapTransform; + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform mat3 clearcoatNormalMapTransform; + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform mat3 clearcoatRoughnessMapTransform; + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + uniform mat3 sheenColorMapTransform; + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + uniform mat3 sheenRoughnessMapTransform; + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + uniform mat3 iridescenceMapTransform; + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform mat3 iridescenceThicknessMapTransform; + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SPECULARMAP + uniform mat3 specularMapTransform; + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + uniform mat3 specularColorMapTransform; + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + uniform mat3 specularIntensityMapTransform; + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`,gh=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + vUv = vec3( uv, 1 ).xy; +#endif +#ifdef USE_MAP + vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ALPHAMAP + vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_LIGHTMAP + vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_AOMAP + vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_BUMPMAP + vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_NORMALMAP + vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_DISPLACEMENTMAP + vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_EMISSIVEMAP + vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_METALNESSMAP + vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ROUGHNESSMAP + vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ANISOTROPYMAP + vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOATMAP + vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCEMAP + vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_COLORMAP + vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULARMAP + vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_COLORMAP + vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_TRANSMISSIONMAP + vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_THICKNESSMAP + vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; +#endif`,_h=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 + vec4 worldPosition = vec4( transformed, 1.0 ); + #ifdef USE_BATCHING + worldPosition = batchingMatrix * worldPosition; + #endif + #ifdef USE_INSTANCING + worldPosition = instanceMatrix * worldPosition; + #endif + worldPosition = modelMatrix * worldPosition; +#endif`;const vh=`varying vec2 vUv; +uniform mat3 uvTransform; +void main() { + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + gl_Position = vec4( position.xy, 1.0, 1.0 ); +}`,xh=`uniform sampler2D t2D; +uniform float backgroundIntensity; +varying vec2 vUv; +void main() { + vec4 texColor = texture2D( t2D, vUv ); + #ifdef DECODE_VIDEO_TEXTURE + texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`,Mh=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,Sh=`#ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; +#elif defined( ENVMAP_TYPE_CUBE_UV ) + uniform sampler2D envMap; +#endif +uniform float flipEnvMap; +uniform float backgroundBlurriness; +uniform float backgroundIntensity; +uniform mat3 backgroundRotation; +varying vec3 vWorldDirection; +#include +void main() { + #ifdef ENVMAP_TYPE_CUBE + vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); + #elif defined( ENVMAP_TYPE_CUBE_UV ) + vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); + #else + vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`,Eh=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,yh=`uniform samplerCube tCube; +uniform float tFlip; +uniform float opacity; +varying vec3 vWorldDirection; +void main() { + vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); + gl_FragColor = texColor; + gl_FragColor.a *= opacity; + #include + #include +}`,Th=`#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vHighPrecisionZW = gl_Position.zw; +}`,Ah=`#if DEPTH_PACKING == 3200 + uniform float opacity; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + vec4 diffuseColor = vec4( 1.0 ); + #include + #if DEPTH_PACKING == 3200 + diffuseColor.a = opacity; + #endif + #include + #include + #include + #include + #include + #ifdef USE_REVERSED_DEPTH_BUFFER + float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ]; + #else + float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5; + #endif + #if DEPTH_PACKING == 3200 + gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); + #elif DEPTH_PACKING == 3201 + gl_FragColor = packDepthToRGBA( fragCoordZ ); + #elif DEPTH_PACKING == 3202 + gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); + #elif DEPTH_PACKING == 3203 + gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); + #endif +}`,bh=`#define DISTANCE +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vWorldPosition = worldPosition.xyz; +}`,wh=`#define DISTANCE +uniform vec3 referencePosition; +uniform float nearDistance; +uniform float farDistance; +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +#include +void main () { + vec4 diffuseColor = vec4( 1.0 ); + #include + #include + #include + #include + #include + float dist = length( vWorldPosition - referencePosition ); + dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); + dist = saturate( dist ); + gl_FragColor = packDepthToRGBA( dist ); +}`,Rh=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include +}`,Ch=`uniform sampler2D tEquirect; +varying vec3 vWorldDirection; +#include +void main() { + vec3 direction = normalize( vWorldDirection ); + vec2 sampleUV = equirectUv( direction ); + gl_FragColor = texture2D( tEquirect, sampleUV ); + #include + #include +}`,Ph=`uniform float scale; +attribute float lineDistance; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vLineDistance = scale * lineDistance; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,Dh=`uniform vec3 diffuse; +uniform float opacity; +uniform float dashSize; +uniform float totalSize; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + if ( mod( vLineDistance, totalSize ) > dashSize ) { + discard; + } + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,Lh=`#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) + #include + #include + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,Ih=`uniform vec3 diffuse; +uniform float opacity; +#ifndef FLAT_SHADED + varying vec3 vNormal; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; + #else + reflectedLight.indirectDiffuse += vec3( 1.0 ); + #endif + #include + reflectedLight.indirectDiffuse *= diffuseColor.rgb; + vec3 outgoingLight = reflectedLight.indirectDiffuse; + #include + #include + #include + #include + #include + #include + #include +}`,Uh=`#define LAMBERT +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`,Nh=`#define LAMBERT +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,Fh=`#define MATCAP +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; +}`,Oh=`#define MATCAP +uniform vec3 diffuse; +uniform float opacity; +uniform sampler2D matcap; +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 viewDir = normalize( vViewPosition ); + vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); + vec3 y = cross( viewDir, x ); + vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; + #ifdef USE_MATCAP + vec4 matcapColor = texture2D( matcap, uv ); + #else + vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); + #endif + vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; + #include + #include + #include + #include + #include + #include +}`,Bh=`#define NORMAL +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + vViewPosition = - mvPosition.xyz; +#endif +}`,Hh=`#define NORMAL +uniform float opacity; +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); + #include + #include + #include + #include + gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a ); + #ifdef OPAQUE + gl_FragColor.a = 1.0; + #endif +}`,zh=`#define PHONG +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`,Gh=`#define PHONG +uniform vec3 diffuse; +uniform vec3 emissive; +uniform vec3 specular; +uniform float shininess; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,kh=`#define STANDARD +varying vec3 vViewPosition; +#ifdef USE_TRANSMISSION + varying vec3 vWorldPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +#ifdef USE_TRANSMISSION + vWorldPosition = worldPosition.xyz; +#endif +}`,Vh=`#define STANDARD +#ifdef PHYSICAL + #define IOR + #define USE_SPECULAR +#endif +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float roughness; +uniform float metalness; +uniform float opacity; +#ifdef IOR + uniform float ior; +#endif +#ifdef USE_SPECULAR + uniform float specularIntensity; + uniform vec3 specularColor; + #ifdef USE_SPECULAR_COLORMAP + uniform sampler2D specularColorMap; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + uniform sampler2D specularIntensityMap; + #endif +#endif +#ifdef USE_CLEARCOAT + uniform float clearcoat; + uniform float clearcoatRoughness; +#endif +#ifdef USE_DISPERSION + uniform float dispersion; +#endif +#ifdef USE_IRIDESCENCE + uniform float iridescence; + uniform float iridescenceIOR; + uniform float iridescenceThicknessMinimum; + uniform float iridescenceThicknessMaximum; +#endif +#ifdef USE_SHEEN + uniform vec3 sheenColor; + uniform float sheenRoughness; + #ifdef USE_SHEEN_COLORMAP + uniform sampler2D sheenColorMap; + #endif + #ifdef USE_SHEEN_ROUGHNESSMAP + uniform sampler2D sheenRoughnessMap; + #endif +#endif +#ifdef USE_ANISOTROPY + uniform vec2 anisotropyVector; + #ifdef USE_ANISOTROPYMAP + uniform sampler2D anisotropyMap; + #endif +#endif +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; + vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; + #include + vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; + #ifdef USE_SHEEN + float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor ); + outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect; + #endif + #ifdef USE_CLEARCOAT + float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); + vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); + outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; + #endif + #include + #include + #include + #include + #include + #include +}`,Wh=`#define TOON +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +}`,Xh=`#define TOON +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include +}`,qh=`uniform float size; +uniform float scale; +#include +#include +#include +#include +#include +#include +#ifdef USE_POINTS_UV + varying vec2 vUv; + uniform mat3 uvTransform; +#endif +void main() { + #ifdef USE_POINTS_UV + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + #endif + #include + #include + #include + #include + #include + #include + gl_PointSize = size; + #ifdef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); + #endif + #include + #include + #include + #include +}`,Yh=`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,$h=`#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,Kh=`uniform vec3 color; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); + #include + #include + #include +}`,Zh=`uniform float rotation; +uniform vec2 center; +#include +#include +#include +#include +#include +void main() { + #include + vec4 mvPosition = modelViewMatrix[ 3 ]; + vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); + #ifndef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) scale *= - mvPosition.z; + #endif + vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; + vec2 rotatedPosition; + rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; + rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; + mvPosition.xy += rotatedPosition; + gl_Position = projectionMatrix * mvPosition; + #include + #include + #include +}`,jh=`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include +}`,Ne={alphahash_fragment:xc,alphahash_pars_fragment:Mc,alphamap_fragment:Sc,alphamap_pars_fragment:Ec,alphatest_fragment:yc,alphatest_pars_fragment:Tc,aomap_fragment:Ac,aomap_pars_fragment:bc,batching_pars_vertex:wc,batching_vertex:Rc,begin_vertex:Cc,beginnormal_vertex:Pc,bsdfs:Dc,iridescence_fragment:Lc,bumpmap_pars_fragment:Ic,clipping_planes_fragment:Uc,clipping_planes_pars_fragment:Nc,clipping_planes_pars_vertex:Fc,clipping_planes_vertex:Oc,color_fragment:Bc,color_pars_fragment:Hc,color_pars_vertex:zc,color_vertex:Gc,common:kc,cube_uv_reflection_fragment:Vc,defaultnormal_vertex:Wc,displacementmap_pars_vertex:Xc,displacementmap_vertex:qc,emissivemap_fragment:Yc,emissivemap_pars_fragment:$c,colorspace_fragment:Kc,colorspace_pars_fragment:Zc,envmap_fragment:jc,envmap_common_pars_fragment:Jc,envmap_pars_fragment:Qc,envmap_pars_vertex:eu,envmap_physical_pars_fragment:hu,envmap_vertex:tu,fog_vertex:nu,fog_pars_vertex:iu,fog_fragment:ru,fog_pars_fragment:su,gradientmap_pars_fragment:au,lightmap_pars_fragment:ou,lights_lambert_fragment:lu,lights_lambert_pars_fragment:cu,lights_pars_begin:uu,lights_toon_fragment:du,lights_toon_pars_fragment:fu,lights_phong_fragment:pu,lights_phong_pars_fragment:mu,lights_physical_fragment:gu,lights_physical_pars_fragment:_u,lights_fragment_begin:vu,lights_fragment_maps:xu,lights_fragment_end:Mu,logdepthbuf_fragment:Su,logdepthbuf_pars_fragment:Eu,logdepthbuf_pars_vertex:yu,logdepthbuf_vertex:Tu,map_fragment:Au,map_pars_fragment:bu,map_particle_fragment:wu,map_particle_pars_fragment:Ru,metalnessmap_fragment:Cu,metalnessmap_pars_fragment:Pu,morphinstance_vertex:Du,morphcolor_vertex:Lu,morphnormal_vertex:Iu,morphtarget_pars_vertex:Uu,morphtarget_vertex:Nu,normal_fragment_begin:Fu,normal_fragment_maps:Ou,normal_pars_fragment:Bu,normal_pars_vertex:Hu,normal_vertex:zu,normalmap_pars_fragment:Gu,clearcoat_normal_fragment_begin:ku,clearcoat_normal_fragment_maps:Vu,clearcoat_pars_fragment:Wu,iridescence_pars_fragment:Xu,opaque_fragment:qu,packing:Yu,premultiplied_alpha_fragment:$u,project_vertex:Ku,dithering_fragment:Zu,dithering_pars_fragment:ju,roughnessmap_fragment:Ju,roughnessmap_pars_fragment:Qu,shadowmap_pars_fragment:eh,shadowmap_pars_vertex:th,shadowmap_vertex:nh,shadowmask_pars_fragment:ih,skinbase_vertex:rh,skinning_pars_vertex:sh,skinning_vertex:ah,skinnormal_vertex:oh,specularmap_fragment:lh,specularmap_pars_fragment:ch,tonemapping_fragment:uh,tonemapping_pars_fragment:hh,transmission_fragment:dh,transmission_pars_fragment:fh,uv_pars_fragment:ph,uv_pars_vertex:mh,uv_vertex:gh,worldpos_vertex:_h,background_vert:vh,background_frag:xh,backgroundCube_vert:Mh,backgroundCube_frag:Sh,cube_vert:Eh,cube_frag:yh,depth_vert:Th,depth_frag:Ah,distanceRGBA_vert:bh,distanceRGBA_frag:wh,equirect_vert:Rh,equirect_frag:Ch,linedashed_vert:Ph,linedashed_frag:Dh,meshbasic_vert:Lh,meshbasic_frag:Ih,meshlambert_vert:Uh,meshlambert_frag:Nh,meshmatcap_vert:Fh,meshmatcap_frag:Oh,meshnormal_vert:Bh,meshnormal_frag:Hh,meshphong_vert:zh,meshphong_frag:Gh,meshphysical_vert:kh,meshphysical_frag:Vh,meshtoon_vert:Wh,meshtoon_frag:Xh,points_vert:qh,points_frag:Yh,shadow_vert:$h,shadow_frag:Kh,sprite_vert:Zh,sprite_frag:jh},re={common:{diffuse:{value:new Oe(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Ie},alphaMap:{value:null},alphaMapTransform:{value:new Ie},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Ie}},envmap:{envMap:{value:null},envMapRotation:{value:new Ie},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Ie}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Ie}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Ie},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Ie},normalScale:{value:new Ge(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Ie},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Ie}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Ie}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Ie}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Oe(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new Oe(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Ie},alphaTest:{value:0},uvTransform:{value:new Ie}},sprite:{diffuse:{value:new Oe(16777215)},opacity:{value:1},center:{value:new Ge(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Ie},alphaMap:{value:null},alphaMapTransform:{value:new Ie},alphaTest:{value:0}}},Vt={basic:{uniforms:_t([re.common,re.specularmap,re.envmap,re.aomap,re.lightmap,re.fog]),vertexShader:Ne.meshbasic_vert,fragmentShader:Ne.meshbasic_frag},lambert:{uniforms:_t([re.common,re.specularmap,re.envmap,re.aomap,re.lightmap,re.emissivemap,re.bumpmap,re.normalmap,re.displacementmap,re.fog,re.lights,{emissive:{value:new Oe(0)}}]),vertexShader:Ne.meshlambert_vert,fragmentShader:Ne.meshlambert_frag},phong:{uniforms:_t([re.common,re.specularmap,re.envmap,re.aomap,re.lightmap,re.emissivemap,re.bumpmap,re.normalmap,re.displacementmap,re.fog,re.lights,{emissive:{value:new Oe(0)},specular:{value:new Oe(1118481)},shininess:{value:30}}]),vertexShader:Ne.meshphong_vert,fragmentShader:Ne.meshphong_frag},standard:{uniforms:_t([re.common,re.envmap,re.aomap,re.lightmap,re.emissivemap,re.bumpmap,re.normalmap,re.displacementmap,re.roughnessmap,re.metalnessmap,re.fog,re.lights,{emissive:{value:new Oe(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Ne.meshphysical_vert,fragmentShader:Ne.meshphysical_frag},toon:{uniforms:_t([re.common,re.aomap,re.lightmap,re.emissivemap,re.bumpmap,re.normalmap,re.displacementmap,re.gradientmap,re.fog,re.lights,{emissive:{value:new Oe(0)}}]),vertexShader:Ne.meshtoon_vert,fragmentShader:Ne.meshtoon_frag},matcap:{uniforms:_t([re.common,re.bumpmap,re.normalmap,re.displacementmap,re.fog,{matcap:{value:null}}]),vertexShader:Ne.meshmatcap_vert,fragmentShader:Ne.meshmatcap_frag},points:{uniforms:_t([re.points,re.fog]),vertexShader:Ne.points_vert,fragmentShader:Ne.points_frag},dashed:{uniforms:_t([re.common,re.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Ne.linedashed_vert,fragmentShader:Ne.linedashed_frag},depth:{uniforms:_t([re.common,re.displacementmap]),vertexShader:Ne.depth_vert,fragmentShader:Ne.depth_frag},normal:{uniforms:_t([re.common,re.bumpmap,re.normalmap,re.displacementmap,{opacity:{value:1}}]),vertexShader:Ne.meshnormal_vert,fragmentShader:Ne.meshnormal_frag},sprite:{uniforms:_t([re.sprite,re.fog]),vertexShader:Ne.sprite_vert,fragmentShader:Ne.sprite_frag},background:{uniforms:{uvTransform:{value:new Ie},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Ne.background_vert,fragmentShader:Ne.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Ie}},vertexShader:Ne.backgroundCube_vert,fragmentShader:Ne.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Ne.cube_vert,fragmentShader:Ne.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Ne.equirect_vert,fragmentShader:Ne.equirect_frag},distanceRGBA:{uniforms:_t([re.common,re.displacementmap,{referencePosition:{value:new F},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Ne.distanceRGBA_vert,fragmentShader:Ne.distanceRGBA_frag},shadow:{uniforms:_t([re.lights,re.fog,{color:{value:new Oe(0)},opacity:{value:1}}]),vertexShader:Ne.shadow_vert,fragmentShader:Ne.shadow_frag}};Vt.physical={uniforms:_t([Vt.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Ie},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Ie},clearcoatNormalScale:{value:new Ge(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Ie},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Ie},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Ie},sheen:{value:0},sheenColor:{value:new Oe(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Ie},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Ie},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Ie},transmissionSamplerSize:{value:new Ge},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Ie},attenuationDistance:{value:0},attenuationColor:{value:new Oe(0)},specularColor:{value:new Oe(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Ie},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Ie},anisotropyVector:{value:new Ge},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Ie}}]),vertexShader:Ne.meshphysical_vert,fragmentShader:Ne.meshphysical_frag};const Ki={r:0,b:0,g:0},yn=new Yt,Jh=new st;function Qh(i,e,t,n,r,s,a){const o=new Oe(0);let c=s===!0?0:1,l,h,d=null,f=0,m=null;function _(A){let E=A.isScene===!0?A.background:null;return E&&E.isTexture&&(E=(A.backgroundBlurriness>0?t:e).get(E)),E}function x(A){let E=!1;const D=_(A);D===null?u(o,c):D&&D.isColor&&(u(D,1),E=!0);const R=i.xr.getEnvironmentBlendMode();R==="additive"?n.buffers.color.setClear(0,0,0,1,a):R==="alpha-blend"&&n.buffers.color.setClear(0,0,0,0,a),(i.autoClear||E)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),i.clear(i.autoClearColor,i.autoClearDepth,i.autoClearStencil))}function p(A,E){const D=_(E);D&&(D.isCubeTexture||D.mapping===ar)?(h===void 0&&(h=new wt(new Ri(1,1,1),new gn({name:"BackgroundCubeMaterial",uniforms:ri(Vt.backgroundCube.uniforms),vertexShader:Vt.backgroundCube.vertexShader,fragmentShader:Vt.backgroundCube.fragmentShader,side:Et,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),h.geometry.deleteAttribute("normal"),h.geometry.deleteAttribute("uv"),h.onBeforeRender=function(R,w,U){this.matrixWorld.copyPosition(U.matrixWorld)},Object.defineProperty(h.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),r.update(h)),yn.copy(E.backgroundRotation),yn.x*=-1,yn.y*=-1,yn.z*=-1,D.isCubeTexture&&D.isRenderTargetTexture===!1&&(yn.y*=-1,yn.z*=-1),h.material.uniforms.envMap.value=D,h.material.uniforms.flipEnvMap.value=D.isCubeTexture&&D.isRenderTargetTexture===!1?-1:1,h.material.uniforms.backgroundBlurriness.value=E.backgroundBlurriness,h.material.uniforms.backgroundIntensity.value=E.backgroundIntensity,h.material.uniforms.backgroundRotation.value.setFromMatrix4(Jh.makeRotationFromEuler(yn)),h.material.toneMapped=Ve.getTransfer(D.colorSpace)!==Ye,(d!==D||f!==D.version||m!==i.toneMapping)&&(h.material.needsUpdate=!0,d=D,f=D.version,m=i.toneMapping),h.layers.enableAll(),A.unshift(h,h.geometry,h.material,0,0,null)):D&&D.isTexture&&(l===void 0&&(l=new wt(new ai(2,2),new gn({name:"BackgroundMaterial",uniforms:ri(Vt.background.uniforms),vertexShader:Vt.background.vertexShader,fragmentShader:Vt.background.fragmentShader,side:mn,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),r.update(l)),l.material.uniforms.t2D.value=D,l.material.uniforms.backgroundIntensity.value=E.backgroundIntensity,l.material.toneMapped=Ve.getTransfer(D.colorSpace)!==Ye,D.matrixAutoUpdate===!0&&D.updateMatrix(),l.material.uniforms.uvTransform.value.copy(D.matrix),(d!==D||f!==D.version||m!==i.toneMapping)&&(l.material.needsUpdate=!0,d=D,f=D.version,m=i.toneMapping),l.layers.enableAll(),A.unshift(l,l.geometry,l.material,0,0,null))}function u(A,E){A.getRGB(Ki,Eo(i)),n.buffers.color.setClear(Ki.r,Ki.g,Ki.b,E,a)}function b(){h!==void 0&&(h.geometry.dispose(),h.material.dispose(),h=void 0),l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0)}return{getClearColor:function(){return o},setClearColor:function(A,E=1){o.set(A),c=E,u(o,c)},getClearAlpha:function(){return c},setClearAlpha:function(A){c=A,u(o,c)},render:x,addToRenderList:p,dispose:b}}function ed(i,e){const t=i.getParameter(i.MAX_VERTEX_ATTRIBS),n={},r=f(null);let s=r,a=!1;function o(M,C,O,z,q){let W=!1;const X=d(z,O,C);s!==X&&(s=X,l(s.object)),W=m(M,z,O,q),W&&_(M,z,O,q),q!==null&&e.update(q,i.ELEMENT_ARRAY_BUFFER),(W||a)&&(a=!1,E(M,C,O,z),q!==null&&i.bindBuffer(i.ELEMENT_ARRAY_BUFFER,e.get(q).buffer))}function c(){return i.createVertexArray()}function l(M){return i.bindVertexArray(M)}function h(M){return i.deleteVertexArray(M)}function d(M,C,O){const z=O.wireframe===!0;let q=n[M.id];q===void 0&&(q={},n[M.id]=q);let W=q[C.id];W===void 0&&(W={},q[C.id]=W);let X=W[z];return X===void 0&&(X=f(c()),W[z]=X),X}function f(M){const C=[],O=[],z=[];for(let q=0;q=0){const ce=q[G];let Ee=W[G];if(Ee===void 0&&(G==="instanceMatrix"&&M.instanceMatrix&&(Ee=M.instanceMatrix),G==="instanceColor"&&M.instanceColor&&(Ee=M.instanceColor)),ce===void 0||ce.attribute!==Ee||Ee&&ce.data!==Ee.data)return!0;X++}return s.attributesNum!==X||s.index!==z}function _(M,C,O,z){const q={},W=C.attributes;let X=0;const Z=O.getAttributes();for(const G in Z)if(Z[G].location>=0){let ce=W[G];ce===void 0&&(G==="instanceMatrix"&&M.instanceMatrix&&(ce=M.instanceMatrix),G==="instanceColor"&&M.instanceColor&&(ce=M.instanceColor));const Ee={};Ee.attribute=ce,ce&&ce.data&&(Ee.data=ce.data),q[G]=Ee,X++}s.attributes=q,s.attributesNum=X,s.index=z}function x(){const M=s.newAttributes;for(let C=0,O=M.length;C=0){let se=q[Z];if(se===void 0&&(Z==="instanceMatrix"&&M.instanceMatrix&&(se=M.instanceMatrix),Z==="instanceColor"&&M.instanceColor&&(se=M.instanceColor)),se!==void 0){const ce=se.normalized,Ee=se.itemSize,Fe=e.get(se);if(Fe===void 0)continue;const Ke=Fe.buffer,Je=Fe.type,We=Fe.bytesPerElement,Y=Je===i.INT||Je===i.UNSIGNED_INT||se.gpuType===Is;if(se.isInterleavedBufferAttribute){const j=se.data,de=j.stride,Ce=se.offset;if(j.isInstancedInterleavedBuffer){for(let Se=0;Se0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.HIGH_FLOAT).precision>0)return"highp";w="mediump"}return w==="mediump"&&i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.MEDIUM_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let l=t.precision!==void 0?t.precision:"highp";const h=c(l);h!==l&&(console.warn("THREE.WebGLRenderer:",l,"not supported, using",h,"instead."),l=h);const d=t.logarithmicDepthBuffer===!0,f=t.reversedDepthBuffer===!0&&e.has("EXT_clip_control"),m=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),_=i.getParameter(i.MAX_VERTEX_TEXTURE_IMAGE_UNITS),x=i.getParameter(i.MAX_TEXTURE_SIZE),p=i.getParameter(i.MAX_CUBE_MAP_TEXTURE_SIZE),u=i.getParameter(i.MAX_VERTEX_ATTRIBS),b=i.getParameter(i.MAX_VERTEX_UNIFORM_VECTORS),A=i.getParameter(i.MAX_VARYING_VECTORS),E=i.getParameter(i.MAX_FRAGMENT_UNIFORM_VECTORS),D=_>0,R=i.getParameter(i.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:s,getMaxPrecision:c,textureFormatReadable:a,textureTypeReadable:o,precision:l,logarithmicDepthBuffer:d,reversedDepthBuffer:f,maxTextures:m,maxVertexTextures:_,maxTextureSize:x,maxCubemapSize:p,maxAttributes:u,maxVertexUniforms:b,maxVaryings:A,maxFragmentUniforms:E,vertexTextures:D,maxSamples:R}}function id(i){const e=this;let t=null,n=0,r=!1,s=!1;const a=new An,o=new Ie,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(d,f){const m=d.length!==0||f||n!==0||r;return r=f,n=d.length,m},this.beginShadows=function(){s=!0,h(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(d,f){t=h(d,f,0)},this.setState=function(d,f,m){const _=d.clippingPlanes,x=d.clipIntersection,p=d.clipShadows,u=i.get(d);if(!r||_===null||_.length===0||s&&!p)s?h(null):l();else{const b=s?0:n,A=b*4;let E=u.clippingState||null;c.value=E,E=h(_,f,A,m);for(let D=0;D!==A;++D)E[D]=t[D];u.clippingState=E,this.numIntersection=x?this.numPlanes:0,this.numPlanes+=b}};function l(){c.value!==t&&(c.value=t,c.needsUpdate=n>0),e.numPlanes=n,e.numIntersection=0}function h(d,f,m,_){const x=d!==null?d.length:0;let p=null;if(x!==0){if(p=c.value,_!==!0||p===null){const u=m+x*4,b=f.matrixWorldInverse;o.getNormalMatrix(b),(p===null||p.length0){const l=new Ql(c.height);return l.fromEquirectangularTexture(i,a),e.set(a,l),a.addEventListener("dispose",r),t(l.texture,a.mapping)}else return null}}return a}function r(a){const o=a.target;o.removeEventListener("dispose",r);const c=e.get(o);c!==void 0&&(e.delete(o),c.dispose())}function s(){e=new WeakMap}return{get:n,dispose:s}}const jn=4,Ca=[.125,.215,.35,.446,.526,.582],Rn=20,Or=new Ro,Pa=new Oe;let Br=null,Hr=0,zr=0,Gr=!1;const bn=(1+Math.sqrt(5))/2,Kn=1/bn,Da=[new F(-bn,Kn,0),new F(bn,Kn,0),new F(-Kn,0,bn),new F(Kn,0,bn),new F(0,bn,-Kn),new F(0,bn,Kn),new F(-1,1,-1),new F(1,1,-1),new F(-1,1,1),new F(1,1,1)],sd=new F;class La{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,n=.1,r=100,s={}){const{size:a=256,position:o=sd}=s;Br=this._renderer.getRenderTarget(),Hr=this._renderer.getActiveCubeFace(),zr=this._renderer.getActiveMipmapLevel(),Gr=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(a);const c=this._allocateTargets();return c.depthBuffer=!0,this._sceneToCubeUV(e,n,r,c,o),t>0&&this._blur(c,0,0,t),this._applyPMREM(c),this._cleanup(c),c}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Na(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Ua(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e2?D:0,D,D),d.setRenderTarget(r),u&&d.render(p,c),d.render(e,c)}p.geometry.dispose(),p.material.dispose(),d.toneMapping=m,d.autoClear=f,e.background=b}_textureToCubeUV(e,t){const n=this._renderer,r=e.mapping===ti||e.mapping===ni;r?(this._cubemapMaterial===null&&(this._cubemapMaterial=Na()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=Ua());const s=r?this._cubemapMaterial:this._equirectMaterial,a=new wt(this._lodPlanes[0],s),o=s.uniforms;o.envMap.value=e;const c=this._cubeSize;Zi(t,0,0,3*c,2*c),n.setRenderTarget(t),n.render(a,Or)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const r=this._lodPlanes.length;for(let s=1;sRn&&console.warn(`sigmaRadians, ${s}, is too large and will clip, as it requested ${p} samples when the maximum is set to ${Rn}`);const u=[];let b=0;for(let w=0;wA-jn?r-A+jn:0),R=4*(this._cubeSize-E);Zi(t,D,R,3*E,2*E),c.setRenderTarget(t),c.render(d,Or)}}function ad(i){const e=[],t=[],n=[];let r=i;const s=i-jn+1+Ca.length;for(let a=0;ai-jn?c=Ca[a-i+jn-1]:a===0&&(c=0),n.push(c);const l=1/(o-2),h=-l,d=1+l,f=[h,h,d,h,d,d,h,h,d,d,h,d],m=6,_=6,x=3,p=2,u=1,b=new Float32Array(x*_*m),A=new Float32Array(p*_*m),E=new Float32Array(u*_*m);for(let R=0;R2?0:-1,S=[w,U,0,w+2/3,U,0,w+2/3,U+1,0,w,U,0,w+2/3,U+1,0,w,U+1,0];b.set(S,x*_*R),A.set(f,p*_*R);const M=[R,R,R,R,R,R];E.set(M,u*_*R)}const D=new sn;D.setAttribute("position",new Xt(b,x)),D.setAttribute("uv",new Xt(A,p)),D.setAttribute("faceIndex",new Xt(E,u)),e.push(D),r>jn&&r--}return{lodPlanes:e,sizeLods:t,sigmas:n}}function Ia(i,e,t){const n=new In(i,e,t);return n.texture.mapping=ar,n.texture.name="PMREM.cubeUv",n.scissorTest=!0,n}function Zi(i,e,t,n,r){i.viewport.set(e,t,n,r),i.scissor.set(e,t,n,r)}function od(i,e,t){const n=new Float32Array(Rn),r=new F(0,1,0);return new gn({name:"SphericalGaussianBlur",defines:{n:Rn,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${i}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:n},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:r}},vertexShader:Ys(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; + + #define ENVMAP_TYPE_CUBE_UV + #include + + vec3 getSample( float theta, vec3 axis ) { + + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + + return bilinearCubeUV( envMap, sampleDirection, mipInt ); + + } + + void main() { + + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + + } + + axis = normalize( axis ); + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + + for ( int i = 1; i < n; i++ ) { + + if ( i >= samples ) { + + break; + + } + + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + + } + + } + `,blending:fn,depthTest:!1,depthWrite:!1})}function Ua(){return new gn({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Ys(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + + } + `,blending:fn,depthTest:!1,depthWrite:!1})}function Na(){return new gn({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Ys(),fragmentShader:` + + precision mediump float; + precision mediump int; + + uniform float flipEnvMap; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + void main() { + + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + + } + `,blending:fn,depthTest:!1,depthWrite:!1})}function Ys(){return` + + precision mediump float; + precision mediump int; + + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + `}function ld(i){let e=new WeakMap,t=null;function n(o){if(o&&o.isTexture){const c=o.mapping,l=c===Jr||c===Qr,h=c===ti||c===ni;if(l||h){let d=e.get(o);const f=d!==void 0?d.texture.pmremVersion:0;if(o.isRenderTargetTexture&&o.pmremVersion!==f)return t===null&&(t=new La(i)),d=l?t.fromEquirectangular(o,d):t.fromCubemap(o,d),d.texture.pmremVersion=o.pmremVersion,e.set(o,d),d.texture;if(d!==void 0)return d.texture;{const m=o.image;return l&&m&&m.height>0||h&&m&&r(m)?(t===null&&(t=new La(i)),d=l?t.fromEquirectangular(o):t.fromCubemap(o),d.texture.pmremVersion=o.pmremVersion,e.set(o,d),o.addEventListener("dispose",s),d.texture):null}}}return o}function r(o){let c=0;const l=6;for(let h=0;he.maxTextureSize&&(R=Math.ceil(D/e.maxTextureSize),D=e.maxTextureSize);const w=new Float32Array(D*R*4*d),U=new go(w,D,R,d);U.type=nn,U.needsUpdate=!0;const S=E*4;for(let C=0;C0)return i;const r=e*t;let s=Oa[r];if(s===void 0&&(s=new Float32Array(r),Oa[r]=s),e!==0){n.toArray(s,0);for(let a=1,o=0;a!==e;++a)o+=t,i[a].toArray(s,o)}return s}function lt(i,e){if(i.length!==e.length)return!1;for(let t=0,n=i.length;t":" "} ${o}: ${t[a]}`)}return n.join(` +`)}const Wa=new Ie;function cf(i){Ve._getMatrix(Wa,Ve.workingColorSpace,i);const e=`mat3( ${Wa.elements.map(t=>t.toFixed(4))} )`;switch(Ve.getTransfer(i)){case rr:return[e,"LinearTransferOETF"];case Ye:return[e,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",i),[e,"LinearTransferOETF"]}}function Xa(i,e,t){const n=i.getShaderParameter(e,i.COMPILE_STATUS),s=(i.getShaderInfoLog(e)||"").trim();if(n&&s==="")return"";const a=/ERROR: 0:(\d+)/.exec(s);if(a){const o=parseInt(a[1]);return t.toUpperCase()+` + +`+s+` + +`+lf(i.getShaderSource(e),o)}else return s}function uf(i,e){const t=cf(e);return[`vec4 ${i}( vec4 value ) {`,` return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,"}"].join(` +`)}function hf(i,e){let t;switch(e){case ul:t="Linear";break;case hl:t="Reinhard";break;case dl:t="Cineon";break;case fl:t="ACESFilmic";break;case ml:t="AgX";break;case gl:t="Neutral";break;case pl:t="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),t="Linear"}return"vec3 "+i+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}const ji=new F;function df(){Ve.getLuminanceCoefficients(ji);const i=ji.x.toFixed(4),e=ji.y.toFixed(4),t=ji.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${i}, ${e}, ${t} );`," return dot( weights, rgb );","}"].join(` +`)}function ff(i){return[i.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",i.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(pi).join(` +`)}function pf(i){const e=[];for(const t in i){const n=i[t];n!==!1&&e.push("#define "+t+" "+n)}return e.join(` +`)}function mf(i,e){const t={},n=i.getProgramParameter(e,i.ACTIVE_ATTRIBUTES);for(let r=0;r/gm;function Ds(i){return i.replace(gf,vf)}const _f=new Map;function vf(i,e){let t=Ne[e];if(t===void 0){const n=_f.get(e);if(n!==void 0)t=Ne[n],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,n);else throw new Error("Can not resolve #include <"+e+">")}return Ds(t)}const xf=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function $a(i){return i.replace(xf,Mf)}function Mf(i,e,t,n){let r="";for(let s=parseInt(e);s0&&(p+=` +`),u=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,_].filter(pi).join(` +`),u.length>0&&(u+=` +`)):(p=[Ka(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,_,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+h:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+c:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` +`].filter(pi).join(` +`),u=[Ka(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,_,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+l:"",t.envMap?"#define "+h:"",t.envMap?"#define "+d:"",f?"#define CUBEUV_TEXEL_WIDTH "+f.texelWidth:"",f?"#define CUBEUV_TEXEL_HEIGHT "+f.texelHeight:"",f?"#define CUBEUV_MAX_MIP "+f.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor||t.batchingColor?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+c:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==pn?"#define TONE_MAPPING":"",t.toneMapping!==pn?Ne.tonemapping_pars_fragment:"",t.toneMapping!==pn?hf("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",Ne.colorspace_pars_fragment,uf("linearToOutputTexel",t.outputColorSpace),df(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",` +`].filter(pi).join(` +`)),a=Ds(a),a=qa(a,t),a=Ya(a,t),o=Ds(o),o=qa(o,t),o=Ya(o,t),a=$a(a),o=$a(o),t.isRawShaderMaterial!==!0&&(b=`#version 300 es +`,p=[m,"#define attribute in","#define varying out","#define texture2D texture"].join(` +`)+` +`+p,u=["#define varying in",t.glslVersion===aa?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===aa?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` +`)+` +`+u);const A=b+p+a,E=b+u+o,D=Va(r,r.VERTEX_SHADER,A),R=Va(r,r.FRAGMENT_SHADER,E);r.attachShader(x,D),r.attachShader(x,R),t.index0AttributeName!==void 0?r.bindAttribLocation(x,0,t.index0AttributeName):t.morphTargets===!0&&r.bindAttribLocation(x,0,"position"),r.linkProgram(x);function w(C){if(i.debug.checkShaderErrors){const O=r.getProgramInfoLog(x)||"",z=r.getShaderInfoLog(D)||"",q=r.getShaderInfoLog(R)||"",W=O.trim(),X=z.trim(),Z=q.trim();let G=!0,se=!0;if(r.getProgramParameter(x,r.LINK_STATUS)===!1)if(G=!1,typeof i.debug.onShaderError=="function")i.debug.onShaderError(r,x,D,R);else{const ce=Xa(r,D,"vertex"),Ee=Xa(r,R,"fragment");console.error("THREE.WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(x,r.VALIDATE_STATUS)+` + +Material Name: `+C.name+` +Material Type: `+C.type+` + +Program Info Log: `+W+` +`+ce+` +`+Ee)}else W!==""?console.warn("THREE.WebGLProgram: Program Info Log:",W):(X===""||Z==="")&&(se=!1);se&&(C.diagnostics={runnable:G,programLog:W,vertexShader:{log:X,prefix:p},fragmentShader:{log:Z,prefix:u}})}r.deleteShader(D),r.deleteShader(R),U=new ir(r,x),S=mf(r,x)}let U;this.getUniforms=function(){return U===void 0&&w(this),U};let S;this.getAttributes=function(){return S===void 0&&w(this),S};let M=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return M===!1&&(M=r.getProgramParameter(x,af)),M},this.destroy=function(){n.releaseStatesOfProgram(this),r.deleteProgram(x),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=of++,this.cacheKey=e,this.usedTimes=1,this.program=x,this.vertexShader=D,this.fragmentShader=R,this}let wf=0;class Rf{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,n=e.fragmentShader,r=this._getShaderStage(t),s=this._getShaderStage(n),a=this._getShaderCacheForMaterial(e);return a.has(r)===!1&&(a.add(r),r.usedTimes++),a.has(s)===!1&&(a.add(s),s.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const n of t)n.usedTimes--,n.usedTimes===0&&this.shaderCache.delete(n.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){const t=this.shaderCache;let n=t.get(e);return n===void 0&&(n=new Cf(e),t.set(e,n)),n}}class Cf{constructor(e){this.id=wf++,this.code=e,this.usedTimes=0}}function Pf(i,e,t,n,r,s,a){const o=new Gs,c=new Rf,l=new Set,h=[],d=r.logarithmicDepthBuffer,f=r.vertexTextures;let m=r.precision;const _={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function x(S){return l.add(S),S===0?"uv":`uv${S}`}function p(S,M,C,O,z){const q=O.fog,W=z.geometry,X=S.isMeshStandardMaterial?O.environment:null,Z=(S.isMeshStandardMaterial?t:e).get(S.envMap||X),G=Z&&Z.mapping===ar?Z.image.height:null,se=_[S.type];S.precision!==null&&(m=r.getMaxPrecision(S.precision),m!==S.precision&&console.warn("THREE.WebGLProgram.getParameters:",S.precision,"not supported, using",m,"instead."));const ce=W.morphAttributes.position||W.morphAttributes.normal||W.morphAttributes.color,Ee=ce!==void 0?ce.length:0;let Fe=0;W.morphAttributes.position!==void 0&&(Fe=1),W.morphAttributes.normal!==void 0&&(Fe=2),W.morphAttributes.color!==void 0&&(Fe=3);let Ke,Je,We,Y;if(se){const Xe=Vt[se];Ke=Xe.vertexShader,Je=Xe.fragmentShader}else Ke=S.vertexShader,Je=S.fragmentShader,c.update(S),We=c.getVertexShaderID(S),Y=c.getFragmentShaderID(S);const j=i.getRenderTarget(),de=i.state.buffers.depth.getReversed(),Ce=z.isInstancedMesh===!0,Se=z.isBatchedMesh===!0,ze=!!S.map,ft=!!S.matcap,T=!!Z,Qe=!!S.aoMap,De=!!S.lightMap,we=!!S.bumpMap,me=!!S.normalMap,et=!!S.displacementMap,ge=!!S.emissiveMap,Ue=!!S.metalnessMap,ut=!!S.roughnessMap,at=S.anisotropy>0,y=S.clearcoat>0,g=S.dispersion>0,N=S.iridescence>0,V=S.sheen>0,K=S.transmission>0,k=at&&!!S.anisotropyMap,Me=y&&!!S.clearcoatMap,ne=y&&!!S.clearcoatNormalMap,_e=y&&!!S.clearcoatRoughnessMap,ve=N&&!!S.iridescenceMap,ee=N&&!!S.iridescenceThicknessMap,le=V&&!!S.sheenColorMap,be=V&&!!S.sheenRoughnessMap,xe=!!S.specularMap,ae=!!S.specularColorMap,Le=!!S.specularIntensityMap,P=K&&!!S.transmissionMap,te=K&&!!S.thicknessMap,ie=!!S.gradientMap,he=!!S.alphaMap,J=S.alphaTest>0,$=!!S.alphaHash,pe=!!S.extensions;let Pe=pn;S.toneMapped&&(j===null||j.isXRRenderTarget===!0)&&(Pe=i.toneMapping);const Ze={shaderID:se,shaderType:S.type,shaderName:S.name,vertexShader:Ke,fragmentShader:Je,defines:S.defines,customVertexShaderID:We,customFragmentShaderID:Y,isRawShaderMaterial:S.isRawShaderMaterial===!0,glslVersion:S.glslVersion,precision:m,batching:Se,batchingColor:Se&&z._colorsTexture!==null,instancing:Ce,instancingColor:Ce&&z.instanceColor!==null,instancingMorph:Ce&&z.morphTexture!==null,supportsVertexTextures:f,outputColorSpace:j===null?i.outputColorSpace:j.isXRRenderTarget===!0?j.texture.colorSpace:ii,alphaToCoverage:!!S.alphaToCoverage,map:ze,matcap:ft,envMap:T,envMapMode:T&&Z.mapping,envMapCubeUVHeight:G,aoMap:Qe,lightMap:De,bumpMap:we,normalMap:me,displacementMap:f&&et,emissiveMap:ge,normalMapObjectSpace:me&&S.normalMapType===Ml,normalMapTangentSpace:me&&S.normalMapType===fo,metalnessMap:Ue,roughnessMap:ut,anisotropy:at,anisotropyMap:k,clearcoat:y,clearcoatMap:Me,clearcoatNormalMap:ne,clearcoatRoughnessMap:_e,dispersion:g,iridescence:N,iridescenceMap:ve,iridescenceThicknessMap:ee,sheen:V,sheenColorMap:le,sheenRoughnessMap:be,specularMap:xe,specularColorMap:ae,specularIntensityMap:Le,transmission:K,transmissionMap:P,thicknessMap:te,gradientMap:ie,opaque:S.transparent===!1&&S.blending===Jn&&S.alphaToCoverage===!1,alphaMap:he,alphaTest:J,alphaHash:$,combine:S.combine,mapUv:ze&&x(S.map.channel),aoMapUv:Qe&&x(S.aoMap.channel),lightMapUv:De&&x(S.lightMap.channel),bumpMapUv:we&&x(S.bumpMap.channel),normalMapUv:me&&x(S.normalMap.channel),displacementMapUv:et&&x(S.displacementMap.channel),emissiveMapUv:ge&&x(S.emissiveMap.channel),metalnessMapUv:Ue&&x(S.metalnessMap.channel),roughnessMapUv:ut&&x(S.roughnessMap.channel),anisotropyMapUv:k&&x(S.anisotropyMap.channel),clearcoatMapUv:Me&&x(S.clearcoatMap.channel),clearcoatNormalMapUv:ne&&x(S.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:_e&&x(S.clearcoatRoughnessMap.channel),iridescenceMapUv:ve&&x(S.iridescenceMap.channel),iridescenceThicknessMapUv:ee&&x(S.iridescenceThicknessMap.channel),sheenColorMapUv:le&&x(S.sheenColorMap.channel),sheenRoughnessMapUv:be&&x(S.sheenRoughnessMap.channel),specularMapUv:xe&&x(S.specularMap.channel),specularColorMapUv:ae&&x(S.specularColorMap.channel),specularIntensityMapUv:Le&&x(S.specularIntensityMap.channel),transmissionMapUv:P&&x(S.transmissionMap.channel),thicknessMapUv:te&&x(S.thicknessMap.channel),alphaMapUv:he&&x(S.alphaMap.channel),vertexTangents:!!W.attributes.tangent&&(me||at),vertexColors:S.vertexColors,vertexAlphas:S.vertexColors===!0&&!!W.attributes.color&&W.attributes.color.itemSize===4,pointsUvs:z.isPoints===!0&&!!W.attributes.uv&&(ze||he),fog:!!q,useFog:S.fog===!0,fogExp2:!!q&&q.isFogExp2,flatShading:S.flatShading===!0&&S.wireframe===!1,sizeAttenuation:S.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:de,skinning:z.isSkinnedMesh===!0,morphTargets:W.morphAttributes.position!==void 0,morphNormals:W.morphAttributes.normal!==void 0,morphColors:W.morphAttributes.color!==void 0,morphTargetsCount:Ee,morphTextureStride:Fe,numDirLights:M.directional.length,numPointLights:M.point.length,numSpotLights:M.spot.length,numSpotLightMaps:M.spotLightMap.length,numRectAreaLights:M.rectArea.length,numHemiLights:M.hemi.length,numDirLightShadows:M.directionalShadowMap.length,numPointLightShadows:M.pointShadowMap.length,numSpotLightShadows:M.spotShadowMap.length,numSpotLightShadowsWithMaps:M.numSpotLightShadowsWithMaps,numLightProbes:M.numLightProbes,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:S.dithering,shadowMapEnabled:i.shadowMap.enabled&&C.length>0,shadowMapType:i.shadowMap.type,toneMapping:Pe,decodeVideoTexture:ze&&S.map.isVideoTexture===!0&&Ve.getTransfer(S.map.colorSpace)===Ye,decodeVideoTextureEmissive:ge&&S.emissiveMap.isVideoTexture===!0&&Ve.getTransfer(S.emissiveMap.colorSpace)===Ye,premultipliedAlpha:S.premultipliedAlpha,doubleSided:S.side===Bt,flipSided:S.side===Et,useDepthPacking:S.depthPacking>=0,depthPacking:S.depthPacking||0,index0AttributeName:S.index0AttributeName,extensionClipCullDistance:pe&&S.extensions.clipCullDistance===!0&&n.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(pe&&S.extensions.multiDraw===!0||Se)&&n.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:S.customProgramCacheKey()};return Ze.vertexUv1s=l.has(1),Ze.vertexUv2s=l.has(2),Ze.vertexUv3s=l.has(3),l.clear(),Ze}function u(S){const M=[];if(S.shaderID?M.push(S.shaderID):(M.push(S.customVertexShaderID),M.push(S.customFragmentShaderID)),S.defines!==void 0)for(const C in S.defines)M.push(C),M.push(S.defines[C]);return S.isRawShaderMaterial===!1&&(b(M,S),A(M,S),M.push(i.outputColorSpace)),M.push(S.customProgramCacheKey),M.join()}function b(S,M){S.push(M.precision),S.push(M.outputColorSpace),S.push(M.envMapMode),S.push(M.envMapCubeUVHeight),S.push(M.mapUv),S.push(M.alphaMapUv),S.push(M.lightMapUv),S.push(M.aoMapUv),S.push(M.bumpMapUv),S.push(M.normalMapUv),S.push(M.displacementMapUv),S.push(M.emissiveMapUv),S.push(M.metalnessMapUv),S.push(M.roughnessMapUv),S.push(M.anisotropyMapUv),S.push(M.clearcoatMapUv),S.push(M.clearcoatNormalMapUv),S.push(M.clearcoatRoughnessMapUv),S.push(M.iridescenceMapUv),S.push(M.iridescenceThicknessMapUv),S.push(M.sheenColorMapUv),S.push(M.sheenRoughnessMapUv),S.push(M.specularMapUv),S.push(M.specularColorMapUv),S.push(M.specularIntensityMapUv),S.push(M.transmissionMapUv),S.push(M.thicknessMapUv),S.push(M.combine),S.push(M.fogExp2),S.push(M.sizeAttenuation),S.push(M.morphTargetsCount),S.push(M.morphAttributeCount),S.push(M.numDirLights),S.push(M.numPointLights),S.push(M.numSpotLights),S.push(M.numSpotLightMaps),S.push(M.numHemiLights),S.push(M.numRectAreaLights),S.push(M.numDirLightShadows),S.push(M.numPointLightShadows),S.push(M.numSpotLightShadows),S.push(M.numSpotLightShadowsWithMaps),S.push(M.numLightProbes),S.push(M.shadowMapType),S.push(M.toneMapping),S.push(M.numClippingPlanes),S.push(M.numClipIntersection),S.push(M.depthPacking)}function A(S,M){o.disableAll(),M.supportsVertexTextures&&o.enable(0),M.instancing&&o.enable(1),M.instancingColor&&o.enable(2),M.instancingMorph&&o.enable(3),M.matcap&&o.enable(4),M.envMap&&o.enable(5),M.normalMapObjectSpace&&o.enable(6),M.normalMapTangentSpace&&o.enable(7),M.clearcoat&&o.enable(8),M.iridescence&&o.enable(9),M.alphaTest&&o.enable(10),M.vertexColors&&o.enable(11),M.vertexAlphas&&o.enable(12),M.vertexUv1s&&o.enable(13),M.vertexUv2s&&o.enable(14),M.vertexUv3s&&o.enable(15),M.vertexTangents&&o.enable(16),M.anisotropy&&o.enable(17),M.alphaHash&&o.enable(18),M.batching&&o.enable(19),M.dispersion&&o.enable(20),M.batchingColor&&o.enable(21),M.gradientMap&&o.enable(22),S.push(o.mask),o.disableAll(),M.fog&&o.enable(0),M.useFog&&o.enable(1),M.flatShading&&o.enable(2),M.logarithmicDepthBuffer&&o.enable(3),M.reversedDepthBuffer&&o.enable(4),M.skinning&&o.enable(5),M.morphTargets&&o.enable(6),M.morphNormals&&o.enable(7),M.morphColors&&o.enable(8),M.premultipliedAlpha&&o.enable(9),M.shadowMapEnabled&&o.enable(10),M.doubleSided&&o.enable(11),M.flipSided&&o.enable(12),M.useDepthPacking&&o.enable(13),M.dithering&&o.enable(14),M.transmission&&o.enable(15),M.sheen&&o.enable(16),M.opaque&&o.enable(17),M.pointsUvs&&o.enable(18),M.decodeVideoTexture&&o.enable(19),M.decodeVideoTextureEmissive&&o.enable(20),M.alphaToCoverage&&o.enable(21),S.push(o.mask)}function E(S){const M=_[S.type];let C;if(M){const O=Vt[M];C=Kl.clone(O.uniforms)}else C=S.uniforms;return C}function D(S,M){let C;for(let O=0,z=h.length;O0?n.push(u):m.transparent===!0?r.push(u):t.push(u)}function c(d,f,m,_,x,p){const u=a(d,f,m,_,x,p);m.transmission>0?n.unshift(u):m.transparent===!0?r.unshift(u):t.unshift(u)}function l(d,f){t.length>1&&t.sort(d||Lf),n.length>1&&n.sort(f||Za),r.length>1&&r.sort(f||Za)}function h(){for(let d=e,f=i.length;d=s.length?(a=new ja,s.push(a)):a=s[r],a}function t(){i=new WeakMap}return{get:e,dispose:t}}function Uf(){const i={};return{get:function(e){if(i[e.id]!==void 0)return i[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new F,color:new Oe};break;case"SpotLight":t={position:new F,direction:new F,color:new Oe,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new F,color:new Oe,distance:0,decay:0};break;case"HemisphereLight":t={direction:new F,skyColor:new Oe,groundColor:new Oe};break;case"RectAreaLight":t={color:new Oe,position:new F,halfWidth:new F,halfHeight:new F};break}return i[e.id]=t,t}}}function Nf(){const i={};return{get:function(e){if(i[e.id]!==void 0)return i[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Ge};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Ge};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Ge,shadowCameraNear:1,shadowCameraFar:1e3};break}return i[e.id]=t,t}}}let Ff=0;function Of(i,e){return(e.castShadow?2:0)-(i.castShadow?2:0)+(e.map?1:0)-(i.map?1:0)}function Bf(i){const e=new Uf,t=Nf(),n={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let l=0;l<9;l++)n.probe.push(new F);const r=new F,s=new st,a=new st;function o(l){let h=0,d=0,f=0;for(let S=0;S<9;S++)n.probe[S].set(0,0,0);let m=0,_=0,x=0,p=0,u=0,b=0,A=0,E=0,D=0,R=0,w=0;l.sort(Of);for(let S=0,M=l.length;S0&&(i.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=re.LTC_FLOAT_1,n.rectAreaLTC2=re.LTC_FLOAT_2):(n.rectAreaLTC1=re.LTC_HALF_1,n.rectAreaLTC2=re.LTC_HALF_2)),n.ambient[0]=h,n.ambient[1]=d,n.ambient[2]=f;const U=n.hash;(U.directionalLength!==m||U.pointLength!==_||U.spotLength!==x||U.rectAreaLength!==p||U.hemiLength!==u||U.numDirectionalShadows!==b||U.numPointShadows!==A||U.numSpotShadows!==E||U.numSpotMaps!==D||U.numLightProbes!==w)&&(n.directional.length=m,n.spot.length=x,n.rectArea.length=p,n.point.length=_,n.hemi.length=u,n.directionalShadow.length=b,n.directionalShadowMap.length=b,n.pointShadow.length=A,n.pointShadowMap.length=A,n.spotShadow.length=E,n.spotShadowMap.length=E,n.directionalShadowMatrix.length=b,n.pointShadowMatrix.length=A,n.spotLightMatrix.length=E+D-R,n.spotLightMap.length=D,n.numSpotLightShadowsWithMaps=R,n.numLightProbes=w,U.directionalLength=m,U.pointLength=_,U.spotLength=x,U.rectAreaLength=p,U.hemiLength=u,U.numDirectionalShadows=b,U.numPointShadows=A,U.numSpotShadows=E,U.numSpotMaps=D,U.numLightProbes=w,n.version=Ff++)}function c(l,h){let d=0,f=0,m=0,_=0,x=0;const p=h.matrixWorldInverse;for(let u=0,b=l.length;u=a.length?(o=new Ja(i),a.push(o)):o=a[s],o}function n(){e=new WeakMap}return{get:t,dispose:n}}const zf=`void main() { + gl_Position = vec4( position, 1.0 ); +}`,Gf=`uniform sampler2D shadow_pass; +uniform vec2 resolution; +uniform float radius; +#include +void main() { + const float samples = float( VSM_SAMPLES ); + float mean = 0.0; + float squared_mean = 0.0; + float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); + float uvStart = samples <= 1.0 ? 0.0 : - 1.0; + for ( float i = 0.0; i < samples; i ++ ) { + float uvOffset = uvStart + i * uvStride; + #ifdef HORIZONTAL_PASS + vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) ); + mean += distribution.x; + squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; + #else + float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) ); + mean += depth; + squared_mean += depth * depth; + #endif + } + mean = mean / samples; + squared_mean = squared_mean / samples; + float std_dev = sqrt( squared_mean - mean * mean ); + gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); +}`;function kf(i,e,t){let n=new ks;const r=new Ge,s=new Ge,a=new rt,o=new sc({depthPacking:xl}),c=new ac,l={},h=t.maxTextureSize,d={[mn]:Et,[Et]:mn,[Bt]:Bt},f=new gn({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Ge},radius:{value:4}},vertexShader:zf,fragmentShader:Gf}),m=f.clone();m.defines.HORIZONTAL_PASS=1;const _=new sn;_.setAttribute("position",new Xt(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const x=new wt(_,f),p=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=to;let u=this.type;this.render=function(R,w,U){if(p.enabled===!1||p.autoUpdate===!1&&p.needsUpdate===!1||R.length===0)return;const S=i.getRenderTarget(),M=i.getActiveCubeFace(),C=i.getActiveMipmapLevel(),O=i.state;O.setBlending(fn),O.buffers.depth.getReversed()===!0?O.buffers.color.setClear(0,0,0,0):O.buffers.color.setClear(1,1,1,1),O.buffers.depth.setTest(!0),O.setScissorTest(!1);const z=u!==en&&this.type===en,q=u===en&&this.type!==en;for(let W=0,X=R.length;Wh||r.y>h)&&(r.x>h&&(s.x=Math.floor(h/se.x),r.x=s.x*se.x,G.mapSize.x=s.x),r.y>h&&(s.y=Math.floor(h/se.y),r.y=s.y*se.y,G.mapSize.y=s.y)),G.map===null||z===!0||q===!0){const Ee=this.type!==en?{minFilter:Gt,magFilter:Gt}:{};G.map!==null&&G.map.dispose(),G.map=new In(r.x,r.y,Ee),G.map.texture.name=Z.name+".shadowMap",G.camera.updateProjectionMatrix()}i.setRenderTarget(G.map),i.clear();const ce=G.getViewportCount();for(let Ee=0;Ee0||w.map&&w.alphaTest>0||w.alphaToCoverage===!0){const O=M.uuid,z=w.uuid;let q=l[O];q===void 0&&(q={},l[O]=q);let W=q[z];W===void 0&&(W=M.clone(),q[z]=W,w.addEventListener("dispose",D)),M=W}if(M.visible=w.visible,M.wireframe=w.wireframe,S===en?M.side=w.shadowSide!==null?w.shadowSide:w.side:M.side=w.shadowSide!==null?w.shadowSide:d[w.side],M.alphaMap=w.alphaMap,M.alphaTest=w.alphaToCoverage===!0?.5:w.alphaTest,M.map=w.map,M.clipShadows=w.clipShadows,M.clippingPlanes=w.clippingPlanes,M.clipIntersection=w.clipIntersection,M.displacementMap=w.displacementMap,M.displacementScale=w.displacementScale,M.displacementBias=w.displacementBias,M.wireframeLinewidth=w.wireframeLinewidth,M.linewidth=w.linewidth,U.isPointLight===!0&&M.isMeshDistanceMaterial===!0){const O=i.properties.get(M);O.light=U}return M}function E(R,w,U,S,M){if(R.visible===!1)return;if(R.layers.test(w.layers)&&(R.isMesh||R.isLine||R.isPoints)&&(R.castShadow||R.receiveShadow&&M===en)&&(!R.frustumCulled||n.intersectsObject(R))){R.modelViewMatrix.multiplyMatrices(U.matrixWorldInverse,R.matrixWorld);const z=e.update(R),q=R.material;if(Array.isArray(q)){const W=z.groups;for(let X=0,Z=W.length;X=1):G.indexOf("OpenGL ES")!==-1&&(Z=parseFloat(/^OpenGL ES (\d)/.exec(G)[1]),X=Z>=2);let se=null,ce={};const Ee=i.getParameter(i.SCISSOR_BOX),Fe=i.getParameter(i.VIEWPORT),Ke=new rt().fromArray(Ee),Je=new rt().fromArray(Fe);function We(P,te,ie,he){const J=new Uint8Array(4),$=i.createTexture();i.bindTexture(P,$),i.texParameteri(P,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(P,i.TEXTURE_MAG_FILTER,i.NEAREST);for(let pe=0;pe"u"?!1:/OculusBrowser/g.test(navigator.userAgent),l=new Ge,h=new WeakMap;let d;const f=new WeakMap;let m=!1;try{m=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function _(y,g){return m?new OffscreenCanvas(y,g):Si("canvas")}function x(y,g,N){let V=1;const K=at(y);if((K.width>N||K.height>N)&&(V=N/Math.max(K.width,K.height)),V<1)if(typeof HTMLImageElement<"u"&&y instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&y instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&y instanceof ImageBitmap||typeof VideoFrame<"u"&&y instanceof VideoFrame){const k=Math.floor(V*K.width),Me=Math.floor(V*K.height);d===void 0&&(d=_(k,Me));const ne=g?_(k,Me):d;return ne.width=k,ne.height=Me,ne.getContext("2d").drawImage(y,0,0,k,Me),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+K.width+"x"+K.height+") to ("+k+"x"+Me+")."),ne}else return"data"in y&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+K.width+"x"+K.height+")."),y;return y}function p(y){return y.generateMipmaps}function u(y){i.generateMipmap(y)}function b(y){return y.isWebGLCubeRenderTarget?i.TEXTURE_CUBE_MAP:y.isWebGL3DRenderTarget?i.TEXTURE_3D:y.isWebGLArrayRenderTarget||y.isCompressedArrayTexture?i.TEXTURE_2D_ARRAY:i.TEXTURE_2D}function A(y,g,N,V,K=!1){if(y!==null){if(i[y]!==void 0)return i[y];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+y+"'")}let k=g;if(g===i.RED&&(N===i.FLOAT&&(k=i.R32F),N===i.HALF_FLOAT&&(k=i.R16F),N===i.UNSIGNED_BYTE&&(k=i.R8)),g===i.RED_INTEGER&&(N===i.UNSIGNED_BYTE&&(k=i.R8UI),N===i.UNSIGNED_SHORT&&(k=i.R16UI),N===i.UNSIGNED_INT&&(k=i.R32UI),N===i.BYTE&&(k=i.R8I),N===i.SHORT&&(k=i.R16I),N===i.INT&&(k=i.R32I)),g===i.RG&&(N===i.FLOAT&&(k=i.RG32F),N===i.HALF_FLOAT&&(k=i.RG16F),N===i.UNSIGNED_BYTE&&(k=i.RG8)),g===i.RG_INTEGER&&(N===i.UNSIGNED_BYTE&&(k=i.RG8UI),N===i.UNSIGNED_SHORT&&(k=i.RG16UI),N===i.UNSIGNED_INT&&(k=i.RG32UI),N===i.BYTE&&(k=i.RG8I),N===i.SHORT&&(k=i.RG16I),N===i.INT&&(k=i.RG32I)),g===i.RGB_INTEGER&&(N===i.UNSIGNED_BYTE&&(k=i.RGB8UI),N===i.UNSIGNED_SHORT&&(k=i.RGB16UI),N===i.UNSIGNED_INT&&(k=i.RGB32UI),N===i.BYTE&&(k=i.RGB8I),N===i.SHORT&&(k=i.RGB16I),N===i.INT&&(k=i.RGB32I)),g===i.RGBA_INTEGER&&(N===i.UNSIGNED_BYTE&&(k=i.RGBA8UI),N===i.UNSIGNED_SHORT&&(k=i.RGBA16UI),N===i.UNSIGNED_INT&&(k=i.RGBA32UI),N===i.BYTE&&(k=i.RGBA8I),N===i.SHORT&&(k=i.RGBA16I),N===i.INT&&(k=i.RGBA32I)),g===i.RGB&&(N===i.UNSIGNED_INT_5_9_9_9_REV&&(k=i.RGB9_E5),N===i.UNSIGNED_INT_10F_11F_11F_REV&&(k=i.R11F_G11F_B10F)),g===i.RGBA){const Me=K?rr:Ve.getTransfer(V);N===i.FLOAT&&(k=i.RGBA32F),N===i.HALF_FLOAT&&(k=i.RGBA16F),N===i.UNSIGNED_BYTE&&(k=Me===Ye?i.SRGB8_ALPHA8:i.RGBA8),N===i.UNSIGNED_SHORT_4_4_4_4&&(k=i.RGBA4),N===i.UNSIGNED_SHORT_5_5_5_1&&(k=i.RGB5_A1)}return(k===i.R16F||k===i.R32F||k===i.RG16F||k===i.RG32F||k===i.RGBA16F||k===i.RGBA32F)&&e.get("EXT_color_buffer_float"),k}function E(y,g){let N;return y?g===null||g===Ln||g===vi?N=i.DEPTH24_STENCIL8:g===nn?N=i.DEPTH32F_STENCIL8:g===_i&&(N=i.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):g===null||g===Ln||g===vi?N=i.DEPTH_COMPONENT24:g===nn?N=i.DEPTH_COMPONENT32F:g===_i&&(N=i.DEPTH_COMPONENT16),N}function D(y,g){return p(y)===!0||y.isFramebufferTexture&&y.minFilter!==Gt&&y.minFilter!==Ut?Math.log2(Math.max(g.width,g.height))+1:y.mipmaps!==void 0&&y.mipmaps.length>0?y.mipmaps.length:y.isCompressedTexture&&Array.isArray(y.image)?g.mipmaps.length:1}function R(y){const g=y.target;g.removeEventListener("dispose",R),U(g),g.isVideoTexture&&h.delete(g)}function w(y){const g=y.target;g.removeEventListener("dispose",w),M(g)}function U(y){const g=n.get(y);if(g.__webglInit===void 0)return;const N=y.source,V=f.get(N);if(V){const K=V[g.__cacheKey];K.usedTimes--,K.usedTimes===0&&S(y),Object.keys(V).length===0&&f.delete(N)}n.remove(y)}function S(y){const g=n.get(y);i.deleteTexture(g.__webglTexture);const N=y.source,V=f.get(N);delete V[g.__cacheKey],a.memory.textures--}function M(y){const g=n.get(y);if(y.depthTexture&&(y.depthTexture.dispose(),n.remove(y.depthTexture)),y.isWebGLCubeRenderTarget)for(let V=0;V<6;V++){if(Array.isArray(g.__webglFramebuffer[V]))for(let K=0;K=r.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+y+" texture units while this GPU supports only "+r.maxTextures),C+=1,y}function q(y){const g=[];return g.push(y.wrapS),g.push(y.wrapT),g.push(y.wrapR||0),g.push(y.magFilter),g.push(y.minFilter),g.push(y.anisotropy),g.push(y.internalFormat),g.push(y.format),g.push(y.type),g.push(y.generateMipmaps),g.push(y.premultiplyAlpha),g.push(y.flipY),g.push(y.unpackAlignment),g.push(y.colorSpace),g.join()}function W(y,g){const N=n.get(y);if(y.isVideoTexture&&Ue(y),y.isRenderTargetTexture===!1&&y.isExternalTexture!==!0&&y.version>0&&N.__version!==y.version){const V=y.image;if(V===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(V.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{Y(N,y,g);return}}else y.isExternalTexture&&(N.__webglTexture=y.sourceTexture?y.sourceTexture:null);t.bindTexture(i.TEXTURE_2D,N.__webglTexture,i.TEXTURE0+g)}function X(y,g){const N=n.get(y);if(y.isRenderTargetTexture===!1&&y.version>0&&N.__version!==y.version){Y(N,y,g);return}t.bindTexture(i.TEXTURE_2D_ARRAY,N.__webglTexture,i.TEXTURE0+g)}function Z(y,g){const N=n.get(y);if(y.isRenderTargetTexture===!1&&y.version>0&&N.__version!==y.version){Y(N,y,g);return}t.bindTexture(i.TEXTURE_3D,N.__webglTexture,i.TEXTURE0+g)}function G(y,g){const N=n.get(y);if(y.version>0&&N.__version!==y.version){j(N,y,g);return}t.bindTexture(i.TEXTURE_CUBE_MAP,N.__webglTexture,i.TEXTURE0+g)}const se={[Cn]:i.REPEAT,[Pn]:i.CLAMP_TO_EDGE,[es]:i.MIRRORED_REPEAT},ce={[Gt]:i.NEAREST,[_l]:i.NEAREST_MIPMAP_NEAREST,[Di]:i.NEAREST_MIPMAP_LINEAR,[Ut]:i.LINEAR,[ur]:i.LINEAR_MIPMAP_NEAREST,[Dn]:i.LINEAR_MIPMAP_LINEAR},Ee={[Sl]:i.NEVER,[wl]:i.ALWAYS,[El]:i.LESS,[po]:i.LEQUAL,[yl]:i.EQUAL,[bl]:i.GEQUAL,[Tl]:i.GREATER,[Al]:i.NOTEQUAL};function Fe(y,g){if(g.type===nn&&e.has("OES_texture_float_linear")===!1&&(g.magFilter===Ut||g.magFilter===ur||g.magFilter===Di||g.magFilter===Dn||g.minFilter===Ut||g.minFilter===ur||g.minFilter===Di||g.minFilter===Dn)&&console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),i.texParameteri(y,i.TEXTURE_WRAP_S,se[g.wrapS]),i.texParameteri(y,i.TEXTURE_WRAP_T,se[g.wrapT]),(y===i.TEXTURE_3D||y===i.TEXTURE_2D_ARRAY)&&i.texParameteri(y,i.TEXTURE_WRAP_R,se[g.wrapR]),i.texParameteri(y,i.TEXTURE_MAG_FILTER,ce[g.magFilter]),i.texParameteri(y,i.TEXTURE_MIN_FILTER,ce[g.minFilter]),g.compareFunction&&(i.texParameteri(y,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE),i.texParameteri(y,i.TEXTURE_COMPARE_FUNC,Ee[g.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(g.magFilter===Gt||g.minFilter!==Di&&g.minFilter!==Dn||g.type===nn&&e.has("OES_texture_float_linear")===!1)return;if(g.anisotropy>1||n.get(g).__currentAnisotropy){const N=e.get("EXT_texture_filter_anisotropic");i.texParameterf(y,N.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(g.anisotropy,r.getMaxAnisotropy())),n.get(g).__currentAnisotropy=g.anisotropy}}}function Ke(y,g){let N=!1;y.__webglInit===void 0&&(y.__webglInit=!0,g.addEventListener("dispose",R));const V=g.source;let K=f.get(V);K===void 0&&(K={},f.set(V,K));const k=q(g);if(k!==y.__cacheKey){K[k]===void 0&&(K[k]={texture:i.createTexture(),usedTimes:0},a.memory.textures++,N=!0),K[k].usedTimes++;const Me=K[y.__cacheKey];Me!==void 0&&(K[y.__cacheKey].usedTimes--,Me.usedTimes===0&&S(g)),y.__cacheKey=k,y.__webglTexture=K[k].texture}return N}function Je(y,g,N){return Math.floor(Math.floor(y/N)/g)}function We(y,g,N,V){const k=y.updateRanges;if(k.length===0)t.texSubImage2D(i.TEXTURE_2D,0,0,0,g.width,g.height,N,V,g.data);else{k.sort((ee,le)=>ee.start-le.start);let Me=0;for(let ee=1;ee0){P&&te&&t.texStorage2D(i.TEXTURE_2D,he,xe,Le[0].width,Le[0].height);for(let J=0,$=Le.length;J<$;J++)ae=Le[J],P?ie&&t.texSubImage2D(i.TEXTURE_2D,J,0,0,ae.width,ae.height,le,be,ae.data):t.texImage2D(i.TEXTURE_2D,J,xe,ae.width,ae.height,0,le,be,ae.data);g.generateMipmaps=!1}else P?(te&&t.texStorage2D(i.TEXTURE_2D,he,xe,ee.width,ee.height),ie&&We(g,ee,le,be)):t.texImage2D(i.TEXTURE_2D,0,xe,ee.width,ee.height,0,le,be,ee.data);else if(g.isCompressedTexture)if(g.isCompressedArrayTexture){P&&te&&t.texStorage3D(i.TEXTURE_2D_ARRAY,he,xe,Le[0].width,Le[0].height,ee.depth);for(let J=0,$=Le.length;J<$;J++)if(ae=Le[J],g.format!==zt)if(le!==null)if(P){if(ie)if(g.layerUpdates.size>0){const pe=Ra(ae.width,ae.height,g.format,g.type);for(const Pe of g.layerUpdates){const Ze=ae.data.subarray(Pe*pe/ae.data.BYTES_PER_ELEMENT,(Pe+1)*pe/ae.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,J,0,0,Pe,ae.width,ae.height,1,le,Ze)}g.clearLayerUpdates()}else t.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,J,0,0,0,ae.width,ae.height,ee.depth,le,ae.data)}else t.compressedTexImage3D(i.TEXTURE_2D_ARRAY,J,xe,ae.width,ae.height,ee.depth,0,ae.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else P?ie&&t.texSubImage3D(i.TEXTURE_2D_ARRAY,J,0,0,0,ae.width,ae.height,ee.depth,le,be,ae.data):t.texImage3D(i.TEXTURE_2D_ARRAY,J,xe,ae.width,ae.height,ee.depth,0,le,be,ae.data)}else{P&&te&&t.texStorage2D(i.TEXTURE_2D,he,xe,Le[0].width,Le[0].height);for(let J=0,$=Le.length;J<$;J++)ae=Le[J],g.format!==zt?le!==null?P?ie&&t.compressedTexSubImage2D(i.TEXTURE_2D,J,0,0,ae.width,ae.height,le,ae.data):t.compressedTexImage2D(i.TEXTURE_2D,J,xe,ae.width,ae.height,0,ae.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):P?ie&&t.texSubImage2D(i.TEXTURE_2D,J,0,0,ae.width,ae.height,le,be,ae.data):t.texImage2D(i.TEXTURE_2D,J,xe,ae.width,ae.height,0,le,be,ae.data)}else if(g.isDataArrayTexture)if(P){if(te&&t.texStorage3D(i.TEXTURE_2D_ARRAY,he,xe,ee.width,ee.height,ee.depth),ie)if(g.layerUpdates.size>0){const J=Ra(ee.width,ee.height,g.format,g.type);for(const $ of g.layerUpdates){const pe=ee.data.subarray($*J/ee.data.BYTES_PER_ELEMENT,($+1)*J/ee.data.BYTES_PER_ELEMENT);t.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,$,ee.width,ee.height,1,le,be,pe)}g.clearLayerUpdates()}else t.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,0,ee.width,ee.height,ee.depth,le,be,ee.data)}else t.texImage3D(i.TEXTURE_2D_ARRAY,0,xe,ee.width,ee.height,ee.depth,0,le,be,ee.data);else if(g.isData3DTexture)P?(te&&t.texStorage3D(i.TEXTURE_3D,he,xe,ee.width,ee.height,ee.depth),ie&&t.texSubImage3D(i.TEXTURE_3D,0,0,0,0,ee.width,ee.height,ee.depth,le,be,ee.data)):t.texImage3D(i.TEXTURE_3D,0,xe,ee.width,ee.height,ee.depth,0,le,be,ee.data);else if(g.isFramebufferTexture){if(te)if(P)t.texStorage2D(i.TEXTURE_2D,he,xe,ee.width,ee.height);else{let J=ee.width,$=ee.height;for(let pe=0;pe>=1,$>>=1}}else if(Le.length>0){if(P&&te){const J=at(Le[0]);t.texStorage2D(i.TEXTURE_2D,he,xe,J.width,J.height)}for(let J=0,$=Le.length;J<$;J++)ae=Le[J],P?ie&&t.texSubImage2D(i.TEXTURE_2D,J,0,0,le,be,ae):t.texImage2D(i.TEXTURE_2D,J,xe,le,be,ae);g.generateMipmaps=!1}else if(P){if(te){const J=at(ee);t.texStorage2D(i.TEXTURE_2D,he,xe,J.width,J.height)}ie&&t.texSubImage2D(i.TEXTURE_2D,0,0,0,le,be,ee)}else t.texImage2D(i.TEXTURE_2D,0,xe,le,be,ee);p(g)&&u(V),Me.__version=k.version,g.onUpdate&&g.onUpdate(g)}y.__version=g.version}function j(y,g,N){if(g.image.length!==6)return;const V=Ke(y,g),K=g.source;t.bindTexture(i.TEXTURE_CUBE_MAP,y.__webglTexture,i.TEXTURE0+N);const k=n.get(K);if(K.version!==k.__version||V===!0){t.activeTexture(i.TEXTURE0+N);const Me=Ve.getPrimaries(Ve.workingColorSpace),ne=g.colorSpace===dn?null:Ve.getPrimaries(g.colorSpace),_e=g.colorSpace===dn||Me===ne?i.NONE:i.BROWSER_DEFAULT_WEBGL;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,g.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,g.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,g.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,_e);const ve=g.isCompressedTexture||g.image[0].isCompressedTexture,ee=g.image[0]&&g.image[0].isDataTexture,le=[];for(let $=0;$<6;$++)!ve&&!ee?le[$]=x(g.image[$],!0,r.maxCubemapSize):le[$]=ee?g.image[$].image:g.image[$],le[$]=ut(g,le[$]);const be=le[0],xe=s.convert(g.format,g.colorSpace),ae=s.convert(g.type),Le=A(g.internalFormat,xe,ae,g.colorSpace),P=g.isVideoTexture!==!0,te=k.__version===void 0||V===!0,ie=K.dataReady;let he=D(g,be);Fe(i.TEXTURE_CUBE_MAP,g);let J;if(ve){P&&te&&t.texStorage2D(i.TEXTURE_CUBE_MAP,he,Le,be.width,be.height);for(let $=0;$<6;$++){J=le[$].mipmaps;for(let pe=0;pe0&&he++;const $=at(le[0]);t.texStorage2D(i.TEXTURE_CUBE_MAP,he,Le,$.width,$.height)}for(let $=0;$<6;$++)if(ee){P?ie&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+$,0,0,0,le[$].width,le[$].height,xe,ae,le[$].data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+$,0,Le,le[$].width,le[$].height,0,xe,ae,le[$].data);for(let pe=0;pe>k),be=Math.max(1,g.height>>k);K===i.TEXTURE_3D||K===i.TEXTURE_2D_ARRAY?t.texImage3D(K,k,_e,le,be,g.depth,0,Me,ne,null):t.texImage2D(K,k,_e,le,be,0,Me,ne,null)}t.bindFramebuffer(i.FRAMEBUFFER,y),ge(g)?o.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,V,K,ee.__webglTexture,0,et(g)):(K===i.TEXTURE_2D||K>=i.TEXTURE_CUBE_MAP_POSITIVE_X&&K<=i.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&i.framebufferTexture2D(i.FRAMEBUFFER,V,K,ee.__webglTexture,k),t.bindFramebuffer(i.FRAMEBUFFER,null)}function Ce(y,g,N){if(i.bindRenderbuffer(i.RENDERBUFFER,y),g.depthBuffer){const V=g.depthTexture,K=V&&V.isDepthTexture?V.type:null,k=E(g.stencilBuffer,K),Me=g.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,ne=et(g);ge(g)?o.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,ne,k,g.width,g.height):N?i.renderbufferStorageMultisample(i.RENDERBUFFER,ne,k,g.width,g.height):i.renderbufferStorage(i.RENDERBUFFER,k,g.width,g.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,Me,i.RENDERBUFFER,y)}else{const V=g.textures;for(let K=0;K{delete g.__boundDepthTexture,delete g.__depthDisposeCallback,V.removeEventListener("dispose",K)};V.addEventListener("dispose",K),g.__depthDisposeCallback=K}g.__boundDepthTexture=V}if(y.depthTexture&&!g.__autoAllocateDepthBuffer){if(N)throw new Error("target.depthTexture not supported in Cube render targets");const V=y.texture.mipmaps;V&&V.length>0?Se(g.__webglFramebuffer[0],y):Se(g.__webglFramebuffer,y)}else if(N){g.__webglDepthbuffer=[];for(let V=0;V<6;V++)if(t.bindFramebuffer(i.FRAMEBUFFER,g.__webglFramebuffer[V]),g.__webglDepthbuffer[V]===void 0)g.__webglDepthbuffer[V]=i.createRenderbuffer(),Ce(g.__webglDepthbuffer[V],y,!1);else{const K=y.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,k=g.__webglDepthbuffer[V];i.bindRenderbuffer(i.RENDERBUFFER,k),i.framebufferRenderbuffer(i.FRAMEBUFFER,K,i.RENDERBUFFER,k)}}else{const V=y.texture.mipmaps;if(V&&V.length>0?t.bindFramebuffer(i.FRAMEBUFFER,g.__webglFramebuffer[0]):t.bindFramebuffer(i.FRAMEBUFFER,g.__webglFramebuffer),g.__webglDepthbuffer===void 0)g.__webglDepthbuffer=i.createRenderbuffer(),Ce(g.__webglDepthbuffer,y,!1);else{const K=y.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,k=g.__webglDepthbuffer;i.bindRenderbuffer(i.RENDERBUFFER,k),i.framebufferRenderbuffer(i.FRAMEBUFFER,K,i.RENDERBUFFER,k)}}t.bindFramebuffer(i.FRAMEBUFFER,null)}function ft(y,g,N){const V=n.get(y);g!==void 0&&de(V.__webglFramebuffer,y,y.texture,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,0),N!==void 0&&ze(y)}function T(y){const g=y.texture,N=n.get(y),V=n.get(g);y.addEventListener("dispose",w);const K=y.textures,k=y.isWebGLCubeRenderTarget===!0,Me=K.length>1;if(Me||(V.__webglTexture===void 0&&(V.__webglTexture=i.createTexture()),V.__version=g.version,a.memory.textures++),k){N.__webglFramebuffer=[];for(let ne=0;ne<6;ne++)if(g.mipmaps&&g.mipmaps.length>0){N.__webglFramebuffer[ne]=[];for(let _e=0;_e0){N.__webglFramebuffer=[];for(let ne=0;ne0&&ge(y)===!1){N.__webglMultisampledFramebuffer=i.createFramebuffer(),N.__webglColorRenderbuffer=[],t.bindFramebuffer(i.FRAMEBUFFER,N.__webglMultisampledFramebuffer);for(let ne=0;ne0)for(let _e=0;_e0)for(let _e=0;_e0){if(ge(y)===!1){const g=y.textures,N=y.width,V=y.height;let K=i.COLOR_BUFFER_BIT;const k=y.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,Me=n.get(y),ne=g.length>1;if(ne)for(let ve=0;ve0?t.bindFramebuffer(i.DRAW_FRAMEBUFFER,Me.__webglFramebuffer[0]):t.bindFramebuffer(i.DRAW_FRAMEBUFFER,Me.__webglFramebuffer);for(let ve=0;ve0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&g.__useRenderToTexture!==!1}function Ue(y){const g=a.render.frame;h.get(y)!==g&&(h.set(y,g),y.update())}function ut(y,g){const N=y.colorSpace,V=y.format,K=y.type;return y.isCompressedTexture===!0||y.isVideoTexture===!0||N!==ii&&N!==dn&&(Ve.getTransfer(N)===Ye?(V!==zt||K!==qt)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",N)),g}function at(y){return typeof HTMLImageElement<"u"&&y instanceof HTMLImageElement?(l.width=y.naturalWidth||y.width,l.height=y.naturalHeight||y.height):typeof VideoFrame<"u"&&y instanceof VideoFrame?(l.width=y.displayWidth,l.height=y.displayHeight):(l.width=y.width,l.height=y.height),l}this.allocateTextureUnit=z,this.resetTextureUnits=O,this.setTexture2D=W,this.setTexture2DArray=X,this.setTexture3D=Z,this.setTextureCube=G,this.rebindTextures=ft,this.setupRenderTarget=T,this.updateRenderTargetMipmap=Qe,this.updateMultisampleRenderTarget=me,this.setupDepthRenderbuffer=ze,this.setupFrameBufferTexture=de,this.useMultisampledRTT=ge}function qf(i,e){function t(n,r=dn){let s;const a=Ve.getTransfer(r);if(n===qt)return i.UNSIGNED_BYTE;if(n===Us)return i.UNSIGNED_SHORT_4_4_4_4;if(n===Ns)return i.UNSIGNED_SHORT_5_5_5_1;if(n===ao)return i.UNSIGNED_INT_5_9_9_9_REV;if(n===oo)return i.UNSIGNED_INT_10F_11F_11F_REV;if(n===ro)return i.BYTE;if(n===so)return i.SHORT;if(n===_i)return i.UNSIGNED_SHORT;if(n===Is)return i.INT;if(n===Ln)return i.UNSIGNED_INT;if(n===nn)return i.FLOAT;if(n===yi)return i.HALF_FLOAT;if(n===lo)return i.ALPHA;if(n===co)return i.RGB;if(n===zt)return i.RGBA;if(n===xi)return i.DEPTH_COMPONENT;if(n===Mi)return i.DEPTH_STENCIL;if(n===uo)return i.RED;if(n===Fs)return i.RED_INTEGER;if(n===ho)return i.RG;if(n===Os)return i.RG_INTEGER;if(n===Bs)return i.RGBA_INTEGER;if(n===Ji||n===Qi||n===er||n===tr)if(a===Ye)if(s=e.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(n===Ji)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===Qi)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===er)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===tr)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=e.get("WEBGL_compressed_texture_s3tc"),s!==null){if(n===Ji)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===Qi)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===er)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===tr)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===ts||n===ns||n===is||n===rs)if(s=e.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(n===ts)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===ns)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===is)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===rs)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===ss||n===as||n===os)if(s=e.get("WEBGL_compressed_texture_etc"),s!==null){if(n===ss||n===as)return a===Ye?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(n===os)return a===Ye?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(n===ls||n===cs||n===us||n===hs||n===ds||n===fs||n===ps||n===ms||n===gs||n===_s||n===vs||n===xs||n===Ms||n===Ss)if(s=e.get("WEBGL_compressed_texture_astc"),s!==null){if(n===ls)return a===Ye?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===cs)return a===Ye?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===us)return a===Ye?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===hs)return a===Ye?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===ds)return a===Ye?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===fs)return a===Ye?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===ps)return a===Ye?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===ms)return a===Ye?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===gs)return a===Ye?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===_s)return a===Ye?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===vs)return a===Ye?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===xs)return a===Ye?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===Ms)return a===Ye?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===Ss)return a===Ye?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===Es||n===ys||n===Ts)if(s=e.get("EXT_texture_compression_bptc"),s!==null){if(n===Es)return a===Ye?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===ys)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===Ts)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===As||n===bs||n===ws||n===Rs)if(s=e.get("EXT_texture_compression_rgtc"),s!==null){if(n===As)return s.COMPRESSED_RED_RGTC1_EXT;if(n===bs)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===ws)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===Rs)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===vi?i.UNSIGNED_INT_24_8:i[n]!==void 0?i[n]:null}return{convert:t}}const Yf=` +void main() { + + gl_Position = vec4( position, 1.0 ); + +}`,$f=` +uniform sampler2DArray depthColor; +uniform float depthWidth; +uniform float depthHeight; + +void main() { + + vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); + + if ( coord.x >= 1.0 ) { + + gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; + + } else { + + gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; + + } + +}`;class Kf{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){const n=new bo(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,n=new gn({vertexShader:Yf,fragmentShader:$f,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new wt(new ai(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class Zf extends si{constructor(e,t){super();const n=this;let r=null,s=1,a=null,o="local-floor",c=1,l=null,h=null,d=null,f=null,m=null,_=null;const x=typeof XRWebGLBinding<"u",p=new Kf,u={},b=t.getContextAttributes();let A=null,E=null;const D=[],R=[],w=new Ge;let U=null;const S=new It;S.viewport=new rt;const M=new It;M.viewport=new rt;const C=[S,M],O=new mc;let z=null,q=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Y){let j=D[Y];return j===void 0&&(j=new Ir,D[Y]=j),j.getTargetRaySpace()},this.getControllerGrip=function(Y){let j=D[Y];return j===void 0&&(j=new Ir,D[Y]=j),j.getGripSpace()},this.getHand=function(Y){let j=D[Y];return j===void 0&&(j=new Ir,D[Y]=j),j.getHandSpace()};function W(Y){const j=R.indexOf(Y.inputSource);if(j===-1)return;const de=D[j];de!==void 0&&(de.update(Y.inputSource,Y.frame,l||a),de.dispatchEvent({type:Y.type,data:Y.inputSource}))}function X(){r.removeEventListener("select",W),r.removeEventListener("selectstart",W),r.removeEventListener("selectend",W),r.removeEventListener("squeeze",W),r.removeEventListener("squeezestart",W),r.removeEventListener("squeezeend",W),r.removeEventListener("end",X),r.removeEventListener("inputsourceschange",Z);for(let Y=0;Y=0&&(R[Ce]=null,D[Ce].disconnect(de))}for(let j=0;j=R.length){R.push(de),Ce=ze;break}else if(R[ze]===null){R[ze]=de,Ce=ze;break}if(Ce===-1)break}const Se=D[Ce];Se&&Se.connect(de)}}const G=new F,se=new F;function ce(Y,j,de){G.setFromMatrixPosition(j.matrixWorld),se.setFromMatrixPosition(de.matrixWorld);const Ce=G.distanceTo(se),Se=j.projectionMatrix.elements,ze=de.projectionMatrix.elements,ft=Se[14]/(Se[10]-1),T=Se[14]/(Se[10]+1),Qe=(Se[9]+1)/Se[5],De=(Se[9]-1)/Se[5],we=(Se[8]-1)/Se[0],me=(ze[8]+1)/ze[0],et=ft*we,ge=ft*me,Ue=Ce/(-we+me),ut=Ue*-we;if(j.matrixWorld.decompose(Y.position,Y.quaternion,Y.scale),Y.translateX(ut),Y.translateZ(Ue),Y.matrixWorld.compose(Y.position,Y.quaternion,Y.scale),Y.matrixWorldInverse.copy(Y.matrixWorld).invert(),Se[10]===-1)Y.projectionMatrix.copy(j.projectionMatrix),Y.projectionMatrixInverse.copy(j.projectionMatrixInverse);else{const at=ft+Ue,y=T+Ue,g=et-ut,N=ge+(Ce-ut),V=Qe*T/y*at,K=De*T/y*at;Y.projectionMatrix.makePerspective(g,N,V,K,at,y),Y.projectionMatrixInverse.copy(Y.projectionMatrix).invert()}}function Ee(Y,j){j===null?Y.matrixWorld.copy(Y.matrix):Y.matrixWorld.multiplyMatrices(j.matrixWorld,Y.matrix),Y.matrixWorldInverse.copy(Y.matrixWorld).invert()}this.updateCamera=function(Y){if(r===null)return;let j=Y.near,de=Y.far;p.texture!==null&&(p.depthNear>0&&(j=p.depthNear),p.depthFar>0&&(de=p.depthFar)),O.near=M.near=S.near=j,O.far=M.far=S.far=de,(z!==O.near||q!==O.far)&&(r.updateRenderState({depthNear:O.near,depthFar:O.far}),z=O.near,q=O.far),O.layers.mask=Y.layers.mask|6,S.layers.mask=O.layers.mask&3,M.layers.mask=O.layers.mask&5;const Ce=Y.parent,Se=O.cameras;Ee(O,Ce);for(let ze=0;ze0&&(p.alphaTest.value=u.alphaTest);const b=e.get(u),A=b.envMap,E=b.envMapRotation;A&&(p.envMap.value=A,Tn.copy(E),Tn.x*=-1,Tn.y*=-1,Tn.z*=-1,A.isCubeTexture&&A.isRenderTargetTexture===!1&&(Tn.y*=-1,Tn.z*=-1),p.envMapRotation.value.setFromMatrix4(jf.makeRotationFromEuler(Tn)),p.flipEnvMap.value=A.isCubeTexture&&A.isRenderTargetTexture===!1?-1:1,p.reflectivity.value=u.reflectivity,p.ior.value=u.ior,p.refractionRatio.value=u.refractionRatio),u.lightMap&&(p.lightMap.value=u.lightMap,p.lightMapIntensity.value=u.lightMapIntensity,t(u.lightMap,p.lightMapTransform)),u.aoMap&&(p.aoMap.value=u.aoMap,p.aoMapIntensity.value=u.aoMapIntensity,t(u.aoMap,p.aoMapTransform))}function a(p,u){p.diffuse.value.copy(u.color),p.opacity.value=u.opacity,u.map&&(p.map.value=u.map,t(u.map,p.mapTransform))}function o(p,u){p.dashSize.value=u.dashSize,p.totalSize.value=u.dashSize+u.gapSize,p.scale.value=u.scale}function c(p,u,b,A){p.diffuse.value.copy(u.color),p.opacity.value=u.opacity,p.size.value=u.size*b,p.scale.value=A*.5,u.map&&(p.map.value=u.map,t(u.map,p.uvTransform)),u.alphaMap&&(p.alphaMap.value=u.alphaMap,t(u.alphaMap,p.alphaMapTransform)),u.alphaTest>0&&(p.alphaTest.value=u.alphaTest)}function l(p,u){p.diffuse.value.copy(u.color),p.opacity.value=u.opacity,p.rotation.value=u.rotation,u.map&&(p.map.value=u.map,t(u.map,p.mapTransform)),u.alphaMap&&(p.alphaMap.value=u.alphaMap,t(u.alphaMap,p.alphaMapTransform)),u.alphaTest>0&&(p.alphaTest.value=u.alphaTest)}function h(p,u){p.specular.value.copy(u.specular),p.shininess.value=Math.max(u.shininess,1e-4)}function d(p,u){u.gradientMap&&(p.gradientMap.value=u.gradientMap)}function f(p,u){p.metalness.value=u.metalness,u.metalnessMap&&(p.metalnessMap.value=u.metalnessMap,t(u.metalnessMap,p.metalnessMapTransform)),p.roughness.value=u.roughness,u.roughnessMap&&(p.roughnessMap.value=u.roughnessMap,t(u.roughnessMap,p.roughnessMapTransform)),u.envMap&&(p.envMapIntensity.value=u.envMapIntensity)}function m(p,u,b){p.ior.value=u.ior,u.sheen>0&&(p.sheenColor.value.copy(u.sheenColor).multiplyScalar(u.sheen),p.sheenRoughness.value=u.sheenRoughness,u.sheenColorMap&&(p.sheenColorMap.value=u.sheenColorMap,t(u.sheenColorMap,p.sheenColorMapTransform)),u.sheenRoughnessMap&&(p.sheenRoughnessMap.value=u.sheenRoughnessMap,t(u.sheenRoughnessMap,p.sheenRoughnessMapTransform))),u.clearcoat>0&&(p.clearcoat.value=u.clearcoat,p.clearcoatRoughness.value=u.clearcoatRoughness,u.clearcoatMap&&(p.clearcoatMap.value=u.clearcoatMap,t(u.clearcoatMap,p.clearcoatMapTransform)),u.clearcoatRoughnessMap&&(p.clearcoatRoughnessMap.value=u.clearcoatRoughnessMap,t(u.clearcoatRoughnessMap,p.clearcoatRoughnessMapTransform)),u.clearcoatNormalMap&&(p.clearcoatNormalMap.value=u.clearcoatNormalMap,t(u.clearcoatNormalMap,p.clearcoatNormalMapTransform),p.clearcoatNormalScale.value.copy(u.clearcoatNormalScale),u.side===Et&&p.clearcoatNormalScale.value.negate())),u.dispersion>0&&(p.dispersion.value=u.dispersion),u.iridescence>0&&(p.iridescence.value=u.iridescence,p.iridescenceIOR.value=u.iridescenceIOR,p.iridescenceThicknessMinimum.value=u.iridescenceThicknessRange[0],p.iridescenceThicknessMaximum.value=u.iridescenceThicknessRange[1],u.iridescenceMap&&(p.iridescenceMap.value=u.iridescenceMap,t(u.iridescenceMap,p.iridescenceMapTransform)),u.iridescenceThicknessMap&&(p.iridescenceThicknessMap.value=u.iridescenceThicknessMap,t(u.iridescenceThicknessMap,p.iridescenceThicknessMapTransform))),u.transmission>0&&(p.transmission.value=u.transmission,p.transmissionSamplerMap.value=b.texture,p.transmissionSamplerSize.value.set(b.width,b.height),u.transmissionMap&&(p.transmissionMap.value=u.transmissionMap,t(u.transmissionMap,p.transmissionMapTransform)),p.thickness.value=u.thickness,u.thicknessMap&&(p.thicknessMap.value=u.thicknessMap,t(u.thicknessMap,p.thicknessMapTransform)),p.attenuationDistance.value=u.attenuationDistance,p.attenuationColor.value.copy(u.attenuationColor)),u.anisotropy>0&&(p.anisotropyVector.value.set(u.anisotropy*Math.cos(u.anisotropyRotation),u.anisotropy*Math.sin(u.anisotropyRotation)),u.anisotropyMap&&(p.anisotropyMap.value=u.anisotropyMap,t(u.anisotropyMap,p.anisotropyMapTransform))),p.specularIntensity.value=u.specularIntensity,p.specularColor.value.copy(u.specularColor),u.specularColorMap&&(p.specularColorMap.value=u.specularColorMap,t(u.specularColorMap,p.specularColorMapTransform)),u.specularIntensityMap&&(p.specularIntensityMap.value=u.specularIntensityMap,t(u.specularIntensityMap,p.specularIntensityMapTransform))}function _(p,u){u.matcap&&(p.matcap.value=u.matcap)}function x(p,u){const b=e.get(u).light;p.referencePosition.value.setFromMatrixPosition(b.matrixWorld),p.nearDistance.value=b.shadow.camera.near,p.farDistance.value=b.shadow.camera.far}return{refreshFogUniforms:n,refreshMaterialUniforms:r}}function Qf(i,e,t,n){let r={},s={},a=[];const o=i.getParameter(i.MAX_UNIFORM_BUFFER_BINDINGS);function c(b,A){const E=A.program;n.uniformBlockBinding(b,E)}function l(b,A){let E=r[b.id];E===void 0&&(_(b),E=h(b),r[b.id]=E,b.addEventListener("dispose",p));const D=A.program;n.updateUBOMapping(b,D);const R=e.render.frame;s[b.id]!==R&&(f(b),s[b.id]=R)}function h(b){const A=d();b.__bindingPointIndex=A;const E=i.createBuffer(),D=b.__size,R=b.usage;return i.bindBuffer(i.UNIFORM_BUFFER,E),i.bufferData(i.UNIFORM_BUFFER,D,R),i.bindBuffer(i.UNIFORM_BUFFER,null),i.bindBufferBase(i.UNIFORM_BUFFER,A,E),E}function d(){for(let b=0;b0&&(E+=D-R),b.__size=E,b.__cache={},this}function x(b){const A={boundary:0,storage:0};return typeof b=="number"||typeof b=="boolean"?(A.boundary=4,A.storage=4):b.isVector2?(A.boundary=8,A.storage=8):b.isVector3||b.isColor?(A.boundary=16,A.storage=12):b.isVector4?(A.boundary=16,A.storage=16):b.isMatrix3?(A.boundary=48,A.storage=48):b.isMatrix4?(A.boundary=64,A.storage=64):b.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",b),A}function p(b){const A=b.target;A.removeEventListener("dispose",p);const E=a.indexOf(A.__bindingPointIndex);a.splice(E,1),i.deleteBuffer(r[A.id]),delete r[A.id],delete s[A.id]}function u(){for(const b in r)i.deleteBuffer(r[b]);a=[],r={},s={}}return{bind:c,update:l,dispose:u}}class ep{constructor(e={}){const{canvas:t=Cl(),context:n=null,depth:r=!0,stencil:s=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:l=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:d=!1,reversedDepthBuffer:f=!1}=e;this.isWebGLRenderer=!0;let m;if(n!==null){if(typeof WebGLRenderingContext<"u"&&n instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");m=n.getContextAttributes().alpha}else m=a;const _=new Uint32Array(4),x=new Int32Array(4);let p=null,u=null;const b=[],A=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=pn,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const E=this;let D=!1;this._outputColorSpace=Lt;let R=0,w=0,U=null,S=-1,M=null;const C=new rt,O=new rt;let z=null;const q=new Oe(0);let W=0,X=t.width,Z=t.height,G=1,se=null,ce=null;const Ee=new rt(0,0,X,Z),Fe=new rt(0,0,X,Z);let Ke=!1;const Je=new ks;let We=!1,Y=!1;const j=new st,de=new F,Ce=new rt,Se={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let ze=!1;function ft(){return U===null?G:1}let T=n;function Qe(v,L){return t.getContext(v,L)}try{const v={alpha:!0,depth:r,stencil:s,antialias:o,premultipliedAlpha:c,preserveDrawingBuffer:l,powerPreference:h,failIfMajorPerformanceCaveat:d};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${Ls}`),t.addEventListener("webglcontextlost",ie,!1),t.addEventListener("webglcontextrestored",he,!1),t.addEventListener("webglcontextcreationerror",J,!1),T===null){const L="webgl2";if(T=Qe(L,v),T===null)throw Qe(L)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(v){throw console.error("THREE.WebGLRenderer: "+v.message),v}let De,we,me,et,ge,Ue,ut,at,y,g,N,V,K,k,Me,ne,_e,ve,ee,le,be,xe,ae,Le;function P(){De=new cd(T),De.init(),xe=new qf(T,De),we=new nd(T,De,e,xe),me=new Wf(T,De),we.reversedDepthBuffer&&f&&me.buffers.depth.setReversed(!0),et=new dd(T),ge=new Df,Ue=new Xf(T,De,me,ge,we,xe,et),ut=new rd(E),at=new ld(E),y=new vc(T),ae=new ed(T,y),g=new ud(T,y,et,ae),N=new pd(T,g,y,et),ee=new fd(T,we,Ue),ne=new id(ge),V=new Pf(E,ut,at,De,we,ae,ne),K=new Jf(E,ge),k=new If,Me=new Hf(De),ve=new Qh(E,ut,at,me,N,m,c),_e=new kf(E,N,we),Le=new Qf(T,et,we,me),le=new td(T,De,et),be=new hd(T,De,et),et.programs=V.programs,E.capabilities=we,E.extensions=De,E.properties=ge,E.renderLists=k,E.shadowMap=_e,E.state=me,E.info=et}P();const te=new Zf(E,T);this.xr=te,this.getContext=function(){return T},this.getContextAttributes=function(){return T.getContextAttributes()},this.forceContextLoss=function(){const v=De.get("WEBGL_lose_context");v&&v.loseContext()},this.forceContextRestore=function(){const v=De.get("WEBGL_lose_context");v&&v.restoreContext()},this.getPixelRatio=function(){return G},this.setPixelRatio=function(v){v!==void 0&&(G=v,this.setSize(X,Z,!1))},this.getSize=function(v){return v.set(X,Z)},this.setSize=function(v,L,B=!0){if(te.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}X=v,Z=L,t.width=Math.floor(v*G),t.height=Math.floor(L*G),B===!0&&(t.style.width=v+"px",t.style.height=L+"px"),this.setViewport(0,0,v,L)},this.getDrawingBufferSize=function(v){return v.set(X*G,Z*G).floor()},this.setDrawingBufferSize=function(v,L,B){X=v,Z=L,G=B,t.width=Math.floor(v*B),t.height=Math.floor(L*B),this.setViewport(0,0,v,L)},this.getCurrentViewport=function(v){return v.copy(C)},this.getViewport=function(v){return v.copy(Ee)},this.setViewport=function(v,L,B,H){v.isVector4?Ee.set(v.x,v.y,v.z,v.w):Ee.set(v,L,B,H),me.viewport(C.copy(Ee).multiplyScalar(G).round())},this.getScissor=function(v){return v.copy(Fe)},this.setScissor=function(v,L,B,H){v.isVector4?Fe.set(v.x,v.y,v.z,v.w):Fe.set(v,L,B,H),me.scissor(O.copy(Fe).multiplyScalar(G).round())},this.getScissorTest=function(){return Ke},this.setScissorTest=function(v){me.setScissorTest(Ke=v)},this.setOpaqueSort=function(v){se=v},this.setTransparentSort=function(v){ce=v},this.getClearColor=function(v){return v.copy(ve.getClearColor())},this.setClearColor=function(){ve.setClearColor(...arguments)},this.getClearAlpha=function(){return ve.getClearAlpha()},this.setClearAlpha=function(){ve.setClearAlpha(...arguments)},this.clear=function(v=!0,L=!0,B=!0){let H=0;if(v){let I=!1;if(U!==null){const Q=U.texture.format;I=Q===Bs||Q===Os||Q===Fs}if(I){const Q=U.texture.type,oe=Q===qt||Q===Ln||Q===_i||Q===vi||Q===Us||Q===Ns,fe=ve.getClearColor(),ue=ve.getClearAlpha(),Ae=fe.r,Re=fe.g,ye=fe.b;oe?(_[0]=Ae,_[1]=Re,_[2]=ye,_[3]=ue,T.clearBufferuiv(T.COLOR,0,_)):(x[0]=Ae,x[1]=Re,x[2]=ye,x[3]=ue,T.clearBufferiv(T.COLOR,0,x))}else H|=T.COLOR_BUFFER_BIT}L&&(H|=T.DEPTH_BUFFER_BIT),B&&(H|=T.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),T.clear(H)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",ie,!1),t.removeEventListener("webglcontextrestored",he,!1),t.removeEventListener("webglcontextcreationerror",J,!1),ve.dispose(),k.dispose(),Me.dispose(),ge.dispose(),ut.dispose(),at.dispose(),N.dispose(),ae.dispose(),Le.dispose(),V.dispose(),te.dispose(),te.removeEventListener("sessionstart",kt),te.removeEventListener("sessionend",$s),_n.stop()};function ie(v){v.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),D=!0}function he(){console.log("THREE.WebGLRenderer: Context Restored."),D=!1;const v=et.autoReset,L=_e.enabled,B=_e.autoUpdate,H=_e.needsUpdate,I=_e.type;P(),et.autoReset=v,_e.enabled=L,_e.autoUpdate=B,_e.needsUpdate=H,_e.type=I}function J(v){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",v.statusMessage)}function $(v){const L=v.target;L.removeEventListener("dispose",$),pe(L)}function pe(v){Pe(v),ge.remove(v)}function Pe(v){const L=ge.get(v).programs;L!==void 0&&(L.forEach(function(B){V.releaseProgram(B)}),v.isShaderMaterial&&V.releaseShaderCache(v))}this.renderBufferDirect=function(v,L,B,H,I,Q){L===null&&(L=Se);const oe=I.isMesh&&I.matrixWorld.determinant()<0,fe=No(v,L,B,H,I);me.setMaterial(H,oe);let ue=B.index,Ae=1;if(H.wireframe===!0){if(ue=g.getWireframeAttribute(B),ue===void 0)return;Ae=2}const Re=B.drawRange,ye=B.attributes.position;let Be=Re.start*Ae,qe=(Re.start+Re.count)*Ae;Q!==null&&(Be=Math.max(Be,Q.start*Ae),qe=Math.min(qe,(Q.start+Q.count)*Ae)),ue!==null?(Be=Math.max(Be,0),qe=Math.min(qe,ue.count)):ye!=null&&(Be=Math.max(Be,0),qe=Math.min(qe,ye.count));const it=qe-Be;if(it<0||it===1/0)return;ae.setup(I,H,fe,B,ue);let je,$e=le;if(ue!==null&&(je=y.get(ue),$e=be,$e.setIndex(je)),I.isMesh)H.wireframe===!0?(me.setLineWidth(H.wireframeLinewidth*ft()),$e.setMode(T.LINES)):$e.setMode(T.TRIANGLES);else if(I.isLine){let Te=H.linewidth;Te===void 0&&(Te=1),me.setLineWidth(Te*ft()),I.isLineSegments?$e.setMode(T.LINES):I.isLineLoop?$e.setMode(T.LINE_LOOP):$e.setMode(T.LINE_STRIP)}else I.isPoints?$e.setMode(T.POINTS):I.isSprite&&$e.setMode(T.TRIANGLES);if(I.isBatchedMesh)if(I._multiDrawInstances!==null)Ei("THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),$e.renderMultiDrawInstances(I._multiDrawStarts,I._multiDrawCounts,I._multiDrawCount,I._multiDrawInstances);else if(De.get("WEBGL_multi_draw"))$e.renderMultiDraw(I._multiDrawStarts,I._multiDrawCounts,I._multiDrawCount);else{const Te=I._multiDrawStarts,tt=I._multiDrawCounts,ke=I._multiDrawCount,yt=ue?y.get(ue).bytesPerElement:1,Un=ge.get(H).currentProgram.getUniforms();for(let Tt=0;Tt{function Q(){if(H.forEach(function(oe){ge.get(oe).currentProgram.isReady()&&H.delete(oe)}),H.size===0){I(v);return}setTimeout(Q,10)}De.get("KHR_parallel_shader_compile")!==null?Q():setTimeout(Q,10)})};let Xe=null;function $t(v){Xe&&Xe(v)}function kt(){_n.stop()}function $s(){_n.start()}const _n=new Co;_n.setAnimationLoop($t),typeof self<"u"&&_n.setContext(self),this.setAnimationLoop=function(v){Xe=v,te.setAnimationLoop(v),v===null?_n.stop():_n.start()},te.addEventListener("sessionstart",kt),te.addEventListener("sessionend",$s),this.render=function(v,L){if(L!==void 0&&L.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(D===!0)return;if(v.matrixWorldAutoUpdate===!0&&v.updateMatrixWorld(),L.parent===null&&L.matrixWorldAutoUpdate===!0&&L.updateMatrixWorld(),te.enabled===!0&&te.isPresenting===!0&&(te.cameraAutoUpdate===!0&&te.updateCamera(L),L=te.getCamera()),v.isScene===!0&&v.onBeforeRender(E,v,L,U),u=Me.get(v,A.length),u.init(L),A.push(u),j.multiplyMatrices(L.projectionMatrix,L.matrixWorldInverse),Je.setFromProjectionMatrix(j,Wt,L.reversedDepth),Y=this.localClippingEnabled,We=ne.init(this.clippingPlanes,Y),p=k.get(v,b.length),p.init(),b.push(p),te.enabled===!0&&te.isPresenting===!0){const Q=E.xr.getDepthSensingMesh();Q!==null&&lr(Q,L,-1/0,E.sortObjects)}lr(v,L,0,E.sortObjects),p.finish(),E.sortObjects===!0&&p.sort(se,ce),ze=te.enabled===!1||te.isPresenting===!1||te.hasDepthSensing()===!1,ze&&ve.addToRenderList(p,v),this.info.render.frame++,We===!0&&ne.beginShadows();const B=u.state.shadowsArray;_e.render(B,v,L),We===!0&&ne.endShadows(),this.info.autoReset===!0&&this.info.reset();const H=p.opaque,I=p.transmissive;if(u.setupLights(),L.isArrayCamera){const Q=L.cameras;if(I.length>0)for(let oe=0,fe=Q.length;oe0&&Zs(H,I,v,L),ze&&ve.render(v),Ks(p,v,L);U!==null&&w===0&&(Ue.updateMultisampleRenderTarget(U),Ue.updateRenderTargetMipmap(U)),v.isScene===!0&&v.onAfterRender(E,v,L),ae.resetDefaultState(),S=-1,M=null,A.pop(),A.length>0?(u=A[A.length-1],We===!0&&ne.setGlobalState(E.clippingPlanes,u.state.camera)):u=null,b.pop(),b.length>0?p=b[b.length-1]:p=null};function lr(v,L,B,H){if(v.visible===!1)return;if(v.layers.test(L.layers)){if(v.isGroup)B=v.renderOrder;else if(v.isLOD)v.autoUpdate===!0&&v.update(L);else if(v.isLight)u.pushLight(v),v.castShadow&&u.pushShadow(v);else if(v.isSprite){if(!v.frustumCulled||Je.intersectsSprite(v)){H&&Ce.setFromMatrixPosition(v.matrixWorld).applyMatrix4(j);const oe=N.update(v),fe=v.material;fe.visible&&p.push(v,oe,fe,B,Ce.z,null)}}else if((v.isMesh||v.isLine||v.isPoints)&&(!v.frustumCulled||Je.intersectsObject(v))){const oe=N.update(v),fe=v.material;if(H&&(v.boundingSphere!==void 0?(v.boundingSphere===null&&v.computeBoundingSphere(),Ce.copy(v.boundingSphere.center)):(oe.boundingSphere===null&&oe.computeBoundingSphere(),Ce.copy(oe.boundingSphere.center)),Ce.applyMatrix4(v.matrixWorld).applyMatrix4(j)),Array.isArray(fe)){const ue=oe.groups;for(let Ae=0,Re=ue.length;Ae0&&Ci(I,L,B),Q.length>0&&Ci(Q,L,B),oe.length>0&&Ci(oe,L,B),me.buffers.depth.setTest(!0),me.buffers.depth.setMask(!0),me.buffers.color.setMask(!0),me.setPolygonOffset(!1)}function Zs(v,L,B,H){if((B.isScene===!0?B.overrideMaterial:null)!==null)return;u.state.transmissionRenderTarget[H.id]===void 0&&(u.state.transmissionRenderTarget[H.id]=new In(1,1,{generateMipmaps:!0,type:De.has("EXT_color_buffer_half_float")||De.has("EXT_color_buffer_float")?yi:qt,minFilter:Dn,samples:4,stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Ve.workingColorSpace}));const Q=u.state.transmissionRenderTarget[H.id],oe=H.viewport||C;Q.setSize(oe.z*E.transmissionResolutionScale,oe.w*E.transmissionResolutionScale);const fe=E.getRenderTarget(),ue=E.getActiveCubeFace(),Ae=E.getActiveMipmapLevel();E.setRenderTarget(Q),E.getClearColor(q),W=E.getClearAlpha(),W<1&&E.setClearColor(16777215,.5),E.clear(),ze&&ve.render(B);const Re=E.toneMapping;E.toneMapping=pn;const ye=H.viewport;if(H.viewport!==void 0&&(H.viewport=void 0),u.setupLightsView(H),We===!0&&ne.setGlobalState(E.clippingPlanes,H),Ci(v,B,H),Ue.updateMultisampleRenderTarget(Q),Ue.updateRenderTargetMipmap(Q),De.has("WEBGL_multisampled_render_to_texture")===!1){let Be=!1;for(let qe=0,it=L.length;qe0),ye=!!B.morphAttributes.position,Be=!!B.morphAttributes.normal,qe=!!B.morphAttributes.color;let it=pn;H.toneMapped&&(U===null||U.isXRRenderTarget===!0)&&(it=E.toneMapping);const je=B.morphAttributes.position||B.morphAttributes.normal||B.morphAttributes.color,$e=je!==void 0?je.length:0,Te=ge.get(H),tt=u.state.lights;if(We===!0&&(Y===!0||v!==M)){const gt=v===M&&H.id===S;ne.setState(H,v,gt)}let ke=!1;H.version===Te.__version?(Te.needsLights&&Te.lightsStateVersion!==tt.state.version||Te.outputColorSpace!==fe||I.isBatchedMesh&&Te.batching===!1||!I.isBatchedMesh&&Te.batching===!0||I.isBatchedMesh&&Te.batchingColor===!0&&I.colorTexture===null||I.isBatchedMesh&&Te.batchingColor===!1&&I.colorTexture!==null||I.isInstancedMesh&&Te.instancing===!1||!I.isInstancedMesh&&Te.instancing===!0||I.isSkinnedMesh&&Te.skinning===!1||!I.isSkinnedMesh&&Te.skinning===!0||I.isInstancedMesh&&Te.instancingColor===!0&&I.instanceColor===null||I.isInstancedMesh&&Te.instancingColor===!1&&I.instanceColor!==null||I.isInstancedMesh&&Te.instancingMorph===!0&&I.morphTexture===null||I.isInstancedMesh&&Te.instancingMorph===!1&&I.morphTexture!==null||Te.envMap!==ue||H.fog===!0&&Te.fog!==Q||Te.numClippingPlanes!==void 0&&(Te.numClippingPlanes!==ne.numPlanes||Te.numIntersection!==ne.numIntersection)||Te.vertexAlphas!==Ae||Te.vertexTangents!==Re||Te.morphTargets!==ye||Te.morphNormals!==Be||Te.morphColors!==qe||Te.toneMapping!==it||Te.morphTargetsCount!==$e)&&(ke=!0):(ke=!0,Te.__version=H.version);let yt=Te.currentProgram;ke===!0&&(yt=Pi(H,L,I));let Un=!1,Tt=!1,li=!1;const nt=yt.getUniforms(),Ct=Te.uniforms;if(me.useProgram(yt.program)&&(Un=!0,Tt=!0,li=!0),H.id!==S&&(S=H.id,Tt=!0),Un||M!==v){me.buffers.depth.getReversed()&&v.reversedDepth!==!0&&(v._reversedDepth=!0,v.updateProjectionMatrix()),nt.setValue(T,"projectionMatrix",v.projectionMatrix),nt.setValue(T,"viewMatrix",v.matrixWorldInverse);const Mt=nt.map.cameraPosition;Mt!==void 0&&Mt.setValue(T,de.setFromMatrixPosition(v.matrixWorld)),we.logarithmicDepthBuffer&&nt.setValue(T,"logDepthBufFC",2/(Math.log(v.far+1)/Math.LN2)),(H.isMeshPhongMaterial||H.isMeshToonMaterial||H.isMeshLambertMaterial||H.isMeshBasicMaterial||H.isMeshStandardMaterial||H.isShaderMaterial)&&nt.setValue(T,"isOrthographic",v.isOrthographicCamera===!0),M!==v&&(M=v,Tt=!0,li=!0)}if(I.isSkinnedMesh){nt.setOptional(T,I,"bindMatrix"),nt.setOptional(T,I,"bindMatrixInverse");const gt=I.skeleton;gt&&(gt.boneTexture===null&>.computeBoneTexture(),nt.setValue(T,"boneTexture",gt.boneTexture,Ue))}I.isBatchedMesh&&(nt.setOptional(T,I,"batchingTexture"),nt.setValue(T,"batchingTexture",I._matricesTexture,Ue),nt.setOptional(T,I,"batchingIdTexture"),nt.setValue(T,"batchingIdTexture",I._indirectTexture,Ue),nt.setOptional(T,I,"batchingColorTexture"),I._colorsTexture!==null&&nt.setValue(T,"batchingColorTexture",I._colorsTexture,Ue));const Pt=B.morphAttributes;if((Pt.position!==void 0||Pt.normal!==void 0||Pt.color!==void 0)&&ee.update(I,B,yt),(Tt||Te.receiveShadow!==I.receiveShadow)&&(Te.receiveShadow=I.receiveShadow,nt.setValue(T,"receiveShadow",I.receiveShadow)),H.isMeshGouraudMaterial&&H.envMap!==null&&(Ct.envMap.value=ue,Ct.flipEnvMap.value=ue.isCubeTexture&&ue.isRenderTargetTexture===!1?-1:1),H.isMeshStandardMaterial&&H.envMap===null&&L.environment!==null&&(Ct.envMapIntensity.value=L.environmentIntensity),Tt&&(nt.setValue(T,"toneMappingExposure",E.toneMappingExposure),Te.needsLights&&Fo(Ct,li),Q&&H.fog===!0&&K.refreshFogUniforms(Ct,Q),K.refreshMaterialUniforms(Ct,H,G,Z,u.state.transmissionRenderTarget[v.id]),ir.upload(T,Js(Te),Ct,Ue)),H.isShaderMaterial&&H.uniformsNeedUpdate===!0&&(ir.upload(T,Js(Te),Ct,Ue),H.uniformsNeedUpdate=!1),H.isSpriteMaterial&&nt.setValue(T,"center",I.center),nt.setValue(T,"modelViewMatrix",I.modelViewMatrix),nt.setValue(T,"normalMatrix",I.normalMatrix),nt.setValue(T,"modelMatrix",I.matrixWorld),H.isShaderMaterial||H.isRawShaderMaterial){const gt=H.uniformsGroups;for(let Mt=0,cr=gt.length;Mt0&&Ue.useMultisampledRTT(v)===!1?I=ge.get(v).__webglMultisampledFramebuffer:Array.isArray(Re)?I=Re[B]:I=Re,C.copy(v.viewport),O.copy(v.scissor),z=v.scissorTest}else C.copy(Ee).multiplyScalar(G).floor(),O.copy(Fe).multiplyScalar(G).floor(),z=Ke;if(B!==0&&(I=Bo),me.bindFramebuffer(T.FRAMEBUFFER,I)&&H&&me.drawBuffers(v,I),me.viewport(C),me.scissor(O),me.setScissorTest(z),Q){const ue=ge.get(v.texture);T.framebufferTexture2D(T.FRAMEBUFFER,T.COLOR_ATTACHMENT0,T.TEXTURE_CUBE_MAP_POSITIVE_X+L,ue.__webglTexture,B)}else if(oe){const ue=L;for(let Ae=0;Ae=0&&L<=v.width-H&&B>=0&&B<=v.height-I&&(v.textures.length>1&&T.readBuffer(T.COLOR_ATTACHMENT0+fe),T.readPixels(L,B,H,I,xe.convert(Re),xe.convert(ye),Q))}finally{const Ae=U!==null?ge.get(U).__webglFramebuffer:null;me.bindFramebuffer(T.FRAMEBUFFER,Ae)}}},this.readRenderTargetPixelsAsync=async function(v,L,B,H,I,Q,oe,fe=0){if(!(v&&v.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let ue=ge.get(v).__webglFramebuffer;if(v.isWebGLCubeRenderTarget&&oe!==void 0&&(ue=ue[oe]),ue)if(L>=0&&L<=v.width-H&&B>=0&&B<=v.height-I){me.bindFramebuffer(T.FRAMEBUFFER,ue);const Ae=v.textures[fe],Re=Ae.format,ye=Ae.type;if(!we.textureFormatReadable(Re))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!we.textureTypeReadable(ye))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const Be=T.createBuffer();T.bindBuffer(T.PIXEL_PACK_BUFFER,Be),T.bufferData(T.PIXEL_PACK_BUFFER,Q.byteLength,T.STREAM_READ),v.textures.length>1&&T.readBuffer(T.COLOR_ATTACHMENT0+fe),T.readPixels(L,B,H,I,xe.convert(Re),xe.convert(ye),0);const qe=U!==null?ge.get(U).__webglFramebuffer:null;me.bindFramebuffer(T.FRAMEBUFFER,qe);const it=T.fenceSync(T.SYNC_GPU_COMMANDS_COMPLETE,0);return T.flush(),await Pl(T,it,4),T.bindBuffer(T.PIXEL_PACK_BUFFER,Be),T.getBufferSubData(T.PIXEL_PACK_BUFFER,0,Q),T.deleteBuffer(Be),T.deleteSync(it),Q}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(v,L=null,B=0){const H=Math.pow(2,-B),I=Math.floor(v.image.width*H),Q=Math.floor(v.image.height*H),oe=L!==null?L.x:0,fe=L!==null?L.y:0;Ue.setTexture2D(v,0),T.copyTexSubImage2D(T.TEXTURE_2D,B,0,0,oe,fe,I,Q),me.unbindTexture()};const Ho=T.createFramebuffer(),zo=T.createFramebuffer();this.copyTextureToTexture=function(v,L,B=null,H=null,I=0,Q=null){Q===null&&(I!==0?(Ei("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),Q=I,I=0):Q=0);let oe,fe,ue,Ae,Re,ye,Be,qe,it;const je=v.isCompressedTexture?v.mipmaps[Q]:v.image;if(B!==null)oe=B.max.x-B.min.x,fe=B.max.y-B.min.y,ue=B.isBox3?B.max.z-B.min.z:1,Ae=B.min.x,Re=B.min.y,ye=B.isBox3?B.min.z:0;else{const Pt=Math.pow(2,-I);oe=Math.floor(je.width*Pt),fe=Math.floor(je.height*Pt),v.isDataArrayTexture?ue=je.depth:v.isData3DTexture?ue=Math.floor(je.depth*Pt):ue=1,Ae=0,Re=0,ye=0}H!==null?(Be=H.x,qe=H.y,it=H.z):(Be=0,qe=0,it=0);const $e=xe.convert(L.format),Te=xe.convert(L.type);let tt;L.isData3DTexture?(Ue.setTexture3D(L,0),tt=T.TEXTURE_3D):L.isDataArrayTexture||L.isCompressedArrayTexture?(Ue.setTexture2DArray(L,0),tt=T.TEXTURE_2D_ARRAY):(Ue.setTexture2D(L,0),tt=T.TEXTURE_2D),T.pixelStorei(T.UNPACK_FLIP_Y_WEBGL,L.flipY),T.pixelStorei(T.UNPACK_PREMULTIPLY_ALPHA_WEBGL,L.premultiplyAlpha),T.pixelStorei(T.UNPACK_ALIGNMENT,L.unpackAlignment);const ke=T.getParameter(T.UNPACK_ROW_LENGTH),yt=T.getParameter(T.UNPACK_IMAGE_HEIGHT),Un=T.getParameter(T.UNPACK_SKIP_PIXELS),Tt=T.getParameter(T.UNPACK_SKIP_ROWS),li=T.getParameter(T.UNPACK_SKIP_IMAGES);T.pixelStorei(T.UNPACK_ROW_LENGTH,je.width),T.pixelStorei(T.UNPACK_IMAGE_HEIGHT,je.height),T.pixelStorei(T.UNPACK_SKIP_PIXELS,Ae),T.pixelStorei(T.UNPACK_SKIP_ROWS,Re),T.pixelStorei(T.UNPACK_SKIP_IMAGES,ye);const nt=v.isDataArrayTexture||v.isData3DTexture,Ct=L.isDataArrayTexture||L.isData3DTexture;if(v.isDepthTexture){const Pt=ge.get(v),gt=ge.get(L),Mt=ge.get(Pt.__renderTarget),cr=ge.get(gt.__renderTarget);me.bindFramebuffer(T.READ_FRAMEBUFFER,Mt.__webglFramebuffer),me.bindFramebuffer(T.DRAW_FRAMEBUFFER,cr.__webglFramebuffer);for(let vn=0;vn(i[i.None=0]="None",i[i.Left=1]="Left",i[i.Right=2]="Right",i[i.Across=3]="Across",i))(mi||{}),gi=(i=>(i[i.Clubs=0]="Clubs",i[i.Diamonds=1]="Diamonds",i[i.Hearts=2]="Hearts",i[i.Spades=3]="Spades",i))(gi||{});class Uo{static atlas=null;static async load(){if(this.atlas)return this.atlas;const e=await fetch("/card_atlas.json");return this.atlas=await e.json(),this.atlas}static getCardKey(e,t){let n;if(typeof t=="string")n=t.toLowerCase();else switch(t){case gi.Clubs:n="clubs";break;case gi.Diamonds:n="diamonds";break;case gi.Hearts:n="hearts";break;case gi.Spades:n="spades";break;default:n="hearts";break}let r;switch(e){case 1:r="A";break;case 11:r="J";break;case 12:r="Q";break;case 13:r="K";break;default:r=e.toString();break}return`${n}_${r}`}static getCardFrame(e,t){if(!this.atlas)return console.error("Card atlas not loaded yet. Call CardAtlasLoader.load() first."),null;const n=this.getCardKey(e,t),r=this.atlas.frames[n];return r||console.error(`Card frame not found for key: ${n}, rank: ${e}, suit: ${t}`),r||null}static calculateUVs(e,t){const n=this.getCardFrame(e,t);if(!n||!this.atlas)return null;const r=this.atlas.size.w,s=this.atlas.size.h,a=n.x/r,o=(n.x+n.w)/r,c=1-(n.y+n.h)/s,l=1-n.y/s;return{uMin:a,uMax:o,vMin:c,vMax:l}}}class tn{mesh;card;cardGeometry;cardMaterial;isHovered=!1;isSelected=!1;static cardTexture=null;static textureLoader=new wo;constructor(e,t){this.card=e,this.mesh=new Zn,this.mesh.position.copy(t),this.cardGeometry=new ai(1.2,1.7),tn.cardTexture||(tn.cardTexture=tn.textureLoader.load("/cards.png"),tn.cardTexture.minFilter=Ut,tn.cardTexture.magFilter=Ut);const n=this.calculateUVs(),r=this.cardGeometry.attributes.uv,s=r.array;s[0]=n.uMin,s[1]=n.vMax,s[2]=n.uMax,s[3]=n.vMax,s[4]=n.uMin,s[5]=n.vMin,s[6]=n.uMax,s[7]=n.vMin,r.needsUpdate=!0,this.cardMaterial=new nr({map:tn.cardTexture,side:Bt,transparent:!1});const a=new wt(this.cardGeometry,this.cardMaterial);this.mesh.add(a),this.mesh.userData={card:this}}calculateUVs(){const e=Uo.calculateUVs(this.card.rank,this.card.suit);return e||(console.warn(`Could not find UV coordinates for card: rank=${this.card.rank}, suit=${this.card.suit}`),{uMin:0,uMax:1,vMin:0,vMax:1})}setHovered(e){this.isHovered!==e&&(this.isHovered=e,e&&!this.isSelected?(this.mesh.position.y+=.2,this.cardMaterial.emissive=new Oe(4473924)):this.isSelected||(this.mesh.position.y-=.2,this.cardMaterial.emissive=new Oe(0)))}setSelected(e){this.isSelected=e,e?(this.mesh.position.y=.4,this.cardMaterial.emissive=new Oe(8947848)):(this.mesh.position.y=.1,this.cardMaterial.emissive=new Oe(0))}animateToPosition(e,t=500){return new Promise(n=>{const r=this.mesh.position.clone(),s=Date.now(),a=()=>{const o=Date.now()-s,c=Math.min(o/t,1),l=c<.5?2*c*c:1-Math.pow(-2*c+2,2)/2;this.mesh.position.lerpVectors(r,e,l),c<1?requestAnimationFrame(a):n()};a()})}dispose(){this.cardGeometry.dispose(),this.cardMaterial.dispose()}}class vt{scene;camera;renderer;raycaster;mouse;playerCards=[];currentTrickCards=[];hoveredCard=null;selectedCards=[];opponentCards={};static bgTexture=null;static textureLoader=new wo;isAtlasLoaded=!1;onCardClick;constructor(e){this.scene=new tc,this.scene.background=new Oe(1722154),this.camera=new It(60,window.innerWidth/window.innerHeight,.1,1e3),this.camera.position.set(0,8,10),this.camera.lookAt(0,0,-2),this.renderer=new ep({antialias:!0}),this.renderer.setSize(window.innerWidth,window.innerHeight),this.renderer.shadowMap.enabled=!0,e.appendChild(this.renderer.domElement),this.raycaster=new gc,this.mouse=new Ge,this.setupLights(),this.createTable(),this.loadCardAtlas(),window.addEventListener("resize",this.onWindowResize.bind(this)),this.renderer.domElement.addEventListener("mousemove",this.onMouseMove.bind(this)),this.renderer.domElement.addEventListener("click",this.onClick.bind(this)),this.animate()}async loadCardAtlas(){try{await Uo.load(),this.isAtlasLoaded=!0,console.log("Card atlas loaded successfully")}catch(e){console.error("Failed to load card atlas:",e)}}setupLights(){const e=new pc(16777215,.6);this.scene.add(e);const t=new fc(16777215,.8);t.position.set(5,10,5),t.castShadow=!0,this.scene.add(t);const n=new uc(16777215,4473924,.4);this.scene.add(n)}createTable(){vt.bgTexture||(vt.bgTexture=vt.textureLoader.load("/bg.png"),vt.bgTexture.wrapS=Cn,vt.bgTexture.wrapT=Cn,vt.bgTexture.repeat.set(2,2));const e=new Vs(8,8,.2,32),t=new nr({map:vt.bgTexture,roughness:.8,metalness:.1}),n=new wt(e,t);n.position.y=-.5,n.receiveShadow=!0,this.scene.add(n);const r=new Ws(8,.15,16,32),s=new nr({color:9127187}),a=new wt(r,s);a.rotation.x=Math.PI/2,a.position.y=-.4,this.scene.add(a)}addPlayerCards(e){this.clearPlayerCards();const t=[...e].sort((o,c)=>{const l=f=>{if(typeof f=="string")switch(f){case"Clubs":return 0;case"Diamonds":return 1;case"Hearts":return 2;case"Spades":return 3;default:return 0}return f},h=l(o.suit),d=l(c.suit);return h!==d?h-d:o.rank-c.rank}),n=t.length,r=1.3,s=5,a=.1;t.forEach((o,c)=>{const h=-(n-1)*r/2+c*r,d=new F(h,a,s),f=new tn(o,d);f.mesh.rotation.x=-Math.PI/2,f.mesh.rotation.z=0,f.mesh.renderOrder=c,this.playerCards.push(f),this.scene.add(f.mesh)})}updateOpponentCards(e,t,n){this.opponentCards[e]&&(this.scene.remove(this.opponentCards[e]),this.opponentCards[e].clear());const r=new Zn;this.opponentCards[e]=r;const a=[{x:-7,z:0,baseRotation:Math.PI/2},{x:0,z:-7,baseRotation:Math.PI},{x:7,z:0,baseRotation:-Math.PI/2}][n%3];vt.bgTexture||(vt.bgTexture=vt.textureLoader.load("/bg.png"),vt.bgTexture.wrapS=Cn,vt.bgTexture.wrapT=Cn);const o=t,c=Math.PI/4,l=5;for(let h=0;h1?-c/2+h/(o-1)*c:0,x=l*Math.sin(_),p=-l*Math.cos(_)+l;a.x!==0?(m.position.set(a.x+p*.3,.5,x),m.rotation.y=a.baseRotation+_):(m.position.set(x,.5,a.z-p*.3),m.rotation.y=a.baseRotation+_),m.rotation.x=-Math.PI/15,m.renderOrder=h,r.add(m)}this.scene.add(r)}addTrickCard(e,t){const r=[new F(0,0,2),new F(-2,0,0),new F(0,0,-2),new F(2,0,0)][t%4],s=new tn(e,r);this.currentTrickCards.push(s),this.scene.add(s.mesh)}clearTrick(){this.currentTrickCards.forEach(e=>{this.scene.remove(e.mesh),e.dispose()}),this.currentTrickCards=[]}clearPlayerCards(){this.playerCards.forEach(e=>{this.scene.remove(e.mesh),e.dispose()}),this.playerCards=[],this.selectedCards=[]}clearOpponentCards(){Object.keys(this.opponentCards).forEach(e=>{this.scene.remove(this.opponentCards[e]),this.opponentCards[e].clear()}),this.opponentCards={}}removePlayerCard(e){const t=this.playerCards.findIndex(n=>n.card.rank===e.rank&&n.card.suit===e.suit);if(t!==-1){const n=this.playerCards[t];this.scene.remove(n.mesh),n.dispose(),this.playerCards.splice(t,1),this.rearrangePlayerCards()}}rearrangePlayerCards(){const e=this.playerCards.length,t=1.3,n=5;this.playerCards.forEach((r,s)=>{const o=-(e-1)*t/2+s*t,c=new F(o,r.mesh.position.y,n);r.animateToPosition(c,300),setTimeout(()=>{r.mesh.rotation.x=-Math.PI/2,r.mesh.rotation.z=0,r.mesh.renderOrder=s},150)})}getSelectedCards(){return this.selectedCards}clearSelection(){this.selectedCards.forEach(e=>e.setSelected(!1)),this.selectedCards=[]}onMouseMove(e){this.mouse.x=e.clientX/window.innerWidth*2-1,this.mouse.y=-(e.clientY/window.innerHeight)*2+1,this.raycaster.setFromCamera(this.mouse,this.camera);const t=this.playerCards.map(r=>r.mesh),n=this.raycaster.intersectObjects(t,!0);if(n.length>0){const s=n[0].object.parent?.userData.card;s&&s!==this.hoveredCard&&(this.hoveredCard&&this.hoveredCard.setHovered(!1),this.hoveredCard=s,this.hoveredCard.setHovered(!0))}else this.hoveredCard&&(this.hoveredCard.setHovered(!1),this.hoveredCard=null)}onClick(e){this.mouse.x=e.clientX/window.innerWidth*2-1,this.mouse.y=-(e.clientY/window.innerHeight)*2+1,this.raycaster.setFromCamera(this.mouse,this.camera);const t=this.playerCards.map(r=>r.mesh),n=this.raycaster.intersectObjects(t,!0);if(n.length>0){const s=n[0].object.parent?.userData.card;s&&(this.handleCardSelection(s),this.onCardClick&&this.onCardClick(s))}}handleCardSelection(e){const t=this.selectedCards.indexOf(e);t!==-1?(this.selectedCards.splice(t,1),e.setSelected(!1)):this.selectedCards.length<3&&(this.selectedCards.push(e),e.setSelected(!0))}onWindowResize(){this.camera.aspect=window.innerWidth/window.innerHeight,this.camera.updateProjectionMatrix(),this.renderer.setSize(window.innerWidth,window.innerHeight)}animate(){requestAnimationFrame(this.animate.bind(this)),this.renderer.render(this.scene,this.camera)}dispose(){window.removeEventListener("resize",this.onWindowResize.bind(this)),this.renderer.domElement.removeEventListener("mousemove",this.onMouseMove.bind(this)),this.renderer.domElement.removeEventListener("click",this.onClick.bind(this)),this.renderer.dispose()}}class tp{connectionPanel;gameInfo;messageDisplay;statusElement;roundNumberEl;playerScoreEl;totalScoreEl;passDirectionEl;turnStatusEl;connectionStatusEl;constructor(){this.connectionPanel=document.getElementById("connection-panel"),this.gameInfo=document.getElementById("game-info"),this.messageDisplay=document.getElementById("message-display"),this.statusElement=document.getElementById("status"),this.roundNumberEl=document.getElementById("round-number"),this.playerScoreEl=document.getElementById("player-score"),this.totalScoreEl=document.getElementById("total-score"),this.passDirectionEl=document.getElementById("pass-direction"),this.turnStatusEl=document.getElementById("turn-status"),this.connectionStatusEl=document.getElementById("connection-status")}showConnectionPanel(){this.connectionPanel.classList.remove("hidden"),this.gameInfo.classList.add("hidden")}hideConnectionPanel(){this.connectionPanel.classList.add("hidden"),this.gameInfo.classList.remove("hidden")}setConnectionStatus(e){this.connectionStatusEl.textContent=e}updateGameInfo(e){e.roundNumber!==void 0&&(this.roundNumberEl.textContent=e.roundNumber.toString()),e.playerScore!==void 0&&(this.playerScoreEl.textContent=e.playerScore.toString()),e.totalScore!==void 0&&(this.totalScoreEl.textContent=e.totalScore.toString()),e.passDirection!==void 0&&(this.passDirectionEl.textContent=`Pass: ${e.passDirection}`),e.isMyTurn!==void 0&&(this.turnStatusEl.textContent=e.isMyTurn?"Your turn!":"Waiting...",this.turnStatusEl.style.color=e.isMyTurn?"#4caf50":"#666")}setStatus(e){this.statusElement.textContent=e}showMessage(e,t=3e3){this.messageDisplay.textContent=e,this.messageDisplay.classList.add("show"),setTimeout(()=>{this.messageDisplay.classList.remove("show")},t)}getConnectionInputs(){return{playerName:document.getElementById("player-name").value,gameId:document.getElementById("game-id").value}}setConnectButtonEnabled(e){const t=document.getElementById("connect-btn");t.disabled=!e}}class np{constructor(e,t){this.actionSocket=e,this.notificationSocket=t,this.gameStartedHandlers=[],this.passingPhaseStartedHandlers=[],this.allPlayersPassedHandlers=[],this.playerPassedCardsHandlers=[],this.itsYourTurnHandlers=[],this.itsPlayersTurnHandlers=[],this.playerPlayedCardHandlers=[],this.trickCompletedHandlers=[],this.roundEndedHandlers=[],this.gameEndedHandlers=[],this.heartsWereBrokenHandlers=[],this.setupNotificationHandlers()}setupNotificationHandlers(){this.notificationSocket.onmessage=e=>{const t=JSON.parse(e.data);this.handleNotification(t)}}handleNotification(e){switch(e.type){case"Hearts.GameStartedNotification":this.gameStartedHandlers.forEach(t=>t(e));break;case"Hearts.PassingPhaseStartedNotification":this.passingPhaseStartedHandlers.forEach(t=>t(e));break;case"Hearts.AllPlayersPassedNotification":this.allPlayersPassedHandlers.forEach(t=>t(e));break;case"Hearts.PlayerPassedCardsNotification":this.playerPassedCardsHandlers.forEach(t=>t(e));break;case"Hearts.ItsYourTurnNotification":this.itsYourTurnHandlers.forEach(t=>t(e));break;case"Hearts.ItsPlayersTurnNotification":this.itsPlayersTurnHandlers.forEach(t=>t(e));break;case"Hearts.PlayerPlayedCardNotification":this.playerPlayedCardHandlers.forEach(t=>t(e));break;case"Hearts.TrickCompletedNotification":this.trickCompletedHandlers.forEach(t=>t(e));break;case"Hearts.RoundEndedNotification":this.roundEndedHandlers.forEach(t=>t(e));break;case"Hearts.GameEndedNotification":this.gameEndedHandlers.forEach(t=>t(e));break;case"Hearts.HeartsAreBrokenNotification":this.heartsWereBrokenHandlers.forEach(t=>t(e));break}}onGameStarted(e){this.gameStartedHandlers.push(e)}offGameStarted(e){const t=this.gameStartedHandlers.indexOf(e);t>-1&&this.gameStartedHandlers.splice(t,1)}onPassingPhaseStarted(e){this.passingPhaseStartedHandlers.push(e)}offPassingPhaseStarted(e){const t=this.passingPhaseStartedHandlers.indexOf(e);t>-1&&this.passingPhaseStartedHandlers.splice(t,1)}onAllPlayersPassed(e){this.allPlayersPassedHandlers.push(e)}offAllPlayersPassed(e){const t=this.allPlayersPassedHandlers.indexOf(e);t>-1&&this.allPlayersPassedHandlers.splice(t,1)}onPlayerPassedCards(e){this.playerPassedCardsHandlers.push(e)}offPlayerPassedCards(e){const t=this.playerPassedCardsHandlers.indexOf(e);t>-1&&this.playerPassedCardsHandlers.splice(t,1)}onItsYourTurn(e){this.itsYourTurnHandlers.push(e)}offItsYourTurn(e){const t=this.itsYourTurnHandlers.indexOf(e);t>-1&&this.itsYourTurnHandlers.splice(t,1)}onItsPlayersTurn(e){this.itsPlayersTurnHandlers.push(e)}offItsPlayersTurn(e){const t=this.itsPlayersTurnHandlers.indexOf(e);t>-1&&this.itsPlayersTurnHandlers.splice(t,1)}onPlayerPlayedCard(e){this.playerPlayedCardHandlers.push(e)}offPlayerPlayedCard(e){const t=this.playerPlayedCardHandlers.indexOf(e);t>-1&&this.playerPlayedCardHandlers.splice(t,1)}onTrickCompleted(e){this.trickCompletedHandlers.push(e)}offTrickCompleted(e){const t=this.trickCompletedHandlers.indexOf(e);t>-1&&this.trickCompletedHandlers.splice(t,1)}onRoundEnded(e){this.roundEndedHandlers.push(e)}offRoundEnded(e){const t=this.roundEndedHandlers.indexOf(e);t>-1&&this.roundEndedHandlers.splice(t,1)}onGameEnded(e){this.gameEndedHandlers.push(e)}offGameEnded(e){const t=this.gameEndedHandlers.indexOf(e);t>-1&&this.gameEndedHandlers.splice(t,1)}onHeartsWereBroken(e){this.heartsWereBrokenHandlers.push(e)}offHeartsWereBroken(e){const t=this.heartsWereBrokenHandlers.indexOf(e);t>-1&&this.heartsWereBrokenHandlers.splice(t,1)}async passCards(e){return new Promise((t,n)=>{const r={...e,type:"Hearts.PassCardsRequest"},s=a=>{const o=JSON.parse(a.data);o.hasError?n(new Error(o.error||"Unknown error")):t(o),this.actionSocket.removeEventListener("message",s)};this.actionSocket.addEventListener("message",s),this.actionSocket.send(JSON.stringify(r))})}async playCard(e){return new Promise((t,n)=>{const r={...e,type:"Hearts.PlayCardRequest"},s=a=>{const o=JSON.parse(a.data);o.hasError?n(new Error(o.error||"Unknown error")):t(o),this.actionSocket.removeEventListener("message",s)};this.actionSocket.addEventListener("message",s),this.actionSocket.send(JSON.stringify(r))})}}class ip{client;scene;ui;playerId="";passingPhase=!1;myTurn=!1;constructor(e,t){this.scene=e,this.ui=t,this.scene.onCardClick=this.handleCardClick.bind(this)}async createGame(e,t){try{console.log("Creating new game...");const n=e.replace("ws://","http://").replace("wss://","https://");console.log("Authenticating with:",n+"/login");const r=await fetch(`${n}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t,password:"default-password"}),credentials:"include"});if(console.log("Login response status:",r.status),!r.ok){const o=await r.text();throw console.error("Login failed:",o),new Error(`Authentication failed: ${r.status} ${r.statusText}`)}await r.json(),console.log("Authenticated successfully"),console.log("Creating Hearts game...");const s=await fetch(`${n}/hearts/create`,{method:"POST",credentials:"include"});if(!s.ok){const o=await s.text();throw new Error(`Failed to create game: ${s.status} ${s.statusText} +${o}`)}const a=await s.json();return console.log("Game created:",a),a.id}catch(n){throw console.error("Error creating game:",n),n}}async connect(e,t,n,r){try{console.log("Starting connection process..."),this.ui.setConnectionStatus("Authenticating..."),this.ui.setConnectButtonEnabled(!1);const s=e.replace("ws://","http://").replace("wss://","https://");console.log("Authenticating with:",s+"/login");const a=await fetch(`${s}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:n,password:"default-password"}),credentials:"include"});if(console.log("Login response status:",a.status),!a.ok){const _=await a.text();throw console.error("Login failed:",_),new Error(`Authentication failed: ${a.status} ${a.statusText} +${_}`)}const o=await a.json();console.log("Authenticated successfully:",o);const c=o.accessToken;this.playerId=o.id,console.log("Using player ID from auth:",this.playerId),this.ui.setConnectionStatus("Authenticated. Connecting to game..."),console.log("Attempting to connect to game:",r);const l=`${e}/hearts/join/${encodeURIComponent(r)}`;console.log("Connecting action socket to:",l);const h=new WebSocket(l);await this.waitForSocketOpen(h),console.log("Action socket connected"),this.ui.setConnectionStatus("Action socket connected. Waiting for connection ID..."),console.log("Waiting for connection ID...");const d=await this.getConnectionId(h);console.log("Received connection ID:",d),this.ui.setConnectionStatus("Establishing notification socket...");const f=`${e}/hearts/join/${d}/finish`;console.log("Connecting notification socket to:",f);const m=new WebSocket(f);await this.waitForSocketOpen(m),console.log("Notification socket connected"),this.ui.setConnectionStatus("Connected!"),console.log("Setting up notification socket logging..."),m.addEventListener("message",_=>{console.log("📨 RAW notification received:",_.data)}),console.log("Creating Hearts client..."),this.client=new np(h,m),console.log("Hearts client created"),console.log("Setting up event handlers..."),this.setupEventHandlers(),console.log("Event handlers set up"),console.log("Hiding connection panel and showing game UI..."),this.ui.hideConnectionPanel(),this.ui.setStatus("Connected to game. Waiting for game to start..."),this.ui.showMessage("Connected to Hearts game!"),console.log("Connection complete. Waiting for game events...")}catch(s){console.error("Connection error:",s);const a=s instanceof Error?s.message:String(s);throw this.ui.setConnectionStatus(`Connection failed: ${a}`),this.ui.showMessage(`Connection failed: ${a}`,1e4),this.ui.setConnectButtonEnabled(!0),s}}getConnectionId(e){return new Promise((t,n)=>{const r=setTimeout(()=>{n(new Error("Timeout waiting for connection ID (10 seconds). The game may not exist or you may not have permission to join."))},1e4),s=a=>{console.log("Received message while waiting for connection ID:",a.data),clearTimeout(r);try{const o=JSON.parse(a.data);if(console.log("Parsed data:",o),o.ConnectionId||o.connectionId){const c=o.ConnectionId||o.connectionId;e.removeEventListener("message",s),console.log("Extracted connection ID:",c),t(c)}else if(o.ErrorMessage||o.errorMessage){const c=o.ErrorMessage||o.errorMessage;console.error("Server error:",c),n(new Error("Server error: "+c))}else console.error("Message does not contain ConnectionId:",o),n(new Error("No ConnectionId in response. Received: "+JSON.stringify(o)))}catch(o){console.error("Failed to parse message:",o,"Raw data:",a.data),n(new Error("Failed to parse connection ID response: "+a.data))}};e.addEventListener("message",s)})}waitForSocketOpen(e){return new Promise((t,n)=>{const r=setTimeout(()=>{n(new Error("Connection timeout - server not responding"))},1e4);e.onopen=()=>{clearTimeout(r),t()},e.onerror=s=>{clearTimeout(r),console.error("WebSocket error:",s),console.error("Socket URL:",e.url),console.error("Socket readyState:",e.readyState),n(new Error(`WebSocket connection failed. Make sure: +1. Server is running on localhost:13992 +2. Game ID exists on server +3. Check server logs for errors`))},e.onclose=s=>{s.wasClean||(clearTimeout(r),n(new Error(`Connection closed unexpectedly (code: ${s.code}, reason: ${s.reason||"none"})`)))}})}setupEventHandlers(){if(!this.client){console.error("Cannot setup event handlers: client is null");return}console.log("Registering GameStarted handler..."),this.client.onGameStarted(e=>{console.log("🎮 Game started event received!",e),this.ui.showMessage("Game started!"),this.ui.setStatus("Game in progress"),e.playerViewOfGame&&this.updateGameState(e.playerViewOfGame)}),console.log("Registering PassingPhaseStarted handler..."),this.client.onPassingPhaseStarted(e=>{console.log("🎴 Passing phase started event received!",e),this.passingPhase=!0;const t=this.getPassDirectionString(e.passDirection);this.ui.showMessage(`Pass 3 cards ${t}`),this.ui.setStatus(`Select 3 cards to pass ${t}`),this.ui.updateGameInfo({passDirection:t})}),this.client.onAllPlayersPassed(e=>{console.log("All players passed:",e),this.passingPhase=!1,this.scene.clearSelection(),e.receivedCards&&e.receivedCards.length>0&&this.ui.showMessage(`Received ${e.receivedCards.length} cards`),this.ui.setStatus("Cards passed. Waiting for round to start...")}),this.client.onPlayerPassedCards(e=>{console.log("Player passed cards:",e)}),console.log("Registering ItsYourTurn handler..."),this.client.onItsYourTurn(e=>{console.log("✋ Your turn event received!",e),this.myTurn=!0,this.ui.showMessage("Your turn!"),this.ui.setStatus("Your turn - select a card to play"),this.ui.updateGameInfo({isMyTurn:!0}),e.playerViewOfGame&&this.updateGameState(e.playerViewOfGame)}),this.client.onItsPlayersTurn(e=>{console.log("It's another player's turn:",e),console.log("My player ID:",this.playerId),console.log("Turn player ID:",e.playerId),e.playerId!==this.playerId?(this.myTurn=!1,this.ui.updateGameInfo({isMyTurn:!1}),this.ui.setStatus("Waiting for other players...")):console.log("Received ItsPlayersTurn for my own ID - this might be a server notification about me playing")}),this.client.onPlayerPlayedCard(e=>{console.log("Player played card:",e),this.scene.addTrickCard(e.card,1)}),this.client.onTrickCompleted(e=>{console.log("Trick completed:",e),this.ui.showMessage(`${e.winnerName||"Player"} won the trick! (+${e.points} points)`),setTimeout(()=>{this.scene.clearTrick()},2e3)}),this.client.onRoundEnded(e=>{console.log("Round ended:",e);let t="Round ended!";e.moonShooterName&&(t=`${e.moonShooterName} shot the moon!`),this.ui.showMessage(t,5e3),this.ui.setStatus("Round ended. Waiting for next round..."),e.scores&&console.log("Scores:",e.scores)}),this.client.onGameEnded(e=>{console.log("Game ended:",e),this.ui.showMessage(`Game Over! Winner: ${e.winnerName||"Unknown"}`,1e4),this.ui.setStatus("Game ended")}),this.client.onHeartsWereBroken(()=>{console.log("Hearts were broken"),this.ui.showMessage("Hearts have been broken!")})}updateGameState(e){console.log("Updating game state:",e),this.ui.updateGameInfo({roundNumber:e.roundNumber,playerScore:e.roundScore,totalScore:e.totalScore,isMyTurn:e.isMyTurn}),e.cards&&this.scene.addPlayerCards(e.cards),e.otherPlayers&&e.otherPlayers.forEach((t,n)=>{this.scene.updateOpponentCards(t.playerId,t.numberOfCards,n)}),e.currentTrick&&(this.scene.clearTrick(),e.currentTrick.forEach((t,n)=>{this.scene.addTrickCard(t.card,n)}))}getPassDirectionString(e){switch(e){case mi.Left:return"Left";case mi.Right:return"Right";case mi.Across:return"Across";case mi.None:return"None";default:return"Unknown"}}async handleCardClick(e){if(console.log("Card clicked:",e.card),console.log("Passing phase:",this.passingPhase),console.log("My turn:",this.myTurn),this.passingPhase){const t=this.scene.getSelectedCards();t.length===3&&(this.ui.setStatus("Passing cards..."),await this.passCards(t.map(n=>n.card)))}else this.myTurn?(this.ui.setStatus("Playing card..."),await this.playCard(e.card)):console.log("Not my turn or not in correct phase")}async passCards(e){if(this.client)try{const t=await this.client.passCards({playerId:this.playerId,cards:e});console.log("Pass cards response:",t),t.hasError?(this.ui.showMessage(`Error: ${t.error}`),this.scene.clearSelection()):(this.ui.showMessage("Cards passed!"),this.ui.setStatus("Waiting for other players to pass..."),e.forEach(n=>this.scene.removePlayerCard(n)),this.scene.clearSelection())}catch(t){console.error("Error passing cards:",t),this.ui.showMessage("Failed to pass cards"),this.scene.clearSelection()}}async playCard(e){if(this.client)try{console.log("Playing card:",e),console.log("Player ID:",this.playerId),console.log("My turn:",this.myTurn);const t=await this.client.playCard({playerId:this.playerId,card:e});console.log("Play card response:",t),t.hasError?this.ui.showMessage(`Error: ${t.error}`):(this.myTurn=!1,this.scene.removePlayerCard(e),this.scene.addTrickCard(e,0),this.ui.setStatus("Waiting for other players..."),this.updateGameState(t))}catch(t){console.error("Error playing card:",t),this.ui.showMessage("Failed to play card")}}}function Qa(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{const e=Math.random()*16|0;return(i==="x"?e:e&3|8).toString(16)})}function eo(){console.log("Initializing Hearts Web Client...");const i=document.getElementById("canvas-container");if(!i){console.error("Canvas container not found!");return}const e=new vt(i);console.log("3D scene initialized");const t=new tp;console.log("UI initialized");const n=new ip(e,t);console.log("Game controller initialized");const r=document.getElementById("create-game-btn"),s=document.getElementById("join-game-btn"),a=document.getElementById("join-section"),o=document.getElementById("created-game-section"),c=document.getElementById("connect-btn"),l=document.getElementById("created-game-id"),h=document.getElementById("copy-game-id-btn"),d=document.getElementById("connect-to-created-btn");let f="";s?.addEventListener("click",()=>{a&&(a.style.display="block"),o&&(o.style.display="none")}),r?.addEventListener("click",async()=>{const _=document.getElementById("player-name").value.trim();if(!_){t.setConnectionStatus("Please enter your name");return}try{t.setConnectionStatus("Creating game..."),r&&(r.disabled=!0);const p=await n.createGame("ws://localhost:13992",_);f=p,l&&(l.value=p),a&&(a.style.display="none"),o&&(o.style.display="block"),t.setConnectionStatus("Game created successfully!"),console.log("Game created with ID:",p)}catch(x){console.error("Failed to create game:",x),t.setConnectionStatus("Failed to create game: "+(x instanceof Error?x.message:String(x)))}finally{r&&(r.disabled=!1)}}),h?.addEventListener("click",()=>{l&&(l.select(),navigator.clipboard.writeText(l.value).then(()=>{const m=h.textContent;h.textContent="Copied!",setTimeout(()=>{h.textContent=m},2e3)}))}),d?.addEventListener("click",async()=>{const _=document.getElementById("player-name").value.trim();if(!_){t.setConnectionStatus("Please enter your name");return}const x=Qa(),p="ws://localhost:13992";console.log("Connection details:"),console.log("- Server URL:",p),console.log("- Player ID:",x),console.log("- Player Name:",_),console.log("- Game ID:",f);try{await n.connect(p,x,_,f)}catch(u){console.error("Failed to connect:",u)}}),c?.addEventListener("click",async()=>{const m=t.getConnectionInputs(),_=m.playerName.trim(),x=m.gameId.trim();if(!_||!x){t.setConnectionStatus("Please fill in all fields");return}const p=Qa(),u="ws://localhost:13992";console.log("Connection details:"),console.log("- Server URL:",u),console.log("- Player ID:",p),console.log("- Player Name:",_),console.log("- Game ID:",x);try{await n.connect(u,p,_,x)}catch(b){console.error("Failed to connect:",b)}}),console.log("Hearts Web Client ready!")}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",eo):eo(); diff --git a/web-clients/hearts/dist/bg.png b/web-clients/hearts/dist/bg.png new file mode 100644 index 00000000..eedd1ae3 Binary files /dev/null and b/web-clients/hearts/dist/bg.png differ diff --git a/web-clients/hearts/dist/card_atlas.json b/web-clients/hearts/dist/card_atlas.json new file mode 100644 index 00000000..638bbb9c --- /dev/null +++ b/web-clients/hearts/dist/card_atlas.json @@ -0,0 +1,322 @@ +{ + "image": "cards.png", + "size": { + "w": 1066, + "h": 944 + }, + "format": "array", + "frames": { + "hearts_A": { + "x": 0, + "y": 7, + "w": 105, + "h": 151 + }, + "hearts_2": { + "x": 105, + "y": 7, + "w": 110, + "h": 151 + }, + "hearts_3": { + "x": 215, + "y": 7, + "w": 106, + "h": 151 + }, + "hearts_4": { + "x": 321, + "y": 7, + "w": 103, + "h": 151 + }, + "hearts_5": { + "x": 424, + "y": 7, + "w": 109, + "h": 151 + }, + "hearts_6": { + "x": 0, + "y": 164, + "w": 105, + "h": 151 + }, + "hearts_7": { + "x": 105, + "y": 164, + "w": 110, + "h": 151 + }, + "hearts_8": { + "x": 215, + "y": 164, + "w": 106, + "h": 151 + }, + "hearts_9": { + "x": 321, + "y": 164, + "w": 103, + "h": 151 + }, + "hearts_10": { + "x": 424, + "y": 164, + "w": 109, + "h": 151 + }, + "hearts_J": { + "x": 0, + "y": 322, + "w": 105, + "h": 151 + }, + "hearts_Q": { + "x": 105, + "y": 322, + "w": 110, + "h": 151 + }, + "hearts_K": { + "x": 215, + "y": 322, + "w": 106, + "h": 151 + }, + "clubs_A": { + "x": 533, + "y": 7, + "w": 111, + "h": 151 + }, + "clubs_2": { + "x": 644, + "y": 7, + "w": 108, + "h": 151 + }, + "clubs_3": { + "x": 752, + "y": 7, + "w": 105, + "h": 151 + }, + "clubs_4": { + "x": 857, + "y": 7, + "w": 104, + "h": 151 + }, + "clubs_5": { + "x": 961, + "y": 7, + "w": 105, + "h": 151 + }, + "clubs_6": { + "x": 533, + "y": 164, + "w": 111, + "h": 151 + }, + "clubs_7": { + "x": 644, + "y": 164, + "w": 108, + "h": 151 + }, + "clubs_8": { + "x": 752, + "y": 164, + "w": 105, + "h": 151 + }, + "clubs_9": { + "x": 857, + "y": 164, + "w": 104, + "h": 151 + }, + "clubs_10": { + "x": 961, + "y": 164, + "w": 105, + "h": 151 + }, + "clubs_J": { + "x": 752, + "y": 322, + "w": 105, + "h": 151 + }, + "clubs_Q": { + "x": 857, + "y": 322, + "w": 104, + "h": 151 + }, + "clubs_K": { + "x": 961, + "y": 322, + "w": 105, + "h": 151 + }, + "diamonds_A": { + "x": 0, + "y": 479, + "w": 105, + "h": 151 + }, + "diamonds_2": { + "x": 105, + "y": 479, + "w": 110, + "h": 151 + }, + "diamonds_3": { + "x": 215, + "y": 479, + "w": 106, + "h": 151 + }, + "diamonds_4": { + "x": 321, + "y": 479, + "w": 103, + "h": 151 + }, + "diamonds_5": { + "x": 424, + "y": 479, + "w": 109, + "h": 151 + }, + "diamonds_6": { + "x": 0, + "y": 636, + "w": 105, + "h": 151 + }, + "diamonds_7": { + "x": 105, + "y": 636, + "w": 110, + "h": 151 + }, + "diamonds_8": { + "x": 215, + "y": 636, + "w": 106, + "h": 151 + }, + "diamonds_9": { + "x": 321, + "y": 636, + "w": 103, + "h": 151 + }, + "diamonds_10": { + "x": 424, + "y": 636, + "w": 109, + "h": 151 + }, + "diamonds_J": { + "x": 0, + "y": 794, + "w": 105, + "h": 150 + }, + "diamonds_Q": { + "x": 105, + "y": 794, + "w": 110, + "h": 150 + }, + "diamonds_K": { + "x": 215, + "y": 794, + "w": 106, + "h": 150 + }, + "spades_A": { + "x": 533, + "y": 479, + "w": 111, + "h": 151 + }, + "spades_2": { + "x": 644, + "y": 479, + "w": 108, + "h": 151 + }, + "spades_3": { + "x": 752, + "y": 479, + "w": 105, + "h": 151 + }, + "spades_4": { + "x": 857, + "y": 479, + "w": 104, + "h": 151 + }, + "spades_5": { + "x": 961, + "y": 479, + "w": 105, + "h": 151 + }, + "spades_6": { + "x": 533, + "y": 636, + "w": 111, + "h": 151 + }, + "spades_7": { + "x": 644, + "y": 636, + "w": 108, + "h": 151 + }, + "spades_8": { + "x": 752, + "y": 636, + "w": 105, + "h": 151 + }, + "spades_9": { + "x": 857, + "y": 636, + "w": 104, + "h": 151 + }, + "spades_10": { + "x": 961, + "y": 636, + "w": 105, + "h": 151 + }, + "spades_J": { + "x": 752, + "y": 794, + "w": 105, + "h": 150 + }, + "spades_Q": { + "x": 857, + "y": 794, + "w": 104, + "h": 150 + }, + "spades_K": { + "x": 961, + "y": 794, + "w": 105, + "h": 150 + } + } +} \ No newline at end of file diff --git a/web-clients/hearts/dist/cards.png b/web-clients/hearts/dist/cards.png new file mode 100644 index 00000000..4c7e9c1c Binary files /dev/null and b/web-clients/hearts/dist/cards.png differ diff --git a/web-clients/hearts/dist/index.html b/web-clients/hearts/dist/index.html new file mode 100644 index 00000000..fa95b66f --- /dev/null +++ b/web-clients/hearts/dist/index.html @@ -0,0 +1,199 @@ + + + + + + Hearts - Deckster + + + + +
+
+
+
+

Hearts Game

+ + +
+ + +
+ + + + + +

+
+ +
+
Waiting to connect...
+
+
+ + diff --git a/web-clients/hearts/index.html b/web-clients/hearts/index.html new file mode 100644 index 00000000..ad4f6a13 --- /dev/null +++ b/web-clients/hearts/index.html @@ -0,0 +1,290 @@ + + + + + + Hearts - Deckster + + + +
+
+
+
+

Hearts Game

+ + +
+ + +
+ + + + + +

+
+ +
+
Waiting to connect...
+ +
+
+ + + diff --git a/web-clients/hearts/package-lock.json b/web-clients/hearts/package-lock.json new file mode 100644 index 00000000..c456cd88 --- /dev/null +++ b/web-clients/hearts/package-lock.json @@ -0,0 +1,1160 @@ +{ + "name": "hearts", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "hearts", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "@types/three": "^0.180.0", + "three": "^0.180.0" + }, + "devDependencies": { + "@types/node": "^24.7.1", + "typescript": "^5.9.3", + "vite": "^7.1.9" + } + }, + "node_modules/@dimforge/rapier3d-compat": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@dimforge/rapier3d-compat/-/rapier3d-compat-0.12.0.tgz", + "integrity": "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==", + "license": "Apache-2.0" + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.10.tgz", + "integrity": "sha512-0NFWnA+7l41irNuaSVlLfgNT12caWJVLzp5eAVhZ0z1qpxbockccEt3s+149rE64VUI3Ml2zt8Nv5JVc4QXTsw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.10.tgz", + "integrity": "sha512-dQAxF1dW1C3zpeCDc5KqIYuZ1tgAdRXNoZP7vkBIRtKZPYe2xVr/d3SkirklCHudW1B45tGiUlz2pUWDfbDD4w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.10.tgz", + "integrity": "sha512-LSQa7eDahypv/VO6WKohZGPSJDq5OVOo3UoFR1E4t4Gj1W7zEQMUhI+lo81H+DtB+kP+tDgBp+M4oNCwp6kffg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.10.tgz", + "integrity": "sha512-MiC9CWdPrfhibcXwr39p9ha1x0lZJ9KaVfvzA0Wxwz9ETX4v5CHfF09bx935nHlhi+MxhA63dKRRQLiVgSUtEg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.10.tgz", + "integrity": "sha512-JC74bdXcQEpW9KkV326WpZZjLguSZ3DfS8wrrvPMHgQOIEIG/sPXEN/V8IssoJhbefLRcRqw6RQH2NnpdprtMA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.10.tgz", + "integrity": "sha512-tguWg1olF6DGqzws97pKZ8G2L7Ig1vjDmGTwcTuYHbuU6TTjJe5FXbgs5C1BBzHbJ2bo1m3WkQDbWO2PvamRcg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.10.tgz", + "integrity": "sha512-3ZioSQSg1HT2N05YxeJWYR+Libe3bREVSdWhEEgExWaDtyFbbXWb49QgPvFH8u03vUPX10JhJPcz7s9t9+boWg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.10.tgz", + "integrity": "sha512-LLgJfHJk014Aa4anGDbh8bmI5Lk+QidDmGzuC2D+vP7mv/GeSN+H39zOf7pN5N8p059FcOfs2bVlrRr4SK9WxA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.10.tgz", + "integrity": "sha512-oR31GtBTFYCqEBALI9r6WxoU/ZofZl962pouZRTEYECvNF/dtXKku8YXcJkhgK/beU+zedXfIzHijSRapJY3vg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.10.tgz", + "integrity": "sha512-5luJWN6YKBsawd5f9i4+c+geYiVEw20FVW5x0v1kEMWNq8UctFjDiMATBxLvmmHA4bf7F6hTRaJgtghFr9iziQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.10.tgz", + "integrity": "sha512-NrSCx2Kim3EnnWgS4Txn0QGt0Xipoumb6z6sUtl5bOEZIVKhzfyp/Lyw4C1DIYvzeW/5mWYPBFJU3a/8Yr75DQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.10.tgz", + "integrity": "sha512-xoSphrd4AZda8+rUDDfD9J6FUMjrkTz8itpTITM4/xgerAZZcFW7Dv+sun7333IfKxGG8gAq+3NbfEMJfiY+Eg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.10.tgz", + "integrity": "sha512-ab6eiuCwoMmYDyTnyptoKkVS3k8fy/1Uvq7Dj5czXI6DF2GqD2ToInBI0SHOp5/X1BdZ26RKc5+qjQNGRBelRA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.10.tgz", + "integrity": "sha512-NLinzzOgZQsGpsTkEbdJTCanwA5/wozN9dSgEl12haXJBzMTpssebuXR42bthOF3z7zXFWH1AmvWunUCkBE4EA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.10.tgz", + "integrity": "sha512-FE557XdZDrtX8NMIeA8LBJX3dC2M8VGXwfrQWU7LB5SLOajfJIxmSdyL/gU1m64Zs9CBKvm4UAuBp5aJ8OgnrA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.10.tgz", + "integrity": "sha512-3BBSbgzuB9ajLoVZk0mGu+EHlBwkusRmeNYdqmznmMc9zGASFjSsxgkNsqmXugpPk00gJ0JNKh/97nxmjctdew==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.10.tgz", + "integrity": "sha512-QSX81KhFoZGwenVyPoberggdW1nrQZSvfVDAIUXr3WqLRZGZqWk/P4T8p2SP+de2Sr5HPcvjhcJzEiulKgnxtA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.10.tgz", + "integrity": "sha512-AKQM3gfYfSW8XRk8DdMCzaLUFB15dTrZfnX8WXQoOUpUBQ+NaAFCP1kPS/ykbbGYz7rxn0WS48/81l9hFl3u4A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.10.tgz", + "integrity": "sha512-7RTytDPGU6fek/hWuN9qQpeGPBZFfB4zZgcz2VK2Z5VpdUxEI8JKYsg3JfO0n/Z1E/6l05n0unDCNc4HnhQGig==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.10.tgz", + "integrity": "sha512-5Se0VM9Wtq797YFn+dLimf2Zx6McttsH2olUBsDml+lm0GOCRVebRWUvDtkY4BWYv/3NgzS8b/UM3jQNh5hYyw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.10.tgz", + "integrity": "sha512-XkA4frq1TLj4bEMB+2HnI0+4RnjbuGZfet2gs/LNs5Hc7D89ZQBHQ0gL2ND6Lzu1+QVkjp3x1gIcPKzRNP8bXw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.10.tgz", + "integrity": "sha512-AVTSBhTX8Y/Fz6OmIVBip9tJzZEUcY8WLh7I59+upa5/GPhh2/aM6bvOMQySspnCCHvFi79kMtdJS1w0DXAeag==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.10.tgz", + "integrity": "sha512-fswk3XT0Uf2pGJmOpDB7yknqhVkJQkAQOcW/ccVOtfx05LkbWOaRAtn5SaqXypeKQra1QaEa841PgrSL9ubSPQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.10.tgz", + "integrity": "sha512-ah+9b59KDTSfpaCg6VdJoOQvKjI33nTaQr4UluQwW7aEwZQsbMCfTmfEO4VyewOxx4RaDT/xCy9ra2GPWmO7Kw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.10.tgz", + "integrity": "sha512-QHPDbKkrGO8/cz9LKVnJU22HOi4pxZnZhhA2HYHez5Pz4JeffhDjf85E57Oyco163GnzNCVkZK0b/n4Y0UHcSw==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.10.tgz", + "integrity": "sha512-9KpxSVFCu0iK1owoez6aC/s/EdUQLDN3adTxGCqxMVhrPDj6bt5dbrHDXUuq+Bs2vATFBBrQS5vdQ/Ed2P+nbw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.52.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.52.4.tgz", + "integrity": "sha512-BTm2qKNnWIQ5auf4deoetINJm2JzvihvGb9R6K/ETwKLql/Bb3Eg2H1FBp1gUb4YGbydMA3jcmQTR73q7J+GAA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.52.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.52.4.tgz", + "integrity": "sha512-P9LDQiC5vpgGFgz7GSM6dKPCiqR3XYN1WwJKA4/BUVDjHpYsf3iBEmVz62uyq20NGYbiGPR5cNHI7T1HqxNs2w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.52.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.52.4.tgz", + "integrity": "sha512-QRWSW+bVccAvZF6cbNZBJwAehmvG9NwfWHwMy4GbWi/BQIA/laTIktebT2ipVjNncqE6GLPxOok5hsECgAxGZg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.52.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.52.4.tgz", + "integrity": "sha512-hZgP05pResAkRJxL1b+7yxCnXPGsXU0fG9Yfd6dUaoGk+FhdPKCJ5L1Sumyxn8kvw8Qi5PvQ8ulenUbRjzeCTw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.52.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.52.4.tgz", + "integrity": "sha512-xmc30VshuBNUd58Xk4TKAEcRZHaXlV+tCxIXELiE9sQuK3kG8ZFgSPi57UBJt8/ogfhAF5Oz4ZSUBN77weM+mQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.52.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.52.4.tgz", + "integrity": "sha512-WdSLpZFjOEqNZGmHflxyifolwAiZmDQzuOzIq9L27ButpCVpD7KzTRtEG1I0wMPFyiyUdOO+4t8GvrnBLQSwpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.52.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.52.4.tgz", + "integrity": "sha512-xRiOu9Of1FZ4SxVbB0iEDXc4ddIcjCv2aj03dmW8UrZIW7aIQ9jVJdLBIhxBI+MaTnGAKyvMwPwQnoOEvP7FgQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.52.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.52.4.tgz", + "integrity": "sha512-FbhM2p9TJAmEIEhIgzR4soUcsW49e9veAQCziwbR+XWB2zqJ12b4i/+hel9yLiD8pLncDH4fKIPIbt5238341Q==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.52.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.52.4.tgz", + "integrity": "sha512-4n4gVwhPHR9q/g8lKCyz0yuaD0MvDf7dV4f9tHt0C73Mp8h38UCtSCSE6R9iBlTbXlmA8CjpsZoujhszefqueg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.52.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.52.4.tgz", + "integrity": "sha512-u0n17nGA0nvi/11gcZKsjkLj1QIpAuPFQbR48Subo7SmZJnGxDpspyw2kbpuoQnyK+9pwf3pAoEXerJs/8Mi9g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.52.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.52.4.tgz", + "integrity": "sha512-0G2c2lpYtbTuXo8KEJkDkClE/+/2AFPdPAbmaHoE870foRFs4pBrDehilMcrSScrN/fB/1HTaWO4bqw+ewBzMQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.52.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.52.4.tgz", + "integrity": "sha512-teSACug1GyZHmPDv14VNbvZFX779UqWTsd7KtTM9JIZRDI5NUwYSIS30kzI8m06gOPB//jtpqlhmraQ68b5X2g==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.52.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.52.4.tgz", + "integrity": "sha512-/MOEW3aHjjs1p4Pw1Xk4+3egRevx8Ji9N6HUIA1Ifh8Q+cg9dremvFCUbOX2Zebz80BwJIgCBUemjqhU5XI5Eg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.52.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.52.4.tgz", + "integrity": "sha512-1HHmsRyh845QDpEWzOFtMCph5Ts+9+yllCrREuBR/vg2RogAQGGBRC8lDPrPOMnrdOJ+mt1WLMOC2Kao/UwcvA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.52.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.52.4.tgz", + "integrity": "sha512-seoeZp4L/6D1MUyjWkOMRU6/iLmCU2EjbMTyAG4oIOs1/I82Y5lTeaxW0KBfkUdHAWN7j25bpkt0rjnOgAcQcA==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.52.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.52.4.tgz", + "integrity": "sha512-Wi6AXf0k0L7E2gteNsNHUs7UMwCIhsCTs6+tqQ5GPwVRWMaflqGec4Sd8n6+FNFDw9vGcReqk2KzBDhCa1DLYg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.52.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.52.4.tgz", + "integrity": "sha512-dtBZYjDmCQ9hW+WgEkaffvRRCKm767wWhxsFW3Lw86VXz/uJRuD438/XvbZT//B96Vs8oTA8Q4A0AfHbrxP9zw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.52.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.52.4.tgz", + "integrity": "sha512-1ox+GqgRWqaB1RnyZXL8PD6E5f7YyRUJYnCqKpNzxzP0TkaUh112NDrR9Tt+C8rJ4x5G9Mk8PQR3o7Ku2RKqKA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.52.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.52.4.tgz", + "integrity": "sha512-8GKr640PdFNXwzIE0IrkMWUNUomILLkfeHjXBi/nUvFlpZP+FA8BKGKpacjW6OUUHaNI6sUURxR2U2g78FOHWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.52.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.52.4.tgz", + "integrity": "sha512-AIy/jdJ7WtJ/F6EcfOb2GjR9UweO0n43jNObQMb6oGxkYTfLcnN7vYYpG+CN3lLxrQkzWnMOoNSHTW54pgbVxw==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.52.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.52.4.tgz", + "integrity": "sha512-UF9KfsH9yEam0UjTwAgdK0anlQ7c8/pWPU2yVjyWcF1I1thABt6WXE47cI71pGiZ8wGvxohBoLnxM04L/wj8mQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.52.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.52.4.tgz", + "integrity": "sha512-bf9PtUa0u8IXDVxzRToFQKsNCRz9qLYfR/MpECxl4mRoWYjAeFjgxj1XdZr2M/GNVpT05p+LgQOHopYDlUu6/w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@tweenjs/tween.js": { + "version": "23.1.3", + "resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-23.1.3.tgz", + "integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==", + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "24.7.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.7.1.tgz", + "integrity": "sha512-CmyhGZanP88uuC5GpWU9q+fI61j2SkhO3UGMUdfYRE6Bcy0ccyzn1Rqj9YAB/ZY4kOXmNf0ocah5GtphmLMP6Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~7.14.0" + } + }, + "node_modules/@types/stats.js": { + "version": "0.17.4", + "resolved": "https://registry.npmjs.org/@types/stats.js/-/stats.js-0.17.4.tgz", + "integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==", + "license": "MIT" + }, + "node_modules/@types/three": { + "version": "0.180.0", + "resolved": "https://registry.npmjs.org/@types/three/-/three-0.180.0.tgz", + "integrity": "sha512-ykFtgCqNnY0IPvDro7h+9ZeLY+qjgUWv+qEvUt84grhenO60Hqd4hScHE7VTB9nOQ/3QM8lkbNE+4vKjEpUxKg==", + "license": "MIT", + "dependencies": { + "@dimforge/rapier3d-compat": "~0.12.0", + "@tweenjs/tween.js": "~23.1.3", + "@types/stats.js": "*", + "@types/webxr": "*", + "@webgpu/types": "*", + "fflate": "~0.8.2", + "meshoptimizer": "~0.22.0" + } + }, + "node_modules/@types/webxr": { + "version": "0.5.24", + "resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz", + "integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==", + "license": "MIT" + }, + "node_modules/@webgpu/types": { + "version": "0.1.65", + "resolved": "https://registry.npmjs.org/@webgpu/types/-/types-0.1.65.tgz", + "integrity": "sha512-cYrHab4d6wuVvDW5tdsfI6/o6vcLMDe6w2Citd1oS51Xxu2ycLCnVo4fqwujfKWijrZMInTJIKcXxteoy21nVA==", + "license": "BSD-3-Clause" + }, + "node_modules/esbuild": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.10.tgz", + "integrity": "sha512-9RiGKvCwaqxO2owP61uQ4BgNborAQskMR6QusfWzQqv7AZOg5oGehdY2pRJMTKuwxd1IDBP4rSbI5lHzU7SMsQ==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.10", + "@esbuild/android-arm": "0.25.10", + "@esbuild/android-arm64": "0.25.10", + "@esbuild/android-x64": "0.25.10", + "@esbuild/darwin-arm64": "0.25.10", + "@esbuild/darwin-x64": "0.25.10", + "@esbuild/freebsd-arm64": "0.25.10", + "@esbuild/freebsd-x64": "0.25.10", + "@esbuild/linux-arm": "0.25.10", + "@esbuild/linux-arm64": "0.25.10", + "@esbuild/linux-ia32": "0.25.10", + "@esbuild/linux-loong64": "0.25.10", + "@esbuild/linux-mips64el": "0.25.10", + "@esbuild/linux-ppc64": "0.25.10", + "@esbuild/linux-riscv64": "0.25.10", + "@esbuild/linux-s390x": "0.25.10", + "@esbuild/linux-x64": "0.25.10", + "@esbuild/netbsd-arm64": "0.25.10", + "@esbuild/netbsd-x64": "0.25.10", + "@esbuild/openbsd-arm64": "0.25.10", + "@esbuild/openbsd-x64": "0.25.10", + "@esbuild/openharmony-arm64": "0.25.10", + "@esbuild/sunos-x64": "0.25.10", + "@esbuild/win32-arm64": "0.25.10", + "@esbuild/win32-ia32": "0.25.10", + "@esbuild/win32-x64": "0.25.10" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fflate": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.2.tgz", + "integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==", + "license": "MIT" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/meshoptimizer": { + "version": "0.22.0", + "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-0.22.0.tgz", + "integrity": "sha512-IebiK79sqIy+E4EgOr+CAw+Ke8hAspXKzBd0JdgEmPHiAwmvEj2S4h1rfvo+o/BnfEYd/jAOg5IeeIjzlzSnDg==", + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.6", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz", + "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/rollup": { + "version": "4.52.4", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.52.4.tgz", + "integrity": "sha512-CLEVl+MnPAiKh5pl4dEWSyMTpuflgNQiLGhMv8ezD5W/qP8AKvmYpCOKRRNOh7oRKnauBZ4SyeYkMS+1VSyKwQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.52.4", + "@rollup/rollup-android-arm64": "4.52.4", + "@rollup/rollup-darwin-arm64": "4.52.4", + "@rollup/rollup-darwin-x64": "4.52.4", + "@rollup/rollup-freebsd-arm64": "4.52.4", + "@rollup/rollup-freebsd-x64": "4.52.4", + "@rollup/rollup-linux-arm-gnueabihf": "4.52.4", + "@rollup/rollup-linux-arm-musleabihf": "4.52.4", + "@rollup/rollup-linux-arm64-gnu": "4.52.4", + "@rollup/rollup-linux-arm64-musl": "4.52.4", + "@rollup/rollup-linux-loong64-gnu": "4.52.4", + "@rollup/rollup-linux-ppc64-gnu": "4.52.4", + "@rollup/rollup-linux-riscv64-gnu": "4.52.4", + "@rollup/rollup-linux-riscv64-musl": "4.52.4", + "@rollup/rollup-linux-s390x-gnu": "4.52.4", + "@rollup/rollup-linux-x64-gnu": "4.52.4", + "@rollup/rollup-linux-x64-musl": "4.52.4", + "@rollup/rollup-openharmony-arm64": "4.52.4", + "@rollup/rollup-win32-arm64-msvc": "4.52.4", + "@rollup/rollup-win32-ia32-msvc": "4.52.4", + "@rollup/rollup-win32-x64-gnu": "4.52.4", + "@rollup/rollup-win32-x64-msvc": "4.52.4", + "fsevents": "~2.3.2" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/three": { + "version": "0.180.0", + "resolved": "https://registry.npmjs.org/three/-/three-0.180.0.tgz", + "integrity": "sha512-o+qycAMZrh+TsE01GqWUxUIKR1AL0S8pq7zDkYOQw8GqfX8b8VoCKYUoHbhiX5j+7hr8XsuHDVU6+gkQJQKg9w==", + "license": "MIT" + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "7.14.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.14.0.tgz", + "integrity": "sha512-QQiYxHuyZ9gQUIrmPo3IA+hUl4KYk8uSA7cHrcKd/l3p1OTpZcM0Tbp9x7FAtXdAYhlasd60ncPpgu6ihG6TOA==", + "dev": true, + "license": "MIT" + }, + "node_modules/vite": { + "version": "7.1.9", + "resolved": "https://registry.npmjs.org/vite/-/vite-7.1.9.tgz", + "integrity": "sha512-4nVGliEpxmhCL8DslSAUdxlB6+SMrhB0a1v5ijlh1xB1nEPuy1mxaHxysVucLHuWryAxLWg6a5ei+U4TLn/rFg==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.5.0", + "picomatch": "^4.0.3", + "postcss": "^8.5.6", + "rollup": "^4.43.0", + "tinyglobby": "^0.2.15" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "lightningcss": "^1.21.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + } + } +} diff --git a/web-clients/hearts/package.json b/web-clients/hearts/package.json new file mode 100644 index 00000000..9b396108 --- /dev/null +++ b/web-clients/hearts/package.json @@ -0,0 +1,23 @@ +{ + "name": "hearts", + "version": "1.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc && vite build", + "preview": "vite preview" + }, + "keywords": [], + "author": "", + "license": "ISC", + "description": "Hearts card game web client using three.js", + "devDependencies": { + "@types/node": "^24.7.1", + "typescript": "^5.9.3", + "vite": "^7.1.9" + }, + "dependencies": { + "@types/three": "^0.180.0", + "three": "^0.180.0" + } +} diff --git a/web-clients/hearts/src/game/HeartsGame.ts b/web-clients/hearts/src/game/HeartsGame.ts new file mode 100644 index 00000000..6251b1ea --- /dev/null +++ b/web-clients/hearts/src/game/HeartsGame.ts @@ -0,0 +1,674 @@ +import { HeartsClientImpl } from '@generated/hearts/HeartsClient'; +import { Card, PassDirection, PlayerViewOfGame } from '@generated/hearts/types'; +import { CardScene } from '../graphics/CardScene'; +import { GameUI } from '../ui/GameUI'; +import { Card3D } from '../graphics/Card3D'; + +export class HeartsGame { + private client?: HeartsClientImpl; + private scene: CardScene; + private ui: GameUI; + private playerId: string = ''; + private playerPositions: Map = new Map(); // Maps playerId to position (0-3) + private playerNames: Map = new Map(); // Maps playerId to player name + + private passingPhase: boolean = false; + private myTurn: boolean = false; + private currentTrickNumber: number = 0; + private currentRoundNumber: number = 1; + private queuedCardPlays: Array<{playerId: string, card: any}> = []; + + constructor(scene: CardScene, ui: GameUI) { + this.scene = scene; + this.ui = ui; + + // Setup scene card click handler + this.scene.onCardClick = this.handleCardClick.bind(this); + } + + public async createGame(serverUrl: string, playerName: string): Promise { + try { + console.log('Creating new game...'); + + // First, authenticate to get access token + const httpUrl = serverUrl.replace('ws://', 'http://').replace('wss://', 'https://'); + console.log('Authenticating with:', httpUrl + '/login'); + + const loginResponse = await fetch(`${httpUrl}/login`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + username: playerName, + password: 'default-password' + }), + credentials: 'include' + }); + + console.log('Login response status:', loginResponse.status); + + if (!loginResponse.ok) { + const errorText = await loginResponse.text(); + console.error('Login failed:', errorText); + throw new Error(`Authentication failed: ${loginResponse.status} ${loginResponse.statusText}`); + } + + await loginResponse.json(); + console.log('Authenticated successfully'); + + // Create the game + console.log('Creating Hearts game...'); + const createResponse = await fetch(`${httpUrl}/hearts/create`, { + method: 'POST', + credentials: 'include' + }); + + if (!createResponse.ok) { + const errorText = await createResponse.text(); + throw new Error(`Failed to create game: ${createResponse.status} ${createResponse.statusText}\n${errorText}`); + } + + const gameInfo = await createResponse.json(); + console.log('Game created:', gameInfo); + + return gameInfo.id; + } catch (error) { + console.error('Error creating game:', error); + throw error; + } + } + + public async connect(serverUrl: string, playerId: string, playerName: string, gameId: string): Promise { + try { + console.log('Starting connection process...'); + this.ui.setConnectionStatus('Authenticating...'); + this.ui.setConnectButtonEnabled(false); + + // First, authenticate to get access token + const httpUrl = serverUrl.replace('ws://', 'http://').replace('wss://', 'https://'); + console.log('Authenticating with:', httpUrl + '/login'); + + const loginResponse = await fetch(`${httpUrl}/login`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + username: playerName, + password: 'default-password' + }), + credentials: 'include' // Important for cookies + }); + + console.log('Login response status:', loginResponse.status); + + if (!loginResponse.ok) { + const errorText = await loginResponse.text(); + console.error('Login failed:', errorText); + throw new Error(`Authentication failed: ${loginResponse.status} ${loginResponse.statusText}\n${errorText}`); + } + + const userData = await loginResponse.json(); + console.log('Authenticated successfully:', userData); + const accessToken = userData.accessToken; + + // Use the authenticated user's ID, not the passed-in playerId + this.playerId = userData.id; + this.playerNames.set(this.playerId, playerName); // Track our own name + console.log('Using player ID from auth:', this.playerId); + + this.ui.setConnectionStatus('Authenticated. Connecting to game...'); + console.log('Attempting to connect to game:', gameId); + + // Create WebSocket connections with proper URL pattern + const actionSocketUrl = `${serverUrl}/hearts/join/${encodeURIComponent(gameId)}`; + console.log('Connecting action socket to:', actionSocketUrl); + const actionSocket = new WebSocket(actionSocketUrl); + + await this.waitForSocketOpen(actionSocket); + console.log('Action socket connected'); + this.ui.setConnectionStatus('Action socket connected. Waiting for connection ID...'); + + // Get connection ID from the first message + console.log('Waiting for connection ID...'); + const connectionId = await this.getConnectionId(actionSocket); + console.log('Received connection ID:', connectionId); + + this.ui.setConnectionStatus('Establishing notification socket...'); + + // After action socket is connected, establish notification socket + const notificationSocketUrl = `${serverUrl}/hearts/join/${connectionId}/finish`; + console.log('Connecting notification socket to:', notificationSocketUrl); + const notificationSocket = new WebSocket(notificationSocketUrl); + + await this.waitForSocketOpen(notificationSocket); + console.log('Notification socket connected'); + this.ui.setConnectionStatus('Connected!'); + + // Add logging to notification socket BEFORE creating client + console.log('Setting up notification socket logging...'); + notificationSocket.addEventListener('message', (event) => { + console.log('📨 RAW notification received:', event.data); + }); + + // Create Hearts client + console.log('Creating Hearts client...'); + this.client = new HeartsClientImpl(actionSocket, notificationSocket); + console.log('Hearts client created'); + + // Setup event handlers + console.log('Setting up event handlers...'); + this.setupEventHandlers(); + console.log('Event handlers set up'); + + // Hide connection panel + console.log('Hiding connection panel and showing game UI...'); + this.ui.hideConnectionPanel(); + this.ui.setStatus('Connected to game. Waiting for game to start...'); + this.ui.showMessage('Connected to Hearts game!'); + console.log('Connection complete. Waiting for game events...'); + + } catch (error) { + console.error('Connection error:', error); + const errorMessage = error instanceof Error ? error.message : String(error); + this.ui.setConnectionStatus(`Connection failed: ${errorMessage}`); + this.ui.showMessage(`Connection failed: ${errorMessage}`, 10000); + this.ui.setConnectButtonEnabled(true); + throw error; + } + } + + private getConnectionId(socket: WebSocket): Promise { + return new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + reject(new Error('Timeout waiting for connection ID (10 seconds). The game may not exist or you may not have permission to join.')); + }, 10000); + + const messageHandler = (event: MessageEvent) => { + console.log('Received message while waiting for connection ID:', event.data); + clearTimeout(timeout); + try { + const data = JSON.parse(event.data); + console.log('Parsed data:', data); + + // Check for ConnectionId (capital C) - this is what the server sends in HelloSuccessMessage + if (data.ConnectionId || data.connectionId) { + const connectionId = data.ConnectionId || data.connectionId; + socket.removeEventListener('message', messageHandler); + console.log('Extracted connection ID:', connectionId); + resolve(connectionId); + } else if (data.ErrorMessage || data.errorMessage) { + // Server sent an error + const errorMsg = data.ErrorMessage || data.errorMessage; + console.error('Server error:', errorMsg); + reject(new Error('Server error: ' + errorMsg)); + } else { + console.error('Message does not contain ConnectionId:', data); + reject(new Error('No ConnectionId in response. Received: ' + JSON.stringify(data))); + } + } catch (error) { + console.error('Failed to parse message:', error, 'Raw data:', event.data); + reject(new Error('Failed to parse connection ID response: ' + event.data)); + } + }; + + socket.addEventListener('message', messageHandler); + }); + } + + private waitForSocketOpen(socket: WebSocket): Promise { + return new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + reject(new Error('Connection timeout - server not responding')); + }, 10000); + + socket.onopen = () => { + clearTimeout(timeout); + resolve(); + }; + + socket.onerror = (error) => { + clearTimeout(timeout); + console.error('WebSocket error:', error); + console.error('Socket URL:', socket.url); + console.error('Socket readyState:', socket.readyState); + reject(new Error(`WebSocket connection failed. Make sure:\n1. Server is running on localhost:13992\n2. Game ID exists on server\n3. Check server logs for errors`)); + }; + + socket.onclose = (event) => { + if (!event.wasClean) { + clearTimeout(timeout); + reject(new Error(`Connection closed unexpectedly (code: ${event.code}, reason: ${event.reason || 'none'})`)); + } + }; + }); + } + + private setupEventHandlers(): void { + if (!this.client) { + console.error('Cannot setup event handlers: client is null'); + return; + } + + console.log('Registering GameStarted handler...'); + this.client.onGameStarted((data) => { + console.log('🎮 Game started event received!', data); + this.ui.showMessage('Game started!'); + this.ui.setStatus('Game in progress'); + this.ui.showDevLog(); // Show developer log when game starts + + if (data.playerViewOfGame) { + this.updateGameState(data.playerViewOfGame); + } + }); + + console.log('Registering PassingPhaseStarted handler...'); + this.client.onPassingPhaseStarted((data) => { + console.log('🎴 Passing phase started event received!', data); + this.passingPhase = true; + const direction = this.getPassDirectionString(data.passDirection); + this.ui.showMessage(`Pass 3 cards ${direction}`); + this.ui.setStatus(`Select 3 cards to pass ${direction}`); + this.ui.updateGameInfo({ passDirection: direction }); + }); + + this.client.onAllPlayersPassed((data) => { + console.log('All players passed:', data); + this.passingPhase = false; + this.scene.clearSelection(); + + if (data.receivedCards && data.receivedCards.length > 0) { + this.ui.showMessage(`Received ${data.receivedCards.length} cards`); + } + + this.ui.setStatus('Cards passed. Waiting for round to start...'); + }); + + this.client.onPlayerPassedCards((data) => { + console.log('Player passed cards:', data); + }); + + console.log('Registering ItsYourTurn handler...'); + this.client.onItsYourTurn((data) => { + console.log('✋ Your turn event received!'); + console.log(' - Setting myTurn = true'); + console.log(' - Is animating:', this.scene.isAnimating()); + this.myTurn = true; + this.ui.showMessage('Your turn!'); + this.ui.setStatus('Your turn - select a card to play'); + this.ui.updateGameInfo({ isMyTurn: true }); + + if (data.playerViewOfGame) { + this.updateGameState(data.playerViewOfGame); + } + console.log(' - After updateGameState, myTurn =', this.myTurn); + }); + + this.client.onItsPlayersTurn((data) => { + console.log("It's another player's turn:", data); + console.log("My player ID:", this.playerId); + console.log("Turn player ID:", data.playerId); + + // Only set myTurn to false if it's NOT our turn + if (data.playerId !== this.playerId) { + this.myTurn = false; + this.ui.updateGameInfo({ isMyTurn: false }); + this.ui.setStatus('Waiting for other players...'); + } else { + console.log("Received ItsPlayersTurn for my own ID - this might be a server notification about me playing"); + } + }); + + this.client.onPlayerPlayedCard(async (data) => { + console.log('🃏 PlayerPlayedCard notification:', data); + + // Skip if this is our own card - playCard will handle everything + if (data.playerId === this.playerId) { + console.log('✅ Skipping notification for our own card - already handled by playCard'); + return; + } + + // If trick animation is running, queue this notification + if (this.scene.isAnimatingTrick) { + console.log('⏸️ Trick animation in progress - queuing card play'); + this.queuedCardPlays.push({ playerId: data.playerId, card: data.card }); + return; + } + + // Process the card play immediately + await this.processCardPlay(data.playerId, data.card); + }); + + this.client.onTrickCompleted(async (data) => { + console.log('Trick completed:', data); + + // Find the winning card + const winningPlay = data.trickCards.find(tc => tc.playerId === data.winnerId); + const winningCardStr = winningPlay ? this.formatCard(winningPlay.card) : 'Unknown'; + + // Log trick result + this.ui.logTrickResult(data.winnerName, winningCardStr, data.points); + + this.ui.showMessage( + `${data.winnerName || 'Player'} won the trick! (+${data.points} points)` + ); + + // Get winner's position + const winnerPosition = this.playerPositions.get(data.winnerId) ?? 0; + console.log(`Winner ${data.winnerName} (ID: ${data.winnerId}) is at position ${winnerPosition}`); + + // Animate cards to winner (animation handles disposal internally) + await this.scene.animateTrickToWinner(winnerPosition, 1500); + + // Process any queued card plays that arrived during animation + await this.processQueuedCardPlays(); + }); + + this.client.onRoundEnded((data) => { + console.log('Round ended:', data); + let message = 'Round ended!'; + + if (data.moonShooterName) { + message = `${data.moonShooterName} shot the moon!`; + } + + // Log round end + this.ui.logRoundEnd(this.currentRoundNumber); + + // Reset trick counter for next round + this.currentTrickNumber = 0; + this.currentRoundNumber++; + + this.ui.showMessage(message, 5000); + this.ui.setStatus('Round ended. Waiting for next round...'); + + if (data.scores) { + console.log('Scores:', data.scores); + } + }); + + this.client.onGameEnded((data) => { + console.log('Game ended:', data); + this.ui.showMessage( + `Game Over! Winner: ${data.winnerName || 'Unknown'}`, + 10000 + ); + this.ui.setStatus('Game ended'); + }); + + this.client.onHeartsWereBroken(() => { + console.log('Hearts were broken'); + this.ui.showMessage('Hearts have been broken!'); + }); + } + + private async updateGameState(state: PlayerViewOfGame): Promise { + console.log('🔄 Updating game state:', state); + console.log(' - Round:', state.roundNumber); + console.log(' - Cards in state:', state.cards?.length || 0); + console.log(' - Is animating:', this.scene.isAnimating()); + console.log(' - Current trick cards:', this.scene.currentTrickCards.length); + console.log(' - Player cards before update:', this.scene.playerCards.length); + + // Sync passing phase with server state + // If hasPassed is true OR passDirection is None, we're not in passing phase + const shouldBeInPassingPhase = !state.hasPassed && state.passDirection !== PassDirection.None; + if (this.passingPhase !== shouldBeInPassingPhase) { + console.log(` - Syncing passingPhase: ${this.passingPhase} -> ${shouldBeInPassingPhase}`); + this.passingPhase = shouldBeInPassingPhase; + } + + // Sync myTurn with server state + if (this.myTurn !== state.isMyTurn) { + console.log(` - Syncing myTurn: ${this.myTurn} -> ${state.isMyTurn}`); + this.myTurn = state.isMyTurn; + } + + // Update UI + this.ui.updateGameInfo({ + roundNumber: state.roundNumber, + playerScore: state.roundScore, + totalScore: state.totalScore, + isMyTurn: state.isMyTurn, + }); + + // Update cards in hand + if (state.cards) { + console.log(' ➡️ Adding', state.cards.length, 'cards to player hand'); + await this.scene.addPlayerCards(state.cards); + console.log(' ✅ Cards added. Player cards after update:', this.scene.playerCards.length); + } else { + console.log(' ⚠️ No cards in state to add'); + } + + // Update opponent cards and track player positions + if (state.otherPlayers) { + // Current player is always position 0 + this.playerPositions.set(this.playerId, 0); + + state.otherPlayers.forEach((player, index) => { + // Opponent positions: 1 (left/west), 2 (across/north), 3 (right/east) + this.playerPositions.set(player.playerId, index + 1); + this.playerNames.set(player.playerId, player.name); + + this.scene.updateOpponentCards( + player.playerId, + player.numberOfCards, + index, + player.name // Pass the player name + ); + }); + } + + // Update current trick + // DON'T clear or rebuild the trick during animations + // The onTrickCompleted handler is responsible for clearing tricks + // We only need to sync if we're out of sync (shouldn't happen normally) + if (this.scene.isAnimating()) { + console.log('Skipping trick update - animation in progress'); + return; + } + + // If there's a mismatch between state and scene, sync it + // This handles edge cases like reconnection or state recovery + if (state.currentTrick) { + const stateTrickCount = state.currentTrick.length; + const sceneTrickCount = this.scene.currentTrickCards.length; + + if (stateTrickCount !== sceneTrickCount) { + console.log(`Trick count mismatch: state=${stateTrickCount}, scene=${sceneTrickCount}. Resyncing...`); + this.scene.clearTrick(); + for (const cardPlay of state.currentTrick) { + const playerPosition = this.playerPositions.get(cardPlay.playerId) ?? 0; + await this.scene.addTrickCard(cardPlay.card, playerPosition); + } + } + } + } + + private getPassDirectionString(direction: PassDirection): string { + switch (direction) { + case PassDirection.Left: + return 'Left'; + case PassDirection.Right: + return 'Right'; + case PassDirection.Across: + return 'Across'; + case PassDirection.None: + return 'None'; + default: + return 'Unknown'; + } + } + + private async handleCardClick(card: Card3D): Promise { + console.log('🖱️ Card clicked:', card.card); + console.log(' - Passing phase:', this.passingPhase); + console.log(' - My turn:', this.myTurn); + console.log(' - Is animating trick:', this.scene.isAnimatingTrick); + console.log(' - Is animating card play:', this.scene.isAnimating()); + + // Block input during trick animations + if (this.scene.isAnimatingTrick) { + console.log('⏸️ Cannot play card - trick animation in progress'); + this.ui.showMessage('Please wait for animation to complete', 1500); + return; + } + + if (this.passingPhase) { + // Handle card passing + const selectedCards = this.scene.getSelectedCards(); + + if (selectedCards.length === 3) { + this.ui.setStatus('Passing cards...'); + await this.passCards(selectedCards.map(c => c.card)); + } + } else if (this.myTurn) { + // Handle card playing + this.ui.setStatus('Playing card...'); + await this.playCard(card.card); + } else { + console.log('Not my turn or not in correct phase'); + } + } + + private async passCards(cards: Card[]): Promise { + if (!this.client) return; + + try { + const response = await this.client.passCards({ + playerId: this.playerId, + cards: cards, + }); + + console.log('Pass cards response:', response); + + if (response.hasError) { + this.ui.showMessage(`Error: ${response.error}`); + this.scene.clearSelection(); + } else { + this.ui.showMessage('Cards passed!'); + this.ui.setStatus('Waiting for other players to pass...'); + + // Remove passed cards from hand + cards.forEach(card => this.scene.removePlayerCard(card)); + this.scene.clearSelection(); + } + } catch (error) { + console.error('Error passing cards:', error); + this.ui.showMessage('Failed to pass cards'); + this.scene.clearSelection(); + } + } + + private async playCard(card: Card): Promise { + if (!this.client) return; + + try { + console.log('Playing card:', card); + console.log('Player ID:', this.playerId); + console.log('My turn:', this.myTurn); + + // Find and save the Card3D object BEFORE sending to server + // This prevents race conditions where updateGameState clears playerCards + // before we can animate the card + const card3D = this.scene.playerCards.find( + c => c.card.rank === card.rank && c.card.suit === card.suit + ); + + if (!card3D) { + console.error('Card3D not found in playerCards before sending to server!'); + this.ui.showMessage('Error: Card not found'); + return; + } + + // Detect if this is the start of a new trick + if (this.scene.currentTrickCards.length === 0) { + this.currentTrickNumber++; + this.ui.logNewTrick(this.currentTrickNumber); + } + + // Log our own card play BEFORE sending to server + // This ensures it appears in the correct order in the dev log + const playerName = this.playerNames.get(this.playerId) ?? 'You'; + const cardStr = this.formatCard(card); + this.ui.logCardPlay(playerName, cardStr); + + const response = await this.client.playCard({ + playerId: this.playerId, + card: card, + }); + + console.log('Play card response:', response); + + if (response.hasError) { + this.ui.showMessage(`Error: ${response.error}`); + } else { + this.myTurn = false; + + // Animate using the saved Card3D reference + // This works even if playerCards has been cleared by updateGameState + await this.scene.playCardWithAnimation(card, 0, card3D); // Pass the saved Card3D + this.ui.setStatus('Waiting for other players...'); + await this.updateGameState(response); + } + } catch (error) { + console.error('Error playing card:', error); + this.ui.showMessage('Failed to play card'); + } + } + + private async processCardPlay(playerId: string, card: any): Promise { + // Detect if this is the start of a new trick (no cards on table) + if (this.scene.currentTrickCards.length === 0) { + this.currentTrickNumber++; + this.ui.logNewTrick(this.currentTrickNumber); + } + + // Get player name and format card + const playerName = this.playerNames.get(playerId) ?? 'Unknown'; + const cardStr = this.formatCard(card); + + // Log to dev console + this.ui.logCardPlay(playerName, cardStr); + + // Get player's position in the scene + const playerPosition = this.playerPositions.get(playerId) ?? 0; + console.log(`Player ${playerId} at position ${playerPosition} played card:`, card); + + // Add the played card to the trick at the correct position + await this.scene.addTrickCard(card, playerPosition); + } + + private async processQueuedCardPlays(): Promise { + if (this.queuedCardPlays.length === 0) { + return; + } + + console.log(`▶️ Processing ${this.queuedCardPlays.length} queued card play(s)`); + + // Process all queued plays in order + while (this.queuedCardPlays.length > 0) { + const queued = this.queuedCardPlays.shift()!; + await this.processCardPlay(queued.playerId, queued.card); + } + } + + private formatCard(card: Card): string { + const rankNames: { [key: number]: string } = { + 1: 'A', 11: 'J', 12: 'Q', 13: 'K' + }; + const rank = rankNames[card.rank] || card.rank.toString(); + + const suitSymbols: { [key: string]: string } = { + 'Hearts': '♥', + 'Diamonds': '♦', + 'Clubs': '♣', + 'Spades': '♠' + }; + const suit = suitSymbols[card.suit] || card.suit; + + return `${rank}${suit}`; + } +} diff --git a/web-clients/hearts/src/graphics/Card3D.ts b/web-clients/hearts/src/graphics/Card3D.ts new file mode 100644 index 00000000..91f1ebd2 --- /dev/null +++ b/web-clients/hearts/src/graphics/Card3D.ts @@ -0,0 +1,319 @@ +import * as THREE from 'three'; +import { Card, Suit } from '@generated/hearts/types'; + +export class Card3D { + public mesh: THREE.Group; + public card: Card; + private cardGeometry: THREE.ExtrudeGeometry; + private cardMaterials: THREE.Material[]; + private isHovered = false; + private isSelected = false; + private static cardBackTexture: THREE.Texture | null = null; + private static textureLoader = new THREE.TextureLoader(); + private static textureCache = new Map(); + + constructor(card: Card, position: THREE.Vector3) { + this.card = card; + this.mesh = new THREE.Group(); + this.mesh.position.copy(position); + + // Create 3D card geometry with rounded corners + const cardWidth = 1.2; + const cardHeight = 1.7; + const cardThickness = 0.02; // Small thickness for 3D effect + const cornerRadius = 0.08; // Rounded corner radius + + // Create geometry and fix UV mapping + this.cardGeometry = this.createRoundedCardGeometry(cardWidth, cardHeight, cardThickness, cornerRadius); + this.fixUVMapping(this.cardGeometry, cardWidth, cardHeight); + + // Load the specific card texture + const cardTexture = this.loadCardTexture(card.rank, card.suit); + + // Load card back texture if not already loaded + if (!Card3D.cardBackTexture) { + Card3D.cardBackTexture = Card3D.textureLoader.load('/bg.png'); + Card3D.cardBackTexture.wrapS = THREE.ClampToEdgeWrapping; + Card3D.cardBackTexture.wrapT = THREE.ClampToEdgeWrapping; + } + + // Create materials for the card + const edgeMaterial = new THREE.MeshStandardMaterial({ + color: 0xffffff, // White edges + roughness: 0.5, + metalness: 0.1, + }); + + const backMaterial = new THREE.MeshStandardMaterial({ + map: Card3D.cardBackTexture, + roughness: 0.5, + metalness: 0.1, + }); + + const frontMaterial = new THREE.MeshStandardMaterial({ + map: cardTexture, + roughness: 0.3, + metalness: 0.1, + }); + + // ExtrudeGeometry uses material index 0 for shape faces, 1 for bevel, 2 for extrude sides + // We need to use an array of materials + this.cardMaterials = [ + frontMaterial, // Shape front face (material index 0) + backMaterial, // Shape back face (material index 1) + edgeMaterial, // Bevel/sides (material index 2) + ]; + + const cardMesh = new THREE.Mesh(this.cardGeometry, this.cardMaterials); + // Don't rotate here - rotation will be applied when placing the card + this.mesh.add(cardMesh); + + this.mesh.userData = { card: this }; + } + + private getSuitName(suit: Suit): string { + console.log(`getSuitName called with suit value:`, suit, `type: ${typeof suit}`); + + // Handle both numeric enum values and string values from server + if (typeof suit === 'string') { + const suitStr = suit.toLowerCase(); + if (suitStr === 'clubs') return 'club'; + if (suitStr === 'diamonds') return 'diamond'; + if (suitStr === 'hearts') return 'heart'; + if (suitStr === 'spades') return 'spade'; + } + + switch (suit) { + case Suit.Clubs: return 'club'; + case Suit.Diamonds: return 'diamond'; + case Suit.Hearts: return 'heart'; + case Suit.Spades: return 'spade'; + default: + console.warn(`Unknown suit value: ${suit}, defaulting to heart`); + return 'heart'; + } + } + + private loadCardTexture(rank: number, suit: Suit): THREE.Texture { + const suitName = this.getSuitName(suit); + const texturePath = `/${suitName}/${rank}_${suitName}.png`; + + console.log(`Loading card texture: ${texturePath} for rank=${rank}, suit=${suit} (${typeof suit})`); + + // Check cache first + if (Card3D.textureCache.has(texturePath)) { + console.log(`Using cached texture: ${texturePath}`); + return Card3D.textureCache.get(texturePath)!; + } + + // Load and cache the texture with error handling + const texture = Card3D.textureLoader.load( + texturePath, + // onLoad callback + () => { + console.log(`Successfully loaded texture: ${texturePath}`); + }, + // onProgress callback + undefined, + // onError callback + (error) => { + console.error(`Failed to load texture: ${texturePath}`, error); + } + ); + texture.minFilter = THREE.LinearFilter; + texture.magFilter = THREE.LinearFilter; + texture.wrapS = THREE.ClampToEdgeWrapping; + texture.wrapT = THREE.ClampToEdgeWrapping; + texture.flipY = false; // Don't flip - we'll handle orientation in UV mapping + texture.colorSpace = THREE.SRGBColorSpace; + + Card3D.textureCache.set(texturePath, texture); + return texture; + } + + private createRoundedCardGeometry( + width: number, + height: number, + depth: number, + radius: number + ): THREE.ExtrudeGeometry { + // Create a rounded rectangle shape + // Shape will be in XY plane, extruded along Z axis + const shape = new THREE.Shape(); + const x = -width / 2; + const y = -height / 2; + + // Start at bottom-left corner (after radius) + shape.moveTo(x + radius, y); + + // Bottom edge + shape.lineTo(x + width - radius, y); + + // Bottom-right corner + shape.quadraticCurveTo(x + width, y, x + width, y + radius); + + // Right edge + shape.lineTo(x + width, y + height - radius); + + // Top-right corner + shape.quadraticCurveTo(x + width, y + height, x + width - radius, y + height); + + // Top edge + shape.lineTo(x + radius, y + height); + + // Top-left corner + shape.quadraticCurveTo(x, y + height, x, y + height - radius); + + // Left edge + shape.lineTo(x, y + radius); + + // Bottom-left corner (close the shape) + shape.quadraticCurveTo(x, y, x + radius, y); + + // Extrude settings - extrude along Z to create depth + const extrudeSettings: THREE.ExtrudeGeometryOptions = { + depth: depth, + bevelEnabled: true, + bevelThickness: depth * 0.1, + bevelSize: depth * 0.1, + bevelSegments: 2, + }; + + const geometry = new THREE.ExtrudeGeometry(shape, extrudeSettings); + + // Don't rotate here - we'll rotate after fixing UVs + return geometry; + } + + private fixUVMapping(geometry: THREE.ExtrudeGeometry, width: number, height: number): void { + const uvAttribute = geometry.attributes.uv; + const positionAttribute = geometry.attributes.position; + + // Before rotation, ExtrudeGeometry has front face at min Z (base) and back at max Z (extruded) + let maxZ = -Infinity; + let minZ = Infinity; + for (let i = 0; i < positionAttribute.count; i++) { + const z = positionAttribute.getZ(i); + maxZ = Math.max(maxZ, z); + minZ = Math.min(minZ, z); + } + + const depth = maxZ - minZ; + const tolerance = depth * 0.4; // Larger tolerance to catch beveled edges + + console.log(`UV Mapping - maxZ: ${maxZ}, minZ: ${minZ}, depth: ${depth}, tolerance: ${tolerance}`); + + // Map both front face (minZ) and back face (maxZ) to full texture + let frontVertexCount = 0; + let backVertexCount = 0; + + for (let i = 0; i < positionAttribute.count; i++) { + const x = positionAttribute.getX(i); + const y = positionAttribute.getY(i); + const z = positionAttribute.getZ(i); + + // Front face (base of extrusion at minZ) - this will be the top when rotated + if (z <= minZ + tolerance) { + // Only flip V coordinate to fix vertical orientation + const u = (x + width / 2) / width; + const v = 1.0 - (y + height / 2) / height; + const clampedU = Math.max(0, Math.min(1, u)); + const clampedV = Math.max(0, Math.min(1, v)); + uvAttribute.setXY(i, clampedU, clampedV); + frontVertexCount++; + } + // Back face (top of extrusion at maxZ) - this will be the bottom when rotated + else if (z >= maxZ - tolerance) { + // Only flip V coordinate to fix vertical orientation + const u = (x + width / 2) / width; + const v = 1.0 - (y + height / 2) / height; + const clampedU = Math.max(0, Math.min(1, u)); + const clampedV = Math.max(0, Math.min(1, v)); + uvAttribute.setXY(i, clampedU, clampedV); + backVertexCount++; + } + } + + console.log(`Updated UVs for ${frontVertexCount} front vertices and ${backVertexCount} back vertices`); + + uvAttribute.needsUpdate = true; + + // Now rotate the geometry so front face (minZ) faces up + geometry.rotateX(-Math.PI / 2); + } + + + public setHovered(hovered: boolean): void { + if (this.isHovered === hovered) return; + this.isHovered = hovered; + + if (hovered && !this.isSelected) { + this.mesh.position.y += 0.2; // Lift card slightly when hovered + // Apply emissive to all materials that support it + this.cardMaterials.forEach(mat => { + if (mat instanceof THREE.MeshStandardMaterial) { + mat.emissive = new THREE.Color(0x444444); + } + }); + } else if (!this.isSelected) { + this.mesh.position.y -= 0.2; + this.cardMaterials.forEach(mat => { + if (mat instanceof THREE.MeshStandardMaterial) { + mat.emissive = new THREE.Color(0x000000); + } + }); + } + } + + public setSelected(selected: boolean): void { + this.isSelected = selected; + + if (selected) { + this.mesh.position.y = 0.4; // Lift selected card higher + this.cardMaterials.forEach(mat => { + if (mat instanceof THREE.MeshStandardMaterial) { + mat.emissive = new THREE.Color(0x888888); + } + }); + } else { + this.mesh.position.y = 0.1; // Reset to table height + this.cardMaterials.forEach(mat => { + if (mat instanceof THREE.MeshStandardMaterial) { + mat.emissive = new THREE.Color(0x000000); + } + }); + } + } + + public animateToPosition(targetPosition: THREE.Vector3, duration: number = 500): Promise { + return new Promise((resolve) => { + const startPosition = this.mesh.position.clone(); + const startTime = Date.now(); + + const animate = () => { + const elapsed = Date.now() - startTime; + const progress = Math.min(elapsed / duration, 1); + + // Easing function + const eased = progress < 0.5 + ? 2 * progress * progress + : 1 - Math.pow(-2 * progress + 2, 2) / 2; + + this.mesh.position.lerpVectors(startPosition, targetPosition, eased); + + if (progress < 1) { + requestAnimationFrame(animate); + } else { + resolve(); + } + }; + + animate(); + }); + } + + public dispose(): void { + this.cardGeometry.dispose(); + this.cardMaterials.forEach(mat => mat.dispose()); + } +} diff --git a/web-clients/hearts/src/graphics/CardAtlas.ts b/web-clients/hearts/src/graphics/CardAtlas.ts new file mode 100644 index 00000000..98d17bd0 --- /dev/null +++ b/web-clients/hearts/src/graphics/CardAtlas.ts @@ -0,0 +1,108 @@ +import { Suit } from '@generated/hearts/types'; + +export interface CardFrame { + x: number; + y: number; + w: number; + h: number; +} + +export interface CardAtlas { + image: string; + size: { + w: number; + h: number; + }; + format: string; + frames: { + [key: string]: CardFrame; + }; +} + +export class CardAtlasLoader { + private static atlas: CardAtlas | null = null; + + public static async load(): Promise { + if (this.atlas) { + return this.atlas; + } + + const response = await fetch('/card_atlas.json'); + this.atlas = await response.json(); + return this.atlas!; + } + + public static getCardKey(rank: number, suit: Suit | string): string { + // Convert suit to lowercase string + let suitName: string; + + // Handle both numeric enum values and string values from server + if (typeof suit === 'string') { + suitName = suit.toLowerCase(); + } else { + // Numeric enum: 0=Clubs, 1=Diamonds, 2=Hearts, 3=Spades + switch (suit) { + case Suit.Clubs: suitName = 'clubs'; break; + case Suit.Diamonds: suitName = 'diamonds'; break; + case Suit.Hearts: suitName = 'hearts'; break; + case Suit.Spades: suitName = 'spades'; break; + default: + console.error(`Unknown suit enum value: ${suit}`); + suitName = 'hearts'; + break; + } + } + + // Convert rank to string (1=A, 11=J, 12=Q, 13=K) + let rankStr: string; + switch (rank) { + case 1: rankStr = 'A'; break; + case 11: rankStr = 'J'; break; + case 12: rankStr = 'Q'; break; + case 13: rankStr = 'K'; break; + default: rankStr = rank.toString(); break; + } + + return `${suitName}_${rankStr}`; + } + + public static getCardFrame(rank: number, suit: Suit | string): CardFrame | null { + if (!this.atlas) { + console.error('Card atlas not loaded yet. Call CardAtlasLoader.load() first.'); + return null; + } + + const key = this.getCardKey(rank, suit); + const frame = this.atlas.frames[key]; + + if (!frame) { + console.error(`Card frame not found for key: ${key}, rank: ${rank}, suit: ${suit}`); + console.error('Available keys in atlas:', Object.keys(this.atlas.frames)); + } + + return frame || null; + } + + public static calculateUVs(rank: number, suit: Suit | string): { uMin: number; uMax: number; vMin: number; vMax: number } | null { + const frame = this.getCardFrame(rank, suit); + if (!frame || !this.atlas) { + return null; + } + + const atlasWidth = this.atlas.size.w; + const atlasHeight = this.atlas.size.h; + + // Add small epsilon to prevent floating point precision issues at edges + const epsilon = 0.0001; + + // Calculate UV coordinates from pixel positions with epsilon padding + const uMin = Math.max(epsilon, frame.x / atlasWidth); + const uMax = Math.min(1 - epsilon, (frame.x + frame.w) / atlasWidth); + + // V coordinates are inverted in Three.js (0 is bottom, 1 is top) + const vMin = Math.max(epsilon, 1 - (frame.y + frame.h) / atlasHeight); + const vMax = Math.min(1 - epsilon, 1 - frame.y / atlasHeight); + + return { uMin, uMax, vMin, vMax }; + } +} diff --git a/web-clients/hearts/src/graphics/CardScene.ts b/web-clients/hearts/src/graphics/CardScene.ts new file mode 100644 index 00000000..9c029b67 --- /dev/null +++ b/web-clients/hearts/src/graphics/CardScene.ts @@ -0,0 +1,780 @@ +import * as THREE from 'three'; +import { Card3D } from './Card3D'; +import { Card } from '@generated/hearts/types'; + +export class CardScene { + private scene: THREE.Scene; + private camera: THREE.PerspectiveCamera; + private renderer: THREE.WebGLRenderer; + private raycaster: THREE.Raycaster; + private mouse: THREE.Vector2; + + public playerCards: Card3D[] = []; + public currentTrickCards: Card3D[] = []; + private hoveredCard: Card3D | null = null; + private selectedCards: Card3D[] = []; + private opponentCards: { [playerId: string]: THREE.Group } = {}; + private opponentAvatars: { [playerId: string]: THREE.Mesh } = {}; + private opponentNameLabels: { [playerId: string]: THREE.Sprite } = {}; + private static bgTexture: THREE.Texture | null = null; + private static textureLoader = new THREE.TextureLoader(); + public isAnimatingTrick: boolean = false; + private isAnimatingCardPlay: boolean = false; + + public onCardClick?: (card: Card3D) => void; + + constructor(container: HTMLElement) { + // Initialize scene + this.scene = new THREE.Scene(); + this.scene.background = new THREE.Color(0x222222); + + // Initialize camera with better angle for card game + this.camera = new THREE.PerspectiveCamera( + 60, + window.innerWidth / window.innerHeight, + 0.1, + 1000 + ); + // Position camera for good table overview + this.camera.position.set(0, 10, 14); + this.camera.lookAt(0, 0, 0); + + // Initialize renderer + this.renderer = new THREE.WebGLRenderer({ antialias: true }); + this.renderer.setSize(window.innerWidth, window.innerHeight); + this.renderer.shadowMap.enabled = true; + container.appendChild(this.renderer.domElement); + + // Initialize raycaster for mouse interaction + this.raycaster = new THREE.Raycaster(); + this.mouse = new THREE.Vector2(); + + // Add lights + this.setupLights(); + + // Add table + this.createTable(); + + // Event listeners + window.addEventListener('resize', this.onWindowResize.bind(this)); + this.renderer.domElement.addEventListener('mousemove', this.onMouseMove.bind(this)); + this.renderer.domElement.addEventListener('click', this.onClick.bind(this)); + + // Start animation loop + this.animate(); + } + + private createMonkeyTexture(): THREE.CanvasTexture { + // Create a canvas to draw the monkey emoji + const canvas = document.createElement('canvas'); + canvas.width = 256; + canvas.height = 256; + const ctx = canvas.getContext('2d'); + + if (ctx) { + // Fill background with semi-transparent brown circle + ctx.fillStyle = '#8B4513'; + ctx.beginPath(); + ctx.arc(128, 128, 120, 0, Math.PI * 2); + ctx.fill(); + + // Add border + ctx.strokeStyle = '#654321'; + ctx.lineWidth = 4; + ctx.stroke(); + + // Draw monkey emoji + ctx.font = '180px Arial'; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillText('🐵', 128, 128); + } + + const texture = new THREE.CanvasTexture(canvas); + texture.needsUpdate = true; + return texture; + } + + private createNameLabelSprite(name: string): THREE.Sprite { + // Create a canvas to draw the text + const canvas = document.createElement('canvas'); + const ctx = canvas.getContext('2d'); + + if (!ctx) { + // Fallback if context can't be created + const texture = new THREE.CanvasTexture(canvas); + const spriteMaterial = new THREE.SpriteMaterial({ map: texture }); + return new THREE.Sprite(spriteMaterial); + } + + // Set font to measure text + ctx.font = 'bold 48px Arial'; + const textMetrics = ctx.measureText(name); + const textWidth = textMetrics.width; + + // Set canvas size with padding + const padding = 20; + canvas.width = textWidth + padding * 2; + canvas.height = 80; + + // Need to set font again after resizing canvas + ctx.font = 'bold 48px Arial'; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + + // Draw background with rounded rectangle + ctx.fillStyle = 'rgba(0, 0, 0, 0.7)'; + this.roundRect(ctx, 0, 0, canvas.width, canvas.height, 15); + ctx.fill(); + + // Draw white border + ctx.strokeStyle = 'rgba(255, 255, 255, 0.8)'; + ctx.lineWidth = 3; + this.roundRect(ctx, 0, 0, canvas.width, canvas.height, 15); + ctx.stroke(); + + // Draw text + ctx.fillStyle = '#FFFFFF'; + ctx.fillText(name, canvas.width / 2, canvas.height / 2); + + // Create sprite + const texture = new THREE.CanvasTexture(canvas); + texture.needsUpdate = true; + const spriteMaterial = new THREE.SpriteMaterial({ + map: texture, + transparent: true, + depthTest: false, // Always render on top + }); + const sprite = new THREE.Sprite(spriteMaterial); + + // Scale sprite to appropriate size (width based on text, height fixed) + const scale = 1.0; // Reduced from 2.5 to 1.0 + sprite.scale.set( + (canvas.width / canvas.height) * scale, + scale, + 1 + ); + + return sprite; + } + + private roundRect(ctx: CanvasRenderingContext2D, x: number, y: number, width: number, height: number, radius: number): void { + ctx.beginPath(); + ctx.moveTo(x + radius, y); + ctx.lineTo(x + width - radius, y); + ctx.quadraticCurveTo(x + width, y, x + width, y + radius); + ctx.lineTo(x + width, y + height - radius); + ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height); + ctx.lineTo(x + radius, y + height); + ctx.quadraticCurveTo(x, y + height, x, y + height - radius); + ctx.lineTo(x, y + radius); + ctx.quadraticCurveTo(x, y, x + radius, y); + ctx.closePath(); + } + + private setupLights(): void { + // Ambient light + const ambientLight = new THREE.AmbientLight(0xffffff, 0.6); + this.scene.add(ambientLight); + + // Directional light (main light) + const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8); + directionalLight.position.set(5, 10, 5); + directionalLight.castShadow = true; + this.scene.add(directionalLight); + + // Hemisphere light for better ambient + const hemiLight = new THREE.HemisphereLight(0xffffff, 0x444444, 0.4); + this.scene.add(hemiLight); + } + + private createTable(): void { + // Load table texture (stretched, not repeated) + const tableTexture = CardScene.textureLoader.load('/bg_table.png'); + tableTexture.wrapS = THREE.ClampToEdgeWrapping; + tableTexture.wrapT = THREE.ClampToEdgeWrapping; + + // Create table surface with texture (increased segments for smoother edges) + const tableGeometry = new THREE.CylinderGeometry(8, 8, 0.2, 128); // Increased from 32 to 128 + const tableMaterial = new THREE.MeshStandardMaterial({ + map: tableTexture, + roughness: 0.8, + metalness: 0.1, + }); + const table = new THREE.Mesh(tableGeometry, tableMaterial); + table.position.y = -0.5; + table.receiveShadow = true; + this.scene.add(table); + + // Add table border (increased segments for smoother torus) + const borderGeometry = new THREE.TorusGeometry(8, 0.15, 32, 128); // Increased from 16,32 to 32,128 + const borderMaterial = new THREE.MeshStandardMaterial({ color: 0x8b4513 }); + const border = new THREE.Mesh(borderGeometry, borderMaterial); + border.rotation.x = Math.PI / 2; + border.position.y = -0.4; + this.scene.add(border); + } + + public async addPlayerCards(cards: Card[]): Promise { + console.log('🎴 addPlayerCards called with', cards.length, 'cards'); + console.log(' - Player cards before clear:', this.playerCards.length); + + // Clear existing cards + this.clearPlayerCards(); + console.log(' - Player cards after clear:', this.playerCards.length); + + // Sort cards by suit first, then by rank + const sortedCards = [...cards].sort((a, b) => { + // Get suit order (convert string to number if needed) + const suitOrder = (suit: any): number => { + if (typeof suit === 'string') { + switch (suit) { + case 'Clubs': return 0; + case 'Diamonds': return 1; + case 'Hearts': return 2; + case 'Spades': return 3; + default: return 0; + } + } + return suit; + }; + + const suitA = suitOrder(a.suit); + const suitB = suitOrder(b.suit); + + // First compare by suit + if (suitA !== suitB) { + return suitA - suitB; + } + + // Then compare by rank + return a.rank - b.rank; + }); + + // Create 3D cards laid flat on the table in a row + const N = sortedCards.length; // number of cards + const cardSpacing = 1.3; // horizontal spacing between cards + const baseZ = 5; // base z position (closer to camera) + const baseY = 0.1; // cards on table surface + + sortedCards.forEach((card, i) => { + // Position cards in a horizontal row + const startX = -(N - 1) * cardSpacing / 2; + const x = startX + i * cardSpacing; + + const position = new THREE.Vector3(x, baseY, baseZ); + const card3D = new Card3D(card, position); + + // Cards are already rotated to lay flat in the geometry + // No rotation needed - cards should be facing up correctly + // (The geometry rotation in Card3D handles the orientation) + + // Adjust card order for proper overlap (higher index = on top) + card3D.mesh.renderOrder = i; + + this.playerCards.push(card3D); + this.scene.add(card3D.mesh); + }); + + console.log(' ✅ addPlayerCards complete. Final player cards count:', this.playerCards.length); + } + + public updateOpponentCards(playerId: string, numberOfCards: number, playerIndex: number, playerName?: string): void { + // Remove existing cards for this opponent + if (this.opponentCards[playerId]) { + this.scene.remove(this.opponentCards[playerId]); + this.opponentCards[playerId].clear(); + } + + // Remove existing avatar if it exists + if (this.opponentAvatars[playerId]) { + this.scene.remove(this.opponentAvatars[playerId]); + } + + // Remove existing name label if it exists + if (this.opponentNameLabels[playerId]) { + this.scene.remove(this.opponentNameLabels[playerId]); + this.opponentNameLabels[playerId].material.map?.dispose(); + this.opponentNameLabels[playerId].material.dispose(); + } + + // Create a group for this opponent's cards + const cardGroup = new THREE.Group(); + this.opponentCards[playerId] = cardGroup; + + // Define positions for opponents (left, top, right) + const positions = [ + { x: -7, z: 0, baseRotation: Math.PI / 2 }, // Left opponent + { x: 0, z: -7, baseRotation: Math.PI }, // Top opponent (across) + { x: 7, z: 0, baseRotation: -Math.PI / 2 }, // Right opponent + ]; + + // Adjust playerIndex to skip current player position (0) + const opponentPosition = positions[playerIndex % 3]; + + // Load background texture for card backs if not already loaded + if (!CardScene.bgTexture) { + CardScene.bgTexture = CardScene.textureLoader.load('/bg.png'); + CardScene.bgTexture.wrapS = THREE.ClampToEdgeWrapping; + CardScene.bgTexture.wrapT = THREE.ClampToEdgeWrapping; + } + + // Create face-down cards using correct fanning formula + const N = numberOfCards; + const theta = Math.PI / 4; // 45 degrees fan for opponents + const R = 5; // Smaller radius for opponents + + for (let i = 0; i < N; i++) { + // Create face-down card with bg texture + const cardGeometry = new THREE.PlaneGeometry(0.9, 1.3); + const cardMaterial = new THREE.MeshStandardMaterial({ + map: CardScene.bgTexture, + side: THREE.DoubleSide, + }); + const cardMesh = new THREE.Mesh(cardGeometry, cardMaterial); + + // Calculate angle using correct formula: αᵢ = -θ/2 + (i / (N - 1)) * θ + const alpha = N > 1 ? -theta/2 + (i / (N - 1)) * theta : 0; + + // Apply fanning formula relative to opponent position + const fanX = R * Math.sin(alpha); + const fanZ = -R * Math.cos(alpha) + R; + + if (opponentPosition.x !== 0) { + // Left or right opponent - rotate fan coordinates + cardMesh.position.set( + opponentPosition.x + fanZ * 0.3, + 0.5, + fanX + ); + cardMesh.rotation.y = opponentPosition.baseRotation + alpha; + } else { + // Top opponent - fan along X axis + cardMesh.position.set( + fanX, + 0.5, + opponentPosition.z - fanZ * 0.3 + ); + cardMesh.rotation.y = opponentPosition.baseRotation + alpha; + } + + // Add slight tilt and render order for overlap + cardMesh.rotation.x = -Math.PI / 15; + cardMesh.renderOrder = i; + + cardGroup.add(cardMesh); + } + + this.scene.add(cardGroup); + + // Create monkey head avatar behind the cards + const monkeyTexture = this.createMonkeyTexture(); + const avatarGeometry = new THREE.CircleGeometry(1.5, 32); + const avatarMaterial = new THREE.MeshStandardMaterial({ + map: monkeyTexture, + transparent: true, + side: THREE.DoubleSide, + }); + const avatar = new THREE.Mesh(avatarGeometry, avatarMaterial); + + // Position avatar behind the cards based on opponent position + if (opponentPosition.x !== 0) { + // Left or right opponent + avatar.position.set( + opponentPosition.x + (opponentPosition.x > 0 ? 1.5 : -1.5), + 1.5, + 0 + ); + avatar.rotation.y = opponentPosition.baseRotation; + } else { + // Top opponent + avatar.position.set( + 0, + 1.5, + opponentPosition.z + (opponentPosition.z > 0 ? 1.5 : -1.5) + ); + avatar.rotation.y = opponentPosition.baseRotation; + } + + this.opponentAvatars[playerId] = avatar; + this.scene.add(avatar); + + // Create name label sprite above the avatar (if name is provided) + if (playerName) { + const nameLabel = this.createNameLabelSprite(playerName); + + // Position label above the avatar + // Sprite will automatically billboard (face camera) + if (opponentPosition.x !== 0) { + // Left or right opponent + nameLabel.position.set( + opponentPosition.x + (opponentPosition.x > 0 ? 1.5 : -1.5), + 3.5, // Above the avatar + 0 + ); + } else { + // Top opponent + nameLabel.position.set( + 0, + 3.5, // Above the avatar + opponentPosition.z + (opponentPosition.z > 0 ? 1.5 : -1.5) + ); + } + + this.opponentNameLabels[playerId] = nameLabel; + this.scene.add(nameLabel); + } + } + + public async addTrickCard(card: Card, playerIndex: number): Promise { + // Position cards in the center based on player position, laid flat on table + const positions = [ + new THREE.Vector3(0, 0.11, 2), // South (current player) + new THREE.Vector3(-2, 0.11, 0), // West + new THREE.Vector3(0, 0.11, -2), // North + new THREE.Vector3(2, 0.11, 0), // East + ]; + + const position = positions[playerIndex % 4]; + const card3D = new Card3D(card, position); + + // Cards are already rotated to lay flat in the geometry + // No additional rotation needed - cards lay flat on table + + this.currentTrickCards.push(card3D); + this.scene.add(card3D.mesh); + } + + public async playCardWithAnimation(card: Card, playerIndex: number, card3D?: Card3D): Promise { + // Mark that we're animating a card play + this.isAnimatingCardPlay = true; + + try { + let cardToAnimate: Card3D; + + if (card3D) { + // Use the provided Card3D object (prevents race conditions) + cardToAnimate = card3D; + // Remove it from playerCards if it's still there + const cardIndex = this.playerCards.indexOf(card3D); + if (cardIndex !== -1) { + this.playerCards.splice(cardIndex, 1); + } + } else { + // Find the card in playerCards (fallback for backward compatibility) + const cardIndex = this.playerCards.findIndex(c => + c.card.rank === card.rank && c.card.suit === card.suit + ); + + if (cardIndex === -1) { + console.error('Card not found in playerCards:', card); + return; + } + + // Get the card3D object + cardToAnimate = this.playerCards[cardIndex]; + + // Remove from playerCards array (but don't dispose or remove from scene yet) + this.playerCards.splice(cardIndex, 1); + } + + // Add to currentTrickCards IMMEDIATELY (before animation) + // This prevents race conditions where other players' notifications + // think it's a new trick while our animation is running + this.currentTrickCards.push(cardToAnimate); + + // Get target position for the trick + const trickPositions = [ + new THREE.Vector3(0, 0.11, 2), // South (current player) + new THREE.Vector3(-2, 0.11, 0), // West + new THREE.Vector3(0, 0.11, -2), // North + new THREE.Vector3(2, 0.11, 0), // East + ]; + const targetPosition = trickPositions[playerIndex % 4]; + + // Animate the card to the trick position + await cardToAnimate.animateToPosition(targetPosition, 500); + + // Rearrange remaining player cards + this.rearrangePlayerCards(); + } finally { + // Always clear the animation flag, even if there was an error + this.isAnimatingCardPlay = false; + } + } + + public async animateTrickToWinner(winnerPosition: number, delay: number = 1000): Promise { + if (this.currentTrickCards.length === 0) return; + + // Save the cards to animate and clear the array IMMEDIATELY + // This prevents new trick cards from being cleared with the old ones + const cardsToAnimate = [...this.currentTrickCards]; + this.currentTrickCards = []; + console.log(`🎬 Starting trick animation with ${cardsToAnimate.length} cards. currentTrickCards cleared.`); + + // Mark that we're animating + this.isAnimatingTrick = true; + + try { + // Determine target position based on winner + let targetPosition: THREE.Vector3; + + switch (winnerPosition) { + case 0: // South (current player) + targetPosition = new THREE.Vector3(0, 0.5, 6); + break; + case 1: // West (left) + targetPosition = new THREE.Vector3(-6, 0.5, 0); + break; + case 2: // North (across) + targetPosition = new THREE.Vector3(0, 0.5, -6); + break; + case 3: // East (right) + targetPosition = new THREE.Vector3(6, 0.5, 0); + break; + default: + targetPosition = new THREE.Vector3(0, 0.5, 0); + } + + // Wait for the delay to let players see the trick + await new Promise(resolve => setTimeout(resolve, delay)); + + // Animate all saved trick cards to the winner's position + const animations = cardsToAnimate.map((card, index) => { + // Slightly offset each card so they stack + const offset = new THREE.Vector3( + (Math.random() - 0.5) * 0.3, + index * 0.05, + (Math.random() - 0.5) * 0.3 + ); + const finalPosition = targetPosition.clone().add(offset); + return card.animateToPosition(finalPosition, 500); + }); + + // Wait for all animations to complete + await Promise.all(animations); + + // Wait a bit more so players can see where the cards went + await new Promise(resolve => setTimeout(resolve, 500)); + + // Dispose of the animated cards + console.log(`🗑️ Disposing ${cardsToAnimate.length} animated trick cards`); + cardsToAnimate.forEach(card => { + this.scene.remove(card.mesh); + card.dispose(); + }); + } finally { + // Always mark animation as complete, even if there was an error + this.isAnimatingTrick = false; + console.log('✅ Trick animation complete'); + } + } + + public isAnimating(): boolean { + return this.isAnimatingTrick || this.isAnimatingCardPlay; + } + + public clearTrick(): void { + console.log(`🗑️ Clearing trick (${this.currentTrickCards.length} cards)`); + this.currentTrickCards.forEach(card => { + this.scene.remove(card.mesh); + card.dispose(); + }); + this.currentTrickCards = []; + } + + public clearPlayerCards(): void { + this.playerCards.forEach(card => { + this.scene.remove(card.mesh); + card.dispose(); + }); + this.playerCards = []; + this.selectedCards = []; + } + + public clearOpponentCards(): void { + Object.keys(this.opponentCards).forEach(playerId => { + this.scene.remove(this.opponentCards[playerId]); + this.opponentCards[playerId].clear(); + }); + this.opponentCards = {}; + + // Also clear avatars + Object.keys(this.opponentAvatars).forEach(playerId => { + this.scene.remove(this.opponentAvatars[playerId]); + this.opponentAvatars[playerId].geometry.dispose(); + if (this.opponentAvatars[playerId].material instanceof THREE.Material) { + this.opponentAvatars[playerId].material.dispose(); + } + }); + this.opponentAvatars = {}; + + // Also clear name labels + Object.keys(this.opponentNameLabels).forEach(playerId => { + this.scene.remove(this.opponentNameLabels[playerId]); + this.opponentNameLabels[playerId].material.map?.dispose(); + this.opponentNameLabels[playerId].material.dispose(); + }); + this.opponentNameLabels = {}; + } + + public removePlayerCard(card: Card): void { + const index = this.playerCards.findIndex(c => + c.card.rank === card.rank && c.card.suit === card.suit + ); + + if (index !== -1) { + const card3D = this.playerCards[index]; + this.scene.remove(card3D.mesh); + card3D.dispose(); + this.playerCards.splice(index, 1); + + // Rearrange remaining cards + this.rearrangePlayerCards(); + } + } + + private rearrangePlayerCards(): void { + const N = this.playerCards.length; // number of cards + const cardSpacing = 1.3; // horizontal spacing - same as addPlayerCards + const baseZ = 5; // base z position - same as addPlayerCards + + this.playerCards.forEach((card, i) => { + // Position cards in a horizontal row + const startX = -(N - 1) * cardSpacing / 2; + const x = startX + i * cardSpacing; + + const targetPosition = new THREE.Vector3(x, card.mesh.position.y, baseZ); + + // Animate position + card.animateToPosition(targetPosition, 300); + + // Update render order + setTimeout(() => { + card.mesh.renderOrder = i; + }, 150); + }); + } + + public getSelectedCards(): Card3D[] { + return this.selectedCards; + } + + public clearSelection(): void { + this.selectedCards.forEach(card => card.setSelected(false)); + this.selectedCards = []; + } + + private onMouseMove(event: MouseEvent): void { + // Calculate mouse position in normalized device coordinates + this.mouse.x = (event.clientX / window.innerWidth) * 2 - 1; + this.mouse.y = -(event.clientY / window.innerHeight) * 2 + 1; + + // Update raycaster + this.raycaster.setFromCamera(this.mouse, this.camera); + + // Check for intersections with player cards + const playerMeshes = this.playerCards.map(c => c.mesh); + const intersects = this.raycaster.intersectObjects(playerMeshes, true); + + if (intersects.length > 0) { + const intersectedGroup = intersects[0].object.parent; + const card = intersectedGroup?.userData.card as Card3D; + + if (card && card !== this.hoveredCard) { + if (this.hoveredCard) { + this.hoveredCard.setHovered(false); + } + this.hoveredCard = card; + this.hoveredCard.setHovered(true); + } + } else { + if (this.hoveredCard) { + this.hoveredCard.setHovered(false); + this.hoveredCard = null; + } + } + } + + private onClick(event: MouseEvent): void { + // Calculate mouse position + this.mouse.x = (event.clientX / window.innerWidth) * 2 - 1; + this.mouse.y = -(event.clientY / window.innerHeight) * 2 + 1; + + // Update raycaster + this.raycaster.setFromCamera(this.mouse, this.camera); + + // Check for intersections with player cards + const playerMeshes = this.playerCards.map(c => c.mesh); + const intersects = this.raycaster.intersectObjects(playerMeshes, true); + + if (intersects.length > 0) { + const intersectedGroup = intersects[0].object.parent; + const card = intersectedGroup?.userData.card as Card3D; + + if (card) { + this.handleCardSelection(card); + if (this.onCardClick) { + this.onCardClick(card); + } + } + } + } + + private handleCardSelection(card: Card3D): void { + const index = this.selectedCards.indexOf(card); + + if (index !== -1) { + // Deselect + this.selectedCards.splice(index, 1); + card.setSelected(false); + } else { + // Select (limit to 3 for passing phase) + if (this.selectedCards.length < 3) { + this.selectedCards.push(card); + card.setSelected(true); + } + } + } + + private onWindowResize(): void { + const width = window.innerWidth; + const height = window.innerHeight; + + // Update camera aspect ratio + this.camera.aspect = width / height; + + // Adjust camera position based on aspect ratio to keep scene in view + // For narrow screens (portrait), move camera back more + // For wide screens (landscape), keep camera closer + const baseDistance = 14; + const aspectRatio = width / height; + + if (aspectRatio < 1) { + // Portrait mode - move camera back more + this.camera.position.set(0, 10, baseDistance * (1.5 / aspectRatio)); + } else { + // Landscape mode - normal distance + this.camera.position.set(0, 10, baseDistance); + } + + this.camera.lookAt(0, 0, 0); + this.camera.updateProjectionMatrix(); + + // Update renderer size + this.renderer.setSize(width, height); + this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); + } + + private animate(): void { + requestAnimationFrame(this.animate.bind(this)); + this.renderer.render(this.scene, this.camera); + } + + public dispose(): void { + window.removeEventListener('resize', this.onWindowResize.bind(this)); + this.renderer.domElement.removeEventListener('mousemove', this.onMouseMove.bind(this)); + this.renderer.domElement.removeEventListener('click', this.onClick.bind(this)); + this.renderer.dispose(); + } +} diff --git a/web-clients/hearts/src/main.ts b/web-clients/hearts/src/main.ts new file mode 100644 index 00000000..402946db --- /dev/null +++ b/web-clients/hearts/src/main.ts @@ -0,0 +1,171 @@ +import { CardScene } from './graphics/CardScene'; +import { GameUI } from './ui/GameUI'; +import { HeartsGame } from './game/HeartsGame'; + +// Generate a GUID (UUID v4) +function generateGuid(): string { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { + const r = Math.random() * 16 | 0; + const v = c === 'x' ? r : (r & 0x3 | 0x8); + return v.toString(16); + }); +} + +// Initialize the application +function init() { + console.log('Initializing Hearts Web Client...'); + + // Get canvas container + const canvasContainer = document.getElementById('canvas-container'); + if (!canvasContainer) { + console.error('Canvas container not found!'); + return; + } + + // Initialize graphics scene + const scene = new CardScene(canvasContainer); + console.log('3D scene initialized'); + + // Initialize UI + const ui = new GameUI(); + console.log('UI initialized'); + + // Initialize game controller + const game = new HeartsGame(scene, ui); + console.log('Game controller initialized'); + + // UI state management + const createGameBtn = document.getElementById('create-game-btn'); + const joinGameBtn = document.getElementById('join-game-btn'); + const joinSection = document.getElementById('join-section'); + const createdGameSection = document.getElementById('created-game-section'); + const connectBtn = document.getElementById('connect-btn'); + const createdGameIdInput = document.getElementById('created-game-id') as HTMLInputElement; + const copyGameIdBtn = document.getElementById('copy-game-id-btn'); + const connectToCreatedBtn = document.getElementById('connect-to-created-btn'); + + let currentGameId = ''; + + // Show join section + joinGameBtn?.addEventListener('click', () => { + if (joinSection) joinSection.style.display = 'block'; + if (createdGameSection) createdGameSection.style.display = 'none'; + }); + + // Create game button + createGameBtn?.addEventListener('click', async () => { + const playerNameInput = document.getElementById('player-name') as HTMLInputElement; + const playerName = playerNameInput.value.trim(); + + if (!playerName) { + ui.setConnectionStatus('Please enter your name'); + return; + } + + try { + ui.setConnectionStatus('Creating game...'); + if (createGameBtn) (createGameBtn as HTMLButtonElement).disabled = true; + + const serverUrl = 'ws://localhost:13992'; + const gameId = await game.createGame(serverUrl, playerName); + + currentGameId = gameId; + if (createdGameIdInput) createdGameIdInput.value = gameId; + + if (joinSection) joinSection.style.display = 'none'; + if (createdGameSection) createdGameSection.style.display = 'block'; + + ui.setConnectionStatus('Game created successfully!'); + console.log('Game created with ID:', gameId); + } catch (error) { + console.error('Failed to create game:', error); + ui.setConnectionStatus('Failed to create game: ' + (error instanceof Error ? error.message : String(error))); + } finally { + if (createGameBtn) (createGameBtn as HTMLButtonElement).disabled = false; + } + }); + + // Copy game ID button + copyGameIdBtn?.addEventListener('click', () => { + if (createdGameIdInput) { + createdGameIdInput.select(); + navigator.clipboard.writeText(createdGameIdInput.value).then(() => { + const originalText = copyGameIdBtn.textContent; + copyGameIdBtn.textContent = 'Copied!'; + setTimeout(() => { + copyGameIdBtn.textContent = originalText; + }, 2000); + }); + } + }); + + // Connect to created game + connectToCreatedBtn?.addEventListener('click', async () => { + const playerNameInput = document.getElementById('player-name') as HTMLInputElement; + const playerName = playerNameInput.value.trim(); + + if (!playerName) { + ui.setConnectionStatus('Please enter your name'); + return; + } + + const playerId = generateGuid(); + const serverUrl = 'ws://localhost:13992'; + + console.log('Connection details:'); + console.log('- Server URL:', serverUrl); + console.log('- Player ID:', playerId); + console.log('- Player Name:', playerName); + console.log('- Game ID:', currentGameId); + + try { + await game.connect(serverUrl, playerId, playerName, currentGameId); + } catch (error) { + console.error('Failed to connect:', error); + } + }); + + // Join existing game button + connectBtn?.addEventListener('click', async () => { + const inputs = ui.getConnectionInputs(); + + // Trim whitespace from inputs + const playerName = inputs.playerName.trim(); + const gameId = inputs.gameId.trim(); + + if (!playerName || !gameId) { + ui.setConnectionStatus('Please fill in all fields'); + return; + } + + // Generate player ID and use default server URL + const playerId = generateGuid(); + const serverUrl = 'ws://localhost:13992'; + + console.log('Connection details:'); + console.log('- Server URL:', serverUrl); + console.log('- Player ID:', playerId); + console.log('- Player Name:', playerName); + console.log('- Game ID:', gameId); + + try { + await game.connect( + serverUrl, + playerId, + playerName, + gameId + ); + } catch (error) { + console.error('Failed to connect:', error); + } + }); + + console.log('Hearts Web Client ready!'); +} + +// Wait for DOM to be ready +if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', init); +} else { + init(); +} diff --git a/web-clients/hearts/src/ui/GameUI.ts b/web-clients/hearts/src/ui/GameUI.ts new file mode 100644 index 00000000..cb01519f --- /dev/null +++ b/web-clients/hearts/src/ui/GameUI.ts @@ -0,0 +1,159 @@ +export class GameUI { + private connectionPanel: HTMLElement; + private gameInfo: HTMLElement; + private messageDisplay: HTMLElement; + private statusElement: HTMLElement; + + private roundNumberEl: HTMLElement; + private playerScoreEl: HTMLElement; + private totalScoreEl: HTMLElement; + private passDirectionEl: HTMLElement; + private turnStatusEl: HTMLElement; + private connectionStatusEl: HTMLElement; + + private devLog: HTMLElement; + private devLogContent: HTMLElement; + private currentTrickNumber: number = 0; + + constructor() { + this.connectionPanel = document.getElementById('connection-panel')!; + this.gameInfo = document.getElementById('game-info')!; + this.messageDisplay = document.getElementById('message-display')!; + this.statusElement = document.getElementById('status')!; + + this.roundNumberEl = document.getElementById('round-number')!; + this.playerScoreEl = document.getElementById('player-score')!; + this.totalScoreEl = document.getElementById('total-score')!; + this.passDirectionEl = document.getElementById('pass-direction')!; + this.turnStatusEl = document.getElementById('turn-status')!; + this.connectionStatusEl = document.getElementById('connection-status')!; + + this.devLog = document.getElementById('dev-log')!; + this.devLogContent = document.getElementById('dev-log-content')!; + + // Setup clear button + const clearButton = document.getElementById('dev-log-clear')!; + clearButton.addEventListener('click', () => this.clearDevLog()); + } + + public showConnectionPanel(): void { + this.connectionPanel.classList.remove('hidden'); + this.gameInfo.classList.add('hidden'); + } + + public hideConnectionPanel(): void { + this.connectionPanel.classList.add('hidden'); + this.gameInfo.classList.remove('hidden'); + } + + public setConnectionStatus(message: string): void { + this.connectionStatusEl.textContent = message; + } + + public updateGameInfo(data: { + roundNumber?: number; + playerScore?: number; + totalScore?: number; + passDirection?: string; + isMyTurn?: boolean; + }): void { + if (data.roundNumber !== undefined) { + this.roundNumberEl.textContent = data.roundNumber.toString(); + } + if (data.playerScore !== undefined) { + this.playerScoreEl.textContent = data.playerScore.toString(); + } + if (data.totalScore !== undefined) { + this.totalScoreEl.textContent = data.totalScore.toString(); + } + if (data.passDirection !== undefined) { + this.passDirectionEl.textContent = `Pass: ${data.passDirection}`; + } + if (data.isMyTurn !== undefined) { + this.turnStatusEl.textContent = data.isMyTurn ? "Your turn!" : "Waiting..."; + this.turnStatusEl.style.color = data.isMyTurn ? '#4caf50' : '#666'; + } + } + + public setStatus(message: string): void { + this.statusElement.textContent = message; + } + + public showMessage(message: string, duration: number = 3000): void { + this.messageDisplay.textContent = message; + this.messageDisplay.classList.add('show'); + + setTimeout(() => { + this.messageDisplay.classList.remove('show'); + }, duration); + } + + public getConnectionInputs(): { + playerName: string; + gameId: string; + } { + return { + playerName: (document.getElementById('player-name') as HTMLInputElement).value, + gameId: (document.getElementById('game-id') as HTMLInputElement).value, + }; + } + + public setConnectButtonEnabled(enabled: boolean): void { + const button = document.getElementById('connect-btn') as HTMLButtonElement; + button.disabled = !enabled; + } + + public showDevLog(): void { + this.devLog.classList.remove('hidden'); + } + + public hideDevLog(): void { + this.devLog.classList.add('hidden'); + } + + public clearDevLog(): void { + this.devLogContent.innerHTML = ''; + this.currentTrickNumber = 0; + } + + public logNewTrick(trickNumber: number): void { + const entry = document.createElement('div'); + entry.className = 'log-entry log-trick-header'; + entry.textContent = `=== Trick ${trickNumber} ===`; + this.devLogContent.appendChild(entry); + this.currentTrickNumber = trickNumber; + this.scrollToBottom(); + } + + public logCardPlay(playerName: string, card: string): void { + const entry = document.createElement('div'); + entry.className = 'log-entry log-card-play'; + entry.textContent = `${playerName} played ${card}`; + this.devLogContent.appendChild(entry); + this.scrollToBottom(); + } + + public logTrickResult(winnerName: string, winningCard: string, points: number): void { + const entry = document.createElement('div'); + entry.className = 'log-entry log-trick-result'; + entry.textContent = `→ Winner: ${winnerName} with ${winningCard} (+${points} pts)`; + this.devLogContent.appendChild(entry); + this.scrollToBottom(); + } + + public logRoundEnd(roundNumber: number): void { + const entry = document.createElement('div'); + entry.className = 'log-entry'; + entry.style.color = '#ff00ff'; + entry.style.fontWeight = 'bold'; + entry.style.marginTop = '12px'; + entry.style.marginBottom = '12px'; + entry.textContent = `========== Round ${roundNumber} Ended ==========`; + this.devLogContent.appendChild(entry); + this.scrollToBottom(); + } + + private scrollToBottom(): void { + this.devLogContent.scrollTop = this.devLogContent.scrollHeight; + } +} diff --git a/web-clients/hearts/tsconfig.json b/web-clients/hearts/tsconfig.json new file mode 100644 index 00000000..49ddc508 --- /dev/null +++ b/web-clients/hearts/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "target": "ES2020", + "useDefineForClassFields": true, + "module": "ESNext", + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "skipLibCheck": true, + + /* Bundler mode */ + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + + /* Linting - relaxed for generated code */ + "strict": false, + "noUnusedLocals": false, + "noUnusedParameters": false, + "noFallthroughCasesInSwitch": true, + + /* Path mapping */ + "baseUrl": ".", + "paths": { + "@generated/*": ["../../generated/typescript/*"] + } + }, + "include": ["src/**/*"] +} diff --git a/web-clients/hearts/vite.config.ts b/web-clients/hearts/vite.config.ts new file mode 100644 index 00000000..1350bd39 --- /dev/null +++ b/web-clients/hearts/vite.config.ts @@ -0,0 +1,15 @@ +import { defineConfig } from 'vite'; +import { resolve } from 'path'; + +export default defineConfig({ + resolve: { + alias: { + '@generated': resolve(__dirname, '../../generated/typescript'), + }, + }, + publicDir: 'assets', + server: { + port: 3000, + open: true, + }, +});