Skip to content

Commit

Permalink
some cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
flo-bit committed Oct 3, 2024
1 parent 9d09e4c commit 46d0b9a
Show file tree
Hide file tree
Showing 11 changed files with 328 additions and 211 deletions.
3 changes: 2 additions & 1 deletion features.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
- [ ] different materials
- [ ] make vegetation sway in the wind
- [ ] make all random stuff dependent on seed
- [ ] instanced vegetation

### weather
- [ ] clouds
Expand Down Expand Up @@ -45,4 +46,4 @@
- [ ] tilt shift

## other
- [ ]
- [ ] walking on planet
15 changes: 14 additions & 1 deletion index.html
Original file line number Diff line number Diff line change
@@ -1,13 +1,24 @@
<!doctype html>
<html lang="en">

<head>
<title>three.js scaffold</title>
<script>
!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+".people (stub)"},o="capture identify alias people.set people.set_once set_config register register_once unregister opt_out_capturing has_opted_out_capturing opt_in_capturing reset isFeatureEnabled onFeatureFlags getFeatureFlag getFeatureFlagPayload reloadFeatureFlags group updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures getActiveMatchingSurveys getSurveys getNextSurveyStep onSessionId".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);
posthog.init('phc_1Q4q6SdTwvStnxFWbmdOIusLc5ve0u6Fk7WpsHPoAlD',{api_host:'https://eu.i.posthog.com', person_profiles: 'identified_only', persistence: 'memory'})
</script>

<title>tiny planets</title>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, user-scalable=no"
/>

<link
rel="icon"
href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🌎</text></svg>"
/>

<link rel="stylesheet" href="./index.css" />
</head>

Expand All @@ -21,6 +32,8 @@

<canvas id="root"></canvas>

<a class="absolute bottom-2 left-3 text-cyan-400 text-sm font-semibold hover:text-cyan-300 transition-colors duration-100" href="https://flo-bit.dev" target="_blank">made by flo-bit</a>

<script src="src/script.ts" type="module"></script>
</body>
</html>
9 changes: 7 additions & 2 deletions src/script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import { Planet } from "./worlds/planet";
import { Stars } from "./worlds/stars";
import { planetPresets } from "./worlds/presets";

const presets = ["beach", "forest", "snowForest"];

Expand Down Expand Up @@ -36,7 +37,7 @@ let sphereMaterial = new THREE.MeshStandardMaterial({
wireframe: true,
wireframeLinewidth: 10,
});
let planetMesh = new THREE.Mesh(sphereGeometry, sphereMaterial);
let planetMesh: THREE.Mesh = new THREE.Mesh(sphereGeometry, sphereMaterial);
scene.add(planetMesh);

const light = new THREE.DirectionalLight();
Expand Down Expand Up @@ -110,12 +111,16 @@ async function createPlanet(preset: string | undefined = undefined) {
console.time("planet");
const planet = new Planet({
detail: 50,
biome: { preset },
...planetPresets[preset],
});
let mesh = await planet.create();
scene.remove(planetMesh);
scene.add(mesh);
planetMesh = mesh;

// planetMesh.add(camera);
// planet.updatePosition(camera, new THREE.Vector3(0, 0, 1.1));

console.timeEnd("planet");
}

