Skip to content

Instantly share code, notes, and snippets.

@trezy
Created January 19, 2022 19:27
Show Gist options
  • Save trezy/198769e749ad57f880020d277fe7354f to your computer and use it in GitHub Desktop.
Save trezy/198769e749ad57f880020d277fe7354f to your computer and use it in GitHub Desktop.
Pseudo code for generating a galaxy based on available mass determined by seed-based Perlin noise
// Local imports
import { STELLAR_CLASSES } from 'helpers/stellarClasses.js'
// The density at a point must be greater than this value for a star to be
// formed.
const DENSITY_THRESHHOLD_FOR_NEW_STAR = 0.2
// That maximum radius of the 3D grid in any direction
const MAXIMUM_SIZE = 10
const GALAXY = new Galaxy()
const SEED = generateSeed()
// Perlin noise should be returned as a 3d array (?) where each item indicates
// the noise density at that point.
const DENSITY_MAP = generatePerlinNoise(MAXIMUM_SIZE, SEED)
// Calculate the maximum/minimum density for all stars, plus the range between
// them. This will allow us to convert proportional density (0 - 1) into actual density.
const {
DENSITY_RANGE,
MAXIMUM_DENSITY,
MINIMUM_DENSITY,
} = Object
.values(STELLAR_CLASSES)
.reduce((accumulator, details) => {
accumulator.MAXIMUM_DENSITY = Math.max(accumulator.MAXIMUM_DENSITY, ...details.massRange)
accumulator.MINIMUM_DENSITY = Math.min(accumulator.MINIMUM_DENSITY, ...details.massRange)
accumulator.DENSITY_RANGE = accumulator.MAXIMUM_DENSITY - accumulator.MINIMUM_DENSITY
return accumulator
}, {
DENSITY_RANGE: 0,
MAXIMUM_DENSITY: 0,
MINIMUM_DENSITY: 0,
})
function generateStar(options) {
const {
proportionalDensity,
x,
y,
z,
} = options
Object
.entries(STELLAR_CLASSES)
.some(([type, details]) => {
const DENSITY = proportionalDensity * DENSITY_RANGE
// Check if density is above maximum range
if (DENSITY >= Math.max(details.massRange)) {
return false
}
// Check if density is below minimum range
if (DENSITY <= Math.min(details.massRange)) {
return false
}
// Generates a star with the following properties. All other properties
// should be able to be consistently derived from the star's mass and
// density.
GALAXY.createStar({
density: DENSITY,
type,
x,
y,
z,
})
return true
})
}
// Loop over every cell in the generated 3D grid and generate a star if the cell
// has the right conditions for doing so.
function generateStars(densityMap) {
let currentX = 0
let currentY = 0
let currentZ = 0
while (true) {
const PROPORTIONAL_DENSITY = densityMap[currentX][currentY][currentZ]
if (PROPORTIONAL_DENSITY >= DENSITY_THRESHHOLD_FOR_NEW_STAR) {
generateStar({
proportionalDensity: PROPORTIONAL_DENSITY,
x: currentX,
y: currentY,
z: currentZ,
})
}
}
}
generateStars(DENSITY_MAP)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment