[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-83964":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":14,"contributorsCount":15,"subscribersCount":15,"size":15,"stars1d":16,"stars7d":17,"stars30d":17,"stars90d":15,"forks30d":15,"starsTrendScore":18,"compositeScore":19,"rankGlobal":10,"rankLanguage":10,"license":20,"archived":21,"fork":21,"defaultBranch":22,"hasWiki":23,"hasPages":21,"topics":24,"createdAt":10,"pushedAt":10,"updatedAt":36,"readmeContent":37,"aiSummary":10,"trendingCount":15,"starSnapshotCount":15,"syncStatus":38,"lastSyncTime":39,"discoverSource":40},83964,"Neo3dEngine","IvanSobolev\u002FNeo3dEngine","IvanSobolev","A minimalist CPU-based 3D console engine in C# (.NET 8) built from scratch. Features Raycasting\u002FRaytracing, dynamic lighting & shadows, .obj loader, and custom TCP-based multiplayer with real-time chat. No external graphics APIs.","https:\u002F\u002Fyoutu.be\u002FvhYE882B9dE",null,"C#",422,4,3,0,48,224,320,2.1,"GNU General Public License v3.0",false,"main",true,[25,26,27,28,29,30,31,32,33,34,35],"3d-engine","console-app","csharp","custom-network-protocol","dotnet","game-engine","game-engine-3d","multiplayer","raycasting","raycasting-engine","tcp-socket","2026-06-12 02:04:36","# 💻 Neo 3D Console (C#)\n\n\u003Cimg width=\"2070\" height=\"1085\" alt=\"Image\" src=\"https:\u002F\u002Fgithub.com\u002Fuser-attachments\u002Fassets\u002F06934758-90d4-4b63-9f40-8bb44ca2831e\" \u002F>\n\nA minimalist 3D engine written in C# that runs entirely inside the system console. This project was built from scratch without any external graphical libraries or modern graphics APIs (like OpenGL or DirectX). Everything—from custom vector mathematics to ray casting\u002Ftracing and the TCP network stack—is computed entirely on the CPU.\n\nThis project was designed for educational and demonstration purposes for a [YouTube video](https:\u002F\u002Fyoutu.be\u002FvhYE882B9dE).\n\n---\n\n## 🚀 Key Features\n\n1. **CPU Raycasting \u002F Raytracing**:\n    * Renders polygonal meshes (`.obj` format) and geometric spheres.\n    * Intersection optimization using Bounding Sphere checks before performing detailed triangle intersection calculations.\n2. **Dynamic Lighting and Shadows**:\n    * Light intensity attenuation based on distance.\n    * Lambertian diffuse shading using surface normals.\n    * Real-time shadow rendering via Shadow Rays cast from intersection points back to light sources.\n3. **Multi-threaded Rendering**:\n    * Leverages `Parallel.For` to distribute pixel rendering calculations across all available CPU cores.\n4. **Optimized Console Output**:\n    * Map light intensity to a character gradient string (`\" .:!\u002Fr(l1Z4H9W8$@\"`) to simulate shading.\n    * Frame buffering with grouped-color output to minimize slow, native OS terminal print API calls.\n5. **Custom 3D Mathematics**:\n    * Custom implementations of `Vector3`, `Vector2`, `Ray`, and rotation matrices (Euler rotations around X, Y, and Z axes).\n    * Manual implementation of the Möller–Trumbore ray-triangle intersection algorithm.\n6. **Low-level Window Input**:\n    * Asynchronous, non-blocking keyboard polling using the Win32 API (`GetAsyncKeyState`), ensuring key presses are detected only when the console window is active.\n7. **Custom Network Multiplayer**:\n    * Client-server TCP network manager built from scratch.\n    * Custom binary packet serialization, routing via stable hash-based type IDs, and a decoupled event subscription model.\n    * Included multiplayer demo featuring real-time player position synchronization and a text-based chat lobby.\n\n---\n\n## 🏗️ Architecture Overview\n\nThe engine is decoupled into clear logical layers:\n\n```\n├── AbstractClass             # Base classes for GameObjects, Scenes, Screens, and Lights\n├── Implementation            # Concrete cameras, rendering managers, and screen renderers\n├── Interfaces                # Contracts for loose coupling (ICamera, IScreen, etc.)\n├── Shape                     # Geometric primitives (Sphere, Triangle, Object3D)\n├── StaticClass               # Helper utilities (ObjLoader, GameTime tracking)\n├── Structure                 # Core structs (Vectors, Rays, RenderData payload)\n├── UI                        # Overlay system for rendering text on top of the frame buffer\n└── Network                   # Networking layer (TCP Manager, Packet abstractions, Serializer)\n```\n\n### Core Architecture Components\n\n* **`Frame`**: The heart of the engine loop. It starts the cycle, updates the active scene's logic (`Update()`), triggers the screen renderer (`RenderFrame()`), prints FPS\u002Fdiagnostics, and tracks delta-time.\n* **`Screen` (ConsoleScreenAsync)**: Manages resolution buffers for brightness and color. Its `RenderFrame` implementation parallelizes the conversion of brightness values into gradient characters and presents the entire frame buffer to the console as grouped color chunks.\n* **`Scene`**: A container for world elements. It manages the active camera, light lists, UI elements, and renderable objects (`IDisplays`). It computes individual pixel states via `GetPixelData` on demand.\n* **`DisplaysManager`**: Calculates intersections, searching for the nearest object intersected by rays projected from the viewport.\n\n---\n\n## 📐 The Rendering Pipeline\n\nEvery frame is rendered using the following steps:\n\n1. **Ray Generation**:\n   The camera translates the 2D UV screen coordinates into a 3D direction vector in world space, adjusting for the camera's position and orientation (Pitch, Yaw, Roll).\n2. **Intersection \u002F Raycast**:\n   The ray is evaluated against all active objects in the scene via the `DisplayManager`:\n    * **Spheres**: Evaluated analytically using the quadratic formula for ray-sphere intersection.\n    * **Polygonal Objects (3D Models)**: First, a quick intersection check is run against the model's Bounding Sphere. If the ray hits the sphere, a detailed loop checks all individual triangles using the Möller–Trumbore algorithm.\n3. **Shading & Shadow Calculation**:\n   If an intersection is found, the engine calculates the light influence at that point:\n    * It determines the direction vector toward each light source.\n    * It calculates the dot product between the surface normal and the light direction (diffuse component).\n    * It casts a **Shadow Ray** from the intersection point toward the light. If another object intersects this shadow ray, the point is shaded as in shadow (brightness = 0).\n4. **Buffering & Output**:\n   The final light intensity is mapped to a character from the gradient array, buffered, and written out to the console terminal.\n\n---\n\n## 🌐 Custom TCP Network Protocol\n\nThe networking module is written on raw sockets (`TcpListener`\u002F`TcpClient`) with zero third-party dependencies.\n\n* **Network Packet Layout**:\n  Packets are serialized into a sequential byte array containing a 12-byte header followed by the payload data:\n  ```\n  [ Type ID (4 bytes) ] [ Sender ID (4 bytes) ] [ Payload Length (4 bytes) ] [  Payload Data (N bytes)  ]\n  ```\n* **Registration & Serialization (`PacketManager`)**:\n  Packets inherit `INetworkPacket` and implement custom `Serialize`\u002F`Deserialize` methods using `BinaryWriter`\u002F`BinaryReader`. They are mapped to unique integer IDs using a stable hashing function on the class name string.\n* **Event Dispatching**:\n  Scripts subscribe to specific packet types asynchronously using the manager: `PacketManager.Subscribe\u003CT>((packet, senderId) => { ... })`.\n\n---\n\n## 🛠️ Getting Started\n\nTo build and run this project, make sure you have the **.NET 8.0 SDK** (or newer) installed.\n\n### Step 1: File Setup\nOrganize the codebase according to the directory structure. Make sure you have a valid `.obj` model file (such as Blender's classic low-poly Suzanne — `monkey.obj`) located in your output execution directory.\n\n### Step 2: Build and Run\nNavigate to your project directory and run:\n```bash\ndotnet run --configuration Release\n```\n*(Running with the `Release` configuration is highly recommended to ensure maximum parallel performance on your CPU).*\n\n### Step 3: Multiplayer Setup\nWhen the console starts, choose your network role:\n1. Press **`S`** to host as a Server. The terminal will display your local IP and port. Share this with a client.\n2. On another machine (or another terminal instance), press **`C`** to connect as a Client, input the Server's IP address, and connect.\n\n### Default Controls:\n* **`W, A, S, D`** — Move camera (Forward, Left, Backward, Right).\n* **`Space` \u002F `Left Shift`** — Fly Up \u002F Down.\n* **Arrow Keys** — Look around (Pitch and Yaw rotations).\n* **`Ctrl` + `W, A, S, D, Space, Shift`** — Move the active light source.\n* **`+` \u002F `-`** — Increase \u002F Decrease light intensity.\n* **`T`** — Open multiplayer chat (Type message -> `Enter` to send, `Esc` to cancel).\n\n---\n\n## 📝 Creating a Custom Scene\n\nYou can create your own scene by inheriting from the base `Scene` class. Here is a simple example rendering a single red sphere illuminated by a light source:\n\n```csharp\nusing _3dEngine;\nusing _3dEngine.AbstractClass;\nusing _3dEngine.Implementation;\nusing _3dEngine.Interfaces;\nusing _3dEngine.Shape;\n\npublic class MyCustomScene : Scene\n{\n    private Camera _camera;\n    private Sphere _sphere;\n    private Light _light;\n\n    public MyCustomScene(IDisplaysManagerAsync manager) : base(manager) { }\n\n    public override void Start()\n    {\n        \u002F\u002F 1. Initialize and set up the camera\n        _camera = new Camera(new Vector3(0, 0, -5), Vector3.Zero);\n        SetMainCamera(_camera);\n\n        \u002F\u002F 2. Add a red sphere at the origin\n        _sphere = new Sphere(Vector3.Zero, Vector3.Zero, r: 1.5f);\n        _sphere.Color = ConsoleColor.Red;\n        AddDisplaysObject(_sphere);\n\n        \u002F\u002F 3. Add a light source pointing at the sphere\n        _light = new Light(new Vector3(-2, 3, -4), lightPower: 15f);\n        AddLight(_light);\n    }\n\n    public override void Update()\n    {\n        \u002F\u002F Add frame update logic here (e.g., rotate objects over time using GameTime.GetDeltaTime())\n    }\n}\n```\n\n[old repository](https:\u002F\u002Fgithub.com\u002FIvanSobolev\u002F3dEngine)\n",2,"2026-06-11 04:11:55","CREATED_QUERY"]