Skip to content

Commit

Permalink
feat(core): re-structure and tres custom renderer base
Browse files Browse the repository at this point in the history
  • Loading branch information
alvarosabu committed Mar 10, 2023
1 parent c0b86ea commit aad0953
Show file tree
Hide file tree
Showing 33 changed files with 371 additions and 48 deletions.
2 changes: 1 addition & 1 deletion packages/cientos/src/core/usePamCameraMouse/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { watchEffect, computed } from 'vue'
import { Camera } from 'three'
import { useWindowSize, useMouse } from '@vueuse/core'
import { useLogger } from '/@/composables/useLogger'
import { useLogger } from '@tresjs/core/src/iternal/useLogger'

export function usePamCameraMouse(disabled = false, factor = 5, camera: Camera | undefined) {
const { x, y } = useMouse()
Expand Down
13 changes: 11 additions & 2 deletions packages/tres/src/App.vue
Original file line number Diff line number Diff line change
@@ -1,14 +1,23 @@
<script setup lang="ts">
import { useTweakPane } from '@tresjs/cientos'
import Shapes from '/@/components/Shapes.vue'
import TresCanvas from './components/TresCanvas'
// import TheEvents from '/@/components/TheEvents.vue'
useTweakPane()
</script>

<template>
<Suspense>
<Shapes />
<TresCanvas>
<TresPerspectiveCamera :args="[45, 1, 0.1, 1000]" />
<TresAmbientLight />
<TresDirectionalLight :intensity="1" color="yellow" :position="[-2, 0, 3]" />
<TresGridHelper :args="[4, 4]"></TresGridHelper>
<TresMesh>
<TresSphereGeometry :args="[2, 32, 16]" />
<TresMeshToonMaterial color="teal" />
</TresMesh>
</TresCanvas>
</Suspense>
</template>

Expand Down
132 changes: 132 additions & 0 deletions packages/tres/src/components/TresCanvas.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import { defineComponent, h, onUnmounted, PropType, ref, watchEffect } from 'vue'
/* eslint-disable vue/one-component-per-file */
import * as THREE from 'three'
import { ShadowMapType, TextureEncoding, ToneMapping } from 'three'
/* import { OrbitControls } from '@tresjs/cientos' */
import { extend, createTres } from '/@/core/renderer'

export const TresCanvas = defineComponent({
name: 'TresCanvas',
props: {
shadows: Boolean,
shadowMapType: Number as PropType<ShadowMapType>,
physicallyCorrectLights: {
type: Boolean,
default: false,
validator: (value: boolean) => {
if (value) {
console.warn('physicallyCorrectLights is deprecated. Use useLegacyLights instead.')
}
return true
},
},
useLegacyLights: Boolean,
outputEncoding: Number as PropType<TextureEncoding>,
toneMapping: Number as PropType<ToneMapping>,
toneMappingExposure: Number,
context: Object as PropType<WebGLRenderingContext>,
powerPreference: String as PropType<'high-performance' | 'low-power' | 'default'>,
preserveDrawingBuffer: Boolean,
clearColor: String,
windowSize: { type: Boolean, default: false },
},
setup(props, { slots, attrs }) {
const container = ref<HTMLElement>()
const canvas = ref<HTMLCanvasElement>()

watchEffect(() => {
const renderer = new THREE.WebGLRenderer({
canvas: canvas.value,
antialias: true,
alpha: true,
powerPreference: 'high-performance',
})
renderer.outputEncoding = THREE.sRGBEncoding
renderer.toneMapping = THREE.ACESFilmicToneMapping
renderer.setSize(window.innerWidth, window.innerHeight)

const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight)
camera.position.set(0, 2, 7)

/* const controls = new OrbitControls(camera, renderer.domElement)
controls.enableDamping = true */

const scene = new THREE.Scene()

window.addEventListener('resize', () => {
renderer.setSize(window.innerWidth, window.innerHeight)
camera.aspect = window.innerWidth / window.innerHeight
camera.updateProjectionMatrix()
})

renderer.setAnimationLoop(() => {
/* controls.update() */
renderer.render(scene, camera)
})

const internal = slots?.default() || []

const internalComponent = defineComponent({
name: 'Wrapper',
setup() {
return () => internal
},
})

const app = createTres(internalComponent)
app.mount(scene)

console.log(app)

onUnmounted(() => {
app.unmount()
})
})

return () => {
return h(
h(
'div',
{
ref: container,
style: {
position: 'relative',
width: '100%',
height: '100%',

pointerEvents: 'auto',
touchAction: 'none',
...(attrs.style as Record<string, unknown>),
},
},
[
h(
'div',
{
style: {
width: '100%',
height: '100%',
},
},
[
h('canvas', {
ref: canvas,
style: {
display: 'block',
width: '100%',
height: '100%',
position: props.windowSize ? 'fixed' : 'absolute',
top: 0,
left: 0,
},
}),
],
),
],
),
)
}
},
})

export default TresCanvas
11 changes: 10 additions & 1 deletion packages/tres/src/composables/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,10 @@
export * from './useLogger'
export * from './useCamera'
export * from './useCatalogue'
export * from './useInstanceCreator'
export * from './useRenderLoop/'
export * from './useRenderer/'
export * from './useScene/'
export * from './useLoader'
export * from './useTexture'
export * from './useTres'
export * from './useRaycaster'
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { App, ref, Component, Ref } from 'vue'
import * as THREE from 'three'
import { useInstanceCreator } from '/@/core'
import { useLogger } from '/@/composables'
import { useLogger } from '../../iternal'
import { TresCatalogue } from '/@/types'

