OpenFOAM solvers: when to use each one

OpenFOAM has many solvers, and several can simulate the same physical problem using different assumptions, numerical methods, or levels of complexity.

The trick is not to choose a solver based only on the geometry. Choose it based on the physics you need to simulate:

  • Is the flow steady or time-dependent?
  • Is the fluid incompressible or compressible?
  • Are you simulating water only, or water and air together?
  • Is the flow turbulent?
  • Are there heat transfer, chemical reactions, particles, or cavitation?
  • Do you need free-surface movement, such as a river or a falling water jet?

I’ll focus on practical engineering applications, including open-channel hydraulics, hydropower, pipes, and water structures, and distinguish solvers that overlap.

Main solver comparison

The following table covers widely used OpenFOAM solver families. Names can vary between OpenFOAM Foundation and OpenCFD releases, so verify the solver names available in your installed version.

SolverMain purposeWhen to use itConcrete exampleOverlap / limitation
simpleFoamSteady, incompressible flowWhen the flow can be approximated as time-independentFlow distribution through a pipe junctionOverlaps with pimpleFoam if the final flow is steady; cannot directly resolve moving free surfaces
pimpleFoamTransient, incompressible, single-phase flowWhen velocity and pressure change with timeStarting a pump or flow developing through a bendCan approach a steady solution; overlaps with simpleFoam
icoFoamTransient, incompressible, laminar flowLow-Reynolds-number flows where turbulence is negligibleSlow flow between platesOverlaps with pimpleFoam; typically intended for simpler laminar cases
simpleFoam + turbulence modelSteady turbulent flowEngineering flows with a stable mean flowHead loss through a manifoldSame solver can use different turbulence models, such as \(k\!-\!\omega\) SST
interFoamTransient, two immiscible incompressible fluids, VOFWhen a water–air interface moves or deformsA partially filled canal, a dam-break wave, or a falling water sheet entering a reservoirOverlaps with interIsoFoam and other VOF solvers
interIsoFoamTransient, two-phase VOF with an isoAdvector interface treatmentWhen a sharp, well-resolved interface is importantA water jet plunging into a tankOverlaps strongly with interFoam; availability depends on distribution/version
multiphaseEulerFoamMultiple interpenetrating fluid phasesGas–liquid flows with substantial dispersed bubbles or dropletsBubble-column reactor or aerated flowNot a direct replacement for VOF when the exact shape of a large free surface matters
compressibleInterFoamCompressible two-phase flowWhen compressibility of the phases is importantHigh-speed compressible gas–liquid interactionOverlaps with incompressible VOF for some cases, but has different governing assumptions
rhoPimpleFoamTransient, compressible single-phase flowWhen density changes significantly with pressure or temperatureHigh-speed gas flow through a nozzleOverlaps with rhoSimpleFoam for steady-flow objectives
rhoSimpleFoamSteady, compressible flowSteady gas dynamicsFlow through a compressible nozzleOverlaps with rhoPimpleFoam
sonicFoamTransient, compressible flow, including sonic effectsShock waves and high-speed gas dynamicsSupersonic flow over a wedgeOverlaps with other compressible solvers; check the specific solver’s formulation and version
buoyantSimpleFoamSteady buoyant heat-transfer flowNatural convection in a stable configurationAir circulation in a heated roomOverlaps with transient buoyant solvers
buoyantPimpleFoamTransient buoyant heat-transfer flowTime-dependent natural convectionCooling of a hot enclosureOverlaps with buoyantSimpleFoam when a steady state is eventually reached
chtMultiRegionFoamConjugate heat transferSimultaneous heat transfer in solids and fluidsHeat conducted through a pipe wall into flowing waterMore specialized than a single-region thermal solver
solidDisplacementFoamSolid deformationMechanical deformation of a solid under loadsDeflection of a loaded plateSolid mechanics rather than ordinary fluid flow; availability and capabilities vary by version
potentialFoamPotential-flow initialization or approximate flowGenerating an initial velocity field for some incompressible casesInitializing flow through a pipe before a more complete simulationNot a general substitute for Navier–Stokes solvers; does not resolve ordinary viscous flow physics
laplacianFoamDiffusion-type scalar equationSimple diffusion and educational test casesTemperature or concentration diffusion under a suitable scalar modelA scalar transport solver, not a general-purpose flow solver

