🎥 Make videos programmatically with React
fix tests
Jonny Burgerbf85a2a22606
diff --git a/packages/create-video/src/templates.tsx b/packages/create-video/src/templates.tsxindex 6620b28046..94a50114ef 100644--- a/packages/create-video/src/templates.tsx+++ b/packages/create-video/src/templates.tsx@@ -225,7 +225,7 @@ export const FEATURED_TEMPLATES: Template[] = [defaultBranch: 'main',featuredOnHomePage: null,previewURL: 'https://template-three-remotion.vercel.app/',- templateInMonorepo: null,+ templateInMonorepo: 'template-three',allowEnableTailwind: false,},{diff --git a/packages/create-video/src/test/patch-package-json.test.ts b/packages/create-video/src/test/patch-package-json.test.tsindex 4538d3db86..515afcfb9d 100644--- a/packages/create-video/src/test/patch-package-json.test.ts+++ b/packages/create-video/src/test/patch-package-json.test.ts@@ -50,8 +50,10 @@ for (const packageManager of packageManagers) {dependencies: {...packageJson.dependencies,'@remotion/cli': latestRemotionVersion,+ '@remotion/tailwind': latestRemotionVersion,remotion: latestRemotionVersion,},+ sideEffects: ['*.css'],devDependencies: {...packageJson.devDependencies,'@remotion/eslint-config': latestRemotionVersion,diff --git a/packages/template-three/.eslintrc b/packages/template-three/.eslintrcnew file mode 100644index 0000000000..9ec5ca74c5--- /dev/null+++ b/packages/template-three/.eslintrc@@ -0,0 +1,3 @@+{+ "extends": "@remotion"+}diff --git a/packages/template-three/.gitignore b/packages/template-three/.gitignorenew file mode 100644index 0000000000..b62197ba2f--- /dev/null+++ b/packages/template-three/.gitignore@@ -0,0 +1,7 @@+node_modules+dist+.DS_Store+.env++# Ignore the output video from Git but not videos you import into src/.+outdiff --git a/packages/template-three/LICENSE.md b/packages/template-three/LICENSE.mdnew file mode 100644index 0000000000..b116fdb87d--- /dev/null+++ b/packages/template-three/LICENSE.md@@ -0,0 +1,7 @@+Copyright (c) 2021 Jonny Burger++Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.diff --git a/packages/template-three/README.md b/packages/template-three/README.mdnew file mode 100644index 0000000000..0222a4e18f--- /dev/null+++ b/packages/template-three/README.md@@ -0,0 +1,61 @@+# Remotion + React Three Fiber Starter Template++<p align="center">+ <img src="demo.gif" style="border-radius: 5px">+</p>++[This is a template repository, click "Use this template" to create a repository based off this template!](https://github.com/JonnyBurger/remotion-template-three/generate)++This is a lightweight boilerplate for [Remotion](https://github.com/jonnyburger/remotion) with [React Three Fiber](https://github.com/pmndrs/react-three-fiber) and [@remotion/three](http://remotion.dev/docs/three) preinstalled.++- [Remotion documentation](https://remotion.dev)+- [React Three Fiber documentation](https://docs.pmnd.rs/react-three-fiber)+- [@remotion/three documentation](http://remotion.dev/docs/three)++This example features a phone with a screen. You can easily switch out the video and change a series of parameters, like size, color, aspect ratio, corner radius etc. of the phone.++You can also simply delete everything inside the canvas to start off with your own 3D project.++## Commands++**Install Dependencies**++```console+npm install+```++**Start Preview**++```console+npm start+```++**Render MP4 video**++```console+npm run build+```++**Upgrade Remotion**++```console+npm run upgrade+```++## Docs++Get started with Remotion by reading the [fundamentals page](https://www.remotion.dev/docs/the-fundamentals).++## Help++We provide help on our [Discord server](https://discord.gg/6VzzNDwUwV).++## Issues++Found an issue with Remotion? [File an issue here](https://github.com/JonnyBurger/remotion/issues/new).++## License++Note that for some entities a company license is needed. [Read the terms here](https://github.com/remotion-dev/remotion/blob/main/LICENSE.md).++The content of this template is licensed under MIT.diff --git a/packages/template-three/demo.gif b/packages/template-three/demo.gifnew file mode 100644index 0000000000..1129ebc58aBinary files /dev/null and b/packages/template-three/demo.gif differdiff --git a/packages/template-three/package.json b/packages/template-three/package.jsonnew file mode 100644index 0000000000..f7f4fd517f--- /dev/null+++ b/packages/template-three/package.json@@ -0,0 +1,35 @@+{+ "name": "remotion-template-three",+ "version": "1.0.0",+ "description": "A React Three Fiber Project",+ "scripts": {+ "start": "remotion studio",+ "build": "remotion render Scene out/video.mp4",+ "upgrade": "remotion upgrade",+ "test": "eslint src --ext ts,tsx,js,jsx && tsc"+ },+ "repository": {},+ "license": "UNLICENSED",+ "dependencies": {+ "@react-three/fiber": "8.13.5",+ "@remotion/cli": "workspace:*",+ "@remotion/media-utils": "workspace:*",+ "@remotion/three": "workspace:*",+ "@remotion/zod-types": "workspace:*",+ "react": "18.3.1",+ "react-dom": "18.3.1",+ "remotion": "workspace:*",+ "three": "0.158.0",+ "zod": "3.22.3"+ },+ "devDependencies": {+ "@remotion/eslint-config": "workspace:*",+ "@types/react": "18.3.1",+ "@types/three": "0.157.2",+ "@types/web": "0.0.78",+ "eslint": "8.56.0",+ "prettier": "3.2.5",+ "typescript": "5.3.3"+ },+ "private": true+}diff --git a/packages/template-three/public/phone.mp4 b/packages/template-three/public/phone.mp4new file mode 100644index 0000000000..d805b460ddBinary files /dev/null and b/packages/template-three/public/phone.mp4 differdiff --git a/packages/template-three/public/tablet.mp4 b/packages/template-three/public/tablet.mp4new file mode 100644index 0000000000..a05d60b916Binary files /dev/null and b/packages/template-three/public/tablet.mp4 differdiff --git a/packages/template-three/remotion.config.ts b/packages/template-three/remotion.config.tsnew file mode 100644index 0000000000..4bae5f2611--- /dev/null+++ b/packages/template-three/remotion.config.ts@@ -0,0 +1,11 @@+/**+ * Note: When using the Node.JS APIs, the config file+ * doesn't apply. Instead, pass options directly to the APIs.+ *+ * All configuration options: https://remotion.dev/docs/config+ */++import {Config} from '@remotion/cli/config';++Config.setChromiumOpenGlRenderer('angle');+Config.setVideoImageFormat('jpeg');diff --git a/packages/template-three/src/Phone.tsx b/packages/template-three/src/Phone.tsxnew file mode 100644index 0000000000..ccfb9d78d6--- /dev/null+++ b/packages/template-three/src/Phone.tsx@@ -0,0 +1,117 @@+import { useThree } from "@react-three/fiber";+import React, { useEffect, useMemo } from "react";+import { interpolate, spring, useCurrentFrame, useVideoConfig } from "remotion";+import { VideoTexture } from "three";+import {+ CAMERA_DISTANCE,+ getPhoneLayout,+ PHONE_CURVE_SEGMENTS,+ PHONE_SHININESS,+} from "./helpers/layout";+import { roundedRect } from "./helpers/rounded-rectangle";+import { RoundedBox } from "./RoundedBox";++export const Phone: React.FC<{+ videoTexture: VideoTexture | null;+ aspectRatio: number;+ baseScale: number;+ phoneColor: string;+}> = ({ aspectRatio, videoTexture, baseScale, phoneColor }) => {+ const frame = useCurrentFrame();+ const { fps, durationInFrames } = useVideoConfig();++ const layout = useMemo(+ () => getPhoneLayout(aspectRatio, baseScale),+ [aspectRatio, baseScale],+ );++ // Place a camera and set the distance to the object.+ // Then make it look at the object.+ const camera = useThree((state) => state.camera);+ useEffect(() => {+ camera.position.set(0, 0, CAMERA_DISTANCE);+ camera.near = 0.2;+ camera.far = Math.max(5000, CAMERA_DISTANCE * 2);+ camera.lookAt(0, 0, 0);+ }, [camera]);++ // Make the video fill the phone texture+ useEffect(() => {+ if (videoTexture) {+ videoTexture.repeat.y = 1 / layout.screen.height;+ videoTexture.repeat.x = 1 / layout.screen.width;+ }+ }, [aspectRatio, layout.screen.height, layout.screen.width, videoTexture]);++ // During the whole scene, the phone is rotating.+ // 2 * Math.PI is a full rotation.+ const constantRotation = interpolate(+ frame,+ [0, durationInFrames],+ [0, Math.PI * 6],+ );++ // When the composition starts, there is some extra+ // rotation and translation.+ const entranceAnimation = spring({+ frame,+ fps,+ config: {+ damping: 200,+ mass: 3,+ },+ });++ // Calculate the entrance rotation,+ // doing one full spin+ const entranceRotation = interpolate(+ entranceAnimation,+ [0, 1],+ [-Math.PI, Math.PI],+ );++ // Calculating the total rotation of the phone+ const rotateY = entranceRotation + constantRotation;++ // Calculating the translation of the phone at the beginning.+ // The start position of the phone is set to 4 "units"+ const translateY = interpolate(entranceAnimation, [0, 1], [-4, 0]);++ // Calculate a rounded rectangle for the phone screen+ const screenGeometry = useMemo(() => {+ return roundedRect({+ width: layout.screen.width,+ height: layout.screen.height,+ radius: layout.screen.radius,+ });+ }, [layout.screen.height, layout.screen.radius, layout.screen.width]);++ return (+ <group+ scale={entranceAnimation}+ rotation={[0, rotateY, 0]}+ position={[0, translateY, 0]}+ >+ <RoundedBox+ radius={layout.phone.radius}+ depth={layout.phone.thickness}+ curveSegments={PHONE_CURVE_SEGMENTS}+ position={layout.phone.position}+ width={layout.phone.width}+ height={layout.phone.height}+ >+ <meshPhongMaterial color={phoneColor} shininess={PHONE_SHININESS} />+ </RoundedBox>+ <mesh position={layout.screen.position}>+ <shapeGeometry args={[screenGeometry]} />+ {videoTexture ? (+ <meshBasicMaterial+ color={0xffffff}+ toneMapped={false}+ map={videoTexture}+ />+ ) : null}+ </mesh>+ </group>+ );+};diff --git a/packages/template-three/src/Root.tsx b/packages/template-three/src/Root.tsxnew file mode 100644index 0000000000..2e0f5d4b77--- /dev/null+++ b/packages/template-three/src/Root.tsx@@ -0,0 +1,38 @@+import { Composition } from "remotion";+import { Scene, myCompSchema } from "./Scene";++// Welcome to the Remotion Three Starter Kit!+// Two compositions have been created, showing how to use+// the `ThreeCanvas` component and the `useVideoTexture` hook.++// You can play around with the example or delete everything inside the canvas.++// Remotion Docs:+// https://remotion.dev/docs++// @remotion/three Docs:+// https://remotion.dev/docs/three++// React Three Fiber Docs:+// https://docs.pmnd.rs/react-three-fiber/getting-started/introduction++export const RemotionRoot: React.FC = () => {+ return (+ <>+ <Composition+ id="Scene"+ component={Scene}+ durationInFrames={300}+ fps={30}+ width={1280}+ height={720}+ schema={myCompSchema}+ defaultProps={{+ deviceType: "phone",+ phoneColor: "rgba(110, 152, 191, 0.00)" as const,+ baseScale: 1,+ }}+ />+ </>+ );+};diff --git a/packages/template-three/src/RoundedBox.tsx b/packages/template-three/src/RoundedBox.tsxnew file mode 100644index 0000000000..4dfc7fbeed--- /dev/null+++ b/packages/template-three/src/RoundedBox.tsx@@ -0,0 +1,43 @@+import React, { useMemo } from "react";+import { roundedRect } from "./helpers/rounded-rectangle";++type Props = {+ width: number;+ height: number;+ radius: number;+ curveSegments: number;+ depth: number;+} & Omit<JSX.IntrinsicElements["mesh"], "args">;++export const RoundedBox: React.FC<Props> = ({+ width,+ height,+ radius,+ curveSegments,+ children,+ depth,+ ...otherProps+}) => {+ const shape = useMemo(+ () => roundedRect({ width, height, radius }),+ [height, radius, width],+ );++ const params = useMemo(+ () => ({+ depth,+ bevelEnabled: true,+ bevelSize: 0,+ bevelThickness: 0,+ curveSegments,+ }),+ [curveSegments, depth],+ );++ return (+ <mesh {...otherProps}>+ <extrudeGeometry attach="geometry" args={[shape, params]} />+ {children}+ </mesh>+ );+};diff --git a/packages/template-three/src/Scene.tsx b/packages/template-three/src/Scene.tsxnew file mode 100644index 0000000000..2cfe7804be--- /dev/null+++ b/packages/template-three/src/Scene.tsx@@ -0,0 +1,62 @@+import { staticFile } from "remotion";+import { getVideoMetadata, VideoMetadata } from "@remotion/media-utils";+import { ThreeCanvas, useVideoTexture } from "@remotion/three";+import React, { useEffect, useRef, useState } from "react";+import { AbsoluteFill, useVideoConfig, Video } from "remotion";+import { Phone } from "./Phone";+import { z } from "zod";+import { zColor } from "@remotion/zod-types";++const container: React.CSSProperties = {+ backgroundColor: "white",+};++const videoStyle: React.CSSProperties = {+ position: "absolute",+ opacity: 0,+};++export const myCompSchema = z.object({+ phoneColor: zColor(),+ deviceType: z.enum(["phone", "tablet"]),+});++type MyCompSchemaType = z.infer<typeof myCompSchema>;++export const Scene: React.FC<+ {+ baseScale: number;+ } & MyCompSchemaType+> = ({ baseScale, phoneColor, deviceType }) => {+ const videoRef = useRef<HTMLVideoElement>(null);+ const { width, height } = useVideoConfig();+ const [videoData, setVideoData] = useState<VideoMetadata | null>(null);++ const videoSrc =+ deviceType === "phone" ? staticFile("phone.mp4") : staticFile("tablet.mp4");++ useEffect(() => {+ getVideoMetadata(videoSrc)+ .then((data) => setVideoData(data))+ .catch((err) => console.log(err));+ }, [videoSrc]);++ const texture = useVideoTexture(videoRef);+ return (+ <AbsoluteFill style={container}>+ <Video ref={videoRef} src={videoSrc} style={videoStyle} />+ {videoData ? (+ <ThreeCanvas linear width={width} height={height}>+ <ambientLight intensity={1.5} color={0xffffff} />+ <pointLight position={[10, 10, 0]} />+ <Phone+ phoneColor={phoneColor}+ baseScale={baseScale}+ videoTexture={texture}+ aspectRatio={videoData.aspectRatio}+ />+ </ThreeCanvas>+ ) : null}+ </AbsoluteFill>+ );+};diff --git a/packages/template-three/src/helpers/layout.ts b/packages/template-three/src/helpers/layout.tsnew file mode 100644index 0000000000..1e5f416174--- /dev/null+++ b/packages/template-three/src/helpers/layout.ts@@ -0,0 +1,97 @@+import { Vector3 } from "@react-three/fiber";++// The distance from which the camera is pointing to the phone.+export const CAMERA_DISTANCE = 2.5;++// A small number to avoid z-index flickering+export const Z_FLICKER_PREVENTION = 0.001;++// Shininess of the phone+export const PHONE_SHININESS = 30;++// In how many segments the phone rounded corners+// are divided. Increase number for smoother phone+export const PHONE_CURVE_SEGMENTS = 8;++// Calculate phone size. Whichever side is smaller gets+// normalized to the base scale.+const getPhoneHeight = (aspectRatio: number, baseScale: number): number => {+ if (aspectRatio > 1) {+ return baseScale;+ }+ return baseScale / aspectRatio;+};++const getPhoneWidth = (aspectRatio: number, baseScale: number): number => {+ if (aspectRatio < 1) {+ return baseScale;+ }+ return baseScale * aspectRatio;+};++type Layout = {+ position: Vector3;+ height: number;+ width: number;+ radius: number;+};++type PhoneLayout = {+ phone: Layout & {+ thickness: number;+ bevel: number;+ };+ screen: Layout;+};++export const getPhoneLayout = (+ // I recommend building the phone layout based+ // on the aspect ratio of the phone+ aspectRatio: number,+ // This value can be increased or decreased to tweak the+ // base value of the phone.+ baseScale: number,+): PhoneLayout => {+ // The depth of the phone body+ const phoneThickness = baseScale * 0.15;++ // How big the border of the phone is.+ const phoneBevel = baseScale * 0.04;++ // The inner radius of the phone, aka the screen radius+ const screenRadius = baseScale * 0.07;++ const phoneHeight = getPhoneHeight(aspectRatio, baseScale);+ const phoneWidth = getPhoneWidth(aspectRatio, baseScale);+ const phonePosition: Vector3 = [-phoneWidth / 2, -phoneHeight / 2, 0];+ const screenWidth = phoneWidth - phoneBevel * 2;+ const screenHeight = phoneHeight - phoneBevel * 2;+ const screenPosition: Vector3 = [+ -screenWidth / 2,+ -screenHeight / 2,+ phoneThickness + Z_FLICKER_PREVENTION,+ ];++ // Define the outer radius of the phone.+ // It looks better if the outer radius is a bit bigger than the screen radios,+ // formula taken from https://twitter.com/joshwcomeau/status/134978208002102886+ const phoneRadius =+ screenRadius + (getPhoneWidth(aspectRatio, baseScale) - screenWidth) / 2;++ return {+ phone: {+ position: phonePosition,+ height: phoneHeight,+ width: phoneWidth,+ radius: phoneRadius,+ thickness: phoneThickness,+ bevel: phoneBevel,+ },+ screen: {+ position: screenPosition,+ height: screenHeight,+ width: screenWidth,+ radius: screenRadius,+ },+ };+};diff --git a/packages/template-three/src/helpers/rounded-rectangle.ts b/packages/template-three/src/helpers/rounded-rectangle.tsnew file mode 100644index 0000000000..422a4379c0--- /dev/null+++ b/packages/template-three/src/helpers/rounded-rectangle.ts@@ -0,0 +1,23 @@+import { Shape } from "three";++export function roundedRect({+ width,+ height,+ radius,+}: {+ width: number;+ height: number;+ radius: number;+}): Shape {+ const roundedRectShape = new Shape();+ roundedRectShape.moveTo(0, radius);+ roundedRectShape.lineTo(0, height - radius);+ roundedRectShape.quadraticCurveTo(0, height, radius, height);+ roundedRectShape.lineTo(width - radius, height);+ roundedRectShape.quadraticCurveTo(width, height, width, height - radius);+ roundedRectShape.lineTo(width, radius);+ roundedRectShape.quadraticCurveTo(width, 0, width - radius, 0);+ roundedRectShape.lineTo(radius, 0);+ roundedRectShape.quadraticCurveTo(0, 0, 0, radius);+ return roundedRectShape;+}diff --git a/packages/template-three/src/index.ts b/packages/template-three/src/index.tsnew file mode 100644index 0000000000..f31c790edb--- /dev/null+++ b/packages/template-three/src/index.ts@@ -0,0 +1,4 @@+import { registerRoot } from "remotion";+import { RemotionRoot } from "./Root";++registerRoot(RemotionRoot);diff --git a/packages/template-three/tsconfig.json b/packages/template-three/tsconfig.jsonnew file mode 100644index 0000000000..0a292af5f2--- /dev/null+++ b/packages/template-three/tsconfig.json@@ -0,0 +1,15 @@+{+ "compilerOptions": {+ "target": "ES2018",+ "module": "commonjs",+ "jsx": "react-jsx",+ "outDir": "./dist",+ "strict": true,+ "noEmit": true,+ "lib": ["es2015"],+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "noUnusedLocals": true+ }+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex c28aa54ddc..8875988778 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1821,6 +1821,61 @@ importers:specifier: 5.3.3version: 5.3.3+ packages/template-three:+ dependencies:+ '@react-three/fiber':+ specifier: 8.13.5+ '@remotion/cli':+ specifier: workspace:*+ version: link:../cli+ '@remotion/media-utils':+ specifier: workspace:*+ version: link:../media-utils+ '@remotion/three':+ specifier: workspace:*+ version: link:../three+ '@remotion/zod-types':+ specifier: workspace:*+ version: link:../zod-types+ react:+ specifier: 18.3.1+ version: 18.3.1+ react-dom:+ specifier: 18.3.1+ version: 18.3.1([email protected])+ remotion:+ specifier: workspace:*+ version: link:../core+ three:+ specifier: 0.158.0+ version: 0.158.0+ zod:+ specifier: 3.22.3+ version: 3.22.3+ devDependencies:+ '@remotion/eslint-config':+ specifier: workspace:*+ version: link:../eslint-config+ '@types/react':+ specifier: 18.3.1+ version: 18.3.1+ '@types/three':+ specifier: 0.157.2+ version: 0.157.2+ '@types/web':+ specifier: 0.0.78+ version: 0.0.78+ eslint:+ specifier: 8.56.0+ version: 8.56.0+ prettier:+ specifier: 3.2.5+ version: 3.2.5+ typescript:+ specifier: 5.3.3+ version: 5.3.3+packages/test-utils:devDependencies:react:@@ -9616,7 +9671,7 @@ packages:react-native:optional: truedependencies:- '@babel/runtime': 7.19.0+ '@babel/runtime': 7.24.8'@types/react-reconciler': 0.26.7its-fine: 1.0.6([email protected])react: 18.3.1diff --git a/tsconfig.json b/tsconfig.jsonindex eb39a9c458..52f5c8b7b5 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -123,6 +123,9 @@{"path": "./packages/template-next-app"},+ {+ "path": "./packages/template-three"+ },{"path": "./packages/template-helloworld"},