Expand Down
25 changes: 23 additions & 2 deletions src/worlds/biome.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export class Biome {

options: BiomeOptions;

vegetationPositions: Octree = new Octree();
vegetationPositions: Octree<VegetationItem> = new Octree();

constructor(opts: BiomeOptions = {}) {
if (opts.preset) {
Expand Down Expand Up @@ -150,10 +150,31 @@ export class Biome {
this.vegetationPositions.insert(position, item);
}

closestVegetationDistance(
position: Vector3,
radius: number,
): number | undefined {
const items = this.vegetationPositions.queryBoxXYZ(
position.x,
position.y,
position.z,
radius,
);
if (items.length === 0) return undefined;

let closest = Infinity;
for (const item of items) {
const distance = position.distanceTo(item);
if (distance < closest) closest = distance;
}

return closest < radius ? closest : undefined;
}

itemsAround(
position: Vector3,
radius: number,
): (Vector3 & { data: VegetationItem })[] {
): (Vector3 & { data?: VegetationItem })[] {
return this.vegetationPositions.query(position, radius);
}
}
28 changes: 28 additions & 0 deletions src/worlds/helper/helper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { BufferGeometry, Float32BufferAttribute } from "three";

export function createBufferGeometry(
positions: number[],
colors?: number[],
normals?: number[],
) {
const geometry = new BufferGeometry();
geometry.setAttribute(
"position",
new Float32BufferAttribute(new Float32Array(positions), 3),
);

if (colors) {
geometry.setAttribute(
"color",
new Float32BufferAttribute(new Float32Array(colors), 3),
);
}
if (normals) {
geometry.setAttribute(
"normal",
new Float32BufferAttribute(new Float32Array(normals), 3),
);
}

return geometry;
}
18 changes: 8 additions & 10 deletions src/worlds/helper/octree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,10 @@ export type OctreeOptions = {
capacity?: number;
};

export type Vector3Data = Vector3 & { data?: unknown };

export class Octree {
export class Octree<T = unknown> {
boundary: Box3;

points: Vector3[];
points: (Vector3 & { data?: T })[];

capacity: number;

Expand Down Expand Up @@ -113,7 +111,7 @@ export class Octree {

// returns array of points where
// distance between pos and point is less than dist
query(pos: Vector3Data, dist = 1): Vector3Data[] {
query(pos: Vector3 & { data?: T }, dist = 1): (Vector3 & { data?: T })[] {
const points = this.queryBoxXYZ(pos.x, pos.y, pos.z, dist);

return points.filter((p) => p.distanceTo(pos) < dist);
Expand All @@ -134,7 +132,7 @@ export class Octree {
return this.queryBox(box);
}

queryBox(box: Box3, found: Vector3Data[] = []) {
queryBox(box: Box3, found: (Vector3 & { data?: T })[] = []) {
found ??= [];

if (!box.intersectsBox(this.boundary)) return found;
Expand All @@ -156,16 +154,16 @@ export class Octree {
}

// insert point with optional data (sets vec.data = data)
insert(pos: Vector3Data, data: unknown = undefined) {
insert(pos: Vector3 & { data?: T }, data: T | undefined = undefined) {
return this.insertPoint(pos, data);
}

// vector3 free version
insertXYZ(x: number, y: number, z: number, data: unknown = undefined) {
insertXYZ(x: number, y: number, z: number, data: T | undefined = undefined) {
return this.insertPoint(new Vector3(x, y, z), data);
}

insertPoint(p: Vector3, data: unknown = undefined) {
insertPoint(p: Vector3, data: T | undefined = undefined) {
p = p.clone();

// @ts-expect-error - data is not a property of Vector3
Expand Down Expand Up @@ -281,7 +279,7 @@ export class Octree {
return boxes;
}

all(arr: Vector3Data[] = []) {
all(arr: (Vector3 & { data?: T })[] = []) {
arr ??= [];
for (const p of this.points) {
arr.push(p);
Expand Down
121 changes: 65 additions & 56 deletions src/worlds/materials/OceanCausticsMaterial.ts
Original file line number Diff line number Diff line change
@@ -1,64 +1,73 @@
import { MeshStandardMaterial } from "three";
import {
MeshStandardMaterial,
type MeshStandardMaterialParameters,
} from "three";
import { noise } from "./noise";

const oceansCausticMaterial = new MeshStandardMaterial({
vertexColors: true,
});
oceansCausticMaterial.onBeforeCompile = (shader) => {
const caustics = `
float caustics(vec4 vPos) {
// More intricate warping for marble patterns
// float warpFactor = 2.0;
// vec4 warpedPos = vPos * warpFactor + snoise(vPos * warpFactor * 0.5);
// vec4 warpedPos2 = warpedPos * warpFactor * 0.3 + snoise(warpedPos * warpFactor * 0.5 + vec4(0, 2, 4, 8)) + vPos;
export class PlanetMaterialWithCaustics extends MeshStandardMaterial {
constructor(parameters: MeshStandardMaterialParameters) {
super(parameters);

// // Modulate the color intensity based on the noise
// float vein = snoise(warpedPos2 * warpFactor) * snoise(warpedPos);
this.onBeforeCompile = (shader) => {
const caustics = `
float caustics(vec4 vPos) {
// More intricate warping for marble patterns
// float warpFactor = 2.0;
// vec4 warpedPos = vPos * warpFactor + snoise(vPos * warpFactor * 0.5);
// vec4 warpedPos2 = warpedPos * warpFactor * 0.3 + snoise(warpedPos * warpFactor * 0.5 + vec4(0, 2, 4, 8)) + vPos;
// // Modulate the color intensity based on the noise
// float vein = snoise(warpedPos2 * warpFactor) * snoise(warpedPos);
// float a = 1.0 - (sin(vein * 12.0) + 1.0) * 0.5;
// float diff = snoise(vPos * warpFactor);
// diff = diff * snoise(diff * vPos) * a;
// return vec3((diff));
vec4 warpedPos = vPos * 2.0 + snoise(vPos * 3.0);
vec4 warpedPos2 = warpedPos * 0.3 + snoise(warpedPos * 2.0 + vec4(0, 2, 4, 8)) + vPos;
float vein = snoise(warpedPos2) * snoise(warpedPos);
float a = 1.0 - (sin(vein * 2.0) + 1.0) * 0.5;
return snoise(vPos + warpedPos + warpedPos2) * a * 1.5;
}`;
shader.vertexShader =
`varying vec3 vPos;\n${shader.vertexShader}`.replace(
`#include <begin_vertex>`,
`#include <begin_vertex>\nvPos = position;`,
);

// float a = 1.0 - (sin(vein * 12.0) + 1.0) * 0.5;
// float diff = snoise(vPos * warpFactor);
// diff = diff * snoise(diff * vPos) * a;
// return vec3((diff));
shader.fragmentShader = `
uniform float time;
varying vec3 vPos;
${noise}
${caustics}
${shader.fragmentShader}`;

vec4 warpedPos = vPos * 2.0 + snoise(vPos * 3.0);
vec4 warpedPos2 = warpedPos * 0.3 + snoise(warpedPos * 2.0 + vec4(0, 2, 4, 8)) + vPos;
float vein = snoise(warpedPos2) * snoise(warpedPos);
float a = 1.0 - (sin(vein * 2.0) + 1.0) * 0.5;
shader.fragmentShader = shader.fragmentShader.replace(
"#include <color_fragment>",
`#include <color_fragment>
vec3 pos = vPos * 3.0;
float len = length(vPos);
// Fade in
float fadeIn = smoothstep(0.96, 0.985, len);
// Fade out
float fadeOut = 1.0 - smoothstep(0.994, 0.999, len);
float causticIntensity = fadeIn * fadeOut * 0.7;
diffuseColor.rgb = mix(diffuseColor.rgb, vec3(1.0), causticIntensity * smoothstep(0.0, 1.0, caustics(vec4(pos, time * 0.05))));
`,
);

return snoise(vPos + warpedPos + warpedPos2) * a * 1.5;
}`;
shader.vertexShader = `varying vec3 vPos;\n${shader.vertexShader}`.replace(
`#include <begin_vertex>`,
`#include <begin_vertex>\nvPos = position;`,
);
shader.uniforms.time = { value: 0 };
this.userData.shader = shader;
};
}

shader.fragmentShader = `
uniform float time;
varying vec3 vPos;
${noise}
${caustics}
${shader.fragmentShader}`;
update() {
if (this.userData.shader?.uniforms?.time) {
this.userData.shader.uniforms.time.value = performance.now() / 1000;
}
}
}

shader.fragmentShader = shader.fragmentShader.replace(
"#include <color_fragment>",
`#include <color_fragment>
vec3 pos = vPos * 3.0;
float len = length(vPos);
// Fade in
float fadeIn = smoothstep(0.96, 0.985, len);
// Fade out
float fadeOut = 1.0 - smoothstep(0.994, 0.999, len);
float causticIntensity = fadeIn * fadeOut * 0.7;
diffuseColor.rgb = mix(diffuseColor.rgb, vec3(1.0), causticIntensity * smoothstep(0.0, 1.0, caustics(vec4(pos, time * 0.05))));
`,
);

shader.uniforms.time = { value: 0 };
oceansCausticMaterial.userData.shader = shader;

// console.log("FRAGMENT", shader.fragmentShader);
// console.log();
// console.log("VERTEX", shader.vertexShader);
};

export default oceansCausticMaterial;
export default PlanetMaterialWithCaustics;
1 change: 0 additions & 1 deletion src/worlds/materials/noise.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,5 +118,4 @@ float snoise(vec4 v) {
m0 = m0 * m0;
m1 = m1 * m1;
return 49.0 * (dot(m0 * m0, vec3(dot(p0, x0), dot(p1, x1), dot(p2, x2))) + dot(m1 * m1, vec2(dot(p3, x3), dot(p4, x4))));
}`;
Loading

0 comments on commit 46d0b9a

Please sign in to comment.