More specialized solvers

SolverWhen to use itConcrete exampleOverlap / important distinction
pisoFoamTransient incompressible turbulent flow using PISOFlow fluctuations through a pipe bendOverlaps with pimpleFoam; PISO and PIMPLE differ in pressure–velocity correction strategy
shallowWaterFoamShallow-water equations, depth-averaged flowFlood propagation across a floodplainMuch cheaper than 3D CFD, but cannot resolve detailed vertical velocity or local turbulence
potentialFreeSurfaceFoamFree-surface flow using a simplified surface-height formulationSome wave and surface-flow problemsOverlaps with VOF approaches but does not resolve the interface in the same way
cavitatingFoamCavitation using a mixture modelVapor formation in a hydraulic turbine or valveDifferent from VOF free-surface flow; solver availability depends on the distribution
interPhaseChangeFoamTwo-phase interface tracking with phase changeCavitation or vapor formation with a VOF interfaceOverlaps with cavitation solvers, but its interface-capturing formulation differs
driftFluxFoamTwo-phase mixture with relative phase driftGas bubbles rising in a liquidMore economical than resolving every bubble individually
twoPhaseEulerFoamTwo interpenetrating phases with a dispersed phaseGas bubbles dispersed through waterOverlaps with multiphaseEulerFoam; phase count and models differ
multiphaseInterFoamMultiple immiscible fluids with resolved interfacesThree immiscible liquid layersOverlaps with interFoam, which is aimed at two phases
nonNewtonianIcoFoamTransient laminar non-Newtonian flowA shear-dependent fluid flowing through a channelOverlaps with other non-Newtonian-capable solvers, depending on version and model support
DPMFoamParticle-laden flow with coupled particle effectsSolid particles carried by a gas or liquidOverlaps with other Lagrangian-particle solvers; not the same as resolving each particle’s surface
MPPICFoamParticle-laden flow using the multiphase particle-in-cell approachDense particle transportOverlaps with DPMFoam; particularly useful for dense particle systems
sprayFoamGas flow containing a spray of liquid dropletsFuel injection or atomized liquid spraysOverlaps with other particle and multiphase approaches; designed for spray physics
reactingFoamFlow with chemical reactionsCombustion in a burnerOverlaps with other reacting solvers, depending on compressibility and chemistry requirements
fireFoamFire and reacting-flow applicationsFire spread and smoke movement in an enclosureMore specialized than a general reacting-flow solver
chtMultiRegionSimpleFoamSteady conjugate heat transferHeat transfer from a hot pipe to surrounding solidsOverlaps with chtMultiRegionFoam, which is transient
solidEquilibriumDisplacementFoamSteady linear-elastic solid deformationDeformation of a loaded structureOverlaps with transient solid mechanics solvers

The most important overlaps

simpleFoam vs pimpleFoam

Both can model incompressible turbulent flow.

  • Use simpleFoam when you want the converged, steady mean flow.
  • Use pimpleFoam when time-dependent effects matter, such as an oscillating jet or flow startup.

If the physical flow is genuinely unsteady, forcing a steady solution may hide important behavior.

interFoam vs interIsoFoam

Both represent two immiscible fluids, commonly water and air, with a VOF method.

  • interFoam is the conventional starting point for a moving water surface.
  • interIsoFoam uses the isoAdvector interface treatment, which can improve interface sharpness in suitable meshes and cases.

Neither automatically guarantees an accurate result. Mesh resolution, time step, interface transport and boundary conditions still matter.

interFoam vs shallowWaterFoam

  • interFoam resolves the 3D water–air interface and can calculate vertical flow structure.
  • shallowWaterFoam solves depth-averaged equations and is suited to large-area flood routing.

