Skip to content

Commit

Permalink
fix: stage model center
Browse files Browse the repository at this point in the history
  • Loading branch information
drcmda committed Apr 9, 2021
1 parent 2681216 commit e50a849
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1077,6 +1077,7 @@ Creates a "stage" with proper studio lighting, content centered and planar, shad
adjustCamera // Optional: zooms the content in
intensity={1} // Optional: light intensity
environment="warehouse" // Optional: environment
controls={controlsRef} // Optional: recalculates control target for correctness
>
<mesh />
</Stage>
Expand Down
28 changes: 22 additions & 6 deletions src/core/Stage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,23 @@ type Props = JSX.IntrinsicElements['group'] & {
adjustCamera?: boolean
environment?: string
intensity?: number
controls?: React.MutableRefObject<{ update(): void; target: THREE.Vector3 }>
}

export function Stage({ children, contactShadow, shadows, adjustCamera, environment, intensity = 1, ...props }: Props) {
export function Stage({
children,
controls,
contactShadow,
shadows,
adjustCamera,
environment,
intensity = 1,
...props
}: Props) {
const camera = useThree((state) => state.camera)
const outer = React.useRef<THREE.Group>(null!)
const inner = React.useRef<THREE.Group>(null!)
const [radius, setRadius] = React.useState(0)
const [{ radius, width, height }, set] = React.useState({ radius: 0, width: 0, height: 0 })

React.useLayoutEffect(() => {
outer.current.position.set(0, 0, 0)
Expand All @@ -25,20 +35,26 @@ export function Stage({ children, contactShadow, shadows, adjustCamera, environm
const center = new THREE.Vector3()
const sphere = new THREE.Sphere()
const height = box3.max.y - box3.min.y
const width = box3.max.x - box3.min.x
box3.getCenter(center)
box3.getBoundingSphere(sphere)
setRadius(sphere.radius)
set({ radius: sphere.radius, width, height })
outer.current.position.set(-center.x, -center.y + height / 2, -center.z)
}, [children])

React.useLayoutEffect(() => {
if (adjustCamera) {
const y = radius / (height > width ? 1.5 : 2.5)
camera.position.set(0, radius * 1.5, radius * 2.5)
camera.near = 1
camera.near = 0.1
camera.far = Math.max(5000, radius * 4)
camera.lookAt(0, 0, 0)
camera.lookAt(0, y, 0)
if (controls && controls.current) {
controls.current.target.set(0, y, 0)
controls.current.update()
}
}
}, [radius, adjustCamera])
}, [radius, height, width, adjustCamera])

return (
<group {...props}>
Expand Down

1 comment on commit e50a849

@vercel
Copy link

@vercel vercel bot commented on e50a849 Apr 9, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.