init commit

This commit is contained in:
Silas 2024-04-30 18:59:39 -04:00
commit ef36a8ffa7
Signed by: silentsilas
GPG Key ID: 4199EFB7DAA34349
26 changed files with 4955 additions and 0 deletions

12
.editorconfig Normal file
View File

@ -0,0 +1,12 @@
root = true
[*]
end_of_line = lf
insert_final_newline = true
indent_style = tab
indent_size = 2
charset = utf-8
trim_trailing_whitespace = true
[package.json]
indent_style = space

13
.eslintignore Normal file
View File

@ -0,0 +1,13 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example
# Ignore files for PNPM, NPM and YARN
pnpm-lock.yaml
package-lock.json
yarn.lock

31
.eslintrc.cjs Normal file
View File

@ -0,0 +1,31 @@
/** @type { import("eslint").Linter.Config } */
module.exports = {
root: true,
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:svelte/recommended',
'prettier'
],
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
parserOptions: {
sourceType: 'module',
ecmaVersion: 2020,
extraFileExtensions: ['.svelte']
},
env: {
browser: true,
es2017: true,
node: true
},
overrides: [
{
files: ['*.svelte'],
parser: 'svelte-eslint-parser',
parserOptions: {
parser: '@typescript-eslint/parser'
}
}
]
};

10
.gitignore vendored Normal file
View File

@ -0,0 +1,10 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example
vite.config.js.timestamp-*
vite.config.ts.timestamp-*

1
.npmrc Normal file
View File

@ -0,0 +1 @@
engine-strict=true

4
.prettierignore Normal file
View File

@ -0,0 +1,4 @@
# Ignore files for PNPM, NPM and YARN
pnpm-lock.yaml
package-lock.json
yarn.lock

8
.prettierrc Normal file
View File

@ -0,0 +1,8 @@
{
"useTabs": true,
"singleQuote": true,
"trailingComma": "none",
"printWidth": 100,
"plugins": ["prettier-plugin-svelte"],
"overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
}

38
README.md Normal file
View File