The second is generally more economical for large flood domains; the first is more suitable for local hydraulic structures where vertical motion is important.

rhoSimpleFoam vs rhoPimpleFoam

Both model compressible flow.

  • rhoSimpleFoam: steady compressible flow.
  • rhoPimpleFoam: transient compressible flow.

For ordinary low-speed water flow, compressibility is usually not the reason to choose between them.

Some guides for solver

This is the practical decision table I’d use for hydraulic engineering.

Your engineering problemRecommended starting solverWhy
Water flowing in a completely full pipesimpleFoamSteady, incompressible flow
Flow developing after opening a valvepimpleFoamTime-dependent flow
Water flowing in a canal with a moving free surfaceinterFoamCaptures water and air
Water falling 5 m into a reservoirinterFoamResolves the plunging water and reservoir free surface
Water jet entering a tank, with a sharp interface importantinterIsoFoam if availableAlternative VOF interface treatment
Flooding over a wide, shallow areashallowWaterFoamDepth-averaged calculation
Pressure-induced cavitation inside a pipe or turbineA suitable cavitation solver, such as cavitatingFoam where availableModels liquid–vapor phase change
Air bubbles dispersed in watermultiphaseEulerFoam or twoPhaseEulerFoamEulerian dispersed-phase modelling
Suspended sediment transported by waterA suitable particle or multiphase modelChoice depends on particle concentration, settling and coupling
Water flowing through a hot pipeA suitable thermal solver, or chtMultiRegionFoam if wall conduction mattersIncludes the required thermal physics
Flow around a rotating turbine runnerA suitable rotating-frame or dynamic-mesh solverAccounts for rotating machinery

#this post was written with assisted AI

Understanding Pressure in OpenFOAM

Cavitation occurs when the local static pressure in a liquid falls sufficiently low for vapour cavities to form and grow. It is an important consideration in hydraulic structures, pipelines, pumps, and hydropower turbines, where it can cause noise, vibration, surface erosion, and reduced hydraulic performance.

The simpleFoam solver normally uses kinematic pressure, denoted by p, rather than pressure expressed directly in pascals.

Kinematic pressure is defined as

p_k=\frac{p_{\mathrm{gauge}}}{\rho}

where:

  • p_k is the kinematic pressure, in \mathrm{m^2/s^2}.
  • p_{\mathrm{gauge}} is the gauge pressure, in \mathrm{Pa}.
  • \rho is the fluid density, in \mathrm{kg/m^3}.

For a constant-density, incompressible water simulation, the gauge pressure can be recovered using

p_{\mathrm{gauge}}=\rho p_k

Absolute pressure is calculated by adding the appropriate reference pressure:

\boxed{p_{\mathrm{abs}}=\rho p_k+p_{\mathrm{ref}}}

If the gauge pressure is referenced to atmospheric pressure, then

p_{\mathrm{abs}}=\rho p_k+p_{\mathrm{atm}}

At standard atmospheric conditions,

p_{\mathrm{atm}}=101325\ \mathrm{Pa}

Example calculation

Suppose the kinematic pressure is 2.0\ \mathrm{m^2/s^2}, the water density is 1000\ \mathrm{kg/m^3}, and the pressure reference is standard atmospheric pressure.

The gauge pressure is

p_{\mathrm{gauge}}=1000\times2.0=2000\ \mathrm{Pa}

The absolute pressure is

p_{\mathrm{abs}}=2000+101325

Therefore,

\boxed{p_{\mathrm{abs}}=103325\ \mathrm{Pa}}

Convert kinetic pressure to absolute pressure in ParaView

Absolute pressure can be calculated from the existing OpenFOAM results without rerunning the simulation, provided that the pressure reference and units are understood.

Follow these steps:

  1. Open the OpenFOAM results in ParaView.
  2. Select the dataset in the Pipeline Browser.
  3. Choose Filters → Alphabetical → Calculator.
  4. Set Result Array Name to p_absolute.
  5. Enter the following expression for water with constant density:
  6. 1000*p + 101325
  7. Click Apply.