const catalogue: Ref<TresCatalogue> = ref({ ...THREE, uuid: THREE.MathUtils.generateUUID() })
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { useEventListener } from '@vueuse/core'
import { isArray, isDefined, isFunction } from '@alvarosabu/utils'
import { normalizeVectorFlexibleParam } from '/@/utils/normalize'
import { useCamera, useCatalogue, useRenderLoop, useTres } from '/@/core/'
import { useLogger } from '/@/composables'
import { useLogger } from '../../iternal'
import { TresAttributes, TresCatalogue, TresInstance, TresVNode, TresVNodeType, TresEvent } from '/@/types'

const VECTOR3_PROPS = ['rotation', 'scale', 'position']
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { isArray } from '@alvarosabu/utils'
import { Object3D } from 'three'
import { useLogger } from '/@/composables'
import { useLogger } from '../../iternal'

export interface TresLoader<T> extends THREE.Loader {
load(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { RendererPresetsType } from './const'
import { ShadowMapType, TextureEncoding, ToneMapping } from 'three'
import { h, defineComponent, ref, provide, onBeforeUnmount, PropType } from 'vue'
import { useRenderer } from '.'
import { useLogger } from '/@/composables'
import { useLogger } from '../../iternal'
import { TresVNodeType } from '/@/types'

/**
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import { normalizeColor } from '/@/utils/normalize'
import { TresColor } from '/@/types'
import { rendererPresets, RendererPresetsType } from './const'
import { merge } from '/@/utils'
import { useLogger } from '/@/composables'
import { useLogger } from '../../iternal'

export interface UseRendererOptions extends WebGLRendererParameters {
/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { defineComponent, inject, provide, Ref } from 'vue'
import type { Renderer } from 'three'
import { useCamera, useTres, useRenderLoop, useScene, useRaycaster } from '/@/core/'
import { useCamera, useTres, useRenderLoop, useScene, useRaycaster } from '..'

/**
* Vue component for rendering a Tres component.
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
4 changes: 4 additions & 0 deletions packages/tres/src/core/catalogue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export const catalogue = {}
export const extend = objects => void Object.assign(catalogue, objects)

export default { catalogue, extend }
10 changes: 0 additions & 10 deletions packages/tres/src/core/index.ts

This file was deleted.

105 changes: 105 additions & 0 deletions packages/tres/src/core/nodeOps.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { useCamera } from '@tresjs/core'
import { RendererOptions } from 'vue'
import { catalogue } from './catalogue'

export const nodeOps: RendererOptions<Node, Element> = {
createElement(type, _isSVG, _isCustomizedBuiltIn, props) {
if (type === 'template') return null
let instance

if (props === null) {
props = {}
}

if (props.arg) {
instance = new catalogue[type.replace('Tres', '')](...props.args)
} else {
instance = new catalogue[type.replace('Tres', '')]()
}

if (instance.isCamera) {
const { pushCamera } = useCamera()
pushCamera(instance)
}

if (props.attach === undefined) {
if (instance.isMaterial) instance.attach = 'material'
else if (instance.isBufferGeometry) instance.attach = 'geometry'
}

console.log({
type,
instance,
threeObj: catalogue[type.replace('Tres', '')],
})

return instance
},
insert(child, parent, beforeChild) {
if (parent?.isObject3D && child?.isObject3D) {
const index = beforeChild ? parent.children.indexOf(beforeChild) : 0
child.parent = parent
parent.children.splice(index, 0, child)
child.dispatchEvent({ type: 'added' })
} else if (typeof child?.attach === 'string') {
child.__previousAttach = child[parent.attach]
parent[child.attach] = child
}
},
remove(node) {
const parent = node.parent
if (parent) {
if (parent.isObject3D && node.isObject3D) {
parent.remove(node)
} else if (typeof child.attach === 'string') {
parent[child.attach] = child.__previousAttach
delete child.__previousAttach
node.parent = null
}
}

node.dispose?.()
node.traverse?.(node => node.dispose?.())
},
patchProp(node, prop, prevValue, nextValue) {
let root = node
let key = prop
let target = root[key]

// Traverse pierced props (e.g. foo-bar=value => foo.bar = value)
if (key.includes('-')) {
const chain = key.split('-')
target = chain.reduce((acc, key) => acc[key], root)
key = chain.pop()

if (!target?.set) root = chain.reduce((acc, key) => acc[key], root)
}

let value = nextValue
try {
const num = parseFloat(value)
value = isNaN(num) ? JSON.parse(value) : num
} catch (_) {}

// Set prop, prefer atomic methods if applicable
if (!target?.set) root[key] = value
else if (target.constructor === value.constructor) target.copy(value)
else if (Array.isArray(value)) target.set(...value)
else if (!target.isColor && target.setScalar) target.setScalar(value)
else target.set(value)
},
createText(text) {},
createComment(text) {},
setText(node, text) {},
setElementText(node, text) {},
parentNode(node) {
return node?.parent || null
},
nextSibling(node) {
if (node?.parent?.children) {
const index = node.parent.children.indexOf(node)
if (index !== -1) return node.parent.children[index + 1]
}
return null
},
}
11 changes: 11 additions & 0 deletions packages/tres/src/core/renderer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import * as THREE from 'three'

import { createRenderer } from 'vue'
import { extend } from './catalogue'
import { nodeOps } from './nodeOps'

export const { createApp: createTres } = createRenderer(nodeOps)

extend(THREE)

export default { createTres, extend }
1 change: 1 addition & 0 deletions packages/tres/src/iternal/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './useLogger'
File renamed without changes.
3 changes: 1 addition & 2 deletions packages/tres/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { createApp } from 'vue'
import App from './App.vue'
import plugin from '.'

import './style.css'

export const app = createApp(App)

app.use(plugin)
app.mount('#app')
Loading

0 comments on commit aad0953

Please sign in to comment.