@ -0,0 +1,38 @@
# create-svelte
Everything you need to build a Svelte project, powered by [`create-svelte`](https://github.com/sveltejs/kit/tree/main/packages/create-svelte).
## Creating a project
If you're seeing this, you've probably already done this step. Congrats!
```bash
# create a new project in the current directory
npm create svelte@latest
# create a new project in my-app
npm create svelte@latest my-app
```
## Developing
Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
```bash
npm run dev
# or start the server and open the app in a new browser tab
npm run dev -- --open
```
## Building
To create a production version of your app:
```bash
npm run build
```
You can preview the production build with `npm run preview`.
> To deploy your app, you may need to install an [adapter](https://kit.svelte.dev/docs/adapters) for your target environment.

4328
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

47
package.json Normal file
View File

@ -0,0 +1,47 @@
{
"name": "playground",
"version": "0.0.1",
"private": true,
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"test": "vitest",
"lint": "prettier --check . && eslint .",
"format": "prettier --write .",
"model-pipeline:run": "node scripts/model-pipeline.js"
},
"devDependencies": {
"@sveltejs/adapter-auto": "^3.0.0",
"@sveltejs/kit": "^2.0.0",
"@sveltejs/vite-plugin-svelte": "^3.0.0",
"@types/eslint": "^8.56.0",
"@typescript-eslint/eslint-plugin": "^7.0.0",
"@typescript-eslint/parser": "^7.0.0",
"eslint": "^8.56.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-svelte": "^2.35.1",
"prettier": "^3.1.1",
"prettier-plugin-svelte": "^3.1.2",
"svelte": "^4.2.7",
"svelte-check": "^3.6.0",
"tslib": "^2.4.1",
"typescript": "^5.0.0",
"vite": "^5.0.3",
"vitest": "^1.2.0",
"@types/three": "^0.159.0",
"@theatre/studio": "^0.7.1"
},
"type": "module",
"dependencies": {
"three": "^0.159.0",
"@threlte/core": "^7.3.0",
"@threlte/extras": "^8.11.2",
"@threlte/rapier": "^2.0.0",
"@dimforge/rapier3d-compat": "^0.11.2",
"@threlte/theatre": "^2.1.7",
"@theatre/core": "^0.7.1"
}
}

149
scripts/model-pipeline.js Normal file
View File

@ -0,0 +1,149 @@
import { execSync } from 'node:child_process'
import { readdirSync, copyFileSync, unlinkSync, mkdirSync, existsSync } from 'node:fs'
import { join, resolve } from 'node:path'
import { exit } from 'node:process'
/**
* This script is used to transform gltf and glb files into Threlte components.
* It uses the `@threlte/gltf` package to do so.
* It works in two steps:
* 1. Transform the gltf/glb files located in the sourceDir directory
* 2. Move the Threlte components to the targetDir directory
*/
const configuration = {
sourceDir: resolve(join('static', 'models')),
targetDir: resolve(join('src', 'lib', 'components', 'models')),
overwrite: false,
root: '/models/',
types: true,
keepnames: false,
meta: false,
shadows: false,
printwidth: 120,
precision: 2,
draco: null,
preload: false,
suspense: false,
isolated: false,
transform: {
enabled: false,
resolution: 1024,
simplify: {
enabled: false,
weld: 0.0001,
ratio: 0.75,
error: 0.001
}
}
}
// if the target directory doesn't exist, create it
mkdirSync(configuration.targetDir, { recursive: true })
// throw error if source directory doesn't exist
if (!existsSync(configuration.sourceDir)) {
throw new Error(`Source directory ${configuration.sourceDir} doesn't exist.`)
}
// read the directory, filter for .glb and .gltf files and files *not* ending
// with -transformed.gltf or -transformed.glb as these should not be transformed
// again.
const gltfFiles = readdirSync(configuration.sourceDir).filter((file) => {
return (
(file.endsWith('.glb') || file.endsWith('.gltf')) &&
!file.endsWith('-transformed.gltf') &&
!file.endsWith('-transformed.glb')
)
})
if (gltfFiles.length === 0) {
console.log('No gltf or glb files found.')
exit()
}
const filteredGltfFiles = gltfFiles.filter((file) => {
if (!configuration.overwrite) {
const componentFilename = file.split('.').slice(0, -1).join('.') + '.svelte'
const componentPath = join(configuration.targetDir, componentFilename)
if (existsSync(componentPath)) {
console.error(`File ${componentPath} already exists, skipping.`)
return false
}
}
return true
})
if (filteredGltfFiles.length === 0) {
console.log('No gltf or glb files to process.')
exit()
}
filteredGltfFiles.forEach((file) => {
// run the gltf transform command on every file
const path = join(configuration.sourceDir, file)
// parse the configuration
const args = []
if (configuration.root) args.push(`--root ${configuration.root}`)
if (configuration.types) args.push('--types')
if (configuration.keepnames) args.push('--keepnames')
if (configuration.meta) args.push('--meta')
if (configuration.shadows) args.push('--shadows')
args.push(`--printwidth ${configuration.printwidth}`)
args.push(`--precision ${configuration.precision}`)
if (configuration.draco) args.push(`--draco ${configuration.draco}`)
if (configuration.preload) args.push('--preload')
if (configuration.suspense) args.push('--suspense')
if (configuration.isolated) args.push('--isolated')
if (configuration.transform.enabled) {
args.push(`--transform`)
args.push(`--resolution ${configuration.transform.resolution}`)
if (configuration.transform.simplify.enabled) {
args.push(`--simplify`)
args.push(`--weld ${configuration.transform.simplify.weld}`)
args.push(`--ratio ${configuration.transform.simplify.ratio}`)
args.push(`--error ${configuration.transform.simplify.error}`)
}
}
const formattedArgs = args.join(' ')
// run the command
const cmd = `npx @threlte/gltf@latest ${path} ${formattedArgs}`
try {
execSync(cmd, {
cwd: configuration.sourceDir
})
} catch (error) {
console.error(`Error transforming model: ${error}`)
}
})
// read dir again, but search for .svelte files only.
const svelteFiles = readdirSync(configuration.sourceDir).filter((file) => file.endsWith('.svelte'))
svelteFiles.forEach((file) => {
// now move every file to /src/components/models
const path = join(configuration.sourceDir, file)
const newPath = join(configuration.targetDir, file)
copyFile: try {
// Sanity check, we checked earlier if the file exists. Still, the CLI takes
// a while, so who knows what happens in the meantime.
if (!configuration.overwrite) {
// check if file already exists
if (existsSync(newPath)) {
console.error(`File ${newPath} already exists, skipping.`)
break copyFile
}
}
copyFileSync(path, newPath)
} catch (error) {
console.error(`Error copying file: ${error}`)
}
// remove the file from /static/models
try {
unlinkSync(path)
} catch (error) {
console.error(`Error removing file: ${error}`)
}
})

13
src/app.d.ts vendored Normal file
View File

@ -0,0 +1,13 @@
// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface PageState {}
// interface Platform {}
}
}
export {};