The resulting field represents absolute pressure in pascals if p is kinematic pressure referenced to atmospheric gauge pressure and the water density is 1000\ \mathrm{kg/m^3}.

If the pressure field already contains pressure in pascals, do not multiply it by density. Instead, add the appropriate reference pressure only if the field is a gauge pressure.

Vapour Pressure and Saturation Pressure

Saturation vapour pressure and vapour pressure are often used interchangeably in engineering cavitation calculations when referring to the equilibrium vapour pressure of water at a specified temperature.

The saturation vapour pressure, p_{\mathrm{sat}}, is the pressure at which liquid water and its vapour can coexist in thermodynamic equilibrium at a given temperature.

Saturation vapour pressure increases with water temperature. Consequently, cavitation can occur at a higher absolute pressure when the water temperature is higher.

Approximate saturation vapour pressures for water are shown below.

Water temperatureSaturation vapour pressure (absolute)
0^\circ\mathrm{C}611\ \mathrm{Pa}
20^\circ\mathrm{C}2339\ \mathrm{Pa}
40^\circ\mathrm{C}7385\ \mathrm{Pa}
60^\circ\mathrm{C}19946\ \mathrm{Pa}
80^\circ\mathrm{C}47414\ \mathrm{Pa}
100^\circ\mathrm{C}101325\ \mathrm{Pa}

All values are absolute pressures. The value at 100^\circ\mathrm{C} corresponds approximately to the normal boiling point of water at standard atmospheric pressure.

Identifying potential cavitation regions

Cavitation risk can be assessed by comparing the local absolute static pressure with the saturation vapour pressure at the local water temperature.

The basic thermodynamic pressure criterion is

\boxed{p_{\mathrm{abs}}\leq p_{\mathrm{sat}}(T)}

When the local pressure approaches or falls below the saturation vapour pressure, vapour cavities may form or grow. However, the actual onset of cavitation also depends on dissolved gases, microscopic nuclei, turbulence, and transient pressure fluctuations.

Example: Water at 20^\circ\mathrm{C}

For water at 20^\circ\mathrm{C}, the saturation vapour pressure is approximately

p_{\mathrm{sat}}=2339\ \mathrm{Pa}

If the local absolute static pressure falls to approximately 2339\ \mathrm{Pa}, the flow reaches the equilibrium vapour-pressure threshold.

If the calculated pressure falls below this value, the location should be investigated as a potential cavitation region. Nevertheless, a pressure comparison alone does not prove that cavitation has started or predict the resulting cavity size.

Creating a pressure-margin field in ParaView

A useful way to visualize potential cavitation regions is to calculate the pressure margin relative to the saturation vapour pressure.

Define the pressure margin as:

p_margin=1000*p + 101325

The local absolute pressure is above the saturation vapour pressure. The calculated negative local pressure is below the saturation vapour pressure, indicating a potential cavitation condition that requires further investigation.

Limitations of Using simpleFoam

Although simpleFoam is useful for steady, incompressible flow calculations, it is a single-phase solver. It does not directly simulate the formation, transport, or collapse of vapour cavities.

Consequently, comparing the calculated absolute pressure with the saturation vapour pressure is a screening method. It can help identify potential cavitation-risk locations, but it cannot fully predict the inception or size and extent of cavitation.

#partly written with AI.

Verification of Varignon’s Theorem with symbolic calculation in python

Varignon’s Theorem, in mechanics, states that the moment of a force about a point is equal to the sum of the moments of the force’s components about the same point. In essence, it allows you to break down a force into simpler components, calculate the moments of those components, and then add those moments to find the total moment of the original force.

import sympy as sp
# 
# Define multiple symbols at the same time
r, x, y = sp.symbols('r x y')
g, t = sp.symbols('g t')
F, FX, FY = sp.symbols('F FX FY')


# Define an expression using all the symbols
F = sp.sqrt(FX**2+FY**2)
r = sp.sqrt(x**2+y**2)
g=sp.atan(FY/FX)
t=sp.atan(y/x)


moment=F*r*sp.cos(sp.pi/2-(g+t))

