recital / core / src / pipeline / 05-flattening / index.ts
index.ts
Raw
/**
 * Copyright (c) 2022 Amorphous
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

import { concatInPlace } from '../../tools/concat-in-place'
import { exposeMeta } from '../../tools/expose-meta'
import { FlatObject, TokenizedFragmentedSceneObject } from '../../types'

export const genFlattenedObject = (scenes: TokenizedFragmentedSceneObject[]): FlatObject[] => {
	const array: FlatObject[] = []
	for (let scene of scenes) {
		const newScene: FlatObject = {
			type: 'scene',
		}
		if (scene.meta) {
			newScene.meta = scene.meta
		}

		exposeMeta(newScene)
		array.push(newScene)

		// now go through all the fragments...
		for (let fragment of scene.fragments) {
			if (fragment.type === 'empty') {
				// concatenate the tokens
				concatInPlace(array, fragment.tokens)
			} else {
				const newFrag: FlatObject = {
					type: 'fragment',
				}
				if (fragment.meta) {
					newFrag.meta = fragment.meta
				}

				exposeMeta(newFrag)
				array.push(newFrag)

				concatInPlace(array, fragment.tokens)

				array.push({
					type: 'endFragment',
				})
			}
		}

		// and end the scene
		array.push({
			type: 'endScene',
		})
	}

	return array
}