diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index dc11d60..a841b69 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -16,6 +16,7 @@ concurrency: env: CARGO_TERM_COLOR: always DEBIAN_FRONTEND: noninteractive + RUSTFLAGS: "-Ctarget-cpu=generic" jobs: test: diff --git a/Cargo.toml b/Cargo.toml index a834598..07b6d6b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ name = "LP" version = "0.1.0" edition = "2024" description = "A systemic 2D platformer in a dynamic living ecosystem.." -license = "Apache-2.0" +license = "MIT OR Apache-2.0" [workspace] members = [ diff --git a/LICENSE b/LICENSE index 261eeb9..0e3e26e 100644 --- a/LICENSE +++ b/LICENSE @@ -1,201 +1,6 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ +Licensed under either of - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION +- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0) +- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT) - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. +at your option. diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..adec22c --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Eremat + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index b4d377d..cc243d7 100644 --- a/README.md +++ b/README.md @@ -1,28 +1,42 @@ # ![Life's Progress Logo](/logo.png) -[![Discord](https://img.shields.io/discord/1177787606432489564?label=Discord&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/u2J25aGy8c) -[![CI](https://github.com/bevyengine/bevy/workflows/CI/badge.svg)](https://github.com/erematorg/LP/actions) +[![License](https://img.shields.io/badge/license-MIT%2FApache-blue.svg)](#license) +[![CI](https://github.com/erematorg/LP/workflows/CI/badge.svg)](https://github.com/erematorg/LP/actions) +[![Discord](https://img.shields.io/discord/1177787606432489564.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/u2J25aGy8c) -A systemic 2D platformer where life emerges from fundamental physics within a dynamic ecosystem. +A systemic 2D platformer in progress with an evolving simulation framework at its core. --- -## About the Project +## What is LP? -*Life's Progress (LP)* is a systemic 2D platformer where players explore an intricately simulated living ecosystem. Unlike traditional games, LP builds life and environments from first principles - atoms form molecules, molecules form cells, and cells evolve into organisms. The world evolves dynamically through physics and chemistry, without direct player intervention shaping its development. +*Life's Progress (LP)* is a systemic 2D platformer in progress with an evolving simulation framework at its core. Unlike traditional games, LP aims to build life and environments from first principles - atoms form molecules, molecules form cells, and cells evolve into organisms. The world evolves dynamically through physics and chemistry, with systems implemented incrementally and validated over time. Over time, parts of the framework may be reusable as standalone tools, but LP remains a game first. Players will witness the rise and fall of species, the balance between organisms, and the subtle interdependencies that drive the progression of life in a dynamic world. Rather than controlling the world, players experience it from within, potentially inhabiting different creatures to explore survival from various perspectives. -## Core Philosophy +## Status + +LP is early-stage and in active development. The simulation crates are active and evolving; gameplay systems are still forming, APIs can change without notice, and some systems are prototypes or partial implementations. + +## Design Goals LP is built on several foundational principles that set it apart: - **True Emergence**: Life and behaviors arise naturally from basic physical and chemical systems rather than being scripted -- **Unified Simulation**: All systems (physics, chemistry, biology, ecology) interact within a single coherent framework +- **Unified Simulation (in progress)**: Systems are designed to interoperate in one framework, but not all subsystems are fully wired yet - **Perspective-Based Experience**: Players experience the world from within, rather than playing as omnipotent manipulators - **Persistent Consequences**: Actions have lasting impacts on a world that evolves organically over time - **Scientific Authenticity**: Based on real principles of biology, ecology, and physics, simplified only where necessary +## Simulation Scope + +LP is a real-time simulation framework for games that may grow into a standalone toolkit, grounded in experimentally verified physical laws and SI units, with LP-0 approximations for real-time performance. + +- **Physics laws**: Newton, Coulomb, Fourier (and related IRL relations) are the basis for forces and transfers. +- **Explicit approximations**: LP-0 uses pairwise interactions, cutoffs, softening, and explicit integration for performance, all documented in code and docs. +- **Scope & roadmap**: LP-0 is not a continuum or quantum solver; higher-fidelity grid PDEs and MPM methods are planned. +- **Honesty goal**: Scientifically honest mechanics where shortcuts are explicit and gameplay abstractions are not presented as physics. + ## Features - **Realistic Ecosystem Simulation**: An immersive environment that evolves based on population dynamics, climate factors, and terrain deformations. @@ -31,7 +45,7 @@ LP is built on several foundational principles that set it apart: - **Bottom-Up Dynamics**: Matter and energy systems that build organically from fundamental forces to complex organisms. - **Multi-Scale Experience**: Explore life from microscopic to macroscopic levels, each with unique survival challenges. -## Documentation +## Docs For detailed information about *Life's Progress*, including gameplay mechanics, controls, and insights into the underlying ecosystem dynamics, check out our [official wiki](https://wiki.lifesprogress.com/). The documentation will guide you through the game's complex systems and help you get the most out of your experience. @@ -50,3 +64,12 @@ We welcome contributions from the community in several ways: - [Report bugs](https://github.com/erematorg/LP/issues/new?template=bug_report.yml) - [Suggest new features](https://github.com/erematorg/LP/issues/new?template=feature_request.yml) - [Browse existing issues](https://github.com/erematorg/LP/issues) + +## License + +LP is dual-licensed under either: + +- MIT License (`LICENSE-MIT` or http://opensource.org/licenses/MIT) +- Apache License, Version 2.0 (`LICENSE-APACHE` or http://www.apache.org/licenses/LICENSE-2.0) + +at your option. diff --git a/crates/energy/Cargo.toml b/crates/energy/Cargo.toml index f38fd8b..e8f58cc 100644 --- a/crates/energy/Cargo.toml +++ b/crates/energy/Cargo.toml @@ -3,7 +3,10 @@ name = "energy" version = "0.1.0" edition = "2024" description = "Core systems governing how energy manifests, transforms and flows." +license = "MIT OR Apache-2.0" [dependencies] bevy = "0.18" +forces = { path = "../forces" } +matter = { path = "../matter" } utils = { path = "../utils" } diff --git a/crates/energy/README.md b/crates/energy/README.md index 325d70c..b486663 100644 --- a/crates/energy/README.md +++ b/crates/energy/README.md @@ -4,9 +4,14 @@ Energy conservation, thermodynamics, electromagnetism, and wave mechanics for LP ## Scope and units - Tracks energy in joules via an accounting ledger; conservation is enforced where modeled. -- Thermodynamics, EM, and waves modules are present but remain partial scaffolds. +- Thermodynamics, EM, and waves modules are present but remain partial implementations. - Uses consistent sim units (SI-style); couple to time/space steps used by the broader sim. +## Scope & Limits +- LP-0 thermodynamics and EM use explicit approximations: pairwise interactions, cutoffs, and quasi-static assumptions for performance. +- Wave solvers use finite differences and simplified damping models; energy coupling is partial. +- Thermal energy uses constant heat capacity and clamps temperatures at 0 K; phase change and EOS are deferred. + ## Not yet implemented - **Wave/EM energy accounting**: Wave damping exists but not coupled to energy ledger; EM fields exist but no work/energy tracking. - **EOS, convection, latent heat, phase transitions**: Deferred to matter/MPM coupling (see tmp/GD/Systems_Overview.md). diff --git a/crates/energy/src/electromagnetism/charges.rs b/crates/energy/src/electromagnetism/charges.rs new file mode 100644 index 0000000..34acd5f --- /dev/null +++ b/crates/energy/src/electromagnetism/charges.rs @@ -0,0 +1,222 @@ +//! Coulomb forces between point charges. +//! +//! **LP-0 SCAFFOLDING**: Particle-particle Coulomb interactions. +//! Future: Will be replaced by grid-based Poisson solve (ρ → φ → E). +//! +//! Physics: F = k·q₁·q₂/r² (Coulomb's law) +//! Complexity: O(N) with SpatialGrid +//! Conservation: Force-only (EM potential energy = 0 for LP-0) + +use bevy::prelude::*; +use forces::core::newton_laws::AppliedForce; +use std::collections::HashMap; +use utils::{SpatiallyIndexed, UnifiedSpatialIndex, force_switch}; + +/// Electric charge component. +/// +/// Units: Coulombs (C) +/// +/// **LP-0 assumption**: Point charges for validation. +/// Future: Replace with charge density fields on grid. +#[derive(Component, Debug, Clone, Copy, Reflect)] +#[reflect(Component)] +pub struct Charge { + /// Charge value in Coulombs. + /// + /// Positive = proton-like, Negative = electron-like. + pub value: f32, +} + +impl Charge { + pub fn new(value: f32) -> Self { + Self { value } + } + + pub fn positive(value: f32) -> Self { + Self { value: value.abs() } + } + + pub fn negative(value: f32) -> Self { + Self { + value: -value.abs(), + } + } +} + +/// Softening length for singularity avoidance. +/// +/// **Property-based**: No hardcoded epsilon values. +/// When r < softening_length, force is smoothly reduced to avoid 1/r² singularity. +/// +/// Units: meters (m) +#[derive(Component, Debug, Clone, Copy, Reflect)] +#[reflect(Component)] +pub struct SofteningLength { + /// Minimum distance for force calculation. + /// + /// Typically ~0.01m for particle-scale simulations. + pub value: f32, +} + +impl Default for SofteningLength { + fn default() -> Self { + Self { value: 0.01 } + } +} + +/// Configuration for Coulomb force system. +#[derive(Resource, Debug, Clone)] +pub struct CoulombConfig { + /// Coulomb constant k = 1/(4πε₀). + /// + /// **UNITS**: Newtons × meters² / Coulombs² (N·m²/C²) + /// **Default**: 8.99×10⁹ N·m²/C² (vacuum permittivity ε₀ = 8.854×10⁻¹² F/m) + /// **IRL PHYSICS**: k = 8.987551792×10⁹ N·m²/C² (exact) + pub coulomb_constant: f32, + + /// Cutoff radius for Coulomb interactions. + /// + /// **UNITS**: meters (m) + /// **PERFORMANCE APPROXIMATION**: IRL Coulomb has infinite range in vacuum. + /// Cutoff is computational approximation, not physics. + /// **Default**: 20m (tunable based on system density and interaction scales) + pub cutoff_radius: f32, + + /// Start of force-switch transition. + /// + /// **UNITS**: meters (m) + /// **Default**: 0.8 × cutoff_radius (C¹ smooth cutoff for numerical stability) + pub switch_on_radius: f32, +} + +impl Default for CoulombConfig { + fn default() -> Self { + let cutoff = 20.0; + Self { + coulomb_constant: 8.99e9, // N⋅m²/C² + cutoff_radius: cutoff, + switch_on_radius: 0.8 * cutoff, + } + } +} + +/// Mark charged entities for spatial indexing. +/// +/// **Phase A2**: Inject SpatiallyIndexed marker for UnifiedSpatialIndex. +/// This allows utils crate to manage spatial indexing without depending on Charge. +pub fn mark_charged_entities_spatially_indexed( + mut commands: Commands, + q: Query, Without)>, +) { + for e in q.iter() { + commands.entity(e).insert(SpatiallyIndexed); + } +} + +/// Apply Coulomb electrostatic forces between charged particles. +/// +/// **LP-0 SCAFFOLDING**: Pairwise particle-particle Coulomb interactions (O(N) via spatial hash grid). +/// **TEMPORARY**: Will be replaced by grid-based Poisson solve (ρ → φ → E) in LP-1. +/// +/// **PHYSICS**: Coulomb's Law F = k·q₁·q₂/r² (Newtons) +/// - F: Force magnitude (N) +/// - k: Coulomb constant = 8.99×10⁹ N·m²/C² (vacuum permittivity) +/// - q₁, q₂: Charges (Coulombs) +/// - r: Distance (meters) +/// - Direction: Along line between charges (repulsive if same sign, attractive if opposite) +/// +/// **APPROXIMATIONS**: +/// - Cutoff radius: 20m default (performance hack, IRL Coulomb has infinite range in vacuum) +/// - Softening: 0.01m default (singularity avoidance for r→0) +/// - Potential energy: Not tracked (force-only, PE = 0 in LP-0) +/// - Pair-once guarantee: Only processes pairs where entity_b.index() > entity_a.index() to avoid double-counting +/// +/// **CONSERVATION**: Momentum conserved (F_ab = -F_ba, Newton's 3rd law). +/// Energy NOT conserved (PE missing from accounting). +pub fn apply_coulomb_pairwise_forces( + mut charges: Query<( + Entity, + &Charge, + &Transform, + Option<&SofteningLength>, + &mut AppliedForce, + )>, + index: Res, + config: Res, +) { + // **LP-0 SCAFFOLDING**: Pairwise particle-particle Coulomb forces. + // Future: Grid-based Poisson solve (ρ → φ → E). + + // Stage charges into map to avoid nested query + let mut charge_data: HashMap = HashMap::new(); + for (entity, charge, trans, softening, _) in charges.iter() { + let pos = trans.translation.truncate(); + + // No silent defaults: require SofteningLength + let Some(soft) = softening else { + #[cfg(debug_assertions)] + panic!( + "Entity {:?} missing SofteningLength for Coulomb forces", + entity + ); + + #[cfg(not(debug_assertions))] + { + static LOGGED: std::sync::atomic::AtomicBool = + std::sync::atomic::AtomicBool::new(false); + if !LOGGED.swap(true, std::sync::atomic::Ordering::Relaxed) { + warn!("Skipping charged entities missing SofteningLength (logged once)"); + } + continue; + } + }; + + charge_data.insert(entity, (charge.value, pos, soft.value)); + } + + // Iterate pairs via UnifiedSpatialIndex + for (entity_a, (charge_a, pos_a, soft_a)) in charge_data.iter() { + // Find neighbors within cutoff using UnifiedSpatialIndex (O(N) average) + for entity_b in index.query_radius(*pos_a, config.cutoff_radius) { + // **Pair-once guarantee**: Only process pairs where B > A + if entity_b.index() <= entity_a.index() { + continue; + } + + // Get data for entity B from staged map + let Some((charge_b, pos_b, soft_b)) = charge_data.get(&entity_b) else { + continue; + }; + + let r_vec = *pos_b - *pos_a; + let r = r_vec.length(); + + // Property-based softening: use max of the two particles' softening lengths + let softening = soft_a.max(*soft_b); + if r < softening || r >= config.cutoff_radius { + continue; + } + + // Coulomb force: F = k·q₁·q₂/r² + let k_qq = config.coulomb_constant * charge_a * charge_b; + let force_magnitude = k_qq / r.powi(2); + let force_bare = (force_magnitude / r) * r_vec; // F_bare = (k·q₁·q₂/r²) · r̂ + + // Apply C¹ force-switch for smooth cutoff + let switch = force_switch(r, config.switch_on_radius, config.cutoff_radius); + let force_2d = force_bare * switch; + let force = force_2d.extend(0.0); // Convert to Vec3 for AppliedForce + + // Apply forces symmetrically (Newton's 3rd law) + if let Ok((_, _, _, _, mut force_a)) = charges.get_mut(*entity_a) { + force_a.force += force; + } + if let Ok((_, _, _, _, mut force_b)) = charges.get_mut(entity_b) { + force_b.force -= force; // F_ba = -F_ab + } + + // **LP-0**: EM potential energy = 0 (force-only). + // Future: Track U(r) = integral of switched force for energy conservation. + } + } +} diff --git a/crates/energy/src/electromagnetism/interactions.rs b/crates/energy/src/electromagnetism/interactions.rs index ff3e8b1..b116451 100644 --- a/crates/energy/src/electromagnetism/interactions.rs +++ b/crates/energy/src/electromagnetism/interactions.rs @@ -3,7 +3,7 @@ use bevy::prelude::*; use super::fields::{ElectricField, MagneticField}; // Speed of light (in m/s) constant physical value -//TODO: Making this cleaner later on to make units of measure dynamic rather than admiting 1 meter = 1 meter, same for seconds and much more +// TODO: Units are fixed to SI for now; make unit scaling configurable. const C: f32 = 299_792_458.0; /// Represents an electromagnetic wave component diff --git a/crates/energy/src/electromagnetism/mod.rs b/crates/energy/src/electromagnetism/mod.rs index 6374b17..da7c450 100644 --- a/crates/energy/src/electromagnetism/mod.rs +++ b/crates/energy/src/electromagnetism/mod.rs @@ -1,20 +1,49 @@ +pub mod charges; pub mod fields; pub mod interactions; use bevy::prelude::*; +use forces::PhysicsSet; +use forces::core::gravity::GravitySet; +use utils::SpatialIndexSet; // NOTE: Charge is NOT conserved; EM is quasi-static (no charge continuity equation). // Ref: .claude/skills/lp-physics-chem-invariants/references/em.md + +// **LP-0 APPROXIMATION**: Quasi-static EM (v << c, no wave propagation). +// Future: Grid-based Poisson solve + wave equation if needed. pub struct ElectromagnetismPlugin; impl Plugin for ElectromagnetismPlugin { fn build(&self, app: &mut App) { - app.register_type::() + app + // LP-0: Coulomb forces between point charges (using UnifiedSpatialIndex) + .init_resource::() + .register_type::() + .register_type::() + // Marker injection in PreUpdate + .add_systems( + PreUpdate, + charges::mark_charged_entities_spatially_indexed + .in_set(SpatialIndexSet::InjectMarkers), + ) + // Coulomb forces in Update, in force accumulation, after gravity + .add_systems( + Update, + charges::apply_coulomb_pairwise_forces + .in_set(PhysicsSet::AccumulateForces) + .after(GravitySet::NBodyGravity), + ) + // Keep field components for visualization + .register_type::() .register_type::() .register_type::() .register_type::() - .add_message::() - .add_systems(Update, fields::calculate_field_interactions); + .add_message::(); + + // **DISABLED**: Field-field interactions violate Maxwell's equations. + // Fields don't interact with each other (they superpose linearly). + // .add_systems(Update, fields::calculate_field_interactions); } } @@ -22,6 +51,7 @@ impl Plugin for ElectromagnetismPlugin { /// /// This includes the most common types for electromagnetic systems. pub mod prelude { + pub use crate::electromagnetism::charges::{Charge, CoulombConfig, SofteningLength}; pub use crate::electromagnetism::fields::{ElectricField, MagneticField}; pub use crate::electromagnetism::interactions::{ElectromagneticWave, MaterialProperties}; } diff --git a/crates/energy/src/thermodynamics/equilibrium.rs b/crates/energy/src/thermodynamics/equilibrium.rs index 56aff39..3dcb994 100644 --- a/crates/energy/src/thermodynamics/equilibrium.rs +++ b/crates/energy/src/thermodynamics/equilibrium.rs @@ -11,7 +11,7 @@ pub struct ThermalEquilibrium { /// Component for phase state of matter that will use the matter crate later once implemented, soon once PBMPM will be in place /// and the matter crate is implemented -/// This is a placeholder for the actual phase state representation +/// Stub phase state representation until matter integration is ready. #[derive(Component, Debug, Clone, Copy, PartialEq, Eq, Reflect)] #[reflect(Component)] pub enum PhaseState { diff --git a/crates/energy/src/thermodynamics/mod.rs b/crates/energy/src/thermodynamics/mod.rs index 55996a7..7ac9396 100644 --- a/crates/energy/src/thermodynamics/mod.rs +++ b/crates/energy/src/thermodynamics/mod.rs @@ -35,7 +35,7 @@ pub mod prelude { validate_equilibrium_group_consistency, }; pub use super::thermal::{ - Temperature, ThermalConductivity, ThermalDiffusivity, HeatCapacity, + HeatCapacity, Temperature, ThermalConductivity, ThermalDiffusivity, thermal_utils::heat_conduction, }; } diff --git a/crates/energy/src/thermodynamics/thermal.rs b/crates/energy/src/thermodynamics/thermal.rs index 5ce6a24..d7f0603 100644 --- a/crates/energy/src/thermodynamics/thermal.rs +++ b/crates/energy/src/thermodynamics/thermal.rs @@ -1,8 +1,50 @@ use bevy::prelude::*; -use utils::{GridCell, SpatialGrid}; +use forces::PhysicsSet; +use forces::core::newton_laws::Mass; +use matter::geometry::Radius; +use std::collections::HashMap; +use utils::{SpatialIndexSet, SpatiallyIndexed, UnifiedSpatialIndex, force_switch}; + +use crate::conservation::{EnergyQuantity, EnergyType}; -#[derive(Resource, Deref, DerefMut)] -pub(crate) struct ThermalGrid(SpatialGrid); +/// Configuration for Fourier conduction system. +/// +/// **LP-0 SCAFFOLDING**: Pairwise particle-particle approximation. +/// Future: Grid-based diffusion PDE (∇·(k∇T) = ρc_p ∂T/∂t). +#[derive(Resource, Debug, Clone, Reflect)] +#[reflect(Resource)] +pub struct ThermalConductionConfig { + /// Cutoff radius for thermal transfer (meters). + /// **PERFORMANCE APPROXIMATION**: IRL heat conduction has no cutoff. + /// **Units**: meters (m) + pub cutoff_radius: f32, + + /// Force-switch start radius (meters). + /// **PERFORMANCE APPROXIMATION**: C¹ smooth cutoff for numerical stability. + /// **Units**: meters (m) + pub switch_on_radius: f32, + + /// CFL safety factor (dimensionless). For dt ≤ safety × dx²/α. + /// **Units**: dimensionless + pub cfl_safety_factor: f32, + + /// Effective thermal conductivity for LP-0 pairwise conduction. + /// **Units**: Watts / (meter × Kelvin) (W/(m·K)) + /// **Note**: Scaffold parameter. Future: per-material property in continuum/PDE. + pub thermal_conductivity_w_per_m_k: f32, +} + +impl Default for ThermalConductionConfig { + fn default() -> Self { + let cutoff = 10.0; + Self { + cutoff_radius: cutoff, + switch_on_radius: 0.8 * cutoff, + cfl_safety_factor: 0.5, + thermal_conductivity_w_per_m_k: 1.0, // Explicit default, SI documented + } + } +} // Physical constants pub const STEFAN_BOLTZMANN: f32 = 5.67e-8; // W/(m²·K⁴) @@ -145,110 +187,206 @@ pub struct ThermalTransferEvent { pub heat_flow: f32, } -use std::collections::HashMap; - -fn update_thermal_grid( - mut grid: ResMut, - mut query: Query<(Entity, &Transform, &mut GridCell), (With, Changed)>, -) { - for (entity, transform, mut cell) in query.iter_mut() { - let position = transform.translation.truncate(); - let new_cell = grid.world_to_grid(position); - if new_cell != cell.cell { - grid.move_entity(entity, cell.cell, new_cell); - cell.cell = new_cell; - } - } -} - -fn attach_grid_cells_to_temperatures( +/// Mark thermal entities for spatial indexing. +/// +/// **Phase A2**: Inject SpatiallyIndexed marker for UnifiedSpatialIndex. +/// This allows utils crate to manage spatial indexing without depending on Temperature. +fn mark_thermal_entities_spatially_indexed( mut commands: Commands, - mut grid: ResMut, - query: Query<(Entity, &Transform), (With, Without)>, + q: Query, Without)>, ) { - for (entity, transform) in query.iter() { - let position = transform.translation.truncate(); - let cell = grid.world_to_grid(position); - grid.insert_in_cell(entity, cell); - commands.entity(entity).insert(GridCell { cell }); + for e in q.iter() { + commands.entity(e).insert(SpatiallyIndexed); } } -pub(crate) fn calculate_thermal_transfer( +/// Compute thermal transfer via Fourier's Law of conduction. +/// +/// **LP-0 SCAFFOLDING**: Pairwise particle-particle thermal conduction (O(N) via spatial hash grid). +/// **TEMPORARY**: Will be replaced by grid-based diffusion PDE (∇·(k∇T) = ρc_p ∂T/∂t) in LP-1. +/// +/// **PHYSICS**: Fourier's Law q = k·A·ΔT/d (W), Q = P·dt (J) +/// - q: Heat flux (Watts) = k·A·ΔT/d +/// - Q: Energy transferred (Joules) = q·dt +/// - k: Thermal conductivity (W/(m·K)) +/// - A: Contact area (m²) - assumes π·r² (spherical particles) +/// - ΔT: Temperature difference (K) +/// - d: Distance (m) +/// +/// **APPROXIMATIONS**: +/// - Cutoff radius: 10m default (performance hack, IRL heat conduction has no cutoff) +/// - Contact area: A = π·min(r₁,r₂)² (assumes spherical particles) +/// - Constant c_p: Heat capacity assumed independent of temperature +/// +/// **CONSERVATION**: Energy-symmetric (Q_out = Q_in), momentum conserved (no forces applied). +/// Not temperature-symmetric (hot bodies lose more than cold gain for same Q). +pub(crate) fn compute_fourier_conduction( mut commands: Commands, - grid: Res, + index: Res, + config: Res, time: Res