# Simplify the expression
# simplified_expr = sp.simplify(moment)

# Display the expression and its simplified form
print( sp.expand(moment))
print( sp.factor(moment))

exp=sp.simplify(moment)
print(exp )

exp=sp.simplify(exp)
print(exp )


exp=sp.simplify(exp)
print(exp )


exp=sp.simplify(exp)
print(exp )

Civil 3D , getting styles from other drawings.

There are various methods to pull styles from other drawings.

Method 1 :  Open both drawings then go to toolspace>settings.  Go to the drawing in which you want to bring the settings to (i.e. to the target drawings). Drag the settings from source drawing to target drawings.

civil3d1

Method 2:  One can use the _AttachReferenceTemplate command to pull style from other drawings.

Screenshot 2024-09-05 093120

Solar system animation in Javascript

This is a realistic animation of solar system that accounts for axial rotation, orbital inclination and time period of all planets. It has two viewports left one shows all the planets, right one has camera that follows the selected planet. Green plane is the orbital plane of earth and sun, this plane helps to visualize how far other planets from earth’s rotation plane.

imageSolar



    
    
  



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>3D Solar System with Two Viewports</title>
    <style>
        body { margin: 0; overflow: hidden; }
        #controls {
            position: absolute;
            top: 10px;
            left: 10px;
            z-index: 100;
            background-color: rgba(255, 255, 255, 0.8);
            padding: 10px;
            border-radius: 5px;
        }
        #controls label {
            display: block;
            margin-bottom: 5px;
        }
        #controls input, #controls select {
            width: 150px;
        }
        #container {
            display: flex;
            height: 100vh;
        }
        #mainViewport, #followViewport {
            width: 50%;
            height: 100%;
        }
    </style>
</head>
<body>
<div id="controls">
    <label for="cameraX">Camera X:</label>
    <input type="range" id="cameraX" min="-200" max="200" value="0" step="1">
    
    <label for="cameraY">Camera Y:</label>
    <input type="range" id="cameraY" min="-200" max="200" value="0" step="1">
    
    <label for="cameraZ">Camera Z:</label>
    <input type="range" id="cameraZ" min="10" max="300" value="100" step="1">

    <label for="togglePlane">Toggle Earth's Orbital Plane:</label>
    <input type="checkbox" id="togglePlane" checked>
    
    <label for="planetSelect">Select Planet:</label>
    <select id="planetSelect">
        <option value="0">Mercury</option>
        <option value="1">Venus</option>
        <option value="2">Earth</option>
        <option value="3">Mars</option>
        <option value="4">Jupiter</option>
        <option value="5">Saturn</option>
        <option value="6">Uranus</option>
        <option value="7">Neptune</option>
    </select>

    <label for="followCamera">Follow Selected Planet:</label>
    <input type="checkbox" id="followCamera">
</div>

<div id="container">
    <div id="mainViewport"></div>
    <div id="followViewport"></div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script>
// Scene, Cameras, Renderers
const scene = new THREE.Scene();
const mainCamera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const followCamera = new THREE.PerspectiveCamera(75, 1, 0.1, 1000);

const mainRenderer = new THREE.WebGLRenderer();
mainRenderer.setSize(window.innerWidth / 2, window.innerHeight);
document.getElementById('mainViewport').appendChild(mainRenderer.domElement);

const followRenderer = new THREE.WebGLRenderer();
followRenderer.setSize(window.innerWidth / 2, window.innerHeight);
document.getElementById('followViewport').appendChild(followRenderer.domElement);

// Light source
const light = new THREE.PointLight(0xffffff, 1.5, 1000);
light.position.set(0, 0, 0);
scene.add(light);

// Sun
const sunGeometry = new THREE.SphereGeometry(5, 32, 32);
const sunMaterial = new THREE.MeshBasicMaterial({ color: 0xffff00 });
const sun = new THREE.Mesh(sunGeometry, sunMaterial);
scene.add(sun);