12
src/app.html Normal file
View File

@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>

7
src/index.test.ts Normal file
View File

@ -0,0 +1,7 @@
import { describe, it, expect } from 'vitest';
describe('sum test', () => {
it('adds 1 + 2 to equal 3', () => {
expect(1 + 2).toBe(3);
});
});

View File

@ -0,0 +1,11 @@
<script lang="ts">
import { Canvas } from '@threlte/core'
import Scene from './Scene.svelte'
import { World } from '@threlte/rapier';
</script>
<Canvas>
<World gravity={[0, 0, 0]}>
<Scene />
</World>
</Canvas>

View File

@ -0,0 +1,109 @@
<script
lang="ts"
context="module"
>
const geometry = new SphereGeometry(1)
const material = new MeshBasicMaterial({ color: '#339933' })
</script>
<script lang="ts">
import { T } from '@threlte/core'
import { HTML } from '@threlte/extras'
import { Attractor, Collider, RigidBody } from '@threlte/rapier'
import { BoxGeometry, MeshBasicMaterial, MeshStandardMaterial, SphereGeometry, Vector3 } from 'three'
export let range: number = 10
export let position: [number, number, number] = [0, 0, 0]
let isHovering = false
let isPointerDown = false
let contactVec = new Vector3()
const bodyPositions = [
new Vector3(position[0] - range, position[0] - range, position[0] - range).toArray(),
new Vector3(position[1] + (range / 2), position[1] + range, position[1] + range).toArray(),
new Vector3(position[2] + range, position[2] - (range / 2), position[2] + range).toArray()
]
const getId = () => {
return Math.random().toString(16).slice(2)
}
const getRandomSize = (): number => {
return (Math.random() / 4) + 0.25
}
const generateBodies = (c: number) => {
return Array(c)
.fill('x')
.map((_, index) => {
return {
id: getId(),
position: bodyPositions[index],
size: getRandomSize()
}
})
}
const onClick = () => {
console.log('clicked')
}
$: bodies = generateBodies(3)
</script>
<HTML
position.x={position[0]}
position.y={position[1]}
position.z={position[2]}
>
<button
on:pointerenter={() => (isHovering = true)}
on:pointerleave={() => {
isPointerDown = false
isHovering = false
}}
on:pointerdown={() => (isPointerDown = true)}
on:pointerup={() => (isPointerDown = false)}
on:pointercancel={() => {
isPointerDown = false
isHovering = false
}}
on:click={onClick}
class="rounded-full bg-orange-500 px-3 text-white hover:opacity-90 active:opacity-70"
>
Hello!
</button>
</HTML>
<Attractor
position.x={position[0]}
position.y={position[1]}
position.z={position[2]}
range={200}
strength={isHovering ? 1 : 0.1}
gravityType={"linear"}
/>
{#each bodies as body (body.id)}
<T.Group position={body.position}>
<RigidBody>
<Collider
shape="ball"
args={[body.size]}
mass={body.size}
/>
<Attractor
range={50}
strength={1}
gravityType={"newtonian"}
/>
<T.Mesh
scale={[body.size, body.size, body.size]}
{geometry}
{material}
/>
</RigidBody>
</T.Group>
{/each}

View File

@ -0,0 +1,64 @@
<script lang="ts">
import { T } from '@threlte/core'
import { ContactShadows, Float, Grid, OrbitControls } from '@threlte/extras'
import { Attractor, RigidBody } from '@threlte/rapier';
import RandomMeshes from './RandomMeshes.svelte';
const size = 100
const count = 500
const positions = new Float32Array(count * 3)
// randomly distribute points in a cube
for (let i = 0; i < count; i++) {
positions[i * 3 + 0] = (Math.random() - 0.5) * size
positions[i * 3 + 1] = (Math.random() - 0.5) * size
positions[i * 3 + 2] = (Math.random() - 0.5) * size
}
</script>
<T.PerspectiveCamera
position.y={15}
position.z={25}
makeDefault
fov={70}
far={10000}
>
<OrbitControls
enableZoom={false}
enablePan={false}
enableRotate={false}
enableDamping
target.y={0}
autoRotate
/>
</T.PerspectiveCamera>
<T.DirectionalLight
intensity={0.8}
position.x={5}
position.y={10}
/>
<T.Points>
<T.BufferGeometry>
<T.BufferAttribute
args={[positions, 3]}
attach={(parent, self) => {
parent.setAttribute('position', self)
return () => {
// cleanup function called when ref changes or the component unmounts
// https://threlte.xyz/docs/reference/core/t#attach
}
}}
/>
</T.BufferGeometry>
<T.PointsMaterial size={0.1} />
</T.Points>
<RandomMeshes
position={[0, 0, 0]}
range={10}
/>

View File

@ -0,0 +1,5 @@
# Threlte Model Pipeline Components
This directory holds automatically generated Threlte components from GLTF models.
Place your models in `static/models` and run `npm run model-pipeline:run` to generate the components.

1
src/lib/index.ts Normal file
View File

@ -0,0 +1 @@
// place files you want to import through the `$lib` alias in this folder.

28
src/routes/+page.svelte Normal file
View File

@ -0,0 +1,28 @@
<script lang="ts">
import App from '$lib/components/App.svelte'
import type { PageData } from './$types';
export let data: PageData;
</script>
<div>
{#each data.models as model}
<span>{model.title}</span>
{/each}
<App />
</div>
<style>
:global(body) {
margin: 0;
}
div {
width: 100vw;
height: 100vh;
background: rgb(0, 36, 6);
background: linear-gradient(180deg, rgba(0, 36, 6, 1) 0%, rgba(0, 0, 0, 1) 100%);
display: absolute;
justify-content: center;
align-items: center;
}
</style>

15
src/routes/+page.ts Normal file
View File

@ -0,0 +1,15 @@
const models: Model[] = [
{ title: 'Model 1' },
{ title: 'Model 2' },
{ title: 'Model 3' }
];
export type Model = { title: string}
export function load(): { models: Model[] } {
return {
models: models.map((model) => ({
title: model.title
}))
};
}

BIN
static/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

BIN
static/models/threlte.glb Normal file

Binary file not shown.

18
svelte.config.js Normal file
View File

@ -0,0 +1,18 @@
import adapter from '@sveltejs/adapter-auto';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
/** @type {import('@sveltejs/kit').Config} */
const config = {
// Consult https://kit.svelte.dev/docs/integrations#preprocessors
// for more information about preprocessors
preprocess: vitePreprocess(),
kit: {
// adapter-auto only supports some environments, see https://kit.svelte.dev/docs/adapter-auto for a list.
// If your environment is not supported, or you settled on a specific environment, switch out the adapter.
// See https://kit.svelte.dev/docs/adapters for more information about adapters.
adapter: adapter()
}
};
export default config;

19
tsconfig.json Normal file
View File

@ -0,0 +1,19 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"moduleResolution": "bundler"
}
// Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias
// except $lib which is handled by https://kit.svelte.dev/docs/configuration#files
//
// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
// from the referenced tsconfig.json - TypeScript does not merge them in
}

12
vite.config.ts Normal file
View File

@ -0,0 +1,12 @@
import { sveltekit } from '@sveltejs/kit/vite'
import { defineConfig } from 'vitest/config'
export default defineConfig({
plugins: [sveltekit()],
ssr: {
noExternal: ['three']
},
test: {
include: ['src/**/*.{test,spec}.{js,ts}']
}
})