// Planets data with rotation direction and inclination
const planets = [
    { name: 'Mercury', size: 0.5, distance: 10, speed: 0.04, tilt: 7, rotationSpeed: 0.01, rotationDirection: 1, inclination: 7.01 },
    { name: 'Venus', size: 1.2, distance: 15, speed: 0.03, tilt: 177.4, rotationSpeed: 0.002, rotationDirection: -1, inclination: 3.39 },
    { name: 'Earth', size: 1.3, distance: 20, speed: 0.02, tilt: 23.5, rotationSpeed: 0.01, rotationDirection: 1, inclination: 0 },
    { name: 'Mars', size: 0.7, distance: 25, speed: 0.017, tilt: 25, rotationSpeed: 0.01, rotationDirection: 1, inclination: 1.85 },
    { name: 'Jupiter', size: 3, distance: 35, speed: 0.013, tilt: 3, rotationSpeed: 0.02, rotationDirection: 1, inclination: 1.31 },
    { name: 'Saturn', size: 2.5, distance: 45, speed: 0.01, tilt: 26.7, rotationSpeed: 0.02, rotationDirection: 1, inclination: 2.49 },
    { name: 'Uranus', size: 2, distance: 55, speed: 0.007, tilt: 97.8, rotationSpeed: 0.015, rotationDirection: 1, inclination: 0.77 },
    { name: 'Neptune', size: 1.9, distance: 65, speed: 0.005, tilt: 28.3, rotationSpeed: 0.015, rotationDirection: 1, inclination: 1.77 }
];

const planetMeshes = [];

// Function to add latitude and longitude lines
function addLatLongLines(planetSize) {
    const latLongMaterial = new THREE.LineBasicMaterial({ color: 0x888888 });
    const latLongGeometry = new THREE.BufferGeometry();
    const positions = [];

    for (let lat = -80; lat <= 80; lat += 20) {
        const phi = (90 - lat) * (Math.PI / 180);
        const thetaStep = 10 * (Math.PI / 180);

        for (let theta = 0; theta <= 360; theta += 10) {
            const theta1 = theta * (Math.PI / 180);
            const theta2 = (theta + 10) * (Math.PI / 180);

            const x1 = planetSize * Math.sin(phi) * Math.cos(theta1);
            const y1 = planetSize * Math.cos(phi);
            const z1 = planetSize * Math.sin(phi) * Math.sin(theta1);

            const x2 = planetSize * Math.sin(phi) * Math.cos(theta2);
            const y2 = planetSize * Math.cos(phi);
            const z2 = planetSize * Math.sin(phi) * Math.sin(theta2);

            positions.push(x1, y1, z1, x2, y2, z2);
        }
    }

    for (let lon = 0; lon <= 360; lon += 10) {
        const theta = lon * (Math.PI / 180);
        const phiStep = 10 * (Math.PI / 180);

        for (let phi = 0; phi <= Math.PI; phi += phiStep) {
            const x1 = planetSize * Math.sin(phi) * Math.cos(theta);
            const y1 = planetSize * Math.cos(phi);
            const z1 = planetSize * Math.sin(phi) * Math.sin(theta);

            const x2 = planetSize * Math.sin(phi + phiStep) * Math.cos(theta);
            const y2 = planetSize * Math.cos(phi + phiStep);
            const z2 = planetSize * Math.sin(phi + phiStep) * Math.sin(theta);

            positions.push(x1, y1, z1, x2, y2, z2);
        }
    }

    latLongGeometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
    const latLongLines = new THREE.LineSegments(latLongGeometry, latLongMaterial);
    return latLongLines;
}

// Create planets with latitude and longitude lines
planets.forEach(planet => {
    const planetGeometry = new THREE.SphereGeometry(planet.size, 32, 32);
    const planetMaterial = new THREE.MeshLambertMaterial({ color: Math.random() * 0xffffff });
    const planetMesh = new THREE.Mesh(planetGeometry, planetMaterial);

    // Position the planet in its orbit, apply inclination
    planetMesh.position.x = Math.cos(THREE.Math.degToRad(planet.inclination)) * planet.distance;
    planetMesh.position.y = Math.sin(THREE.Math.degToRad(planet.inclination)) * planet.distance;
    planetMesh.rotation.z = THREE.Math.degToRad(planet.tilt);

    // Add latitude and longitude lines to the planet
    const latLongLines = addLatLongLines(planet.size);
    planetMesh.add(latLongLines);

    planetMeshes.push({
        mesh: planetMesh,
        speed: planet.speed,
        distance: planet.distance,
        rotationSpeed: planet.rotationSpeed * planet.rotationDirection,
        angle: Math.random() * Math.PI * 2
    });

    scene.add(planetMesh);
});

// Earth's orbital plane
const planeGeometry = new THREE.PlaneGeometry(100, 100);
const planeMaterial = new THREE.MeshBasicMaterial({ color: 0x00ff00, side: THREE.DoubleSide, transparent: true, opacity: 0.3 });
const orbitalPlane = new THREE.Mesh(planeGeometry, planeMaterial);
orbitalPlane.rotation.x = Math.PI / 2;
scene.add(orbitalPlane);

// Set up cameras
mainCamera.position.set(0, 0, 100);
followCamera.position.set(0, 0, 100);
followCamera.lookAt(0, 0, 0);

// State variables
let followPlanet = null;

// Animation loop
function animate() {
    requestAnimationFrame(animate);

    // Rotate planets around the Sun
    planetMeshes.forEach(planet => {
        planet.angle += planet.speed;
        planet.mesh.position.x = Math.cos(planet.angle) * planet.distance;
        planet.mesh.position.z = Math.sin(planet.angle) * planet.distance;

        // Rotate planet on its axis
        planet.mesh.rotation.y += planet.rotationSpeed;
    });

    // Update camera positions
    mainRenderer.render(scene, mainCamera);

    if (followPlanet !== null) {
        const selectedPlanet = planetMeshes[followPlanet];
        const planetMesh = selectedPlanet.mesh;
        followCamera.position.set(
            planetMesh.position.x + selectedPlanet.distance * Math.cos(planetMesh.rotation.y),
            planetMesh.position.y,
            planetMesh.position.z + selectedPlanet.distance * Math.sin(planetMesh.rotation.y)
        );
        followCamera.lookAt(planetMesh.position);
        followRenderer.render(scene, followCamera);
    } else {
        followRenderer.render(scene, followCamera);
    }
}

animate();

// Handle window resize
window.addEventListener('resize', () => {
    const width = window.innerWidth / 2;
    const height = window.innerHeight;
    mainRenderer.setSize(width, height);
    followRenderer.setSize(width, height);
    mainCamera.aspect = width / height;
    mainCamera.updateProjectionMatrix();
    followCamera.aspect = width / height;
    followCamera.updateProjectionMatrix();
});

// Camera control with sliders
document.getElementById('cameraX').addEventListener('input', function() {
    if (followPlanet === null) {
        mainCamera.position.x = parseFloat(this.value);
    }
});

document.getElementById('cameraY').addEventListener('input', function() {
    if (followPlanet === null) {
        mainCamera.position.y = parseFloat(this.value);
    }
});

document.getElementById('cameraZ').addEventListener('input', function() {
    if (followPlanet === null) {
        mainCamera.position.z = parseFloat(this.value);
    }
});

// Toggle Earth's orbital plane visibility
document.getElementById('togglePlane').addEventListener('change', function() {
    orbitalPlane.visible = this.checked;
});

// Handle planet selection
document.getElementById('planetSelect').addEventListener('change', function() {
    followPlanet = parseInt(this.value);
});

// Handle camera follow toggle
document.getElementById('followCamera').addEventListener('change', function() {
    if (this.checked) {
        // Enable follow mode
        const selectedPlanet = document.getElementById('planetSelect').value;
        followPlanet = parseInt(selectedPlanet);
    } else {
        // Disable follow mode
        followPlanet = null;
    }
});
</script>
</body>
</html>
Create your own website, free on WordPress.com.Create your own website.
Start free