file_path stringlengths 3 280 | file_language stringclasses 66 values | content stringlengths 1 1.04M | repo_name stringlengths 5 92 | repo_stars int64 0 154k | repo_description stringlengths 0 402 | repo_primary_language stringclasses 108 values | developer_username stringlengths 1 25 | developer_name stringlengths 0 30 | developer_company stringlengths 0 82 |
|---|---|---|---|---|---|---|---|---|---|
components/ui/tooltip/Tooltip.vue | Vue | <script setup lang="ts">
import { TooltipRoot, type TooltipRootEmits, type TooltipRootProps, useForwardPropsEmits } from 'radix-vue'
const props = defineProps<TooltipRootProps>()
const emits = defineEmits<TooltipRootEmits>()
const forwarded = useForwardPropsEmits(props, emits)
</script>
<template>
<TooltipRoot v-bind="forwarded">
<slot />
</TooltipRoot>
</template>
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
components/ui/tooltip/TooltipContent.vue | Vue | <script setup lang="ts">
import { TooltipContent, type TooltipContentEmits, type TooltipContentProps, TooltipPortal, useForwardPropsEmits } from 'radix-vue'
import { cn } from '@/utils'
const props = withDefaults(defineProps<TooltipContentProps>(), {
sideOffset: 4,
})
const emits = defineEmits<TooltipContentEmits>()
const forwarded = useForwardPropsEmits(props, emits)
</script>
<template>
<TooltipPortal>
<TooltipContent v-bind="{ ...forwarded, ...$attrs }" :class="cn('z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2', $attrs.class ?? '')">
<slot />
</TooltipContent>
</TooltipPortal>
</template>
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
components/ui/tooltip/TooltipProvider.vue | Vue | <script setup lang="ts">
import { TooltipProvider, type TooltipProviderProps } from 'radix-vue'
const props = defineProps<TooltipProviderProps>()
</script>
<template>
<TooltipProvider v-bind="props">
<slot />
</TooltipProvider>
</template>
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
components/ui/tooltip/TooltipTrigger.vue | Vue | <script setup lang="ts">
import { TooltipTrigger, type TooltipTriggerProps } from 'radix-vue'
const props = defineProps<TooltipTriggerProps>()
</script>
<template>
<TooltipTrigger v-bind="props" class="">
<slot />
</TooltipTrigger>
</template>
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
components/ui/tooltip/index.ts | TypeScript | export { default as Tooltip } from './Tooltip.vue'
export { default as TooltipContent } from './TooltipContent.vue'
export { default as TooltipTrigger } from './TooltipTrigger.vue'
export { default as TooltipProvider } from './TooltipProvider.vue'
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
composables/openai.ts | TypeScript | export function useOpenAIKey() {
return useLocalStorage('openai_key', () => '')
}
export function useNewPrompt() {
return useState('init', () => false)
}
type FetchRequest = Parameters<typeof $fetch>[0]
export function usePrompt() {
const fetchResult = createEventHook<void>()
const fetchError = createEventHook<string>()
const fetchStream = createEventHook<string>()
const openaiKey = useOpenAIKey()
const isNewPrompt = useNewPrompt()
const loading = ref(false)
const content = ref('')
const contentCode = computed(() => content.value.split('\`\`\`vue')?.[1]?.replace('\`\`\`', '') ?? '')
function handleInit(prompt: string, slug?: string | null, basedOnResultId?: string) {
loading.value = true
return $fetch<DBComponent>('/api/init', {
method: 'POST',
body: {
prompt,
slug,
basedOnResultId,
},
headers: {
'x-openai-key': openaiKey.value,
},
})
}
async function handlePrompt(request: FetchRequest, body: Record<string, any>) {
loading.value = true
content.value = ''
try {
const completion = await $fetch<ReadableStream>(request, {
method: 'POST',
body,
responseType: 'stream',
headers: {
'x-openai-key': openaiKey.value,
},
})
const reader = completion.getReader()
const decoder = new TextDecoder('utf-8')
const read = async (): Promise<void> => {
const { done, value } = await reader.read()
if (done) {
console.log('release locked')
loading.value = false
fetchResult.trigger()
return reader.releaseLock()
}
const chunk = decoder.decode(value, { stream: true })
if (chunk.includes('[Error]:'))
throw new Error(chunk.split('[Error]:')[1])
content.value += chunk
fetchStream.trigger(content.value)
return read()
}
await read()
}
catch (err) {
console.log(err)
loading.value = false
if (err instanceof Error)
fetchError.trigger(err.message)
}
}
const handleCreate = (body: Record<string, any>) => {
isNewPrompt.value = false
return handlePrompt('/api/create', body)
}
const handleIterate = (body: Record<string, any>) => {
return handlePrompt('/api/iterate', body)
}
return {
loading,
content,
contentCode,
isNewPrompt,
handleInit,
handleCreate,
handleIterate,
onDone: fetchResult.on,
onError: fetchError.on,
onStream: fetchStream.on,
}
}
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
composables/parse.ts | TypeScript | import { Parser } from 'htmlparser2'
import { DomHandler } from 'domhandler'
import domSerializer from 'dom-serializer'
export function parseTemplate(inputHTML: string) {
const handler = new DomHandler()
// Parse HTML
const parser = new Parser(handler, { xmlMode: true })
parser.write(inputHTML)
parser.end()
// Serialize the parsed DOM back to HTML
const fixedHTML = domSerializer(handler.dom)
return fixedHTML
}
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
drizzle.config.ts | TypeScript | import { join } from 'pathe'
import type { Config } from 'drizzle-kit'
export default {
out: 'server/database/migrations',
schema: 'server/database/schema.ts',
driver: 'better-sqlite',
dbCredentials: {
url: join(process.cwd(), './db.sqlite'),
},
// driver: 'turso',
// dbCredentials: {
// // url: join(process.cwd(), './db.sqlite'),
// url: process.env.TURSO_DB_URL!,
// authToken: process.env.TURSO_DB_TOKEN!,
// },
} satisfies Config
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
eslint.config.js | JavaScript | import antfu from '@antfu/eslint-config'
export default antfu({
rules: {
'no-console': 'off',
'node/prefer-global/process': 'off',
},
})
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
layouts/blank.vue | Vue | <template>
<slot />
</template>
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
layouts/default.vue | Vue | <script setup lang="ts">
import { GithubLogoIcon } from '@radix-icons/vue'
</script>
<template>
<div>
<div class=" w-full h-full flex flex-col items-center justify-center ">
<header class="sticky top-0 flex p-2 md:p-4 w-full z-10">
<NuxtLink to="/" class="group h-10 flex items-center gap-1 text-xl md:text-3xl font-black">
<Logo />
<span>vue0</span>
</NuxtLink>
<div class="mx-auto" />
<div class="flex items-center gap-2">
<UiButton as-child class="flex-shrink-0 bg-white" variant="outline">
<NuxtLink to="https://github.com/zernonia/vue0" target="_blank">
<GithubLogoIcon class="mr-1" />
<span>GitHub</span>
</NuxtLink>
</UiButton>
<UserMenu />
</div>
</header>
<div class="px-2 md:px-4 w-full">
<slot />
</div>
</div>
<UiToaster />
</div>
</template>
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
nuxt.config.ts | TypeScript | // https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
// devtools totally broken, not sure why
devtools: { enabled: false },
app: {
head: {
link: [{ rel: 'icon', type: 'image/svg', href: '/logo.svg' }],
},
},
runtimeConfig: {
public: {
siteUrl: '',
umamiHost: '',
umamiId: '',
},
browserlessApiKey: '',
github: {
clientId: '',
clientSecret: '',
},
session: {
name: 'nuxt-session',
password: '',
},
},
modules: [
'@nuxtjs/tailwindcss',
'@vueuse/nuxt',
'shadcn-nuxt',
'@nuxtjs/google-fonts',
'nuxt-auth-utils',
'@nuxtseo/module',
'@nuxt/content',
],
extends: ['nuxt-umami'],
appConfig: {
umami: {
version: 2,
ignoreLocalhost: true,
},
},
shadcn: {
prefix: 'Ui',
},
tailwindcss: {
viewer: false,
},
ogImage: {
debug: true,
compatibility: {
prerender: {
chromium: false,
},
},
},
hooks: {
'vite:extendConfig': (config, { isClient }) => {
if (isClient)
// @ts-expect-error it has alias of vue
config.resolve.alias.vue = 'vue/dist/vue.esm-bundler.js'
},
},
nitro: {
vercel: {
functions: {
maxDuration: 300, // 5mins maximum possible for Vercel Pro
},
},
},
googleFonts: {
families: {
Inter: '400..800',
},
},
site: {
name: 'vue0',
description: 'Generate Component with simple text prompts.',
defaultLocale: 'en',
},
})
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
pages/[...name].vue | Vue | <script setup lang="ts">
const route = useRoute()
const name = computed(() => route.params.name)
const { data } = await useFetch<DBComponent[]>(`/api/component/user/${name.value}`)
const dataUser = computed(() => data.value?.at(-1)?.user)
if (!data.value?.length) {
throw createError({
statusCode: 404,
statusMessage: 'Page Not Found',
})
}
</script>
<template>
<div>
<div v-if="dataUser" class="w-full flex flex-col justify-center items-center py-8">
<UiAvatar size="lg">
<UiAvatarImage :src="dataUser?.avatarUrl ?? ''" />
<UiAvatarFallback>{{ dataUser?.name?.slice(0, 1) }}</UiAvatarFallback>
</UiAvatar>
<h2 class="text-2xl font-bold my-4">
{{ dataUser.name }}
</h2>
</div>
<GeneratedList :data="data" />
</div>
</template>
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
pages/faq.vue | Vue | <script setup lang="ts">
useSeoMeta({
title: 'FAQs',
description: 'Get answers to common questions about vue0, the generative UI tool.',
})
</script>
<template>
<div class="prose mx-auto py-6">
<h1 class="font-bold text-4xl px-6 ">
FAQs
</h1>
<article class="mt-8 bg-muted rounded-xl px-6 py-4 prose transition-all prose-slate prose-headings:relative prose-headings:scroll-mt-20 [&_a]:prose-h2:font-semibold [&_a]:prose-h2:no-underline prose-li:my-0">
<ContentDoc />
</article>
</div>
</template>
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
pages/index.vue | Vue | <script setup lang="ts">
import { Github } from 'lucide-vue-next'
import { useToast } from '~/components/ui/toast'
const prompt = ref('')
const { data } = useFetch<DBComponent[]>('/api/component/all')
const { isNewPrompt, handleInit, loading } = usePrompt()
const { toast } = useToast()
const openaiKey = useOpenAIKey()
const { loggedIn } = useUserSession()
const openLoginDialog = ref(false)
const openSetupOpenAiDialog = ref(loggedIn.value && !openaiKey.value)
async function handleSubmit() {
if (!prompt.value)
return
if (!loggedIn.value) {
openLoginDialog.value = true
return
}
if (!openaiKey.value) {
openSetupOpenAiDialog.value = true
return
}
loading.value = true
isNewPrompt.value = true
umTrackEvent('create-generation')
try {
const result = await handleInit(prompt.value)
await navigateTo(`/t/${result.slug}`)
}
catch (err) {
console.log({ err })
toast({
variant: 'destructive',
title: 'Error',
// @ts-expect-error ignore error for now
description: err?.data?.message ?? 'Something wrong',
})
}
finally {
loading.value = false
}
}
function saveOpenaiKey() {
if (openaiKey.value.startsWith('sk-') === false) {
toast({
variant: 'destructive',
title: 'Error',
description: 'Please enter a correct OpenAI API key',
})
return
}
openSetupOpenAiDialog.value = false
}
useSeoMeta({
ogImage: `${useRuntimeConfig().public.siteUrl}/og.png`,
})
</script>
<template>
<div class="pb-4 md:pb-8">
<div class="mb-8 w-full h-[65vh] flex items-center justify-center magicpattern">
<UiCard class="mx-auto md:min-w-96 w-full max-w-[600px]">
<UiCardHeader>
<UiCardTitle>Generate component with prompt</UiCardTitle>
</UiCardHeader>
<UiCardContent>
<PromptInput v-model="prompt" placeholder="A login page" :loading="loading" @submit="handleSubmit" />
</UiCardContent>
</UiCard>
</div>
<div class="w-full p-3 md:p-6 border bg-secondary rounded-xl">
<h2 class="my-3 md:my-6 text-2xl md:text-3xl font-bold text-center">
Generated
</h2>
<GeneratedList :data="data" />
</div>
<DialogAction
v-model:open="openLoginDialog"
title="Sign in to vue0.dev"
description="A GitHub account is required to use vue0."
>
<template #footer>
<a href="/api/auth/github" class="ml-auto" @click="umTrackEvent('login')">
<UiButton>
<Github class="mr-2 h-4 w-4" />
<span>Login with GitHub</span>
</UiButton>
</a>
</template>
</DialogAction>
<DialogAction
v-model:open="openSetupOpenAiDialog"
title="Setup OpenAI API Key"
>
<template #body>
<form class="flex flex-col gap-4" @submit.prevent="saveOpenaiKey">
<p class="text-sm">
Get your own <a href="https://platform.openai.com/api-keys" target="_blank" class="underline">OpenAI API key</a> and enter it below:
</p>
<div class="px-1 pb-1 w-full">
<UiInput v-model="openaiKey" placeholder="sk-************ (Required)" required />
</div>
<UiButton type="submit" class="ml-auto">
<span>Save</span>
</UiButton>
</form>
</template>
</DialogAction>
</div>
</template>
<style>
.magicpattern {
background-size: cover;
background-position: center center;
background-repeat: repeat;
background-image: url("data:image/svg+xml;utf8,%3Csvg viewBox=%220 0 2000 1400%22 xmlns=%22http:%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cmask id=%22b%22 x=%220%22 y=%220%22 width=%222000%22 height=%221400%22%3E%3Cpath fill=%22url(%23a)%22 d=%22M0 0h2000v1400H0z%22%2F%3E%3C%2Fmask%3E%3Cpath fill=%22rgba(255%2C 255%2C 255%2C 0)%22 d=%22M0 0h2000v1400H0z%22%2F%3E%3Cg style=%22transform-origin:center center%22 mask=%22url(%23b)%22%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m165.87 0 82.745 47.773v95.546l-82.745 47.773-82.745-47.773V47.773ZM332.12 0l82.745 47.773v95.546l-82.745 47.773-82.745-47.773V47.773ZM498.37 0l82.745 47.773v95.546l-82.745 47.773-82.745-47.773V47.773ZM664.62 0l82.745 47.773v95.546l-82.745 47.773-82.745-47.773V47.773ZM830.87 0l82.745 47.773v95.546l-82.745 47.773-82.745-47.773V47.773Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f907%22 d=%22m997.12 0 82.745 47.773v95.546l-82.745 47.773-82.745-47.773V47.773Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1163.37 0 82.745 47.773v95.546l-82.745 47.773-82.745-47.773V47.773ZM1329.62 0l82.745 47.773v95.546l-82.745 47.773-82.745-47.773V47.773ZM1495.87 0l82.745 47.773v95.546l-82.745 47.773-82.745-47.773V47.773ZM1662.12 0l82.745 47.773v95.546l-82.745 47.773-82.745-47.773V47.773ZM1828.37 0l82.745 47.773v95.546l-82.745 47.773-82.745-47.773V47.773ZM1994.62 0l82.745 47.773v95.546l-82.745 47.773-82.745-47.773V47.773ZM2160.87 0l82.745 47.773v95.546l-82.745 47.773-82.745-47.773V47.773ZM2327.12 0l82.745 47.773v95.546l-82.745 47.773-82.745-47.773V47.773ZM2493.37 0l82.745 47.773v95.546l-82.745 47.773-82.745-47.773V47.773Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f97b%22 d=%22m82.745 143.319 82.745 47.773v95.546L82.745 334.41 0 286.638v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m248.995 143.319 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM415.245 143.319l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM581.495 143.319l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9bb%22 d=%22m747.745 143.319 82.745 47.773v95.546l-82.745 47.773L665 286.638v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m913.995 143.319 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1080.245 143.319l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f930%22 d=%22m1246.495 143.319 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1412.745 143.319 82.745 47.773v95.546l-82.745 47.773L1330 286.638v-95.546ZM1578.995 143.319l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1745.245 143.319l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9a9%22 d=%22m1911.495 143.319 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f987%22 d=%22m2077.745 143.319 82.745 47.773v95.546l-82.745 47.773L1995 286.638v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f997%22 d=%22m2243.995 143.319 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m2410.245 143.319 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM165.87 286.638l82.745 47.773v95.546L165.87 477.73l-82.745-47.773V334.41ZM332.12 286.638l82.745 47.773v95.546L332.12 477.73l-82.745-47.773V334.41ZM498.37 286.638l82.745 47.773v95.546L498.37 477.73l-82.745-47.773V334.41ZM664.62 286.638l82.745 47.773v95.546L664.62 477.73l-82.745-47.773V334.41ZM830.87 286.638l82.745 47.773v95.546L830.87 477.73l-82.745-47.773V334.41ZM997.12 286.638l82.745 47.773v95.546L997.12 477.73l-82.745-47.773V334.41ZM1163.37 286.638l82.745 47.773v95.546l-82.745 47.773-82.745-47.773V334.41Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9c3%22 d=%22m1329.62 286.638 82.745 47.773v95.546l-82.745 47.773-82.745-47.773V334.41Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1495.87 286.638 82.745 47.773v95.546l-82.745 47.773-82.745-47.773V334.41ZM1662.12 286.638l82.745 47.773v95.546l-82.745 47.773-82.745-47.773V334.41ZM1828.37 286.638l82.745 47.773v95.546l-82.745 47.773-82.745-47.773V334.41Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9a7%22 d=%22m1994.62 286.638 82.745 47.773v95.546l-82.745 47.773-82.745-47.773V334.41Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m2160.87 286.638 82.745 47.773v95.546l-82.745 47.773-82.745-47.773V334.41Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f991%22 d=%22m2327.12 286.638 82.745 47.773v95.546l-82.745 47.773-82.745-47.773V334.41Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m2493.37 286.638 82.745 47.773v95.546l-82.745 47.773-82.745-47.773V334.41Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f942%22 d=%22m82.745 429.957 82.745 47.773v95.546l-82.745 47.773L0 573.276V477.73Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m248.995 429.957 82.745 47.773v95.546l-82.745 47.773-82.745-47.773V477.73ZM415.245 429.957l82.745 47.773v95.546l-82.745 47.773-82.745-47.773V477.73ZM581.495 429.957l82.745 47.773v95.546l-82.745 47.773-82.745-47.773V477.73ZM747.745 429.957l82.745 47.773v95.546l-82.745 47.773L665 573.276V477.73Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f96b%22 d=%22m913.995 429.957 82.745 47.773v95.546l-82.745 47.773-82.745-47.773V477.73Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9ae%22 d=%22m1080.245 429.957 82.745 47.773v95.546l-82.745 47.773-82.745-47.773V477.73Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1246.495 429.957 82.745 47.773v95.546l-82.745 47.773-82.745-47.773V477.73ZM1412.745 429.957l82.745 47.773v95.546l-82.745 47.773L1330 573.276V477.73ZM1578.995 429.957l82.745 47.773v95.546l-82.745 47.773-82.745-47.773V477.73ZM1745.245 429.957l82.745 47.773v95.546l-82.745 47.773-82.745-47.773V477.73ZM1911.495 429.957l82.745 47.773v95.546l-82.745 47.773-82.745-47.773V477.73Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f910%22 d=%22m2077.745 429.957 82.745 47.773v95.546l-82.745 47.773L1995 573.276V477.73Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m2243.995 429.957 82.745 47.773v95.546l-82.745 47.773-82.745-47.773V477.73ZM2410.245 429.957l82.745 47.773v95.546l-82.745 47.773-82.745-47.773V477.73Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f974%22 d=%22m165.87 573.276 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f99f%22 d=%22m332.12 573.276 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9bb%22 d=%22m498.37 573.276 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m664.62 573.276 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f919%22 d=%22m830.87 573.276 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m997.12 573.276 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1163.37 573.276l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1329.62 573.276l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9b4%22 d=%22m1495.87 573.276 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f983%22 d=%22m1662.12 573.276 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9ac%22 d=%22m1828.37 573.276 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1994.62 573.276 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9ca%22 d=%22m2160.87 573.276 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m2327.12 573.276 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2493.37 573.276l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f966%22 d=%22m82.745 716.595 82.745 47.773v95.546l-82.745 47.773L0 859.914v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m248.995 716.595 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM415.245 716.595l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9bb%22 d=%22m581.495 716.595 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m747.745 716.595 82.745 47.773v95.546l-82.745 47.773L665 859.914v-95.546ZM913.995 716.595l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1080.245 716.595l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f99e%22 d=%22m1246.495 716.595 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f91f%22 d=%22m1412.745 716.595 82.745 47.773v95.546l-82.745 47.773L1330 859.914v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1578.995 716.595 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9a1%22 d=%22m1745.245 716.595 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f900%22 d=%22m1911.495 716.595 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m2077.745 716.595 82.745 47.773v95.546l-82.745 47.773L1995 859.914v-95.546ZM2243.995 716.595l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2410.245 716.595l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM165.87 859.914l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM332.12 859.914l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f92d%22 d=%22m498.37 859.914 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m664.62 859.914 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM830.87 859.914l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f92e%22 d=%22m997.12 859.914 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f966%22 d=%22m1163.37 859.914 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1329.62 859.914 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1495.87 859.914l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1662.12 859.914l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1828.37 859.914l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9a2%22 d=%22m1994.62 859.914 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m2160.87 859.914 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f97d%22 d=%22m2327.12 859.914 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m2493.37 859.914 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f94f%22 d=%22m82.745 1003.233 82.745 47.773v95.546l-82.745 47.773L0 1146.552v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f974%22 d=%22m248.995 1003.233 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m415.245 1003.233 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM581.495 1003.233l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM747.745 1003.233l82.745 47.773v95.546l-82.745 47.773L665 1146.552v-95.546ZM913.995 1003.233l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1080.245 1003.233l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f958%22 d=%22m1246.495 1003.233 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1412.745 1003.233 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f98e%22 d=%22m1578.995 1003.233 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1745.245 1003.233 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1911.495 1003.233l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2077.745 1003.233l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9b6%22 d=%22m2243.995 1003.233 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m2410.245 1003.233 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM165.87 1146.552l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM332.12 1146.552l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM498.37 1146.552l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM664.62 1146.552l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM830.87 1146.552l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM997.12 1146.552l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1163.37 1146.552l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1329.62 1146.552l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1495.87 1146.552l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1662.12 1146.552l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1828.37 1146.552l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1994.62 1146.552l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f92f%22 d=%22m2160.87 1146.552 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m2327.12 1146.552 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2493.37 1146.552l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM82.745 1289.87l82.745 47.774v95.546l-82.745 47.773L0 1433.19v-95.546ZM248.995 1289.87l82.745 47.774v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f94f%22 d=%22m415.245 1289.87 82.745 47.774v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m581.495 1289.87 82.745 47.774v95.546l-82.745 47.773-82.745-47.773v-95.546ZM747.745 1289.87l82.745 47.774v95.546l-82.745 47.773L665 1433.19v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f920%22 d=%22m913.995 1289.87 82.745 47.774v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1080.245 1289.87 82.745 47.774v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1246.495 1289.87l82.745 47.774v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1412.745 1289.87l82.745 47.774v95.546l-82.745 47.773L1330 1433.19v-95.546ZM1578.995 1289.87l82.745 47.774v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1745.245 1289.87l82.745 47.774v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1911.495 1289.87l82.745 47.774v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f919%22 d=%22m2077.745 1289.87 82.745 47.774v95.546l-82.745 47.773L1995 1433.19v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m2243.995 1289.87 82.745 47.774v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9b1%22 d=%22m2410.245 1289.87 82.745 47.774v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m165.87 1433.19 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f92c%22 d=%22m332.12 1433.19 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m498.37 1433.19 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM664.62 1433.19l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM830.87 1433.19l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f908%22 d=%22m997.12 1433.19 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1163.37 1433.19 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1329.62 1433.19l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1495.87 1433.19l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f974%22 d=%22m1662.12 1433.19 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1828.37 1433.19 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1994.62 1433.19l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2160.87 1433.19l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2327.12 1433.19l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2493.37 1433.19l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM82.745 1576.509l82.745 47.773v95.546L82.745 1767.6 0 1719.828v-95.546ZM248.995 1576.509l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM415.245 1576.509l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM581.495 1576.509l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM747.745 1576.509l82.745 47.773v95.546l-82.745 47.773L665 1719.828v-95.546ZM913.995 1576.509l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1080.245 1576.509l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1246.495 1576.509l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1412.745 1576.509l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9c4%22 d=%22m1578.995 1576.509 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1745.245 1576.509 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1911.495 1576.509l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2077.745 1576.509l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2243.995 1576.509l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2410.245 1576.509l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f945%22 d=%22m165.87 1719.828 82.745 47.773v95.546l-82.745 47.773-82.745-47.773V1767.6Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f970%22 d=%22m332.12 1719.828 82.745 47.773v95.546l-82.745 47.773-82.745-47.773V1767.6Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m498.37 1719.828 82.745 47.773v95.546l-82.745 47.773-82.745-47.773V1767.6ZM664.62 1719.828l82.745 47.773v95.546l-82.745 47.773-82.745-47.773V1767.6Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f939%22 d=%22m830.87 1719.828 82.745 47.773v95.546l-82.745 47.773-82.745-47.773V1767.6Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f92c%22 d=%22m997.12 1719.828 82.745 47.773v95.546l-82.745 47.773-82.745-47.773V1767.6Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1163.37 1719.828 82.745 47.773v95.546l-82.745 47.773-82.745-47.773V1767.6Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f99b%22 d=%22m1329.62 1719.828 82.745 47.773v95.546l-82.745 47.773-82.745-47.773V1767.6Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1495.87 1719.828 82.745 47.773v95.546l-82.745 47.773-82.745-47.773V1767.6Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9a6%22 d=%22m1662.12 1719.828 82.745 47.773v95.546l-82.745 47.773-82.745-47.773V1767.6Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1828.37 1719.828 82.745 47.773v95.546l-82.745 47.773-82.745-47.773V1767.6ZM1994.62 1719.828l82.745 47.773v95.546l-82.745 47.773-82.745-47.773V1767.6ZM2160.87 1719.828l82.745 47.773v95.546l-82.745 47.773-82.745-47.773V1767.6ZM2327.12 1719.828l82.745 47.773v95.546l-82.745 47.773-82.745-47.773V1767.6Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f959%22 d=%22m2493.37 1719.828 82.745 47.773v95.546l-82.745 47.773-82.745-47.773V1767.6Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m82.745 1863.147 82.745 47.773v95.546l-82.745 47.773L0 2006.466v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f959%22 d=%22m248.995 1863.147 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m415.245 1863.147 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9ac%22 d=%22m581.495 1863.147 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m747.745 1863.147 82.745 47.773v95.546l-82.745 47.773L665 2006.466v-95.546ZM913.995 1863.147l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9b4%22 d=%22m1080.245 1863.147 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1246.495 1863.147 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1412.745 1863.147l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1578.995 1863.147l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1745.245 1863.147l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1911.495 1863.147l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2077.745 1863.147l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2243.995 1863.147l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f90f%22 d=%22m2410.245 1863.147 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m165.87 2006.466 82.745 47.773v95.545l-82.745 47.773-82.745-47.773v-95.545ZM332.12 2006.466l82.745 47.773v95.545l-82.745 47.773-82.745-47.773v-95.545ZM498.37 2006.466l82.745 47.773v95.545l-82.745 47.773-82.745-47.773v-95.545ZM664.62 2006.466l82.745 47.773v95.545l-82.745 47.773-82.745-47.773v-95.545ZM830.87 2006.466l82.745 47.773v95.545l-82.745 47.773-82.745-47.773v-95.545Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f951%22 d=%22m997.12 2006.466 82.745 47.773v95.545l-82.745 47.773-82.745-47.773v-95.545Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1163.37 2006.466 82.745 47.773v95.545l-82.745 47.773-82.745-47.773v-95.545Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f91b%22 d=%22m1329.62 2006.466 82.745 47.773v95.545l-82.745 47.773-82.745-47.773v-95.545Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f935%22 d=%22m1495.87 2006.466 82.745 47.773v95.545l-82.745 47.773-82.745-47.773v-95.545Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1662.12 2006.466 82.745 47.773v95.545l-82.745 47.773-82.745-47.773v-95.545ZM1828.37 2006.466l82.745 47.773v95.545l-82.745 47.773-82.745-47.773v-95.545ZM1994.62 2006.466l82.745 47.773v95.545l-82.745 47.773-82.745-47.773v-95.545ZM2160.87 2006.466l82.745 47.773v95.545l-82.745 47.773-82.745-47.773v-95.545ZM2327.12 2006.466l82.745 47.773v95.545l-82.745 47.773-82.745-47.773v-95.545ZM2493.37 2006.466l82.745 47.773v95.545l-82.745 47.773-82.745-47.773v-95.545ZM82.745 2149.784l82.745 47.773v95.546l-82.745 47.773L0 2293.103v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f980%22 d=%22m248.995 2149.784 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m415.245 2149.784 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM581.495 2149.784l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM747.745 2149.784l82.745 47.773v95.546l-82.745 47.773L665 2293.103v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f916%22 d=%22m913.995 2149.784 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1080.245 2149.784 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1246.495 2149.784l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f933%22 d=%22m1412.745 2149.784 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1578.995 2149.784 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1745.245 2149.784l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f954%22 d=%22m1911.495 2149.784 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f998%22 d=%22m2077.745 2149.784 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m2243.995 2149.784 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f937%22 d=%22m2410.245 2149.784 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m165.87 2293.103 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f96c%22 d=%22m332.12 2293.103 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m498.37 2293.103 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM664.62 2293.103l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f94e%22 d=%22m830.87 2293.103 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m997.12 2293.103 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1163.37 2293.103l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1329.62 2293.103l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1495.87 2293.103l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1662.12 2293.103l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1828.37 2293.103l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f969%22 d=%22m1994.62 2293.103 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f934%22 d=%22m2160.87 2293.103 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f970%22 d=%22m2327.12 2293.103 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f92f%22 d=%22m2493.37 2293.103 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m82.745 2436.422 82.745 47.773v95.546l-82.745 47.773L0 2579.741v-95.546ZM248.995 2436.422l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM415.245 2436.422l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM581.495 2436.422l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9b5%22 d=%22m747.745 2436.422 82.745 47.773v95.546l-82.745 47.773L665 2579.741v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m913.995 2436.422 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1080.245 2436.422l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1246.495 2436.422l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1412.745 2436.422l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f966%22 d=%22m1578.995 2436.422 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1745.245 2436.422 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f985%22 d=%22m1911.495 2436.422 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m2077.745 2436.422 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2243.995 2436.422l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2410.245 2436.422l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f95f%22 d=%22m165.87 2579.741 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m332.12 2579.741 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f977%22 d=%22m498.37 2579.741 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m664.62 2579.741 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM830.87 2579.741l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM997.12 2579.741l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1163.37 2579.741l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1329.62 2579.741l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1495.87 2579.741l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1662.12 2579.741l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1828.37 2579.741l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1994.62 2579.741l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f97f%22 d=%22m2160.87 2579.741 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m2327.12 2579.741 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2493.37 2579.741l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM82.745 2723.06l82.745 47.773v95.546l-82.745 47.773L0 2866.38v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f922%22 d=%22m248.995 2723.06 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m415.245 2723.06 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM581.495 2723.06l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM747.745 2723.06l82.745 47.773v95.546l-82.745 47.773L665 2866.38v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f994%22 d=%22m913.995 2723.06 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f913%22 d=%22m1080.245 2723.06 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f952%22 d=%22m1246.495 2723.06 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9b7%22 d=%22m1412.745 2723.06 82.745 47.773v95.546l-82.745 47.773L1330 2866.38v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1578.995 2723.06 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1745.245 2723.06l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f95f%22 d=%22m1911.495 2723.06 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m2077.745 2723.06 82.745 47.773v95.546l-82.745 47.773L1995 2866.38v-95.546ZM2243.995 2723.06l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2410.245 2723.06l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM165.87 2866.38l82.745 47.772v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9a3%22 d=%22m332.12 2866.38 82.745 47.772v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m498.37 2866.38 82.745 47.772v95.546l-82.745 47.773-82.745-47.773v-95.546ZM664.62 2866.38l82.745 47.772v95.546l-82.745 47.773-82.745-47.773v-95.546ZM830.87 2866.38l82.745 47.772v95.546l-82.745 47.773-82.745-47.773v-95.546ZM997.12 2866.38l82.745 47.772v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f942%22 d=%22m1163.37 2866.38 82.745 47.772v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1329.62 2866.38 82.745 47.772v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f952%22 d=%22m1495.87 2866.38 82.745 47.772v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1662.12 2866.38 82.745 47.772v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1828.37 2866.38l82.745 47.772v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1994.62 2866.38l82.745 47.772v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2160.87 2866.38l82.745 47.772v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2327.12 2866.38l82.745 47.772v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f924%22 d=%22m2493.37 2866.38 82.745 47.772v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m82.745 3009.698 82.745 47.773v95.546l-82.745 47.773L0 3153.017v-95.546ZM248.995 3009.698l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f925%22 d=%22m415.245 3009.698 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f928%22 d=%22m581.495 3009.698 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m747.745 3009.698 82.745 47.773v95.546l-82.745 47.773L665 3153.017v-95.546ZM913.995 3009.698l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f91c%22 d=%22m1080.245 3009.698 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f912%22 d=%22m1246.495 3009.698 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1412.745 3009.698 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1578.995 3009.698l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1745.245 3009.698l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1911.495 3009.698l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f932%22 d=%22m2077.745 3009.698 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m2243.995 3009.698 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2410.245 3009.698l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM165.87 3153.017l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f998%22 d=%22m332.12 3153.017 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f98a%22 d=%22m498.37 3153.017 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9b7%22 d=%22m664.62 3153.017 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m830.87 3153.017 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM997.12 3153.017l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1163.37 3153.017l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1329.62 3153.017l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f966%22 d=%22m1495.87 3153.017 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1662.12 3153.017 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1828.37 3153.017l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1994.62 3153.017l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f93b%22 d=%22m2160.87 3153.017 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m2327.12 3153.017 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f92f%22 d=%22m2493.37 3153.017 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m82.745 3296.336 82.745 47.773v95.546l-82.745 47.773L0 3439.655v-95.546ZM248.995 3296.336l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM415.245 3296.336l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f92a%22 d=%22m581.495 3296.336 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m747.745 3296.336 82.745 47.773v95.546l-82.745 47.773L665 3439.655v-95.546ZM913.995 3296.336l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1080.245 3296.336l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1246.495 3296.336l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1412.745 3296.336l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f907%22 d=%22m1578.995 3296.336 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1745.245 3296.336 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1911.495 3296.336l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2077.745 3296.336l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f97e%22 d=%22m2243.995 3296.336 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m2410.245 3296.336 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9cb%22 d=%22m165.87 3439.655 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9ce%22 d=%22m332.12 3439.655 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m498.37 3439.655 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f93a%22 d=%22m664.62 3439.655 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f98a%22 d=%22m830.87 3439.655 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m997.12 3439.655 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1163.37 3439.655l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1329.62 3439.655l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1495.87 3439.655l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1662.12 3439.655l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1828.37 3439.655l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1994.62 3439.655l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2160.87 3439.655l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2327.12 3439.655l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2493.37 3439.655l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f902%22 d=%22m82.745 3582.974 82.745 47.773v95.546l-82.745 47.773L0 3726.293v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f98c%22 d=%22m248.995 3582.974 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m415.245 3582.974 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f92f%22 d=%22m581.495 3582.974 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f971%22 d=%22m747.745 3582.974 82.745 47.773v95.546l-82.745 47.773L665 3726.293v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m913.995 3582.974 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1080.245 3582.974l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1246.495 3582.974l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f96c%22 d=%22m1412.745 3582.974 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1578.995 3582.974 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f904%22 d=%22m1745.245 3582.974 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1911.495 3582.974 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2077.745 3582.974l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2243.995 3582.974l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2410.245 3582.974l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f96a%22 d=%22m165.87 3726.293 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f974%22 d=%22m332.12 3726.293 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m498.37 3726.293 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM664.62 3726.293l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f935%22 d=%22m830.87 3726.293 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m997.12 3726.293 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1163.37 3726.293l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1329.62 3726.293l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f942%22 d=%22m1495.87 3726.293 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1662.12 3726.293 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1828.37 3726.293l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1994.62 3726.293l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2160.87 3726.293l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2327.12 3726.293l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2493.37 3726.293l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM82.745 3869.612l82.745 47.773v95.546l-82.745 47.773L0 4012.931v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f97e%22 d=%22m248.995 3869.612 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f930%22 d=%22m415.245 3869.612 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m581.495 3869.612 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM747.745 3869.612l82.745 47.773v95.546l-82.745 47.773L665 4012.931v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f924%22 d=%22m913.995 3869.612 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9a8%22 d=%22m1080.245 3869.612 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1246.495 3869.612 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1412.745 3869.612l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1578.995 3869.612l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1745.245 3869.612l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1911.495 3869.612l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2077.745 3869.612l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2243.995 3869.612l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2410.245 3869.612l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM165.87 4012.931l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM332.12 4012.931l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM498.37 4012.931l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM664.62 4012.931l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM830.87 4012.931l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM997.12 4012.931l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1163.37 4012.931l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1329.62 4012.931l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1495.87 4012.931l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1662.12 4012.931l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f972%22 d=%22m1828.37 4012.931 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1994.62 4012.931 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2160.87 4012.931l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9ac%22 d=%22m2327.12 4012.931 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9ad%22 d=%22m2493.37 4012.931 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m82.745 4156.25 82.745 47.773v95.546l-82.745 47.773L0 4299.569v-95.546ZM248.995 4156.25l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f96d%22 d=%22m415.245 4156.25 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f93b%22 d=%22m581.495 4156.25 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m747.745 4156.25 82.745 47.773v95.546l-82.745 47.773L665 4299.569v-95.546ZM913.995 4156.25l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1080.245 4156.25l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1246.495 4156.25l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1412.745 4156.25l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1578.995 4156.25l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f945%22 d=%22m1745.245 4156.25 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1911.495 4156.25 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2077.745 4156.25l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2243.995 4156.25l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f954%22 d=%22m2410.245 4156.25 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m165.87 4299.569 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f942%22 d=%22m332.12 4299.569 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m498.37 4299.569 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM664.62 4299.569l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM830.87 4299.569l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f924%22 d=%22m997.12 4299.569 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1163.37 4299.569 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1329.62 4299.569l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1495.87 4299.569l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f99e%22 d=%22m1662.12 4299.569 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f93e%22 d=%22m1828.37 4299.569 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1994.62 4299.569 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2160.87 4299.569l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2327.12 4299.569l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2493.37 4299.569l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM82.745 4442.888l82.745 47.773v95.546l-82.745 47.773L0 4586.207v-95.546ZM248.995 4442.888l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM415.245 4442.888l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM581.495 4442.888l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM747.745 4442.888l82.745 47.773v95.546l-82.745 47.773L665 4586.207v-95.546ZM913.995 4442.888l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1080.245 4442.888l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9b3%22 d=%22m1246.495 4442.888 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1412.745 4442.888 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1578.995 4442.888l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9bd%22 d=%22m1745.245 4442.888 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1911.495 4442.888 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2077.745 4442.888l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2243.995 4442.888l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2410.245 4442.888l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f99a%22 d=%22m165.87 4586.207 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f950%22 d=%22m332.12 4586.207 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m498.37 4586.207 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM664.62 4586.207l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f93c%22 d=%22m830.87 4586.207 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m997.12 4586.207 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1163.37 4586.207l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1329.62 4586.207l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1495.87 4586.207l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f926%22 d=%22m1662.12 4586.207 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1828.37 4586.207 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1994.62 4586.207l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2160.87 4586.207l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f946%22 d=%22m2327.12 4586.207 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m2493.37 4586.207 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM82.745 4729.526l82.745 47.773v95.546l-82.745 47.773L0 4872.845v-95.546ZM248.995 4729.526l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM415.245 4729.526l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM581.495 4729.526l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM747.745 4729.526l82.745 47.773v95.546l-82.745 47.773L665 4872.845v-95.546ZM913.995 4729.526l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1080.245 4729.526l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f966%22 d=%22m1246.495 4729.526 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9a5%22 d=%22m1412.745 4729.526 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f960%22 d=%22m1578.995 4729.526 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1745.245 4729.526 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1911.495 4729.526l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2077.745 4729.526l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2243.995 4729.526l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2410.245 4729.526l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM165.87 4872.845l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM332.12 4872.845l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f923%22 d=%22m498.37 4872.845 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f910%22 d=%22m664.62 4872.845 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f962%22 d=%22m830.87 4872.845 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m997.12 4872.845 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1163.37 4872.845l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1329.62 4872.845l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1495.87 4872.845l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1662.12 4872.845l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1828.37 4872.845l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1994.62 4872.845l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2160.87 4872.845l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f95f%22 d=%22m2327.12 4872.845 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m2493.37 4872.845 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM82.745 5016.164l82.745 47.773v95.546l-82.745 47.773L0 5159.483v-95.546ZM248.995 5016.164l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM415.245 5016.164l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM581.495 5016.164l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM747.745 5016.164l82.745 47.773v95.546l-82.745 47.773L665 5159.483v-95.546ZM913.995 5016.164l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1080.245 5016.164l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f965%22 d=%22m1246.495 5016.164 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1412.745 5016.164 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1578.995 5016.164l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9b5%22 d=%22m1745.245 5016.164 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1911.495 5016.164 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f971%22 d=%22m2077.745 5016.164 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f97b%22 d=%22m2243.995 5016.164 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m2410.245 5016.164 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM165.87 5159.483l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM332.12 5159.483l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM498.37 5159.483l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9b7%22 d=%22m664.62 5159.483 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m830.87 5159.483 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM997.12 5159.483l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f993%22 d=%22m1163.37 5159.483 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f9bc%22 d=%22m1329.62 5159.483 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m1495.87 5159.483 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1662.12 5159.483l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM1828.37 5159.483l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22%23f1f5f988%22 d=%22m1994.62 5159.483 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3Cpath stroke=%22%23f1f5f9cf%22 stroke-width=%221.91092%22 fill=%22none%22 d=%22m2160.87 5159.483 82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2327.12 5159.483l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546ZM2493.37 5159.483l82.745 47.773v95.546l-82.745 47.773-82.745-47.773v-95.546Z%22%2F%3E%3C%2Fg%3E%3Cdefs%3E%3CradialGradient id=%22a%22%3E%3Cstop offset=%220%22 stop-color=%22%23fff%22%2F%3E%3Cstop offset=%221%22 stop-color=%22%23fff%22 stop-opacity=%220%22%2F%3E%3C%2FradialGradient%3E%3C%2Fdefs%3E%3C%2Fsvg%3E");
}
</style>
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
pages/p/[slug].vue | Vue | <script setup lang="ts">
const route = useRoute()
const slug = computed(() => route.params.slug.toString())
const { data } = await useFetch<DBComponent[]>(`/api/component/${slug.value}`)
const sfcString = ref(data.value?.[0].code ?? '')
const errorMessage = ref(data.value?.[0].error)
onMounted(() => {
window.addEventListener('message', (e: MessageEvent) => {
const message = e.data as { from: string, data: IframeData }
if (e.origin === location.origin && message.from === 'vue0') {
sfcString.value = message.data.code
errorMessage.value = message.data.error
}
})
})
definePageMeta({
layout: 'blank',
})
useHead({
script: [
{ src: 'https://cdn.jsdelivr.net/gh/zernonia/vue0/public/cdn/tailwind.js' },
],
})
</script>
<template>
<div>
<OutputWrapper>
<Output v-if="sfcString || errorMessage" :sfc-string="sfcString" :error-message="errorMessage" />
</OutputWrapper>
</div>
</template>
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
pages/s/[id].vue | Vue | <script setup lang="ts">
const route = useRoute()
const id = computed(() => route.params.id.toString())
const { data } = await useFetch<DBComponent[]>(`/api/component/id/${id.value}`)
const sfcString = ref(data.value?.[0].code ?? '')
definePageMeta({
layout: 'blank',
})
useHead({
script: [
{ src: 'https://cdn.jsdelivr.net/gh/zernonia/vue0/public/cdn/tailwind.js' },
],
})
</script>
<template>
<div>
<OutputWrapper>
<Output v-if="sfcString" :sfc-string="sfcString" />
</OutputWrapper>
</div>
</template>
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
pages/t/[slug].vue | Vue | <script setup lang="ts">
import { upperFirst } from 'scule'
import { AlertTriangle, Clipboard, ClipboardCheck, Clock, Code2Icon, GitBranch, IterationCw, MoreVertical, MousePointerSquare, Share, Trash, Trash2 } from 'lucide-vue-next'
import { differenceInMinutes } from 'date-fns'
import { useToast } from '~/components/ui/toast'
const route = useRoute()
const slug = computed(() => route.params.slug.toString())
const { toast } = useToast()
const { data, refresh } = await useFetch<DBComponent[]>(`/api/component/${slug.value}`)
const { user } = useUserSession()
const dataUser = computed(() => data.value?.at(-1)?.user)
const isUserCreator = computed(() => dataUser.value?.id === user.value?.id)
const selectedVersion = ref<NonNullable<typeof data.value>[number]>()
const iframeRef = ref<HTMLIFrameElement>()
watch(data, (n) => {
const item = n?.[0]
selectedVersion.value = item
sendDataToIframe({ code: item?.code ?? '', error: item?.error })
}, { immediate: true })
const prompt = ref('')
const { loading, contentCode, onDone, onStream, onError, isNewPrompt, handleInit, handleIterate, handleCreate } = usePrompt()
const sfcString = computed(() => selectedVersion.value?.code ?? contentCode.value ?? '')
const isGenerationStucked = computed(() => {
if (selectedVersion.value?.completed || loading.value)
return false
if (selectedVersion.value?.error)
return true
return differenceInMinutes(
new Date(),
new Date(selectedVersion.value!.createdAt!),
) > 5 // if stuck more than 5 minutes show regenerate button
})
function sendDataToIframe(data: IframeData) {
const channel = new MessageChannel()
if (iframeRef.value)
iframeRef.value.contentWindow?.postMessage({ from: 'vue0', data }, '*', [channel.port2])
}
function handleChangeVersion(version: DBComponent) {
selectedVersion.value = version
sendDataToIframe({ code: version.code!, error: version.error })
}
function handleRegenerate() {
if (!selectedVersion.value)
return
const payload = {
id: selectedVersion.value.id,
prompt: selectedVersion.value.description,
}
if (selectedVersion.value === data.value?.at(-1))
handleCreate(payload)
else handleIterate(payload)
}
async function handleSubmit() {
if (!prompt.value)
return
umTrackEvent('iterate-generation', { slug: slug.value })
const basedOnResultId = selectedVersion.value?.id
const result = await handleInit(prompt.value, selectedVersion.value?.slug, basedOnResultId)
data.value = [result, ...(data.value ?? [])]
handleIterate({
id: result.id,
prompt: result.description,
})
}
onStream(data => sendDataToIframe({ code: data }))
onError((err) => {
refresh()
toast({
title: 'Error',
description: err,
variant: 'destructive',
})
sendDataToIframe({ code: '', error: err })
})
onDone(() => {
refresh()
prompt.value = ''
toast({
title: 'Completed',
description: 'Latest generation is completed!',
})
})
onMounted(() => {
if (isNewPrompt.value && data.value?.length === 1) {
// need not to handleInit as it will be done on the landing page
handleCreate({
id: data.value[0].id,
prompt: data.value[0].description,
})
}
})
const dropdownOpen = ref(false)
const isPreviewing = ref(false)
const { copy, copied } = useClipboard()
const { copy: copyLink } = useClipboard()
function handleShare() {
copyLink(location.href)
umTrackEvent('share-generation', { slug: slug.value })
}
const isForking = ref(false)
async function handleFork() {
isForking.value = true
umTrackEvent('fork-generation')
try {
const result = await $fetch<DBComponent>('/api/component/fork', {
method: 'POST',
body: {
id: selectedVersion.value?.id,
slug: slug.value,
},
})
if (result.id)
navigateTo(`/t/${result.slug}`)
}
catch (err) {
console.log(err)
}
finally {
isForking.value = false
}
}
const isDeleting = ref(false)
async function handleDelete(all = false) {
isDeleting.value = true
const body = all ? { slug: slug.value, id: selectedVersion.value?.id } : { id: selectedVersion.value?.id }
umTrackEvent('delete-generation')
try {
const result = await $fetch<DBComponent>('/api/component/delete', {
method: 'POST',
body,
})
if (result) {
if (all)
await navigateTo('/')
else
await refresh()
}
}
catch (err) {
console.log(err)
}
finally {
isDeleting.value = false
dropdownOpen.value = false
}
}
const componentDescription = computed(() => upperFirst(data.value?.at(-1)?.description ?? ''))
// Page meta section
useHead({
title() {
return componentDescription.value
},
})
defineOgImageComponent('Generated', {
title: componentDescription.value,
avatarUrl: dataUser.value?.avatarUrl,
imageUrl: `${useRuntimeConfig().public.siteUrl}/api/image/${slug.value}?slug=true`,
})
</script>
<template>
<div class="pb-2 md:pb-8">
<div class="flex flex-col md:flex-row w-full">
<div class="flex-shrink-0 md:mt-4 md:mr-4 flex flex-row md:flex-col items-center gap-3 ">
<div class="flex gap-2 items-center">
<Clock class="w-4 h-4 text-gray-400" />
<span class="text-gray-400 font-medium text-sm hidden md:inline-flex">Versions</span>
</div>
<div class="flex flex-row-reverse md:flex-col-reverse gap-3 overflow-auto p-1">
<div
v-for="(version, index) in data"
:key="version.id"
>
<UiTooltip :delay-duration="500">
<UiTooltipTrigger as-child>
<UiButton
class="justify-start h-auto min-w-[6rem] min-h-6 p-1 overflow-hidden text-left text-gray-400 rounded-lg outline-1 hover:text-primary relative "
:class="{ 'outline outline-primary !text-primary': selectedVersion?.id === version.id }"
variant="secondary"
@click="handleChangeVersion(version)"
>
<UiBadge variant="outline" class="bg-white absolute bottom-2 left-2">
v{{ data!.length - 1 - index }}
</UiBadge>
<img :src="`/api/image/${version.id}`" class="aspect-video object-cover w-32 h-auto">
</UiButton>
</UiTooltipTrigger>
<UiTooltipContent align="start" side="right" class="max-w-64 flex flex-col gap-2 p-1.5">
<img :src="`/api/image/${version.id}`" class="aspect-video object-cover w-auto h-auto rounded">
<span class="text-sm p-0.5">{{ version.description }}</span>
</UiTooltipContent>
</UiTooltip>
</div>
</div>
</div>
<div class="flex-1 mt-2 md:mt-0 w-full">
<div class="flex justify-between">
<div class="flex items-center gap-2">
<NuxtLink v-if="dataUser" class="inline-flex" :to="`/${dataUser.name}`">
<UiAvatar class="w-9 h-9">
<UiAvatarImage :src="dataUser.avatarUrl ?? ''" />
<UiAvatarFallback>{{ dataUser.name?.slice(0, 1) }}</UiAvatarFallback>
</UiAvatar>
</NuxtLink>
<div class="text-sm max-w-[9rem] md:max-w-[32rem] text-ellipsis whitespace-nowrap overflow-hidden">
{{ selectedVersion?.description }}
</div>
</div>
<div class="flex items-center gap-2">
<UiTooltip v-if="selectedVersion?.error">
<UiTooltipTrigger class="text-destructive mr-2">
<AlertTriangle class="p-0.5" />
</UiTooltipTrigger>
<UiTooltipContent class="bg-destructive" side="bottom">
Error {{ selectedVersion?.error }}
</UiTooltipContent>
</UiTooltip>
<UiDropdownMenu v-model:open="dropdownOpen">
<UiDropdownMenuTrigger as-child>
<UiButton
size="icon"
variant="outline"
>
<MoreVertical class="p-1" />
</UiButton>
</UiDropdownMenuTrigger>
<UiDropdownMenuContent align="end">
<UiDropdownMenuItem :disabled="!sfcString" @click="handleFork">
<GitBranch class="py-1 mr-1" />
<span>Fork</span>
</UiDropdownMenuItem>
<UiDropdownMenuItem @click="handleShare">
<Share class="py-1 mr-1" />
<span>Share</span>
</UiDropdownMenuItem>
<template v-if="isUserCreator">
<UiDropdownMenuSeparator />
<DialogDelete
v-if="selectedVersion?.id !== data?.at(-1)?.id"
title="Are you sure you want to delete this version?"
description="This will delete the current selected version. This action cannot be undone."
>
<UiDropdownMenuItem class="!text-destructive" @select.prevent>
<Trash class="py-1 mr-1" />
<span>Delete Version</span>
</UiDropdownMenuItem>
<template #footer>
<UiAlertDialogCancel :disabled="isDeleting">
Cancel
</UiAlertDialogCancel>
<UiAlertDialogAction as-child>
<UiButton variants="'destructive'" :loading="isDeleting" @click="handleDelete()">
Delete Version
</UiButton>
</UiAlertDialogAction>
</template>
</DialogDelete>
<DialogDelete
title="Are you sure you want to delete this generation?"
description="This will delete the generation and all results. This action cannot be undone."
>
<UiDropdownMenuItem class="!text-destructive" @select.prevent>
<Trash2 class="py-1 mr-1" />
<span>Delete Generation</span>
</UiDropdownMenuItem>
<template #footer>
<UiAlertDialogCancel :disabled="isDeleting">
Cancel
</UiAlertDialogCancel>
<UiAlertDialogAction as-child>
<UiButton variants="'destructive'" :loading="isDeleting" @click="handleDelete(true)">
Delete Generation
</UiButton>
</UiAlertDialogAction>
</template>
</DialogDelete>
</template>
</UiDropdownMenuContent>
</UiDropdownMenu>
<UiButton v-if="isGenerationStucked && isUserCreator" class="px-1.5 md:px-4" :disabled="loading && !sfcString" variant="outline" @click="handleRegenerate(); umTrackEvent('regenerate-code', { id: selectedVersion?.id! }) ">
<IterationCw class="py-1 md:mr-1 md:-ml-1" />
<span class="hidden md:inline">Regenerate</span>
</UiButton>
<template v-else>
<UiButton class="px-1.5 md:px-4" :loading="loading && !sfcString" :disabled="!sfcString" variant="outline" @click="copy(selectedVersion?.code ?? ''); umTrackEvent('copy-code', { slug }) ">
<ClipboardCheck v-if="copied" class="py-1 md:mr-1 md:-ml-1" />
<Clipboard v-else class="py-1 md:mr-1 md:-ml-1" />
<span class="hidden md:inline">{{ copied ? 'Copied' : 'Copy' }}</span>
</UiButton>
<UiButton class="px-1.5 md:px-4" :loading="loading && !sfcString" :disabled="!sfcString" @click="isPreviewing = !isPreviewing">
<MousePointerSquare v-if="isPreviewing" class="py-1 md:mr-1 md:-ml-1" />
<Code2Icon v-else class="py-1 md:mr-1 md:-ml-1" />
<span class="hidden md:inline">{{ isPreviewing ? 'Preview' : 'Code' }}</span>
</UiButton>
</template>
</div>
</div>
<div class="relative z-0 flex w-full mt-3 md:mt-4 overflow-hidden border rounded-xl" :class="[isUserCreator ? 'h-[calc(100vh-14rem)]' : 'h-[calc(100vh-10rem)]']">
<LazyOutputCode v-show="isPreviewing" :sfc-string="sfcString" />
<iframe ref="iframeRef" :src="`/p/${slug}`" class="w-full h-full" />
</div>
</div>
</div>
<div v-if="isUserCreator && !selectedVersion?.error" class="relative flex items-center justify-center w-full gap-2 mt-3 md:mt-16">
<PromptInput v-model="prompt" :loading="loading" class="md:absolute bottom-0 w-full md:w-fit md:-translate-x-1/2 left-1/2" placeholder="Make the padding larger" @submit="handleSubmit" />
</div>
</div>
</template>
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
public/cdn/tailwind.js | JavaScript | (()=>{var Qx=Object.create;var xn=Object.defineProperty;var Jx=Object.getOwnPropertyDescriptor;var Xx=Object.getOwnPropertyNames;var Kx=Object.getPrototypeOf,Zx=Object.prototype.hasOwnProperty;var Gc=t=>xn(t,"__esModule",{value:!0});var Hc=t=>{if(typeof require!="undefined")return require(t);throw new Error('Dynamic require of "'+t+'" is not supported')};var A=(t,e)=>()=>(t&&(e=t(t=0)),e);var k=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ge=(t,e)=>{Gc(t);for(var r in e)xn(t,r,{get:e[r],enumerable:!0})},ek=(t,e,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Xx(e))!Zx.call(t,i)&&i!=="default"&&xn(t,i,{get:()=>e[i],enumerable:!(r=Jx(e,i))||r.enumerable});return t},ce=t=>ek(Gc(xn(t!=null?Qx(Kx(t)):{},"default",t&&t.__esModule&&"default"in t?{get:()=>t.default,enumerable:!0}:{value:t,enumerable:!0})),t);var g,l=A(()=>{g={platform:"",env:{},versions:{node:"14.17.6"}}});var tk,me,ft=A(()=>{l();tk=0,me={readFileSync:t=>self[t]||"",statSync:()=>({mtimeMs:tk++}),promises:{readFile:t=>Promise.resolve(self[t]||"")}}});var Aa=k((_L,Qc)=>{l();"use strict";var Yc=class{constructor(e={}){if(!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");if(typeof e.maxAge=="number"&&e.maxAge===0)throw new TypeError("`maxAge` must be a number greater than 0");this.maxSize=e.maxSize,this.maxAge=e.maxAge||1/0,this.onEviction=e.onEviction,this.cache=new Map,this.oldCache=new Map,this._size=0}_emitEvictions(e){if(typeof this.onEviction=="function")for(let[r,i]of e)this.onEviction(r,i.value)}_deleteIfExpired(e,r){return typeof r.expiry=="number"&&r.expiry<=Date.now()?(typeof this.onEviction=="function"&&this.onEviction(e,r.value),this.delete(e)):!1}_getOrDeleteIfExpired(e,r){if(this._deleteIfExpired(e,r)===!1)return r.value}_getItemValue(e,r){return r.expiry?this._getOrDeleteIfExpired(e,r):r.value}_peek(e,r){let i=r.get(e);return this._getItemValue(e,i)}_set(e,r){this.cache.set(e,r),this._size++,this._size>=this.maxSize&&(this._size=0,this._emitEvictions(this.oldCache),this.oldCache=this.cache,this.cache=new Map)}_moveToRecent(e,r){this.oldCache.delete(e),this._set(e,r)}*_entriesAscending(){for(let e of this.oldCache){let[r,i]=e;this.cache.has(r)||this._deleteIfExpired(r,i)===!1&&(yield e)}for(let e of this.cache){let[r,i]=e;this._deleteIfExpired(r,i)===!1&&(yield e)}}get(e){if(this.cache.has(e)){let r=this.cache.get(e);return this._getItemValue(e,r)}if(this.oldCache.has(e)){let r=this.oldCache.get(e);if(this._deleteIfExpired(e,r)===!1)return this._moveToRecent(e,r),r.value}}set(e,r,{maxAge:i=this.maxAge===1/0?void 0:Date.now()+this.maxAge}={}){this.cache.has(e)?this.cache.set(e,{value:r,maxAge:i}):this._set(e,{value:r,expiry:i})}has(e){return this.cache.has(e)?!this._deleteIfExpired(e,this.cache.get(e)):this.oldCache.has(e)?!this._deleteIfExpired(e,this.oldCache.get(e)):!1}peek(e){if(this.cache.has(e))return this._peek(e,this.cache);if(this.oldCache.has(e))return this._peek(e,this.oldCache)}delete(e){let r=this.cache.delete(e);return r&&this._size--,this.oldCache.delete(e)||r}clear(){this.cache.clear(),this.oldCache.clear(),this._size=0}resize(e){if(!(e&&e>0))throw new TypeError("`maxSize` must be a number greater than 0");let r=[...this._entriesAscending()],i=r.length-e;i<0?(this.cache=new Map(r),this.oldCache=new Map,this._size=r.length):(i>0&&this._emitEvictions(r.slice(0,i)),this.oldCache=new Map(r.slice(i)),this.cache=new Map,this._size=0),this.maxSize=e}*keys(){for(let[e]of this)yield e}*values(){for(let[,e]of this)yield e}*[Symbol.iterator](){for(let e of this.cache){let[r,i]=e;this._deleteIfExpired(r,i)===!1&&(yield[r,i.value])}for(let e of this.oldCache){let[r,i]=e;this.cache.has(r)||this._deleteIfExpired(r,i)===!1&&(yield[r,i.value])}}*entriesDescending(){let e=[...this.cache];for(let r=e.length-1;r>=0;--r){let i=e[r],[n,s]=i;this._deleteIfExpired(n,s)===!1&&(yield[n,s.value])}e=[...this.oldCache];for(let r=e.length-1;r>=0;--r){let i=e[r],[n,s]=i;this.cache.has(n)||this._deleteIfExpired(n,s)===!1&&(yield[n,s.value])}}*entriesAscending(){for(let[e,r]of this._entriesAscending())yield[e,r.value]}get size(){if(!this._size)return this.oldCache.size;let e=0;for(let r of this.oldCache.keys())this.cache.has(r)||e++;return Math.min(this._size+e,this.maxSize)}};Qc.exports=Yc});var Jc,Xc=A(()=>{l();Jc=t=>t&&t._hash});function kn(t){return Jc(t,{ignoreUnknown:!0})}var Kc=A(()=>{l();Xc()});function _t(t){if(t=`${t}`,t==="0")return"0";if(/^[+-]?(\d+|\d*\.\d+)(e[+-]?\d+)?(%|\w+)?$/.test(t))return t.replace(/^[+-]?/,r=>r==="-"?"":"-");let e=["var","calc","min","max","clamp"];for(let r of e)if(t.includes(`${r}(`))return`calc(${t} * -1)`}var Sn=A(()=>{l()});var Zc,ep=A(()=>{l();Zc=["preflight","container","accessibility","pointerEvents","visibility","position","inset","isolation","zIndex","order","gridColumn","gridColumnStart","gridColumnEnd","gridRow","gridRowStart","gridRowEnd","float","clear","margin","boxSizing","lineClamp","display","aspectRatio","size","height","maxHeight","minHeight","width","minWidth","maxWidth","flex","flexShrink","flexGrow","flexBasis","tableLayout","captionSide","borderCollapse","borderSpacing","transformOrigin","translate","rotate","skew","scale","transform","animation","cursor","touchAction","userSelect","resize","scrollSnapType","scrollSnapAlign","scrollSnapStop","scrollMargin","scrollPadding","listStylePosition","listStyleType","listStyleImage","appearance","columns","breakBefore","breakInside","breakAfter","gridAutoColumns","gridAutoFlow","gridAutoRows","gridTemplateColumns","gridTemplateRows","flexDirection","flexWrap","placeContent","placeItems","alignContent","alignItems","justifyContent","justifyItems","gap","space","divideWidth","divideStyle","divideColor","divideOpacity","placeSelf","alignSelf","justifySelf","overflow","overscrollBehavior","scrollBehavior","textOverflow","hyphens","whitespace","textWrap","wordBreak","borderRadius","borderWidth","borderStyle","borderColor","borderOpacity","backgroundColor","backgroundOpacity","backgroundImage","gradientColorStops","boxDecorationBreak","backgroundSize","backgroundAttachment","backgroundClip","backgroundPosition","backgroundRepeat","backgroundOrigin","fill","stroke","strokeWidth","objectFit","objectPosition","padding","textAlign","textIndent","verticalAlign","fontFamily","fontSize","fontWeight","textTransform","fontStyle","fontVariantNumeric","lineHeight","letterSpacing","textColor","textOpacity","textDecoration","textDecorationColor","textDecorationStyle","textDecorationThickness","textUnderlineOffset","fontSmoothing","placeholderColor","placeholderOpacity","caretColor","accentColor","opacity","backgroundBlendMode","mixBlendMode","boxShadow","boxShadowColor","outlineStyle","outlineWidth","outlineOffset","outlineColor","ringWidth","ringColor","ringOpacity","ringOffsetWidth","ringOffsetColor","blur","brightness","contrast","dropShadow","grayscale","hueRotate","invert","saturate","sepia","filter","backdropBlur","backdropBrightness","backdropContrast","backdropGrayscale","backdropHueRotate","backdropInvert","backdropOpacity","backdropSaturate","backdropSepia","backdropFilter","transitionProperty","transitionDelay","transitionDuration","transitionTimingFunction","willChange","content","forcedColorAdjust"]});function tp(t,e){return t===void 0?e:Array.isArray(t)?t:[...new Set(e.filter(i=>t!==!1&&t[i]!==!1).concat(Object.keys(t).filter(i=>t[i]!==!1)))]}var rp=A(()=>{l()});var ip={};Ge(ip,{default:()=>He});var He,_n=A(()=>{l();He=new Proxy({},{get:()=>String})});function Ca(t,e,r){typeof g!="undefined"&&g.env.JEST_WORKER_ID||r&&np.has(r)||(r&&np.add(r),console.warn(""),e.forEach(i=>console.warn(t,"-",i)))}function Pa(t){return He.dim(t)}var np,V,Ye=A(()=>{l();_n();np=new Set;V={info(t,e){Ca(He.bold(He.cyan("info")),...Array.isArray(t)?[t]:[e,t])},warn(t,e){["content-problems"].includes(t)||Ca(He.bold(He.yellow("warn")),...Array.isArray(t)?[t]:[e,t])},risk(t,e){Ca(He.bold(He.magenta("risk")),...Array.isArray(t)?[t]:[e,t])}}});var Da={};Ge(Da,{default:()=>Ia});function Vr({version:t,from:e,to:r}){V.warn(`${e}-color-renamed`,[`As of Tailwind CSS ${t}, \`${e}\` has been renamed to \`${r}\`.`,"Update your configuration file to silence this warning."])}var Ia,Tn=A(()=>{l();Ye();Ia={inherit:"inherit",current:"currentColor",transparent:"transparent",black:"#000",white:"#fff",slate:{50:"#f8fafc",100:"#f1f5f9",200:"#e2e8f0",300:"#cbd5e1",400:"#94a3b8",500:"#64748b",600:"#475569",700:"#334155",800:"#1e293b",900:"#0f172a",950:"#020617"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},zinc:{50:"#fafafa",100:"#f4f4f5",200:"#e4e4e7",300:"#d4d4d8",400:"#a1a1aa",500:"#71717a",600:"#52525b",700:"#3f3f46",800:"#27272a",900:"#18181b",950:"#09090b"},neutral:{50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"},stone:{50:"#fafaf9",100:"#f5f5f4",200:"#e7e5e4",300:"#d6d3d1",400:"#a8a29e",500:"#78716c",600:"#57534e",700:"#44403c",800:"#292524",900:"#1c1917",950:"#0c0a09"},red:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d",950:"#450a0a"},orange:{50:"#fff7ed",100:"#ffedd5",200:"#fed7aa",300:"#fdba74",400:"#fb923c",500:"#f97316",600:"#ea580c",700:"#c2410c",800:"#9a3412",900:"#7c2d12",950:"#431407"},amber:{50:"#fffbeb",100:"#fef3c7",200:"#fde68a",300:"#fcd34d",400:"#fbbf24",500:"#f59e0b",600:"#d97706",700:"#b45309",800:"#92400e",900:"#78350f",950:"#451a03"},yellow:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12",950:"#422006"},lime:{50:"#f7fee7",100:"#ecfccb",200:"#d9f99d",300:"#bef264",400:"#a3e635",500:"#84cc16",600:"#65a30d",700:"#4d7c0f",800:"#3f6212",900:"#365314",950:"#1a2e05"},green:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d",950:"#052e16"},emerald:{50:"#ecfdf5",100:"#d1fae5",200:"#a7f3d0",300:"#6ee7b7",400:"#34d399",500:"#10b981",600:"#059669",700:"#047857",800:"#065f46",900:"#064e3b",950:"#022c22"},teal:{50:"#f0fdfa",100:"#ccfbf1",200:"#99f6e4",300:"#5eead4",400:"#2dd4bf",500:"#14b8a6",600:"#0d9488",700:"#0f766e",800:"#115e59",900:"#134e4a",950:"#042f2e"},cyan:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},sky:{50:"#f0f9ff",100:"#e0f2fe",200:"#bae6fd",300:"#7dd3fc",400:"#38bdf8",500:"#0ea5e9",600:"#0284c7",700:"#0369a1",800:"#075985",900:"#0c4a6e",950:"#082f49"},blue:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},indigo:{50:"#eef2ff",100:"#e0e7ff",200:"#c7d2fe",300:"#a5b4fc",400:"#818cf8",500:"#6366f1",600:"#4f46e5",700:"#4338ca",800:"#3730a3",900:"#312e81",950:"#1e1b4b"},violet:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},purple:{50:"#faf5ff",100:"#f3e8ff",200:"#e9d5ff",300:"#d8b4fe",400:"#c084fc",500:"#a855f7",600:"#9333ea",700:"#7e22ce",800:"#6b21a8",900:"#581c87",950:"#3b0764"},fuchsia:{50:"#fdf4ff",100:"#fae8ff",200:"#f5d0fe",300:"#f0abfc",400:"#e879f9",500:"#d946ef",600:"#c026d3",700:"#a21caf",800:"#86198f",900:"#701a75",950:"#4a044e"},pink:{50:"#fdf2f8",100:"#fce7f3",200:"#fbcfe8",300:"#f9a8d4",400:"#f472b6",500:"#ec4899",600:"#db2777",700:"#be185d",800:"#9d174d",900:"#831843",950:"#500724"},rose:{50:"#fff1f2",100:"#ffe4e6",200:"#fecdd3",300:"#fda4af",400:"#fb7185",500:"#f43f5e",600:"#e11d48",700:"#be123c",800:"#9f1239",900:"#881337",950:"#4c0519"},get lightBlue(){return Vr({version:"v2.2",from:"lightBlue",to:"sky"}),this.sky},get warmGray(){return Vr({version:"v3.0",from:"warmGray",to:"stone"}),this.stone},get trueGray(){return Vr({version:"v3.0",from:"trueGray",to:"neutral"}),this.neutral},get coolGray(){return Vr({version:"v3.0",from:"coolGray",to:"gray"}),this.gray},get blueGray(){return Vr({version:"v3.0",from:"blueGray",to:"slate"}),this.slate}}});function qa(t,...e){for(let r of e){for(let i in r)t?.hasOwnProperty?.(i)||(t[i]=r[i]);for(let i of Object.getOwnPropertySymbols(r))t?.hasOwnProperty?.(i)||(t[i]=r[i])}return t}var sp=A(()=>{l()});function Tt(t){if(Array.isArray(t))return t;let e=t.split("[").length-1,r=t.split("]").length-1;if(e!==r)throw new Error(`Path is invalid. Has unbalanced brackets: ${t}`);return t.split(/\.(?![^\[]*\])|[\[\]]/g).filter(Boolean)}var On=A(()=>{l()});function pe(t,e){return En.future.includes(e)?t.future==="all"||(t?.future?.[e]??ap[e]??!1):En.experimental.includes(e)?t.experimental==="all"||(t?.experimental?.[e]??ap[e]??!1):!1}function op(t){return t.experimental==="all"?En.experimental:Object.keys(t?.experimental??{}).filter(e=>En.experimental.includes(e)&&t.experimental[e])}function lp(t){if(g.env.JEST_WORKER_ID===void 0&&op(t).length>0){let e=op(t).map(r=>He.yellow(r)).join(", ");V.warn("experimental-flags-enabled",[`You have enabled experimental features: ${e}`,"Experimental features in Tailwind CSS are not covered by semver, may introduce breaking changes, and can change at any time."])}}var ap,En,ct=A(()=>{l();_n();Ye();ap={optimizeUniversalDefaults:!1,generalizedModifiers:!0,get disableColorOpacityUtilitiesByDefault(){return!1},get relativeContentPathsByDefault(){return!1}},En={future:["hoverOnlyWhenSupported","respectDefaultRingColorOpacity","disableColorOpacityUtilitiesByDefault","relativeContentPathsByDefault"],experimental:["optimizeUniversalDefaults","generalizedModifiers"]}});function up(t){(()=>{if(t.purge||!t.content||!Array.isArray(t.content)&&!(typeof t.content=="object"&&t.content!==null))return!1;if(Array.isArray(t.content))return t.content.every(r=>typeof r=="string"?!0:!(typeof r?.raw!="string"||r?.extension&&typeof r?.extension!="string"));if(typeof t.content=="object"&&t.content!==null){if(Object.keys(t.content).some(r=>!["files","relative","extract","transform"].includes(r)))return!1;if(Array.isArray(t.content.files)){if(!t.content.files.every(r=>typeof r=="string"?!0:!(typeof r?.raw!="string"||r?.extension&&typeof r?.extension!="string")))return!1;if(typeof t.content.extract=="object"){for(let r of Object.values(t.content.extract))if(typeof r!="function")return!1}else if(!(t.content.extract===void 0||typeof t.content.extract=="function"))return!1;if(typeof t.content.transform=="object"){for(let r of Object.values(t.content.transform))if(typeof r!="function")return!1}else if(!(t.content.transform===void 0||typeof t.content.transform=="function"))return!1;if(typeof t.content.relative!="boolean"&&typeof t.content.relative!="undefined")return!1}return!0}return!1})()||V.warn("purge-deprecation",["The `purge`/`content` options have changed in Tailwind CSS v3.0.","Update your configuration file to eliminate this warning.","https://tailwindcss.com/docs/upgrade-guide#configure-content-sources"]),t.safelist=(()=>{let{content:r,purge:i,safelist:n}=t;return Array.isArray(n)?n:Array.isArray(r?.safelist)?r.safelist:Array.isArray(i?.safelist)?i.safelist:Array.isArray(i?.options?.safelist)?i.options.safelist:[]})(),t.blocklist=(()=>{let{blocklist:r}=t;if(Array.isArray(r)){if(r.every(i=>typeof i=="string"))return r;V.warn("blocklist-invalid",["The `blocklist` option must be an array of strings.","https://tailwindcss.com/docs/content-configuration#discarding-classes"])}return[]})(),typeof t.prefix=="function"?(V.warn("prefix-function",["As of Tailwind CSS v3.0, `prefix` cannot be a function.","Update `prefix` in your configuration to be a string to eliminate this warning.","https://tailwindcss.com/docs/upgrade-guide#prefix-cannot-be-a-function"]),t.prefix=""):t.prefix=t.prefix??"",t.content={relative:(()=>{let{content:r}=t;return r?.relative?r.relative:pe(t,"relativeContentPathsByDefault")})(),files:(()=>{let{content:r,purge:i}=t;return Array.isArray(i)?i:Array.isArray(i?.content)?i.content:Array.isArray(r)?r:Array.isArray(r?.content)?r.content:Array.isArray(r?.files)?r.files:[]})(),extract:(()=>{let r=(()=>t.purge?.extract?t.purge.extract:t.content?.extract?t.content.extract:t.purge?.extract?.DEFAULT?t.purge.extract.DEFAULT:t.content?.extract?.DEFAULT?t.content.extract.DEFAULT:t.purge?.options?.extractors?t.purge.options.extractors:t.content?.options?.extractors?t.content.options.extractors:{})(),i={},n=(()=>{if(t.purge?.options?.defaultExtractor)return t.purge.options.defaultExtractor;if(t.content?.options?.defaultExtractor)return t.content.options.defaultExtractor})();if(n!==void 0&&(i.DEFAULT=n),typeof r=="function")i.DEFAULT=r;else if(Array.isArray(r))for(let{extensions:s,extractor:a}of r??[])for(let o of s)i[o]=a;else typeof r=="object"&&r!==null&&Object.assign(i,r);return i})(),transform:(()=>{let r=(()=>t.purge?.transform?t.purge.transform:t.content?.transform?t.content.transform:t.purge?.transform?.DEFAULT?t.purge.transform.DEFAULT:t.content?.transform?.DEFAULT?t.content.transform.DEFAULT:{})(),i={};return typeof r=="function"&&(i.DEFAULT=r),typeof r=="object"&&r!==null&&Object.assign(i,r),i})()};for(let r of t.content.files)if(typeof r=="string"&&/{([^,]*?)}/g.test(r)){V.warn("invalid-glob-braces",[`The glob pattern ${Pa(r)} in your Tailwind CSS configuration is invalid.`,`Update it to ${Pa(r.replace(/{([^,]*?)}/g,"$1"))} to silence this warning.`]);break}return t}var fp=A(()=>{l();ct();Ye()});function we(t){if(Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||Object.getPrototypeOf(e)===null}var tr=A(()=>{l()});function Ot(t){return Array.isArray(t)?t.map(e=>Ot(e)):typeof t=="object"&&t!==null?Object.fromEntries(Object.entries(t).map(([e,r])=>[e,Ot(r)])):t}var An=A(()=>{l()});function jt(t){return t.replace(/\\,/g,"\\2c ")}var Cn=A(()=>{l()});var Ra,cp=A(()=>{l();Ra={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}});function Wr(t,{loose:e=!1}={}){if(typeof t!="string")return null;if(t=t.trim(),t==="transparent")return{mode:"rgb",color:["0","0","0"],alpha:"0"};if(t in Ra)return{mode:"rgb",color:Ra[t].map(s=>s.toString())};let r=t.replace(ik,(s,a,o,u,c)=>["#",a,a,o,o,u,u,c?c+c:""].join("")).match(rk);if(r!==null)return{mode:"rgb",color:[parseInt(r[1],16),parseInt(r[2],16),parseInt(r[3],16)].map(s=>s.toString()),alpha:r[4]?(parseInt(r[4],16)/255).toString():void 0};let i=t.match(nk)??t.match(sk);if(i===null)return null;let n=[i[2],i[3],i[4]].filter(Boolean).map(s=>s.toString());return n.length===2&&n[0].startsWith("var(")?{mode:i[1],color:[n[0]],alpha:n[1]}:!e&&n.length!==3||n.length<3&&!n.some(s=>/^var\(.*?\)$/.test(s))?null:{mode:i[1],color:n,alpha:i[5]?.toString?.()}}function La({mode:t,color:e,alpha:r}){let i=r!==void 0;return t==="rgba"||t==="hsla"?`${t}(${e.join(", ")}${i?`, ${r}`:""})`:`${t}(${e.join(" ")}${i?` / ${r}`:""})`}var rk,ik,Et,Pn,pp,At,nk,sk,Ba=A(()=>{l();cp();rk=/^#([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i,ik=/^#([a-f\d])([a-f\d])([a-f\d])([a-f\d])?$/i,Et=/(?:\d+|\d*\.\d+)%?/,Pn=/(?:\s*,\s*|\s+)/,pp=/\s*[,/]\s*/,At=/var\(--(?:[^ )]*?)(?:,(?:[^ )]*?|var\(--[^ )]*?\)))?\)/,nk=new RegExp(`^(rgba?)\\(\\s*(${Et.source}|${At.source})(?:${Pn.source}(${Et.source}|${At.source}))?(?:${Pn.source}(${Et.source}|${At.source}))?(?:${pp.source}(${Et.source}|${At.source}))?\\s*\\)$`),sk=new RegExp(`^(hsla?)\\(\\s*((?:${Et.source})(?:deg|rad|grad|turn)?|${At.source})(?:${Pn.source}(${Et.source}|${At.source}))?(?:${Pn.source}(${Et.source}|${At.source}))?(?:${pp.source}(${Et.source}|${At.source}))?\\s*\\)$`)});function Ze(t,e,r){if(typeof t=="function")return t({opacityValue:e});let i=Wr(t,{loose:!0});return i===null?r:La({...i,alpha:e})}function _e({color:t,property:e,variable:r}){let i=[].concat(e);if(typeof t=="function")return{[r]:"1",...Object.fromEntries(i.map(s=>[s,t({opacityVariable:r,opacityValue:`var(${r})`})]))};let n=Wr(t);return n===null?Object.fromEntries(i.map(s=>[s,t])):n.alpha!==void 0?Object.fromEntries(i.map(s=>[s,t])):{[r]:"1",...Object.fromEntries(i.map(s=>[s,La({...n,alpha:`var(${r})`})]))}}var Gr=A(()=>{l();Ba()});function Te(t,e){let r=[],i=[],n=0,s=!1;for(let a=0;a<t.length;a++){let o=t[a];r.length===0&&o===e[0]&&!s&&(e.length===1||t.slice(a,a+e.length)===e)&&(i.push(t.slice(n,a)),n=a+e.length),s?s=!1:o==="\\"&&(s=!0),o==="("||o==="["||o==="{"?r.push(o):(o===")"&&r[r.length-1]==="("||o==="]"&&r[r.length-1]==="["||o==="}"&&r[r.length-1]==="{")&&r.pop()}return i.push(t.slice(n)),i}var rr=A(()=>{l()});function In(t){return Te(t,",").map(r=>{let i=r.trim(),n={raw:i},s=i.split(ok),a=new Set;for(let o of s)dp.lastIndex=0,!a.has("KEYWORD")&&ak.has(o)?(n.keyword=o,a.add("KEYWORD")):dp.test(o)?a.has("X")?a.has("Y")?a.has("BLUR")?a.has("SPREAD")||(n.spread=o,a.add("SPREAD")):(n.blur=o,a.add("BLUR")):(n.y=o,a.add("Y")):(n.x=o,a.add("X")):n.color?(n.unknown||(n.unknown=[]),n.unknown.push(o)):n.color=o;return n.valid=n.x!==void 0&&n.y!==void 0,n})}function hp(t){return t.map(e=>e.valid?[e.keyword,e.x,e.y,e.blur,e.spread,e.color].filter(Boolean).join(" "):e.raw).join(", ")}var ak,ok,dp,Ma=A(()=>{l();rr();ak=new Set(["inset","inherit","initial","revert","unset"]),ok=/\ +(?![^(]*\))/g,dp=/^-?(\d+|\.\d+)(.*?)$/g});function Fa(t){return lk.some(e=>new RegExp(`^${e}\\(.*\\)`).test(t))}function G(t,e=null,r=!0){let i=e&&uk.has(e.property);return t.startsWith("--")&&!i?`var(${t})`:t.includes("url(")?t.split(/(url\(.*?\))/g).filter(Boolean).map(n=>/^url\(.*?\)$/.test(n)?n:G(n,e,!1)).join(""):(t=t.replace(/([^\\])_+/g,(n,s)=>s+" ".repeat(n.length-1)).replace(/^_/g," ").replace(/\\_/g,"_"),r&&(t=t.trim()),t=fk(t),t)}function fk(t){let e=["theme"],r=["min-content","max-content","fit-content","safe-area-inset-top","safe-area-inset-right","safe-area-inset-bottom","safe-area-inset-left","titlebar-area-x","titlebar-area-y","titlebar-area-width","titlebar-area-height","keyboard-inset-top","keyboard-inset-right","keyboard-inset-bottom","keyboard-inset-left","keyboard-inset-width","keyboard-inset-height"];return t.replace(/(calc|min|max|clamp)\(.+\)/g,i=>{let n="";function s(){let a=n.trimEnd();return a[a.length-1]}for(let a=0;a<i.length;a++){let o=function(f){return f.split("").every((p,h)=>i[a+h]===p)},u=function(f){let p=1/0;for(let m of f){let v=i.indexOf(m,a);v!==-1&&v<p&&(p=v)}let h=i.slice(a,p);return a+=h.length-1,h},c=i[a];if(o("var"))n+=u([")",","]);else if(r.some(f=>o(f))){let f=r.find(p=>o(p));n+=f,a+=f.length-1}else e.some(f=>o(f))?n+=u([")"]):["+","-","*","/"].includes(c)&&!["(","+","-","*","/",","].includes(s())?n+=` ${c} `:n+=c}return n.replace(/\s+/g," ")})}function Na(t){return t.startsWith("url(")}function za(t){return!isNaN(Number(t))||Fa(t)}function Hr(t){return t.endsWith("%")&&za(t.slice(0,-1))||Fa(t)}function Yr(t){return t==="0"||new RegExp(`^[+-]?[0-9]*.?[0-9]+(?:[eE][+-]?[0-9]+)?${pk}$`).test(t)||Fa(t)}function mp(t){return dk.has(t)}function gp(t){let e=In(G(t));for(let r of e)if(!r.valid)return!1;return!0}function yp(t){let e=0;return Te(t,"_").every(i=>(i=G(i),i.startsWith("var(")?!0:Wr(i,{loose:!0})!==null?(e++,!0):!1))?e>0:!1}function vp(t){let e=0;return Te(t,",").every(i=>(i=G(i),i.startsWith("var(")?!0:Na(i)||mk(i)||["element(","image(","cross-fade(","image-set("].some(n=>i.startsWith(n))?(e++,!0):!1))?e>0:!1}function mk(t){t=G(t);for(let e of hk)if(t.startsWith(`${e}(`))return!0;return!1}function wp(t){let e=0;return Te(t,"_").every(i=>(i=G(i),i.startsWith("var(")?!0:gk.has(i)||Yr(i)||Hr(i)?(e++,!0):!1))?e>0:!1}function bp(t){let e=0;return Te(t,",").every(i=>(i=G(i),i.startsWith("var(")?!0:i.includes(" ")&&!/(['"])([^"']+)\1/g.test(i)||/^\d/g.test(i)?!1:(e++,!0)))?e>0:!1}function xp(t){return yk.has(t)}function kp(t){return vk.has(t)}function Sp(t){return wk.has(t)}var lk,uk,ck,pk,dk,hk,gk,yk,vk,wk,Qr=A(()=>{l();Ba();Ma();rr();lk=["min","max","clamp","calc"];uk=new Set(["scroll-timeline-name","timeline-scope","view-timeline-name","font-palette","scroll-timeline","animation-timeline","view-timeline"]);ck=["cm","mm","Q","in","pc","pt","px","em","ex","ch","rem","lh","rlh","vw","vh","vmin","vmax","vb","vi","svw","svh","lvw","lvh","dvw","dvh","cqw","cqh","cqi","cqb","cqmin","cqmax"],pk=`(?:${ck.join("|")})`;dk=new Set(["thin","medium","thick"]);hk=new Set(["conic-gradient","linear-gradient","radial-gradient","repeating-conic-gradient","repeating-linear-gradient","repeating-radial-gradient"]);gk=new Set(["center","top","right","bottom","left"]);yk=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]);vk=new Set(["xx-small","x-small","small","medium","large","x-large","x-large","xxx-large"]);wk=new Set(["larger","smaller"])});function _p(t){let e=["cover","contain"];return Te(t,",").every(r=>{let i=Te(r,"_").filter(Boolean);return i.length===1&&e.includes(i[0])?!0:i.length!==1&&i.length!==2?!1:i.every(n=>Yr(n)||Hr(n)||n==="auto")})}var Tp=A(()=>{l();Qr();rr()});function Op(t,e){t.walkClasses(r=>{r.value=e(r.value),r.raws&&r.raws.value&&(r.raws.value=jt(r.raws.value))})}function Ep(t,e){if(!Ct(t))return;let r=t.slice(1,-1);if(!!e(r))return G(r)}function bk(t,e={},r){let i=e[t];if(i!==void 0)return _t(i);if(Ct(t)){let n=Ep(t,r);return n===void 0?void 0:_t(n)}}function Dn(t,e={},{validate:r=()=>!0}={}){let i=e.values?.[t];return i!==void 0?i:e.supportsNegativeValues&&t.startsWith("-")?bk(t.slice(1),e.values,r):Ep(t,r)}function Ct(t){return t.startsWith("[")&&t.endsWith("]")}function Ap(t){let e=t.lastIndexOf("/"),r=t.lastIndexOf("[",e),i=t.indexOf("]",e);return t[e-1]==="]"||t[e+1]==="["||r!==-1&&i!==-1&&r<e&&e<i&&(e=t.lastIndexOf("/",r)),e===-1||e===t.length-1?[t,void 0]:Ct(t)&&!t.includes("]/[")?[t,void 0]:[t.slice(0,e),t.slice(e+1)]}function ir(t){if(typeof t=="string"&&t.includes("<alpha-value>")){let e=t;return({opacityValue:r=1})=>e.replace("<alpha-value>",r)}return t}function Cp(t){return G(t.slice(1,-1))}function xk(t,e={},{tailwindConfig:r={}}={}){if(e.values?.[t]!==void 0)return ir(e.values?.[t]);let[i,n]=Ap(t);if(n!==void 0){let s=e.values?.[i]??(Ct(i)?i.slice(1,-1):void 0);return s===void 0?void 0:(s=ir(s),Ct(n)?Ze(s,Cp(n)):r.theme?.opacity?.[n]===void 0?void 0:Ze(s,r.theme.opacity[n]))}return Dn(t,e,{validate:yp})}function kk(t,e={}){return e.values?.[t]}function De(t){return(e,r)=>Dn(e,r,{validate:t})}function Sk(t,e){let r=t.indexOf(e);return r===-1?[void 0,t]:[t.slice(0,r),t.slice(r+1)]}function ja(t,e,r,i){if(r.values&&e in r.values)for(let{type:s}of t??[]){let a=$a[s](e,r,{tailwindConfig:i});if(a!==void 0)return[a,s,null]}if(Ct(e)){let s=e.slice(1,-1),[a,o]=Sk(s,":");if(!/^[\w-_]+$/g.test(a))o=s;else if(a!==void 0&&!Pp.includes(a))return[];if(o.length>0&&Pp.includes(a))return[Dn(`[${o}]`,r),a,null]}let n=Ua(t,e,r,i);for(let s of n)return s;return[]}function*Ua(t,e,r,i){let n=pe(i,"generalizedModifiers"),[s,a]=Ap(e);if(n&&r.modifiers!=null&&(r.modifiers==="any"||typeof r.modifiers=="object"&&(a&&Ct(a)||a in r.modifiers))||(s=e,a=void 0),a!==void 0&&s===""&&(s="DEFAULT"),a!==void 0&&typeof r.modifiers=="object"){let u=r.modifiers?.[a]??null;u!==null?a=u:Ct(a)&&(a=Cp(a))}for(let{type:u}of t??[]){let c=$a[u](s,r,{tailwindConfig:i});c!==void 0&&(yield[c,u,a??null])}}var $a,Pp,Jr=A(()=>{l();Cn();Gr();Qr();Sn();Tp();ct();$a={any:Dn,color:xk,url:De(Na),image:De(vp),length:De(Yr),percentage:De(Hr),position:De(wp),lookup:kk,"generic-name":De(xp),"family-name":De(bp),number:De(za),"line-width":De(mp),"absolute-size":De(kp),"relative-size":De(Sp),shadow:De(gp),size:De(_p)},Pp=Object.keys($a)});function H(t){return typeof t=="function"?t({}):t}var Va=A(()=>{l()});function nr(t){return typeof t=="function"}function Xr(t,...e){let r=e.pop();for(let i of e)for(let n in i){let s=r(t[n],i[n]);s===void 0?we(t[n])&&we(i[n])?t[n]=Xr({},t[n],i[n],r):t[n]=i[n]:t[n]=s}return t}function _k(t,...e){return nr(t)?t(...e):t}function Tk(t){return t.reduce((e,{extend:r})=>Xr(e,r,(i,n)=>i===void 0?[n]:Array.isArray(i)?[n,...i]:[n,i]),{})}function Ok(t){return{...t.reduce((e,r)=>qa(e,r),{}),extend:Tk(t)}}function Ip(t,e){if(Array.isArray(t)&&we(t[0]))return t.concat(e);if(Array.isArray(e)&&we(e[0])&&we(t))return[t,...e];if(Array.isArray(e))return e}function Ek({extend:t,...e}){return Xr(e,t,(r,i)=>!nr(r)&&!i.some(nr)?Xr({},r,...i,Ip):(n,s)=>Xr({},...[r,...i].map(a=>_k(a,n,s)),Ip))}function*Ak(t){let e=Tt(t);if(e.length===0||(yield e,Array.isArray(t)))return;let r=/^(.*?)\s*\/\s*([^/]+)$/,i=t.match(r);if(i!==null){let[,n,s]=i,a=Tt(n);a.alpha=s,yield a}}function Ck(t){let e=(r,i)=>{for(let n of Ak(r)){let s=0,a=t;for(;a!=null&&s<n.length;)a=a[n[s++]],a=nr(a)&&(n.alpha===void 0||s<=n.length-1)?a(e,Wa):a;if(a!==void 0){if(n.alpha!==void 0){let o=ir(a);return Ze(o,n.alpha,H(o))}return we(a)?Ot(a):a}}return i};return Object.assign(e,{theme:e,...Wa}),Object.keys(t).reduce((r,i)=>(r[i]=nr(t[i])?t[i](e,Wa):t[i],r),{})}function Dp(t){let e=[];return t.forEach(r=>{e=[...e,r];let i=r?.plugins??[];i.length!==0&&i.forEach(n=>{n.__isOptionsFunction&&(n=n()),e=[...e,...Dp([n?.config??{}])]})}),e}function Pk(t){return[...t].reduceRight((r,i)=>nr(i)?i({corePlugins:r}):tp(i,r),Zc)}function Ik(t){return[...t].reduceRight((r,i)=>[...r,...i],[])}function Ga(t){let e=[...Dp(t),{prefix:"",important:!1,separator:":"}];return up(qa({theme:Ck(Ek(Ok(e.map(r=>r?.theme??{})))),corePlugins:Pk(e.map(r=>r.corePlugins)),plugins:Ik(t.map(r=>r?.plugins??[]))},...e))}var Wa,qp=A(()=>{l();Sn();ep();rp();Tn();sp();On();fp();tr();An();Jr();Gr();Va();Wa={colors:Ia,negative(t){return Object.keys(t).filter(e=>t[e]!=="0").reduce((e,r)=>{let i=_t(t[r]);return i!==void 0&&(e[`-${r}`]=i),e},{})},breakpoints(t){return Object.keys(t).filter(e=>typeof t[e]=="string").reduce((e,r)=>({...e,[`screen-${r}`]:t[r]}),{})}}});var qn=k((EB,Rp)=>{l();Rp.exports={content:[],presets:[],darkMode:"media",theme:{accentColor:({theme:t})=>({...t("colors"),auto:"auto"}),animation:{none:"none",spin:"spin 1s linear infinite",ping:"ping 1s cubic-bezier(0, 0, 0.2, 1) infinite",pulse:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite",bounce:"bounce 1s infinite"},aria:{busy:'busy="true"',checked:'checked="true"',disabled:'disabled="true"',expanded:'expanded="true"',hidden:'hidden="true"',pressed:'pressed="true"',readonly:'readonly="true"',required:'required="true"',selected:'selected="true"'},aspectRatio:{auto:"auto",square:"1 / 1",video:"16 / 9"},backdropBlur:({theme:t})=>t("blur"),backdropBrightness:({theme:t})=>t("brightness"),backdropContrast:({theme:t})=>t("contrast"),backdropGrayscale:({theme:t})=>t("grayscale"),backdropHueRotate:({theme:t})=>t("hueRotate"),backdropInvert:({theme:t})=>t("invert"),backdropOpacity:({theme:t})=>t("opacity"),backdropSaturate:({theme:t})=>t("saturate"),backdropSepia:({theme:t})=>t("sepia"),backgroundColor:({theme:t})=>t("colors"),backgroundImage:{none:"none","gradient-to-t":"linear-gradient(to top, var(--tw-gradient-stops))","gradient-to-tr":"linear-gradient(to top right, var(--tw-gradient-stops))","gradient-to-r":"linear-gradient(to right, var(--tw-gradient-stops))","gradient-to-br":"linear-gradient(to bottom right, var(--tw-gradient-stops))","gradient-to-b":"linear-gradient(to bottom, var(--tw-gradient-stops))","gradient-to-bl":"linear-gradient(to bottom left, var(--tw-gradient-stops))","gradient-to-l":"linear-gradient(to left, var(--tw-gradient-stops))","gradient-to-tl":"linear-gradient(to top left, var(--tw-gradient-stops))"},backgroundOpacity:({theme:t})=>t("opacity"),backgroundPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},backgroundSize:{auto:"auto",cover:"cover",contain:"contain"},blur:{0:"0",none:"0",sm:"4px",DEFAULT:"8px",md:"12px",lg:"16px",xl:"24px","2xl":"40px","3xl":"64px"},borderColor:({theme:t})=>({...t("colors"),DEFAULT:t("colors.gray.200","currentColor")}),borderOpacity:({theme:t})=>t("opacity"),borderRadius:{none:"0px",sm:"0.125rem",DEFAULT:"0.25rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem","3xl":"1.5rem",full:"9999px"},borderSpacing:({theme:t})=>({...t("spacing")}),borderWidth:{DEFAULT:"1px",0:"0px",2:"2px",4:"4px",8:"8px"},boxShadow:{sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",DEFAULT:"0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)",inner:"inset 0 2px 4px 0 rgb(0 0 0 / 0.05)",none:"none"},boxShadowColor:({theme:t})=>t("colors"),brightness:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5",200:"2"},caretColor:({theme:t})=>t("colors"),colors:({colors:t})=>({inherit:t.inherit,current:t.current,transparent:t.transparent,black:t.black,white:t.white,slate:t.slate,gray:t.gray,zinc:t.zinc,neutral:t.neutral,stone:t.stone,red:t.red,orange:t.orange,amber:t.amber,yellow:t.yellow,lime:t.lime,green:t.green,emerald:t.emerald,teal:t.teal,cyan:t.cyan,sky:t.sky,blue:t.blue,indigo:t.indigo,violet:t.violet,purple:t.purple,fuchsia:t.fuchsia,pink:t.pink,rose:t.rose}),columns:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12","3xs":"16rem","2xs":"18rem",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem"},container:{},content:{none:"none"},contrast:{0:"0",50:".5",75:".75",100:"1",125:"1.25",150:"1.5",200:"2"},cursor:{auto:"auto",default:"default",pointer:"pointer",wait:"wait",text:"text",move:"move",help:"help","not-allowed":"not-allowed",none:"none","context-menu":"context-menu",progress:"progress",cell:"cell",crosshair:"crosshair","vertical-text":"vertical-text",alias:"alias",copy:"copy","no-drop":"no-drop",grab:"grab",grabbing:"grabbing","all-scroll":"all-scroll","col-resize":"col-resize","row-resize":"row-resize","n-resize":"n-resize","e-resize":"e-resize","s-resize":"s-resize","w-resize":"w-resize","ne-resize":"ne-resize","nw-resize":"nw-resize","se-resize":"se-resize","sw-resize":"sw-resize","ew-resize":"ew-resize","ns-resize":"ns-resize","nesw-resize":"nesw-resize","nwse-resize":"nwse-resize","zoom-in":"zoom-in","zoom-out":"zoom-out"},divideColor:({theme:t})=>t("borderColor"),divideOpacity:({theme:t})=>t("borderOpacity"),divideWidth:({theme:t})=>t("borderWidth"),dropShadow:{sm:"0 1px 1px rgb(0 0 0 / 0.05)",DEFAULT:["0 1px 2px rgb(0 0 0 / 0.1)","0 1px 1px rgb(0 0 0 / 0.06)"],md:["0 4px 3px rgb(0 0 0 / 0.07)","0 2px 2px rgb(0 0 0 / 0.06)"],lg:["0 10px 8px rgb(0 0 0 / 0.04)","0 4px 3px rgb(0 0 0 / 0.1)"],xl:["0 20px 13px rgb(0 0 0 / 0.03)","0 8px 5px rgb(0 0 0 / 0.08)"],"2xl":"0 25px 25px rgb(0 0 0 / 0.15)",none:"0 0 #0000"},fill:({theme:t})=>({none:"none",...t("colors")}),flex:{1:"1 1 0%",auto:"1 1 auto",initial:"0 1 auto",none:"none"},flexBasis:({theme:t})=>({auto:"auto",...t("spacing"),"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%"}),flexGrow:{0:"0",DEFAULT:"1"},flexShrink:{0:"0",DEFAULT:"1"},fontFamily:{sans:["ui-sans-serif","system-ui","sans-serif",'"Apple Color Emoji"','"Segoe UI Emoji"','"Segoe UI Symbol"','"Noto Color Emoji"'],serif:["ui-serif","Georgia","Cambria",'"Times New Roman"',"Times","serif"],mono:["ui-monospace","SFMono-Regular","Menlo","Monaco","Consolas",'"Liberation Mono"','"Courier New"',"monospace"]},fontSize:{xs:["0.75rem",{lineHeight:"1rem"}],sm:["0.875rem",{lineHeight:"1.25rem"}],base:["1rem",{lineHeight:"1.5rem"}],lg:["1.125rem",{lineHeight:"1.75rem"}],xl:["1.25rem",{lineHeight:"1.75rem"}],"2xl":["1.5rem",{lineHeight:"2rem"}],"3xl":["1.875rem",{lineHeight:"2.25rem"}],"4xl":["2.25rem",{lineHeight:"2.5rem"}],"5xl":["3rem",{lineHeight:"1"}],"6xl":["3.75rem",{lineHeight:"1"}],"7xl":["4.5rem",{lineHeight:"1"}],"8xl":["6rem",{lineHeight:"1"}],"9xl":["8rem",{lineHeight:"1"}]},fontWeight:{thin:"100",extralight:"200",light:"300",normal:"400",medium:"500",semibold:"600",bold:"700",extrabold:"800",black:"900"},gap:({theme:t})=>t("spacing"),gradientColorStops:({theme:t})=>t("colors"),gradientColorStopPositions:{"0%":"0%","5%":"5%","10%":"10%","15%":"15%","20%":"20%","25%":"25%","30%":"30%","35%":"35%","40%":"40%","45%":"45%","50%":"50%","55%":"55%","60%":"60%","65%":"65%","70%":"70%","75%":"75%","80%":"80%","85%":"85%","90%":"90%","95%":"95%","100%":"100%"},grayscale:{0:"0",DEFAULT:"100%"},gridAutoColumns:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridAutoRows:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridColumn:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-7":"span 7 / span 7","span-8":"span 8 / span 8","span-9":"span 9 / span 9","span-10":"span 10 / span 10","span-11":"span 11 / span 11","span-12":"span 12 / span 12","span-full":"1 / -1"},gridColumnEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13"},gridColumnStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13"},gridRow:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-7":"span 7 / span 7","span-8":"span 8 / span 8","span-9":"span 9 / span 9","span-10":"span 10 / span 10","span-11":"span 11 / span 11","span-12":"span 12 / span 12","span-full":"1 / -1"},gridRowEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13"},gridRowStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13"},gridTemplateColumns:{none:"none",subgrid:"subgrid",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))",7:"repeat(7, minmax(0, 1fr))",8:"repeat(8, minmax(0, 1fr))",9:"repeat(9, minmax(0, 1fr))",10:"repeat(10, minmax(0, 1fr))",11:"repeat(11, minmax(0, 1fr))",12:"repeat(12, minmax(0, 1fr))"},gridTemplateRows:{none:"none",subgrid:"subgrid",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))",7:"repeat(7, minmax(0, 1fr))",8:"repeat(8, minmax(0, 1fr))",9:"repeat(9, minmax(0, 1fr))",10:"repeat(10, minmax(0, 1fr))",11:"repeat(11, minmax(0, 1fr))",12:"repeat(12, minmax(0, 1fr))"},height:({theme:t})=>({auto:"auto",...t("spacing"),"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%",full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content"}),hueRotate:{0:"0deg",15:"15deg",30:"30deg",60:"60deg",90:"90deg",180:"180deg"},inset:({theme:t})=>({auto:"auto",...t("spacing"),"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%"}),invert:{0:"0",DEFAULT:"100%"},keyframes:{spin:{to:{transform:"rotate(360deg)"}},ping:{"75%, 100%":{transform:"scale(2)",opacity:"0"}},pulse:{"50%":{opacity:".5"}},bounce:{"0%, 100%":{transform:"translateY(-25%)",animationTimingFunction:"cubic-bezier(0.8,0,1,1)"},"50%":{transform:"none",animationTimingFunction:"cubic-bezier(0,0,0.2,1)"}}},letterSpacing:{tighter:"-0.05em",tight:"-0.025em",normal:"0em",wide:"0.025em",wider:"0.05em",widest:"0.1em"},lineHeight:{none:"1",tight:"1.25",snug:"1.375",normal:"1.5",relaxed:"1.625",loose:"2",3:".75rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem"},listStyleType:{none:"none",disc:"disc",decimal:"decimal"},listStyleImage:{none:"none"},margin:({theme:t})=>({auto:"auto",...t("spacing")}),lineClamp:{1:"1",2:"2",3:"3",4:"4",5:"5",6:"6"},maxHeight:({theme:t})=>({...t("spacing"),none:"none",full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content"}),maxWidth:({theme:t,breakpoints:e})=>({...t("spacing"),none:"none",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem",full:"100%",min:"min-content",max:"max-content",fit:"fit-content",prose:"65ch",...e(t("screens"))}),minHeight:({theme:t})=>({...t("spacing"),full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content"}),minWidth:({theme:t})=>({...t("spacing"),full:"100%",min:"min-content",max:"max-content",fit:"fit-content"}),objectPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},opacity:{0:"0",5:"0.05",10:"0.1",15:"0.15",20:"0.2",25:"0.25",30:"0.3",35:"0.35",40:"0.4",45:"0.45",50:"0.5",55:"0.55",60:"0.6",65:"0.65",70:"0.7",75:"0.75",80:"0.8",85:"0.85",90:"0.9",95:"0.95",100:"1"},order:{first:"-9999",last:"9999",none:"0",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12"},outlineColor:({theme:t})=>t("colors"),outlineOffset:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px"},outlineWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px"},padding:({theme:t})=>t("spacing"),placeholderColor:({theme:t})=>t("colors"),placeholderOpacity:({theme:t})=>t("opacity"),ringColor:({theme:t})=>({DEFAULT:t("colors.blue.500","#3b82f6"),...t("colors")}),ringOffsetColor:({theme:t})=>t("colors"),ringOffsetWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px"},ringOpacity:({theme:t})=>({DEFAULT:"0.5",...t("opacity")}),ringWidth:{DEFAULT:"3px",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px"},rotate:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg",45:"45deg",90:"90deg",180:"180deg"},saturate:{0:"0",50:".5",100:"1",150:"1.5",200:"2"},scale:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5"},screens:{sm:"640px",md:"768px",lg:"1024px",xl:"1280px","2xl":"1536px"},scrollMargin:({theme:t})=>({...t("spacing")}),scrollPadding:({theme:t})=>t("spacing"),sepia:{0:"0",DEFAULT:"100%"},skew:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg"},space:({theme:t})=>({...t("spacing")}),spacing:{px:"1px",0:"0px",.5:"0.125rem",1:"0.25rem",1.5:"0.375rem",2:"0.5rem",2.5:"0.625rem",3:"0.75rem",3.5:"0.875rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem",11:"2.75rem",12:"3rem",14:"3.5rem",16:"4rem",20:"5rem",24:"6rem",28:"7rem",32:"8rem",36:"9rem",40:"10rem",44:"11rem",48:"12rem",52:"13rem",56:"14rem",60:"15rem",64:"16rem",72:"18rem",80:"20rem",96:"24rem"},stroke:({theme:t})=>({none:"none",...t("colors")}),strokeWidth:{0:"0",1:"1",2:"2"},supports:{},data:{},textColor:({theme:t})=>t("colors"),textDecorationColor:({theme:t})=>t("colors"),textDecorationThickness:{auto:"auto","from-font":"from-font",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px"},textIndent:({theme:t})=>({...t("spacing")}),textOpacity:({theme:t})=>t("opacity"),textUnderlineOffset:{auto:"auto",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px"},transformOrigin:{center:"center",top:"top","top-right":"top right",right:"right","bottom-right":"bottom right",bottom:"bottom","bottom-left":"bottom left",left:"left","top-left":"top left"},transitionDelay:{0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1e3:"1000ms"},transitionDuration:{DEFAULT:"150ms",0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1e3:"1000ms"},transitionProperty:{none:"none",all:"all",DEFAULT:"color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter",colors:"color, background-color, border-color, text-decoration-color, fill, stroke",opacity:"opacity",shadow:"box-shadow",transform:"transform"},transitionTimingFunction:{DEFAULT:"cubic-bezier(0.4, 0, 0.2, 1)",linear:"linear",in:"cubic-bezier(0.4, 0, 1, 1)",out:"cubic-bezier(0, 0, 0.2, 1)","in-out":"cubic-bezier(0.4, 0, 0.2, 1)"},translate:({theme:t})=>({...t("spacing"),"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%"}),size:({theme:t})=>({auto:"auto",...t("spacing"),"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",min:"min-content",max:"max-content",fit:"fit-content"}),width:({theme:t})=>({auto:"auto",...t("spacing"),"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",screen:"100vw",svw:"100svw",lvw:"100lvw",dvw:"100dvw",min:"min-content",max:"max-content",fit:"fit-content"}),willChange:{auto:"auto",scroll:"scroll-position",contents:"contents",transform:"transform"},zIndex:{auto:"auto",0:"0",10:"10",20:"20",30:"30",40:"40",50:"50"}},plugins:[]}});function Rn(t){let e=(t?.presets??[Lp.default]).slice().reverse().flatMap(n=>Rn(n instanceof Function?n():n)),r={respectDefaultRingColorOpacity:{theme:{ringColor:({theme:n})=>({DEFAULT:"#3b82f67f",...n("colors")})}},disableColorOpacityUtilitiesByDefault:{corePlugins:{backgroundOpacity:!1,borderOpacity:!1,divideOpacity:!1,placeholderOpacity:!1,ringOpacity:!1,textOpacity:!1}}},i=Object.keys(r).filter(n=>pe(t,n)).map(n=>r[n]);return[t,...i,...e]}var Lp,Bp=A(()=>{l();Lp=ce(qn());ct()});var Mp={};Ge(Mp,{default:()=>Kr});function Kr(...t){let[,...e]=Rn(t[0]);return Ga([...t,...e])}var Ha=A(()=>{l();qp();Bp()});var Fp={};Ge(Fp,{default:()=>de});var de,Ut=A(()=>{l();de={resolve:t=>t,extname:t=>"."+t.split(".").pop()}});function Ln(t){return typeof t=="object"&&t!==null}function qk(t){return Object.keys(t).length===0}function Np(t){return typeof t=="string"||t instanceof String}function Ya(t){return Ln(t)&&t.config===void 0&&!qk(t)?null:Ln(t)&&t.config!==void 0&&Np(t.config)?de.resolve(t.config):Ln(t)&&t.config!==void 0&&Ln(t.config)?null:Np(t)?de.resolve(t):Rk()}function Rk(){for(let t of Dk)try{let e=de.resolve(t);return me.accessSync(e),e}catch(e){}return null}var Dk,zp=A(()=>{l();ft();Ut();Dk=["./tailwind.config.js","./tailwind.config.cjs","./tailwind.config.mjs","./tailwind.config.ts"]});var $p={};Ge($p,{default:()=>Qa});var Qa,Ja=A(()=>{l();Qa={parse:t=>({href:t})}});var Xa=k(()=>{l()});var Bn=k((MB,Vp)=>{l();"use strict";var jp=(_n(),ip),Up=Xa(),sr=class extends Error{constructor(e,r,i,n,s,a){super(e);this.name="CssSyntaxError",this.reason=e,s&&(this.file=s),n&&(this.source=n),a&&(this.plugin=a),typeof r!="undefined"&&typeof i!="undefined"&&(typeof r=="number"?(this.line=r,this.column=i):(this.line=r.line,this.column=r.column,this.endLine=i.line,this.endColumn=i.column)),this.setMessage(),Error.captureStackTrace&&Error.captureStackTrace(this,sr)}setMessage(){this.message=this.plugin?this.plugin+": ":"",this.message+=this.file?this.file:"<css input>",typeof this.line!="undefined"&&(this.message+=":"+this.line+":"+this.column),this.message+=": "+this.reason}showSourceCode(e){if(!this.source)return"";let r=this.source;e==null&&(e=jp.isColorSupported),Up&&e&&(r=Up(r));let i=r.split(/\r?\n/),n=Math.max(this.line-3,0),s=Math.min(this.line+2,i.length),a=String(s).length,o,u;if(e){let{bold:c,red:f,gray:p}=jp.createColors(!0);o=h=>c(f(h)),u=h=>p(h)}else o=u=c=>c;return i.slice(n,s).map((c,f)=>{let p=n+1+f,h=" "+(" "+p).slice(-a)+" | ";if(p===this.line){let m=u(h.replace(/\d/g," "))+c.slice(0,this.column-1).replace(/[^\t]/g," ");return o(">")+u(h)+c+`
`+m+o("^")}return" "+u(h)+c}).join(`
`)}toString(){let e=this.showSourceCode();return e&&(e=`
`+e+`
`),this.name+": "+this.message+e}};Vp.exports=sr;sr.default=sr});var Mn=k((FB,Ka)=>{l();"use strict";Ka.exports.isClean=Symbol("isClean");Ka.exports.my=Symbol("my")});var Za=k((NB,Gp)=>{l();"use strict";var Wp={colon:": ",indent:" ",beforeDecl:`
`,beforeRule:`
`,beforeOpen:" ",beforeClose:`
`,beforeComment:`
`,after:`
`,emptyBody:"",commentLeft:" ",commentRight:" ",semicolon:!1};function Lk(t){return t[0].toUpperCase()+t.slice(1)}var Fn=class{constructor(e){this.builder=e}stringify(e,r){if(!this[e.type])throw new Error("Unknown AST node type "+e.type+". Maybe you need to change PostCSS stringifier.");this[e.type](e,r)}document(e){this.body(e)}root(e){this.body(e),e.raws.after&&this.builder(e.raws.after)}comment(e){let r=this.raw(e,"left","commentLeft"),i=this.raw(e,"right","commentRight");this.builder("/*"+r+e.text+i+"*/",e)}decl(e,r){let i=this.raw(e,"between","colon"),n=e.prop+i+this.rawValue(e,"value");e.important&&(n+=e.raws.important||" !important"),r&&(n+=";"),this.builder(n,e)}rule(e){this.block(e,this.rawValue(e,"selector")),e.raws.ownSemicolon&&this.builder(e.raws.ownSemicolon,e,"end")}atrule(e,r){let i="@"+e.name,n=e.params?this.rawValue(e,"params"):"";if(typeof e.raws.afterName!="undefined"?i+=e.raws.afterName:n&&(i+=" "),e.nodes)this.block(e,i+n);else{let s=(e.raws.between||"")+(r?";":"");this.builder(i+n+s,e)}}body(e){let r=e.nodes.length-1;for(;r>0&&e.nodes[r].type==="comment";)r-=1;let i=this.raw(e,"semicolon");for(let n=0;n<e.nodes.length;n++){let s=e.nodes[n],a=this.raw(s,"before");a&&this.builder(a),this.stringify(s,r!==n||i)}}block(e,r){let i=this.raw(e,"between","beforeOpen");this.builder(r+i+"{",e,"start");let n;e.nodes&&e.nodes.length?(this.body(e),n=this.raw(e,"after")):n=this.raw(e,"after","emptyBody"),n&&this.builder(n),this.builder("}",e,"end")}raw(e,r,i){let n;if(i||(i=r),r&&(n=e.raws[r],typeof n!="undefined"))return n;let s=e.parent;if(i==="before"&&(!s||s.type==="root"&&s.first===e||s&&s.type==="document"))return"";if(!s)return Wp[i];let a=e.root();if(a.rawCache||(a.rawCache={}),typeof a.rawCache[i]!="undefined")return a.rawCache[i];if(i==="before"||i==="after")return this.beforeAfter(e,i);{let o="raw"+Lk(i);this[o]?n=this[o](a,e):a.walk(u=>{if(n=u.raws[r],typeof n!="undefined")return!1})}return typeof n=="undefined"&&(n=Wp[i]),a.rawCache[i]=n,n}rawSemicolon(e){let r;return e.walk(i=>{if(i.nodes&&i.nodes.length&&i.last.type==="decl"&&(r=i.raws.semicolon,typeof r!="undefined"))return!1}),r}rawEmptyBody(e){let r;return e.walk(i=>{if(i.nodes&&i.nodes.length===0&&(r=i.raws.after,typeof r!="undefined"))return!1}),r}rawIndent(e){if(e.raws.indent)return e.raws.indent;let r;return e.walk(i=>{let n=i.parent;if(n&&n!==e&&n.parent&&n.parent===e&&typeof i.raws.before!="undefined"){let s=i.raws.before.split(`
`);return r=s[s.length-1],r=r.replace(/\S/g,""),!1}}),r}rawBeforeComment(e,r){let i;return e.walkComments(n=>{if(typeof n.raws.before!="undefined")return i=n.raws.before,i.includes(`
`)&&(i=i.replace(/[^\n]+$/,"")),!1}),typeof i=="undefined"?i=this.raw(r,null,"beforeDecl"):i&&(i=i.replace(/\S/g,"")),i}rawBeforeDecl(e,r){let i;return e.walkDecls(n=>{if(typeof n.raws.before!="undefined")return i=n.raws.before,i.includes(`
`)&&(i=i.replace(/[^\n]+$/,"")),!1}),typeof i=="undefined"?i=this.raw(r,null,"beforeRule"):i&&(i=i.replace(/\S/g,"")),i}rawBeforeRule(e){let r;return e.walk(i=>{if(i.nodes&&(i.parent!==e||e.first!==i)&&typeof i.raws.before!="undefined")return r=i.raws.before,r.includes(`
`)&&(r=r.replace(/[^\n]+$/,"")),!1}),r&&(r=r.replace(/\S/g,"")),r}rawBeforeClose(e){let r;return e.walk(i=>{if(i.nodes&&i.nodes.length>0&&typeof i.raws.after!="undefined")return r=i.raws.after,r.includes(`
`)&&(r=r.replace(/[^\n]+$/,"")),!1}),r&&(r=r.replace(/\S/g,"")),r}rawBeforeOpen(e){let r;return e.walk(i=>{if(i.type!=="decl"&&(r=i.raws.between,typeof r!="undefined"))return!1}),r}rawColon(e){let r;return e.walkDecls(i=>{if(typeof i.raws.between!="undefined")return r=i.raws.between.replace(/[^\s:]/g,""),!1}),r}beforeAfter(e,r){let i;e.type==="decl"?i=this.raw(e,null,"beforeDecl"):e.type==="comment"?i=this.raw(e,null,"beforeComment"):r==="before"?i=this.raw(e,null,"beforeRule"):i=this.raw(e,null,"beforeClose");let n=e.parent,s=0;for(;n&&n.type!=="root";)s+=1,n=n.parent;if(i.includes(`
`)){let a=this.raw(e,null,"indent");if(a.length)for(let o=0;o<s;o++)i+=a}return i}rawValue(e,r){let i=e[r],n=e.raws[r];return n&&n.value===i?n.raw:i}};Gp.exports=Fn;Fn.default=Fn});var Zr=k((zB,Hp)=>{l();"use strict";var Bk=Za();function eo(t,e){new Bk(e).stringify(t)}Hp.exports=eo;eo.default=eo});var ei=k(($B,Yp)=>{l();"use strict";var{isClean:Nn,my:Mk}=Mn(),Fk=Bn(),Nk=Za(),zk=Zr();function to(t,e){let r=new t.constructor;for(let i in t){if(!Object.prototype.hasOwnProperty.call(t,i)||i==="proxyCache")continue;let n=t[i],s=typeof n;i==="parent"&&s==="object"?e&&(r[i]=e):i==="source"?r[i]=n:Array.isArray(n)?r[i]=n.map(a=>to(a,r)):(s==="object"&&n!==null&&(n=to(n)),r[i]=n)}return r}var zn=class{constructor(e={}){this.raws={},this[Nn]=!1,this[Mk]=!0;for(let r in e)if(r==="nodes"){this.nodes=[];for(let i of e[r])typeof i.clone=="function"?this.append(i.clone()):this.append(i)}else this[r]=e[r]}error(e,r={}){if(this.source){let{start:i,end:n}=this.rangeBy(r);return this.source.input.error(e,{line:i.line,column:i.column},{line:n.line,column:n.column},r)}return new Fk(e)}warn(e,r,i){let n={node:this};for(let s in i)n[s]=i[s];return e.warn(r,n)}remove(){return this.parent&&this.parent.removeChild(this),this.parent=void 0,this}toString(e=zk){e.stringify&&(e=e.stringify);let r="";return e(this,i=>{r+=i}),r}assign(e={}){for(let r in e)this[r]=e[r];return this}clone(e={}){let r=to(this);for(let i in e)r[i]=e[i];return r}cloneBefore(e={}){let r=this.clone(e);return this.parent.insertBefore(this,r),r}cloneAfter(e={}){let r=this.clone(e);return this.parent.insertAfter(this,r),r}replaceWith(...e){if(this.parent){let r=this,i=!1;for(let n of e)n===this?i=!0:i?(this.parent.insertAfter(r,n),r=n):this.parent.insertBefore(r,n);i||this.remove()}return this}next(){if(!this.parent)return;let e=this.parent.index(this);return this.parent.nodes[e+1]}prev(){if(!this.parent)return;let e=this.parent.index(this);return this.parent.nodes[e-1]}before(e){return this.parent.insertBefore(this,e),this}after(e){return this.parent.insertAfter(this,e),this}root(){let e=this;for(;e.parent&&e.parent.type!=="document";)e=e.parent;return e}raw(e,r){return new Nk().raw(this,e,r)}cleanRaws(e){delete this.raws.before,delete this.raws.after,e||delete this.raws.between}toJSON(e,r){let i={},n=r==null;r=r||new Map;let s=0;for(let a in this){if(!Object.prototype.hasOwnProperty.call(this,a)||a==="parent"||a==="proxyCache")continue;let o=this[a];if(Array.isArray(o))i[a]=o.map(u=>typeof u=="object"&&u.toJSON?u.toJSON(null,r):u);else if(typeof o=="object"&&o.toJSON)i[a]=o.toJSON(null,r);else if(a==="source"){let u=r.get(o.input);u==null&&(u=s,r.set(o.input,s),s++),i[a]={inputId:u,start:o.start,end:o.end}}else i[a]=o}return n&&(i.inputs=[...r.keys()].map(a=>a.toJSON())),i}positionInside(e){let r=this.toString(),i=this.source.start.column,n=this.source.start.line;for(let s=0;s<e;s++)r[s]===`
`?(i=1,n+=1):i+=1;return{line:n,column:i}}positionBy(e){let r=this.source.start;if(e.index)r=this.positionInside(e.index);else if(e.word){let i=this.toString().indexOf(e.word);i!==-1&&(r=this.positionInside(i))}return r}rangeBy(e){let r={line:this.source.start.line,column:this.source.start.column},i=this.source.end?{line:this.source.end.line,column:this.source.end.column+1}:{line:r.line,column:r.column+1};if(e.word){let n=this.toString().indexOf(e.word);n!==-1&&(r=this.positionInside(n),i=this.positionInside(n+e.word.length))}else e.start?r={line:e.start.line,column:e.start.column}:e.index&&(r=this.positionInside(e.index)),e.end?i={line:e.end.line,column:e.end.column}:e.endIndex?i=this.positionInside(e.endIndex):e.index&&(i=this.positionInside(e.index+1));return(i.line<r.line||i.line===r.line&&i.column<=r.column)&&(i={line:r.line,column:r.column+1}),{start:r,end:i}}getProxyProcessor(){return{set(e,r,i){return e[r]===i||(e[r]=i,(r==="prop"||r==="value"||r==="name"||r==="params"||r==="important"||r==="text")&&e.markDirty()),!0},get(e,r){return r==="proxyOf"?e:r==="root"?()=>e.root().toProxy():e[r]}}}toProxy(){return this.proxyCache||(this.proxyCache=new Proxy(this,this.getProxyProcessor())),this.proxyCache}addToError(e){if(e.postcssNode=this,e.stack&&this.source&&/\n\s{4}at /.test(e.stack)){let r=this.source;e.stack=e.stack.replace(/\n\s{4}at /,`$&${r.input.from}:${r.start.line}:${r.start.column}$&`)}return e}markDirty(){if(this[Nn]){this[Nn]=!1;let e=this;for(;e=e.parent;)e[Nn]=!1}}get proxyOf(){return this}};Yp.exports=zn;zn.default=zn});var ti=k((jB,Qp)=>{l();"use strict";var $k=ei(),$n=class extends $k{constructor(e){e&&typeof e.value!="undefined"&&typeof e.value!="string"&&(e={...e,value:String(e.value)});super(e);this.type="decl"}get variable(){return this.prop.startsWith("--")||this.prop[0]==="$"}};Qp.exports=$n;$n.default=$n});var ro=k((UB,Jp)=>{l();Jp.exports=function(t,e){return{generate:()=>{let r="";return t(e,i=>{r+=i}),[r]}}}});var ri=k((VB,Xp)=>{l();"use strict";var jk=ei(),jn=class extends jk{constructor(e){super(e);this.type="comment"}};Xp.exports=jn;jn.default=jn});var Pt=k((WB,ad)=>{l();"use strict";var{isClean:Kp,my:Zp}=Mn(),ed=ti(),td=ri(),Uk=ei(),rd,io,no,id;function nd(t){return t.map(e=>(e.nodes&&(e.nodes=nd(e.nodes)),delete e.source,e))}function sd(t){if(t[Kp]=!1,t.proxyOf.nodes)for(let e of t.proxyOf.nodes)sd(e)}var Le=class extends Uk{push(e){return e.parent=this,this.proxyOf.nodes.push(e),this}each(e){if(!this.proxyOf.nodes)return;let r=this.getIterator(),i,n;for(;this.indexes[r]<this.proxyOf.nodes.length&&(i=this.indexes[r],n=e(this.proxyOf.nodes[i],i),n!==!1);)this.indexes[r]+=1;return delete this.indexes[r],n}walk(e){return this.each((r,i)=>{let n;try{n=e(r,i)}catch(s){throw r.addToError(s)}return n!==!1&&r.walk&&(n=r.walk(e)),n})}walkDecls(e,r){return r?e instanceof RegExp?this.walk((i,n)=>{if(i.type==="decl"&&e.test(i.prop))return r(i,n)}):this.walk((i,n)=>{if(i.type==="decl"&&i.prop===e)return r(i,n)}):(r=e,this.walk((i,n)=>{if(i.type==="decl")return r(i,n)}))}walkRules(e,r){return r?e instanceof RegExp?this.walk((i,n)=>{if(i.type==="rule"&&e.test(i.selector))return r(i,n)}):this.walk((i,n)=>{if(i.type==="rule"&&i.selector===e)return r(i,n)}):(r=e,this.walk((i,n)=>{if(i.type==="rule")return r(i,n)}))}walkAtRules(e,r){return r?e instanceof RegExp?this.walk((i,n)=>{if(i.type==="atrule"&&e.test(i.name))return r(i,n)}):this.walk((i,n)=>{if(i.type==="atrule"&&i.name===e)return r(i,n)}):(r=e,this.walk((i,n)=>{if(i.type==="atrule")return r(i,n)}))}walkComments(e){return this.walk((r,i)=>{if(r.type==="comment")return e(r,i)})}append(...e){for(let r of e){let i=this.normalize(r,this.last);for(let n of i)this.proxyOf.nodes.push(n)}return this.markDirty(),this}prepend(...e){e=e.reverse();for(let r of e){let i=this.normalize(r,this.first,"prepend").reverse();for(let n of i)this.proxyOf.nodes.unshift(n);for(let n in this.indexes)this.indexes[n]=this.indexes[n]+i.length}return this.markDirty(),this}cleanRaws(e){if(super.cleanRaws(e),this.nodes)for(let r of this.nodes)r.cleanRaws(e)}insertBefore(e,r){let i=this.index(e),n=i===0?"prepend":!1,s=this.normalize(r,this.proxyOf.nodes[i],n).reverse();i=this.index(e);for(let o of s)this.proxyOf.nodes.splice(i,0,o);let a;for(let o in this.indexes)a=this.indexes[o],i<=a&&(this.indexes[o]=a+s.length);return this.markDirty(),this}insertAfter(e,r){let i=this.index(e),n=this.normalize(r,this.proxyOf.nodes[i]).reverse();i=this.index(e);for(let a of n)this.proxyOf.nodes.splice(i+1,0,a);let s;for(let a in this.indexes)s=this.indexes[a],i<s&&(this.indexes[a]=s+n.length);return this.markDirty(),this}removeChild(e){e=this.index(e),this.proxyOf.nodes[e].parent=void 0,this.proxyOf.nodes.splice(e,1);let r;for(let i in this.indexes)r=this.indexes[i],r>=e&&(this.indexes[i]=r-1);return this.markDirty(),this}removeAll(){for(let e of this.proxyOf.nodes)e.parent=void 0;return this.proxyOf.nodes=[],this.markDirty(),this}replaceValues(e,r,i){return i||(i=r,r={}),this.walkDecls(n=>{r.props&&!r.props.includes(n.prop)||r.fast&&!n.value.includes(r.fast)||(n.value=n.value.replace(e,i))}),this.markDirty(),this}every(e){return this.nodes.every(e)}some(e){return this.nodes.some(e)}index(e){return typeof e=="number"?e:(e.proxyOf&&(e=e.proxyOf),this.proxyOf.nodes.indexOf(e))}get first(){if(!!this.proxyOf.nodes)return this.proxyOf.nodes[0]}get last(){if(!!this.proxyOf.nodes)return this.proxyOf.nodes[this.proxyOf.nodes.length-1]}normalize(e,r){if(typeof e=="string")e=nd(rd(e).nodes);else if(Array.isArray(e)){e=e.slice(0);for(let n of e)n.parent&&n.parent.removeChild(n,"ignore")}else if(e.type==="root"&&this.type!=="document"){e=e.nodes.slice(0);for(let n of e)n.parent&&n.parent.removeChild(n,"ignore")}else if(e.type)e=[e];else if(e.prop){if(typeof e.value=="undefined")throw new Error("Value field is missed in node creation");typeof e.value!="string"&&(e.value=String(e.value)),e=[new ed(e)]}else if(e.selector)e=[new io(e)];else if(e.name)e=[new no(e)];else if(e.text)e=[new td(e)];else throw new Error("Unknown node type in node creation");return e.map(n=>(n[Zp]||Le.rebuild(n),n=n.proxyOf,n.parent&&n.parent.removeChild(n),n[Kp]&&sd(n),typeof n.raws.before=="undefined"&&r&&typeof r.raws.before!="undefined"&&(n.raws.before=r.raws.before.replace(/\S/g,"")),n.parent=this.proxyOf,n))}getProxyProcessor(){return{set(e,r,i){return e[r]===i||(e[r]=i,(r==="name"||r==="params"||r==="selector")&&e.markDirty()),!0},get(e,r){return r==="proxyOf"?e:e[r]?r==="each"||typeof r=="string"&&r.startsWith("walk")?(...i)=>e[r](...i.map(n=>typeof n=="function"?(s,a)=>n(s.toProxy(),a):n)):r==="every"||r==="some"?i=>e[r]((n,...s)=>i(n.toProxy(),...s)):r==="root"?()=>e.root().toProxy():r==="nodes"?e.nodes.map(i=>i.toProxy()):r==="first"||r==="last"?e[r].toProxy():e[r]:e[r]}}}getIterator(){this.lastEach||(this.lastEach=0),this.indexes||(this.indexes={}),this.lastEach+=1;let e=this.lastEach;return this.indexes[e]=0,e}};Le.registerParse=t=>{rd=t};Le.registerRule=t=>{io=t};Le.registerAtRule=t=>{no=t};Le.registerRoot=t=>{id=t};ad.exports=Le;Le.default=Le;Le.rebuild=t=>{t.type==="atrule"?Object.setPrototypeOf(t,no.prototype):t.type==="rule"?Object.setPrototypeOf(t,io.prototype):t.type==="decl"?Object.setPrototypeOf(t,ed.prototype):t.type==="comment"?Object.setPrototypeOf(t,td.prototype):t.type==="root"&&Object.setPrototypeOf(t,id.prototype),t[Zp]=!0,t.nodes&&t.nodes.forEach(e=>{Le.rebuild(e)})}});var Un=k((GB,ud)=>{l();"use strict";var Vk=Pt(),od,ld,ar=class extends Vk{constructor(e){super({type:"document",...e});this.nodes||(this.nodes=[])}toResult(e={}){return new od(new ld,this,e).stringify()}};ar.registerLazyResult=t=>{od=t};ar.registerProcessor=t=>{ld=t};ud.exports=ar;ar.default=ar});var so=k((HB,cd)=>{l();"use strict";var fd={};cd.exports=function(e){fd[e]||(fd[e]=!0,typeof console!="undefined"&&console.warn&&console.warn(e))}});var ao=k((YB,pd)=>{l();"use strict";var Vn=class{constructor(e,r={}){if(this.type="warning",this.text=e,r.node&&r.node.source){let i=r.node.rangeBy(r);this.line=i.start.line,this.column=i.start.column,this.endLine=i.end.line,this.endColumn=i.end.column}for(let i in r)this[i]=r[i]}toString(){return this.node?this.node.error(this.text,{plugin:this.plugin,index:this.index,word:this.word}).message:this.plugin?this.plugin+": "+this.text:this.text}};pd.exports=Vn;Vn.default=Vn});var Gn=k((QB,dd)=>{l();"use strict";var Wk=ao(),Wn=class{constructor(e,r,i){this.processor=e,this.messages=[],this.root=r,this.opts=i,this.css=void 0,this.map=void 0}toString(){return this.css}warn(e,r={}){r.plugin||this.lastPlugin&&this.lastPlugin.postcssPlugin&&(r.plugin=this.lastPlugin.postcssPlugin);let i=new Wk(e,r);return this.messages.push(i),i}warnings(){return this.messages.filter(e=>e.type==="warning")}get content(){return this.css}};dd.exports=Wn;Wn.default=Wn});var vd=k((JB,yd)=>{l();"use strict";var oo="'".charCodeAt(0),hd='"'.charCodeAt(0),Hn="\\".charCodeAt(0),md="/".charCodeAt(0),Yn=`
`.charCodeAt(0),ii=" ".charCodeAt(0),Qn="\f".charCodeAt(0),Jn=" ".charCodeAt(0),Xn="\r".charCodeAt(0),Gk="[".charCodeAt(0),Hk="]".charCodeAt(0),Yk="(".charCodeAt(0),Qk=")".charCodeAt(0),Jk="{".charCodeAt(0),Xk="}".charCodeAt(0),Kk=";".charCodeAt(0),Zk="*".charCodeAt(0),eS=":".charCodeAt(0),tS="@".charCodeAt(0),Kn=/[\t\n\f\r "#'()/;[\\\]{}]/g,Zn=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,rS=/.[\n"'(/\\]/,gd=/[\da-f]/i;yd.exports=function(e,r={}){let i=e.css.valueOf(),n=r.ignoreErrors,s,a,o,u,c,f,p,h,m,v,S=i.length,b=0,w=[],_=[];function T(){return b}function O(N){throw e.error("Unclosed "+N,b)}function E(){return _.length===0&&b>=S}function F(N){if(_.length)return _.pop();if(b>=S)return;let fe=N?N.ignoreUnclosed:!1;switch(s=i.charCodeAt(b),s){case Yn:case ii:case Jn:case Xn:case Qn:{a=b;do a+=1,s=i.charCodeAt(a);while(s===ii||s===Yn||s===Jn||s===Xn||s===Qn);v=["space",i.slice(b,a)],b=a-1;break}case Gk:case Hk:case Jk:case Xk:case eS:case Kk:case Qk:{let ye=String.fromCharCode(s);v=[ye,ye,b];break}case Yk:{if(h=w.length?w.pop()[1]:"",m=i.charCodeAt(b+1),h==="url"&&m!==oo&&m!==hd&&m!==ii&&m!==Yn&&m!==Jn&&m!==Qn&&m!==Xn){a=b;do{if(f=!1,a=i.indexOf(")",a+1),a===-1)if(n||fe){a=b;break}else O("bracket");for(p=a;i.charCodeAt(p-1)===Hn;)p-=1,f=!f}while(f);v=["brackets",i.slice(b,a+1),b,a],b=a}else a=i.indexOf(")",b+1),u=i.slice(b,a+1),a===-1||rS.test(u)?v=["(","(",b]:(v=["brackets",u,b,a],b=a);break}case oo:case hd:{o=s===oo?"'":'"',a=b;do{if(f=!1,a=i.indexOf(o,a+1),a===-1)if(n||fe){a=b+1;break}else O("string");for(p=a;i.charCodeAt(p-1)===Hn;)p-=1,f=!f}while(f);v=["string",i.slice(b,a+1),b,a],b=a;break}case tS:{Kn.lastIndex=b+1,Kn.test(i),Kn.lastIndex===0?a=i.length-1:a=Kn.lastIndex-2,v=["at-word",i.slice(b,a+1),b,a],b=a;break}case Hn:{for(a=b,c=!0;i.charCodeAt(a+1)===Hn;)a+=1,c=!c;if(s=i.charCodeAt(a+1),c&&s!==md&&s!==ii&&s!==Yn&&s!==Jn&&s!==Xn&&s!==Qn&&(a+=1,gd.test(i.charAt(a)))){for(;gd.test(i.charAt(a+1));)a+=1;i.charCodeAt(a+1)===ii&&(a+=1)}v=["word",i.slice(b,a+1),b,a],b=a;break}default:{s===md&&i.charCodeAt(b+1)===Zk?(a=i.indexOf("*/",b+2)+1,a===0&&(n||fe?a=i.length:O("comment")),v=["comment",i.slice(b,a+1),b,a],b=a):(Zn.lastIndex=b+1,Zn.test(i),Zn.lastIndex===0?a=i.length-1:a=Zn.lastIndex-2,v=["word",i.slice(b,a+1),b,a],w.push(v),b=a);break}}return b++,v}function z(N){_.push(N)}return{back:z,nextToken:F,endOfFile:E,position:T}}});var es=k((XB,bd)=>{l();"use strict";var wd=Pt(),ni=class extends wd{constructor(e){super(e);this.type="atrule"}append(...e){return this.proxyOf.nodes||(this.nodes=[]),super.append(...e)}prepend(...e){return this.proxyOf.nodes||(this.nodes=[]),super.prepend(...e)}};bd.exports=ni;ni.default=ni;wd.registerAtRule(ni)});var or=k((KB,_d)=>{l();"use strict";var xd=Pt(),kd,Sd,Vt=class extends xd{constructor(e){super(e);this.type="root",this.nodes||(this.nodes=[])}removeChild(e,r){let i=this.index(e);return!r&&i===0&&this.nodes.length>1&&(this.nodes[1].raws.before=this.nodes[i].raws.before),super.removeChild(e)}normalize(e,r,i){let n=super.normalize(e);if(r){if(i==="prepend")this.nodes.length>1?r.raws.before=this.nodes[1].raws.before:delete r.raws.before;else if(this.first!==r)for(let s of n)s.raws.before=r.raws.before}return n}toResult(e={}){return new kd(new Sd,this,e).stringify()}};Vt.registerLazyResult=t=>{kd=t};Vt.registerProcessor=t=>{Sd=t};_d.exports=Vt;Vt.default=Vt;xd.registerRoot(Vt)});var lo=k((ZB,Td)=>{l();"use strict";var si={split(t,e,r){let i=[],n="",s=!1,a=0,o=!1,u="",c=!1;for(let f of t)c?c=!1:f==="\\"?c=!0:o?f===u&&(o=!1):f==='"'||f==="'"?(o=!0,u=f):f==="("?a+=1:f===")"?a>0&&(a-=1):a===0&&e.includes(f)&&(s=!0),s?(n!==""&&i.push(n.trim()),n="",s=!1):n+=f;return(r||n!=="")&&i.push(n.trim()),i},space(t){let e=[" ",`
`," "];return si.split(t,e)},comma(t){return si.split(t,[","],!0)}};Td.exports=si;si.default=si});var ts=k((eM,Ed)=>{l();"use strict";var Od=Pt(),iS=lo(),ai=class extends Od{constructor(e){super(e);this.type="rule",this.nodes||(this.nodes=[])}get selectors(){return iS.comma(this.selector)}set selectors(e){let r=this.selector?this.selector.match(/,\s*/):null,i=r?r[0]:","+this.raw("between","beforeOpen");this.selector=e.join(i)}};Ed.exports=ai;ai.default=ai;Od.registerRule(ai)});var Dd=k((tM,Id)=>{l();"use strict";var nS=ti(),sS=vd(),aS=ri(),oS=es(),lS=or(),Ad=ts(),Cd={empty:!0,space:!0};function uS(t){for(let e=t.length-1;e>=0;e--){let r=t[e],i=r[3]||r[2];if(i)return i}}var Pd=class{constructor(e){this.input=e,this.root=new lS,this.current=this.root,this.spaces="",this.semicolon=!1,this.customProperty=!1,this.createTokenizer(),this.root.source={input:e,start:{offset:0,line:1,column:1}}}createTokenizer(){this.tokenizer=sS(this.input)}parse(){let e;for(;!this.tokenizer.endOfFile();)switch(e=this.tokenizer.nextToken(),e[0]){case"space":this.spaces+=e[1];break;case";":this.freeSemicolon(e);break;case"}":this.end(e);break;case"comment":this.comment(e);break;case"at-word":this.atrule(e);break;case"{":this.emptyRule(e);break;default:this.other(e);break}this.endFile()}comment(e){let r=new aS;this.init(r,e[2]),r.source.end=this.getPosition(e[3]||e[2]);let i=e[1].slice(2,-2);if(/^\s*$/.test(i))r.text="",r.raws.left=i,r.raws.right="";else{let n=i.match(/^(\s*)([^]*\S)(\s*)$/);r.text=n[2],r.raws.left=n[1],r.raws.right=n[3]}}emptyRule(e){let r=new Ad;this.init(r,e[2]),r.selector="",r.raws.between="",this.current=r}other(e){let r=!1,i=null,n=!1,s=null,a=[],o=e[1].startsWith("--"),u=[],c=e;for(;c;){if(i=c[0],u.push(c),i==="("||i==="[")s||(s=c),a.push(i==="("?")":"]");else if(o&&n&&i==="{")s||(s=c),a.push("}");else if(a.length===0)if(i===";")if(n){this.decl(u,o);return}else break;else if(i==="{"){this.rule(u);return}else if(i==="}"){this.tokenizer.back(u.pop()),r=!0;break}else i===":"&&(n=!0);else i===a[a.length-1]&&(a.pop(),a.length===0&&(s=null));c=this.tokenizer.nextToken()}if(this.tokenizer.endOfFile()&&(r=!0),a.length>0&&this.unclosedBracket(s),r&&n){if(!o)for(;u.length&&(c=u[u.length-1][0],!(c!=="space"&&c!=="comment"));)this.tokenizer.back(u.pop());this.decl(u,o)}else this.unknownWord(u)}rule(e){e.pop();let r=new Ad;this.init(r,e[0][2]),r.raws.between=this.spacesAndCommentsFromEnd(e),this.raw(r,"selector",e),this.current=r}decl(e,r){let i=new nS;this.init(i,e[0][2]);let n=e[e.length-1];for(n[0]===";"&&(this.semicolon=!0,e.pop()),i.source.end=this.getPosition(n[3]||n[2]||uS(e));e[0][0]!=="word";)e.length===1&&this.unknownWord(e),i.raws.before+=e.shift()[1];for(i.source.start=this.getPosition(e[0][2]),i.prop="";e.length;){let c=e[0][0];if(c===":"||c==="space"||c==="comment")break;i.prop+=e.shift()[1]}i.raws.between="";let s;for(;e.length;)if(s=e.shift(),s[0]===":"){i.raws.between+=s[1];break}else s[0]==="word"&&/\w/.test(s[1])&&this.unknownWord([s]),i.raws.between+=s[1];(i.prop[0]==="_"||i.prop[0]==="*")&&(i.raws.before+=i.prop[0],i.prop=i.prop.slice(1));let a=[],o;for(;e.length&&(o=e[0][0],!(o!=="space"&&o!=="comment"));)a.push(e.shift());this.precheckMissedSemicolon(e);for(let c=e.length-1;c>=0;c--){if(s=e[c],s[1].toLowerCase()==="!important"){i.important=!0;let f=this.stringFrom(e,c);f=this.spacesFromEnd(e)+f,f!==" !important"&&(i.raws.important=f);break}else if(s[1].toLowerCase()==="important"){let f=e.slice(0),p="";for(let h=c;h>0;h--){let m=f[h][0];if(p.trim().indexOf("!")===0&&m!=="space")break;p=f.pop()[1]+p}p.trim().indexOf("!")===0&&(i.important=!0,i.raws.important=p,e=f)}if(s[0]!=="space"&&s[0]!=="comment")break}e.some(c=>c[0]!=="space"&&c[0]!=="comment")&&(i.raws.between+=a.map(c=>c[1]).join(""),a=[]),this.raw(i,"value",a.concat(e),r),i.value.includes(":")&&!r&&this.checkMissedSemicolon(e)}atrule(e){let r=new oS;r.name=e[1].slice(1),r.name===""&&this.unnamedAtrule(r,e),this.init(r,e[2]);let i,n,s,a=!1,o=!1,u=[],c=[];for(;!this.tokenizer.endOfFile();){if(e=this.tokenizer.nextToken(),i=e[0],i==="("||i==="["?c.push(i==="("?")":"]"):i==="{"&&c.length>0?c.push("}"):i===c[c.length-1]&&c.pop(),c.length===0)if(i===";"){r.source.end=this.getPosition(e[2]),this.semicolon=!0;break}else if(i==="{"){o=!0;break}else if(i==="}"){if(u.length>0){for(s=u.length-1,n=u[s];n&&n[0]==="space";)n=u[--s];n&&(r.source.end=this.getPosition(n[3]||n[2]))}this.end(e);break}else u.push(e);else u.push(e);if(this.tokenizer.endOfFile()){a=!0;break}}r.raws.between=this.spacesAndCommentsFromEnd(u),u.length?(r.raws.afterName=this.spacesAndCommentsFromStart(u),this.raw(r,"params",u),a&&(e=u[u.length-1],r.source.end=this.getPosition(e[3]||e[2]),this.spaces=r.raws.between,r.raws.between="")):(r.raws.afterName="",r.params=""),o&&(r.nodes=[],this.current=r)}end(e){this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.semicolon=!1,this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.spaces="",this.current.parent?(this.current.source.end=this.getPosition(e[2]),this.current=this.current.parent):this.unexpectedClose(e)}endFile(){this.current.parent&&this.unclosedBlock(),this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.current.raws.after=(this.current.raws.after||"")+this.spaces}freeSemicolon(e){if(this.spaces+=e[1],this.current.nodes){let r=this.current.nodes[this.current.nodes.length-1];r&&r.type==="rule"&&!r.raws.ownSemicolon&&(r.raws.ownSemicolon=this.spaces,this.spaces="")}}getPosition(e){let r=this.input.fromOffset(e);return{offset:e,line:r.line,column:r.col}}init(e,r){this.current.push(e),e.source={start:this.getPosition(r),input:this.input},e.raws.before=this.spaces,this.spaces="",e.type!=="comment"&&(this.semicolon=!1)}raw(e,r,i,n){let s,a,o=i.length,u="",c=!0,f,p;for(let h=0;h<o;h+=1)s=i[h],a=s[0],a==="space"&&h===o-1&&!n?c=!1:a==="comment"?(p=i[h-1]?i[h-1][0]:"empty",f=i[h+1]?i[h+1][0]:"empty",!Cd[p]&&!Cd[f]?u.slice(-1)===","?c=!1:u+=s[1]:c=!1):u+=s[1];if(!c){let h=i.reduce((m,v)=>m+v[1],"");e.raws[r]={value:u,raw:h}}e[r]=u}spacesAndCommentsFromEnd(e){let r,i="";for(;e.length&&(r=e[e.length-1][0],!(r!=="space"&&r!=="comment"));)i=e.pop()[1]+i;return i}spacesAndCommentsFromStart(e){let r,i="";for(;e.length&&(r=e[0][0],!(r!=="space"&&r!=="comment"));)i+=e.shift()[1];return i}spacesFromEnd(e){let r,i="";for(;e.length&&(r=e[e.length-1][0],r==="space");)i=e.pop()[1]+i;return i}stringFrom(e,r){let i="";for(let n=r;n<e.length;n++)i+=e[n][1];return e.splice(r,e.length-r),i}colon(e){let r=0,i,n,s;for(let[a,o]of e.entries()){if(i=o,n=i[0],n==="("&&(r+=1),n===")"&&(r-=1),r===0&&n===":")if(!s)this.doubleColon(i);else{if(s[0]==="word"&&s[1]==="progid")continue;return a}s=i}return!1}unclosedBracket(e){throw this.input.error("Unclosed bracket",{offset:e[2]},{offset:e[2]+1})}unknownWord(e){throw this.input.error("Unknown word",{offset:e[0][2]},{offset:e[0][2]+e[0][1].length})}unexpectedClose(e){throw this.input.error("Unexpected }",{offset:e[2]},{offset:e[2]+1})}unclosedBlock(){let e=this.current.source.start;throw this.input.error("Unclosed block",e.line,e.column)}doubleColon(e){throw this.input.error("Double colon",{offset:e[2]},{offset:e[2]+e[1].length})}unnamedAtrule(e,r){throw this.input.error("At-rule without name",{offset:r[2]},{offset:r[2]+r[1].length})}precheckMissedSemicolon(){}checkMissedSemicolon(e){let r=this.colon(e);if(r===!1)return;let i=0,n;for(let s=r-1;s>=0&&(n=e[s],!(n[0]!=="space"&&(i+=1,i===2)));s--);throw this.input.error("Missed semicolon",n[0]==="word"?n[3]+1:n[2])}};Id.exports=Pd});var qd=k(()=>{l()});var Ld=k((nM,Rd)=>{l();var fS="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",cS=(t,e=21)=>(r=e)=>{let i="",n=r;for(;n--;)i+=t[Math.random()*t.length|0];return i},pS=(t=21)=>{let e="",r=t;for(;r--;)e+=fS[Math.random()*64|0];return e};Rd.exports={nanoid:pS,customAlphabet:cS}});var uo=k((sM,Bd)=>{l();Bd.exports={}});var is=k((aM,zd)=>{l();"use strict";var{SourceMapConsumer:dS,SourceMapGenerator:hS}=qd(),{fileURLToPath:Md,pathToFileURL:rs}=(Ja(),$p),{resolve:fo,isAbsolute:co}=(Ut(),Fp),{nanoid:mS}=Ld(),po=Xa(),Fd=Bn(),gS=uo(),ho=Symbol("fromOffsetCache"),yS=Boolean(dS&&hS),Nd=Boolean(fo&&co),oi=class{constructor(e,r={}){if(e===null||typeof e=="undefined"||typeof e=="object"&&!e.toString)throw new Error(`PostCSS received ${e} instead of CSS string`);if(this.css=e.toString(),this.css[0]==="\uFEFF"||this.css[0]==="\uFFFE"?(this.hasBOM=!0,this.css=this.css.slice(1)):this.hasBOM=!1,r.from&&(!Nd||/^\w+:\/\//.test(r.from)||co(r.from)?this.file=r.from:this.file=fo(r.from)),Nd&&yS){let i=new gS(this.css,r);if(i.text){this.map=i;let n=i.consumer().file;!this.file&&n&&(this.file=this.mapResolve(n))}}this.file||(this.id="<input css "+mS(6)+">"),this.map&&(this.map.file=this.from)}fromOffset(e){let r,i;if(this[ho])i=this[ho];else{let s=this.css.split(`
`);i=new Array(s.length);let a=0;for(let o=0,u=s.length;o<u;o++)i[o]=a,a+=s[o].length+1;this[ho]=i}r=i[i.length-1];let n=0;if(e>=r)n=i.length-1;else{let s=i.length-2,a;for(;n<s;)if(a=n+(s-n>>1),e<i[a])s=a-1;else if(e>=i[a+1])n=a+1;else{n=a;break}}return{line:n+1,col:e-i[n]+1}}error(e,r,i,n={}){let s,a,o;if(r&&typeof r=="object"){let c=r,f=i;if(typeof c.offset=="number"){let p=this.fromOffset(c.offset);r=p.line,i=p.col}else r=c.line,i=c.column;if(typeof f.offset=="number"){let p=this.fromOffset(f.offset);a=p.line,o=p.col}else a=f.line,o=f.column}else if(!i){let c=this.fromOffset(r);r=c.line,i=c.col}let u=this.origin(r,i,a,o);return u?s=new Fd(e,u.endLine===void 0?u.line:{line:u.line,column:u.column},u.endLine===void 0?u.column:{line:u.endLine,column:u.endColumn},u.source,u.file,n.plugin):s=new Fd(e,a===void 0?r:{line:r,column:i},a===void 0?i:{line:a,column:o},this.css,this.file,n.plugin),s.input={line:r,column:i,endLine:a,endColumn:o,source:this.css},this.file&&(rs&&(s.input.url=rs(this.file).toString()),s.input.file=this.file),s}origin(e,r,i,n){if(!this.map)return!1;let s=this.map.consumer(),a=s.originalPositionFor({line:e,column:r});if(!a.source)return!1;let o;typeof i=="number"&&(o=s.originalPositionFor({line:i,column:n}));let u;co(a.source)?u=rs(a.source):u=new URL(a.source,this.map.consumer().sourceRoot||rs(this.map.mapFile));let c={url:u.toString(),line:a.line,column:a.column,endLine:o&&o.line,endColumn:o&&o.column};if(u.protocol==="file:")if(Md)c.file=Md(u);else throw new Error("file: protocol is not available in this PostCSS build");let f=s.sourceContentFor(a.source);return f&&(c.source=f),c}mapResolve(e){return/^\w+:\/\//.test(e)?e:fo(this.map.consumer().sourceRoot||this.map.root||".",e)}get from(){return this.file||this.id}toJSON(){let e={};for(let r of["hasBOM","css","file","id"])this[r]!=null&&(e[r]=this[r]);return this.map&&(e.map={...this.map},e.map.consumerCache&&(e.map.consumerCache=void 0)),e}};zd.exports=oi;oi.default=oi;po&&po.registerInput&&po.registerInput(oi)});var ss=k((oM,$d)=>{l();"use strict";var vS=Pt(),wS=Dd(),bS=is();function ns(t,e){let r=new bS(t,e),i=new wS(r);try{i.parse()}catch(n){throw n}return i.root}$d.exports=ns;ns.default=ns;vS.registerParse(ns)});var yo=k((uM,Wd)=>{l();"use strict";var{isClean:et,my:xS}=Mn(),kS=ro(),SS=Zr(),_S=Pt(),TS=Un(),lM=so(),jd=Gn(),OS=ss(),ES=or(),AS={document:"Document",root:"Root",atrule:"AtRule",rule:"Rule",decl:"Declaration",comment:"Comment"},CS={postcssPlugin:!0,prepare:!0,Once:!0,Document:!0,Root:!0,Declaration:!0,Rule:!0,AtRule:!0,Comment:!0,DeclarationExit:!0,RuleExit:!0,AtRuleExit:!0,CommentExit:!0,RootExit:!0,DocumentExit:!0,OnceExit:!0},PS={postcssPlugin:!0,prepare:!0,Once:!0},lr=0;function li(t){return typeof t=="object"&&typeof t.then=="function"}function Ud(t){let e=!1,r=AS[t.type];return t.type==="decl"?e=t.prop.toLowerCase():t.type==="atrule"&&(e=t.name.toLowerCase()),e&&t.append?[r,r+"-"+e,lr,r+"Exit",r+"Exit-"+e]:e?[r,r+"-"+e,r+"Exit",r+"Exit-"+e]:t.append?[r,lr,r+"Exit"]:[r,r+"Exit"]}function Vd(t){let e;return t.type==="document"?e=["Document",lr,"DocumentExit"]:t.type==="root"?e=["Root",lr,"RootExit"]:e=Ud(t),{node:t,events:e,eventIndex:0,visitors:[],visitorIndex:0,iterator:0}}function mo(t){return t[et]=!1,t.nodes&&t.nodes.forEach(e=>mo(e)),t}var go={},pt=class{constructor(e,r,i){this.stringified=!1,this.processed=!1;let n;if(typeof r=="object"&&r!==null&&(r.type==="root"||r.type==="document"))n=mo(r);else if(r instanceof pt||r instanceof jd)n=mo(r.root),r.map&&(typeof i.map=="undefined"&&(i.map={}),i.map.inline||(i.map.inline=!1),i.map.prev=r.map);else{let s=OS;i.syntax&&(s=i.syntax.parse),i.parser&&(s=i.parser),s.parse&&(s=s.parse);try{n=s(r,i)}catch(a){this.processed=!0,this.error=a}n&&!n[xS]&&_S.rebuild(n)}this.result=new jd(e,n,i),this.helpers={...go,result:this.result,postcss:go},this.plugins=this.processor.plugins.map(s=>typeof s=="object"&&s.prepare?{...s,...s.prepare(this.result)}:s)}get[Symbol.toStringTag](){return"LazyResult"}get processor(){return this.result.processor}get opts(){return this.result.opts}get css(){return this.stringify().css}get content(){return this.stringify().content}get map(){return this.stringify().map}get root(){return this.sync().root}get messages(){return this.sync().messages}warnings(){return this.sync().warnings()}toString(){return this.css}then(e,r){return this.async().then(e,r)}catch(e){return this.async().catch(e)}finally(e){return this.async().then(e,e)}async(){return this.error?Promise.reject(this.error):this.processed?Promise.resolve(this.result):(this.processing||(this.processing=this.runAsync()),this.processing)}sync(){if(this.error)throw this.error;if(this.processed)return this.result;if(this.processed=!0,this.processing)throw this.getAsyncError();for(let e of this.plugins){let r=this.runOnRoot(e);if(li(r))throw this.getAsyncError()}if(this.prepareVisitors(),this.hasListener){let e=this.result.root;for(;!e[et];)e[et]=!0,this.walkSync(e);if(this.listeners.OnceExit)if(e.type==="document")for(let r of e.nodes)this.visitSync(this.listeners.OnceExit,r);else this.visitSync(this.listeners.OnceExit,e)}return this.result}stringify(){if(this.error)throw this.error;if(this.stringified)return this.result;this.stringified=!0,this.sync();let e=this.result.opts,r=SS;e.syntax&&(r=e.syntax.stringify),e.stringifier&&(r=e.stringifier),r.stringify&&(r=r.stringify);let n=new kS(r,this.result.root,this.result.opts).generate();return this.result.css=n[0],this.result.map=n[1],this.result}walkSync(e){e[et]=!0;let r=Ud(e);for(let i of r)if(i===lr)e.nodes&&e.each(n=>{n[et]||this.walkSync(n)});else{let n=this.listeners[i];if(n&&this.visitSync(n,e.toProxy()))return}}visitSync(e,r){for(let[i,n]of e){this.result.lastPlugin=i;let s;try{s=n(r,this.helpers)}catch(a){throw this.handleError(a,r.proxyOf)}if(r.type!=="root"&&r.type!=="document"&&!r.parent)return!0;if(li(s))throw this.getAsyncError()}}runOnRoot(e){this.result.lastPlugin=e;try{if(typeof e=="object"&&e.Once){if(this.result.root.type==="document"){let r=this.result.root.nodes.map(i=>e.Once(i,this.helpers));return li(r[0])?Promise.all(r):r}return e.Once(this.result.root,this.helpers)}else if(typeof e=="function")return e(this.result.root,this.result)}catch(r){throw this.handleError(r)}}getAsyncError(){throw new Error("Use process(css).then(cb) to work with async plugins")}handleError(e,r){let i=this.result.lastPlugin;try{r&&r.addToError(e),this.error=e,e.name==="CssSyntaxError"&&!e.plugin?(e.plugin=i.postcssPlugin,e.setMessage()):i.postcssVersion}catch(n){console&&console.error&&console.error(n)}return e}async runAsync(){this.plugin=0;for(let e=0;e<this.plugins.length;e++){let r=this.plugins[e],i=this.runOnRoot(r);if(li(i))try{await i}catch(n){throw this.handleError(n)}}if(this.prepareVisitors(),this.hasListener){let e=this.result.root;for(;!e[et];){e[et]=!0;let r=[Vd(e)];for(;r.length>0;){let i=this.visitTick(r);if(li(i))try{await i}catch(n){let s=r[r.length-1].node;throw this.handleError(n,s)}}}if(this.listeners.OnceExit)for(let[r,i]of this.listeners.OnceExit){this.result.lastPlugin=r;try{if(e.type==="document"){let n=e.nodes.map(s=>i(s,this.helpers));await Promise.all(n)}else await i(e,this.helpers)}catch(n){throw this.handleError(n)}}}return this.processed=!0,this.stringify()}prepareVisitors(){this.listeners={};let e=(r,i,n)=>{this.listeners[i]||(this.listeners[i]=[]),this.listeners[i].push([r,n])};for(let r of this.plugins)if(typeof r=="object")for(let i in r){if(!CS[i]&&/^[A-Z]/.test(i))throw new Error(`Unknown event ${i} in ${r.postcssPlugin}. Try to update PostCSS (${this.processor.version} now).`);if(!PS[i])if(typeof r[i]=="object")for(let n in r[i])n==="*"?e(r,i,r[i][n]):e(r,i+"-"+n.toLowerCase(),r[i][n]);else typeof r[i]=="function"&&e(r,i,r[i])}this.hasListener=Object.keys(this.listeners).length>0}visitTick(e){let r=e[e.length-1],{node:i,visitors:n}=r;if(i.type!=="root"&&i.type!=="document"&&!i.parent){e.pop();return}if(n.length>0&&r.visitorIndex<n.length){let[a,o]=n[r.visitorIndex];r.visitorIndex+=1,r.visitorIndex===n.length&&(r.visitors=[],r.visitorIndex=0),this.result.lastPlugin=a;try{return o(i.toProxy(),this.helpers)}catch(u){throw this.handleError(u,i)}}if(r.iterator!==0){let a=r.iterator,o;for(;o=i.nodes[i.indexes[a]];)if(i.indexes[a]+=1,!o[et]){o[et]=!0,e.push(Vd(o));return}r.iterator=0,delete i.indexes[a]}let s=r.events;for(;r.eventIndex<s.length;){let a=s[r.eventIndex];if(r.eventIndex+=1,a===lr){i.nodes&&i.nodes.length&&(i[et]=!0,r.iterator=i.getIterator());return}else if(this.listeners[a]){r.visitors=this.listeners[a];return}}e.pop()}};pt.registerPostcss=t=>{go=t};Wd.exports=pt;pt.default=pt;ES.registerLazyResult(pt);TS.registerLazyResult(pt)});var Hd=k((cM,Gd)=>{l();"use strict";var IS=ro(),DS=Zr(),fM=so(),qS=ss(),RS=Gn(),as=class{constructor(e,r,i){r=r.toString(),this.stringified=!1,this._processor=e,this._css=r,this._opts=i,this._map=void 0;let n,s=DS;this.result=new RS(this._processor,n,this._opts),this.result.css=r;let a=this;Object.defineProperty(this.result,"root",{get(){return a.root}});let o=new IS(s,n,this._opts,r);if(o.isMap()){let[u,c]=o.generate();u&&(this.result.css=u),c&&(this.result.map=c)}}get[Symbol.toStringTag](){return"NoWorkResult"}get processor(){return this.result.processor}get opts(){return this.result.opts}get css(){return this.result.css}get content(){return this.result.css}get map(){return this.result.map}get root(){if(this._root)return this._root;let e,r=qS;try{e=r(this._css,this._opts)}catch(i){this.error=i}if(this.error)throw this.error;return this._root=e,e}get messages(){return[]}warnings(){return[]}toString(){return this._css}then(e,r){return this.async().then(e,r)}catch(e){return this.async().catch(e)}finally(e){return this.async().then(e,e)}async(){return this.error?Promise.reject(this.error):Promise.resolve(this.result)}sync(){if(this.error)throw this.error;return this.result}};Gd.exports=as;as.default=as});var Qd=k((pM,Yd)=>{l();"use strict";var LS=Hd(),BS=yo(),MS=Un(),FS=or(),ur=class{constructor(e=[]){this.version="8.4.24",this.plugins=this.normalize(e)}use(e){return this.plugins=this.plugins.concat(this.normalize([e])),this}process(e,r={}){return this.plugins.length===0&&typeof r.parser=="undefined"&&typeof r.stringifier=="undefined"&&typeof r.syntax=="undefined"?new LS(this,e,r):new BS(this,e,r)}normalize(e){let r=[];for(let i of e)if(i.postcss===!0?i=i():i.postcss&&(i=i.postcss),typeof i=="object"&&Array.isArray(i.plugins))r=r.concat(i.plugins);else if(typeof i=="object"&&i.postcssPlugin)r.push(i);else if(typeof i=="function")r.push(i);else if(!(typeof i=="object"&&(i.parse||i.stringify)))throw new Error(i+" is not a PostCSS plugin");return r}};Yd.exports=ur;ur.default=ur;FS.registerProcessor(ur);MS.registerProcessor(ur)});var Xd=k((dM,Jd)=>{l();"use strict";var NS=ti(),zS=uo(),$S=ri(),jS=es(),US=is(),VS=or(),WS=ts();function ui(t,e){if(Array.isArray(t))return t.map(n=>ui(n));let{inputs:r,...i}=t;if(r){e=[];for(let n of r){let s={...n,__proto__:US.prototype};s.map&&(s.map={...s.map,__proto__:zS.prototype}),e.push(s)}}if(i.nodes&&(i.nodes=t.nodes.map(n=>ui(n,e))),i.source){let{inputId:n,...s}=i.source;i.source=s,n!=null&&(i.source.input=e[n])}if(i.type==="root")return new VS(i);if(i.type==="decl")return new NS(i);if(i.type==="rule")return new WS(i);if(i.type==="comment")return new $S(i);if(i.type==="atrule")return new jS(i);throw new Error("Unknown node type: "+t.type)}Jd.exports=ui;ui.default=ui});var qe=k((hM,nh)=>{l();"use strict";var GS=Bn(),Kd=ti(),HS=yo(),YS=Pt(),vo=Qd(),QS=Zr(),JS=Xd(),Zd=Un(),XS=ao(),eh=ri(),th=es(),KS=Gn(),ZS=is(),e_=ss(),t_=lo(),rh=ts(),ih=or(),r_=ei();function J(...t){return t.length===1&&Array.isArray(t[0])&&(t=t[0]),new vo(t)}J.plugin=function(e,r){let i=!1;function n(...a){console&&console.warn&&!i&&(i=!0,console.warn(e+`: postcss.plugin was deprecated. Migration guide:
https://evilmartians.com/chronicles/postcss-8-plugin-migration`),g.env.LANG&&g.env.LANG.startsWith("cn")&&console.warn(e+`: \u91CC\u9762 postcss.plugin \u88AB\u5F03\u7528. \u8FC1\u79FB\u6307\u5357:
https://www.w3ctech.com/topic/2226`));let o=r(...a);return o.postcssPlugin=e,o.postcssVersion=new vo().version,o}let s;return Object.defineProperty(n,"postcss",{get(){return s||(s=n()),s}}),n.process=function(a,o,u){return J([n(u)]).process(a,o)},n};J.stringify=QS;J.parse=e_;J.fromJSON=JS;J.list=t_;J.comment=t=>new eh(t);J.atRule=t=>new th(t);J.decl=t=>new Kd(t);J.rule=t=>new rh(t);J.root=t=>new ih(t);J.document=t=>new Zd(t);J.CssSyntaxError=GS;J.Declaration=Kd;J.Container=YS;J.Processor=vo;J.Document=Zd;J.Comment=eh;J.Warning=XS;J.AtRule=th;J.Result=KS;J.Input=ZS;J.Rule=rh;J.Root=ih;J.Node=r_;HS.registerPostcss(J);nh.exports=J;J.default=J});var ee,X,mM,gM,yM,vM,wM,bM,xM,kM,SM,_M,TM,OM,EM,AM,CM,PM,IM,DM,qM,RM,LM,BM,MM,FM,It=A(()=>{l();ee=ce(qe()),X=ee.default,mM=ee.default.stringify,gM=ee.default.fromJSON,yM=ee.default.plugin,vM=ee.default.parse,wM=ee.default.list,bM=ee.default.document,xM=ee.default.comment,kM=ee.default.atRule,SM=ee.default.rule,_M=ee.default.decl,TM=ee.default.root,OM=ee.default.CssSyntaxError,EM=ee.default.Declaration,AM=ee.default.Container,CM=ee.default.Processor,PM=ee.default.Document,IM=ee.default.Comment,DM=ee.default.Warning,qM=ee.default.AtRule,RM=ee.default.Result,LM=ee.default.Input,BM=ee.default.Rule,MM=ee.default.Root,FM=ee.default.Node});var wo=k((zM,sh)=>{l();sh.exports=function(t,e,r,i,n){for(e=e.split?e.split("."):e,i=0;i<e.length;i++)t=t?t[e[i]]:n;return t===n?r:t}});var ls=k((os,ah)=>{l();"use strict";os.__esModule=!0;os.default=s_;function i_(t){for(var e=t.toLowerCase(),r="",i=!1,n=0;n<6&&e[n]!==void 0;n++){var s=e.charCodeAt(n),a=s>=97&&s<=102||s>=48&&s<=57;if(i=s===32,!a)break;r+=e[n]}if(r.length!==0){var o=parseInt(r,16),u=o>=55296&&o<=57343;return u||o===0||o>1114111?["\uFFFD",r.length+(i?1:0)]:[String.fromCodePoint(o),r.length+(i?1:0)]}}var n_=/\\/;function s_(t){var e=n_.test(t);if(!e)return t;for(var r="",i=0;i<t.length;i++){if(t[i]==="\\"){var n=i_(t.slice(i+1,i+7));if(n!==void 0){r+=n[0],i+=n[1];continue}if(t[i+1]==="\\"){r+="\\",i++;continue}t.length===i+1&&(r+=t[i]);continue}r+=t[i]}return r}ah.exports=os.default});var lh=k((us,oh)=>{l();"use strict";us.__esModule=!0;us.default=a_;function a_(t){for(var e=arguments.length,r=new Array(e>1?e-1:0),i=1;i<e;i++)r[i-1]=arguments[i];for(;r.length>0;){var n=r.shift();if(!t[n])return;t=t[n]}return t}oh.exports=us.default});var fh=k((fs,uh)=>{l();"use strict";fs.__esModule=!0;fs.default=o_;function o_(t){for(var e=arguments.length,r=new Array(e>1?e-1:0),i=1;i<e;i++)r[i-1]=arguments[i];for(;r.length>0;){var n=r.shift();t[n]||(t[n]={}),t=t[n]}}uh.exports=fs.default});var ph=k((cs,ch)=>{l();"use strict";cs.__esModule=!0;cs.default=l_;function l_(t){for(var e="",r=t.indexOf("/*"),i=0;r>=0;){e=e+t.slice(i,r);var n=t.indexOf("*/",r+2);if(n<0)return e;i=n+2,r=t.indexOf("/*",i)}return e=e+t.slice(i),e}ch.exports=cs.default});var fi=k(tt=>{l();"use strict";tt.__esModule=!0;tt.unesc=tt.stripComments=tt.getProp=tt.ensureObject=void 0;var u_=ps(ls());tt.unesc=u_.default;var f_=ps(lh());tt.getProp=f_.default;var c_=ps(fh());tt.ensureObject=c_.default;var p_=ps(ph());tt.stripComments=p_.default;function ps(t){return t&&t.__esModule?t:{default:t}}});var dt=k((ci,mh)=>{l();"use strict";ci.__esModule=!0;ci.default=void 0;var dh=fi();function hh(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}function d_(t,e,r){return e&&hh(t.prototype,e),r&&hh(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}var h_=function t(e,r){if(typeof e!="object"||e===null)return e;var i=new e.constructor;for(var n in e)if(!!e.hasOwnProperty(n)){var s=e[n],a=typeof s;n==="parent"&&a==="object"?r&&(i[n]=r):s instanceof Array?i[n]=s.map(function(o){return t(o,i)}):i[n]=t(s,i)}return i},m_=function(){function t(r){r===void 0&&(r={}),Object.assign(this,r),this.spaces=this.spaces||{},this.spaces.before=this.spaces.before||"",this.spaces.after=this.spaces.after||""}var e=t.prototype;return e.remove=function(){return this.parent&&this.parent.removeChild(this),this.parent=void 0,this},e.replaceWith=function(){if(this.parent){for(var i in arguments)this.parent.insertBefore(this,arguments[i]);this.remove()}return this},e.next=function(){return this.parent.at(this.parent.index(this)+1)},e.prev=function(){return this.parent.at(this.parent.index(this)-1)},e.clone=function(i){i===void 0&&(i={});var n=h_(this);for(var s in i)n[s]=i[s];return n},e.appendToPropertyAndEscape=function(i,n,s){this.raws||(this.raws={});var a=this[i],o=this.raws[i];this[i]=a+n,o||s!==n?this.raws[i]=(o||a)+s:delete this.raws[i]},e.setPropertyAndEscape=function(i,n,s){this.raws||(this.raws={}),this[i]=n,this.raws[i]=s},e.setPropertyWithoutEscape=function(i,n){this[i]=n,this.raws&&delete this.raws[i]},e.isAtPosition=function(i,n){if(this.source&&this.source.start&&this.source.end)return!(this.source.start.line>i||this.source.end.line<i||this.source.start.line===i&&this.source.start.column>n||this.source.end.line===i&&this.source.end.column<n)},e.stringifyProperty=function(i){return this.raws&&this.raws[i]||this[i]},e.valueToString=function(){return String(this.stringifyProperty("value"))},e.toString=function(){return[this.rawSpaceBefore,this.valueToString(),this.rawSpaceAfter].join("")},d_(t,[{key:"rawSpaceBefore",get:function(){var i=this.raws&&this.raws.spaces&&this.raws.spaces.before;return i===void 0&&(i=this.spaces&&this.spaces.before),i||""},set:function(i){(0,dh.ensureObject)(this,"raws","spaces"),this.raws.spaces.before=i}},{key:"rawSpaceAfter",get:function(){var i=this.raws&&this.raws.spaces&&this.raws.spaces.after;return i===void 0&&(i=this.spaces.after),i||""},set:function(i){(0,dh.ensureObject)(this,"raws","spaces"),this.raws.spaces.after=i}}]),t}();ci.default=m_;mh.exports=ci.default});var be=k(te=>{l();"use strict";te.__esModule=!0;te.UNIVERSAL=te.TAG=te.STRING=te.SELECTOR=te.ROOT=te.PSEUDO=te.NESTING=te.ID=te.COMMENT=te.COMBINATOR=te.CLASS=te.ATTRIBUTE=void 0;var g_="tag";te.TAG=g_;var y_="string";te.STRING=y_;var v_="selector";te.SELECTOR=v_;var w_="root";te.ROOT=w_;var b_="pseudo";te.PSEUDO=b_;var x_="nesting";te.NESTING=x_;var k_="id";te.ID=k_;var S_="comment";te.COMMENT=S_;var __="combinator";te.COMBINATOR=__;var T_="class";te.CLASS=T_;var O_="attribute";te.ATTRIBUTE=O_;var E_="universal";te.UNIVERSAL=E_});var ds=k((pi,wh)=>{l();"use strict";pi.__esModule=!0;pi.default=void 0;var A_=P_(dt()),ht=C_(be());function gh(t){if(typeof WeakMap!="function")return null;var e=new WeakMap,r=new WeakMap;return(gh=function(n){return n?r:e})(t)}function C_(t,e){if(!e&&t&&t.__esModule)return t;if(t===null||typeof t!="object"&&typeof t!="function")return{default:t};var r=gh(e);if(r&&r.has(t))return r.get(t);var i={},n=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in t)if(s!=="default"&&Object.prototype.hasOwnProperty.call(t,s)){var a=n?Object.getOwnPropertyDescriptor(t,s):null;a&&(a.get||a.set)?Object.defineProperty(i,s,a):i[s]=t[s]}return i.default=t,r&&r.set(t,i),i}function P_(t){return t&&t.__esModule?t:{default:t}}function I_(t,e){var r=typeof Symbol!="undefined"&&t[Symbol.iterator]||t["@@iterator"];if(r)return(r=r.call(t)).next.bind(r);if(Array.isArray(t)||(r=D_(t))||e&&t&&typeof t.length=="number"){r&&(t=r);var i=0;return function(){return i>=t.length?{done:!0}:{done:!1,value:t[i++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function D_(t,e){if(!!t){if(typeof t=="string")return yh(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return yh(t,e)}}function yh(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,i=new Array(e);r<e;r++)i[r]=t[r];return i}function vh(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}function q_(t,e,r){return e&&vh(t.prototype,e),r&&vh(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function R_(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,bo(t,e)}function bo(t,e){return bo=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},bo(t,e)}var L_=function(t){R_(e,t);function e(i){var n;return n=t.call(this,i)||this,n.nodes||(n.nodes=[]),n}var r=e.prototype;return r.append=function(n){return n.parent=this,this.nodes.push(n),this},r.prepend=function(n){return n.parent=this,this.nodes.unshift(n),this},r.at=function(n){return this.nodes[n]},r.index=function(n){return typeof n=="number"?n:this.nodes.indexOf(n)},r.removeChild=function(n){n=this.index(n),this.at(n).parent=void 0,this.nodes.splice(n,1);var s;for(var a in this.indexes)s=this.indexes[a],s>=n&&(this.indexes[a]=s-1);return this},r.removeAll=function(){for(var n=I_(this.nodes),s;!(s=n()).done;){var a=s.value;a.parent=void 0}return this.nodes=[],this},r.empty=function(){return this.removeAll()},r.insertAfter=function(n,s){s.parent=this;var a=this.index(n);this.nodes.splice(a+1,0,s),s.parent=this;var o;for(var u in this.indexes)o=this.indexes[u],a<=o&&(this.indexes[u]=o+1);return this},r.insertBefore=function(n,s){s.parent=this;var a=this.index(n);this.nodes.splice(a,0,s),s.parent=this;var o;for(var u in this.indexes)o=this.indexes[u],o<=a&&(this.indexes[u]=o+1);return this},r._findChildAtPosition=function(n,s){var a=void 0;return this.each(function(o){if(o.atPosition){var u=o.atPosition(n,s);if(u)return a=u,!1}else if(o.isAtPosition(n,s))return a=o,!1}),a},r.atPosition=function(n,s){if(this.isAtPosition(n,s))return this._findChildAtPosition(n,s)||this},r._inferEndPosition=function(){this.last&&this.last.source&&this.last.source.end&&(this.source=this.source||{},this.source.end=this.source.end||{},Object.assign(this.source.end,this.last.source.end))},r.each=function(n){this.lastEach||(this.lastEach=0),this.indexes||(this.indexes={}),this.lastEach++;var s=this.lastEach;if(this.indexes[s]=0,!!this.length){for(var a,o;this.indexes[s]<this.length&&(a=this.indexes[s],o=n(this.at(a),a),o!==!1);)this.indexes[s]+=1;if(delete this.indexes[s],o===!1)return!1}},r.walk=function(n){return this.each(function(s,a){var o=n(s,a);if(o!==!1&&s.length&&(o=s.walk(n)),o===!1)return!1})},r.walkAttributes=function(n){var s=this;return this.walk(function(a){if(a.type===ht.ATTRIBUTE)return n.call(s,a)})},r.walkClasses=function(n){var s=this;return this.walk(function(a){if(a.type===ht.CLASS)return n.call(s,a)})},r.walkCombinators=function(n){var s=this;return this.walk(function(a){if(a.type===ht.COMBINATOR)return n.call(s,a)})},r.walkComments=function(n){var s=this;return this.walk(function(a){if(a.type===ht.COMMENT)return n.call(s,a)})},r.walkIds=function(n){var s=this;return this.walk(function(a){if(a.type===ht.ID)return n.call(s,a)})},r.walkNesting=function(n){var s=this;return this.walk(function(a){if(a.type===ht.NESTING)return n.call(s,a)})},r.walkPseudos=function(n){var s=this;return this.walk(function(a){if(a.type===ht.PSEUDO)return n.call(s,a)})},r.walkTags=function(n){var s=this;return this.walk(function(a){if(a.type===ht.TAG)return n.call(s,a)})},r.walkUniversals=function(n){var s=this;return this.walk(function(a){if(a.type===ht.UNIVERSAL)return n.call(s,a)})},r.split=function(n){var s=this,a=[];return this.reduce(function(o,u,c){var f=n.call(s,u);return a.push(u),f?(o.push(a),a=[]):c===s.length-1&&o.push(a),o},[])},r.map=function(n){return this.nodes.map(n)},r.reduce=function(n,s){return this.nodes.reduce(n,s)},r.every=function(n){return this.nodes.every(n)},r.some=function(n){return this.nodes.some(n)},r.filter=function(n){return this.nodes.filter(n)},r.sort=function(n){return this.nodes.sort(n)},r.toString=function(){return this.map(String).join("")},q_(e,[{key:"first",get:function(){return this.at(0)}},{key:"last",get:function(){return this.at(this.length-1)}},{key:"length",get:function(){return this.nodes.length}}]),e}(A_.default);pi.default=L_;wh.exports=pi.default});var ko=k((di,xh)=>{l();"use strict";di.__esModule=!0;di.default=void 0;var B_=F_(ds()),M_=be();function F_(t){return t&&t.__esModule?t:{default:t}}function bh(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}function N_(t,e,r){return e&&bh(t.prototype,e),r&&bh(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function z_(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,xo(t,e)}function xo(t,e){return xo=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},xo(t,e)}var $_=function(t){z_(e,t);function e(i){var n;return n=t.call(this,i)||this,n.type=M_.ROOT,n}var r=e.prototype;return r.toString=function(){var n=this.reduce(function(s,a){return s.push(String(a)),s},[]).join(",");return this.trailingComma?n+",":n},r.error=function(n,s){return this._error?this._error(n,s):new Error(n)},N_(e,[{key:"errorGenerator",set:function(n){this._error=n}}]),e}(B_.default);di.default=$_;xh.exports=di.default});var _o=k((hi,kh)=>{l();"use strict";hi.__esModule=!0;hi.default=void 0;var j_=V_(ds()),U_=be();function V_(t){return t&&t.__esModule?t:{default:t}}function W_(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,So(t,e)}function So(t,e){return So=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},So(t,e)}var G_=function(t){W_(e,t);function e(r){var i;return i=t.call(this,r)||this,i.type=U_.SELECTOR,i}return e}(j_.default);hi.default=G_;kh.exports=hi.default});var Wt=k((UM,Sh)=>{l();"use strict";var H_={},Y_=H_.hasOwnProperty,Q_=function(e,r){if(!e)return r;var i={};for(var n in r)i[n]=Y_.call(e,n)?e[n]:r[n];return i},J_=/[ -,\.\/:-@\[-\^`\{-~]/,X_=/[ -,\.\/:-@\[\]\^`\{-~]/,K_=/(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g,To=function t(e,r){r=Q_(r,t.options),r.quotes!="single"&&r.quotes!="double"&&(r.quotes="single");for(var i=r.quotes=="double"?'"':"'",n=r.isIdentifier,s=e.charAt(0),a="",o=0,u=e.length;o<u;){var c=e.charAt(o++),f=c.charCodeAt(),p=void 0;if(f<32||f>126){if(f>=55296&&f<=56319&&o<u){var h=e.charCodeAt(o++);(h&64512)==56320?f=((f&1023)<<10)+(h&1023)+65536:o--}p="\\"+f.toString(16).toUpperCase()+" "}else r.escapeEverything?J_.test(c)?p="\\"+c:p="\\"+f.toString(16).toUpperCase()+" ":/[\t\n\f\r\x0B]/.test(c)?p="\\"+f.toString(16).toUpperCase()+" ":c=="\\"||!n&&(c=='"'&&i==c||c=="'"&&i==c)||n&&X_.test(c)?p="\\"+c:p=c;a+=p}return n&&(/^-[-\d]/.test(a)?a="\\-"+a.slice(1):/\d/.test(s)&&(a="\\3"+s+" "+a.slice(1))),a=a.replace(K_,function(m,v,S){return v&&v.length%2?m:(v||"")+S}),!n&&r.wrap?i+a+i:a};To.options={escapeEverything:!1,isIdentifier:!1,quotes:"single",wrap:!1};To.version="3.0.0";Sh.exports=To});var Eo=k((mi,Oh)=>{l();"use strict";mi.__esModule=!0;mi.default=void 0;var Z_=_h(Wt()),e2=fi(),t2=_h(dt()),r2=be();function _h(t){return t&&t.__esModule?t:{default:t}}function Th(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}function i2(t,e,r){return e&&Th(t.prototype,e),r&&Th(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function n2(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,Oo(t,e)}function Oo(t,e){return Oo=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},Oo(t,e)}var s2=function(t){n2(e,t);function e(i){var n;return n=t.call(this,i)||this,n.type=r2.CLASS,n._constructed=!0,n}var r=e.prototype;return r.valueToString=function(){return"."+t.prototype.valueToString.call(this)},i2(e,[{key:"value",get:function(){return this._value},set:function(n){if(this._constructed){var s=(0,Z_.default)(n,{isIdentifier:!0});s!==n?((0,e2.ensureObject)(this,"raws"),this.raws.value=s):this.raws&&delete this.raws.value}this._value=n}}]),e}(t2.default);mi.default=s2;Oh.exports=mi.default});var Co=k((gi,Eh)=>{l();"use strict";gi.__esModule=!0;gi.default=void 0;var a2=l2(dt()),o2=be();function l2(t){return t&&t.__esModule?t:{default:t}}function u2(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,Ao(t,e)}function Ao(t,e){return Ao=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},Ao(t,e)}var f2=function(t){u2(e,t);function e(r){var i;return i=t.call(this,r)||this,i.type=o2.COMMENT,i}return e}(a2.default);gi.default=f2;Eh.exports=gi.default});var Io=k((yi,Ah)=>{l();"use strict";yi.__esModule=!0;yi.default=void 0;var c2=d2(dt()),p2=be();function d2(t){return t&&t.__esModule?t:{default:t}}function h2(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,Po(t,e)}function Po(t,e){return Po=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},Po(t,e)}var m2=function(t){h2(e,t);function e(i){var n;return n=t.call(this,i)||this,n.type=p2.ID,n}var r=e.prototype;return r.valueToString=function(){return"#"+t.prototype.valueToString.call(this)},e}(c2.default);yi.default=m2;Ah.exports=yi.default});var hs=k((vi,Ih)=>{l();"use strict";vi.__esModule=!0;vi.default=void 0;var g2=Ch(Wt()),y2=fi(),v2=Ch(dt());function Ch(t){return t&&t.__esModule?t:{default:t}}function Ph(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}function w2(t,e,r){return e&&Ph(t.prototype,e),r&&Ph(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function b2(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,Do(t,e)}function Do(t,e){return Do=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},Do(t,e)}var x2=function(t){b2(e,t);function e(){return t.apply(this,arguments)||this}var r=e.prototype;return r.qualifiedName=function(n){return this.namespace?this.namespaceString+"|"+n:n},r.valueToString=function(){return this.qualifiedName(t.prototype.valueToString.call(this))},w2(e,[{key:"namespace",get:function(){return this._namespace},set:function(n){if(n===!0||n==="*"||n==="&"){this._namespace=n,this.raws&&delete this.raws.namespace;return}var s=(0,g2.default)(n,{isIdentifier:!0});this._namespace=n,s!==n?((0,y2.ensureObject)(this,"raws"),this.raws.namespace=s):this.raws&&delete this.raws.namespace}},{key:"ns",get:function(){return this._namespace},set:function(n){this.namespace=n}},{key:"namespaceString",get:function(){if(this.namespace){var n=this.stringifyProperty("namespace");return n===!0?"":n}else return""}}]),e}(v2.default);vi.default=x2;Ih.exports=vi.default});var Ro=k((wi,Dh)=>{l();"use strict";wi.__esModule=!0;wi.default=void 0;var k2=_2(hs()),S2=be();function _2(t){return t&&t.__esModule?t:{default:t}}function T2(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,qo(t,e)}function qo(t,e){return qo=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},qo(t,e)}var O2=function(t){T2(e,t);function e(r){var i;return i=t.call(this,r)||this,i.type=S2.TAG,i}return e}(k2.default);wi.default=O2;Dh.exports=wi.default});var Bo=k((bi,qh)=>{l();"use strict";bi.__esModule=!0;bi.default=void 0;var E2=C2(dt()),A2=be();function C2(t){return t&&t.__esModule?t:{default:t}}function P2(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,Lo(t,e)}function Lo(t,e){return Lo=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},Lo(t,e)}var I2=function(t){P2(e,t);function e(r){var i;return i=t.call(this,r)||this,i.type=A2.STRING,i}return e}(E2.default);bi.default=I2;qh.exports=bi.default});var Fo=k((xi,Rh)=>{l();"use strict";xi.__esModule=!0;xi.default=void 0;var D2=R2(ds()),q2=be();function R2(t){return t&&t.__esModule?t:{default:t}}function L2(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,Mo(t,e)}function Mo(t,e){return Mo=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},Mo(t,e)}var B2=function(t){L2(e,t);function e(i){var n;return n=t.call(this,i)||this,n.type=q2.PSEUDO,n}var r=e.prototype;return r.toString=function(){var n=this.length?"("+this.map(String).join(",")+")":"";return[this.rawSpaceBefore,this.stringifyProperty("value"),n,this.rawSpaceAfter].join("")},e}(D2.default);xi.default=B2;Rh.exports=xi.default});var Lh={};Ge(Lh,{deprecate:()=>M2});function M2(t){return t}var Bh=A(()=>{l()});var No=k((VM,Mh)=>{l();Mh.exports=(Bh(),Lh).deprecate});var Wo=k(_i=>{l();"use strict";_i.__esModule=!0;_i.default=void 0;_i.unescapeValue=Uo;var ki=$o(Wt()),F2=$o(ls()),N2=$o(hs()),z2=be(),zo;function $o(t){return t&&t.__esModule?t:{default:t}}function Fh(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}function $2(t,e,r){return e&&Fh(t.prototype,e),r&&Fh(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function j2(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,jo(t,e)}function jo(t,e){return jo=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},jo(t,e)}var Si=No(),U2=/^('|")([^]*)\1$/,V2=Si(function(){},"Assigning an attribute a value containing characters that might need to be escaped is deprecated. Call attribute.setValue() instead."),W2=Si(function(){},"Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead."),G2=Si(function(){},"Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");function Uo(t){var e=!1,r=null,i=t,n=i.match(U2);return n&&(r=n[1],i=n[2]),i=(0,F2.default)(i),i!==t&&(e=!0),{deprecatedUsage:e,unescaped:i,quoteMark:r}}function H2(t){if(t.quoteMark!==void 0||t.value===void 0)return t;G2();var e=Uo(t.value),r=e.quoteMark,i=e.unescaped;return t.raws||(t.raws={}),t.raws.value===void 0&&(t.raws.value=t.value),t.value=i,t.quoteMark=r,t}var ms=function(t){j2(e,t);function e(i){var n;return i===void 0&&(i={}),n=t.call(this,H2(i))||this,n.type=z2.ATTRIBUTE,n.raws=n.raws||{},Object.defineProperty(n.raws,"unquoted",{get:Si(function(){return n.value},"attr.raws.unquoted is deprecated. Call attr.value instead."),set:Si(function(){return n.value},"Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")}),n._constructed=!0,n}var r=e.prototype;return r.getQuotedValue=function(n){n===void 0&&(n={});var s=this._determineQuoteMark(n),a=Vo[s],o=(0,ki.default)(this._value,a);return o},r._determineQuoteMark=function(n){return n.smart?this.smartQuoteMark(n):this.preferredQuoteMark(n)},r.setValue=function(n,s){s===void 0&&(s={}),this._value=n,this._quoteMark=this._determineQuoteMark(s),this._syncRawValue()},r.smartQuoteMark=function(n){var s=this.value,a=s.replace(/[^']/g,"").length,o=s.replace(/[^"]/g,"").length;if(a+o===0){var u=(0,ki.default)(s,{isIdentifier:!0});if(u===s)return e.NO_QUOTE;var c=this.preferredQuoteMark(n);if(c===e.NO_QUOTE){var f=this.quoteMark||n.quoteMark||e.DOUBLE_QUOTE,p=Vo[f],h=(0,ki.default)(s,p);if(h.length<u.length)return f}return c}else return o===a?this.preferredQuoteMark(n):o<a?e.DOUBLE_QUOTE:e.SINGLE_QUOTE},r.preferredQuoteMark=function(n){var s=n.preferCurrentQuoteMark?this.quoteMark:n.quoteMark;return s===void 0&&(s=n.preferCurrentQuoteMark?n.quoteMark:this.quoteMark),s===void 0&&(s=e.DOUBLE_QUOTE),s},r._syncRawValue=function(){var n=(0,ki.default)(this._value,Vo[this.quoteMark]);n===this._value?this.raws&&delete this.raws.value:this.raws.value=n},r._handleEscapes=function(n,s){if(this._constructed){var a=(0,ki.default)(s,{isIdentifier:!0});a!==s?this.raws[n]=a:delete this.raws[n]}},r._spacesFor=function(n){var s={before:"",after:""},a=this.spaces[n]||{},o=this.raws.spaces&&this.raws.spaces[n]||{};return Object.assign(s,a,o)},r._stringFor=function(n,s,a){s===void 0&&(s=n),a===void 0&&(a=Nh);var o=this._spacesFor(s);return a(this.stringifyProperty(n),o)},r.offsetOf=function(n){var s=1,a=this._spacesFor("attribute");if(s+=a.before.length,n==="namespace"||n==="ns")return this.namespace?s:-1;if(n==="attributeNS"||(s+=this.namespaceString.length,this.namespace&&(s+=1),n==="attribute"))return s;s+=this.stringifyProperty("attribute").length,s+=a.after.length;var o=this._spacesFor("operator");s+=o.before.length;var u=this.stringifyProperty("operator");if(n==="operator")return u?s:-1;s+=u.length,s+=o.after.length;var c=this._spacesFor("value");s+=c.before.length;var f=this.stringifyProperty("value");if(n==="value")return f?s:-1;s+=f.length,s+=c.after.length;var p=this._spacesFor("insensitive");return s+=p.before.length,n==="insensitive"&&this.insensitive?s:-1},r.toString=function(){var n=this,s=[this.rawSpaceBefore,"["];return s.push(this._stringFor("qualifiedAttribute","attribute")),this.operator&&(this.value||this.value==="")&&(s.push(this._stringFor("operator")),s.push(this._stringFor("value")),s.push(this._stringFor("insensitiveFlag","insensitive",function(a,o){return a.length>0&&!n.quoted&&o.before.length===0&&!(n.spaces.value&&n.spaces.value.after)&&(o.before=" "),Nh(a,o)}))),s.push("]"),s.push(this.rawSpaceAfter),s.join("")},$2(e,[{key:"quoted",get:function(){var n=this.quoteMark;return n==="'"||n==='"'},set:function(n){W2()}},{key:"quoteMark",get:function(){return this._quoteMark},set:function(n){if(!this._constructed){this._quoteMark=n;return}this._quoteMark!==n&&(this._quoteMark=n,this._syncRawValue())}},{key:"qualifiedAttribute",get:function(){return this.qualifiedName(this.raws.attribute||this.attribute)}},{key:"insensitiveFlag",get:function(){return this.insensitive?"i":""}},{key:"value",get:function(){return this._value},set:function(n){if(this._constructed){var s=Uo(n),a=s.deprecatedUsage,o=s.unescaped,u=s.quoteMark;if(a&&V2(),o===this._value&&u===this._quoteMark)return;this._value=o,this._quoteMark=u,this._syncRawValue()}else this._value=n}},{key:"insensitive",get:function(){return this._insensitive},set:function(n){n||(this._insensitive=!1,this.raws&&(this.raws.insensitiveFlag==="I"||this.raws.insensitiveFlag==="i")&&(this.raws.insensitiveFlag=void 0)),this._insensitive=n}},{key:"attribute",get:function(){return this._attribute},set:function(n){this._handleEscapes("attribute",n),this._attribute=n}}]),e}(N2.default);_i.default=ms;ms.NO_QUOTE=null;ms.SINGLE_QUOTE="'";ms.DOUBLE_QUOTE='"';var Vo=(zo={"'":{quotes:"single",wrap:!0},'"':{quotes:"double",wrap:!0}},zo[null]={isIdentifier:!0},zo);function Nh(t,e){return""+e.before+t+e.after}});var Ho=k((Ti,zh)=>{l();"use strict";Ti.__esModule=!0;Ti.default=void 0;var Y2=J2(hs()),Q2=be();function J2(t){return t&&t.__esModule?t:{default:t}}function X2(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,Go(t,e)}function Go(t,e){return Go=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},Go(t,e)}var K2=function(t){X2(e,t);function e(r){var i;return i=t.call(this,r)||this,i.type=Q2.UNIVERSAL,i.value="*",i}return e}(Y2.default);Ti.default=K2;zh.exports=Ti.default});var Qo=k((Oi,$h)=>{l();"use strict";Oi.__esModule=!0;Oi.default=void 0;var Z2=tT(dt()),eT=be();function tT(t){return t&&t.__esModule?t:{default:t}}function rT(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,Yo(t,e)}function Yo(t,e){return Yo=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},Yo(t,e)}var iT=function(t){rT(e,t);function e(r){var i;return i=t.call(this,r)||this,i.type=eT.COMBINATOR,i}return e}(Z2.default);Oi.default=iT;$h.exports=Oi.default});var Xo=k((Ei,jh)=>{l();"use strict";Ei.__esModule=!0;Ei.default=void 0;var nT=aT(dt()),sT=be();function aT(t){return t&&t.__esModule?t:{default:t}}function oT(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,Jo(t,e)}function Jo(t,e){return Jo=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},Jo(t,e)}var lT=function(t){oT(e,t);function e(r){var i;return i=t.call(this,r)||this,i.type=sT.NESTING,i.value="&",i}return e}(nT.default);Ei.default=lT;jh.exports=Ei.default});var Vh=k((gs,Uh)=>{l();"use strict";gs.__esModule=!0;gs.default=uT;function uT(t){return t.sort(function(e,r){return e-r})}Uh.exports=gs.default});var Ko=k(B=>{l();"use strict";B.__esModule=!0;B.word=B.tilde=B.tab=B.str=B.space=B.slash=B.singleQuote=B.semicolon=B.plus=B.pipe=B.openSquare=B.openParenthesis=B.newline=B.greaterThan=B.feed=B.equals=B.doubleQuote=B.dollar=B.cr=B.comment=B.comma=B.combinator=B.colon=B.closeSquare=B.closeParenthesis=B.caret=B.bang=B.backslash=B.at=B.asterisk=B.ampersand=void 0;var fT=38;B.ampersand=fT;var cT=42;B.asterisk=cT;var pT=64;B.at=pT;var dT=44;B.comma=dT;var hT=58;B.colon=hT;var mT=59;B.semicolon=mT;var gT=40;B.openParenthesis=gT;var yT=41;B.closeParenthesis=yT;var vT=91;B.openSquare=vT;var wT=93;B.closeSquare=wT;var bT=36;B.dollar=bT;var xT=126;B.tilde=xT;var kT=94;B.caret=kT;var ST=43;B.plus=ST;var _T=61;B.equals=_T;var TT=124;B.pipe=TT;var OT=62;B.greaterThan=OT;var ET=32;B.space=ET;var Wh=39;B.singleQuote=Wh;var AT=34;B.doubleQuote=AT;var CT=47;B.slash=CT;var PT=33;B.bang=PT;var IT=92;B.backslash=IT;var DT=13;B.cr=DT;var qT=12;B.feed=qT;var RT=10;B.newline=RT;var LT=9;B.tab=LT;var BT=Wh;B.str=BT;var MT=-1;B.comment=MT;var FT=-2;B.word=FT;var NT=-3;B.combinator=NT});var Yh=k(Ai=>{l();"use strict";Ai.__esModule=!0;Ai.FIELDS=void 0;Ai.default=GT;var I=zT(Ko()),fr,K;function Gh(t){if(typeof WeakMap!="function")return null;var e=new WeakMap,r=new WeakMap;return(Gh=function(n){return n?r:e})(t)}function zT(t,e){if(!e&&t&&t.__esModule)return t;if(t===null||typeof t!="object"&&typeof t!="function")return{default:t};var r=Gh(e);if(r&&r.has(t))return r.get(t);var i={},n=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in t)if(s!=="default"&&Object.prototype.hasOwnProperty.call(t,s)){var a=n?Object.getOwnPropertyDescriptor(t,s):null;a&&(a.get||a.set)?Object.defineProperty(i,s,a):i[s]=t[s]}return i.default=t,r&&r.set(t,i),i}var $T=(fr={},fr[I.tab]=!0,fr[I.newline]=!0,fr[I.cr]=!0,fr[I.feed]=!0,fr),jT=(K={},K[I.space]=!0,K[I.tab]=!0,K[I.newline]=!0,K[I.cr]=!0,K[I.feed]=!0,K[I.ampersand]=!0,K[I.asterisk]=!0,K[I.bang]=!0,K[I.comma]=!0,K[I.colon]=!0,K[I.semicolon]=!0,K[I.openParenthesis]=!0,K[I.closeParenthesis]=!0,K[I.openSquare]=!0,K[I.closeSquare]=!0,K[I.singleQuote]=!0,K[I.doubleQuote]=!0,K[I.plus]=!0,K[I.pipe]=!0,K[I.tilde]=!0,K[I.greaterThan]=!0,K[I.equals]=!0,K[I.dollar]=!0,K[I.caret]=!0,K[I.slash]=!0,K),Zo={},Hh="0123456789abcdefABCDEF";for(ys=0;ys<Hh.length;ys++)Zo[Hh.charCodeAt(ys)]=!0;var ys;function UT(t,e){var r=e,i;do{if(i=t.charCodeAt(r),jT[i])return r-1;i===I.backslash?r=VT(t,r)+1:r++}while(r<t.length);return r-1}function VT(t,e){var r=e,i=t.charCodeAt(r+1);if(!$T[i])if(Zo[i]){var n=0;do r++,n++,i=t.charCodeAt(r+1);while(Zo[i]&&n<6);n<6&&i===I.space&&r++}else r++;return r}var WT={TYPE:0,START_LINE:1,START_COL:2,END_LINE:3,END_COL:4,START_POS:5,END_POS:6};Ai.FIELDS=WT;function GT(t){var e=[],r=t.css.valueOf(),i=r,n=i.length,s=-1,a=1,o=0,u=0,c,f,p,h,m,v,S,b,w,_,T,O,E;function F(z,N){if(t.safe)r+=N,w=r.length-1;else throw t.error("Unclosed "+z,a,o-s,o)}for(;o<n;){switch(c=r.charCodeAt(o),c===I.newline&&(s=o,a+=1),c){case I.space:case I.tab:case I.newline:case I.cr:case I.feed:w=o;do w+=1,c=r.charCodeAt(w),c===I.newline&&(s=w,a+=1);while(c===I.space||c===I.newline||c===I.tab||c===I.cr||c===I.feed);E=I.space,h=a,p=w-s-1,u=w;break;case I.plus:case I.greaterThan:case I.tilde:case I.pipe:w=o;do w+=1,c=r.charCodeAt(w);while(c===I.plus||c===I.greaterThan||c===I.tilde||c===I.pipe);E=I.combinator,h=a,p=o-s,u=w;break;case I.asterisk:case I.ampersand:case I.bang:case I.comma:case I.equals:case I.dollar:case I.caret:case I.openSquare:case I.closeSquare:case I.colon:case I.semicolon:case I.openParenthesis:case I.closeParenthesis:w=o,E=c,h=a,p=o-s,u=w+1;break;case I.singleQuote:case I.doubleQuote:O=c===I.singleQuote?"'":'"',w=o;do for(m=!1,w=r.indexOf(O,w+1),w===-1&&F("quote",O),v=w;r.charCodeAt(v-1)===I.backslash;)v-=1,m=!m;while(m);E=I.str,h=a,p=o-s,u=w+1;break;default:c===I.slash&&r.charCodeAt(o+1)===I.asterisk?(w=r.indexOf("*/",o+2)+1,w===0&&F("comment","*/"),f=r.slice(o,w+1),b=f.split(`
`),S=b.length-1,S>0?(_=a+S,T=w-b[S].length):(_=a,T=s),E=I.comment,a=_,h=_,p=w-T):c===I.slash?(w=o,E=c,h=a,p=o-s,u=w+1):(w=UT(r,o),E=I.word,h=a,p=w-s),u=w+1;break}e.push([E,a,o-s,h,p,o,u]),T&&(s=T,T=null),o=u}return e}});var rm=k((Ci,tm)=>{l();"use strict";Ci.__esModule=!0;Ci.default=void 0;var HT=Be(ko()),el=Be(_o()),YT=Be(Eo()),Qh=Be(Co()),QT=Be(Io()),JT=Be(Ro()),tl=Be(Bo()),XT=Be(Fo()),Jh=vs(Wo()),KT=Be(Ho()),rl=Be(Qo()),ZT=Be(Xo()),eO=Be(Vh()),C=vs(Yh()),q=vs(Ko()),tO=vs(be()),ae=fi(),Gt,il;function Xh(t){if(typeof WeakMap!="function")return null;var e=new WeakMap,r=new WeakMap;return(Xh=function(n){return n?r:e})(t)}function vs(t,e){if(!e&&t&&t.__esModule)return t;if(t===null||typeof t!="object"&&typeof t!="function")return{default:t};var r=Xh(e);if(r&&r.has(t))return r.get(t);var i={},n=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in t)if(s!=="default"&&Object.prototype.hasOwnProperty.call(t,s)){var a=n?Object.getOwnPropertyDescriptor(t,s):null;a&&(a.get||a.set)?Object.defineProperty(i,s,a):i[s]=t[s]}return i.default=t,r&&r.set(t,i),i}function Be(t){return t&&t.__esModule?t:{default:t}}function Kh(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}function rO(t,e,r){return e&&Kh(t.prototype,e),r&&Kh(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}var nl=(Gt={},Gt[q.space]=!0,Gt[q.cr]=!0,Gt[q.feed]=!0,Gt[q.newline]=!0,Gt[q.tab]=!0,Gt),iO=Object.assign({},nl,(il={},il[q.comment]=!0,il));function Zh(t){return{line:t[C.FIELDS.START_LINE],column:t[C.FIELDS.START_COL]}}function em(t){return{line:t[C.FIELDS.END_LINE],column:t[C.FIELDS.END_COL]}}function Ht(t,e,r,i){return{start:{line:t,column:e},end:{line:r,column:i}}}function cr(t){return Ht(t[C.FIELDS.START_LINE],t[C.FIELDS.START_COL],t[C.FIELDS.END_LINE],t[C.FIELDS.END_COL])}function sl(t,e){if(!!t)return Ht(t[C.FIELDS.START_LINE],t[C.FIELDS.START_COL],e[C.FIELDS.END_LINE],e[C.FIELDS.END_COL])}function pr(t,e){var r=t[e];if(typeof r=="string")return r.indexOf("\\")!==-1&&((0,ae.ensureObject)(t,"raws"),t[e]=(0,ae.unesc)(r),t.raws[e]===void 0&&(t.raws[e]=r)),t}function al(t,e){for(var r=-1,i=[];(r=t.indexOf(e,r+1))!==-1;)i.push(r);return i}function nO(){var t=Array.prototype.concat.apply([],arguments);return t.filter(function(e,r){return r===t.indexOf(e)})}var sO=function(){function t(r,i){i===void 0&&(i={}),this.rule=r,this.options=Object.assign({lossy:!1,safe:!1},i),this.position=0,this.css=typeof this.rule=="string"?this.rule:this.rule.selector,this.tokens=(0,C.default)({css:this.css,error:this._errorGenerator(),safe:this.options.safe});var n=sl(this.tokens[0],this.tokens[this.tokens.length-1]);this.root=new HT.default({source:n}),this.root.errorGenerator=this._errorGenerator();var s=new el.default({source:{start:{line:1,column:1}}});this.root.append(s),this.current=s,this.loop()}var e=t.prototype;return e._errorGenerator=function(){var i=this;return function(n,s){return typeof i.rule=="string"?new Error(n):i.rule.error(n,s)}},e.attribute=function(){var i=[],n=this.currToken;for(this.position++;this.position<this.tokens.length&&this.currToken[C.FIELDS.TYPE]!==q.closeSquare;)i.push(this.currToken),this.position++;if(this.currToken[C.FIELDS.TYPE]!==q.closeSquare)return this.expected("closing square bracket",this.currToken[C.FIELDS.START_POS]);var s=i.length,a={source:Ht(n[1],n[2],this.currToken[3],this.currToken[4]),sourceIndex:n[C.FIELDS.START_POS]};if(s===1&&!~[q.word].indexOf(i[0][C.FIELDS.TYPE]))return this.expected("attribute",i[0][C.FIELDS.START_POS]);for(var o=0,u="",c="",f=null,p=!1;o<s;){var h=i[o],m=this.content(h),v=i[o+1];switch(h[C.FIELDS.TYPE]){case q.space:if(p=!0,this.options.lossy)break;if(f){(0,ae.ensureObject)(a,"spaces",f);var S=a.spaces[f].after||"";a.spaces[f].after=S+m;var b=(0,ae.getProp)(a,"raws","spaces",f,"after")||null;b&&(a.raws.spaces[f].after=b+m)}else u=u+m,c=c+m;break;case q.asterisk:if(v[C.FIELDS.TYPE]===q.equals)a.operator=m,f="operator";else if((!a.namespace||f==="namespace"&&!p)&&v){u&&((0,ae.ensureObject)(a,"spaces","attribute"),a.spaces.attribute.before=u,u=""),c&&((0,ae.ensureObject)(a,"raws","spaces","attribute"),a.raws.spaces.attribute.before=u,c=""),a.namespace=(a.namespace||"")+m;var w=(0,ae.getProp)(a,"raws","namespace")||null;w&&(a.raws.namespace+=m),f="namespace"}p=!1;break;case q.dollar:if(f==="value"){var _=(0,ae.getProp)(a,"raws","value");a.value+="$",_&&(a.raws.value=_+"$");break}case q.caret:v[C.FIELDS.TYPE]===q.equals&&(a.operator=m,f="operator"),p=!1;break;case q.combinator:if(m==="~"&&v[C.FIELDS.TYPE]===q.equals&&(a.operator=m,f="operator"),m!=="|"){p=!1;break}v[C.FIELDS.TYPE]===q.equals?(a.operator=m,f="operator"):!a.namespace&&!a.attribute&&(a.namespace=!0),p=!1;break;case q.word:if(v&&this.content(v)==="|"&&i[o+2]&&i[o+2][C.FIELDS.TYPE]!==q.equals&&!a.operator&&!a.namespace)a.namespace=m,f="namespace";else if(!a.attribute||f==="attribute"&&!p){u&&((0,ae.ensureObject)(a,"spaces","attribute"),a.spaces.attribute.before=u,u=""),c&&((0,ae.ensureObject)(a,"raws","spaces","attribute"),a.raws.spaces.attribute.before=c,c=""),a.attribute=(a.attribute||"")+m;var T=(0,ae.getProp)(a,"raws","attribute")||null;T&&(a.raws.attribute+=m),f="attribute"}else if(!a.value&&a.value!==""||f==="value"&&!(p||a.quoteMark)){var O=(0,ae.unesc)(m),E=(0,ae.getProp)(a,"raws","value")||"",F=a.value||"";a.value=F+O,a.quoteMark=null,(O!==m||E)&&((0,ae.ensureObject)(a,"raws"),a.raws.value=(E||F)+m),f="value"}else{var z=m==="i"||m==="I";(a.value||a.value==="")&&(a.quoteMark||p)?(a.insensitive=z,(!z||m==="I")&&((0,ae.ensureObject)(a,"raws"),a.raws.insensitiveFlag=m),f="insensitive",u&&((0,ae.ensureObject)(a,"spaces","insensitive"),a.spaces.insensitive.before=u,u=""),c&&((0,ae.ensureObject)(a,"raws","spaces","insensitive"),a.raws.spaces.insensitive.before=c,c="")):(a.value||a.value==="")&&(f="value",a.value+=m,a.raws.value&&(a.raws.value+=m))}p=!1;break;case q.str:if(!a.attribute||!a.operator)return this.error("Expected an attribute followed by an operator preceding the string.",{index:h[C.FIELDS.START_POS]});var N=(0,Jh.unescapeValue)(m),fe=N.unescaped,ye=N.quoteMark;a.value=fe,a.quoteMark=ye,f="value",(0,ae.ensureObject)(a,"raws"),a.raws.value=m,p=!1;break;case q.equals:if(!a.attribute)return this.expected("attribute",h[C.FIELDS.START_POS],m);if(a.value)return this.error('Unexpected "=" found; an operator was already defined.',{index:h[C.FIELDS.START_POS]});a.operator=a.operator?a.operator+m:m,f="operator",p=!1;break;case q.comment:if(f)if(p||v&&v[C.FIELDS.TYPE]===q.space||f==="insensitive"){var Se=(0,ae.getProp)(a,"spaces",f,"after")||"",Ve=(0,ae.getProp)(a,"raws","spaces",f,"after")||Se;(0,ae.ensureObject)(a,"raws","spaces",f),a.raws.spaces[f].after=Ve+m}else{var W=a[f]||"",ve=(0,ae.getProp)(a,"raws",f)||W;(0,ae.ensureObject)(a,"raws"),a.raws[f]=ve+m}else c=c+m;break;default:return this.error('Unexpected "'+m+'" found.',{index:h[C.FIELDS.START_POS]})}o++}pr(a,"attribute"),pr(a,"namespace"),this.newNode(new Jh.default(a)),this.position++},e.parseWhitespaceEquivalentTokens=function(i){i<0&&(i=this.tokens.length);var n=this.position,s=[],a="",o=void 0;do if(nl[this.currToken[C.FIELDS.TYPE]])this.options.lossy||(a+=this.content());else if(this.currToken[C.FIELDS.TYPE]===q.comment){var u={};a&&(u.before=a,a=""),o=new Qh.default({value:this.content(),source:cr(this.currToken),sourceIndex:this.currToken[C.FIELDS.START_POS],spaces:u}),s.push(o)}while(++this.position<i);if(a){if(o)o.spaces.after=a;else if(!this.options.lossy){var c=this.tokens[n],f=this.tokens[this.position-1];s.push(new tl.default({value:"",source:Ht(c[C.FIELDS.START_LINE],c[C.FIELDS.START_COL],f[C.FIELDS.END_LINE],f[C.FIELDS.END_COL]),sourceIndex:c[C.FIELDS.START_POS],spaces:{before:a,after:""}}))}}return s},e.convertWhitespaceNodesToSpace=function(i,n){var s=this;n===void 0&&(n=!1);var a="",o="";i.forEach(function(c){var f=s.lossySpace(c.spaces.before,n),p=s.lossySpace(c.rawSpaceBefore,n);a+=f+s.lossySpace(c.spaces.after,n&&f.length===0),o+=f+c.value+s.lossySpace(c.rawSpaceAfter,n&&p.length===0)}),o===a&&(o=void 0);var u={space:a,rawSpace:o};return u},e.isNamedCombinator=function(i){return i===void 0&&(i=this.position),this.tokens[i+0]&&this.tokens[i+0][C.FIELDS.TYPE]===q.slash&&this.tokens[i+1]&&this.tokens[i+1][C.FIELDS.TYPE]===q.word&&this.tokens[i+2]&&this.tokens[i+2][C.FIELDS.TYPE]===q.slash},e.namedCombinator=function(){if(this.isNamedCombinator()){var i=this.content(this.tokens[this.position+1]),n=(0,ae.unesc)(i).toLowerCase(),s={};n!==i&&(s.value="/"+i+"/");var a=new rl.default({value:"/"+n+"/",source:Ht(this.currToken[C.FIELDS.START_LINE],this.currToken[C.FIELDS.START_COL],this.tokens[this.position+2][C.FIELDS.END_LINE],this.tokens[this.position+2][C.FIELDS.END_COL]),sourceIndex:this.currToken[C.FIELDS.START_POS],raws:s});return this.position=this.position+3,a}else this.unexpected()},e.combinator=function(){var i=this;if(this.content()==="|")return this.namespace();var n=this.locateNextMeaningfulToken(this.position);if(n<0||this.tokens[n][C.FIELDS.TYPE]===q.comma){var s=this.parseWhitespaceEquivalentTokens(n);if(s.length>0){var a=this.current.last;if(a){var o=this.convertWhitespaceNodesToSpace(s),u=o.space,c=o.rawSpace;c!==void 0&&(a.rawSpaceAfter+=c),a.spaces.after+=u}else s.forEach(function(E){return i.newNode(E)})}return}var f=this.currToken,p=void 0;n>this.position&&(p=this.parseWhitespaceEquivalentTokens(n));var h;if(this.isNamedCombinator()?h=this.namedCombinator():this.currToken[C.FIELDS.TYPE]===q.combinator?(h=new rl.default({value:this.content(),source:cr(this.currToken),sourceIndex:this.currToken[C.FIELDS.START_POS]}),this.position++):nl[this.currToken[C.FIELDS.TYPE]]||p||this.unexpected(),h){if(p){var m=this.convertWhitespaceNodesToSpace(p),v=m.space,S=m.rawSpace;h.spaces.before=v,h.rawSpaceBefore=S}}else{var b=this.convertWhitespaceNodesToSpace(p,!0),w=b.space,_=b.rawSpace;_||(_=w);var T={},O={spaces:{}};w.endsWith(" ")&&_.endsWith(" ")?(T.before=w.slice(0,w.length-1),O.spaces.before=_.slice(0,_.length-1)):w.startsWith(" ")&&_.startsWith(" ")?(T.after=w.slice(1),O.spaces.after=_.slice(1)):O.value=_,h=new rl.default({value:" ",source:sl(f,this.tokens[this.position-1]),sourceIndex:f[C.FIELDS.START_POS],spaces:T,raws:O})}return this.currToken&&this.currToken[C.FIELDS.TYPE]===q.space&&(h.spaces.after=this.optionalSpace(this.content()),this.position++),this.newNode(h)},e.comma=function(){if(this.position===this.tokens.length-1){this.root.trailingComma=!0,this.position++;return}this.current._inferEndPosition();var i=new el.default({source:{start:Zh(this.tokens[this.position+1])}});this.current.parent.append(i),this.current=i,this.position++},e.comment=function(){var i=this.currToken;this.newNode(new Qh.default({value:this.content(),source:cr(i),sourceIndex:i[C.FIELDS.START_POS]})),this.position++},e.error=function(i,n){throw this.root.error(i,n)},e.missingBackslash=function(){return this.error("Expected a backslash preceding the semicolon.",{index:this.currToken[C.FIELDS.START_POS]})},e.missingParenthesis=function(){return this.expected("opening parenthesis",this.currToken[C.FIELDS.START_POS])},e.missingSquareBracket=function(){return this.expected("opening square bracket",this.currToken[C.FIELDS.START_POS])},e.unexpected=function(){return this.error("Unexpected '"+this.content()+"'. Escaping special characters with \\ may help.",this.currToken[C.FIELDS.START_POS])},e.unexpectedPipe=function(){return this.error("Unexpected '|'.",this.currToken[C.FIELDS.START_POS])},e.namespace=function(){var i=this.prevToken&&this.content(this.prevToken)||!0;if(this.nextToken[C.FIELDS.TYPE]===q.word)return this.position++,this.word(i);if(this.nextToken[C.FIELDS.TYPE]===q.asterisk)return this.position++,this.universal(i);this.unexpectedPipe()},e.nesting=function(){if(this.nextToken){var i=this.content(this.nextToken);if(i==="|"){this.position++;return}}var n=this.currToken;this.newNode(new ZT.default({value:this.content(),source:cr(n),sourceIndex:n[C.FIELDS.START_POS]})),this.position++},e.parentheses=function(){var i=this.current.last,n=1;if(this.position++,i&&i.type===tO.PSEUDO){var s=new el.default({source:{start:Zh(this.tokens[this.position-1])}}),a=this.current;for(i.append(s),this.current=s;this.position<this.tokens.length&&n;)this.currToken[C.FIELDS.TYPE]===q.openParenthesis&&n++,this.currToken[C.FIELDS.TYPE]===q.closeParenthesis&&n--,n?this.parse():(this.current.source.end=em(this.currToken),this.current.parent.source.end=em(this.currToken),this.position++);this.current=a}else{for(var o=this.currToken,u="(",c;this.position<this.tokens.length&&n;)this.currToken[C.FIELDS.TYPE]===q.openParenthesis&&n++,this.currToken[C.FIELDS.TYPE]===q.closeParenthesis&&n--,c=this.currToken,u+=this.parseParenthesisToken(this.currToken),this.position++;i?i.appendToPropertyAndEscape("value",u,u):this.newNode(new tl.default({value:u,source:Ht(o[C.FIELDS.START_LINE],o[C.FIELDS.START_COL],c[C.FIELDS.END_LINE],c[C.FIELDS.END_COL]),sourceIndex:o[C.FIELDS.START_POS]}))}if(n)return this.expected("closing parenthesis",this.currToken[C.FIELDS.START_POS])},e.pseudo=function(){for(var i=this,n="",s=this.currToken;this.currToken&&this.currToken[C.FIELDS.TYPE]===q.colon;)n+=this.content(),this.position++;if(!this.currToken)return this.expected(["pseudo-class","pseudo-element"],this.position-1);if(this.currToken[C.FIELDS.TYPE]===q.word)this.splitWord(!1,function(a,o){n+=a,i.newNode(new XT.default({value:n,source:sl(s,i.currToken),sourceIndex:s[C.FIELDS.START_POS]})),o>1&&i.nextToken&&i.nextToken[C.FIELDS.TYPE]===q.openParenthesis&&i.error("Misplaced parenthesis.",{index:i.nextToken[C.FIELDS.START_POS]})});else return this.expected(["pseudo-class","pseudo-element"],this.currToken[C.FIELDS.START_POS])},e.space=function(){var i=this.content();this.position===0||this.prevToken[C.FIELDS.TYPE]===q.comma||this.prevToken[C.FIELDS.TYPE]===q.openParenthesis||this.current.nodes.every(function(n){return n.type==="comment"})?(this.spaces=this.optionalSpace(i),this.position++):this.position===this.tokens.length-1||this.nextToken[C.FIELDS.TYPE]===q.comma||this.nextToken[C.FIELDS.TYPE]===q.closeParenthesis?(this.current.last.spaces.after=this.optionalSpace(i),this.position++):this.combinator()},e.string=function(){var i=this.currToken;this.newNode(new tl.default({value:this.content(),source:cr(i),sourceIndex:i[C.FIELDS.START_POS]})),this.position++},e.universal=function(i){var n=this.nextToken;if(n&&this.content(n)==="|")return this.position++,this.namespace();var s=this.currToken;this.newNode(new KT.default({value:this.content(),source:cr(s),sourceIndex:s[C.FIELDS.START_POS]}),i),this.position++},e.splitWord=function(i,n){for(var s=this,a=this.nextToken,o=this.content();a&&~[q.dollar,q.caret,q.equals,q.word].indexOf(a[C.FIELDS.TYPE]);){this.position++;var u=this.content();if(o+=u,u.lastIndexOf("\\")===u.length-1){var c=this.nextToken;c&&c[C.FIELDS.TYPE]===q.space&&(o+=this.requiredSpace(this.content(c)),this.position++)}a=this.nextToken}var f=al(o,".").filter(function(v){var S=o[v-1]==="\\",b=/^\d+\.\d+%$/.test(o);return!S&&!b}),p=al(o,"#").filter(function(v){return o[v-1]!=="\\"}),h=al(o,"#{");h.length&&(p=p.filter(function(v){return!~h.indexOf(v)}));var m=(0,eO.default)(nO([0].concat(f,p)));m.forEach(function(v,S){var b=m[S+1]||o.length,w=o.slice(v,b);if(S===0&&n)return n.call(s,w,m.length);var _,T=s.currToken,O=T[C.FIELDS.START_POS]+m[S],E=Ht(T[1],T[2]+v,T[3],T[2]+(b-1));if(~f.indexOf(v)){var F={value:w.slice(1),source:E,sourceIndex:O};_=new YT.default(pr(F,"value"))}else if(~p.indexOf(v)){var z={value:w.slice(1),source:E,sourceIndex:O};_=new QT.default(pr(z,"value"))}else{var N={value:w,source:E,sourceIndex:O};pr(N,"value"),_=new JT.default(N)}s.newNode(_,i),i=null}),this.position++},e.word=function(i){var n=this.nextToken;return n&&this.content(n)==="|"?(this.position++,this.namespace()):this.splitWord(i)},e.loop=function(){for(;this.position<this.tokens.length;)this.parse(!0);return this.current._inferEndPosition(),this.root},e.parse=function(i){switch(this.currToken[C.FIELDS.TYPE]){case q.space:this.space();break;case q.comment:this.comment();break;case q.openParenthesis:this.parentheses();break;case q.closeParenthesis:i&&this.missingParenthesis();break;case q.openSquare:this.attribute();break;case q.dollar:case q.caret:case q.equals:case q.word:this.word();break;case q.colon:this.pseudo();break;case q.comma:this.comma();break;case q.asterisk:this.universal();break;case q.ampersand:this.nesting();break;case q.slash:case q.combinator:this.combinator();break;case q.str:this.string();break;case q.closeSquare:this.missingSquareBracket();case q.semicolon:this.missingBackslash();default:this.unexpected()}},e.expected=function(i,n,s){if(Array.isArray(i)){var a=i.pop();i=i.join(", ")+" or "+a}var o=/^[aeiou]/.test(i[0])?"an":"a";return s?this.error("Expected "+o+" "+i+', found "'+s+'" instead.',{index:n}):this.error("Expected "+o+" "+i+".",{index:n})},e.requiredSpace=function(i){return this.options.lossy?" ":i},e.optionalSpace=function(i){return this.options.lossy?"":i},e.lossySpace=function(i,n){return this.options.lossy?n?" ":"":i},e.parseParenthesisToken=function(i){var n=this.content(i);return i[C.FIELDS.TYPE]===q.space?this.requiredSpace(n):n},e.newNode=function(i,n){return n&&(/^ +$/.test(n)&&(this.options.lossy||(this.spaces=(this.spaces||"")+n),n=!0),i.namespace=n,pr(i,"namespace")),this.spaces&&(i.spaces.before=this.spaces,this.spaces=""),this.current.append(i)},e.content=function(i){return i===void 0&&(i=this.currToken),this.css.slice(i[C.FIELDS.START_POS],i[C.FIELDS.END_POS])},e.locateNextMeaningfulToken=function(i){i===void 0&&(i=this.position+1);for(var n=i;n<this.tokens.length;)if(iO[this.tokens[n][C.FIELDS.TYPE]]){n++;continue}else return n;return-1},rO(t,[{key:"currToken",get:function(){return this.tokens[this.position]}},{key:"nextToken",get:function(){return this.tokens[this.position+1]}},{key:"prevToken",get:function(){return this.tokens[this.position-1]}}]),t}();Ci.default=sO;tm.exports=Ci.default});var nm=k((Pi,im)=>{l();"use strict";Pi.__esModule=!0;Pi.default=void 0;var aO=oO(rm());function oO(t){return t&&t.__esModule?t:{default:t}}var lO=function(){function t(r,i){this.func=r||function(){},this.funcRes=null,this.options=i}var e=t.prototype;return e._shouldUpdateSelector=function(i,n){n===void 0&&(n={});var s=Object.assign({},this.options,n);return s.updateSelector===!1?!1:typeof i!="string"},e._isLossy=function(i){i===void 0&&(i={});var n=Object.assign({},this.options,i);return n.lossless===!1},e._root=function(i,n){n===void 0&&(n={});var s=new aO.default(i,this._parseOptions(n));return s.root},e._parseOptions=function(i){return{lossy:this._isLossy(i)}},e._run=function(i,n){var s=this;return n===void 0&&(n={}),new Promise(function(a,o){try{var u=s._root(i,n);Promise.resolve(s.func(u)).then(function(c){var f=void 0;return s._shouldUpdateSelector(i,n)&&(f=u.toString(),i.selector=f),{transform:c,root:u,string:f}}).then(a,o)}catch(c){o(c);return}})},e._runSync=function(i,n){n===void 0&&(n={});var s=this._root(i,n),a=this.func(s);if(a&&typeof a.then=="function")throw new Error("Selector processor returned a promise to a synchronous call.");var o=void 0;return n.updateSelector&&typeof i!="string"&&(o=s.toString(),i.selector=o),{transform:a,root:s,string:o}},e.ast=function(i,n){return this._run(i,n).then(function(s){return s.root})},e.astSync=function(i,n){return this._runSync(i,n).root},e.transform=function(i,n){return this._run(i,n).then(function(s){return s.transform})},e.transformSync=function(i,n){return this._runSync(i,n).transform},e.process=function(i,n){return this._run(i,n).then(function(s){return s.string||s.root.toString()})},e.processSync=function(i,n){var s=this._runSync(i,n);return s.string||s.root.toString()},t}();Pi.default=lO;im.exports=Pi.default});var sm=k(re=>{l();"use strict";re.__esModule=!0;re.universal=re.tag=re.string=re.selector=re.root=re.pseudo=re.nesting=re.id=re.comment=re.combinator=re.className=re.attribute=void 0;var uO=Me(Wo()),fO=Me(Eo()),cO=Me(Qo()),pO=Me(Co()),dO=Me(Io()),hO=Me(Xo()),mO=Me(Fo()),gO=Me(ko()),yO=Me(_o()),vO=Me(Bo()),wO=Me(Ro()),bO=Me(Ho());function Me(t){return t&&t.__esModule?t:{default:t}}var xO=function(e){return new uO.default(e)};re.attribute=xO;var kO=function(e){return new fO.default(e)};re.className=kO;var SO=function(e){return new cO.default(e)};re.combinator=SO;var _O=function(e){return new pO.default(e)};re.comment=_O;var TO=function(e){return new dO.default(e)};re.id=TO;var OO=function(e){return new hO.default(e)};re.nesting=OO;var EO=function(e){return new mO.default(e)};re.pseudo=EO;var AO=function(e){return new gO.default(e)};re.root=AO;var CO=function(e){return new yO.default(e)};re.selector=CO;var PO=function(e){return new vO.default(e)};re.string=PO;var IO=function(e){return new wO.default(e)};re.tag=IO;var DO=function(e){return new bO.default(e)};re.universal=DO});var um=k(Y=>{l();"use strict";Y.__esModule=!0;Y.isComment=Y.isCombinator=Y.isClassName=Y.isAttribute=void 0;Y.isContainer=VO;Y.isIdentifier=void 0;Y.isNamespace=WO;Y.isNesting=void 0;Y.isNode=ol;Y.isPseudo=void 0;Y.isPseudoClass=UO;Y.isPseudoElement=lm;Y.isUniversal=Y.isTag=Y.isString=Y.isSelector=Y.isRoot=void 0;var oe=be(),Ae,qO=(Ae={},Ae[oe.ATTRIBUTE]=!0,Ae[oe.CLASS]=!0,Ae[oe.COMBINATOR]=!0,Ae[oe.COMMENT]=!0,Ae[oe.ID]=!0,Ae[oe.NESTING]=!0,Ae[oe.PSEUDO]=!0,Ae[oe.ROOT]=!0,Ae[oe.SELECTOR]=!0,Ae[oe.STRING]=!0,Ae[oe.TAG]=!0,Ae[oe.UNIVERSAL]=!0,Ae);function ol(t){return typeof t=="object"&&qO[t.type]}function Fe(t,e){return ol(e)&&e.type===t}var am=Fe.bind(null,oe.ATTRIBUTE);Y.isAttribute=am;var RO=Fe.bind(null,oe.CLASS);Y.isClassName=RO;var LO=Fe.bind(null,oe.COMBINATOR);Y.isCombinator=LO;var BO=Fe.bind(null,oe.COMMENT);Y.isComment=BO;var MO=Fe.bind(null,oe.ID);Y.isIdentifier=MO;var FO=Fe.bind(null,oe.NESTING);Y.isNesting=FO;var ll=Fe.bind(null,oe.PSEUDO);Y.isPseudo=ll;var NO=Fe.bind(null,oe.ROOT);Y.isRoot=NO;var zO=Fe.bind(null,oe.SELECTOR);Y.isSelector=zO;var $O=Fe.bind(null,oe.STRING);Y.isString=$O;var om=Fe.bind(null,oe.TAG);Y.isTag=om;var jO=Fe.bind(null,oe.UNIVERSAL);Y.isUniversal=jO;function lm(t){return ll(t)&&t.value&&(t.value.startsWith("::")||t.value.toLowerCase()===":before"||t.value.toLowerCase()===":after"||t.value.toLowerCase()===":first-letter"||t.value.toLowerCase()===":first-line")}function UO(t){return ll(t)&&!lm(t)}function VO(t){return!!(ol(t)&&t.walk)}function WO(t){return am(t)||om(t)}});var fm=k(Qe=>{l();"use strict";Qe.__esModule=!0;var ul=be();Object.keys(ul).forEach(function(t){t==="default"||t==="__esModule"||t in Qe&&Qe[t]===ul[t]||(Qe[t]=ul[t])});var fl=sm();Object.keys(fl).forEach(function(t){t==="default"||t==="__esModule"||t in Qe&&Qe[t]===fl[t]||(Qe[t]=fl[t])});var cl=um();Object.keys(cl).forEach(function(t){t==="default"||t==="__esModule"||t in Qe&&Qe[t]===cl[t]||(Qe[t]=cl[t])})});var rt=k((Ii,pm)=>{l();"use strict";Ii.__esModule=!0;Ii.default=void 0;var GO=QO(nm()),HO=YO(fm());function cm(t){if(typeof WeakMap!="function")return null;var e=new WeakMap,r=new WeakMap;return(cm=function(n){return n?r:e})(t)}function YO(t,e){if(!e&&t&&t.__esModule)return t;if(t===null||typeof t!="object"&&typeof t!="function")return{default:t};var r=cm(e);if(r&&r.has(t))return r.get(t);var i={},n=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in t)if(s!=="default"&&Object.prototype.hasOwnProperty.call(t,s)){var a=n?Object.getOwnPropertyDescriptor(t,s):null;a&&(a.get||a.set)?Object.defineProperty(i,s,a):i[s]=t[s]}return i.default=t,r&&r.set(t,i),i}function QO(t){return t&&t.__esModule?t:{default:t}}var pl=function(e){return new GO.default(e)};Object.assign(pl,HO);delete pl.__esModule;var JO=pl;Ii.default=JO;pm.exports=Ii.default});function mt(t){return["fontSize","outline"].includes(t)?e=>(typeof e=="function"&&(e=e({})),Array.isArray(e)&&(e=e[0]),e):t==="fontFamily"?e=>{typeof e=="function"&&(e=e({}));let r=Array.isArray(e)&&we(e[1])?e[0]:e;return Array.isArray(r)?r.join(", "):r}:["boxShadow","transitionProperty","transitionDuration","transitionDelay","transitionTimingFunction","backgroundImage","backgroundSize","backgroundColor","cursor","animation"].includes(t)?e=>(typeof e=="function"&&(e=e({})),Array.isArray(e)&&(e=e.join(", ")),e):["gridTemplateColumns","gridTemplateRows","objectPosition"].includes(t)?e=>(typeof e=="function"&&(e=e({})),typeof e=="string"&&(e=X.list.comma(e).join(" ")),e):(e,r={})=>(typeof e=="function"&&(e=e(r)),e)}var Di=A(()=>{l();It();tr()});var wm=k((eF,yl)=>{l();var{Rule:dm,AtRule:XO}=qe(),hm=rt();function dl(t,e){let r;try{hm(i=>{r=i}).processSync(t)}catch(i){throw t.includes(":")?e?e.error("Missed semicolon"):i:e?e.error(i.message):i}return r.at(0)}function mm(t,e){let r=!1;return t.each(i=>{if(i.type==="nesting"){let n=e.clone({});i.value!=="&"?i.replaceWith(dl(i.value.replace("&",n.toString()))):i.replaceWith(n),r=!0}else"nodes"in i&&i.nodes&&mm(i,e)&&(r=!0)}),r}function gm(t,e){let r=[];return t.selectors.forEach(i=>{let n=dl(i,t);e.selectors.forEach(s=>{if(!s)return;let a=dl(s,e);mm(a,n)||(a.prepend(hm.combinator({value:" "})),a.prepend(n.clone({}))),r.push(a.toString())})}),r}function ws(t,e){let r=t.prev();for(e.after(t);r&&r.type==="comment";){let i=r.prev();e.after(r),r=i}return t}function KO(t){return function e(r,i,n,s=n){let a=[];if(i.each(o=>{o.type==="rule"&&n?s&&(o.selectors=gm(r,o)):o.type==="atrule"&&o.nodes?t[o.name]?e(r,o,s):i[ml]!==!1&&a.push(o):a.push(o)}),n&&a.length){let o=r.clone({nodes:[]});for(let u of a)o.append(u);i.prepend(o)}}}function hl(t,e,r){let i=new dm({selector:t,nodes:[]});return i.append(e),r.after(i),i}function ym(t,e){let r={};for(let i of t)r[i]=!0;if(e)for(let i of e)r[i.replace(/^@/,"")]=!0;return r}function ZO(t){t=t.trim();let e=t.match(/^\((.*)\)$/);if(!e)return{type:"basic",selector:t};let r=e[1].match(/^(with(?:out)?):(.+)$/);if(r){let i=r[1]==="with",n=Object.fromEntries(r[2].trim().split(/\s+/).map(a=>[a,!0]));if(i&&n.all)return{type:"noop"};let s=a=>!!n[a];return n.all?s=()=>!0:i&&(s=a=>a==="all"?!1:!n[a]),{type:"withrules",escapes:s}}return{type:"unknown"}}function eE(t){let e=[],r=t.parent;for(;r&&r instanceof XO;)e.push(r),r=r.parent;return e}function tE(t){let e=t[vm];if(!e)t.after(t.nodes);else{let r=t.nodes,i,n=-1,s,a,o,u=eE(t);if(u.forEach((c,f)=>{if(e(c.name))i=c,n=f,a=o;else{let p=o;o=c.clone({nodes:[]}),p&&o.append(p),s=s||o}}),i?a?(s.append(r),i.after(a)):i.after(r):t.after(r),t.next()&&i){let c;u.slice(0,n+1).forEach((f,p,h)=>{let m=c;c=f.clone({nodes:[]}),m&&c.append(m);let v=[],b=(h[p-1]||t).next();for(;b;)v.push(b),b=b.next();c.append(v)}),c&&(a||r[r.length-1]).after(c)}}t.remove()}var ml=Symbol("rootRuleMergeSel"),vm=Symbol("rootRuleEscapes");function rE(t){let{params:e}=t,{type:r,selector:i,escapes:n}=ZO(e);if(r==="unknown")throw t.error(`Unknown @${t.name} parameter ${JSON.stringify(e)}`);if(r==="basic"&&i){let s=new dm({selector:i,nodes:t.nodes});t.removeAll(),t.append(s)}t[vm]=n,t[ml]=n?!n("all"):r==="noop"}var gl=Symbol("hasRootRule");yl.exports=(t={})=>{let e=ym(["media","supports","layer","container"],t.bubble),r=KO(e),i=ym(["document","font-face","keyframes","-webkit-keyframes","-moz-keyframes"],t.unwrap),n=(t.rootRuleName||"at-root").replace(/^@/,""),s=t.preserveEmpty;return{postcssPlugin:"postcss-nested",Once(a){a.walkAtRules(n,o=>{rE(o),a[gl]=!0})},Rule(a){let o=!1,u=a,c=!1,f=[];a.each(p=>{p.type==="rule"?(f.length&&(u=hl(a.selector,f,u),f=[]),c=!0,o=!0,p.selectors=gm(a,p),u=ws(p,u)):p.type==="atrule"?(f.length&&(u=hl(a.selector,f,u),f=[]),p.name===n?(o=!0,r(a,p,!0,p[ml]),u=ws(p,u)):e[p.name]?(c=!0,o=!0,r(a,p,!0),u=ws(p,u)):i[p.name]?(c=!0,o=!0,r(a,p,!1),u=ws(p,u)):c&&f.push(p)):p.type==="decl"&&c&&f.push(p)}),f.length&&(u=hl(a.selector,f,u)),o&&s!==!0&&(a.raws.semicolon=!0,a.nodes.length===0&&a.remove())},RootExit(a){a[gl]&&(a.walkAtRules(n,tE),a[gl]=!1)}}};yl.exports.postcss=!0});var Sm=k((tF,km)=>{l();"use strict";var bm=/-(\w|$)/g,xm=(t,e)=>e.toUpperCase(),iE=t=>(t=t.toLowerCase(),t==="float"?"cssFloat":t.startsWith("-ms-")?t.substr(1).replace(bm,xm):t.replace(bm,xm));km.exports=iE});var bl=k((rF,_m)=>{l();var nE=Sm(),sE={boxFlex:!0,boxFlexGroup:!0,columnCount:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,strokeDashoffset:!0,strokeOpacity:!0,strokeWidth:!0};function vl(t){return typeof t.nodes=="undefined"?!0:wl(t)}function wl(t){let e,r={};return t.each(i=>{if(i.type==="atrule")e="@"+i.name,i.params&&(e+=" "+i.params),typeof r[e]=="undefined"?r[e]=vl(i):Array.isArray(r[e])?r[e].push(vl(i)):r[e]=[r[e],vl(i)];else if(i.type==="rule"){let n=wl(i);if(r[i.selector])for(let s in n)r[i.selector][s]=n[s];else r[i.selector]=n}else if(i.type==="decl"){i.prop[0]==="-"&&i.prop[1]==="-"||i.parent&&i.parent.selector===":export"?e=i.prop:e=nE(i.prop);let n=i.value;!isNaN(i.value)&&sE[e]&&(n=parseFloat(i.value)),i.important&&(n+=" !important"),typeof r[e]=="undefined"?r[e]=n:Array.isArray(r[e])?r[e].push(n):r[e]=[r[e],n]}}),r}_m.exports=wl});var bs=k((iF,Am)=>{l();var qi=qe(),Tm=/\s*!important\s*$/i,aE={"box-flex":!0,"box-flex-group":!0,"column-count":!0,flex:!0,"flex-grow":!0,"flex-positive":!0,"flex-shrink":!0,"flex-negative":!0,"font-weight":!0,"line-clamp":!0,"line-height":!0,opacity:!0,order:!0,orphans:!0,"tab-size":!0,widows:!0,"z-index":!0,zoom:!0,"fill-opacity":!0,"stroke-dashoffset":!0,"stroke-opacity":!0,"stroke-width":!0};function oE(t){return t.replace(/([A-Z])/g,"-$1").replace(/^ms-/,"-ms-").toLowerCase()}function Om(t,e,r){r===!1||r===null||(e.startsWith("--")||(e=oE(e)),typeof r=="number"&&(r===0||aE[e]?r=r.toString():r+="px"),e==="css-float"&&(e="float"),Tm.test(r)?(r=r.replace(Tm,""),t.push(qi.decl({prop:e,value:r,important:!0}))):t.push(qi.decl({prop:e,value:r})))}function Em(t,e,r){let i=qi.atRule({name:e[1],params:e[3]||""});typeof r=="object"&&(i.nodes=[],xl(r,i)),t.push(i)}function xl(t,e){let r,i,n;for(r in t)if(i=t[r],!(i===null||typeof i=="undefined"))if(r[0]==="@"){let s=r.match(/@(\S+)(\s+([\W\w]*)\s*)?/);if(Array.isArray(i))for(let a of i)Em(e,s,a);else Em(e,s,i)}else if(Array.isArray(i))for(let s of i)Om(e,r,s);else typeof i=="object"?(n=qi.rule({selector:r}),xl(i,n),e.push(n)):Om(e,r,i)}Am.exports=function(t){let e=qi.root();return xl(t,e),e}});var kl=k((nF,Cm)=>{l();var lE=bl();Cm.exports=function(e){return console&&console.warn&&e.warnings().forEach(r=>{let i=r.plugin||"PostCSS";console.warn(i+": "+r.text)}),lE(e.root)}});var Im=k((sF,Pm)=>{l();var uE=qe(),fE=kl(),cE=bs();Pm.exports=function(e){let r=uE(e);return async i=>{let n=await r.process(i,{parser:cE,from:void 0});return fE(n)}}});var qm=k((aF,Dm)=>{l();var pE=qe(),dE=kl(),hE=bs();Dm.exports=function(t){let e=pE(t);return r=>{let i=e.process(r,{parser:hE,from:void 0});return dE(i)}}});var Lm=k((oF,Rm)=>{l();var mE=bl(),gE=bs(),yE=Im(),vE=qm();Rm.exports={objectify:mE,parse:gE,async:yE,sync:vE}});var dr,Bm,lF,uF,fF,cF,Mm=A(()=>{l();dr=ce(Lm()),Bm=dr.default,lF=dr.default.objectify,uF=dr.default.parse,fF=dr.default.async,cF=dr.default.sync});function hr(t){return Array.isArray(t)?t.flatMap(e=>X([(0,Fm.default)({bubble:["screen"]})]).process(e,{parser:Bm}).root.nodes):hr([t])}var Fm,Sl=A(()=>{l();It();Fm=ce(wm());Mm()});function mr(t,e,r=!1){if(t==="")return e;let i=typeof e=="string"?(0,Nm.default)().astSync(e):e;return i.walkClasses(n=>{let s=n.value,a=r&&s.startsWith("-");n.value=a?`-${t}${s.slice(1)}`:`${t}${s}`}),typeof e=="string"?i.toString():i}var Nm,xs=A(()=>{l();Nm=ce(rt())});function Ce(t){let e=zm.default.className();return e.value=t,jt(e?.raws?.value??e.value)}var zm,gr=A(()=>{l();zm=ce(rt());Cn()});function _l(t){return jt(`.${Ce(t)}`)}function ks(t,e){return _l(Ri(t,e))}function Ri(t,e){return e==="DEFAULT"?t:e==="-"||e==="-DEFAULT"?`-${t}`:e.startsWith("-")?`-${t}${e}`:e.startsWith("/")?`${t}${e}`:`${t}-${e}`}var Tl=A(()=>{l();gr();Cn()});function L(t,e=[[t,[t]]],{filterDefault:r=!1,...i}={}){let n=mt(t);return function({matchUtilities:s,theme:a}){for(let o of e){let u=Array.isArray(o[0])?o:[o];s(u.reduce((c,[f,p])=>Object.assign(c,{[f]:h=>p.reduce((m,v)=>Array.isArray(v)?Object.assign(m,{[v[0]]:v[1]}):Object.assign(m,{[v]:n(h)}),{})}),{}),{...i,values:r?Object.fromEntries(Object.entries(a(t)??{}).filter(([c])=>c!=="DEFAULT")):a(t)})}}}var $m=A(()=>{l();Di()});function Dt(t){return t=Array.isArray(t)?t:[t],t.map(e=>{let r=e.values.map(i=>i.raw!==void 0?i.raw:[i.min&&`(min-width: ${i.min})`,i.max&&`(max-width: ${i.max})`].filter(Boolean).join(" and "));return e.not?`not all and ${r}`:r}).join(", ")}var Ss=A(()=>{l()});function Ol(t){return t.split(TE).map(r=>{let i=r.trim(),n={value:i},s=i.split(OE),a=new Set;for(let o of s)!a.has("DIRECTIONS")&&wE.has(o)?(n.direction=o,a.add("DIRECTIONS")):!a.has("PLAY_STATES")&&bE.has(o)?(n.playState=o,a.add("PLAY_STATES")):!a.has("FILL_MODES")&&xE.has(o)?(n.fillMode=o,a.add("FILL_MODES")):!a.has("ITERATION_COUNTS")&&(kE.has(o)||EE.test(o))?(n.iterationCount=o,a.add("ITERATION_COUNTS")):!a.has("TIMING_FUNCTION")&&SE.has(o)||!a.has("TIMING_FUNCTION")&&_E.some(u=>o.startsWith(`${u}(`))?(n.timingFunction=o,a.add("TIMING_FUNCTION")):!a.has("DURATION")&&jm.test(o)?(n.duration=o,a.add("DURATION")):!a.has("DELAY")&&jm.test(o)?(n.delay=o,a.add("DELAY")):a.has("NAME")?(n.unknown||(n.unknown=[]),n.unknown.push(o)):(n.name=o,a.add("NAME"));return n})}var wE,bE,xE,kE,SE,_E,TE,OE,jm,EE,Um=A(()=>{l();wE=new Set(["normal","reverse","alternate","alternate-reverse"]),bE=new Set(["running","paused"]),xE=new Set(["none","forwards","backwards","both"]),kE=new Set(["infinite"]),SE=new Set(["linear","ease","ease-in","ease-out","ease-in-out","step-start","step-end"]),_E=["cubic-bezier","steps"],TE=/\,(?![^(]*\))/g,OE=/\ +(?![^(]*\))/g,jm=/^(-?[\d.]+m?s)$/,EE=/^(\d+)$/});var Vm,ge,Wm=A(()=>{l();Vm=t=>Object.assign({},...Object.entries(t??{}).flatMap(([e,r])=>typeof r=="object"?Object.entries(Vm(r)).map(([i,n])=>({[e+(i==="DEFAULT"?"":`-${i}`)]:n})):[{[`${e}`]:r}])),ge=Vm});var AE,Al,CE,PE,IE,DE,qE,RE,LE,BE,ME,FE,NE,zE,$E,jE,UE,VE,Cl,El=A(()=>{AE="tailwindcss",Al="3.4.0",CE="A utility-first CSS framework for rapidly building custom user interfaces.",PE="MIT",IE="lib/index.js",DE="types/index.d.ts",qE="https://github.com/tailwindlabs/tailwindcss.git",RE="https://github.com/tailwindlabs/tailwindcss/issues",LE="https://tailwindcss.com",BE={tailwind:"lib/cli.js",tailwindcss:"lib/cli.js"},ME={engine:"stable"},FE={prebuild:"npm run generate && rimraf lib",build:`swc src --out-dir lib --copy-files --config jsc.transform.optimizer.globals.vars.__OXIDE__='"false"'`,postbuild:"esbuild lib/cli-peer-dependencies.js --bundle --platform=node --outfile=peers/index.js --define:process.env.CSS_TRANSFORMER_WASM=false","rebuild-fixtures":"npm run build && node -r @swc/register scripts/rebuildFixtures.js",style:"eslint .",pretest:"npm run generate",test:"jest","test:integrations":"npm run test --prefix ./integrations","install:integrations":"node scripts/install-integrations.js","generate:plugin-list":"node -r @swc/register scripts/create-plugin-list.js","generate:types":"node -r @swc/register scripts/generate-types.js",generate:"npm run generate:plugin-list && npm run generate:types","release-channel":"node ./scripts/release-channel.js","release-notes":"node ./scripts/release-notes.js",prepublishOnly:"npm install --force && npm run build"},NE=["src/*","cli/*","lib/*","peers/*","scripts/*.js","stubs/*","nesting/*","types/**/*","*.d.ts","*.css","*.js"],zE={"@swc/cli":"^0.1.62","@swc/core":"^1.3.55","@swc/jest":"^0.2.26","@swc/register":"^0.1.10",autoprefixer:"^10.4.14",browserslist:"^4.21.5",concurrently:"^8.0.1",cssnano:"^6.0.0",esbuild:"^0.17.18",eslint:"^8.39.0","eslint-config-prettier":"^8.8.0","eslint-plugin-prettier":"^4.2.1",jest:"^29.6.0","jest-diff":"^29.6.0",lightningcss:"1.18.0",prettier:"^2.8.8",rimraf:"^5.0.0","source-map-js":"^1.0.2",turbo:"^1.9.3"},$E={"@alloc/quick-lru":"^5.2.0",arg:"^5.0.2",chokidar:"^3.5.3",didyoumean:"^1.2.2",dlv:"^1.1.3","fast-glob":"^3.3.0","glob-parent":"^6.0.2","is-glob":"^4.0.3",jiti:"^1.19.1",lilconfig:"^2.1.0",micromatch:"^4.0.5","normalize-path":"^3.0.0","object-hash":"^3.0.0",picocolors:"^1.0.0",postcss:"^8.4.23","postcss-import":"^15.1.0","postcss-js":"^4.0.1","postcss-load-config":"^4.0.1","postcss-nested":"^6.0.1","postcss-selector-parser":"^6.0.11",resolve:"^1.22.2",sucrase:"^3.32.0"},jE=["> 1%","not edge <= 18","not ie 11","not op_mini all"],UE={testTimeout:3e4,setupFilesAfterEnv:["<rootDir>/jest/customMatchers.js"],testPathIgnorePatterns:["/node_modules/","/integrations/","/standalone-cli/","\\.test\\.skip\\.js$"],transformIgnorePatterns:["node_modules/(?!lightningcss)"],transform:{"\\.js$":"@swc/jest","\\.ts$":"@swc/jest"}},VE={node:">=14.0.0"},Cl={name:AE,version:Al,description:CE,license:PE,main:IE,types:DE,repository:qE,bugs:RE,homepage:LE,bin:BE,tailwindcss:ME,scripts:FE,files:NE,devDependencies:zE,dependencies:$E,browserslist:jE,jest:UE,engines:VE}});function qt(t,e=!0){return Array.isArray(t)?t.map(r=>{if(e&&Array.isArray(r))throw new Error("The tuple syntax is not supported for `screens`.");if(typeof r=="string")return{name:r.toString(),not:!1,values:[{min:r,max:void 0}]};let[i,n]=r;return i=i.toString(),typeof n=="string"?{name:i,not:!1,values:[{min:n,max:void 0}]}:Array.isArray(n)?{name:i,not:!1,values:n.map(s=>Hm(s))}:{name:i,not:!1,values:[Hm(n)]}}):qt(Object.entries(t??{}),!1)}function _s(t){return t.values.length!==1?{result:!1,reason:"multiple-values"}:t.values[0].raw!==void 0?{result:!1,reason:"raw-values"}:t.values[0].min!==void 0&&t.values[0].max!==void 0?{result:!1,reason:"min-and-max"}:{result:!0,reason:null}}function Gm(t,e,r){let i=Ts(e,t),n=Ts(r,t),s=_s(i),a=_s(n);if(s.reason==="multiple-values"||a.reason==="multiple-values")throw new Error("Attempted to sort a screen with multiple values. This should never happen. Please open a bug report.");if(s.reason==="raw-values"||a.reason==="raw-values")throw new Error("Attempted to sort a screen with raw values. This should never happen. Please open a bug report.");if(s.reason==="min-and-max"||a.reason==="min-and-max")throw new Error("Attempted to sort a screen with both min and max values. This should never happen. Please open a bug report.");let{min:o,max:u}=i.values[0],{min:c,max:f}=n.values[0];e.not&&([o,u]=[u,o]),r.not&&([c,f]=[f,c]),o=o===void 0?o:parseFloat(o),u=u===void 0?u:parseFloat(u),c=c===void 0?c:parseFloat(c),f=f===void 0?f:parseFloat(f);let[p,h]=t==="min"?[o,c]:[f,u];return p-h}function Ts(t,e){return typeof t=="object"?t:{name:"arbitrary-screen",values:[{[e]:t}]}}function Hm({"min-width":t,min:e=t,max:r,raw:i}={}){return{min:e,max:r,raw:i}}var Os=A(()=>{l()});function Es(t,e){t.walkDecls(r=>{if(e.includes(r.prop)){r.remove();return}for(let i of e)r.value.includes(`/ var(${i})`)&&(r.value=r.value.replace(`/ var(${i})`,""))})}var Ym=A(()=>{l()});var xe,Je,it,nt,Qm,Jm=A(()=>{l();ft();Ut();It();$m();Ss();gr();Um();Wm();Gr();Va();tr();Di();El();Ye();Os();Ma();Ym();ct();Qr();Bi();xe={childVariant:({addVariant:t})=>{t("*","& > *")},pseudoElementVariants:({addVariant:t})=>{t("first-letter","&::first-letter"),t("first-line","&::first-line"),t("marker",[({container:e})=>(Es(e,["--tw-text-opacity"]),"& *::marker"),({container:e})=>(Es(e,["--tw-text-opacity"]),"&::marker")]),t("selection",["& *::selection","&::selection"]),t("file","&::file-selector-button"),t("placeholder","&::placeholder"),t("backdrop","&::backdrop"),t("before",({container:e})=>(e.walkRules(r=>{let i=!1;r.walkDecls("content",()=>{i=!0}),i||r.prepend(X.decl({prop:"content",value:"var(--tw-content)"}))}),"&::before")),t("after",({container:e})=>(e.walkRules(r=>{let i=!1;r.walkDecls("content",()=>{i=!0}),i||r.prepend(X.decl({prop:"content",value:"var(--tw-content)"}))}),"&::after"))},pseudoClassVariants:({addVariant:t,matchVariant:e,config:r,prefix:i})=>{let n=[["first","&:first-child"],["last","&:last-child"],["only","&:only-child"],["odd","&:nth-child(odd)"],["even","&:nth-child(even)"],"first-of-type","last-of-type","only-of-type",["visited",({container:a})=>(Es(a,["--tw-text-opacity","--tw-border-opacity","--tw-bg-opacity"]),"&:visited")],"target",["open","&[open]"],"default","checked","indeterminate","placeholder-shown","autofill","optional","required","valid","invalid","in-range","out-of-range","read-only","empty","focus-within",["hover",pe(r(),"hoverOnlyWhenSupported")?"@media (hover: hover) and (pointer: fine) { &:hover }":"&:hover"],"focus","focus-visible","active","enabled","disabled"].map(a=>Array.isArray(a)?a:[a,`&:${a}`]);for(let[a,o]of n)t(a,u=>typeof o=="function"?o(u):o);let s={group:(a,{modifier:o})=>o?[`:merge(${i(".group")}\\/${Ce(o)})`," &"]:[`:merge(${i(".group")})`," &"],peer:(a,{modifier:o})=>o?[`:merge(${i(".peer")}\\/${Ce(o)})`," ~ &"]:[`:merge(${i(".peer")})`," ~ &"]};for(let[a,o]of Object.entries(s))e(a,(u="",c)=>{let f=G(typeof u=="function"?u(c):u);f.includes("&")||(f="&"+f);let[p,h]=o("",c),m=null,v=null,S=0;for(let b=0;b<f.length;++b){let w=f[b];w==="&"?m=b:w==="'"||w==='"'?S+=1:m!==null&&w===" "&&!S&&(v=b)}return m!==null&&v===null&&(v=f.length),f.slice(0,m)+p+f.slice(m+1,v)+h+f.slice(v)},{values:Object.fromEntries(n),[Li]:{respectPrefix:!1}})},directionVariants:({addVariant:t})=>{t("ltr",':is(:where([dir="ltr"]) &)'),t("rtl",':is(:where([dir="rtl"]) &)')},reducedMotionVariants:({addVariant:t})=>{t("motion-safe","@media (prefers-reduced-motion: no-preference)"),t("motion-reduce","@media (prefers-reduced-motion: reduce)")},darkVariants:({config:t,addVariant:e})=>{let[r,i=".dark"]=[].concat(t("darkMode","media"));r===!1&&(r="media",V.warn("darkmode-false",["The `darkMode` option in your Tailwind CSS configuration is set to `false`, which now behaves the same as `media`.","Change `darkMode` to `media` or remove it entirely.","https://tailwindcss.com/docs/upgrade-guide#remove-dark-mode-configuration"])),r==="class"?e("dark",`:is(:where(${i}) &)`):r==="media"&&e("dark","@media (prefers-color-scheme: dark)")},printVariant:({addVariant:t})=>{t("print","@media print")},screenVariants:({theme:t,addVariant:e,matchVariant:r})=>{let i=t("screens")??{},n=Object.values(i).every(w=>typeof w=="string"),s=qt(t("screens")),a=new Set([]);function o(w){return w.match(/(\D+)$/)?.[1]??"(none)"}function u(w){w!==void 0&&a.add(o(w))}function c(w){return u(w),a.size===1}for(let w of s)for(let _ of w.values)u(_.min),u(_.max);let f=a.size<=1;function p(w){return Object.fromEntries(s.filter(_=>_s(_).result).map(_=>{let{min:T,max:O}=_.values[0];if(w==="min"&&T!==void 0)return _;if(w==="min"&&O!==void 0)return{..._,not:!_.not};if(w==="max"&&O!==void 0)return _;if(w==="max"&&T!==void 0)return{..._,not:!_.not}}).map(_=>[_.name,_]))}function h(w){return(_,T)=>Gm(w,_.value,T.value)}let m=h("max"),v=h("min");function S(w){return _=>{if(n)if(f){if(typeof _=="string"&&!c(_))return V.warn("minmax-have-mixed-units",["The `min-*` and `max-*` variants are not supported with a `screens` configuration containing mixed units."]),[]}else return V.warn("mixed-screen-units",["The `min-*` and `max-*` variants are not supported with a `screens` configuration containing mixed units."]),[];else return V.warn("complex-screen-config",["The `min-*` and `max-*` variants are not supported with a `screens` configuration containing objects."]),[];return[`@media ${Dt(Ts(_,w))}`]}}r("max",S("max"),{sort:m,values:n?p("max"):{}});let b="min-screens";for(let w of s)e(w.name,`@media ${Dt(w)}`,{id:b,sort:n&&f?v:void 0,value:w});r("min",S("min"),{id:b,sort:v})},supportsVariants:({matchVariant:t,theme:e})=>{t("supports",(r="")=>{let i=G(r),n=/^\w*\s*\(/.test(i);return i=n?i.replace(/\b(and|or|not)\b/g," $1 "):i,n?`@supports ${i}`:(i.includes(":")||(i=`${i}: var(--tw)`),i.startsWith("(")&&i.endsWith(")")||(i=`(${i})`),`@supports ${i}`)},{values:e("supports")??{}})},hasVariants:({matchVariant:t})=>{t("has",e=>`&:has(${G(e)})`,{values:{}}),t("group-has",(e,{modifier:r})=>r?`:merge(.group\\/${r}):has(${G(e)}) &`:`:merge(.group):has(${G(e)}) &`,{values:{}}),t("peer-has",(e,{modifier:r})=>r?`:merge(.peer\\/${r}):has(${G(e)}) ~ &`:`:merge(.peer):has(${G(e)}) ~ &`,{values:{}})},ariaVariants:({matchVariant:t,theme:e})=>{t("aria",r=>`&[aria-${G(r)}]`,{values:e("aria")??{}}),t("group-aria",(r,{modifier:i})=>i?`:merge(.group\\/${i})[aria-${G(r)}] &`:`:merge(.group)[aria-${G(r)}] &`,{values:e("aria")??{}}),t("peer-aria",(r,{modifier:i})=>i?`:merge(.peer\\/${i})[aria-${G(r)}] ~ &`:`:merge(.peer)[aria-${G(r)}] ~ &`,{values:e("aria")??{}})},dataVariants:({matchVariant:t,theme:e})=>{t("data",r=>`&[data-${G(r)}]`,{values:e("data")??{}}),t("group-data",(r,{modifier:i})=>i?`:merge(.group\\/${i})[data-${G(r)}] &`:`:merge(.group)[data-${G(r)}] &`,{values:e("data")??{}}),t("peer-data",(r,{modifier:i})=>i?`:merge(.peer\\/${i})[data-${G(r)}] ~ &`:`:merge(.peer)[data-${G(r)}] ~ &`,{values:e("data")??{}})},orientationVariants:({addVariant:t})=>{t("portrait","@media (orientation: portrait)"),t("landscape","@media (orientation: landscape)")},prefersContrastVariants:({addVariant:t})=>{t("contrast-more","@media (prefers-contrast: more)"),t("contrast-less","@media (prefers-contrast: less)")},forcedColorsVariants:({addVariant:t})=>{t("forced-colors","@media (forced-colors: active)")}},Je=["translate(var(--tw-translate-x), var(--tw-translate-y))","rotate(var(--tw-rotate))","skewX(var(--tw-skew-x))","skewY(var(--tw-skew-y))","scaleX(var(--tw-scale-x))","scaleY(var(--tw-scale-y))"].join(" "),it=["var(--tw-blur)","var(--tw-brightness)","var(--tw-contrast)","var(--tw-grayscale)","var(--tw-hue-rotate)","var(--tw-invert)","var(--tw-saturate)","var(--tw-sepia)","var(--tw-drop-shadow)"].join(" "),nt=["var(--tw-backdrop-blur)","var(--tw-backdrop-brightness)","var(--tw-backdrop-contrast)","var(--tw-backdrop-grayscale)","var(--tw-backdrop-hue-rotate)","var(--tw-backdrop-invert)","var(--tw-backdrop-opacity)","var(--tw-backdrop-saturate)","var(--tw-backdrop-sepia)"].join(" "),Qm={preflight:({addBase:t})=>{let e=X.parse(`*,::after,::before{box-sizing:border-box;border-width:0;border-style:solid;border-color:theme('borderColor.DEFAULT', currentColor)}::after,::before{--tw-content:''}:host,html{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;font-family:theme('fontFamily.sans', ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:theme('fontFamily.sans[1].fontFeatureSettings', normal);font-variation-settings:theme('fontFamily.sans[1].fontVariationSettings', normal);-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:theme('fontFamily.mono', ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:theme('fontFamily.mono[1].fontFeatureSettings', normal);font-variation-settings:theme('fontFamily.mono[1].fontVariationSettings', normal);font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::placeholder,textarea::placeholder{opacity:1;color:theme('colors.gray.4', #9ca3af)}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]{display:none}`);t([X.comment({text:`! tailwindcss v${Al} | MIT License | https://tailwindcss.com`}),...e.nodes])},container:(()=>{function t(r=[]){return r.flatMap(i=>i.values.map(n=>n.min)).filter(i=>i!==void 0)}function e(r,i,n){if(typeof n=="undefined")return[];if(!(typeof n=="object"&&n!==null))return[{screen:"DEFAULT",minWidth:0,padding:n}];let s=[];n.DEFAULT&&s.push({screen:"DEFAULT",minWidth:0,padding:n.DEFAULT});for(let a of r)for(let o of i)for(let{min:u}of o.values)u===a&&s.push({minWidth:a,padding:n[o.name]});return s}return function({addComponents:r,theme:i}){let n=qt(i("container.screens",i("screens"))),s=t(n),a=e(s,n,i("container.padding")),o=c=>{let f=a.find(p=>p.minWidth===c);return f?{paddingRight:f.padding,paddingLeft:f.padding}:{}},u=Array.from(new Set(s.slice().sort((c,f)=>parseInt(c)-parseInt(f)))).map(c=>({[`@media (min-width: ${c})`]:{".container":{"max-width":c,...o(c)}}}));r([{".container":Object.assign({width:"100%"},i("container.center",!1)?{marginRight:"auto",marginLeft:"auto"}:{},o(0))},...u])}})(),accessibility:({addUtilities:t})=>{t({".sr-only":{position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"},".not-sr-only":{position:"static",width:"auto",height:"auto",padding:"0",margin:"0",overflow:"visible",clip:"auto",whiteSpace:"normal"}})},pointerEvents:({addUtilities:t})=>{t({".pointer-events-none":{"pointer-events":"none"},".pointer-events-auto":{"pointer-events":"auto"}})},visibility:({addUtilities:t})=>{t({".visible":{visibility:"visible"},".invisible":{visibility:"hidden"},".collapse":{visibility:"collapse"}})},position:({addUtilities:t})=>{t({".static":{position:"static"},".fixed":{position:"fixed"},".absolute":{position:"absolute"},".relative":{position:"relative"},".sticky":{position:"sticky"}})},inset:L("inset",[["inset",["inset"]],[["inset-x",["left","right"]],["inset-y",["top","bottom"]]],[["start",["inset-inline-start"]],["end",["inset-inline-end"]],["top",["top"]],["right",["right"]],["bottom",["bottom"]],["left",["left"]]]],{supportsNegativeValues:!0}),isolation:({addUtilities:t})=>{t({".isolate":{isolation:"isolate"},".isolation-auto":{isolation:"auto"}})},zIndex:L("zIndex",[["z",["zIndex"]]],{supportsNegativeValues:!0}),order:L("order",void 0,{supportsNegativeValues:!0}),gridColumn:L("gridColumn",[["col",["gridColumn"]]]),gridColumnStart:L("gridColumnStart",[["col-start",["gridColumnStart"]]]),gridColumnEnd:L("gridColumnEnd",[["col-end",["gridColumnEnd"]]]),gridRow:L("gridRow",[["row",["gridRow"]]]),gridRowStart:L("gridRowStart",[["row-start",["gridRowStart"]]]),gridRowEnd:L("gridRowEnd",[["row-end",["gridRowEnd"]]]),float:({addUtilities:t})=>{t({".float-start":{float:"inline-start"},".float-end":{float:"inline-end"},".float-right":{float:"right"},".float-left":{float:"left"},".float-none":{float:"none"}})},clear:({addUtilities:t})=>{t({".clear-start":{clear:"inline-start"},".clear-end":{clear:"inline-end"},".clear-left":{clear:"left"},".clear-right":{clear:"right"},".clear-both":{clear:"both"},".clear-none":{clear:"none"}})},margin:L("margin",[["m",["margin"]],[["mx",["margin-left","margin-right"]],["my",["margin-top","margin-bottom"]]],[["ms",["margin-inline-start"]],["me",["margin-inline-end"]],["mt",["margin-top"]],["mr",["margin-right"]],["mb",["margin-bottom"]],["ml",["margin-left"]]]],{supportsNegativeValues:!0}),boxSizing:({addUtilities:t})=>{t({".box-border":{"box-sizing":"border-box"},".box-content":{"box-sizing":"content-box"}})},lineClamp:({matchUtilities:t,addUtilities:e,theme:r})=>{t({"line-clamp":i=>({overflow:"hidden",display:"-webkit-box","-webkit-box-orient":"vertical","-webkit-line-clamp":`${i}`})},{values:r("lineClamp")}),e({".line-clamp-none":{overflow:"visible",display:"block","-webkit-box-orient":"horizontal","-webkit-line-clamp":"none"}})},display:({addUtilities:t})=>{t({".block":{display:"block"},".inline-block":{display:"inline-block"},".inline":{display:"inline"},".flex":{display:"flex"},".inline-flex":{display:"inline-flex"},".table":{display:"table"},".inline-table":{display:"inline-table"},".table-caption":{display:"table-caption"},".table-cell":{display:"table-cell"},".table-column":{display:"table-column"},".table-column-group":{display:"table-column-group"},".table-footer-group":{display:"table-footer-group"},".table-header-group":{display:"table-header-group"},".table-row-group":{display:"table-row-group"},".table-row":{display:"table-row"},".flow-root":{display:"flow-root"},".grid":{display:"grid"},".inline-grid":{display:"inline-grid"},".contents":{display:"contents"},".list-item":{display:"list-item"},".hidden":{display:"none"}})},aspectRatio:L("aspectRatio",[["aspect",["aspect-ratio"]]]),size:L("size",[["size",["width","height"]]]),height:L("height",[["h",["height"]]]),maxHeight:L("maxHeight",[["max-h",["maxHeight"]]]),minHeight:L("minHeight",[["min-h",["minHeight"]]]),width:L("width",[["w",["width"]]]),minWidth:L("minWidth",[["min-w",["minWidth"]]]),maxWidth:L("maxWidth",[["max-w",["maxWidth"]]]),flex:L("flex"),flexShrink:L("flexShrink",[["flex-shrink",["flex-shrink"]],["shrink",["flex-shrink"]]]),flexGrow:L("flexGrow",[["flex-grow",["flex-grow"]],["grow",["flex-grow"]]]),flexBasis:L("flexBasis",[["basis",["flex-basis"]]]),tableLayout:({addUtilities:t})=>{t({".table-auto":{"table-layout":"auto"},".table-fixed":{"table-layout":"fixed"}})},captionSide:({addUtilities:t})=>{t({".caption-top":{"caption-side":"top"},".caption-bottom":{"caption-side":"bottom"}})},borderCollapse:({addUtilities:t})=>{t({".border-collapse":{"border-collapse":"collapse"},".border-separate":{"border-collapse":"separate"}})},borderSpacing:({addDefaults:t,matchUtilities:e,theme:r})=>{t("border-spacing",{"--tw-border-spacing-x":0,"--tw-border-spacing-y":0}),e({"border-spacing":i=>({"--tw-border-spacing-x":i,"--tw-border-spacing-y":i,"@defaults border-spacing":{},"border-spacing":"var(--tw-border-spacing-x) var(--tw-border-spacing-y)"}),"border-spacing-x":i=>({"--tw-border-spacing-x":i,"@defaults border-spacing":{},"border-spacing":"var(--tw-border-spacing-x) var(--tw-border-spacing-y)"}),"border-spacing-y":i=>({"--tw-border-spacing-y":i,"@defaults border-spacing":{},"border-spacing":"var(--tw-border-spacing-x) var(--tw-border-spacing-y)"})},{values:r("borderSpacing")})},transformOrigin:L("transformOrigin",[["origin",["transformOrigin"]]]),translate:L("translate",[[["translate-x",[["@defaults transform",{}],"--tw-translate-x",["transform",Je]]],["translate-y",[["@defaults transform",{}],"--tw-translate-y",["transform",Je]]]]],{supportsNegativeValues:!0}),rotate:L("rotate",[["rotate",[["@defaults transform",{}],"--tw-rotate",["transform",Je]]]],{supportsNegativeValues:!0}),skew:L("skew",[[["skew-x",[["@defaults transform",{}],"--tw-skew-x",["transform",Je]]],["skew-y",[["@defaults transform",{}],"--tw-skew-y",["transform",Je]]]]],{supportsNegativeValues:!0}),scale:L("scale",[["scale",[["@defaults transform",{}],"--tw-scale-x","--tw-scale-y",["transform",Je]]],[["scale-x",[["@defaults transform",{}],"--tw-scale-x",["transform",Je]]],["scale-y",[["@defaults transform",{}],"--tw-scale-y",["transform",Je]]]]],{supportsNegativeValues:!0}),transform:({addDefaults:t,addUtilities:e})=>{t("transform",{"--tw-translate-x":"0","--tw-translate-y":"0","--tw-rotate":"0","--tw-skew-x":"0","--tw-skew-y":"0","--tw-scale-x":"1","--tw-scale-y":"1"}),e({".transform":{"@defaults transform":{},transform:Je},".transform-cpu":{transform:Je},".transform-gpu":{transform:Je.replace("translate(var(--tw-translate-x), var(--tw-translate-y))","translate3d(var(--tw-translate-x), var(--tw-translate-y), 0)")},".transform-none":{transform:"none"}})},animation:({matchUtilities:t,theme:e,config:r})=>{let i=s=>Ce(r("prefix")+s),n=Object.fromEntries(Object.entries(e("keyframes")??{}).map(([s,a])=>[s,{[`@keyframes ${i(s)}`]:a}]));t({animate:s=>{let a=Ol(s);return[...a.flatMap(o=>n[o.name]),{animation:a.map(({name:o,value:u})=>o===void 0||n[o]===void 0?u:u.replace(o,i(o))).join(", ")}]}},{values:e("animation")})},cursor:L("cursor"),touchAction:({addDefaults:t,addUtilities:e})=>{t("touch-action",{"--tw-pan-x":" ","--tw-pan-y":" ","--tw-pinch-zoom":" "});let r="var(--tw-pan-x) var(--tw-pan-y) var(--tw-pinch-zoom)";e({".touch-auto":{"touch-action":"auto"},".touch-none":{"touch-action":"none"},".touch-pan-x":{"@defaults touch-action":{},"--tw-pan-x":"pan-x","touch-action":r},".touch-pan-left":{"@defaults touch-action":{},"--tw-pan-x":"pan-left","touch-action":r},".touch-pan-right":{"@defaults touch-action":{},"--tw-pan-x":"pan-right","touch-action":r},".touch-pan-y":{"@defaults touch-action":{},"--tw-pan-y":"pan-y","touch-action":r},".touch-pan-up":{"@defaults touch-action":{},"--tw-pan-y":"pan-up","touch-action":r},".touch-pan-down":{"@defaults touch-action":{},"--tw-pan-y":"pan-down","touch-action":r},".touch-pinch-zoom":{"@defaults touch-action":{},"--tw-pinch-zoom":"pinch-zoom","touch-action":r},".touch-manipulation":{"touch-action":"manipulation"}})},userSelect:({addUtilities:t})=>{t({".select-none":{"user-select":"none"},".select-text":{"user-select":"text"},".select-all":{"user-select":"all"},".select-auto":{"user-select":"auto"}})},resize:({addUtilities:t})=>{t({".resize-none":{resize:"none"},".resize-y":{resize:"vertical"},".resize-x":{resize:"horizontal"},".resize":{resize:"both"}})},scrollSnapType:({addDefaults:t,addUtilities:e})=>{t("scroll-snap-type",{"--tw-scroll-snap-strictness":"proximity"}),e({".snap-none":{"scroll-snap-type":"none"},".snap-x":{"@defaults scroll-snap-type":{},"scroll-snap-type":"x var(--tw-scroll-snap-strictness)"},".snap-y":{"@defaults scroll-snap-type":{},"scroll-snap-type":"y var(--tw-scroll-snap-strictness)"},".snap-both":{"@defaults scroll-snap-type":{},"scroll-snap-type":"both var(--tw-scroll-snap-strictness)"},".snap-mandatory":{"--tw-scroll-snap-strictness":"mandatory"},".snap-proximity":{"--tw-scroll-snap-strictness":"proximity"}})},scrollSnapAlign:({addUtilities:t})=>{t({".snap-start":{"scroll-snap-align":"start"},".snap-end":{"scroll-snap-align":"end"},".snap-center":{"scroll-snap-align":"center"},".snap-align-none":{"scroll-snap-align":"none"}})},scrollSnapStop:({addUtilities:t})=>{t({".snap-normal":{"scroll-snap-stop":"normal"},".snap-always":{"scroll-snap-stop":"always"}})},scrollMargin:L("scrollMargin",[["scroll-m",["scroll-margin"]],[["scroll-mx",["scroll-margin-left","scroll-margin-right"]],["scroll-my",["scroll-margin-top","scroll-margin-bottom"]]],[["scroll-ms",["scroll-margin-inline-start"]],["scroll-me",["scroll-margin-inline-end"]],["scroll-mt",["scroll-margin-top"]],["scroll-mr",["scroll-margin-right"]],["scroll-mb",["scroll-margin-bottom"]],["scroll-ml",["scroll-margin-left"]]]],{supportsNegativeValues:!0}),scrollPadding:L("scrollPadding",[["scroll-p",["scroll-padding"]],[["scroll-px",["scroll-padding-left","scroll-padding-right"]],["scroll-py",["scroll-padding-top","scroll-padding-bottom"]]],[["scroll-ps",["scroll-padding-inline-start"]],["scroll-pe",["scroll-padding-inline-end"]],["scroll-pt",["scroll-padding-top"]],["scroll-pr",["scroll-padding-right"]],["scroll-pb",["scroll-padding-bottom"]],["scroll-pl",["scroll-padding-left"]]]]),listStylePosition:({addUtilities:t})=>{t({".list-inside":{"list-style-position":"inside"},".list-outside":{"list-style-position":"outside"}})},listStyleType:L("listStyleType",[["list",["listStyleType"]]]),listStyleImage:L("listStyleImage",[["list-image",["listStyleImage"]]]),appearance:({addUtilities:t})=>{t({".appearance-none":{appearance:"none"},".appearance-auto":{appearance:"auto"}})},columns:L("columns",[["columns",["columns"]]]),breakBefore:({addUtilities:t})=>{t({".break-before-auto":{"break-before":"auto"},".break-before-avoid":{"break-before":"avoid"},".break-before-all":{"break-before":"all"},".break-before-avoid-page":{"break-before":"avoid-page"},".break-before-page":{"break-before":"page"},".break-before-left":{"break-before":"left"},".break-before-right":{"break-before":"right"},".break-before-column":{"break-before":"column"}})},breakInside:({addUtilities:t})=>{t({".break-inside-auto":{"break-inside":"auto"},".break-inside-avoid":{"break-inside":"avoid"},".break-inside-avoid-page":{"break-inside":"avoid-page"},".break-inside-avoid-column":{"break-inside":"avoid-column"}})},breakAfter:({addUtilities:t})=>{t({".break-after-auto":{"break-after":"auto"},".break-after-avoid":{"break-after":"avoid"},".break-after-all":{"break-after":"all"},".break-after-avoid-page":{"break-after":"avoid-page"},".break-after-page":{"break-after":"page"},".break-after-left":{"break-after":"left"},".break-after-right":{"break-after":"right"},".break-after-column":{"break-after":"column"}})},gridAutoColumns:L("gridAutoColumns",[["auto-cols",["gridAutoColumns"]]]),gridAutoFlow:({addUtilities:t})=>{t({".grid-flow-row":{gridAutoFlow:"row"},".grid-flow-col":{gridAutoFlow:"column"},".grid-flow-dense":{gridAutoFlow:"dense"},".grid-flow-row-dense":{gridAutoFlow:"row dense"},".grid-flow-col-dense":{gridAutoFlow:"column dense"}})},gridAutoRows:L("gridAutoRows",[["auto-rows",["gridAutoRows"]]]),gridTemplateColumns:L("gridTemplateColumns",[["grid-cols",["gridTemplateColumns"]]]),gridTemplateRows:L("gridTemplateRows",[["grid-rows",["gridTemplateRows"]]]),flexDirection:({addUtilities:t})=>{t({".flex-row":{"flex-direction":"row"},".flex-row-reverse":{"flex-direction":"row-reverse"},".flex-col":{"flex-direction":"column"},".flex-col-reverse":{"flex-direction":"column-reverse"}})},flexWrap:({addUtilities:t})=>{t({".flex-wrap":{"flex-wrap":"wrap"},".flex-wrap-reverse":{"flex-wrap":"wrap-reverse"},".flex-nowrap":{"flex-wrap":"nowrap"}})},placeContent:({addUtilities:t})=>{t({".place-content-center":{"place-content":"center"},".place-content-start":{"place-content":"start"},".place-content-end":{"place-content":"end"},".place-content-between":{"place-content":"space-between"},".place-content-around":{"place-content":"space-around"},".place-content-evenly":{"place-content":"space-evenly"},".place-content-baseline":{"place-content":"baseline"},".place-content-stretch":{"place-content":"stretch"}})},placeItems:({addUtilities:t})=>{t({".place-items-start":{"place-items":"start"},".place-items-end":{"place-items":"end"},".place-items-center":{"place-items":"center"},".place-items-baseline":{"place-items":"baseline"},".place-items-stretch":{"place-items":"stretch"}})},alignContent:({addUtilities:t})=>{t({".content-normal":{"align-content":"normal"},".content-center":{"align-content":"center"},".content-start":{"align-content":"flex-start"},".content-end":{"align-content":"flex-end"},".content-between":{"align-content":"space-between"},".content-around":{"align-content":"space-around"},".content-evenly":{"align-content":"space-evenly"},".content-baseline":{"align-content":"baseline"},".content-stretch":{"align-content":"stretch"}})},alignItems:({addUtilities:t})=>{t({".items-start":{"align-items":"flex-start"},".items-end":{"align-items":"flex-end"},".items-center":{"align-items":"center"},".items-baseline":{"align-items":"baseline"},".items-stretch":{"align-items":"stretch"}})},justifyContent:({addUtilities:t})=>{t({".justify-normal":{"justify-content":"normal"},".justify-start":{"justify-content":"flex-start"},".justify-end":{"justify-content":"flex-end"},".justify-center":{"justify-content":"center"},".justify-between":{"justify-content":"space-between"},".justify-around":{"justify-content":"space-around"},".justify-evenly":{"justify-content":"space-evenly"},".justify-stretch":{"justify-content":"stretch"}})},justifyItems:({addUtilities:t})=>{t({".justify-items-start":{"justify-items":"start"},".justify-items-end":{"justify-items":"end"},".justify-items-center":{"justify-items":"center"},".justify-items-stretch":{"justify-items":"stretch"}})},gap:L("gap",[["gap",["gap"]],[["gap-x",["columnGap"]],["gap-y",["rowGap"]]]]),space:({matchUtilities:t,addUtilities:e,theme:r})=>{t({"space-x":i=>(i=i==="0"?"0px":i,{"& > :not([hidden]) ~ :not([hidden])":{"--tw-space-x-reverse":"0","margin-right":`calc(${i} * var(--tw-space-x-reverse))`,"margin-left":`calc(${i} * calc(1 - var(--tw-space-x-reverse)))`}}),"space-y":i=>(i=i==="0"?"0px":i,{"& > :not([hidden]) ~ :not([hidden])":{"--tw-space-y-reverse":"0","margin-top":`calc(${i} * calc(1 - var(--tw-space-y-reverse)))`,"margin-bottom":`calc(${i} * var(--tw-space-y-reverse))`}})},{values:r("space"),supportsNegativeValues:!0}),e({".space-y-reverse > :not([hidden]) ~ :not([hidden])":{"--tw-space-y-reverse":"1"},".space-x-reverse > :not([hidden]) ~ :not([hidden])":{"--tw-space-x-reverse":"1"}})},divideWidth:({matchUtilities:t,addUtilities:e,theme:r})=>{t({"divide-x":i=>(i=i==="0"?"0px":i,{"& > :not([hidden]) ~ :not([hidden])":{"@defaults border-width":{},"--tw-divide-x-reverse":"0","border-right-width":`calc(${i} * var(--tw-divide-x-reverse))`,"border-left-width":`calc(${i} * calc(1 - var(--tw-divide-x-reverse)))`}}),"divide-y":i=>(i=i==="0"?"0px":i,{"& > :not([hidden]) ~ :not([hidden])":{"@defaults border-width":{},"--tw-divide-y-reverse":"0","border-top-width":`calc(${i} * calc(1 - var(--tw-divide-y-reverse)))`,"border-bottom-width":`calc(${i} * var(--tw-divide-y-reverse))`}})},{values:r("divideWidth"),type:["line-width","length","any"]}),e({".divide-y-reverse > :not([hidden]) ~ :not([hidden])":{"@defaults border-width":{},"--tw-divide-y-reverse":"1"},".divide-x-reverse > :not([hidden]) ~ :not([hidden])":{"@defaults border-width":{},"--tw-divide-x-reverse":"1"}})},divideStyle:({addUtilities:t})=>{t({".divide-solid > :not([hidden]) ~ :not([hidden])":{"border-style":"solid"},".divide-dashed > :not([hidden]) ~ :not([hidden])":{"border-style":"dashed"},".divide-dotted > :not([hidden]) ~ :not([hidden])":{"border-style":"dotted"},".divide-double > :not([hidden]) ~ :not([hidden])":{"border-style":"double"},".divide-none > :not([hidden]) ~ :not([hidden])":{"border-style":"none"}})},divideColor:({matchUtilities:t,theme:e,corePlugins:r})=>{t({divide:i=>r("divideOpacity")?{["& > :not([hidden]) ~ :not([hidden])"]:_e({color:i,property:"border-color",variable:"--tw-divide-opacity"})}:{["& > :not([hidden]) ~ :not([hidden])"]:{"border-color":H(i)}}},{values:(({DEFAULT:i,...n})=>n)(ge(e("divideColor"))),type:["color","any"]})},divideOpacity:({matchUtilities:t,theme:e})=>{t({"divide-opacity":r=>({["& > :not([hidden]) ~ :not([hidden])"]:{"--tw-divide-opacity":r}})},{values:e("divideOpacity")})},placeSelf:({addUtilities:t})=>{t({".place-self-auto":{"place-self":"auto"},".place-self-start":{"place-self":"start"},".place-self-end":{"place-self":"end"},".place-self-center":{"place-self":"center"},".place-self-stretch":{"place-self":"stretch"}})},alignSelf:({addUtilities:t})=>{t({".self-auto":{"align-self":"auto"},".self-start":{"align-self":"flex-start"},".self-end":{"align-self":"flex-end"},".self-center":{"align-self":"center"},".self-stretch":{"align-self":"stretch"},".self-baseline":{"align-self":"baseline"}})},justifySelf:({addUtilities:t})=>{t({".justify-self-auto":{"justify-self":"auto"},".justify-self-start":{"justify-self":"start"},".justify-self-end":{"justify-self":"end"},".justify-self-center":{"justify-self":"center"},".justify-self-stretch":{"justify-self":"stretch"}})},overflow:({addUtilities:t})=>{t({".overflow-auto":{overflow:"auto"},".overflow-hidden":{overflow:"hidden"},".overflow-clip":{overflow:"clip"},".overflow-visible":{overflow:"visible"},".overflow-scroll":{overflow:"scroll"},".overflow-x-auto":{"overflow-x":"auto"},".overflow-y-auto":{"overflow-y":"auto"},".overflow-x-hidden":{"overflow-x":"hidden"},".overflow-y-hidden":{"overflow-y":"hidden"},".overflow-x-clip":{"overflow-x":"clip"},".overflow-y-clip":{"overflow-y":"clip"},".overflow-x-visible":{"overflow-x":"visible"},".overflow-y-visible":{"overflow-y":"visible"},".overflow-x-scroll":{"overflow-x":"scroll"},".overflow-y-scroll":{"overflow-y":"scroll"}})},overscrollBehavior:({addUtilities:t})=>{t({".overscroll-auto":{"overscroll-behavior":"auto"},".overscroll-contain":{"overscroll-behavior":"contain"},".overscroll-none":{"overscroll-behavior":"none"},".overscroll-y-auto":{"overscroll-behavior-y":"auto"},".overscroll-y-contain":{"overscroll-behavior-y":"contain"},".overscroll-y-none":{"overscroll-behavior-y":"none"},".overscroll-x-auto":{"overscroll-behavior-x":"auto"},".overscroll-x-contain":{"overscroll-behavior-x":"contain"},".overscroll-x-none":{"overscroll-behavior-x":"none"}})},scrollBehavior:({addUtilities:t})=>{t({".scroll-auto":{"scroll-behavior":"auto"},".scroll-smooth":{"scroll-behavior":"smooth"}})},textOverflow:({addUtilities:t})=>{t({".truncate":{overflow:"hidden","text-overflow":"ellipsis","white-space":"nowrap"},".overflow-ellipsis":{"text-overflow":"ellipsis"},".text-ellipsis":{"text-overflow":"ellipsis"},".text-clip":{"text-overflow":"clip"}})},hyphens:({addUtilities:t})=>{t({".hyphens-none":{hyphens:"none"},".hyphens-manual":{hyphens:"manual"},".hyphens-auto":{hyphens:"auto"}})},whitespace:({addUtilities:t})=>{t({".whitespace-normal":{"white-space":"normal"},".whitespace-nowrap":{"white-space":"nowrap"},".whitespace-pre":{"white-space":"pre"},".whitespace-pre-line":{"white-space":"pre-line"},".whitespace-pre-wrap":{"white-space":"pre-wrap"},".whitespace-break-spaces":{"white-space":"break-spaces"}})},textWrap:({addUtilities:t})=>{t({".text-wrap":{"text-wrap":"wrap"},".text-nowrap":{"text-wrap":"nowrap"},".text-balance":{"text-wrap":"balance"},".text-pretty":{"text-wrap":"pretty"}})},wordBreak:({addUtilities:t})=>{t({".break-normal":{"overflow-wrap":"normal","word-break":"normal"},".break-words":{"overflow-wrap":"break-word"},".break-all":{"word-break":"break-all"},".break-keep":{"word-break":"keep-all"}})},borderRadius:L("borderRadius",[["rounded",["border-radius"]],[["rounded-s",["border-start-start-radius","border-end-start-radius"]],["rounded-e",["border-start-end-radius","border-end-end-radius"]],["rounded-t",["border-top-left-radius","border-top-right-radius"]],["rounded-r",["border-top-right-radius","border-bottom-right-radius"]],["rounded-b",["border-bottom-right-radius","border-bottom-left-radius"]],["rounded-l",["border-top-left-radius","border-bottom-left-radius"]]],[["rounded-ss",["border-start-start-radius"]],["rounded-se",["border-start-end-radius"]],["rounded-ee",["border-end-end-radius"]],["rounded-es",["border-end-start-radius"]],["rounded-tl",["border-top-left-radius"]],["rounded-tr",["border-top-right-radius"]],["rounded-br",["border-bottom-right-radius"]],["rounded-bl",["border-bottom-left-radius"]]]]),borderWidth:L("borderWidth",[["border",[["@defaults border-width",{}],"border-width"]],[["border-x",[["@defaults border-width",{}],"border-left-width","border-right-width"]],["border-y",[["@defaults border-width",{}],"border-top-width","border-bottom-width"]]],[["border-s",[["@defaults border-width",{}],"border-inline-start-width"]],["border-e",[["@defaults border-width",{}],"border-inline-end-width"]],["border-t",[["@defaults border-width",{}],"border-top-width"]],["border-r",[["@defaults border-width",{}],"border-right-width"]],["border-b",[["@defaults border-width",{}],"border-bottom-width"]],["border-l",[["@defaults border-width",{}],"border-left-width"]]]],{type:["line-width","length"]}),borderStyle:({addUtilities:t})=>{t({".border-solid":{"border-style":"solid"},".border-dashed":{"border-style":"dashed"},".border-dotted":{"border-style":"dotted"},".border-double":{"border-style":"double"},".border-hidden":{"border-style":"hidden"},".border-none":{"border-style":"none"}})},borderColor:({matchUtilities:t,theme:e,corePlugins:r})=>{t({border:i=>r("borderOpacity")?_e({color:i,property:"border-color",variable:"--tw-border-opacity"}):{"border-color":H(i)}},{values:(({DEFAULT:i,...n})=>n)(ge(e("borderColor"))),type:["color","any"]}),t({"border-x":i=>r("borderOpacity")?_e({color:i,property:["border-left-color","border-right-color"],variable:"--tw-border-opacity"}):{"border-left-color":H(i),"border-right-color":H(i)},"border-y":i=>r("borderOpacity")?_e({color:i,property:["border-top-color","border-bottom-color"],variable:"--tw-border-opacity"}):{"border-top-color":H(i),"border-bottom-color":H(i)}},{values:(({DEFAULT:i,...n})=>n)(ge(e("borderColor"))),type:["color","any"]}),t({"border-s":i=>r("borderOpacity")?_e({color:i,property:"border-inline-start-color",variable:"--tw-border-opacity"}):{"border-inline-start-color":H(i)},"border-e":i=>r("borderOpacity")?_e({color:i,property:"border-inline-end-color",variable:"--tw-border-opacity"}):{"border-inline-end-color":H(i)},"border-t":i=>r("borderOpacity")?_e({color:i,property:"border-top-color",variable:"--tw-border-opacity"}):{"border-top-color":H(i)},"border-r":i=>r("borderOpacity")?_e({color:i,property:"border-right-color",variable:"--tw-border-opacity"}):{"border-right-color":H(i)},"border-b":i=>r("borderOpacity")?_e({color:i,property:"border-bottom-color",variable:"--tw-border-opacity"}):{"border-bottom-color":H(i)},"border-l":i=>r("borderOpacity")?_e({color:i,property:"border-left-color",variable:"--tw-border-opacity"}):{"border-left-color":H(i)}},{values:(({DEFAULT:i,...n})=>n)(ge(e("borderColor"))),type:["color","any"]})},borderOpacity:L("borderOpacity",[["border-opacity",["--tw-border-opacity"]]]),backgroundColor:({matchUtilities:t,theme:e,corePlugins:r})=>{t({bg:i=>r("backgroundOpacity")?_e({color:i,property:"background-color",variable:"--tw-bg-opacity"}):{"background-color":H(i)}},{values:ge(e("backgroundColor")),type:["color","any"]})},backgroundOpacity:L("backgroundOpacity",[["bg-opacity",["--tw-bg-opacity"]]]),backgroundImage:L("backgroundImage",[["bg",["background-image"]]],{type:["lookup","image","url"]}),gradientColorStops:(()=>{function t(e){return Ze(e,0,"rgb(255 255 255 / 0)")}return function({matchUtilities:e,theme:r,addDefaults:i}){i("gradient-color-stops",{"--tw-gradient-from-position":" ","--tw-gradient-via-position":" ","--tw-gradient-to-position":" "});let n={values:ge(r("gradientColorStops")),type:["color","any"]},s={values:r("gradientColorStopPositions"),type:["length","percentage"]};e({from:a=>{let o=t(a);return{"@defaults gradient-color-stops":{},"--tw-gradient-from":`${H(a)} var(--tw-gradient-from-position)`,"--tw-gradient-to":`${o} var(--tw-gradient-to-position)`,"--tw-gradient-stops":"var(--tw-gradient-from), var(--tw-gradient-to)"}}},n),e({from:a=>({"--tw-gradient-from-position":a})},s),e({via:a=>{let o=t(a);return{"@defaults gradient-color-stops":{},"--tw-gradient-to":`${o} var(--tw-gradient-to-position)`,"--tw-gradient-stops":`var(--tw-gradient-from), ${H(a)} var(--tw-gradient-via-position), var(--tw-gradient-to)`}}},n),e({via:a=>({"--tw-gradient-via-position":a})},s),e({to:a=>({"@defaults gradient-color-stops":{},"--tw-gradient-to":`${H(a)} var(--tw-gradient-to-position)`})},n),e({to:a=>({"--tw-gradient-to-position":a})},s)}})(),boxDecorationBreak:({addUtilities:t})=>{t({".decoration-slice":{"box-decoration-break":"slice"},".decoration-clone":{"box-decoration-break":"clone"},".box-decoration-slice":{"box-decoration-break":"slice"},".box-decoration-clone":{"box-decoration-break":"clone"}})},backgroundSize:L("backgroundSize",[["bg",["background-size"]]],{type:["lookup","length","percentage","size"]}),backgroundAttachment:({addUtilities:t})=>{t({".bg-fixed":{"background-attachment":"fixed"},".bg-local":{"background-attachment":"local"},".bg-scroll":{"background-attachment":"scroll"}})},backgroundClip:({addUtilities:t})=>{t({".bg-clip-border":{"background-clip":"border-box"},".bg-clip-padding":{"background-clip":"padding-box"},".bg-clip-content":{"background-clip":"content-box"},".bg-clip-text":{"background-clip":"text"}})},backgroundPosition:L("backgroundPosition",[["bg",["background-position"]]],{type:["lookup",["position",{preferOnConflict:!0}]]}),backgroundRepeat:({addUtilities:t})=>{t({".bg-repeat":{"background-repeat":"repeat"},".bg-no-repeat":{"background-repeat":"no-repeat"},".bg-repeat-x":{"background-repeat":"repeat-x"},".bg-repeat-y":{"background-repeat":"repeat-y"},".bg-repeat-round":{"background-repeat":"round"},".bg-repeat-space":{"background-repeat":"space"}})},backgroundOrigin:({addUtilities:t})=>{t({".bg-origin-border":{"background-origin":"border-box"},".bg-origin-padding":{"background-origin":"padding-box"},".bg-origin-content":{"background-origin":"content-box"}})},fill:({matchUtilities:t,theme:e})=>{t({fill:r=>({fill:H(r)})},{values:ge(e("fill")),type:["color","any"]})},stroke:({matchUtilities:t,theme:e})=>{t({stroke:r=>({stroke:H(r)})},{values:ge(e("stroke")),type:["color","url","any"]})},strokeWidth:L("strokeWidth",[["stroke",["stroke-width"]]],{type:["length","number","percentage"]}),objectFit:({addUtilities:t})=>{t({".object-contain":{"object-fit":"contain"},".object-cover":{"object-fit":"cover"},".object-fill":{"object-fit":"fill"},".object-none":{"object-fit":"none"},".object-scale-down":{"object-fit":"scale-down"}})},objectPosition:L("objectPosition",[["object",["object-position"]]]),padding:L("padding",[["p",["padding"]],[["px",["padding-left","padding-right"]],["py",["padding-top","padding-bottom"]]],[["ps",["padding-inline-start"]],["pe",["padding-inline-end"]],["pt",["padding-top"]],["pr",["padding-right"]],["pb",["padding-bottom"]],["pl",["padding-left"]]]]),textAlign:({addUtilities:t})=>{t({".text-left":{"text-align":"left"},".text-center":{"text-align":"center"},".text-right":{"text-align":"right"},".text-justify":{"text-align":"justify"},".text-start":{"text-align":"start"},".text-end":{"text-align":"end"}})},textIndent:L("textIndent",[["indent",["text-indent"]]],{supportsNegativeValues:!0}),verticalAlign:({addUtilities:t,matchUtilities:e})=>{t({".align-baseline":{"vertical-align":"baseline"},".align-top":{"vertical-align":"top"},".align-middle":{"vertical-align":"middle"},".align-bottom":{"vertical-align":"bottom"},".align-text-top":{"vertical-align":"text-top"},".align-text-bottom":{"vertical-align":"text-bottom"},".align-sub":{"vertical-align":"sub"},".align-super":{"vertical-align":"super"}}),e({align:r=>({"vertical-align":r})})},fontFamily:({matchUtilities:t,theme:e})=>{t({font:r=>{let[i,n={}]=Array.isArray(r)&&we(r[1])?r:[r],{fontFeatureSettings:s,fontVariationSettings:a}=n;return{"font-family":Array.isArray(i)?i.join(", "):i,...s===void 0?{}:{"font-feature-settings":s},...a===void 0?{}:{"font-variation-settings":a}}}},{values:e("fontFamily"),type:["lookup","generic-name","family-name"]})},fontSize:({matchUtilities:t,theme:e})=>{t({text:(r,{modifier:i})=>{let[n,s]=Array.isArray(r)?r:[r];if(i)return{"font-size":n,"line-height":i};let{lineHeight:a,letterSpacing:o,fontWeight:u}=we(s)?s:{lineHeight:s};return{"font-size":n,...a===void 0?{}:{"line-height":a},...o===void 0?{}:{"letter-spacing":o},...u===void 0?{}:{"font-weight":u}}}},{values:e("fontSize"),modifiers:e("lineHeight"),type:["absolute-size","relative-size","length","percentage"]})},fontWeight:L("fontWeight",[["font",["fontWeight"]]],{type:["lookup","number","any"]}),textTransform:({addUtilities:t})=>{t({".uppercase":{"text-transform":"uppercase"},".lowercase":{"text-transform":"lowercase"},".capitalize":{"text-transform":"capitalize"},".normal-case":{"text-transform":"none"}})},fontStyle:({addUtilities:t})=>{t({".italic":{"font-style":"italic"},".not-italic":{"font-style":"normal"}})},fontVariantNumeric:({addDefaults:t,addUtilities:e})=>{let r="var(--tw-ordinal) var(--tw-slashed-zero) var(--tw-numeric-figure) var(--tw-numeric-spacing) var(--tw-numeric-fraction)";t("font-variant-numeric",{"--tw-ordinal":" ","--tw-slashed-zero":" ","--tw-numeric-figure":" ","--tw-numeric-spacing":" ","--tw-numeric-fraction":" "}),e({".normal-nums":{"font-variant-numeric":"normal"},".ordinal":{"@defaults font-variant-numeric":{},"--tw-ordinal":"ordinal","font-variant-numeric":r},".slashed-zero":{"@defaults font-variant-numeric":{},"--tw-slashed-zero":"slashed-zero","font-variant-numeric":r},".lining-nums":{"@defaults font-variant-numeric":{},"--tw-numeric-figure":"lining-nums","font-variant-numeric":r},".oldstyle-nums":{"@defaults font-variant-numeric":{},"--tw-numeric-figure":"oldstyle-nums","font-variant-numeric":r},".proportional-nums":{"@defaults font-variant-numeric":{},"--tw-numeric-spacing":"proportional-nums","font-variant-numeric":r},".tabular-nums":{"@defaults font-variant-numeric":{},"--tw-numeric-spacing":"tabular-nums","font-variant-numeric":r},".diagonal-fractions":{"@defaults font-variant-numeric":{},"--tw-numeric-fraction":"diagonal-fractions","font-variant-numeric":r},".stacked-fractions":{"@defaults font-variant-numeric":{},"--tw-numeric-fraction":"stacked-fractions","font-variant-numeric":r}})},lineHeight:L("lineHeight",[["leading",["lineHeight"]]]),letterSpacing:L("letterSpacing",[["tracking",["letterSpacing"]]],{supportsNegativeValues:!0}),textColor:({matchUtilities:t,theme:e,corePlugins:r})=>{t({text:i=>r("textOpacity")?_e({color:i,property:"color",variable:"--tw-text-opacity"}):{color:H(i)}},{values:ge(e("textColor")),type:["color","any"]})},textOpacity:L("textOpacity",[["text-opacity",["--tw-text-opacity"]]]),textDecoration:({addUtilities:t})=>{t({".underline":{"text-decoration-line":"underline"},".overline":{"text-decoration-line":"overline"},".line-through":{"text-decoration-line":"line-through"},".no-underline":{"text-decoration-line":"none"}})},textDecorationColor:({matchUtilities:t,theme:e})=>{t({decoration:r=>({"text-decoration-color":H(r)})},{values:ge(e("textDecorationColor")),type:["color","any"]})},textDecorationStyle:({addUtilities:t})=>{t({".decoration-solid":{"text-decoration-style":"solid"},".decoration-double":{"text-decoration-style":"double"},".decoration-dotted":{"text-decoration-style":"dotted"},".decoration-dashed":{"text-decoration-style":"dashed"},".decoration-wavy":{"text-decoration-style":"wavy"}})},textDecorationThickness:L("textDecorationThickness",[["decoration",["text-decoration-thickness"]]],{type:["length","percentage"]}),textUnderlineOffset:L("textUnderlineOffset",[["underline-offset",["text-underline-offset"]]],{type:["length","percentage","any"]}),fontSmoothing:({addUtilities:t})=>{t({".antialiased":{"-webkit-font-smoothing":"antialiased","-moz-osx-font-smoothing":"grayscale"},".subpixel-antialiased":{"-webkit-font-smoothing":"auto","-moz-osx-font-smoothing":"auto"}})},placeholderColor:({matchUtilities:t,theme:e,corePlugins:r})=>{t({placeholder:i=>r("placeholderOpacity")?{"&::placeholder":_e({color:i,property:"color",variable:"--tw-placeholder-opacity"})}:{"&::placeholder":{color:H(i)}}},{values:ge(e("placeholderColor")),type:["color","any"]})},placeholderOpacity:({matchUtilities:t,theme:e})=>{t({"placeholder-opacity":r=>({["&::placeholder"]:{"--tw-placeholder-opacity":r}})},{values:e("placeholderOpacity")})},caretColor:({matchUtilities:t,theme:e})=>{t({caret:r=>({"caret-color":H(r)})},{values:ge(e("caretColor")),type:["color","any"]})},accentColor:({matchUtilities:t,theme:e})=>{t({accent:r=>({"accent-color":H(r)})},{values:ge(e("accentColor")),type:["color","any"]})},opacity:L("opacity",[["opacity",["opacity"]]]),backgroundBlendMode:({addUtilities:t})=>{t({".bg-blend-normal":{"background-blend-mode":"normal"},".bg-blend-multiply":{"background-blend-mode":"multiply"},".bg-blend-screen":{"background-blend-mode":"screen"},".bg-blend-overlay":{"background-blend-mode":"overlay"},".bg-blend-darken":{"background-blend-mode":"darken"},".bg-blend-lighten":{"background-blend-mode":"lighten"},".bg-blend-color-dodge":{"background-blend-mode":"color-dodge"},".bg-blend-color-burn":{"background-blend-mode":"color-burn"},".bg-blend-hard-light":{"background-blend-mode":"hard-light"},".bg-blend-soft-light":{"background-blend-mode":"soft-light"},".bg-blend-difference":{"background-blend-mode":"difference"},".bg-blend-exclusion":{"background-blend-mode":"exclusion"},".bg-blend-hue":{"background-blend-mode":"hue"},".bg-blend-saturation":{"background-blend-mode":"saturation"},".bg-blend-color":{"background-blend-mode":"color"},".bg-blend-luminosity":{"background-blend-mode":"luminosity"}})},mixBlendMode:({addUtilities:t})=>{t({".mix-blend-normal":{"mix-blend-mode":"normal"},".mix-blend-multiply":{"mix-blend-mode":"multiply"},".mix-blend-screen":{"mix-blend-mode":"screen"},".mix-blend-overlay":{"mix-blend-mode":"overlay"},".mix-blend-darken":{"mix-blend-mode":"darken"},".mix-blend-lighten":{"mix-blend-mode":"lighten"},".mix-blend-color-dodge":{"mix-blend-mode":"color-dodge"},".mix-blend-color-burn":{"mix-blend-mode":"color-burn"},".mix-blend-hard-light":{"mix-blend-mode":"hard-light"},".mix-blend-soft-light":{"mix-blend-mode":"soft-light"},".mix-blend-difference":{"mix-blend-mode":"difference"},".mix-blend-exclusion":{"mix-blend-mode":"exclusion"},".mix-blend-hue":{"mix-blend-mode":"hue"},".mix-blend-saturation":{"mix-blend-mode":"saturation"},".mix-blend-color":{"mix-blend-mode":"color"},".mix-blend-luminosity":{"mix-blend-mode":"luminosity"},".mix-blend-plus-lighter":{"mix-blend-mode":"plus-lighter"}})},boxShadow:(()=>{let t=mt("boxShadow"),e=["var(--tw-ring-offset-shadow, 0 0 #0000)","var(--tw-ring-shadow, 0 0 #0000)","var(--tw-shadow)"].join(", ");return function({matchUtilities:r,addDefaults:i,theme:n}){i(" box-shadow",{"--tw-ring-offset-shadow":"0 0 #0000","--tw-ring-shadow":"0 0 #0000","--tw-shadow":"0 0 #0000","--tw-shadow-colored":"0 0 #0000"}),r({shadow:s=>{s=t(s);let a=In(s);for(let o of a)!o.valid||(o.color="var(--tw-shadow-color)");return{"@defaults box-shadow":{},"--tw-shadow":s==="none"?"0 0 #0000":s,"--tw-shadow-colored":s==="none"?"0 0 #0000":hp(a),"box-shadow":e}}},{values:n("boxShadow"),type:["shadow"]})}})(),boxShadowColor:({matchUtilities:t,theme:e})=>{t({shadow:r=>({"--tw-shadow-color":H(r),"--tw-shadow":"var(--tw-shadow-colored)"})},{values:ge(e("boxShadowColor")),type:["color","any"]})},outlineStyle:({addUtilities:t})=>{t({".outline-none":{outline:"2px solid transparent","outline-offset":"2px"},".outline":{"outline-style":"solid"},".outline-dashed":{"outline-style":"dashed"},".outline-dotted":{"outline-style":"dotted"},".outline-double":{"outline-style":"double"}})},outlineWidth:L("outlineWidth",[["outline",["outline-width"]]],{type:["length","number","percentage"]}),outlineOffset:L("outlineOffset",[["outline-offset",["outline-offset"]]],{type:["length","number","percentage","any"],supportsNegativeValues:!0}),outlineColor:({matchUtilities:t,theme:e})=>{t({outline:r=>({"outline-color":H(r)})},{values:ge(e("outlineColor")),type:["color","any"]})},ringWidth:({matchUtilities:t,addDefaults:e,addUtilities:r,theme:i,config:n})=>{let s=(()=>{if(pe(n(),"respectDefaultRingColorOpacity"))return i("ringColor.DEFAULT");let a=i("ringOpacity.DEFAULT","0.5");return i("ringColor")?.DEFAULT?Ze(i("ringColor")?.DEFAULT,a,`rgb(147 197 253 / ${a})`):`rgb(147 197 253 / ${a})`})();e("ring-width",{"--tw-ring-inset":" ","--tw-ring-offset-width":i("ringOffsetWidth.DEFAULT","0px"),"--tw-ring-offset-color":i("ringOffsetColor.DEFAULT","#fff"),"--tw-ring-color":s,"--tw-ring-offset-shadow":"0 0 #0000","--tw-ring-shadow":"0 0 #0000","--tw-shadow":"0 0 #0000","--tw-shadow-colored":"0 0 #0000"}),t({ring:a=>({"@defaults ring-width":{},"--tw-ring-offset-shadow":"var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)","--tw-ring-shadow":`var(--tw-ring-inset) 0 0 0 calc(${a} + var(--tw-ring-offset-width)) var(--tw-ring-color)`,"box-shadow":["var(--tw-ring-offset-shadow)","var(--tw-ring-shadow)","var(--tw-shadow, 0 0 #0000)"].join(", ")})},{values:i("ringWidth"),type:"length"}),r({".ring-inset":{"@defaults ring-width":{},"--tw-ring-inset":"inset"}})},ringColor:({matchUtilities:t,theme:e,corePlugins:r})=>{t({ring:i=>r("ringOpacity")?_e({color:i,property:"--tw-ring-color",variable:"--tw-ring-opacity"}):{"--tw-ring-color":H(i)}},{values:Object.fromEntries(Object.entries(ge(e("ringColor"))).filter(([i])=>i!=="DEFAULT")),type:["color","any"]})},ringOpacity:t=>{let{config:e}=t;return L("ringOpacity",[["ring-opacity",["--tw-ring-opacity"]]],{filterDefault:!pe(e(),"respectDefaultRingColorOpacity")})(t)},ringOffsetWidth:L("ringOffsetWidth",[["ring-offset",["--tw-ring-offset-width"]]],{type:"length"}),ringOffsetColor:({matchUtilities:t,theme:e})=>{t({"ring-offset":r=>({"--tw-ring-offset-color":H(r)})},{values:ge(e("ringOffsetColor")),type:["color","any"]})},blur:({matchUtilities:t,theme:e})=>{t({blur:r=>({"--tw-blur":`blur(${r})`,"@defaults filter":{},filter:it})},{values:e("blur")})},brightness:({matchUtilities:t,theme:e})=>{t({brightness:r=>({"--tw-brightness":`brightness(${r})`,"@defaults filter":{},filter:it})},{values:e("brightness")})},contrast:({matchUtilities:t,theme:e})=>{t({contrast:r=>({"--tw-contrast":`contrast(${r})`,"@defaults filter":{},filter:it})},{values:e("contrast")})},dropShadow:({matchUtilities:t,theme:e})=>{t({"drop-shadow":r=>({"--tw-drop-shadow":Array.isArray(r)?r.map(i=>`drop-shadow(${i})`).join(" "):`drop-shadow(${r})`,"@defaults filter":{},filter:it})},{values:e("dropShadow")})},grayscale:({matchUtilities:t,theme:e})=>{t({grayscale:r=>({"--tw-grayscale":`grayscale(${r})`,"@defaults filter":{},filter:it})},{values:e("grayscale")})},hueRotate:({matchUtilities:t,theme:e})=>{t({"hue-rotate":r=>({"--tw-hue-rotate":`hue-rotate(${r})`,"@defaults filter":{},filter:it})},{values:e("hueRotate"),supportsNegativeValues:!0})},invert:({matchUtilities:t,theme:e})=>{t({invert:r=>({"--tw-invert":`invert(${r})`,"@defaults filter":{},filter:it})},{values:e("invert")})},saturate:({matchUtilities:t,theme:e})=>{t({saturate:r=>({"--tw-saturate":`saturate(${r})`,"@defaults filter":{},filter:it})},{values:e("saturate")})},sepia:({matchUtilities:t,theme:e})=>{t({sepia:r=>({"--tw-sepia":`sepia(${r})`,"@defaults filter":{},filter:it})},{values:e("sepia")})},filter:({addDefaults:t,addUtilities:e})=>{t("filter",{"--tw-blur":" ","--tw-brightness":" ","--tw-contrast":" ","--tw-grayscale":" ","--tw-hue-rotate":" ","--tw-invert":" ","--tw-saturate":" ","--tw-sepia":" ","--tw-drop-shadow":" "}),e({".filter":{"@defaults filter":{},filter:it},".filter-none":{filter:"none"}})},backdropBlur:({matchUtilities:t,theme:e})=>{t({"backdrop-blur":r=>({"--tw-backdrop-blur":`blur(${r})`,"@defaults backdrop-filter":{},"backdrop-filter":nt})},{values:e("backdropBlur")})},backdropBrightness:({matchUtilities:t,theme:e})=>{t({"backdrop-brightness":r=>({"--tw-backdrop-brightness":`brightness(${r})`,"@defaults backdrop-filter":{},"backdrop-filter":nt})},{values:e("backdropBrightness")})},backdropContrast:({matchUtilities:t,theme:e})=>{t({"backdrop-contrast":r=>({"--tw-backdrop-contrast":`contrast(${r})`,"@defaults backdrop-filter":{},"backdrop-filter":nt})},{values:e("backdropContrast")})},backdropGrayscale:({matchUtilities:t,theme:e})=>{t({"backdrop-grayscale":r=>({"--tw-backdrop-grayscale":`grayscale(${r})`,"@defaults backdrop-filter":{},"backdrop-filter":nt})},{values:e("backdropGrayscale")})},backdropHueRotate:({matchUtilities:t,theme:e})=>{t({"backdrop-hue-rotate":r=>({"--tw-backdrop-hue-rotate":`hue-rotate(${r})`,"@defaults backdrop-filter":{},"backdrop-filter":nt})},{values:e("backdropHueRotate"),supportsNegativeValues:!0})},backdropInvert:({matchUtilities:t,theme:e})=>{t({"backdrop-invert":r=>({"--tw-backdrop-invert":`invert(${r})`,"@defaults backdrop-filter":{},"backdrop-filter":nt})},{values:e("backdropInvert")})},backdropOpacity:({matchUtilities:t,theme:e})=>{t({"backdrop-opacity":r=>({"--tw-backdrop-opacity":`opacity(${r})`,"@defaults backdrop-filter":{},"backdrop-filter":nt})},{values:e("backdropOpacity")})},backdropSaturate:({matchUtilities:t,theme:e})=>{t({"backdrop-saturate":r=>({"--tw-backdrop-saturate":`saturate(${r})`,"@defaults backdrop-filter":{},"backdrop-filter":nt})},{values:e("backdropSaturate")})},backdropSepia:({matchUtilities:t,theme:e})=>{t({"backdrop-sepia":r=>({"--tw-backdrop-sepia":`sepia(${r})`,"@defaults backdrop-filter":{},"backdrop-filter":nt})},{values:e("backdropSepia")})},backdropFilter:({addDefaults:t,addUtilities:e})=>{t("backdrop-filter",{"--tw-backdrop-blur":" ","--tw-backdrop-brightness":" ","--tw-backdrop-contrast":" ","--tw-backdrop-grayscale":" ","--tw-backdrop-hue-rotate":" ","--tw-backdrop-invert":" ","--tw-backdrop-opacity":" ","--tw-backdrop-saturate":" ","--tw-backdrop-sepia":" "}),e({".backdrop-filter":{"@defaults backdrop-filter":{},"backdrop-filter":nt},".backdrop-filter-none":{"backdrop-filter":"none"}})},transitionProperty:({matchUtilities:t,theme:e})=>{let r=e("transitionTimingFunction.DEFAULT"),i=e("transitionDuration.DEFAULT");t({transition:n=>({"transition-property":n,...n==="none"?{}:{"transition-timing-function":r,"transition-duration":i}})},{values:e("transitionProperty")})},transitionDelay:L("transitionDelay",[["delay",["transitionDelay"]]]),transitionDuration:L("transitionDuration",[["duration",["transitionDuration"]]],{filterDefault:!0}),transitionTimingFunction:L("transitionTimingFunction",[["ease",["transitionTimingFunction"]]],{filterDefault:!0}),willChange:L("willChange",[["will-change",["will-change"]]]),content:L("content",[["content",["--tw-content",["content","var(--tw-content)"]]]]),forcedColorAdjust:({addUtilities:t})=>{t({".forced-color-adjust-auto":{"forced-color-adjust":"auto"},".forced-color-adjust-none":{"forced-color-adjust":"none"}})}}});function WE(t){if(t===void 0)return!1;if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;if(t==="*")return!0;let e=t.split(",").map(r=>r.split(":")[0]);return e.includes("-tailwindcss")?!1:!!e.includes("tailwindcss")}var Xe,Xm,Km,As,Pl,gt,Mi,Rt=A(()=>{l();El();Xe=typeof g!="undefined"?{NODE_ENV:"production",DEBUG:WE(g.env.DEBUG),ENGINE:Cl.tailwindcss.engine}:{NODE_ENV:"production",DEBUG:!1,ENGINE:Cl.tailwindcss.engine},Xm=new Map,Km=new Map,As=new Map,Pl=new Map,gt=new String("*"),Mi=Symbol("__NONE__")});function yr(t){let e=[],r=!1;for(let i=0;i<t.length;i++){let n=t[i];if(n===":"&&!r&&e.length===0)return!1;if(GE.has(n)&&t[i-1]!=="\\"&&(r=!r),!r&&t[i-1]!=="\\"){if(Zm.has(n))e.push(n);else if(eg.has(n)){let s=eg.get(n);if(e.length<=0||e.pop()!==s)return!1}}}return!(e.length>0)}var Zm,eg,GE,Il=A(()=>{l();Zm=new Map([["{","}"],["[","]"],["(",")"]]),eg=new Map(Array.from(Zm.entries()).map(([t,e])=>[e,t])),GE=new Set(['"',"'","`"])});function vr(t){let[e]=tg(t);return e.forEach(([r,i])=>r.removeChild(i)),t.nodes.push(...e.map(([,r])=>r)),t}function tg(t){let e=[],r=null;for(let i of t.nodes)if(i.type==="combinator")e=e.filter(([,n])=>ql(n).includes("jumpable")),r=null;else if(i.type==="pseudo"){HE(i)?(r=i,e.push([t,i,null])):r&&YE(i,r)?e.push([t,i,r]):r=null;for(let n of i.nodes??[]){let[s,a]=tg(n);r=a||r,e.push(...s)}}return[e,r]}function rg(t){return t.value.startsWith("::")||Dl[t.value]!==void 0}function HE(t){return rg(t)&&ql(t).includes("terminal")}function YE(t,e){return t.type!=="pseudo"||rg(t)?!1:ql(e).includes("actionable")}function ql(t){return Dl[t.value]??Dl.__default__}var Dl,Cs=A(()=>{l();Dl={"::after":["terminal","jumpable"],"::backdrop":["terminal","jumpable"],"::before":["terminal","jumpable"],"::cue":["terminal"],"::cue-region":["terminal"],"::first-letter":["terminal","jumpable"],"::first-line":["terminal","jumpable"],"::grammar-error":["terminal"],"::marker":["terminal","jumpable"],"::part":["terminal","actionable"],"::placeholder":["terminal","jumpable"],"::selection":["terminal","jumpable"],"::slotted":["terminal"],"::spelling-error":["terminal"],"::target-text":["terminal"],"::file-selector-button":["terminal","actionable"],"::deep":["actionable"],"::v-deep":["actionable"],"::ng-deep":["actionable"],":after":["terminal","jumpable"],":before":["terminal","jumpable"],":first-letter":["terminal","jumpable"],":first-line":["terminal","jumpable"],__default__:["terminal","actionable"]}});function wr(t,{context:e,candidate:r}){let i=e?.tailwindConfig.prefix??"",n=t.map(a=>{let o=(0,st.default)().astSync(a.format);return{...a,ast:a.respectPrefix?mr(i,o):o}}),s=st.default.root({nodes:[st.default.selector({nodes:[st.default.className({value:Ce(r)})]})]});for(let{ast:a}of n)[s,a]=JE(s,a),a.walkNesting(o=>o.replaceWith(...s.nodes[0].nodes)),s=a;return s}function ng(t){let e=[];for(;t.prev()&&t.prev().type!=="combinator";)t=t.prev();for(;t&&t.type!=="combinator";)e.push(t),t=t.next();return e}function QE(t){return t.sort((e,r)=>e.type==="tag"&&r.type==="class"?-1:e.type==="class"&&r.type==="tag"?1:e.type==="class"&&r.type==="pseudo"&&r.value.startsWith("::")?-1:e.type==="pseudo"&&e.value.startsWith("::")&&r.type==="class"?1:t.index(e)-t.index(r)),t}function Ll(t,e){let r=!1;t.walk(i=>{if(i.type==="class"&&i.value===e)return r=!0,!1}),r||t.remove()}function Ps(t,e,{context:r,candidate:i,base:n}){let s=r?.tailwindConfig?.separator??":";n=n??Te(i,s).pop();let a=(0,st.default)().astSync(t);if(a.walkClasses(f=>{f.raws&&f.value.includes(n)&&(f.raws.value=Ce((0,ig.default)(f.raws.value)))}),a.each(f=>Ll(f,n)),a.length===0)return null;let o=Array.isArray(e)?wr(e,{context:r,candidate:i}):e;if(o===null)return a.toString();let u=st.default.comment({value:"/*__simple__*/"}),c=st.default.comment({value:"/*__simple__*/"});return a.walkClasses(f=>{if(f.value!==n)return;let p=f.parent,h=o.nodes[0].nodes;if(p.nodes.length===1){f.replaceWith(...h);return}let m=ng(f);p.insertBefore(m[0],u),p.insertAfter(m[m.length-1],c);for(let S of h)p.insertBefore(m[0],S.clone());f.remove(),m=ng(u);let v=p.index(u);p.nodes.splice(v,m.length,...QE(st.default.selector({nodes:m})).nodes),u.remove(),c.remove()}),a.walkPseudos(f=>{f.value===Rl&&f.replaceWith(f.nodes)}),a.each(f=>vr(f)),a.toString()}function JE(t,e){let r=[];return t.walkPseudos(i=>{i.value===Rl&&r.push({pseudo:i,value:i.nodes[0].toString()})}),e.walkPseudos(i=>{if(i.value!==Rl)return;let n=i.nodes[0].toString(),s=r.find(c=>c.value===n);if(!s)return;let a=[],o=i.next();for(;o&&o.type!=="combinator";)a.push(o),o=o.next();let u=o;s.pseudo.parent.insertAfter(s.pseudo,st.default.selector({nodes:a.map(c=>c.clone())})),i.remove(),a.forEach(c=>c.remove()),u&&u.type==="combinator"&&u.remove()}),[t,e]}var st,ig,Rl,Bl=A(()=>{l();st=ce(rt()),ig=ce(ls());gr();xs();Cs();rr();Rl=":merge"});function Is(t,e){let r=(0,Ml.default)().astSync(t);return r.each(i=>{i.nodes[0].type==="pseudo"&&i.nodes[0].value===":is"&&i.nodes.every(s=>s.type!=="combinator")||(i.nodes=[Ml.default.pseudo({value:":is",nodes:[i.clone()]})]),vr(i)}),`${e} ${r.toString()}`}var Ml,Fl=A(()=>{l();Ml=ce(rt());Cs()});function Nl(t){return XE.transformSync(t)}function*KE(t){let e=1/0;for(;e>=0;){let r,i=!1;if(e===1/0&&t.endsWith("]")){let a=t.indexOf("[");t[a-1]==="-"?r=a-1:t[a-1]==="/"?(r=a-1,i=!0):r=-1}else e===1/0&&t.includes("/")?(r=t.lastIndexOf("/"),i=!0):r=t.lastIndexOf("-",e);if(r<0)break;let n=t.slice(0,r),s=t.slice(i?r:r+1);e=r-1,!(n===""||s==="/")&&(yield[n,s])}}function ZE(t,e){if(t.length===0||e.tailwindConfig.prefix==="")return t;for(let r of t){let[i]=r;if(i.options.respectPrefix){let n=X.root({nodes:[r[1].clone()]}),s=r[1].raws.tailwind.classCandidate;n.walkRules(a=>{let o=s.startsWith("-");a.selector=mr(e.tailwindConfig.prefix,a.selector,o)}),r[1]=n.nodes[0]}}return t}function eA(t,e){if(t.length===0)return t;let r=[];for(let[i,n]of t){let s=X.root({nodes:[n.clone()]});s.walkRules(a=>{let o=(0,Ds.default)().astSync(a.selector);o.each(u=>Ll(u,e)),Op(o,u=>u===e?`!${u}`:u),a.selector=o.toString(),a.walkDecls(u=>u.important=!0)}),r.push([{...i,important:!0},s.nodes[0]])}return r}function tA(t,e,r){if(e.length===0)return e;let i={modifier:null,value:Mi};{let[n,...s]=Te(t,"/");if(s.length>1&&(n=n+"/"+s.slice(0,-1).join("/"),s=s.slice(-1)),s.length&&!r.variantMap.has(t)&&(t=n,i.modifier=s[0],!pe(r.tailwindConfig,"generalizedModifiers")))return[]}if(t.endsWith("]")&&!t.startsWith("[")){let n=/(.)(-?)\[(.*)\]/g.exec(t);if(n){let[,s,a,o]=n;if(s==="@"&&a==="-")return[];if(s!=="@"&&a==="")return[];t=t.replace(`${a}[${o}]`,""),i.value=o}}if(jl(t)&&!r.variantMap.has(t)){let n=r.offsets.recordVariant(t),s=G(t.slice(1,-1)),a=Te(s,",");if(a.length>1)return[];if(!a.every(Bs))return[];let o=a.map((u,c)=>[r.offsets.applyParallelOffset(n,c),Fi(u.trim())]);r.variantMap.set(t,o)}if(r.variantMap.has(t)){let n=jl(t),s=r.variantOptions.get(t)?.[Li]??{},a=r.variantMap.get(t).slice(),o=[],u=(()=>!(n||s.respectPrefix===!1))();for(let[c,f]of e){if(c.layer==="user")continue;let p=X.root({nodes:[f.clone()]});for(let[h,m,v]of a){let w=function(){S.raws.neededBackup||(S.raws.neededBackup=!0,S.walkRules(E=>E.raws.originalSelector=E.selector))},_=function(E){return w(),S.each(F=>{F.type==="rule"&&(F.selectors=F.selectors.map(z=>E({get className(){return Nl(z)},selector:z})))}),S},S=(v??p).clone(),b=[],T=m({get container(){return w(),S},separator:r.tailwindConfig.separator,modifySelectors:_,wrap(E){let F=S.nodes;S.removeAll(),E.append(F),S.append(E)},format(E){b.push({format:E,respectPrefix:u})},args:i});if(Array.isArray(T)){for(let[E,F]of T.entries())a.push([r.offsets.applyParallelOffset(h,E),F,S.clone()]);continue}if(typeof T=="string"&&b.push({format:T,respectPrefix:u}),T===null)continue;S.raws.neededBackup&&(delete S.raws.neededBackup,S.walkRules(E=>{let F=E.raws.originalSelector;if(!F||(delete E.raws.originalSelector,F===E.selector))return;let z=E.selector,N=(0,Ds.default)(fe=>{fe.walkClasses(ye=>{ye.value=`${t}${r.tailwindConfig.separator}${ye.value}`})}).processSync(F);b.push({format:z.replace(N,"&"),respectPrefix:u}),E.selector=F})),S.nodes[0].raws.tailwind={...S.nodes[0].raws.tailwind,parentLayer:c.layer};let O=[{...c,sort:r.offsets.applyVariantOffset(c.sort,h,Object.assign(i,r.variantOptions.get(t))),collectedFormats:(c.collectedFormats??[]).concat(b)},S.nodes[0]];o.push(O)}}return o}return[]}function zl(t,e,r={}){return!we(t)&&!Array.isArray(t)?[[t],r]:Array.isArray(t)?zl(t[0],e,t[1]):(e.has(t)||e.set(t,hr(t)),[e.get(t),r])}function iA(t){return rA.test(t)}function nA(t){if(!t.includes("://"))return!1;try{let e=new URL(t);return e.scheme!==""&&e.host!==""}catch(e){return!1}}function sg(t){let e=!0;return t.walkDecls(r=>{if(!ag(r.prop,r.value))return e=!1,!1}),e}function ag(t,e){if(nA(`${t}:${e}`))return!1;try{return X.parse(`a{${t}:${e}}`).toResult(),!0}catch(r){return!1}}function sA(t,e){let[,r,i]=t.match(/^\[([a-zA-Z0-9-_]+):(\S+)\]$/)??[];if(i===void 0||!iA(r)||!yr(i))return null;let n=G(i,{property:r});return ag(r,n)?[[{sort:e.offsets.arbitraryProperty(),layer:"utilities"},()=>({[_l(t)]:{[r]:n}})]]:null}function*aA(t,e){e.candidateRuleMap.has(t)&&(yield[e.candidateRuleMap.get(t),"DEFAULT"]),yield*function*(o){o!==null&&(yield[o,"DEFAULT"])}(sA(t,e));let r=t,i=!1,n=e.tailwindConfig.prefix,s=n.length,a=r.startsWith(n)||r.startsWith(`-${n}`);r[s]==="-"&&a&&(i=!0,r=n+r.slice(s+1)),i&&e.candidateRuleMap.has(r)&&(yield[e.candidateRuleMap.get(r),"-DEFAULT"]);for(let[o,u]of KE(r))e.candidateRuleMap.has(o)&&(yield[e.candidateRuleMap.get(o),i?`-${u}`:u])}function oA(t,e){return t===gt?[gt]:Te(t,e)}function*lA(t,e){for(let r of t)r[1].raws.tailwind={...r[1].raws.tailwind,classCandidate:e,preserveSource:r[0].options?.preserveSource??!1},yield r}function*$l(t,e){let r=e.tailwindConfig.separator,[i,...n]=oA(t,r).reverse(),s=!1;i.startsWith("!")&&(s=!0,i=i.slice(1));for(let a of aA(i,e)){let o=[],u=new Map,[c,f]=a,p=c.length===1;for(let[h,m]of c){let v=[];if(typeof m=="function")for(let S of[].concat(m(f,{isOnlyPlugin:p}))){let[b,w]=zl(S,e.postCssNodeCache);for(let _ of b)v.push([{...h,options:{...h.options,...w}},_])}else if(f==="DEFAULT"||f==="-DEFAULT"){let S=m,[b,w]=zl(S,e.postCssNodeCache);for(let _ of b)v.push([{...h,options:{...h.options,...w}},_])}if(v.length>0){let S=Array.from(Ua(h.options?.types??[],f,h.options??{},e.tailwindConfig)).map(([b,w])=>w);S.length>0&&u.set(v,S),o.push(v)}}if(jl(f)){if(o.length>1){let v=function(b){return b.length===1?b[0]:b.find(w=>{let _=u.get(w);return w.some(([{options:T},O])=>sg(O)?T.types.some(({type:E,preferOnConflict:F})=>_.includes(E)&&F):!1)})},[h,m]=o.reduce((b,w)=>(w.some(([{options:T}])=>T.types.some(({type:O})=>O==="any"))?b[0].push(w):b[1].push(w),b),[[],[]]),S=v(m)??v(h);if(S)o=[S];else{let b=o.map(_=>new Set([...u.get(_)??[]]));for(let _ of b)for(let T of _){let O=!1;for(let E of b)_!==E&&E.has(T)&&(E.delete(T),O=!0);O&&_.delete(T)}let w=[];for(let[_,T]of b.entries())for(let O of T){let E=o[_].map(([,F])=>F).flat().map(F=>F.toString().split(`
`).slice(1,-1).map(z=>z.trim()).map(z=>` ${z}`).join(`
`)).join(`
`);w.push(` Use \`${t.replace("[",`[${O}:`)}\` for \`${E.trim()}\``);break}V.warn([`The class \`${t}\` is ambiguous and matches multiple utilities.`,...w,`If this is content and not a class, replace it with \`${t.replace("[","[").replace("]","]")}\` to silence this warning.`]);continue}}o=o.map(h=>h.filter(m=>sg(m[1])))}o=o.flat(),o=Array.from(lA(o,i)),o=ZE(o,e),s&&(o=eA(o,i));for(let h of n)o=tA(h,o,e);for(let h of o)h[1].raws.tailwind={...h[1].raws.tailwind,candidate:t},h=uA(h,{context:e,candidate:t}),h!==null&&(yield h)}}function uA(t,{context:e,candidate:r}){if(!t[0].collectedFormats)return t;let i=!0,n;try{n=wr(t[0].collectedFormats,{context:e,candidate:r})}catch{return null}let s=X.root({nodes:[t[1].clone()]});return s.walkRules(a=>{if(!qs(a))try{let o=Ps(a.selector,n,{candidate:r,context:e});if(o===null){a.remove();return}a.selector=o}catch{return i=!1,!1}}),!i||s.nodes.length===0?null:(t[1]=s.nodes[0],t)}function qs(t){return t.parent&&t.parent.type==="atrule"&&t.parent.name==="keyframes"}function fA(t){if(t===!0)return e=>{qs(e)||e.walkDecls(r=>{r.parent.type==="rule"&&!qs(r.parent)&&(r.important=!0)})};if(typeof t=="string")return e=>{qs(e)||(e.selectors=e.selectors.map(r=>Is(r,t)))}}function Rs(t,e,r=!1){let i=[],n=fA(e.tailwindConfig.important);for(let s of t){if(e.notClassCache.has(s))continue;if(e.candidateRuleCache.has(s)){i=i.concat(Array.from(e.candidateRuleCache.get(s)));continue}let a=Array.from($l(s,e));if(a.length===0){e.notClassCache.add(s);continue}e.classCache.set(s,a);let o=e.candidateRuleCache.get(s)??new Set;e.candidateRuleCache.set(s,o);for(let u of a){let[{sort:c,options:f},p]=u;if(f.respectImportant&&n){let m=X.root({nodes:[p.clone()]});m.walkRules(n),p=m.nodes[0]}let h=[c,r?p.clone():p];o.add(h),e.ruleCache.add(h),i.push(h)}}return i}function jl(t){return t.startsWith("[")&&t.endsWith("]")}var Ds,XE,rA,Ls=A(()=>{l();It();Ds=ce(rt());Sl();tr();xs();Jr();Ye();Rt();Bl();Tl();Qr();Bi();Il();rr();ct();Fl();XE=(0,Ds.default)(t=>t.first.filter(({type:e})=>e==="class").pop().value);rA=/^[a-z_-]/});var og,lg=A(()=>{l();og={}});function cA(t){try{return og.createHash("md5").update(t,"utf-8").digest("binary")}catch(e){return""}}function ug(t,e){let r=e.toString();if(!r.includes("@tailwind"))return!1;let i=Pl.get(t),n=cA(r),s=i!==n;return Pl.set(t,n),s}var fg=A(()=>{l();lg();Rt()});function Ms(t){return(t>0n)-(t<0n)}var cg=A(()=>{l()});function pg(t,e){let r=0n,i=0n;for(let[n,s]of e)t&n&&(r=r|n,i=i|s);return t&~r|i}var dg=A(()=>{l()});function hg(t){let e=null;for(let r of t)e=e??r,e=e>r?e:r;return e}function pA(t,e){let r=t.length,i=e.length,n=r<i?r:i;for(let s=0;s<n;s++){let a=t.charCodeAt(s)-e.charCodeAt(s);if(a!==0)return a}return r-i}var Ul,mg=A(()=>{l();cg();dg();Ul=class{constructor(){this.offsets={defaults:0n,base:0n,components:0n,utilities:0n,variants:0n,user:0n},this.layerPositions={defaults:0n,base:1n,components:2n,utilities:3n,user:4n,variants:5n},this.reservedVariantBits=0n,this.variantOffsets=new Map}create(e){return{layer:e,parentLayer:e,arbitrary:0n,variants:0n,parallelIndex:0n,index:this.offsets[e]++,options:[]}}arbitraryProperty(){return{...this.create("utilities"),arbitrary:1n}}forVariant(e,r=0){let i=this.variantOffsets.get(e);if(i===void 0)throw new Error(`Cannot find offset for unknown variant ${e}`);return{...this.create("variants"),variants:i<<BigInt(r)}}applyVariantOffset(e,r,i){return i.variant=r.variants,{...e,layer:"variants",parentLayer:e.layer==="variants"?e.parentLayer:e.layer,variants:e.variants|r.variants,options:i.sort?[].concat(i,e.options):e.options,parallelIndex:hg([e.parallelIndex,r.parallelIndex])}}applyParallelOffset(e,r){return{...e,parallelIndex:BigInt(r)}}recordVariants(e,r){for(let i of e)this.recordVariant(i,r(i))}recordVariant(e,r=1){return this.variantOffsets.set(e,1n<<this.reservedVariantBits),this.reservedVariantBits+=BigInt(r),{...this.create("variants"),variants:this.variantOffsets.get(e)}}compare(e,r){if(e.layer!==r.layer)return this.layerPositions[e.layer]-this.layerPositions[r.layer];if(e.parentLayer!==r.parentLayer)return this.layerPositions[e.parentLayer]-this.layerPositions[r.parentLayer];for(let i of e.options)for(let n of r.options){if(i.id!==n.id||!i.sort||!n.sort)continue;let s=hg([i.variant,n.variant])??0n,a=~(s|s-1n),o=e.variants&a,u=r.variants&a;if(o!==u)continue;let c=i.sort({value:i.value,modifier:i.modifier},{value:n.value,modifier:n.modifier});if(c!==0)return c}return e.variants!==r.variants?e.variants-r.variants:e.parallelIndex!==r.parallelIndex?e.parallelIndex-r.parallelIndex:e.arbitrary!==r.arbitrary?e.arbitrary-r.arbitrary:e.index-r.index}recalculateVariantOffsets(){let e=Array.from(this.variantOffsets.entries()).filter(([n])=>n.startsWith("[")).sort(([n],[s])=>pA(n,s)),r=e.map(([,n])=>n).sort((n,s)=>Ms(n-s));return e.map(([,n],s)=>[n,r[s]]).filter(([n,s])=>n!==s)}remapArbitraryVariantOffsets(e){let r=this.recalculateVariantOffsets();return r.length===0?e:e.map(i=>{let[n,s]=i;return n={...n,variants:pg(n.variants,r)},[n,s]})}sort(e){return e=this.remapArbitraryVariantOffsets(e),e.sort(([r],[i])=>Ms(this.compare(r,i)))}}});function Hl(t,e){let r=t.tailwindConfig.prefix;return typeof r=="function"?r(e):r+e}function yg({type:t="any",...e}){let r=[].concat(t);return{...e,types:r.map(i=>Array.isArray(i)?{type:i[0],...i[1]}:{type:i,preferOnConflict:!1})}}function dA(t){let e=[],r="",i=0;for(let n=0;n<t.length;n++){let s=t[n];if(s==="\\")r+="\\"+t[++n];else if(s==="{")++i,e.push(r.trim()),r="";else if(s==="}"){if(--i<0)throw new Error("Your { and } are unbalanced.");e.push(r.trim()),r=""}else r+=s}return r.length>0&&e.push(r.trim()),e=e.filter(n=>n!==""),e}function hA(t,e,{before:r=[]}={}){if(r=[].concat(r),r.length<=0){t.push(e);return}let i=t.length-1;for(let n of r){let s=t.indexOf(n);s!==-1&&(i=Math.min(i,s))}t.splice(i,0,e)}function vg(t){return Array.isArray(t)?t.flatMap(e=>!Array.isArray(e)&&!we(e)?e:hr(e)):vg([t])}function mA(t,e){return(0,Vl.default)(i=>{let n=[];return e&&e(i),i.walkClasses(s=>{n.push(s.value)}),n}).transformSync(t)}function gA(t){t.walkPseudos(e=>{e.value===":not"&&e.remove()})}function yA(t,e={containsNonOnDemandable:!1},r=0){let i=[],n=[];t.type==="rule"?n.push(...t.selectors):t.type==="atrule"&&t.walkRules(s=>n.push(...s.selectors));for(let s of n){let a=mA(s,gA);a.length===0&&(e.containsNonOnDemandable=!0);for(let o of a)i.push(o)}return r===0?[e.containsNonOnDemandable||i.length===0,i]:i}function Fs(t){return vg(t).flatMap(e=>{let r=new Map,[i,n]=yA(e);return i&&n.unshift(gt),n.map(s=>(r.has(e)||r.set(e,e),[s,r.get(e)]))})}function Bs(t){return t.startsWith("@")||t.includes("&")}function Fi(t){t=t.replace(/\n+/g,"").replace(/\s{1,}/g," ").trim();let e=dA(t).map(r=>{if(!r.startsWith("@"))return({format:s})=>s(r);let[,i,n]=/@(\S*)( .+|[({].*)?/g.exec(r);return({wrap:s})=>s(X.atRule({name:i,params:n?.trim()??""}))}).reverse();return r=>{for(let i of e)i(r)}}function vA(t,e,{variantList:r,variantMap:i,offsets:n,classList:s}){function a(h,m){return h?(0,gg.default)(t,h,m):t}function o(h){return mr(t.prefix,h)}function u(h,m){return h===gt?gt:m.respectPrefix?e.tailwindConfig.prefix+h:h}function c(h,m,v={}){let S=Tt(h),b=a(["theme",...S],m);return mt(S[0])(b,v)}let f=0,p={postcss:X,prefix:o,e:Ce,config:a,theme:c,corePlugins:h=>Array.isArray(t.corePlugins)?t.corePlugins.includes(h):a(["corePlugins",h],!0),variants:()=>[],addBase(h){for(let[m,v]of Fs(h)){let S=u(m,{}),b=n.create("base");e.candidateRuleMap.has(S)||e.candidateRuleMap.set(S,[]),e.candidateRuleMap.get(S).push([{sort:b,layer:"base"},v])}},addDefaults(h,m){let v={[`@defaults ${h}`]:m};for(let[S,b]of Fs(v)){let w=u(S,{});e.candidateRuleMap.has(w)||e.candidateRuleMap.set(w,[]),e.candidateRuleMap.get(w).push([{sort:n.create("defaults"),layer:"defaults"},b])}},addComponents(h,m){m=Object.assign({},{preserveSource:!1,respectPrefix:!0,respectImportant:!1},Array.isArray(m)?{}:m);for(let[S,b]of Fs(h)){let w=u(S,m);s.add(w),e.candidateRuleMap.has(w)||e.candidateRuleMap.set(w,[]),e.candidateRuleMap.get(w).push([{sort:n.create("components"),layer:"components",options:m},b])}},addUtilities(h,m){m=Object.assign({},{preserveSource:!1,respectPrefix:!0,respectImportant:!0},Array.isArray(m)?{}:m);for(let[S,b]of Fs(h)){let w=u(S,m);s.add(w),e.candidateRuleMap.has(w)||e.candidateRuleMap.set(w,[]),e.candidateRuleMap.get(w).push([{sort:n.create("utilities"),layer:"utilities",options:m},b])}},matchUtilities:function(h,m){m=yg({...{respectPrefix:!0,respectImportant:!0,modifiers:!1},...m});let S=n.create("utilities");for(let b in h){let T=function(E,{isOnlyPlugin:F}){let[z,N,fe]=ja(m.types,E,m,t);if(z===void 0)return[];if(!m.types.some(({type:W})=>W===N))if(F)V.warn([`Unnecessary typehint \`${N}\` in \`${b}-${E}\`.`,`You can safely update it to \`${b}-${E.replace(N+":","")}\`.`]);else return[];if(!yr(z))return[];let ye={get modifier(){return m.modifiers||V.warn(`modifier-used-without-options-for-${b}`,["Your plugin must set `modifiers: true` in its options to support modifiers."]),fe}},Se=pe(t,"generalizedModifiers");return[].concat(Se?_(z,ye):_(z)).filter(Boolean).map(W=>({[ks(b,E)]:W}))},w=u(b,m),_=h[b];s.add([w,m]);let O=[{sort:S,layer:"utilities",options:m},T];e.candidateRuleMap.has(w)||e.candidateRuleMap.set(w,[]),e.candidateRuleMap.get(w).push(O)}},matchComponents:function(h,m){m=yg({...{respectPrefix:!0,respectImportant:!1,modifiers:!1},...m});let S=n.create("components");for(let b in h){let T=function(E,{isOnlyPlugin:F}){let[z,N,fe]=ja(m.types,E,m,t);if(z===void 0)return[];if(!m.types.some(({type:W})=>W===N))if(F)V.warn([`Unnecessary typehint \`${N}\` in \`${b}-${E}\`.`,`You can safely update it to \`${b}-${E.replace(N+":","")}\`.`]);else return[];if(!yr(z))return[];let ye={get modifier(){return m.modifiers||V.warn(`modifier-used-without-options-for-${b}`,["Your plugin must set `modifiers: true` in its options to support modifiers."]),fe}},Se=pe(t,"generalizedModifiers");return[].concat(Se?_(z,ye):_(z)).filter(Boolean).map(W=>({[ks(b,E)]:W}))},w=u(b,m),_=h[b];s.add([w,m]);let O=[{sort:S,layer:"components",options:m},T];e.candidateRuleMap.has(w)||e.candidateRuleMap.set(w,[]),e.candidateRuleMap.get(w).push(O)}},addVariant(h,m,v={}){m=[].concat(m).map(S=>{if(typeof S!="string")return(b={})=>{let{args:w,modifySelectors:_,container:T,separator:O,wrap:E,format:F}=b,z=S(Object.assign({modifySelectors:_,container:T,separator:O},v.type===Wl.MatchVariant&&{args:w,wrap:E,format:F}));if(typeof z=="string"&&!Bs(z))throw new Error(`Your custom variant \`${h}\` has an invalid format string. Make sure it's an at-rule or contains a \`&\` placeholder.`);return Array.isArray(z)?z.filter(N=>typeof N=="string").map(N=>Fi(N)):z&&typeof z=="string"&&Fi(z)(b)};if(!Bs(S))throw new Error(`Your custom variant \`${h}\` has an invalid format string. Make sure it's an at-rule or contains a \`&\` placeholder.`);return Fi(S)}),hA(r,h,v),i.set(h,m),e.variantOptions.set(h,v)},matchVariant(h,m,v){let S=v?.id??++f,b=h==="@",w=pe(t,"generalizedModifiers");for(let[T,O]of Object.entries(v?.values??{}))T!=="DEFAULT"&&p.addVariant(b?`${h}${T}`:`${h}-${T}`,({args:E,container:F})=>m(O,w?{modifier:E?.modifier,container:F}:{container:F}),{...v,value:O,id:S,type:Wl.MatchVariant,variantInfo:Gl.Base});let _="DEFAULT"in(v?.values??{});p.addVariant(h,({args:T,container:O})=>T?.value===Mi&&!_?null:m(T?.value===Mi?v.values.DEFAULT:T?.value??(typeof T=="string"?T:""),w?{modifier:T?.modifier,container:O}:{container:O}),{...v,id:S,type:Wl.MatchVariant,variantInfo:Gl.Dynamic})}};return p}function Ns(t){return Yl.has(t)||Yl.set(t,new Map),Yl.get(t)}function wg(t,e){let r=!1,i=new Map;for(let n of t){if(!n)continue;let s=Qa.parse(n),a=s.hash?s.href.replace(s.hash,""):s.href;a=s.search?a.replace(s.search,""):a;let o=me.statSync(decodeURIComponent(a),{throwIfNoEntry:!1})?.mtimeMs;!o||((!e.has(n)||o>e.get(n))&&(r=!0),i.set(n,o))}return[r,i]}function bg(t){t.walkAtRules(e=>{["responsive","variants"].includes(e.name)&&(bg(e),e.before(e.nodes),e.remove())})}function wA(t){let e=[];return t.each(r=>{r.type==="atrule"&&["responsive","variants"].includes(r.name)&&(r.name="layer",r.params="utilities")}),t.walkAtRules("layer",r=>{if(bg(r),r.params==="base"){for(let i of r.nodes)e.push(function({addBase:n}){n(i,{respectPrefix:!1})});r.remove()}else if(r.params==="components"){for(let i of r.nodes)e.push(function({addComponents:n}){n(i,{respectPrefix:!1,preserveSource:!0})});r.remove()}else if(r.params==="utilities"){for(let i of r.nodes)e.push(function({addUtilities:n}){n(i,{respectPrefix:!1,preserveSource:!0})});r.remove()}}),e}function bA(t,e){let r=Object.entries({...xe,...Qm}).map(([o,u])=>t.tailwindConfig.corePlugins.includes(o)?u:null).filter(Boolean),i=t.tailwindConfig.plugins.map(o=>(o.__isOptionsFunction&&(o=o()),typeof o=="function"?o:o.handler)),n=wA(e),s=[xe.childVariant,xe.pseudoElementVariants,xe.pseudoClassVariants,xe.hasVariants,xe.ariaVariants,xe.dataVariants],a=[xe.supportsVariants,xe.reducedMotionVariants,xe.prefersContrastVariants,xe.printVariant,xe.screenVariants,xe.orientationVariants,xe.directionVariants,xe.darkVariants,xe.forcedColorsVariants];return[...r,...s,...i,...a,...n]}function xA(t,e){let r=[],i=new Map;e.variantMap=i;let n=new Ul;e.offsets=n;let s=new Set,a=vA(e.tailwindConfig,e,{variantList:r,variantMap:i,offsets:n,classList:s});for(let f of t)if(Array.isArray(f))for(let p of f)p(a);else f?.(a);n.recordVariants(r,f=>i.get(f).length);for(let[f,p]of i.entries())e.variantMap.set(f,p.map((h,m)=>[n.forVariant(f,m),h]));let o=(e.tailwindConfig.safelist??[]).filter(Boolean);if(o.length>0){let f=[];for(let p of o){if(typeof p=="string"){e.changedContent.push({content:p,extension:"html"});continue}if(p instanceof RegExp){V.warn("root-regex",["Regular expressions in `safelist` work differently in Tailwind CSS v3.0.","Update your `safelist` configuration to eliminate this warning.","https://tailwindcss.com/docs/content-configuration#safelisting-classes"]);continue}f.push(p)}if(f.length>0){let p=new Map,h=e.tailwindConfig.prefix.length,m=f.some(v=>v.pattern.source.includes("!"));for(let v of s){let S=Array.isArray(v)?(()=>{let[b,w]=v,T=Object.keys(w?.values??{}).map(O=>Ri(b,O));return w?.supportsNegativeValues&&(T=[...T,...T.map(O=>"-"+O)],T=[...T,...T.map(O=>O.slice(0,h)+"-"+O.slice(h))]),w.types.some(({type:O})=>O==="color")&&(T=[...T,...T.flatMap(O=>Object.keys(e.tailwindConfig.theme.opacity).map(E=>`${O}/${E}`))]),m&&w?.respectImportant&&(T=[...T,...T.map(O=>"!"+O)]),T})():[v];for(let b of S)for(let{pattern:w,variants:_=[]}of f)if(w.lastIndex=0,p.has(w)||p.set(w,0),!!w.test(b)){p.set(w,p.get(w)+1),e.changedContent.push({content:b,extension:"html"});for(let T of _)e.changedContent.push({content:T+e.tailwindConfig.separator+b,extension:"html"})}}for(let[v,S]of p.entries())S===0&&V.warn([`The safelist pattern \`${v}\` doesn't match any Tailwind CSS classes.`,"Fix this pattern or remove it from your `safelist` configuration.","https://tailwindcss.com/docs/content-configuration#safelisting-classes"])}}let u=[].concat(e.tailwindConfig.darkMode??"media")[1]??"dark",c=[Hl(e,u),Hl(e,"group"),Hl(e,"peer")];e.getClassOrder=function(p){let h=[...p].sort((b,w)=>b===w?0:b<w?-1:1),m=new Map(h.map(b=>[b,null])),v=Rs(new Set(h),e,!0);v=e.offsets.sort(v);let S=BigInt(c.length);for(let[,b]of v){let w=b.raws.tailwind.candidate;m.set(w,m.get(w)??S++)}return p.map(b=>{let w=m.get(b)??null,_=c.indexOf(b);return w===null&&_!==-1&&(w=BigInt(_)),[b,w]})},e.getClassList=function(p={}){let h=[];for(let m of s)if(Array.isArray(m)){let[v,S]=m,b=[],w=Object.keys(S?.modifiers??{});S?.types?.some(({type:O})=>O==="color")&&w.push(...Object.keys(e.tailwindConfig.theme.opacity??{}));let _={modifiers:w},T=p.includeMetadata&&w.length>0;for(let[O,E]of Object.entries(S?.values??{})){if(E==null)continue;let F=Ri(v,O);if(h.push(T?[F,_]:F),S?.supportsNegativeValues&&_t(E)){let z=Ri(v,`-${O}`);b.push(T?[z,_]:z)}}h.push(...b)}else h.push(m);return h},e.getVariants=function(){let p=[];for(let[h,m]of e.variantOptions.entries())m.variantInfo!==Gl.Base&&p.push({name:h,isArbitrary:m.type===Symbol.for("MATCH_VARIANT"),values:Object.keys(m.values??{}),hasDash:h!=="@",selectors({modifier:v,value:S}={}){let b="__TAILWIND_PLACEHOLDER__",w=X.rule({selector:`.${b}`}),_=X.root({nodes:[w.clone()]}),T=_.toString(),O=(e.variantMap.get(h)??[]).flatMap(([W,ve])=>ve),E=[];for(let W of O){let ve=[],wn={args:{modifier:v,value:m.values?.[S]??S},separator:e.tailwindConfig.separator,modifySelectors(We){return _.each(Ea=>{Ea.type==="rule"&&(Ea.selectors=Ea.selectors.map(Wc=>We({get className(){return Nl(Wc)},selector:Wc})))}),_},format(We){ve.push(We)},wrap(We){ve.push(`@${We.name} ${We.params} { & }`)},container:_},bn=W(wn);if(ve.length>0&&E.push(ve),Array.isArray(bn))for(let We of bn)ve=[],We(wn),E.push(ve)}let F=[],z=_.toString();T!==z&&(_.walkRules(W=>{let ve=W.selector,wn=(0,Vl.default)(bn=>{bn.walkClasses(We=>{We.value=`${h}${e.tailwindConfig.separator}${We.value}`})}).processSync(ve);F.push(ve.replace(wn,"&").replace(b,"&"))}),_.walkAtRules(W=>{F.push(`@${W.name} (${W.params}) { & }`)}));let N=!(S in(m.values??{})),fe=m[Li]??{},ye=(()=>!(N||fe.respectPrefix===!1))();E=E.map(W=>W.map(ve=>({format:ve,respectPrefix:ye}))),F=F.map(W=>({format:W,respectPrefix:ye}));let Se={candidate:b,context:e},Ve=E.map(W=>Ps(`.${b}`,wr(W,Se),Se).replace(`.${b}`,"&").replace("{ & }","").trim());return F.length>0&&Ve.push(wr(F,Se).toString().replace(`.${b}`,"&")),Ve}});return p}}function xg(t,e){!t.classCache.has(e)||(t.notClassCache.add(e),t.classCache.delete(e),t.applyClassCache.delete(e),t.candidateRuleMap.delete(e),t.candidateRuleCache.delete(e),t.stylesheetCache=null)}function kA(t,e){let r=e.raws.tailwind.candidate;if(!!r){for(let i of t.ruleCache)i[1].raws.tailwind.candidate===r&&t.ruleCache.delete(i);xg(t,r)}}function Ql(t,e=[],r=X.root()){let i={disposables:[],ruleCache:new Set,candidateRuleCache:new Map,classCache:new Map,applyClassCache:new Map,notClassCache:new Set(t.blocklist??[]),postCssNodeCache:new Map,candidateRuleMap:new Map,tailwindConfig:t,changedContent:e,variantMap:new Map,stylesheetCache:null,variantOptions:new Map,markInvalidUtilityCandidate:s=>xg(i,s),markInvalidUtilityNode:s=>kA(i,s)},n=bA(i,r);return xA(n,i),i}function kg(t,e,r,i,n,s){let a=e.opts.from,o=i!==null;Xe.DEBUG&&console.log("Source path:",a);let u;if(o&&br.has(a))u=br.get(a);else if(Ni.has(n)){let h=Ni.get(n);Lt.get(h).add(a),br.set(a,h),u=h}let c=ug(a,t);if(u){let[h,m]=wg([...s],Ns(u));if(!h&&!c)return[u,!1,m]}if(br.has(a)){let h=br.get(a);if(Lt.has(h)&&(Lt.get(h).delete(a),Lt.get(h).size===0)){Lt.delete(h);for(let[m,v]of Ni)v===h&&Ni.delete(m);for(let m of h.disposables.splice(0))m(h)}}Xe.DEBUG&&console.log("Setting up new context...");let f=Ql(r,[],t);Object.assign(f,{userConfigPath:i});let[,p]=wg([...s],Ns(f));return Ni.set(n,f),br.set(a,f),Lt.has(f)||Lt.set(f,new Set),Lt.get(f).add(a),[f,!0,p]}var gg,Vl,Li,Wl,Gl,Yl,br,Ni,Lt,Bi=A(()=>{l();ft();Ja();It();gg=ce(wo()),Vl=ce(rt());Di();Sl();xs();tr();gr();Tl();Jr();Jm();Rt();Rt();On();Ye();Sn();Il();Ls();fg();mg();ct();Bl();Li=Symbol(),Wl={AddVariant:Symbol.for("ADD_VARIANT"),MatchVariant:Symbol.for("MATCH_VARIANT")},Gl={Base:1<<0,Dynamic:1<<1};Yl=new WeakMap;br=Xm,Ni=Km,Lt=As});function Jl(t){return t.ignore?[]:t.glob?g.env.ROLLUP_WATCH==="true"?[{type:"dependency",file:t.base}]:[{type:"dir-dependency",dir:t.base,glob:t.glob}]:[{type:"dependency",file:t.base}]}var Sg=A(()=>{l()});function _g(t,e){return{handler:t,config:e}}var Tg,Og=A(()=>{l();_g.withOptions=function(t,e=()=>({})){let r=function(i){return{__options:i,handler:t(i),config:e(i)}};return r.__isOptionsFunction=!0,r.__pluginFunction=t,r.__configFunction=e,r};Tg=_g});var zs={};Ge(zs,{default:()=>SA});var SA,$s=A(()=>{l();Og();SA=Tg});var Ag=k((aN,Eg)=>{l();var _A=($s(),zs).default,TA={overflow:"hidden",display:"-webkit-box","-webkit-box-orient":"vertical"},OA=_A(function({matchUtilities:t,addUtilities:e,theme:r,variants:i}){let n=r("lineClamp");t({"line-clamp":s=>({...TA,"-webkit-line-clamp":`${s}`})},{values:n}),e([{".line-clamp-none":{"-webkit-line-clamp":"unset"}}],i("lineClamp"))},{theme:{lineClamp:{1:"1",2:"2",3:"3",4:"4",5:"5",6:"6"}},variants:{lineClamp:["responsive"]}});Eg.exports=OA});function Xl(t){t.content.files.length===0&&V.warn("content-problems",["The `content` option in your Tailwind CSS configuration is missing or empty.","Configure your content sources or your generated CSS will be missing styles.","https://tailwindcss.com/docs/content-configuration"]);try{let e=Ag();t.plugins.includes(e)&&(V.warn("line-clamp-in-core",["As of Tailwind CSS v3.3, the `@tailwindcss/line-clamp` plugin is now included by default.","Remove it from the `plugins` array in your configuration to eliminate this warning."]),t.plugins=t.plugins.filter(r=>r!==e))}catch{}return t}var Cg=A(()=>{l();Ye()});var Pg,Ig=A(()=>{l();Pg=()=>!1});var js,Dg=A(()=>{l();js={sync:t=>[].concat(t),generateTasks:t=>[{dynamic:!1,base:".",negative:[],positive:[].concat(t),patterns:[].concat(t)}],escapePath:t=>t}});var Kl,qg=A(()=>{l();Kl=t=>t});var Rg,Lg=A(()=>{l();Rg=()=>""});function Bg(t){let e=t,r=Rg(t);return r!=="."&&(e=t.substr(r.length),e.charAt(0)==="/"&&(e=e.substr(1))),e.substr(0,2)==="./"&&(e=e.substr(2)),e.charAt(0)==="/"&&(e=e.substr(1)),{base:r,glob:e}}var Mg=A(()=>{l();Lg()});function Fg(t,e){let r=e.content.files;r=r.filter(o=>typeof o=="string"),r=r.map(Kl);let i=js.generateTasks(r),n=[],s=[];for(let o of i)n.push(...o.positive.map(u=>Ng(u,!1))),s.push(...o.negative.map(u=>Ng(u,!0)));let a=[...n,...s];return a=AA(t,a),a=a.flatMap(CA),a=a.map(EA),a}function Ng(t,e){let r={original:t,base:t,ignore:e,pattern:t,glob:null};return Pg(t)&&Object.assign(r,Bg(t)),r}function EA(t){let e=Kl(t.base);return e=js.escapePath(e),t.pattern=t.glob?`${e}/${t.glob}`:e,t.pattern=t.ignore?`!${t.pattern}`:t.pattern,t}function AA(t,e){let r=[];return t.userConfigPath&&t.tailwindConfig.content.relative&&(r=[de.dirname(t.userConfigPath)]),e.map(i=>(i.base=de.resolve(...r,i.base),i))}function CA(t){let e=[t];try{let r=me.realpathSync(t.base);r!==t.base&&e.push({...t,base:r})}catch{}return e}function zg(t,e,r){let i=t.tailwindConfig.content.files.filter(a=>typeof a.raw=="string").map(({raw:a,extension:o="html"})=>({content:a,extension:o})),[n,s]=PA(e,r);for(let a of n){let o=de.extname(a).slice(1);i.push({file:a,extension:o})}return[i,s]}function PA(t,e){let r=t.map(a=>a.pattern),i=new Map,n=new Set;Xe.DEBUG&&console.time("Finding changed files");let s=js.sync(r,{absolute:!0});for(let a of s){let o=e.get(a)||-1/0,u=me.statSync(a).mtimeMs;u>o&&(n.add(a),i.set(a,u))}return Xe.DEBUG&&console.timeEnd("Finding changed files"),[n,i]}var $g=A(()=>{l();ft();Ut();Ig();Dg();qg();Mg();Rt()});function jg(){}var Ug=A(()=>{l()});function RA(t,e){for(let r of e){let i=`${t}${r}`;if(me.existsSync(i)&&me.statSync(i).isFile())return i}for(let r of e){let i=`${t}/index${r}`;if(me.existsSync(i))return i}return null}function*Vg(t,e,r,i=de.extname(t)){let n=RA(de.resolve(e,t),IA.includes(i)?DA:qA);if(n===null||r.has(n))return;r.add(n),yield n,e=de.dirname(n),i=de.extname(n);let s=me.readFileSync(n,"utf-8");for(let a of[...s.matchAll(/import[\s\S]*?['"](.{3,}?)['"]/gi),...s.matchAll(/import[\s\S]*from[\s\S]*?['"](.{3,}?)['"]/gi),...s.matchAll(/require\(['"`](.+)['"`]\)/gi)])!a[1].startsWith(".")||(yield*Vg(a[1],e,r,i))}function Zl(t){return t===null?new Set:new Set(Vg(t,de.dirname(t),new Set))}var IA,DA,qA,Wg=A(()=>{l();ft();Ut();IA=[".js",".cjs",".mjs"],DA=["",".js",".cjs",".mjs",".ts",".cts",".mts",".jsx",".tsx"],qA=["",".ts",".cts",".mts",".tsx",".js",".cjs",".mjs",".jsx"]});function LA(t,e){if(eu.has(t))return eu.get(t);let r=Fg(t,e);return eu.set(t,r).get(t)}function BA(t){let e=Ya(t);if(e!==null){let[i,n,s,a]=Hg.get(e)||[],o=Zl(e),u=!1,c=new Map;for(let h of o){let m=me.statSync(h).mtimeMs;c.set(h,m),(!a||!a.has(h)||m>a.get(h))&&(u=!0)}if(!u)return[i,e,n,s];for(let h of o)delete Hc.cache[h];let f=Xl(Kr(jg(e))),p=kn(f);return Hg.set(e,[f,p,o,c]),[f,e,p,o]}let r=Kr(t?.config??t??{});return r=Xl(r),[r,null,kn(r),[]]}function tu(t){return({tailwindDirectives:e,registerDependency:r})=>(i,n)=>{let[s,a,o,u]=BA(t),c=new Set(u);if(e.size>0){c.add(n.opts.from);for(let v of n.messages)v.type==="dependency"&&c.add(v.file)}let[f,,p]=kg(i,n,s,a,o,c),h=Ns(f),m=LA(f,s);if(e.size>0){for(let b of m)for(let w of Jl(b))r(w);let[v,S]=zg(f,m,h);for(let b of v)f.changedContent.push(b);for(let[b,w]of S.entries())p.set(b,w)}for(let v of u)r({type:"dependency",file:v});for(let[v,S]of p.entries())h.set(v,S);return f}}var Gg,Hg,eu,Yg=A(()=>{l();ft();Gg=ce(Aa());Kc();Ha();zp();Bi();Sg();Cg();$g();Ug();Wg();Hg=new Gg.default({maxSize:100}),eu=new WeakMap});function ru(t){let e=new Set,r=new Set,i=new Set;if(t.walkAtRules(n=>{n.name==="apply"&&i.add(n),n.name==="import"&&(n.params==='"tailwindcss/base"'||n.params==="'tailwindcss/base'"?(n.name="tailwind",n.params="base"):n.params==='"tailwindcss/components"'||n.params==="'tailwindcss/components'"?(n.name="tailwind",n.params="components"):n.params==='"tailwindcss/utilities"'||n.params==="'tailwindcss/utilities'"?(n.name="tailwind",n.params="utilities"):(n.params==='"tailwindcss/screens"'||n.params==="'tailwindcss/screens'"||n.params==='"tailwindcss/variants"'||n.params==="'tailwindcss/variants'")&&(n.name="tailwind",n.params="variants")),n.name==="tailwind"&&(n.params==="screens"&&(n.params="variants"),e.add(n.params)),["layer","responsive","variants"].includes(n.name)&&(["responsive","variants"].includes(n.name)&&V.warn(`${n.name}-at-rule-deprecated`,[`The \`@${n.name}\` directive has been deprecated in Tailwind CSS v3.0.`,"Use `@layer utilities` or `@layer components` instead.","https://tailwindcss.com/docs/upgrade-guide#replace-variants-with-layer"]),r.add(n))}),!e.has("base")||!e.has("components")||!e.has("utilities")){for(let n of r)if(n.name==="layer"&&["base","components","utilities"].includes(n.params)){if(!e.has(n.params))throw n.error(`\`@layer ${n.params}\` is used but no matching \`@tailwind ${n.params}\` directive is present.`)}else if(n.name==="responsive"){if(!e.has("utilities"))throw n.error("`@responsive` is used but `@tailwind utilities` is missing.")}else if(n.name==="variants"&&!e.has("utilities"))throw n.error("`@variants` is used but `@tailwind utilities` is missing.")}return{tailwindDirectives:e,applyDirectives:i}}var Qg=A(()=>{l();Ye()});function Yt(t,e=void 0,r=void 0){return t.map(i=>{let n=i.clone();return r!==void 0&&(n.raws.tailwind={...n.raws.tailwind,...r}),e!==void 0&&Jg(n,s=>{if(s.raws.tailwind?.preserveSource===!0&&s.source)return!1;s.source=e}),n})}function Jg(t,e){e(t)!==!1&&t.each?.(r=>Jg(r,e))}var Xg=A(()=>{l()});function iu(t){return t=Array.isArray(t)?t:[t],t=t.map(e=>e instanceof RegExp?e.source:e),t.join("")}function Re(t){return new RegExp(iu(t),"g")}function Bt(t){return`(?:${t.map(iu).join("|")})`}function nu(t){return`(?:${iu(t)})?`}function Zg(t){return t&&MA.test(t)?t.replace(Kg,"\\$&"):t||""}var Kg,MA,ey=A(()=>{l();Kg=/[\\^$.*+?()[\]{}|]/g,MA=RegExp(Kg.source)});function ty(t){let e=Array.from(FA(t));return r=>{let i=[];for(let n of e)for(let s of r.match(n)??[])i.push($A(s));return i}}function*FA(t){let e=t.tailwindConfig.separator,r=t.tailwindConfig.prefix!==""?nu(Re([/-?/,Zg(t.tailwindConfig.prefix)])):"",i=Bt([/\[[^\s:'"`]+:[^\s\[\]]+\]/,/\[[^\s:'"`\]]+:[^\s]+?\[[^\s]+\][^\s]+?\]/,Re([Bt([/-?(?:\w+)/,/@(?:\w+)/]),nu(Bt([Re([Bt([/-(?:\w+-)*\['[^\s]+'\]/,/-(?:\w+-)*\["[^\s]+"\]/,/-(?:\w+-)*\[`[^\s]+`\]/,/-(?:\w+-)*\[(?:[^\s\[\]]+\[[^\s\[\]]+\])*[^\s:\[\]]+\]/]),/(?![{([]])/,/(?:\/[^\s'"`\\><$]*)?/]),Re([Bt([/-(?:\w+-)*\['[^\s]+'\]/,/-(?:\w+-)*\["[^\s]+"\]/,/-(?:\w+-)*\[`[^\s]+`\]/,/-(?:\w+-)*\[(?:[^\s\[\]]+\[[^\s\[\]]+\])*[^\s\[\]]+\]/]),/(?![{([]])/,/(?:\/[^\s'"`\\$]*)?/]),/[-\/][^\s'"`\\$={><]*/]))])]),n=[Bt([Re([/@\[[^\s"'`]+\](\/[^\s"'`]+)?/,e]),Re([/([^\s"'`\[\\]+-)?\[[^\s"'`]+\]\/\w+/,e]),Re([/([^\s"'`\[\\]+-)?\[[^\s"'`]+\]/,e]),Re([/[^\s"'`\[\\]+/,e])]),Bt([Re([/([^\s"'`\[\\]+-)?\[[^\s`]+\]\/\w+/,e]),Re([/([^\s"'`\[\\]+-)?\[[^\s`]+\]/,e]),Re([/[^\s`\[\\]+/,e])])];for(let s of n)yield Re(["((?=((",s,")+))\\2)?",/!?/,r,i]);yield/[^<>"'`\s.(){}[\]#=%$]*[^<>"'`\s.(){}[\]#=%:$]/g}function $A(t){if(!t.includes("-["))return t;let e=0,r=[],i=t.matchAll(NA);i=Array.from(i).flatMap(n=>{let[,...s]=n;return s.map((a,o)=>Object.assign([],n,{index:n.index+o,0:a}))});for(let n of i){let s=n[0],a=r[r.length-1];if(s===a?r.pop():(s==="'"||s==='"'||s==="`")&&r.push(s),!a){if(s==="["){e++;continue}else if(s==="]"){e--;continue}if(e<0)return t.substring(0,n.index-1);if(e===0&&!zA.test(s))return t.substring(0,n.index)}}return t}var NA,zA,ry=A(()=>{l();ey();NA=/([\[\]'"`])([^\[\]'"`])?/g,zA=/[^"'`\s<>\]]+/});function jA(t,e){let r=t.tailwindConfig.content.extract;return r[e]||r.DEFAULT||ny[e]||ny.DEFAULT(t)}function UA(t,e){let r=t.content.transform;return r[e]||r.DEFAULT||sy[e]||sy.DEFAULT}function VA(t,e,r,i){zi.has(e)||zi.set(e,new iy.default({maxSize:25e3}));for(let n of t.split(`
`))if(n=n.trim(),!i.has(n))if(i.add(n),zi.get(e).has(n))for(let s of zi.get(e).get(n))r.add(s);else{let s=e(n).filter(o=>o!=="!*"),a=new Set(s);for(let o of a)r.add(o);zi.get(e).set(n,a)}}function WA(t,e){let r=e.offsets.sort(t),i={base:new Set,defaults:new Set,components:new Set,utilities:new Set,variants:new Set};for(let[n,s]of r)i[n.layer].add(s);return i}function su(t){return async e=>{let r={base:null,components:null,utilities:null,variants:null};if(e.walkAtRules(v=>{v.name==="tailwind"&&Object.keys(r).includes(v.params)&&(r[v.params]=v)}),Object.values(r).every(v=>v===null))return e;let i=new Set([...t.candidates??[],gt]),n=new Set;yt.DEBUG&&console.time("Reading changed files");{let v=[];for(let b of t.changedContent){let w=UA(t.tailwindConfig,b.extension),_=jA(t,b.extension);v.push([b,{transformer:w,extractor:_}])}let S=500;for(let b=0;b<v.length;b+=S){let w=v.slice(b,b+S);await Promise.all(w.map(async([{file:_,content:T},{transformer:O,extractor:E}])=>{T=_?await me.promises.readFile(_,"utf8"):T,VA(O(T),E,i,n)}))}}yt.DEBUG&&console.timeEnd("Reading changed files");let s=t.classCache.size;yt.DEBUG&&console.time("Generate rules"),yt.DEBUG&&console.time("Sorting candidates");let a=new Set([...i].sort((v,S)=>v===S?0:v<S?-1:1));yt.DEBUG&&console.timeEnd("Sorting candidates"),Rs(a,t),yt.DEBUG&&console.timeEnd("Generate rules"),yt.DEBUG&&console.time("Build stylesheet"),(t.stylesheetCache===null||t.classCache.size!==s)&&(t.stylesheetCache=WA([...t.ruleCache],t)),yt.DEBUG&&console.timeEnd("Build stylesheet");let{defaults:o,base:u,components:c,utilities:f,variants:p}=t.stylesheetCache;r.base&&(r.base.before(Yt([...u,...o],r.base.source,{layer:"base"})),r.base.remove()),r.components&&(r.components.before(Yt([...c],r.components.source,{layer:"components"})),r.components.remove()),r.utilities&&(r.utilities.before(Yt([...f],r.utilities.source,{layer:"utilities"})),r.utilities.remove());let h=Array.from(p).filter(v=>{let S=v.raws.tailwind?.parentLayer;return S==="components"?r.components!==null:S==="utilities"?r.utilities!==null:!0});r.variants?(r.variants.before(Yt(h,r.variants.source,{layer:"variants"})),r.variants.remove()):h.length>0&&e.append(Yt(h,e.source,{layer:"variants"})),e.source.end=e.source.end??e.source.start;let m=h.some(v=>v.raws.tailwind?.parentLayer==="utilities");r.utilities&&f.size===0&&!m&&V.warn("content-problems",["No utility classes were detected in your source files. If this is unexpected, double-check the `content` option in your Tailwind CSS configuration.","https://tailwindcss.com/docs/content-configuration"]),yt.DEBUG&&(console.log("Potential classes: ",i.size),console.log("Active contexts: ",As.size)),t.changedContent=[],e.walkAtRules("layer",v=>{Object.keys(r).includes(v.params)&&v.remove()})}}var iy,yt,ny,sy,zi,ay=A(()=>{l();ft();iy=ce(Aa());Rt();Ls();Ye();Xg();ry();yt=Xe,ny={DEFAULT:ty},sy={DEFAULT:t=>t,svelte:t=>t.replace(/(?:^|\s)class:/g," ")};zi=new WeakMap});function Vs(t){let e=new Map;X.root({nodes:[t.clone()]}).walkRules(s=>{(0,Us.default)(a=>{a.walkClasses(o=>{let u=o.parent.toString(),c=e.get(u);c||e.set(u,c=new Set),c.add(o.value)})}).processSync(s.selector)});let i=Array.from(e.values(),s=>Array.from(s)),n=i.flat();return Object.assign(n,{groups:i})}function au(t){return GA.astSync(t)}function oy(t,e){let r=new Set;for(let i of t)r.add(i.split(e).pop());return Array.from(r)}function ly(t,e){let r=t.tailwindConfig.prefix;return typeof r=="function"?r(e):r+e}function*uy(t){for(yield t;t.parent;)yield t.parent,t=t.parent}function HA(t,e={}){let r=t.nodes;t.nodes=[];let i=t.clone(e);return t.nodes=r,i}function YA(t){for(let e of uy(t))if(t!==e){if(e.type==="root")break;t=HA(e,{nodes:[t]})}return t}function QA(t,e){let r=new Map;return t.walkRules(i=>{for(let a of uy(i))if(a.raws.tailwind?.layer!==void 0)return;let n=YA(i),s=e.offsets.create("user");for(let a of Vs(i)){let o=r.get(a)||[];r.set(a,o),o.push([{layer:"user",sort:s,important:!1},n])}}),r}function JA(t,e){for(let r of t){if(e.notClassCache.has(r)||e.applyClassCache.has(r))continue;if(e.classCache.has(r)){e.applyClassCache.set(r,e.classCache.get(r).map(([n,s])=>[n,s.clone()]));continue}let i=Array.from($l(r,e));if(i.length===0){e.notClassCache.add(r);continue}e.applyClassCache.set(r,i)}return e.applyClassCache}function XA(t){let e=null;return{get:r=>(e=e||t(),e.get(r)),has:r=>(e=e||t(),e.has(r))}}function KA(t){return{get:e=>t.flatMap(r=>r.get(e)||[]),has:e=>t.some(r=>r.has(e))}}function fy(t){let e=t.split(/[\s\t\n]+/g);return e[e.length-1]==="!important"?[e.slice(0,-1),!0]:[e,!1]}function cy(t,e,r){let i=new Set,n=[];if(t.walkAtRules("apply",u=>{let[c]=fy(u.params);for(let f of c)i.add(f);n.push(u)}),n.length===0)return;let s=KA([r,JA(i,e)]);function a(u,c,f){let p=au(u),h=au(c),v=au(`.${Ce(f)}`).nodes[0].nodes[0];return p.each(S=>{let b=new Set;h.each(w=>{let _=!1;w=w.clone(),w.walkClasses(T=>{T.value===v.value&&(_||(T.replaceWith(...S.nodes.map(O=>O.clone())),b.add(w),_=!0))})});for(let w of b){let _=[[]];for(let T of w.nodes)T.type==="combinator"?(_.push(T),_.push([])):_[_.length-1].push(T);w.nodes=[];for(let T of _)Array.isArray(T)&&T.sort((O,E)=>O.type==="tag"&&E.type==="class"?-1:O.type==="class"&&E.type==="tag"?1:O.type==="class"&&E.type==="pseudo"&&E.value.startsWith("::")?-1:O.type==="pseudo"&&O.value.startsWith("::")&&E.type==="class"?1:0),w.nodes=w.nodes.concat(T)}S.replaceWith(...b)}),p.toString()}let o=new Map;for(let u of n){let[c]=o.get(u.parent)||[[],u.source];o.set(u.parent,[c,u.source]);let[f,p]=fy(u.params);if(u.parent.type==="atrule"){if(u.parent.name==="screen"){let h=u.parent.params;throw u.error(`@apply is not supported within nested at-rules like @screen. We suggest you write this as @apply ${f.map(m=>`${h}:${m}`).join(" ")} instead.`)}throw u.error(`@apply is not supported within nested at-rules like @${u.parent.name}. You can fix this by un-nesting @${u.parent.name}.`)}for(let h of f){if([ly(e,"group"),ly(e,"peer")].includes(h))throw u.error(`@apply should not be used with the '${h}' utility`);if(!s.has(h))throw u.error(`The \`${h}\` class does not exist. If \`${h}\` is a custom class, make sure it is defined within a \`@layer\` directive.`);let m=s.get(h);c.push([h,p,m])}}for(let[u,[c,f]]of o){let p=[];for(let[m,v,S]of c){let b=[m,...oy([m],e.tailwindConfig.separator)];for(let[w,_]of S){let T=Vs(u),O=Vs(_);if(O=O.groups.filter(N=>N.some(fe=>b.includes(fe))).flat(),O=O.concat(oy(O,e.tailwindConfig.separator)),T.some(N=>O.includes(N)))throw _.error(`You cannot \`@apply\` the \`${m}\` utility here because it creates a circular dependency.`);let F=X.root({nodes:[_.clone()]});F.walk(N=>{N.source=f}),(_.type!=="atrule"||_.type==="atrule"&&_.name!=="keyframes")&&F.walkRules(N=>{if(!Vs(N).some(W=>W===m)){N.remove();return}let fe=typeof e.tailwindConfig.important=="string"?e.tailwindConfig.important:null,Se=u.raws.tailwind!==void 0&&fe&&u.selector.indexOf(fe)===0?u.selector.slice(fe.length):u.selector;Se===""&&(Se=u.selector),N.selector=a(Se,N.selector,m),fe&&Se!==u.selector&&(N.selector=Is(N.selector,fe)),N.walkDecls(W=>{W.important=w.important||v});let Ve=(0,Us.default)().astSync(N.selector);Ve.each(W=>vr(W)),N.selector=Ve.toString()}),!!F.nodes[0]&&p.push([w.sort,F.nodes[0]])}}let h=e.offsets.sort(p).map(m=>m[1]);u.after(h)}for(let u of n)u.parent.nodes.length>1?u.remove():u.parent.remove();cy(t,e,r)}function ou(t){return e=>{let r=XA(()=>QA(e,t));cy(e,t,r)}}var Us,GA,py=A(()=>{l();It();Us=ce(rt());Ls();gr();Fl();Cs();GA=(0,Us.default)()});var dy=k((i9,Ws)=>{l();(function(){"use strict";function t(i,n,s){if(!i)return null;t.caseSensitive||(i=i.toLowerCase());var a=t.threshold===null?null:t.threshold*i.length,o=t.thresholdAbsolute,u;a!==null&&o!==null?u=Math.min(a,o):a!==null?u=a:o!==null?u=o:u=null;var c,f,p,h,m,v=n.length;for(m=0;m<v;m++)if(f=n[m],s&&(f=f[s]),!!f&&(t.caseSensitive?p=f:p=f.toLowerCase(),h=r(i,p,u),(u===null||h<u)&&(u=h,s&&t.returnWinningObject?c=n[m]:c=f,t.returnFirstMatch)))return c;return c||t.nullResultValue}t.threshold=.4,t.thresholdAbsolute=20,t.caseSensitive=!1,t.nullResultValue=null,t.returnWinningObject=null,t.returnFirstMatch=!1,typeof Ws!="undefined"&&Ws.exports?Ws.exports=t:window.didYouMean=t;var e=Math.pow(2,32)-1;function r(i,n,s){s=s||s===0?s:e;var a=i.length,o=n.length;if(a===0)return Math.min(s+1,o);if(o===0)return Math.min(s+1,a);if(Math.abs(a-o)>s)return s+1;var u=[],c,f,p,h,m;for(c=0;c<=o;c++)u[c]=[c];for(f=0;f<=a;f++)u[0][f]=f;for(c=1;c<=o;c++){for(p=e,h=1,c>s&&(h=c-s),m=o+1,m>s+c&&(m=s+c),f=1;f<=a;f++)f<h||f>m?u[c][f]=s+1:n.charAt(c-1)===i.charAt(f-1)?u[c][f]=u[c-1][f-1]:u[c][f]=Math.min(u[c-1][f-1]+1,Math.min(u[c][f-1]+1,u[c-1][f]+1)),u[c][f]<p&&(p=u[c][f]);if(p>s)return s+1}return u[o][a]}})()});var my=k((n9,hy)=>{l();var lu="(".charCodeAt(0),uu=")".charCodeAt(0),Gs="'".charCodeAt(0),fu='"'.charCodeAt(0),cu="\\".charCodeAt(0),xr="/".charCodeAt(0),pu=",".charCodeAt(0),du=":".charCodeAt(0),Hs="*".charCodeAt(0),ZA="u".charCodeAt(0),eC="U".charCodeAt(0),tC="+".charCodeAt(0),rC=/^[a-f0-9?-]+$/i;hy.exports=function(t){for(var e=[],r=t,i,n,s,a,o,u,c,f,p=0,h=r.charCodeAt(p),m=r.length,v=[{nodes:e}],S=0,b,w="",_="",T="";p<m;)if(h<=32){i=p;do i+=1,h=r.charCodeAt(i);while(h<=32);a=r.slice(p,i),s=e[e.length-1],h===uu&&S?T=a:s&&s.type==="div"?(s.after=a,s.sourceEndIndex+=a.length):h===pu||h===du||h===xr&&r.charCodeAt(i+1)!==Hs&&(!b||b&&b.type==="function"&&!1)?_=a:e.push({type:"space",sourceIndex:p,sourceEndIndex:i,value:a}),p=i}else if(h===Gs||h===fu){i=p,n=h===Gs?"'":'"',a={type:"string",sourceIndex:p,quote:n};do if(o=!1,i=r.indexOf(n,i+1),~i)for(u=i;r.charCodeAt(u-1)===cu;)u-=1,o=!o;else r+=n,i=r.length-1,a.unclosed=!0;while(o);a.value=r.slice(p+1,i),a.sourceEndIndex=a.unclosed?i:i+1,e.push(a),p=i+1,h=r.charCodeAt(p)}else if(h===xr&&r.charCodeAt(p+1)===Hs)i=r.indexOf("*/",p),a={type:"comment",sourceIndex:p,sourceEndIndex:i+2},i===-1&&(a.unclosed=!0,i=r.length,a.sourceEndIndex=i),a.value=r.slice(p+2,i),e.push(a),p=i+2,h=r.charCodeAt(p);else if((h===xr||h===Hs)&&b&&b.type==="function")a=r[p],e.push({type:"word",sourceIndex:p-_.length,sourceEndIndex:p+a.length,value:a}),p+=1,h=r.charCodeAt(p);else if(h===xr||h===pu||h===du)a=r[p],e.push({type:"div",sourceIndex:p-_.length,sourceEndIndex:p+a.length,value:a,before:_,after:""}),_="",p+=1,h=r.charCodeAt(p);else if(lu===h){i=p;do i+=1,h=r.charCodeAt(i);while(h<=32);if(f=p,a={type:"function",sourceIndex:p-w.length,value:w,before:r.slice(f+1,i)},p=i,w==="url"&&h!==Gs&&h!==fu){i-=1;do if(o=!1,i=r.indexOf(")",i+1),~i)for(u=i;r.charCodeAt(u-1)===cu;)u-=1,o=!o;else r+=")",i=r.length-1,a.unclosed=!0;while(o);c=i;do c-=1,h=r.charCodeAt(c);while(h<=32);f<c?(p!==c+1?a.nodes=[{type:"word",sourceIndex:p,sourceEndIndex:c+1,value:r.slice(p,c+1)}]:a.nodes=[],a.unclosed&&c+1!==i?(a.after="",a.nodes.push({type:"space",sourceIndex:c+1,sourceEndIndex:i,value:r.slice(c+1,i)})):(a.after=r.slice(c+1,i),a.sourceEndIndex=i)):(a.after="",a.nodes=[]),p=i+1,a.sourceEndIndex=a.unclosed?i:p,h=r.charCodeAt(p),e.push(a)}else S+=1,a.after="",a.sourceEndIndex=p+1,e.push(a),v.push(a),e=a.nodes=[],b=a;w=""}else if(uu===h&&S)p+=1,h=r.charCodeAt(p),b.after=T,b.sourceEndIndex+=T.length,T="",S-=1,v[v.length-1].sourceEndIndex=p,v.pop(),b=v[S],e=b.nodes;else{i=p;do h===cu&&(i+=1),i+=1,h=r.charCodeAt(i);while(i<m&&!(h<=32||h===Gs||h===fu||h===pu||h===du||h===xr||h===lu||h===Hs&&b&&b.type==="function"&&!0||h===xr&&b.type==="function"&&!0||h===uu&&S));a=r.slice(p,i),lu===h?w=a:(ZA===a.charCodeAt(0)||eC===a.charCodeAt(0))&&tC===a.charCodeAt(1)&&rC.test(a.slice(2))?e.push({type:"unicode-range",sourceIndex:p,sourceEndIndex:i,value:a}):e.push({type:"word",sourceIndex:p,sourceEndIndex:i,value:a}),p=i}for(p=v.length-1;p;p-=1)v[p].unclosed=!0,v[p].sourceEndIndex=r.length;return v[0].nodes}});var yy=k((s9,gy)=>{l();gy.exports=function t(e,r,i){var n,s,a,o;for(n=0,s=e.length;n<s;n+=1)a=e[n],i||(o=r(a,n,e)),o!==!1&&a.type==="function"&&Array.isArray(a.nodes)&&t(a.nodes,r,i),i&&r(a,n,e)}});var xy=k((a9,by)=>{l();function vy(t,e){var r=t.type,i=t.value,n,s;return e&&(s=e(t))!==void 0?s:r==="word"||r==="space"?i:r==="string"?(n=t.quote||"",n+i+(t.unclosed?"":n)):r==="comment"?"/*"+i+(t.unclosed?"":"*/"):r==="div"?(t.before||"")+i+(t.after||""):Array.isArray(t.nodes)?(n=wy(t.nodes,e),r!=="function"?n:i+"("+(t.before||"")+n+(t.after||"")+(t.unclosed?"":")")):i}function wy(t,e){var r,i;if(Array.isArray(t)){for(r="",i=t.length-1;~i;i-=1)r=vy(t[i],e)+r;return r}return vy(t,e)}by.exports=wy});var Sy=k((o9,ky)=>{l();var Ys="-".charCodeAt(0),Qs="+".charCodeAt(0),hu=".".charCodeAt(0),iC="e".charCodeAt(0),nC="E".charCodeAt(0);function sC(t){var e=t.charCodeAt(0),r;if(e===Qs||e===Ys){if(r=t.charCodeAt(1),r>=48&&r<=57)return!0;var i=t.charCodeAt(2);return r===hu&&i>=48&&i<=57}return e===hu?(r=t.charCodeAt(1),r>=48&&r<=57):e>=48&&e<=57}ky.exports=function(t){var e=0,r=t.length,i,n,s;if(r===0||!sC(t))return!1;for(i=t.charCodeAt(e),(i===Qs||i===Ys)&&e++;e<r&&(i=t.charCodeAt(e),!(i<48||i>57));)e+=1;if(i=t.charCodeAt(e),n=t.charCodeAt(e+1),i===hu&&n>=48&&n<=57)for(e+=2;e<r&&(i=t.charCodeAt(e),!(i<48||i>57));)e+=1;if(i=t.charCodeAt(e),n=t.charCodeAt(e+1),s=t.charCodeAt(e+2),(i===iC||i===nC)&&(n>=48&&n<=57||(n===Qs||n===Ys)&&s>=48&&s<=57))for(e+=n===Qs||n===Ys?3:2;e<r&&(i=t.charCodeAt(e),!(i<48||i>57));)e+=1;return{number:t.slice(0,e),unit:t.slice(e)}}});var Ey=k((l9,Oy)=>{l();var aC=my(),_y=yy(),Ty=xy();function Mt(t){return this instanceof Mt?(this.nodes=aC(t),this):new Mt(t)}Mt.prototype.toString=function(){return Array.isArray(this.nodes)?Ty(this.nodes):""};Mt.prototype.walk=function(t,e){return _y(this.nodes,t,e),this};Mt.unit=Sy();Mt.walk=_y;Mt.stringify=Ty;Oy.exports=Mt});function gu(t){return typeof t=="object"&&t!==null}function oC(t,e){let r=Tt(e);do if(r.pop(),(0,$i.default)(t,r)!==void 0)break;while(r.length);return r.length?r:void 0}function kr(t){return typeof t=="string"?t:t.reduce((e,r,i)=>r.includes(".")?`${e}[${r}]`:i===0?r:`${e}.${r}`,"")}function Cy(t){return t.map(e=>`'${e}'`).join(", ")}function Py(t){return Cy(Object.keys(t))}function yu(t,e,r,i={}){let n=Array.isArray(e)?kr(e):e.replace(/^['"]+|['"]+$/g,""),s=Array.isArray(e)?e:Tt(n),a=(0,$i.default)(t.theme,s,r);if(a===void 0){let u=`'${n}' does not exist in your theme config.`,c=s.slice(0,-1),f=(0,$i.default)(t.theme,c);if(gu(f)){let p=Object.keys(f).filter(m=>yu(t,[...c,m]).isValid),h=(0,Ay.default)(s[s.length-1],p);h?u+=` Did you mean '${kr([...c,h])}'?`:p.length>0&&(u+=` '${kr(c)}' has the following valid keys: ${Cy(p)}`)}else{let p=oC(t.theme,n);if(p){let h=(0,$i.default)(t.theme,p);gu(h)?u+=` '${kr(p)}' has the following keys: ${Py(h)}`:u+=` '${kr(p)}' is not an object.`}else u+=` Your theme has the following top-level keys: ${Py(t.theme)}`}return{isValid:!1,error:u}}if(!(typeof a=="string"||typeof a=="number"||typeof a=="function"||a instanceof String||a instanceof Number||Array.isArray(a))){let u=`'${n}' was found but does not resolve to a string.`;if(gu(a)){let c=Object.keys(a).filter(f=>yu(t,[...s,f]).isValid);c.length&&(u+=` Did you mean something like '${kr([...s,c[0]])}'?`)}return{isValid:!1,error:u}}let[o]=s;return{isValid:!0,value:mt(o)(a,i)}}function lC(t,e,r){e=e.map(n=>Iy(t,n,r));let i=[""];for(let n of e)n.type==="div"&&n.value===","?i.push(""):i[i.length-1]+=mu.default.stringify(n);return i}function Iy(t,e,r){if(e.type==="function"&&r[e.value]!==void 0){let i=lC(t,e.nodes,r);e.type="word",e.value=r[e.value](t,...i)}return e}function uC(t,e,r){return Object.keys(r).some(n=>e.includes(`${n}(`))?(0,mu.default)(e).walk(n=>{Iy(t,n,r)}).toString():e}function*cC(t){t=t.replace(/^['"]+|['"]+$/g,"");let e=t.match(/^([^\s]+)(?![^\[]*\])(?:\s*\/\s*([^\/\s]+))$/),r;yield[t,void 0],e&&(t=e[1],r=e[2],yield[t,r])}function pC(t,e,r){let i=Array.from(cC(e)).map(([n,s])=>Object.assign(yu(t,n,r,{opacityValue:s}),{resolvedPath:n,alpha:s}));return i.find(n=>n.isValid)??i[0]}function Dy(t){let e=t.tailwindConfig,r={theme:(i,n,...s)=>{let{isValid:a,value:o,error:u,alpha:c}=pC(e,n,s.length?s:void 0);if(!a){let h=i.parent,m=h?.raws.tailwind?.candidate;if(h&&m!==void 0){t.markInvalidUtilityNode(h),h.remove(),V.warn("invalid-theme-key-in-class",[`The utility \`${m}\` contains an invalid theme value and was not generated.`]);return}throw i.error(u)}let f=ir(o),p=f!==void 0&&typeof f=="function";return(c!==void 0||p)&&(c===void 0&&(c=1),o=Ze(f,c,f)),o},screen:(i,n)=>{n=n.replace(/^['"]+/g,"").replace(/['"]+$/g,"");let a=qt(e.theme.screens).find(({name:o})=>o===n);if(!a)throw i.error(`The '${n}' screen does not exist in your theme.`);return Dt(a)}};return i=>{i.walk(n=>{let s=fC[n.type];s!==void 0&&(n[s]=uC(n,n[s],r))})}}var $i,Ay,mu,fC,qy=A(()=>{l();$i=ce(wo()),Ay=ce(dy());Di();mu=ce(Ey());Os();Ss();On();Gr();Jr();Ye();fC={atrule:"params",decl:"value"}});function Ry({tailwindConfig:{theme:t}}){return function(e){e.walkAtRules("screen",r=>{let i=r.params,s=qt(t.screens).find(({name:a})=>a===i);if(!s)throw r.error(`No \`${i}\` screen found.`);r.name="media",r.params=Dt(s)})}}var Ly=A(()=>{l();Os();Ss()});function dC(t){let e=t.filter(o=>o.type!=="pseudo"||o.nodes.length>0?!0:o.value.startsWith("::")||[":before",":after",":first-line",":first-letter"].includes(o.value)).reverse(),r=new Set(["tag","class","id","attribute"]),i=e.findIndex(o=>r.has(o.type));if(i===-1)return e.reverse().join("").trim();let n=e[i],s=By[n.type]?By[n.type](n):n;e=e.slice(0,i);let a=e.findIndex(o=>o.type==="combinator"&&o.value===">");return a!==-1&&(e.splice(0,a),e.unshift(Js.default.universal())),[s,...e.reverse()].join("").trim()}function mC(t){return vu.has(t)||vu.set(t,hC.transformSync(t)),vu.get(t)}function wu({tailwindConfig:t}){return e=>{let r=new Map,i=new Set;if(e.walkAtRules("defaults",n=>{if(n.nodes&&n.nodes.length>0){i.add(n);return}let s=n.params;r.has(s)||r.set(s,new Set),r.get(s).add(n.parent),n.remove()}),pe(t,"optimizeUniversalDefaults"))for(let n of i){let s=new Map,a=r.get(n.params)??[];for(let o of a)for(let u of mC(o.selector)){let c=u.includes(":-")||u.includes("::-")?u:"__DEFAULT__",f=s.get(c)??new Set;s.set(c,f),f.add(u)}if(pe(t,"optimizeUniversalDefaults")){if(s.size===0){n.remove();continue}for(let[,o]of s){let u=X.rule({source:n.source});u.selectors=[...o],u.append(n.nodes.map(c=>c.clone())),n.before(u)}}n.remove()}else if(i.size){let n=X.rule({selectors:["*","::before","::after"]});for(let a of i)n.append(a.nodes),n.parent||a.before(n),n.source||(n.source=a.source),a.remove();let s=n.clone({selectors:["::backdrop"]});n.after(s)}}}var Js,By,hC,vu,My=A(()=>{l();It();Js=ce(rt());ct();By={id(t){return Js.default.attribute({attribute:"id",operator:"=",value:t.value,quoteMark:'"'})}};hC=(0,Js.default)(t=>t.map(e=>{let r=e.split(i=>i.type==="combinator"&&i.value===" ").pop();return dC(r)})),vu=new Map});function bu(){function t(e){let r=null;e.each(i=>{if(!gC.has(i.type)){r=null;return}if(r===null){r=i;return}let n=Fy[i.type];i.type==="atrule"&&i.name==="font-face"?r=i:n.every(s=>(i[s]??"").replace(/\s+/g," ")===(r[s]??"").replace(/\s+/g," "))?(i.nodes&&r.append(i.nodes),i.remove()):r=i}),e.each(i=>{i.type==="atrule"&&t(i)})}return e=>{t(e)}}var Fy,gC,Ny=A(()=>{l();Fy={atrule:["name","params"],rule:["selector"]},gC=new Set(Object.keys(Fy))});function xu(){return t=>{t.walkRules(e=>{let r=new Map,i=new Set([]),n=new Map;e.walkDecls(s=>{if(s.parent===e){if(r.has(s.prop)){if(r.get(s.prop).value===s.value){i.add(r.get(s.prop)),r.set(s.prop,s);return}n.has(s.prop)||n.set(s.prop,new Set),n.get(s.prop).add(r.get(s.prop)),n.get(s.prop).add(s)}r.set(s.prop,s)}});for(let s of i)s.remove();for(let s of n.values()){let a=new Map;for(let o of s){let u=vC(o.value);u!==null&&(a.has(u)||a.set(u,new Set),a.get(u).add(o))}for(let o of a.values()){let u=Array.from(o).slice(0,-1);for(let c of u)c.remove()}}})}}function vC(t){let e=/^-?\d*.?\d+([\w%]+)?$/g.exec(t);return e?e[1]??yC:null}var yC,zy=A(()=>{l();yC=Symbol("unitless-number")});function wC(t){if(!t.walkAtRules)return;let e=new Set;if(t.walkAtRules("apply",r=>{e.add(r.parent)}),e.size!==0)for(let r of e){let i=[],n=[];for(let s of r.nodes)s.type==="atrule"&&s.name==="apply"?(n.length>0&&(i.push(n),n=[]),i.push([s])):n.push(s);if(n.length>0&&i.push(n),i.length!==1){for(let s of[...i].reverse()){let a=r.clone({nodes:[]});a.append(s),r.after(a)}r.remove()}}}function Xs(){return t=>{wC(t)}}var $y=A(()=>{l()});function bC(t){return t.type==="root"}function xC(t){return t.type==="atrule"&&t.name==="layer"}function jy(t){return(e,r)=>{let i=!1;e.walkAtRules("tailwind",n=>{if(i)return!1;if(n.parent&&!(bC(n.parent)||xC(n.parent)))return i=!0,n.warn(r,["Nested @tailwind rules were detected, but are not supported.","Consider using a prefix to scope Tailwind's classes: https://tailwindcss.com/docs/configuration#prefix","Alternatively, use the important selector strategy: https://tailwindcss.com/docs/configuration#selector-strategy"].join(`
`)),!1}),e.walkRules(n=>{if(i)return!1;n.walkRules(s=>(i=!0,s.warn(r,["Nested CSS was detected, but CSS nesting has not been configured correctly.","Please enable a CSS nesting plugin *before* Tailwind in your configuration.","See how here: https://tailwindcss.com/docs/using-with-preprocessors#nesting"].join(`
`)),!1))})}}var Uy=A(()=>{l()});function Ks(t){return async function(e,r){let{tailwindDirectives:i,applyDirectives:n}=ru(e);jy()(e,r),Xs()(e,r);let s=t({tailwindDirectives:i,applyDirectives:n,registerDependency(a){r.messages.push({plugin:"tailwindcss",parent:r.opts.from,...a})},createContext(a,o){return Ql(a,o,e)}})(e,r);if(s.tailwindConfig.separator==="-")throw new Error("The '-' character cannot be used as a custom separator in JIT mode due to parsing ambiguity. Please use another character like '_' instead.");lp(s.tailwindConfig),await su(s)(e,r),Xs()(e,r),ou(s)(e,r),Dy(s)(e,r),Ry(s)(e,r),wu(s)(e,r),bu(s)(e,r),xu(s)(e,r)}}var Vy=A(()=>{l();Qg();ay();py();qy();Ly();My();Ny();zy();$y();Uy();Bi();ct()});function Wy(t,e){let r=null,i=null;return t.walkAtRules("config",n=>{if(i=n.source?.input.file??e.opts.from??null,i===null)throw n.error("The `@config` directive cannot be used without setting `from` in your PostCSS config.");if(r)throw n.error("Only one `@config` directive is allowed per file.");let s=n.params.match(/(['"])(.*?)\1/);if(!s)throw n.error("A path is required when using the `@config` directive.");let a=s[2];if(de.isAbsolute(a))throw n.error("The `@config` directive cannot be used with an absolute path.");if(r=de.resolve(de.dirname(i),a),!me.existsSync(r))throw n.error(`The config file at "${a}" does not exist. Make sure the path is correct and the file exists.`);n.remove()}),r||null}var Gy=A(()=>{l();ft();Ut()});var Hy=k((H9,ku)=>{l();Yg();Vy();Rt();Gy();ku.exports=function(e){return{postcssPlugin:"tailwindcss",plugins:[Xe.DEBUG&&function(r){return console.log(`
`),console.time("JIT TOTAL"),r},async function(r,i){e=Wy(r,i)??e;let n=tu(e);if(r.type==="document"){let s=r.nodes.filter(a=>a.type==="root");for(let a of s)a.type==="root"&&await Ks(n)(a,i);return}await Ks(n)(r,i)},!1,Xe.DEBUG&&function(r){return console.timeEnd("JIT TOTAL"),console.log(`
`),r}].filter(Boolean)}};ku.exports.postcss=!0});var Qy=k((Y9,Yy)=>{l();Yy.exports=Hy()});var Su=k((Q9,Jy)=>{l();Jy.exports=()=>["and_chr 114","and_uc 15.5","chrome 114","chrome 113","chrome 109","edge 114","firefox 114","ios_saf 16.5","ios_saf 16.4","ios_saf 16.3","ios_saf 16.1","opera 99","safari 16.5","samsung 21"]});var Zs={};Ge(Zs,{agents:()=>kC,feature:()=>SC});function SC(){return{status:"cr",title:"CSS Feature Queries",stats:{ie:{"6":"n","7":"n","8":"n","9":"n","10":"n","11":"n","5.5":"n"},edge:{"12":"y","13":"y","14":"y","15":"y","16":"y","17":"y","18":"y","79":"y","80":"y","81":"y","83":"y","84":"y","85":"y","86":"y","87":"y","88":"y","89":"y","90":"y","91":"y","92":"y","93":"y","94":"y","95":"y","96":"y","97":"y","98":"y","99":"y","100":"y","101":"y","102":"y","103":"y","104":"y","105":"y","106":"y","107":"y","108":"y","109":"y","110":"y","111":"y","112":"y","113":"y","114":"y"},firefox:{"2":"n","3":"n","4":"n","5":"n","6":"n","7":"n","8":"n","9":"n","10":"n","11":"n","12":"n","13":"n","14":"n","15":"n","16":"n","17":"n","18":"n","19":"n","20":"n","21":"n","22":"y","23":"y","24":"y","25":"y","26":"y","27":"y","28":"y","29":"y","30":"y","31":"y","32":"y","33":"y","34":"y","35":"y","36":"y","37":"y","38":"y","39":"y","40":"y","41":"y","42":"y","43":"y","44":"y","45":"y","46":"y","47":"y","48":"y","49":"y","50":"y","51":"y","52":"y","53":"y","54":"y","55":"y","56":"y","57":"y","58":"y","59":"y","60":"y","61":"y","62":"y","63":"y","64":"y","65":"y","66":"y","67":"y","68":"y","69":"y","70":"y","71":"y","72":"y","73":"y","74":"y","75":"y","76":"y","77":"y","78":"y","79":"y","80":"y","81":"y","82":"y","83":"y","84":"y","85":"y","86":"y","87":"y","88":"y","89":"y","90":"y","91":"y","92":"y","93":"y","94":"y","95":"y","96":"y","97":"y","98":"y","99":"y","100":"y","101":"y","102":"y","103":"y","104":"y","105":"y","106":"y","107":"y","108":"y","109":"y","110":"y","111":"y","112":"y","113":"y","114":"y","115":"y","116":"y","117":"y","3.5":"n","3.6":"n"},chrome:{"4":"n","5":"n","6":"n","7":"n","8":"n","9":"n","10":"n","11":"n","12":"n","13":"n","14":"n","15":"n","16":"n","17":"n","18":"n","19":"n","20":"n","21":"n","22":"n","23":"n","24":"n","25":"n","26":"n","27":"n","28":"y","29":"y","30":"y","31":"y","32":"y","33":"y","34":"y","35":"y","36":"y","37":"y","38":"y","39":"y","40":"y","41":"y","42":"y","43":"y","44":"y","45":"y","46":"y","47":"y","48":"y","49":"y","50":"y","51":"y","52":"y","53":"y","54":"y","55":"y","56":"y","57":"y","58":"y","59":"y","60":"y","61":"y","62":"y","63":"y","64":"y","65":"y","66":"y","67":"y","68":"y","69":"y","70":"y","71":"y","72":"y","73":"y","74":"y","75":"y","76":"y","77":"y","78":"y","79":"y","80":"y","81":"y","83":"y","84":"y","85":"y","86":"y","87":"y","88":"y","89":"y","90":"y","91":"y","92":"y","93":"y","94":"y","95":"y","96":"y","97":"y","98":"y","99":"y","100":"y","101":"y","102":"y","103":"y","104":"y","105":"y","106":"y","107":"y","108":"y","109":"y","110":"y","111":"y","112":"y","113":"y","114":"y","115":"y","116":"y","117":"y"},safari:{"4":"n","5":"n","6":"n","7":"n","8":"n","9":"y","10":"y","11":"y","12":"y","13":"y","14":"y","15":"y","17":"y","9.1":"y","10.1":"y","11.1":"y","12.1":"y","13.1":"y","14.1":"y","15.1":"y","15.2-15.3":"y","15.4":"y","15.5":"y","15.6":"y","16.0":"y","16.1":"y","16.2":"y","16.3":"y","16.4":"y","16.5":"y","16.6":"y",TP:"y","3.1":"n","3.2":"n","5.1":"n","6.1":"n","7.1":"n"},opera:{"9":"n","11":"n","12":"n","15":"y","16":"y","17":"y","18":"y","19":"y","20":"y","21":"y","22":"y","23":"y","24":"y","25":"y","26":"y","27":"y","28":"y","29":"y","30":"y","31":"y","32":"y","33":"y","34":"y","35":"y","36":"y","37":"y","38":"y","39":"y","40":"y","41":"y","42":"y","43":"y","44":"y","45":"y","46":"y","47":"y","48":"y","49":"y","50":"y","51":"y","52":"y","53":"y","54":"y","55":"y","56":"y","57":"y","58":"y","60":"y","62":"y","63":"y","64":"y","65":"y","66":"y","67":"y","68":"y","69":"y","70":"y","71":"y","72":"y","73":"y","74":"y","75":"y","76":"y","77":"y","78":"y","79":"y","80":"y","81":"y","82":"y","83":"y","84":"y","85":"y","86":"y","87":"y","88":"y","89":"y","90":"y","91":"y","92":"y","93":"y","94":"y","95":"y","96":"y","97":"y","98":"y","99":"y","100":"y","12.1":"y","9.5-9.6":"n","10.0-10.1":"n","10.5":"n","10.6":"n","11.1":"n","11.5":"n","11.6":"n"},ios_saf:{"8":"n","17":"y","9.0-9.2":"y","9.3":"y","10.0-10.2":"y","10.3":"y","11.0-11.2":"y","11.3-11.4":"y","12.0-12.1":"y","12.2-12.5":"y","13.0-13.1":"y","13.2":"y","13.3":"y","13.4-13.7":"y","14.0-14.4":"y","14.5-14.8":"y","15.0-15.1":"y","15.2-15.3":"y","15.4":"y","15.5":"y","15.6":"y","16.0":"y","16.1":"y","16.2":"y","16.3":"y","16.4":"y","16.5":"y","16.6":"y","3.2":"n","4.0-4.1":"n","4.2-4.3":"n","5.0-5.1":"n","6.0-6.1":"n","7.0-7.1":"n","8.1-8.4":"n"},op_mini:{all:"y"},android:{"3":"n","4":"n","114":"y","4.4":"y","4.4.3-4.4.4":"y","2.1":"n","2.2":"n","2.3":"n","4.1":"n","4.2-4.3":"n"},bb:{"7":"n","10":"n"},op_mob:{"10":"n","11":"n","12":"n","73":"y","11.1":"n","11.5":"n","12.1":"n"},and_chr:{"114":"y"},and_ff:{"115":"y"},ie_mob:{"10":"n","11":"n"},and_uc:{"15.5":"y"},samsung:{"4":"y","20":"y","21":"y","5.0-5.4":"y","6.2-6.4":"y","7.2-7.4":"y","8.2":"y","9.2":"y","10.1":"y","11.1-11.2":"y","12.0":"y","13.0":"y","14.0":"y","15.0":"y","16.0":"y","17.0":"y","18.0":"y","19.0":"y"},and_qq:{"13.1":"y"},baidu:{"13.18":"y"},kaios:{"2.5":"y","3.0-3.1":"y"}}}}var kC,ea=A(()=>{l();kC={ie:{prefix:"ms"},edge:{prefix:"webkit",prefix_exceptions:{"12":"ms","13":"ms","14":"ms","15":"ms","16":"ms","17":"ms","18":"ms"}},firefox:{prefix:"moz"},chrome:{prefix:"webkit"},safari:{prefix:"webkit"},opera:{prefix:"webkit",prefix_exceptions:{"9":"o","11":"o","12":"o","9.5-9.6":"o","10.0-10.1":"o","10.5":"o","10.6":"o","11.1":"o","11.5":"o","11.6":"o","12.1":"o"}},ios_saf:{prefix:"webkit"},op_mini:{prefix:"o"},android:{prefix:"webkit"},bb:{prefix:"webkit"},op_mob:{prefix:"o",prefix_exceptions:{"73":"webkit"}},and_chr:{prefix:"webkit"},and_ff:{prefix:"moz"},ie_mob:{prefix:"ms"},and_uc:{prefix:"webkit",prefix_exceptions:{"15.5":"webkit"}},samsung:{prefix:"webkit"},and_qq:{prefix:"webkit"},baidu:{prefix:"webkit"},kaios:{prefix:"moz"}}});var Xy=k(()=>{l()});var Oe=k((K9,Ft)=>{l();var{list:_u}=qe();Ft.exports.error=function(t){let e=new Error(t);throw e.autoprefixer=!0,e};Ft.exports.uniq=function(t){return[...new Set(t)]};Ft.exports.removeNote=function(t){return t.includes(" ")?t.split(" ")[0]:t};Ft.exports.escapeRegexp=function(t){return t.replace(/[$()*+-.?[\\\]^{|}]/g,"\\$&")};Ft.exports.regexp=function(t,e=!0){return e&&(t=this.escapeRegexp(t)),new RegExp(`(^|[\\s,(])(${t}($|[\\s(,]))`,"gi")};Ft.exports.editList=function(t,e){let r=_u.comma(t),i=e(r,[]);if(r===i)return t;let n=t.match(/,\s*/);return n=n?n[0]:", ",i.join(n)};Ft.exports.splitSelector=function(t){return _u.comma(t).map(e=>_u.space(e).map(r=>r.split(/(?=\.|#)/g)))}});var Nt=k((Z9,ev)=>{l();var _C=Su(),Ky=(ea(),Zs).agents,TC=Oe(),Zy=class{static prefixes(){if(this.prefixesCache)return this.prefixesCache;this.prefixesCache=[];for(let e in Ky)this.prefixesCache.push(`-${Ky[e].prefix}-`);return this.prefixesCache=TC.uniq(this.prefixesCache).sort((e,r)=>r.length-e.length),this.prefixesCache}static withPrefix(e){return this.prefixesRegexp||(this.prefixesRegexp=new RegExp(this.prefixes().join("|"))),this.prefixesRegexp.test(e)}constructor(e,r,i,n){this.data=e,this.options=i||{},this.browserslistOpts=n||{},this.selected=this.parse(r)}parse(e){let r={};for(let i in this.browserslistOpts)r[i]=this.browserslistOpts[i];return r.path=this.options.from,_C(e,r)}prefix(e){let[r,i]=e.split(" "),n=this.data[r],s=n.prefix_exceptions&&n.prefix_exceptions[i];return s||(s=n.prefix),`-${s}-`}isSelected(e){return this.selected.includes(e)}};ev.exports=Zy});var ji=k((ez,tv)=>{l();tv.exports={prefix(t){let e=t.match(/^(-\w+-)/);return e?e[0]:""},unprefixed(t){return t.replace(/^-\w+-/,"")}}});var Sr=k((tz,iv)=>{l();var OC=Nt(),rv=ji(),EC=Oe();function Tu(t,e){let r=new t.constructor;for(let i of Object.keys(t||{})){let n=t[i];i==="parent"&&typeof n=="object"?e&&(r[i]=e):i==="source"||i===null?r[i]=n:Array.isArray(n)?r[i]=n.map(s=>Tu(s,r)):i!=="_autoprefixerPrefix"&&i!=="_autoprefixerValues"&&i!=="proxyCache"&&(typeof n=="object"&&n!==null&&(n=Tu(n,r)),r[i]=n)}return r}var ta=class{static hack(e){return this.hacks||(this.hacks={}),e.names.map(r=>(this.hacks[r]=e,this.hacks[r]))}static load(e,r,i){let n=this.hacks&&this.hacks[e];return n?new n(e,r,i):new this(e,r,i)}static clone(e,r){let i=Tu(e);for(let n in r)i[n]=r[n];return i}constructor(e,r,i){this.prefixes=r,this.name=e,this.all=i}parentPrefix(e){let r;return typeof e._autoprefixerPrefix!="undefined"?r=e._autoprefixerPrefix:e.type==="decl"&&e.prop[0]==="-"?r=rv.prefix(e.prop):e.type==="root"?r=!1:e.type==="rule"&&e.selector.includes(":-")&&/:(-\w+-)/.test(e.selector)?r=e.selector.match(/:(-\w+-)/)[1]:e.type==="atrule"&&e.name[0]==="-"?r=rv.prefix(e.name):r=this.parentPrefix(e.parent),OC.prefixes().includes(r)||(r=!1),e._autoprefixerPrefix=r,e._autoprefixerPrefix}process(e,r){if(!this.check(e))return;let i=this.parentPrefix(e),n=this.prefixes.filter(a=>!i||i===EC.removeNote(a)),s=[];for(let a of n)this.add(e,a,s.concat([a]),r)&&s.push(a);return s}clone(e,r){return ta.clone(e,r)}};iv.exports=ta});var j=k((rz,av)=>{l();var AC=Sr(),CC=Nt(),nv=Oe(),sv=class extends AC{check(){return!0}prefixed(e,r){return r+e}normalize(e){return e}otherPrefixes(e,r){for(let i of CC.prefixes())if(i!==r&&e.includes(i))return!0;return!1}set(e,r){return e.prop=this.prefixed(e.prop,r),e}needCascade(e){return e._autoprefixerCascade||(e._autoprefixerCascade=this.all.options.cascade!==!1&&e.raw("before").includes(`
`)),e._autoprefixerCascade}maxPrefixed(e,r){if(r._autoprefixerMax)return r._autoprefixerMax;let i=0;for(let n of e)n=nv.removeNote(n),n.length>i&&(i=n.length);return r._autoprefixerMax=i,r._autoprefixerMax}calcBefore(e,r,i=""){let s=this.maxPrefixed(e,r)-nv.removeNote(i).length,a=r.raw("before");return s>0&&(a+=Array(s).fill(" ").join("")),a}restoreBefore(e){let r=e.raw("before").split(`
`),i=r[r.length-1];this.all.group(e).up(n=>{let s=n.raw("before").split(`
`),a=s[s.length-1];a.length<i.length&&(i=a)}),r[r.length-1]=i,e.raws.before=r.join(`
`)}insert(e,r,i){let n=this.set(this.clone(e),r);if(!(!n||e.parent.some(a=>a.prop===n.prop&&a.value===n.value)))return this.needCascade(e)&&(n.raws.before=this.calcBefore(i,e,r)),e.parent.insertBefore(e,n)}isAlready(e,r){let i=this.all.group(e).up(n=>n.prop===r);return i||(i=this.all.group(e).down(n=>n.prop===r)),i}add(e,r,i,n){let s=this.prefixed(e.prop,r);if(!(this.isAlready(e,s)||this.otherPrefixes(e.value,r)))return this.insert(e,r,i,n)}process(e,r){if(!this.needCascade(e)){super.process(e,r);return}let i=super.process(e,r);!i||!i.length||(this.restoreBefore(e),e.raws.before=this.calcBefore(i,e))}old(e,r){return[this.prefixed(e,r)]}};av.exports=sv});var lv=k((iz,ov)=>{l();ov.exports=function t(e){return{mul:r=>new t(e*r),div:r=>new t(e/r),simplify:()=>new t(e),toString:()=>e.toString()}}});var cv=k((nz,fv)=>{l();var PC=lv(),IC=Sr(),Ou=Oe(),DC=/(min|max)-resolution\s*:\s*\d*\.?\d+(dppx|dpcm|dpi|x)/gi,qC=/(min|max)-resolution(\s*:\s*)(\d*\.?\d+)(dppx|dpcm|dpi|x)/i,uv=class extends IC{prefixName(e,r){return e==="-moz-"?r+"--moz-device-pixel-ratio":e+r+"-device-pixel-ratio"}prefixQuery(e,r,i,n,s){return n=new PC(n),s==="dpi"?n=n.div(96):s==="dpcm"&&(n=n.mul(2.54).div(96)),n=n.simplify(),e==="-o-"&&(n=n.n+"/"+n.d),this.prefixName(e,r)+i+n}clean(e){if(!this.bad){this.bad=[];for(let r of this.prefixes)this.bad.push(this.prefixName(r,"min")),this.bad.push(this.prefixName(r,"max"))}e.params=Ou.editList(e.params,r=>r.filter(i=>this.bad.every(n=>!i.includes(n))))}process(e){let r=this.parentPrefix(e),i=r?[r]:this.prefixes;e.params=Ou.editList(e.params,(n,s)=>{for(let a of n){if(!a.includes("min-resolution")&&!a.includes("max-resolution")){s.push(a);continue}for(let o of i){let u=a.replace(DC,c=>{let f=c.match(qC);return this.prefixQuery(o,f[1],f[2],f[3],f[4])});s.push(u)}s.push(a)}return Ou.uniq(s)})}};fv.exports=uv});var dv=k((sz,pv)=>{l();var Eu="(".charCodeAt(0),Au=")".charCodeAt(0),ra="'".charCodeAt(0),Cu='"'.charCodeAt(0),Pu="\\".charCodeAt(0),_r="/".charCodeAt(0),Iu=",".charCodeAt(0),Du=":".charCodeAt(0),ia="*".charCodeAt(0),RC="u".charCodeAt(0),LC="U".charCodeAt(0),BC="+".charCodeAt(0),MC=/^[a-f0-9?-]+$/i;pv.exports=function(t){for(var e=[],r=t,i,n,s,a,o,u,c,f,p=0,h=r.charCodeAt(p),m=r.length,v=[{nodes:e}],S=0,b,w="",_="",T="";p<m;)if(h<=32){i=p;do i+=1,h=r.charCodeAt(i);while(h<=32);a=r.slice(p,i),s=e[e.length-1],h===Au&&S?T=a:s&&s.type==="div"?(s.after=a,s.sourceEndIndex+=a.length):h===Iu||h===Du||h===_r&&r.charCodeAt(i+1)!==ia&&(!b||b&&b.type==="function"&&b.value!=="calc")?_=a:e.push({type:"space",sourceIndex:p,sourceEndIndex:i,value:a}),p=i}else if(h===ra||h===Cu){i=p,n=h===ra?"'":'"',a={type:"string",sourceIndex:p,quote:n};do if(o=!1,i=r.indexOf(n,i+1),~i)for(u=i;r.charCodeAt(u-1)===Pu;)u-=1,o=!o;else r+=n,i=r.length-1,a.unclosed=!0;while(o);a.value=r.slice(p+1,i),a.sourceEndIndex=a.unclosed?i:i+1,e.push(a),p=i+1,h=r.charCodeAt(p)}else if(h===_r&&r.charCodeAt(p+1)===ia)i=r.indexOf("*/",p),a={type:"comment",sourceIndex:p,sourceEndIndex:i+2},i===-1&&(a.unclosed=!0,i=r.length,a.sourceEndIndex=i),a.value=r.slice(p+2,i),e.push(a),p=i+2,h=r.charCodeAt(p);else if((h===_r||h===ia)&&b&&b.type==="function"&&b.value==="calc")a=r[p],e.push({type:"word",sourceIndex:p-_.length,sourceEndIndex:p+a.length,value:a}),p+=1,h=r.charCodeAt(p);else if(h===_r||h===Iu||h===Du)a=r[p],e.push({type:"div",sourceIndex:p-_.length,sourceEndIndex:p+a.length,value:a,before:_,after:""}),_="",p+=1,h=r.charCodeAt(p);else if(Eu===h){i=p;do i+=1,h=r.charCodeAt(i);while(h<=32);if(f=p,a={type:"function",sourceIndex:p-w.length,value:w,before:r.slice(f+1,i)},p=i,w==="url"&&h!==ra&&h!==Cu){i-=1;do if(o=!1,i=r.indexOf(")",i+1),~i)for(u=i;r.charCodeAt(u-1)===Pu;)u-=1,o=!o;else r+=")",i=r.length-1,a.unclosed=!0;while(o);c=i;do c-=1,h=r.charCodeAt(c);while(h<=32);f<c?(p!==c+1?a.nodes=[{type:"word",sourceIndex:p,sourceEndIndex:c+1,value:r.slice(p,c+1)}]:a.nodes=[],a.unclosed&&c+1!==i?(a.after="",a.nodes.push({type:"space",sourceIndex:c+1,sourceEndIndex:i,value:r.slice(c+1,i)})):(a.after=r.slice(c+1,i),a.sourceEndIndex=i)):(a.after="",a.nodes=[]),p=i+1,a.sourceEndIndex=a.unclosed?i:p,h=r.charCodeAt(p),e.push(a)}else S+=1,a.after="",a.sourceEndIndex=p+1,e.push(a),v.push(a),e=a.nodes=[],b=a;w=""}else if(Au===h&&S)p+=1,h=r.charCodeAt(p),b.after=T,b.sourceEndIndex+=T.length,T="",S-=1,v[v.length-1].sourceEndIndex=p,v.pop(),b=v[S],e=b.nodes;else{i=p;do h===Pu&&(i+=1),i+=1,h=r.charCodeAt(i);while(i<m&&!(h<=32||h===ra||h===Cu||h===Iu||h===Du||h===_r||h===Eu||h===ia&&b&&b.type==="function"&&b.value==="calc"||h===_r&&b.type==="function"&&b.value==="calc"||h===Au&&S));a=r.slice(p,i),Eu===h?w=a:(RC===a.charCodeAt(0)||LC===a.charCodeAt(0))&&BC===a.charCodeAt(1)&&MC.test(a.slice(2))?e.push({type:"unicode-range",sourceIndex:p,sourceEndIndex:i,value:a}):e.push({type:"word",sourceIndex:p,sourceEndIndex:i,value:a}),p=i}for(p=v.length-1;p;p-=1)v[p].unclosed=!0,v[p].sourceEndIndex=r.length;return v[0].nodes}});var mv=k((az,hv)=>{l();hv.exports=function t(e,r,i){var n,s,a,o;for(n=0,s=e.length;n<s;n+=1)a=e[n],i||(o=r(a,n,e)),o!==!1&&a.type==="function"&&Array.isArray(a.nodes)&&t(a.nodes,r,i),i&&r(a,n,e)}});var wv=k((oz,vv)=>{l();function gv(t,e){var r=t.type,i=t.value,n,s;return e&&(s=e(t))!==void 0?s:r==="word"||r==="space"?i:r==="string"?(n=t.quote||"",n+i+(t.unclosed?"":n)):r==="comment"?"/*"+i+(t.unclosed?"":"*/"):r==="div"?(t.before||"")+i+(t.after||""):Array.isArray(t.nodes)?(n=yv(t.nodes,e),r!=="function"?n:i+"("+(t.before||"")+n+(t.after||"")+(t.unclosed?"":")")):i}function yv(t,e){var r,i;if(Array.isArray(t)){for(r="",i=t.length-1;~i;i-=1)r=gv(t[i],e)+r;return r}return gv(t,e)}vv.exports=yv});var xv=k((lz,bv)=>{l();var na="-".charCodeAt(0),sa="+".charCodeAt(0),qu=".".charCodeAt(0),FC="e".charCodeAt(0),NC="E".charCodeAt(0);function zC(t){var e=t.charCodeAt(0),r;if(e===sa||e===na){if(r=t.charCodeAt(1),r>=48&&r<=57)return!0;var i=t.charCodeAt(2);return r===qu&&i>=48&&i<=57}return e===qu?(r=t.charCodeAt(1),r>=48&&r<=57):e>=48&&e<=57}bv.exports=function(t){var e=0,r=t.length,i,n,s;if(r===0||!zC(t))return!1;for(i=t.charCodeAt(e),(i===sa||i===na)&&e++;e<r&&(i=t.charCodeAt(e),!(i<48||i>57));)e+=1;if(i=t.charCodeAt(e),n=t.charCodeAt(e+1),i===qu&&n>=48&&n<=57)for(e+=2;e<r&&(i=t.charCodeAt(e),!(i<48||i>57));)e+=1;if(i=t.charCodeAt(e),n=t.charCodeAt(e+1),s=t.charCodeAt(e+2),(i===FC||i===NC)&&(n>=48&&n<=57||(n===sa||n===na)&&s>=48&&s<=57))for(e+=n===sa||n===na?3:2;e<r&&(i=t.charCodeAt(e),!(i<48||i>57));)e+=1;return{number:t.slice(0,e),unit:t.slice(e)}}});var aa=k((uz,_v)=>{l();var $C=dv(),kv=mv(),Sv=wv();function zt(t){return this instanceof zt?(this.nodes=$C(t),this):new zt(t)}zt.prototype.toString=function(){return Array.isArray(this.nodes)?Sv(this.nodes):""};zt.prototype.walk=function(t,e){return kv(this.nodes,t,e),this};zt.unit=xv();zt.walk=kv;zt.stringify=Sv;_v.exports=zt});var Cv=k((fz,Av)=>{l();var{list:jC}=qe(),Tv=aa(),UC=Nt(),Ov=ji(),Ev=class{constructor(e){this.props=["transition","transition-property"],this.prefixes=e}add(e,r){let i,n,s=this.prefixes.add[e.prop],a=this.ruleVendorPrefixes(e),o=a||s&&s.prefixes||[],u=this.parse(e.value),c=u.map(m=>this.findProp(m)),f=[];if(c.some(m=>m[0]==="-"))return;for(let m of u){if(n=this.findProp(m),n[0]==="-")continue;let v=this.prefixes.add[n];if(!(!v||!v.prefixes))for(i of v.prefixes){if(a&&!a.some(b=>i.includes(b)))continue;let S=this.prefixes.prefixed(n,i);S!=="-ms-transform"&&!c.includes(S)&&(this.disabled(n,i)||f.push(this.clone(n,S,m)))}}u=u.concat(f);let p=this.stringify(u),h=this.stringify(this.cleanFromUnprefixed(u,"-webkit-"));if(o.includes("-webkit-")&&this.cloneBefore(e,`-webkit-${e.prop}`,h),this.cloneBefore(e,e.prop,h),o.includes("-o-")){let m=this.stringify(this.cleanFromUnprefixed(u,"-o-"));this.cloneBefore(e,`-o-${e.prop}`,m)}for(i of o)if(i!=="-webkit-"&&i!=="-o-"){let m=this.stringify(this.cleanOtherPrefixes(u,i));this.cloneBefore(e,i+e.prop,m)}p!==e.value&&!this.already(e,e.prop,p)&&(this.checkForWarning(r,e),e.cloneBefore(),e.value=p)}findProp(e){let r=e[0].value;if(/^\d/.test(r)){for(let[i,n]of e.entries())if(i!==0&&n.type==="word")return n.value}return r}already(e,r,i){return e.parent.some(n=>n.prop===r&&n.value===i)}cloneBefore(e,r,i){this.already(e,r,i)||e.cloneBefore({prop:r,value:i})}checkForWarning(e,r){if(r.prop!=="transition-property")return;let i=!1,n=!1;r.parent.each(s=>{if(s.type!=="decl"||s.prop.indexOf("transition-")!==0)return;let a=jC.comma(s.value);if(s.prop==="transition-property"){a.forEach(o=>{let u=this.prefixes.add[o];u&&u.prefixes&&u.prefixes.length>0&&(i=!0)});return}return n=n||a.length>1,!1}),i&&n&&r.warn(e,"Replace transition-property to transition, because Autoprefixer could not support any cases of transition-property and other transition-*")}remove(e){let r=this.parse(e.value);r=r.filter(a=>{let o=this.prefixes.remove[this.findProp(a)];return!o||!o.remove});let i=this.stringify(r);if(e.value===i)return;if(r.length===0){e.remove();return}let n=e.parent.some(a=>a.prop===e.prop&&a.value===i),s=e.parent.some(a=>a!==e&&a.prop===e.prop&&a.value.length>i.length);if(n||s){e.remove();return}e.value=i}parse(e){let r=Tv(e),i=[],n=[];for(let s of r.nodes)n.push(s),s.type==="div"&&s.value===","&&(i.push(n),n=[]);return i.push(n),i.filter(s=>s.length>0)}stringify(e){if(e.length===0)return"";let r=[];for(let i of e)i[i.length-1].type!=="div"&&i.push(this.div(e)),r=r.concat(i);return r[0].type==="div"&&(r=r.slice(1)),r[r.length-1].type==="div"&&(r=r.slice(0,-2+1||void 0)),Tv.stringify({nodes:r})}clone(e,r,i){let n=[],s=!1;for(let a of i)!s&&a.type==="word"&&a.value===e?(n.push({type:"word",value:r}),s=!0):n.push(a);return n}div(e){for(let r of e)for(let i of r)if(i.type==="div"&&i.value===",")return i;return{type:"div",value:",",after:" "}}cleanOtherPrefixes(e,r){return e.filter(i=>{let n=Ov.prefix(this.findProp(i));return n===""||n===r})}cleanFromUnprefixed(e,r){let i=e.map(s=>this.findProp(s)).filter(s=>s.slice(0,r.length)===r).map(s=>this.prefixes.unprefixed(s)),n=[];for(let s of e){let a=this.findProp(s),o=Ov.prefix(a);!i.includes(a)&&(o===r||o==="")&&n.push(s)}return n}disabled(e,r){let i=["order","justify-content","align-self","align-content"];if(e.includes("flex")||i.includes(e)){if(this.prefixes.options.flexbox===!1)return!0;if(this.prefixes.options.flexbox==="no-2009")return r.includes("2009")}}ruleVendorPrefixes(e){let{parent:r}=e;if(r.type!=="rule")return!1;if(!r.selector.includes(":-"))return!1;let i=UC.prefixes().filter(n=>r.selector.includes(":"+n));return i.length>0?i:!1}};Av.exports=Ev});var Tr=k((cz,Iv)=>{l();var VC=Oe(),Pv=class{constructor(e,r,i,n){this.unprefixed=e,this.prefixed=r,this.string=i||r,this.regexp=n||VC.regexp(r)}check(e){return e.includes(this.string)?!!e.match(this.regexp):!1}};Iv.exports=Pv});var Ne=k((pz,qv)=>{l();var WC=Sr(),GC=Tr(),HC=ji(),YC=Oe(),Dv=class extends WC{static save(e,r){let i=r.prop,n=[];for(let s in r._autoprefixerValues){let a=r._autoprefixerValues[s];if(a===r.value)continue;let o,u=HC.prefix(i);if(u==="-pie-")continue;if(u===s){o=r.value=a,n.push(o);continue}let c=e.prefixed(i,s),f=r.parent;if(!f.every(v=>v.prop!==c)){n.push(o);continue}let p=a.replace(/\s+/," ");if(f.some(v=>v.prop===r.prop&&v.value.replace(/\s+/," ")===p)){n.push(o);continue}let m=this.clone(r,{value:a});o=r.parent.insertBefore(r,m),n.push(o)}return n}check(e){let r=e.value;return r.includes(this.name)?!!r.match(this.regexp()):!1}regexp(){return this.regexpCache||(this.regexpCache=YC.regexp(this.name))}replace(e,r){return e.replace(this.regexp(),`$1${r}$2`)}value(e){return e.raws.value&&e.raws.value.value===e.value?e.raws.value.raw:e.value}add(e,r){e._autoprefixerValues||(e._autoprefixerValues={});let i=e._autoprefixerValues[r]||this.value(e),n;do if(n=i,i=this.replace(i,r),i===!1)return;while(i!==n);e._autoprefixerValues[r]=i}old(e){return new GC(this.name,e+this.name)}};qv.exports=Dv});var $t=k((dz,Rv)=>{l();Rv.exports={}});var Lu=k((hz,Mv)=>{l();var Lv=aa(),QC=Ne(),JC=$t().insertAreas,XC=/(^|[^-])linear-gradient\(\s*(top|left|right|bottom)/i,KC=/(^|[^-])radial-gradient\(\s*\d+(\w*|%)\s+\d+(\w*|%)\s*,/i,ZC=/(!\s*)?autoprefixer:\s*ignore\s+next/i,eP=/(!\s*)?autoprefixer\s*grid:\s*(on|off|(no-)?autoplace)/i,tP=["width","height","min-width","max-width","min-height","max-height","inline-size","min-inline-size","max-inline-size","block-size","min-block-size","max-block-size"];function Ru(t){return t.parent.some(e=>e.prop==="grid-template"||e.prop==="grid-template-areas")}function rP(t){let e=t.parent.some(i=>i.prop==="grid-template-rows"),r=t.parent.some(i=>i.prop==="grid-template-columns");return e&&r}var Bv=class{constructor(e){this.prefixes=e}add(e,r){let i=this.prefixes.add["@resolution"],n=this.prefixes.add["@keyframes"],s=this.prefixes.add["@viewport"],a=this.prefixes.add["@supports"];e.walkAtRules(f=>{if(f.name==="keyframes"){if(!this.disabled(f,r))return n&&n.process(f)}else if(f.name==="viewport"){if(!this.disabled(f,r))return s&&s.process(f)}else if(f.name==="supports"){if(this.prefixes.options.supports!==!1&&!this.disabled(f,r))return a.process(f)}else if(f.name==="media"&&f.params.includes("-resolution")&&!this.disabled(f,r))return i&&i.process(f)}),e.walkRules(f=>{if(!this.disabled(f,r))return this.prefixes.add.selectors.map(p=>p.process(f,r))});function o(f){return f.parent.nodes.some(p=>{if(p.type!=="decl")return!1;let h=p.prop==="display"&&/(inline-)?grid/.test(p.value),m=p.prop.startsWith("grid-template"),v=/^grid-([A-z]+-)?gap/.test(p.prop);return h||m||v})}function u(f){return f.parent.some(p=>p.prop==="display"&&/(inline-)?flex/.test(p.value))}let c=this.gridStatus(e,r)&&this.prefixes.add["grid-area"]&&this.prefixes.add["grid-area"].prefixes;return e.walkDecls(f=>{if(this.disabledDecl(f,r))return;let p=f.parent,h=f.prop,m=f.value;if(h==="grid-row-span"){r.warn("grid-row-span is not part of final Grid Layout. Use grid-row.",{node:f});return}else if(h==="grid-column-span"){r.warn("grid-column-span is not part of final Grid Layout. Use grid-column.",{node:f});return}else if(h==="display"&&m==="box"){r.warn("You should write display: flex by final spec instead of display: box",{node:f});return}else if(h==="text-emphasis-position")(m==="under"||m==="over")&&r.warn("You should use 2 values for text-emphasis-position For example, `under left` instead of just `under`.",{node:f});else if(/^(align|justify|place)-(items|content)$/.test(h)&&u(f))(m==="start"||m==="end")&&r.warn(`${m} value has mixed support, consider using flex-${m} instead`,{node:f});else if(h==="text-decoration-skip"&&m==="ink")r.warn("Replace text-decoration-skip: ink to text-decoration-skip-ink: auto, because spec had been changed",{node:f});else{if(c&&this.gridStatus(f,r))if(f.value==="subgrid"&&r.warn("IE does not support subgrid",{node:f}),/^(align|justify|place)-items$/.test(h)&&o(f)){let S=h.replace("-items","-self");r.warn(`IE does not support ${h} on grid containers. Try using ${S} on child elements instead: ${f.parent.selector} > * { ${S}: ${f.value} }`,{node:f})}else if(/^(align|justify|place)-content$/.test(h)&&o(f))r.warn(`IE does not support ${f.prop} on grid containers`,{node:f});else if(h==="display"&&f.value==="contents"){r.warn("Please do not use display: contents; if you have grid setting enabled",{node:f});return}else if(f.prop==="grid-gap"){let S=this.gridStatus(f,r);S==="autoplace"&&!rP(f)&&!Ru(f)?r.warn("grid-gap only works if grid-template(-areas) is being used or both rows and columns have been declared and cells have not been manually placed inside the explicit grid",{node:f}):(S===!0||S==="no-autoplace")&&!Ru(f)&&r.warn("grid-gap only works if grid-template(-areas) is being used",{node:f})}else if(h==="grid-auto-columns"){r.warn("grid-auto-columns is not supported by IE",{node:f});return}else if(h==="grid-auto-rows"){r.warn("grid-auto-rows is not supported by IE",{node:f});return}else if(h==="grid-auto-flow"){let S=p.some(w=>w.prop==="grid-template-rows"),b=p.some(w=>w.prop==="grid-template-columns");Ru(f)?r.warn("grid-auto-flow is not supported by IE",{node:f}):m.includes("dense")?r.warn("grid-auto-flow: dense is not supported by IE",{node:f}):!S&&!b&&r.warn("grid-auto-flow works only if grid-template-rows and grid-template-columns are present in the same rule",{node:f});return}else if(m.includes("auto-fit")){r.warn("auto-fit value is not supported by IE",{node:f,word:"auto-fit"});return}else if(m.includes("auto-fill")){r.warn("auto-fill value is not supported by IE",{node:f,word:"auto-fill"});return}else h.startsWith("grid-template")&&m.includes("[")&&r.warn("Autoprefixer currently does not support line names. Try using grid-template-areas instead.",{node:f,word:"["});if(m.includes("radial-gradient"))if(KC.test(f.value))r.warn("Gradient has outdated direction syntax. New syntax is like `closest-side at 0 0` instead of `0 0, closest-side`.",{node:f});else{let S=Lv(m);for(let b of S.nodes)if(b.type==="function"&&b.value==="radial-gradient")for(let w of b.nodes)w.type==="word"&&(w.value==="cover"?r.warn("Gradient has outdated direction syntax. Replace `cover` to `farthest-corner`.",{node:f}):w.value==="contain"&&r.warn("Gradient has outdated direction syntax. Replace `contain` to `closest-side`.",{node:f}))}m.includes("linear-gradient")&&XC.test(m)&&r.warn("Gradient has outdated direction syntax. New syntax is like `to left` instead of `right`.",{node:f})}tP.includes(f.prop)&&(f.value.includes("-fill-available")||(f.value.includes("fill-available")?r.warn("Replace fill-available to stretch, because spec had been changed",{node:f}):f.value.includes("fill")&&Lv(m).nodes.some(b=>b.type==="word"&&b.value==="fill")&&r.warn("Replace fill to stretch, because spec had been changed",{node:f})));let v;if(f.prop==="transition"||f.prop==="transition-property")return this.prefixes.transition.add(f,r);if(f.prop==="align-self"){if(this.displayType(f)!=="grid"&&this.prefixes.options.flexbox!==!1&&(v=this.prefixes.add["align-self"],v&&v.prefixes&&v.process(f)),this.gridStatus(f,r)!==!1&&(v=this.prefixes.add["grid-row-align"],v&&v.prefixes))return v.process(f,r)}else if(f.prop==="justify-self"){if(this.gridStatus(f,r)!==!1&&(v=this.prefixes.add["grid-column-align"],v&&v.prefixes))return v.process(f,r)}else if(f.prop==="place-self"){if(v=this.prefixes.add["place-self"],v&&v.prefixes&&this.gridStatus(f,r)!==!1)return v.process(f,r)}else if(v=this.prefixes.add[f.prop],v&&v.prefixes)return v.process(f,r)}),this.gridStatus(e,r)&&JC(e,this.disabled),e.walkDecls(f=>{if(this.disabledValue(f,r))return;let p=this.prefixes.unprefixed(f.prop),h=this.prefixes.values("add",p);if(Array.isArray(h))for(let m of h)m.process&&m.process(f,r);QC.save(this.prefixes,f)})}remove(e,r){let i=this.prefixes.remove["@resolution"];e.walkAtRules((n,s)=>{this.prefixes.remove[`@${n.name}`]?this.disabled(n,r)||n.parent.removeChild(s):n.name==="media"&&n.params.includes("-resolution")&&i&&i.clean(n)});for(let n of this.prefixes.remove.selectors)e.walkRules((s,a)=>{n.check(s)&&(this.disabled(s,r)||s.parent.removeChild(a))});return e.walkDecls((n,s)=>{if(this.disabled(n,r))return;let a=n.parent,o=this.prefixes.unprefixed(n.prop);if((n.prop==="transition"||n.prop==="transition-property")&&this.prefixes.transition.remove(n),this.prefixes.remove[n.prop]&&this.prefixes.remove[n.prop].remove){let u=this.prefixes.group(n).down(c=>this.prefixes.normalize(c.prop)===o);if(o==="flex-flow"&&(u=!0),n.prop==="-webkit-box-orient"){let c={"flex-direction":!0,"flex-flow":!0};if(!n.parent.some(f=>c[f.prop]))return}if(u&&!this.withHackValue(n)){n.raw("before").includes(`
`)&&this.reduceSpaces(n),a.removeChild(s);return}}for(let u of this.prefixes.values("remove",o)){if(!u.check||!u.check(n.value))continue;if(o=u.unprefixed,this.prefixes.group(n).down(f=>f.value.includes(o))){a.removeChild(s);return}}})}withHackValue(e){return e.prop==="-webkit-background-clip"&&e.value==="text"}disabledValue(e,r){return this.gridStatus(e,r)===!1&&e.type==="decl"&&e.prop==="display"&&e.value.includes("grid")||this.prefixes.options.flexbox===!1&&e.type==="decl"&&e.prop==="display"&&e.value.includes("flex")||e.type==="decl"&&e.prop==="content"?!0:this.disabled(e,r)}disabledDecl(e,r){if(this.gridStatus(e,r)===!1&&e.type==="decl"&&(e.prop.includes("grid")||e.prop==="justify-items"))return!0;if(this.prefixes.options.flexbox===!1&&e.type==="decl"){let i=["order","justify-content","align-items","align-content"];if(e.prop.includes("flex")||i.includes(e.prop))return!0}return this.disabled(e,r)}disabled(e,r){if(!e)return!1;if(e._autoprefixerDisabled!==void 0)return e._autoprefixerDisabled;if(e.parent){let n=e.prev();if(n&&n.type==="comment"&&ZC.test(n.text))return e._autoprefixerDisabled=!0,e._autoprefixerSelfDisabled=!0,!0}let i=null;if(e.nodes){let n;e.each(s=>{s.type==="comment"&&/(!\s*)?autoprefixer:\s*(off|on)/i.test(s.text)&&(typeof n!="undefined"?r.warn("Second Autoprefixer control comment was ignored. Autoprefixer applies control comment to whole block, not to next rules.",{node:s}):n=/on/i.test(s.text))}),n!==void 0&&(i=!n)}if(!e.nodes||i===null)if(e.parent){let n=this.disabled(e.parent,r);e.parent._autoprefixerSelfDisabled===!0?i=!1:i=n}else i=!1;return e._autoprefixerDisabled=i,i}reduceSpaces(e){let r=!1;if(this.prefixes.group(e).up(()=>(r=!0,!0)),r)return;let i=e.raw("before").split(`
`),n=i[i.length-1].length,s=!1;this.prefixes.group(e).down(a=>{i=a.raw("before").split(`
`);let o=i.length-1;i[o].length>n&&(s===!1&&(s=i[o].length-n),i[o]=i[o].slice(0,-s),a.raws.before=i.join(`
`))})}displayType(e){for(let r of e.parent.nodes)if(r.prop==="display"){if(r.value.includes("flex"))return"flex";if(r.value.includes("grid"))return"grid"}return!1}gridStatus(e,r){if(!e)return!1;if(e._autoprefixerGridStatus!==void 0)return e._autoprefixerGridStatus;let i=null;if(e.nodes){let n;e.each(s=>{if(s.type==="comment"&&eP.test(s.text)){let a=/:\s*autoplace/i.test(s.text),o=/no-autoplace/i.test(s.text);typeof n!="undefined"?r.warn("Second Autoprefixer grid control comment was ignored. Autoprefixer applies control comments to the whole block, not to the next rules.",{node:s}):a?n="autoplace":o?n=!0:n=/on/i.test(s.text)}}),n!==void 0&&(i=n)}if(e.type==="atrule"&&e.name==="supports"){let n=e.params;n.includes("grid")&&n.includes("auto")&&(i=!1)}if(!e.nodes||i===null)if(e.parent){let n=this.gridStatus(e.parent,r);e.parent._autoprefixerSelfDisabled===!0?i=!1:i=n}else typeof this.prefixes.options.grid!="undefined"?i=this.prefixes.options.grid:typeof g.env.AUTOPREFIXER_GRID!="undefined"?g.env.AUTOPREFIXER_GRID==="autoplace"?i="autoplace":i=!0:i=!1;return e._autoprefixerGridStatus=i,i}};Mv.exports=Bv});var Nv=k((mz,Fv)=>{l();Fv.exports={A:{A:{"2":"K E F G A B JC"},B:{"1":"C L M H N D O P Q R S T U V W X Y Z a b c d e f g h i j n o p q r s t u v w x y z I"},C:{"1":"2 3 4 5 6 7 8 9 AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB ZB aB bB cB 0B dB 1B eB fB gB hB iB jB kB lB mB nB oB m pB qB rB sB tB P Q R 2B S T U V W X Y Z a b c d e f g h i j n o p q r s t u v w x y z I uB 3B 4B","2":"0 1 KC zB J K E F G A B C L M H N D O k l LC MC"},D:{"1":"8 9 AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB ZB aB bB cB 0B dB 1B eB fB gB hB iB jB kB lB mB nB oB m pB qB rB sB tB P Q R S T U V W X Y Z a b c d e f g h i j n o p q r s t u v w x y z I uB 3B 4B","2":"0 1 2 3 4 5 6 7 J K E F G A B C L M H N D O k l"},E:{"1":"G A B C L M H D RC 6B vB wB 7B SC TC 8B 9B xB AC yB BC CC DC EC FC GC UC","2":"0 J K E F NC 5B OC PC QC"},F:{"1":"1 2 3 4 5 6 7 8 9 H N D O k l AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB m pB qB rB sB tB P Q R 2B S T U V W X Y Z a b c d e f g h i j wB","2":"G B C VC WC XC YC vB HC ZC"},G:{"1":"D fC gC hC iC jC kC lC mC nC oC pC qC rC sC tC 8B 9B xB AC yB BC CC DC EC FC GC","2":"F 5B aC IC bC cC dC eC"},H:{"1":"uC"},I:{"1":"I zC 0C","2":"zB J vC wC xC yC IC"},J:{"2":"E A"},K:{"1":"m","2":"A B C vB HC wB"},L:{"1":"I"},M:{"1":"uB"},N:{"2":"A B"},O:{"1":"xB"},P:{"1":"J k l 1C 2C 3C 4C 5C 6B 6C 7C 8C 9C AD yB BD CD DD"},Q:{"1":"7B"},R:{"1":"ED"},S:{"1":"FD GD"}},B:4,C:"CSS Feature Queries"}});var Uv=k((gz,jv)=>{l();function zv(t){return t[t.length-1]}var $v={parse(t){let e=[""],r=[e];for(let i of t){if(i==="("){e=[""],zv(r).push(e),r.push(e);continue}if(i===")"){r.pop(),e=zv(r),e.push("");continue}e[e.length-1]+=i}return r[0]},stringify(t){let e="";for(let r of t){if(typeof r=="object"){e+=`(${$v.stringify(r)})`;continue}e+=r}return e}};jv.exports=$v});var Yv=k((yz,Hv)=>{l();var iP=Nv(),{feature:nP}=(ea(),Zs),{parse:sP}=qe(),aP=Nt(),Bu=Uv(),oP=Ne(),lP=Oe(),Vv=nP(iP),Wv=[];for(let t in Vv.stats){let e=Vv.stats[t];for(let r in e){let i=e[r];/y/.test(i)&&Wv.push(t+" "+r)}}var Gv=class{constructor(e,r){this.Prefixes=e,this.all=r}prefixer(){if(this.prefixerCache)return this.prefixerCache;let e=this.all.browsers.selected.filter(i=>Wv.includes(i)),r=new aP(this.all.browsers.data,e,this.all.options);return this.prefixerCache=new this.Prefixes(this.all.data,r,this.all.options),this.prefixerCache}parse(e){let r=e.split(":"),i=r[0],n=r[1];return n||(n=""),[i.trim(),n.trim()]}virtual(e){let[r,i]=this.parse(e),n=sP("a{}").first;return n.append({prop:r,value:i,raws:{before:""}}),n}prefixed(e){let r=this.virtual(e);if(this.disabled(r.first))return r.nodes;let i={warn:()=>null},n=this.prefixer().add[r.first.prop];n&&n.process&&n.process(r.first,i);for(let s of r.nodes){for(let a of this.prefixer().values("add",r.first.prop))a.process(s);oP.save(this.all,s)}return r.nodes}isNot(e){return typeof e=="string"&&/not\s*/i.test(e)}isOr(e){return typeof e=="string"&&/\s*or\s*/i.test(e)}isProp(e){return typeof e=="object"&&e.length===1&&typeof e[0]=="string"}isHack(e,r){return!new RegExp(`(\\(|\\s)${lP.escapeRegexp(r)}:`).test(e)}toRemove(e,r){let[i,n]=this.parse(e),s=this.all.unprefixed(i),a=this.all.cleaner();if(a.remove[i]&&a.remove[i].remove&&!this.isHack(r,s))return!0;for(let o of a.values("remove",s))if(o.check(n))return!0;return!1}remove(e,r){let i=0;for(;i<e.length;){if(!this.isNot(e[i-1])&&this.isProp(e[i])&&this.isOr(e[i+1])){if(this.toRemove(e[i][0],r)){e.splice(i,2);continue}i+=2;continue}typeof e[i]=="object"&&(e[i]=this.remove(e[i],r)),i+=1}return e}cleanBrackets(e){return e.map(r=>typeof r!="object"?r:r.length===1&&typeof r[0]=="object"?this.cleanBrackets(r[0]):this.cleanBrackets(r))}convert(e){let r=[""];for(let i of e)r.push([`${i.prop}: ${i.value}`]),r.push(" or ");return r[r.length-1]="",r}normalize(e){if(typeof e!="object")return e;if(e=e.filter(r=>r!==""),typeof e[0]=="string"){let r=e[0].trim();if(r.includes(":")||r==="selector"||r==="not selector")return[Bu.stringify(e)]}return e.map(r=>this.normalize(r))}add(e,r){return e.map(i=>{if(this.isProp(i)){let n=this.prefixed(i[0]);return n.length>1?this.convert(n):i}return typeof i=="object"?this.add(i,r):i})}process(e){let r=Bu.parse(e.params);r=this.normalize(r),r=this.remove(r,e.params),r=this.add(r,e.params),r=this.cleanBrackets(r),e.params=Bu.stringify(r)}disabled(e){if(!this.all.options.grid&&(e.prop==="display"&&e.value.includes("grid")||e.prop.includes("grid")||e.prop==="justify-items"))return!0;if(this.all.options.flexbox===!1){if(e.prop==="display"&&e.value.includes("flex"))return!0;let r=["order","justify-content","align-items","align-content"];if(e.prop.includes("flex")||r.includes(e.prop))return!0}return!1}};Hv.exports=Gv});var Xv=k((vz,Jv)=>{l();var Qv=class{constructor(e,r){this.prefix=r,this.prefixed=e.prefixed(this.prefix),this.regexp=e.regexp(this.prefix),this.prefixeds=e.possible().map(i=>[e.prefixed(i),e.regexp(i)]),this.unprefixed=e.name,this.nameRegexp=e.regexp()}isHack(e){let r=e.parent.index(e)+1,i=e.parent.nodes;for(;r<i.length;){let n=i[r].selector;if(!n)return!0;if(n.includes(this.unprefixed)&&n.match(this.nameRegexp))return!1;let s=!1;for(let[a,o]of this.prefixeds)if(n.includes(a)&&n.match(o)){s=!0;break}if(!s)return!0;r+=1}return!0}check(e){return!(!e.selector.includes(this.prefixed)||!e.selector.match(this.regexp)||this.isHack(e))}};Jv.exports=Qv});var Or=k((wz,Zv)=>{l();var{list:uP}=qe(),fP=Xv(),cP=Sr(),pP=Nt(),dP=Oe(),Kv=class extends cP{constructor(e,r,i){super(e,r,i);this.regexpCache=new Map}check(e){return e.selector.includes(this.name)?!!e.selector.match(this.regexp()):!1}prefixed(e){return this.name.replace(/^(\W*)/,`$1${e}`)}regexp(e){if(!this.regexpCache.has(e)){let r=e?this.prefixed(e):this.name;this.regexpCache.set(e,new RegExp(`(^|[^:"'=])${dP.escapeRegexp(r)}`,"gi"))}return this.regexpCache.get(e)}possible(){return pP.prefixes()}prefixeds(e){if(e._autoprefixerPrefixeds){if(e._autoprefixerPrefixeds[this.name])return e._autoprefixerPrefixeds}else e._autoprefixerPrefixeds={};let r={};if(e.selector.includes(",")){let n=uP.comma(e.selector).filter(s=>s.includes(this.name));for(let s of this.possible())r[s]=n.map(a=>this.replace(a,s)).join(", ")}else for(let i of this.possible())r[i]=this.replace(e.selector,i);return e._autoprefixerPrefixeds[this.name]=r,e._autoprefixerPrefixeds}already(e,r,i){let n=e.parent.index(e)-1;for(;n>=0;){let s=e.parent.nodes[n];if(s.type!=="rule")return!1;let a=!1;for(let o in r[this.name]){let u=r[this.name][o];if(s.selector===u){if(i===o)return!0;a=!0;break}}if(!a)return!1;n-=1}return!1}replace(e,r){return e.replace(this.regexp(),`$1${this.prefixed(r)}`)}add(e,r){let i=this.prefixeds(e);if(this.already(e,i,r))return;let n=this.clone(e,{selector:i[this.name][r]});e.parent.insertBefore(e,n)}old(e){return new fP(this,e)}};Zv.exports=Kv});var r0=k((bz,t0)=>{l();var hP=Sr(),e0=class extends hP{add(e,r){let i=r+e.name;if(e.parent.some(a=>a.name===i&&a.params===e.params))return;let s=this.clone(e,{name:i});return e.parent.insertBefore(e,s)}process(e){let r=this.parentPrefix(e);for(let i of this.prefixes)(!r||r===i)&&this.add(e,i)}};t0.exports=e0});var n0=k((xz,i0)=>{l();var mP=Or(),Mu=class extends mP{prefixed(e){return e==="-webkit-"?":-webkit-full-screen":e==="-moz-"?":-moz-full-screen":`:${e}fullscreen`}};Mu.names=[":fullscreen"];i0.exports=Mu});var a0=k((kz,s0)=>{l();var gP=Or(),Fu=class extends gP{possible(){return super.possible().concat(["-moz- old","-ms- old"])}prefixed(e){return e==="-webkit-"?"::-webkit-input-placeholder":e==="-ms-"?"::-ms-input-placeholder":e==="-ms- old"?":-ms-input-placeholder":e==="-moz- old"?":-moz-placeholder":`::${e}placeholder`}};Fu.names=["::placeholder"];s0.exports=Fu});var l0=k((Sz,o0)=>{l();var yP=Or(),Nu=class extends yP{prefixed(e){return e==="-ms-"?":-ms-input-placeholder":`:${e}placeholder-shown`}};Nu.names=[":placeholder-shown"];o0.exports=Nu});var f0=k((_z,u0)=>{l();var vP=Or(),wP=Oe(),zu=class extends vP{constructor(e,r,i){super(e,r,i);this.prefixes&&(this.prefixes=wP.uniq(this.prefixes.map(n=>"-webkit-")))}prefixed(e){return e==="-webkit-"?"::-webkit-file-upload-button":`::${e}file-selector-button`}};zu.names=["::file-selector-button"];u0.exports=zu});var Pe=k((Tz,c0)=>{l();c0.exports=function(t){let e;return t==="-webkit- 2009"||t==="-moz-"?e=2009:t==="-ms-"?e=2012:t==="-webkit-"&&(e="final"),t==="-webkit- 2009"&&(t="-webkit-"),[e,t]}});var m0=k((Oz,h0)=>{l();var p0=qe().list,d0=Pe(),bP=j(),Er=class extends bP{prefixed(e,r){let i;return[i,r]=d0(r),i===2009?r+"box-flex":super.prefixed(e,r)}normalize(){return"flex"}set(e,r){let i=d0(r)[0];if(i===2009)return e.value=p0.space(e.value)[0],e.value=Er.oldValues[e.value]||e.value,super.set(e,r);if(i===2012){let n=p0.space(e.value);n.length===3&&n[2]==="0"&&(e.value=n.slice(0,2).concat("0px").join(" "))}return super.set(e,r)}};Er.names=["flex","box-flex"];Er.oldValues={auto:"1",none:"0"};h0.exports=Er});var v0=k((Ez,y0)=>{l();var g0=Pe(),xP=j(),$u=class extends xP{prefixed(e,r){let i;return[i,r]=g0(r),i===2009?r+"box-ordinal-group":i===2012?r+"flex-order":super.prefixed(e,r)}normalize(){return"order"}set(e,r){return g0(r)[0]===2009&&/\d/.test(e.value)?(e.value=(parseInt(e.value)+1).toString(),super.set(e,r)):super.set(e,r)}};$u.names=["order","flex-order","box-ordinal-group"];y0.exports=$u});var b0=k((Az,w0)=>{l();var kP=j(),ju=class extends kP{check(e){let r=e.value;return!r.toLowerCase().includes("alpha(")&&!r.includes("DXImageTransform.Microsoft")&&!r.includes("data:image/svg+xml")}};ju.names=["filter"];w0.exports=ju});var k0=k((Cz,x0)=>{l();var SP=j(),Uu=class extends SP{insert(e,r,i,n){if(r!=="-ms-")return super.insert(e,r,i);let s=this.clone(e),a=e.prop.replace(/end$/,"start"),o=r+e.prop.replace(/end$/,"span");if(!e.parent.some(u=>u.prop===o)){if(s.prop=o,e.value.includes("span"))s.value=e.value.replace(/span\s/i,"");else{let u;if(e.parent.walkDecls(a,c=>{u=c}),u){let c=Number(e.value)-Number(u.value)+"";s.value=c}else e.warn(n,`Can not prefix ${e.prop} (${a} is not found)`)}e.cloneBefore(s)}}};Uu.names=["grid-row-end","grid-column-end"];x0.exports=Uu});var _0=k((Pz,S0)=>{l();var _P=j(),Vu=class extends _P{check(e){return!e.value.split(/\s+/).some(r=>{let i=r.toLowerCase();return i==="reverse"||i==="alternate-reverse"})}};Vu.names=["animation","animation-direction"];S0.exports=Vu});var O0=k((Iz,T0)=>{l();var TP=Pe(),OP=j(),Wu=class extends OP{insert(e,r,i){let n;if([n,r]=TP(r),n!==2009)return super.insert(e,r,i);let s=e.value.split(/\s+/).filter(p=>p!=="wrap"&&p!=="nowrap"&&"wrap-reverse");if(s.length===0||e.parent.some(p=>p.prop===r+"box-orient"||p.prop===r+"box-direction"))return;let o=s[0],u=o.includes("row")?"horizontal":"vertical",c=o.includes("reverse")?"reverse":"normal",f=this.clone(e);return f.prop=r+"box-orient",f.value=u,this.needCascade(e)&&(f.raws.before=this.calcBefore(i,e,r)),e.parent.insertBefore(e,f),f=this.clone(e),f.prop=r+"box-direction",f.value=c,this.needCascade(e)&&(f.raws.before=this.calcBefore(i,e,r)),e.parent.insertBefore(e,f)}};Wu.names=["flex-flow","box-direction","box-orient"];T0.exports=Wu});var A0=k((Dz,E0)=>{l();var EP=Pe(),AP=j(),Gu=class extends AP{normalize(){return"flex"}prefixed(e,r){let i;return[i,r]=EP(r),i===2009?r+"box-flex":i===2012?r+"flex-positive":super.prefixed(e,r)}};Gu.names=["flex-grow","flex-positive"];E0.exports=Gu});var P0=k((qz,C0)=>{l();var CP=Pe(),PP=j(),Hu=class extends PP{set(e,r){if(CP(r)[0]!==2009)return super.set(e,r)}};Hu.names=["flex-wrap"];C0.exports=Hu});var D0=k((Rz,I0)=>{l();var IP=j(),Ar=$t(),Yu=class extends IP{insert(e,r,i,n){if(r!=="-ms-")return super.insert(e,r,i);let s=Ar.parse(e),[a,o]=Ar.translate(s,0,2),[u,c]=Ar.translate(s,1,3);[["grid-row",a],["grid-row-span",o],["grid-column",u],["grid-column-span",c]].forEach(([f,p])=>{Ar.insertDecl(e,f,p)}),Ar.warnTemplateSelectorNotFound(e,n),Ar.warnIfGridRowColumnExists(e,n)}};Yu.names=["grid-area"];I0.exports=Yu});var R0=k((Lz,q0)=>{l();var DP=j(),Ui=$t(),Qu=class extends DP{insert(e,r,i){if(r!=="-ms-")return super.insert(e,r,i);if(e.parent.some(a=>a.prop==="-ms-grid-row-align"))return;let[[n,s]]=Ui.parse(e);s?(Ui.insertDecl(e,"grid-row-align",n),Ui.insertDecl(e,"grid-column-align",s)):(Ui.insertDecl(e,"grid-row-align",n),Ui.insertDecl(e,"grid-column-align",n))}};Qu.names=["place-self"];q0.exports=Qu});var B0=k((Bz,L0)=>{l();var qP=j(),Ju=class extends qP{check(e){let r=e.value;return!r.includes("/")||r.includes("span")}normalize(e){return e.replace("-start","")}prefixed(e,r){let i=super.prefixed(e,r);return r==="-ms-"&&(i=i.replace("-start","")),i}};Ju.names=["grid-row-start","grid-column-start"];L0.exports=Ju});var N0=k((Mz,F0)=>{l();var M0=Pe(),RP=j(),Cr=class extends RP{check(e){return e.parent&&!e.parent.some(r=>r.prop&&r.prop.startsWith("grid-"))}prefixed(e,r){let i;return[i,r]=M0(r),i===2012?r+"flex-item-align":super.prefixed(e,r)}normalize(){return"align-self"}set(e,r){let i=M0(r)[0];if(i===2012)return e.value=Cr.oldValues[e.value]||e.value,super.set(e,r);if(i==="final")return super.set(e,r)}};Cr.names=["align-self","flex-item-align"];Cr.oldValues={"flex-end":"end","flex-start":"start"};F0.exports=Cr});var $0=k((Fz,z0)=>{l();var LP=j(),BP=Oe(),Xu=class extends LP{constructor(e,r,i){super(e,r,i);this.prefixes&&(this.prefixes=BP.uniq(this.prefixes.map(n=>n==="-ms-"?"-webkit-":n)))}};Xu.names=["appearance"];z0.exports=Xu});var V0=k((Nz,U0)=>{l();var j0=Pe(),MP=j(),Ku=class extends MP{normalize(){return"flex-basis"}prefixed(e,r){let i;return[i,r]=j0(r),i===2012?r+"flex-preferred-size":super.prefixed(e,r)}set(e,r){let i;if([i,r]=j0(r),i===2012||i==="final")return super.set(e,r)}};Ku.names=["flex-basis","flex-preferred-size"];U0.exports=Ku});var G0=k((zz,W0)=>{l();var FP=j(),Zu=class extends FP{normalize(){return this.name.replace("box-image","border")}prefixed(e,r){let i=super.prefixed(e,r);return r==="-webkit-"&&(i=i.replace("border","box-image")),i}};Zu.names=["mask-border","mask-border-source","mask-border-slice","mask-border-width","mask-border-outset","mask-border-repeat","mask-box-image","mask-box-image-source","mask-box-image-slice","mask-box-image-width","mask-box-image-outset","mask-box-image-repeat"];W0.exports=Zu});var Y0=k(($z,H0)=>{l();var NP=j(),at=class extends NP{insert(e,r,i){let n=e.prop==="mask-composite",s;n?s=e.value.split(","):s=e.value.match(at.regexp)||[],s=s.map(c=>c.trim()).filter(c=>c);let a=s.length,o;if(a&&(o=this.clone(e),o.value=s.map(c=>at.oldValues[c]||c).join(", "),s.includes("intersect")&&(o.value+=", xor"),o.prop=r+"mask-composite"),n)return a?(this.needCascade(e)&&(o.raws.before=this.calcBefore(i,e,r)),e.parent.insertBefore(e,o)):void 0;let u=this.clone(e);return u.prop=r+u.prop,a&&(u.value=u.value.replace(at.regexp,"")),this.needCascade(e)&&(u.raws.before=this.calcBefore(i,e,r)),e.parent.insertBefore(e,u),a?(this.needCascade(e)&&(o.raws.before=this.calcBefore(i,e,r)),e.parent.insertBefore(e,o)):e}};at.names=["mask","mask-composite"];at.oldValues={add:"source-over",subtract:"source-out",intersect:"source-in",exclude:"xor"};at.regexp=new RegExp(`\\s+(${Object.keys(at.oldValues).join("|")})\\b(?!\\))\\s*(?=[,])`,"ig");H0.exports=at});var X0=k((jz,J0)=>{l();var Q0=Pe(),zP=j(),Pr=class extends zP{prefixed(e,r){let i;return[i,r]=Q0(r),i===2009?r+"box-align":i===2012?r+"flex-align":super.prefixed(e,r)}normalize(){return"align-items"}set(e,r){let i=Q0(r)[0];return(i===2009||i===2012)&&(e.value=Pr.oldValues[e.value]||e.value),super.set(e,r)}};Pr.names=["align-items","flex-align","box-align"];Pr.oldValues={"flex-end":"end","flex-start":"start"};J0.exports=Pr});var Z0=k((Uz,K0)=>{l();var $P=j(),ef=class extends $P{set(e,r){return r==="-ms-"&&e.value==="contain"&&(e.value="element"),super.set(e,r)}insert(e,r,i){if(!(e.value==="all"&&r==="-ms-"))return super.insert(e,r,i)}};ef.names=["user-select"];K0.exports=ef});var rw=k((Vz,tw)=>{l();var ew=Pe(),jP=j(),tf=class extends jP{normalize(){return"flex-shrink"}prefixed(e,r){let i;return[i,r]=ew(r),i===2012?r+"flex-negative":super.prefixed(e,r)}set(e,r){let i;if([i,r]=ew(r),i===2012||i==="final")return super.set(e,r)}};tf.names=["flex-shrink","flex-negative"];tw.exports=tf});var nw=k((Wz,iw)=>{l();var UP=j(),rf=class extends UP{prefixed(e,r){return`${r}column-${e}`}normalize(e){return e.includes("inside")?"break-inside":e.includes("before")?"break-before":"break-after"}set(e,r){return(e.prop==="break-inside"&&e.value==="avoid-column"||e.value==="avoid-page")&&(e.value="avoid"),super.set(e,r)}insert(e,r,i){if(e.prop!=="break-inside")return super.insert(e,r,i);if(!(/region/i.test(e.value)||/page/i.test(e.value)))return super.insert(e,r,i)}};rf.names=["break-inside","page-break-inside","column-break-inside","break-before","page-break-before","column-break-before","break-after","page-break-after","column-break-after"];iw.exports=rf});var aw=k((Gz,sw)=>{l();var VP=j(),nf=class extends VP{prefixed(e,r){return r+"print-color-adjust"}normalize(){return"color-adjust"}};nf.names=["color-adjust","print-color-adjust"];sw.exports=nf});var lw=k((Hz,ow)=>{l();var WP=j(),Ir=class extends WP{insert(e,r,i){if(r==="-ms-"){let n=this.set(this.clone(e),r);this.needCascade(e)&&(n.raws.before=this.calcBefore(i,e,r));let s="ltr";return e.parent.nodes.forEach(a=>{a.prop==="direction"&&(a.value==="rtl"||a.value==="ltr")&&(s=a.value)}),n.value=Ir.msValues[s][e.value]||e.value,e.parent.insertBefore(e,n)}return super.insert(e,r,i)}};Ir.names=["writing-mode"];Ir.msValues={ltr:{"horizontal-tb":"lr-tb","vertical-rl":"tb-rl","vertical-lr":"tb-lr"},rtl:{"horizontal-tb":"rl-tb","vertical-rl":"bt-rl","vertical-lr":"bt-lr"}};ow.exports=Ir});var fw=k((Yz,uw)=>{l();var GP=j(),sf=class extends GP{set(e,r){return e.value=e.value.replace(/\s+fill(\s)/,"$1"),super.set(e,r)}};sf.names=["border-image"];uw.exports=sf});var dw=k((Qz,pw)=>{l();var cw=Pe(),HP=j(),Dr=class extends HP{prefixed(e,r){let i;return[i,r]=cw(r),i===2012?r+"flex-line-pack":super.prefixed(e,r)}normalize(){return"align-content"}set(e,r){let i=cw(r)[0];if(i===2012)return e.value=Dr.oldValues[e.value]||e.value,super.set(e,r);if(i==="final")return super.set(e,r)}};Dr.names=["align-content","flex-line-pack"];Dr.oldValues={"flex-end":"end","flex-start":"start","space-between":"justify","space-around":"distribute"};pw.exports=Dr});var mw=k((Jz,hw)=>{l();var YP=j(),ze=class extends YP{prefixed(e,r){return r==="-moz-"?r+(ze.toMozilla[e]||e):super.prefixed(e,r)}normalize(e){return ze.toNormal[e]||e}};ze.names=["border-radius"];ze.toMozilla={};ze.toNormal={};for(let t of["top","bottom"])for(let e of["left","right"]){let r=`border-${t}-${e}-radius`,i=`border-radius-${t}${e}`;ze.names.push(r),ze.names.push(i),ze.toMozilla[r]=i,ze.toNormal[i]=r}hw.exports=ze});var yw=k((Xz,gw)=>{l();var QP=j(),af=class extends QP{prefixed(e,r){return e.includes("-start")?r+e.replace("-block-start","-before"):r+e.replace("-block-end","-after")}normalize(e){return e.includes("-before")?e.replace("-before","-block-start"):e.replace("-after","-block-end")}};af.names=["border-block-start","border-block-end","margin-block-start","margin-block-end","padding-block-start","padding-block-end","border-before","border-after","margin-before","margin-after","padding-before","padding-after"];gw.exports=af});var ww=k((Kz,vw)=>{l();var JP=j(),{parseTemplate:XP,warnMissedAreas:KP,getGridGap:ZP,warnGridGap:e5,inheritGridGap:t5}=$t(),of=class extends JP{insert(e,r,i,n){if(r!=="-ms-")return super.insert(e,r,i);if(e.parent.some(m=>m.prop==="-ms-grid-rows"))return;let s=ZP(e),a=t5(e,s),{rows:o,columns:u,areas:c}=XP({decl:e,gap:a||s}),f=Object.keys(c).length>0,p=Boolean(o),h=Boolean(u);return e5({gap:s,hasColumns:h,decl:e,result:n}),KP(c,e,n),(p&&h||f)&&e.cloneBefore({prop:"-ms-grid-rows",value:o,raws:{}}),h&&e.cloneBefore({prop:"-ms-grid-columns",value:u,raws:{}}),e}};of.names=["grid-template"];vw.exports=of});var xw=k((Zz,bw)=>{l();var r5=j(),lf=class extends r5{prefixed(e,r){return r+e.replace("-inline","")}normalize(e){return e.replace(/(margin|padding|border)-(start|end)/,"$1-inline-$2")}};lf.names=["border-inline-start","border-inline-end","margin-inline-start","margin-inline-end","padding-inline-start","padding-inline-end","border-start","border-end","margin-start","margin-end","padding-start","padding-end"];bw.exports=lf});var Sw=k((e$,kw)=>{l();var i5=j(),uf=class extends i5{check(e){return!e.value.includes("flex-")&&e.value!=="baseline"}prefixed(e,r){return r+"grid-row-align"}normalize(){return"align-self"}};uf.names=["grid-row-align"];kw.exports=uf});var Tw=k((t$,_w)=>{l();var n5=j(),qr=class extends n5{keyframeParents(e){let{parent:r}=e;for(;r;){if(r.type==="atrule"&&r.name==="keyframes")return!0;({parent:r}=r)}return!1}contain3d(e){if(e.prop==="transform-origin")return!1;for(let r of qr.functions3d)if(e.value.includes(`${r}(`))return!0;return!1}set(e,r){return e=super.set(e,r),r==="-ms-"&&(e.value=e.value.replace(/rotatez/gi,"rotate")),e}insert(e,r,i){if(r==="-ms-"){if(!this.contain3d(e)&&!this.keyframeParents(e))return super.insert(e,r,i)}else if(r==="-o-"){if(!this.contain3d(e))return super.insert(e,r,i)}else return super.insert(e,r,i)}};qr.names=["transform","transform-origin"];qr.functions3d=["matrix3d","translate3d","translateZ","scale3d","scaleZ","rotate3d","rotateX","rotateY","perspective"];_w.exports=qr});var Aw=k((r$,Ew)=>{l();var Ow=Pe(),s5=j(),ff=class extends s5{normalize(){return"flex-direction"}insert(e,r,i){let n;if([n,r]=Ow(r),n!==2009)return super.insert(e,r,i);if(e.parent.some(f=>f.prop===r+"box-orient"||f.prop===r+"box-direction"))return;let a=e.value,o,u;a==="inherit"||a==="initial"||a==="unset"?(o=a,u=a):(o=a.includes("row")?"horizontal":"vertical",u=a.includes("reverse")?"reverse":"normal");let c=this.clone(e);return c.prop=r+"box-orient",c.value=o,this.needCascade(e)&&(c.raws.before=this.calcBefore(i,e,r)),e.parent.insertBefore(e,c),c=this.clone(e),c.prop=r+"box-direction",c.value=u,this.needCascade(e)&&(c.raws.before=this.calcBefore(i,e,r)),e.parent.insertBefore(e,c)}old(e,r){let i;return[i,r]=Ow(r),i===2009?[r+"box-orient",r+"box-direction"]:super.old(e,r)}};ff.names=["flex-direction","box-direction","box-orient"];Ew.exports=ff});var Pw=k((i$,Cw)=>{l();var a5=j(),cf=class extends a5{check(e){return e.value==="pixelated"}prefixed(e,r){return r==="-ms-"?"-ms-interpolation-mode":super.prefixed(e,r)}set(e,r){return r!=="-ms-"?super.set(e,r):(e.prop="-ms-interpolation-mode",e.value="nearest-neighbor",e)}normalize(){return"image-rendering"}process(e,r){return super.process(e,r)}};cf.names=["image-rendering","interpolation-mode"];Cw.exports=cf});var Dw=k((n$,Iw)=>{l();var o5=j(),l5=Oe(),pf=class extends o5{constructor(e,r,i){super(e,r,i);this.prefixes&&(this.prefixes=l5.uniq(this.prefixes.map(n=>n==="-ms-"?"-webkit-":n)))}};pf.names=["backdrop-filter"];Iw.exports=pf});var Rw=k((s$,qw)=>{l();var u5=j(),f5=Oe(),df=class extends u5{constructor(e,r,i){super(e,r,i);this.prefixes&&(this.prefixes=f5.uniq(this.prefixes.map(n=>n==="-ms-"?"-webkit-":n)))}check(e){return e.value.toLowerCase()==="text"}};df.names=["background-clip"];qw.exports=df});var Bw=k((a$,Lw)=>{l();var c5=j(),p5=["none","underline","overline","line-through","blink","inherit","initial","unset"],hf=class extends c5{check(e){return e.value.split(/\s+/).some(r=>!p5.includes(r))}};hf.names=["text-decoration"];Lw.exports=hf});var Nw=k((o$,Fw)=>{l();var Mw=Pe(),d5=j(),Rr=class extends d5{prefixed(e,r){let i;return[i,r]=Mw(r),i===2009?r+"box-pack":i===2012?r+"flex-pack":super.prefixed(e,r)}normalize(){return"justify-content"}set(e,r){let i=Mw(r)[0];if(i===2009||i===2012){let n=Rr.oldValues[e.value]||e.value;if(e.value=n,i!==2009||n!=="distribute")return super.set(e,r)}else if(i==="final")return super.set(e,r)}};Rr.names=["justify-content","flex-pack","box-pack"];Rr.oldValues={"flex-end":"end","flex-start":"start","space-between":"justify","space-around":"distribute"};Fw.exports=Rr});var $w=k((l$,zw)=>{l();var h5=j(),mf=class extends h5{set(e,r){let i=e.value.toLowerCase();return r==="-webkit-"&&!i.includes(" ")&&i!=="contain"&&i!=="cover"&&(e.value=e.value+" "+e.value),super.set(e,r)}};mf.names=["background-size"];zw.exports=mf});var Uw=k((u$,jw)=>{l();var m5=j(),gf=$t(),yf=class extends m5{insert(e,r,i){if(r!=="-ms-")return super.insert(e,r,i);let n=gf.parse(e),[s,a]=gf.translate(n,0,1);n[0]&&n[0].includes("span")&&(a=n[0].join("").replace(/\D/g,"")),[[e.prop,s],[`${e.prop}-span`,a]].forEach(([u,c])=>{gf.insertDecl(e,u,c)})}};yf.names=["grid-row","grid-column"];jw.exports=yf});var Gw=k((f$,Ww)=>{l();var g5=j(),{prefixTrackProp:Vw,prefixTrackValue:y5,autoplaceGridItems:v5,getGridGap:w5,inheritGridGap:b5}=$t(),x5=Lu(),vf=class extends g5{prefixed(e,r){return r==="-ms-"?Vw({prop:e,prefix:r}):super.prefixed(e,r)}normalize(e){return e.replace(/^grid-(rows|columns)/,"grid-template-$1")}insert(e,r,i,n){if(r!=="-ms-")return super.insert(e,r,i);let{parent:s,prop:a,value:o}=e,u=a.includes("rows"),c=a.includes("columns"),f=s.some(_=>_.prop==="grid-template"||_.prop==="grid-template-areas");if(f&&u)return!1;let p=new x5({options:{}}),h=p.gridStatus(s,n),m=w5(e);m=b5(e,m)||m;let v=u?m.row:m.column;(h==="no-autoplace"||h===!0)&&!f&&(v=null);let S=y5({value:o,gap:v});e.cloneBefore({prop:Vw({prop:a,prefix:r}),value:S});let b=s.nodes.find(_=>_.prop==="grid-auto-flow"),w="row";if(b&&!p.disabled(b,n)&&(w=b.value.trim()),h==="autoplace"){let _=s.nodes.find(O=>O.prop==="grid-template-rows");if(!_&&f)return;if(!_&&!f){e.warn(n,"Autoplacement does not work without grid-template-rows property");return}!s.nodes.find(O=>O.prop==="grid-template-columns")&&!f&&e.warn(n,"Autoplacement does not work without grid-template-columns property"),c&&!f&&v5(e,n,m,w)}}};vf.names=["grid-template-rows","grid-template-columns","grid-rows","grid-columns"];Ww.exports=vf});var Yw=k((c$,Hw)=>{l();var k5=j(),wf=class extends k5{check(e){return!e.value.includes("flex-")&&e.value!=="baseline"}prefixed(e,r){return r+"grid-column-align"}normalize(){return"justify-self"}};wf.names=["grid-column-align"];Hw.exports=wf});var Jw=k((p$,Qw)=>{l();var S5=j(),bf=class extends S5{prefixed(e,r){return r+"scroll-chaining"}normalize(){return"overscroll-behavior"}set(e,r){return e.value==="auto"?e.value="chained":(e.value==="none"||e.value==="contain")&&(e.value="none"),super.set(e,r)}};bf.names=["overscroll-behavior","scroll-chaining"];Qw.exports=bf});var Zw=k((d$,Kw)=>{l();var _5=j(),{parseGridAreas:T5,warnMissedAreas:O5,prefixTrackProp:E5,prefixTrackValue:Xw,getGridGap:A5,warnGridGap:C5,inheritGridGap:P5}=$t();function I5(t){return t.trim().slice(1,-1).split(/["']\s*["']?/g)}var xf=class extends _5{insert(e,r,i,n){if(r!=="-ms-")return super.insert(e,r,i);let s=!1,a=!1,o=e.parent,u=A5(e);u=P5(e,u)||u,o.walkDecls(/-ms-grid-rows/,p=>p.remove()),o.walkDecls(/grid-template-(rows|columns)/,p=>{if(p.prop==="grid-template-rows"){a=!0;let{prop:h,value:m}=p;p.cloneBefore({prop:E5({prop:h,prefix:r}),value:Xw({value:m,gap:u.row})})}else s=!0});let c=I5(e.value);s&&!a&&u.row&&c.length>1&&e.cloneBefore({prop:"-ms-grid-rows",value:Xw({value:`repeat(${c.length}, auto)`,gap:u.row}),raws:{}}),C5({gap:u,hasColumns:s,decl:e,result:n});let f=T5({rows:c,gap:u});return O5(f,e,n),e}};xf.names=["grid-template-areas"];Kw.exports=xf});var tb=k((h$,eb)=>{l();var D5=j(),kf=class extends D5{set(e,r){return r==="-webkit-"&&(e.value=e.value.replace(/\s*(right|left)\s*/i,"")),super.set(e,r)}};kf.names=["text-emphasis-position"];eb.exports=kf});var ib=k((m$,rb)=>{l();var q5=j(),Sf=class extends q5{set(e,r){return e.prop==="text-decoration-skip-ink"&&e.value==="auto"?(e.prop=r+"text-decoration-skip",e.value="ink",e):super.set(e,r)}};Sf.names=["text-decoration-skip-ink","text-decoration-skip"];rb.exports=Sf});var ub=k((g$,lb)=>{l();"use strict";lb.exports={wrap:nb,limit:sb,validate:ab,test:_f,curry:R5,name:ob};function nb(t,e,r){var i=e-t;return((r-t)%i+i)%i+t}function sb(t,e,r){return Math.max(t,Math.min(e,r))}function ab(t,e,r,i,n){if(!_f(t,e,r,i,n))throw new Error(r+" is outside of range ["+t+","+e+")");return r}function _f(t,e,r,i,n){return!(r<t||r>e||n&&r===e||i&&r===t)}function ob(t,e,r,i){return(r?"(":"[")+t+","+e+(i?")":"]")}function R5(t,e,r,i){var n=ob.bind(null,t,e,r,i);return{wrap:nb.bind(null,t,e),limit:sb.bind(null,t,e),validate:function(s){return ab(t,e,s,r,i)},test:function(s){return _f(t,e,s,r,i)},toString:n,name:n}}});var pb=k((y$,cb)=>{l();var Tf=aa(),L5=ub(),B5=Tr(),M5=Ne(),F5=Oe(),fb=/top|left|right|bottom/gi,vt=class extends M5{replace(e,r){let i=Tf(e);for(let n of i.nodes)if(n.type==="function"&&n.value===this.name)if(n.nodes=this.newDirection(n.nodes),n.nodes=this.normalize(n.nodes),r==="-webkit- old"){if(!this.oldWebkit(n))return!1}else n.nodes=this.convertDirection(n.nodes),n.value=r+n.value;return i.toString()}replaceFirst(e,...r){return r.map(n=>n===" "?{type:"space",value:n}:{type:"word",value:n}).concat(e.slice(1))}normalizeUnit(e,r){return`${parseFloat(e)/r*360}deg`}normalize(e){if(!e[0])return e;if(/-?\d+(.\d+)?grad/.test(e[0].value))e[0].value=this.normalizeUnit(e[0].value,400);else if(/-?\d+(.\d+)?rad/.test(e[0].value))e[0].value=this.normalizeUnit(e[0].value,2*Math.PI);else if(/-?\d+(.\d+)?turn/.test(e[0].value))e[0].value=this.normalizeUnit(e[0].value,1);else if(e[0].value.includes("deg")){let r=parseFloat(e[0].value);r=L5.wrap(0,360,r),e[0].value=`${r}deg`}return e[0].value==="0deg"?e=this.replaceFirst(e,"to"," ","top"):e[0].value==="90deg"?e=this.replaceFirst(e,"to"," ","right"):e[0].value==="180deg"?e=this.replaceFirst(e,"to"," ","bottom"):e[0].value==="270deg"&&(e=this.replaceFirst(e,"to"," ","left")),e}newDirection(e){if(e[0].value==="to"||(fb.lastIndex=0,!fb.test(e[0].value)))return e;e.unshift({type:"word",value:"to"},{type:"space",value:" "});for(let r=2;r<e.length&&e[r].type!=="div";r++)e[r].type==="word"&&(e[r].value=this.revertDirection(e[r].value));return e}isRadial(e){let r="before";for(let i of e)if(r==="before"&&i.type==="space")r="at";else if(r==="at"&&i.value==="at")r="after";else{if(r==="after"&&i.type==="space")return!0;if(i.type==="div")break;r="before"}return!1}convertDirection(e){return e.length>0&&(e[0].value==="to"?this.fixDirection(e):e[0].value.includes("deg")?this.fixAngle(e):this.isRadial(e)&&this.fixRadial(e)),e}fixDirection(e){e.splice(0,2);for(let r of e){if(r.type==="div")break;r.type==="word"&&(r.value=this.revertDirection(r.value))}}fixAngle(e){let r=e[0].value;r=parseFloat(r),r=Math.abs(450-r)%360,r=this.roundFloat(r,3),e[0].value=`${r}deg`}fixRadial(e){let r=[],i=[],n,s,a,o,u;for(o=0;o<e.length-2;o++)if(n=e[o],s=e[o+1],a=e[o+2],n.type==="space"&&s.value==="at"&&a.type==="space"){u=o+3;break}else r.push(n);let c;for(o=u;o<e.length;o++)if(e[o].type==="div"){c=e[o];break}else i.push(e[o]);e.splice(0,o,...i,c,...r)}revertDirection(e){return vt.directions[e.toLowerCase()]||e}roundFloat(e,r){return parseFloat(e.toFixed(r))}oldWebkit(e){let{nodes:r}=e,i=Tf.stringify(e.nodes);if(this.name!=="linear-gradient"||r[0]&&r[0].value.includes("deg")||i.includes("px")||i.includes("-corner")||i.includes("-side"))return!1;let n=[[]];for(let s of r)n[n.length-1].push(s),s.type==="div"&&s.value===","&&n.push([]);this.oldDirection(n),this.colorStops(n),e.nodes=[];for(let s of n)e.nodes=e.nodes.concat(s);return e.nodes.unshift({type:"word",value:"linear"},this.cloneDiv(e.nodes)),e.value="-webkit-gradient",!0}oldDirection(e){let r=this.cloneDiv(e[0]);if(e[0][0].value!=="to")return e.unshift([{type:"word",value:vt.oldDirections.bottom},r]);{let i=[];for(let s of e[0].slice(2))s.type==="word"&&i.push(s.value.toLowerCase());i=i.join(" ");let n=vt.oldDirections[i]||i;return e[0]=[{type:"word",value:n},r],e[0]}}cloneDiv(e){for(let r of e)if(r.type==="div"&&r.value===",")return r;return{type:"div",value:",",after:" "}}colorStops(e){let r=[];for(let i=0;i<e.length;i++){let n,s=e[i],a;if(i===0)continue;let o=Tf.stringify(s[0]);s[1]&&s[1].type==="word"?n=s[1].value:s[2]&&s[2].type==="word"&&(n=s[2].value);let u;i===1&&(!n||n==="0%")?u=`from(${o})`:i===e.length-1&&(!n||n==="100%")?u=`to(${o})`:n?u=`color-stop(${n}, ${o})`:u=`color-stop(${o})`;let c=s[s.length-1];e[i]=[{type:"word",value:u}],c.type==="div"&&c.value===","&&(a=e[i].push(c)),r.push(a)}return r}old(e){if(e==="-webkit-"){let r=this.name==="linear-gradient"?"linear":"radial",i="-gradient",n=F5.regexp(`-webkit-(${r}-gradient|gradient\\(\\s*${r})`,!1);return new B5(this.name,e+this.name,i,n)}else return super.old(e)}add(e,r){let i=e.prop;if(i.includes("mask")){if(r==="-webkit-"||r==="-webkit- old")return super.add(e,r)}else if(i==="list-style"||i==="list-style-image"||i==="content"){if(r==="-webkit-"||r==="-webkit- old")return super.add(e,r)}else return super.add(e,r)}};vt.names=["linear-gradient","repeating-linear-gradient","radial-gradient","repeating-radial-gradient"];vt.directions={top:"bottom",left:"right",bottom:"top",right:"left"};vt.oldDirections={top:"left bottom, left top",left:"right top, left top",bottom:"left top, left bottom",right:"left top, right top","top right":"left bottom, right top","top left":"right bottom, left top","right top":"left bottom, right top","right bottom":"left top, right bottom","bottom right":"left top, right bottom","bottom left":"right top, left bottom","left top":"right bottom, left top","left bottom":"right top, left bottom"};cb.exports=vt});var mb=k((v$,hb)=>{l();var N5=Tr(),z5=Ne();function db(t){return new RegExp(`(^|[\\s,(])(${t}($|[\\s),]))`,"gi")}var Of=class extends z5{regexp(){return this.regexpCache||(this.regexpCache=db(this.name)),this.regexpCache}isStretch(){return this.name==="stretch"||this.name==="fill"||this.name==="fill-available"}replace(e,r){return r==="-moz-"&&this.isStretch()?e.replace(this.regexp(),"$1-moz-available$3"):r==="-webkit-"&&this.isStretch()?e.replace(this.regexp(),"$1-webkit-fill-available$3"):super.replace(e,r)}old(e){let r=e+this.name;return this.isStretch()&&(e==="-moz-"?r="-moz-available":e==="-webkit-"&&(r="-webkit-fill-available")),new N5(this.name,r,r,db(r))}add(e,r){if(!(e.prop.includes("grid")&&r!=="-webkit-"))return super.add(e,r)}};Of.names=["max-content","min-content","fit-content","fill","fill-available","stretch"];hb.exports=Of});var vb=k((w$,yb)=>{l();var gb=Tr(),$5=Ne(),Ef=class extends $5{replace(e,r){return r==="-webkit-"?e.replace(this.regexp(),"$1-webkit-optimize-contrast"):r==="-moz-"?e.replace(this.regexp(),"$1-moz-crisp-edges"):super.replace(e,r)}old(e){return e==="-webkit-"?new gb(this.name,"-webkit-optimize-contrast"):e==="-moz-"?new gb(this.name,"-moz-crisp-edges"):super.old(e)}};Ef.names=["pixelated"];yb.exports=Ef});var bb=k((b$,wb)=>{l();var j5=Ne(),Af=class extends j5{replace(e,r){let i=super.replace(e,r);return r==="-webkit-"&&(i=i.replace(/("[^"]+"|'[^']+')(\s+\d+\w)/gi,"url($1)$2")),i}};Af.names=["image-set"];wb.exports=Af});var kb=k((x$,xb)=>{l();var U5=qe().list,V5=Ne(),Cf=class extends V5{replace(e,r){return U5.space(e).map(i=>{if(i.slice(0,+this.name.length+1)!==this.name+"(")return i;let n=i.lastIndexOf(")"),s=i.slice(n+1),a=i.slice(this.name.length+1,n);if(r==="-webkit-"){let o=a.match(/\d*.?\d+%?/);o?(a=a.slice(o[0].length).trim(),a+=`, ${o[0]}`):a+=", 0.5"}return r+this.name+"("+a+")"+s}).join(" ")}};Cf.names=["cross-fade"];xb.exports=Cf});var _b=k((k$,Sb)=>{l();var W5=Pe(),G5=Tr(),H5=Ne(),Pf=class extends H5{constructor(e,r){super(e,r);e==="display-flex"&&(this.name="flex")}check(e){return e.prop==="display"&&e.value===this.name}prefixed(e){let r,i;return[r,e]=W5(e),r===2009?this.name==="flex"?i="box":i="inline-box":r===2012?this.name==="flex"?i="flexbox":i="inline-flexbox":r==="final"&&(i=this.name),e+i}replace(e,r){return this.prefixed(r)}old(e){let r=this.prefixed(e);if(!!r)return new G5(this.name,r)}};Pf.names=["display-flex","inline-flex"];Sb.exports=Pf});var Ob=k((S$,Tb)=>{l();var Y5=Ne(),If=class extends Y5{constructor(e,r){super(e,r);e==="display-grid"&&(this.name="grid")}check(e){return e.prop==="display"&&e.value===this.name}};If.names=["display-grid","inline-grid"];Tb.exports=If});var Ab=k((_$,Eb)=>{l();var Q5=Ne(),Df=class extends Q5{constructor(e,r){super(e,r);e==="filter-function"&&(this.name="filter")}};Df.names=["filter","filter-function"];Eb.exports=Df});var Db=k((T$,Ib)=>{l();var Cb=ji(),U=j(),Pb=cv(),J5=Cv(),X5=Lu(),K5=Yv(),qf=Nt(),Lr=Or(),Z5=r0(),ot=Ne(),Br=Oe(),e4=n0(),t4=a0(),r4=l0(),i4=f0(),n4=m0(),s4=v0(),a4=b0(),o4=k0(),l4=_0(),u4=O0(),f4=A0(),c4=P0(),p4=D0(),d4=R0(),h4=B0(),m4=N0(),g4=$0(),y4=V0(),v4=G0(),w4=Y0(),b4=X0(),x4=Z0(),k4=rw(),S4=nw(),_4=aw(),T4=lw(),O4=fw(),E4=dw(),A4=mw(),C4=yw(),P4=ww(),I4=xw(),D4=Sw(),q4=Tw(),R4=Aw(),L4=Pw(),B4=Dw(),M4=Rw(),F4=Bw(),N4=Nw(),z4=$w(),$4=Uw(),j4=Gw(),U4=Yw(),V4=Jw(),W4=Zw(),G4=tb(),H4=ib(),Y4=pb(),Q4=mb(),J4=vb(),X4=bb(),K4=kb(),Z4=_b(),e3=Ob(),t3=Ab();Lr.hack(e4);Lr.hack(t4);Lr.hack(r4);Lr.hack(i4);U.hack(n4);U.hack(s4);U.hack(a4);U.hack(o4);U.hack(l4);U.hack(u4);U.hack(f4);U.hack(c4);U.hack(p4);U.hack(d4);U.hack(h4);U.hack(m4);U.hack(g4);U.hack(y4);U.hack(v4);U.hack(w4);U.hack(b4);U.hack(x4);U.hack(k4);U.hack(S4);U.hack(_4);U.hack(T4);U.hack(O4);U.hack(E4);U.hack(A4);U.hack(C4);U.hack(P4);U.hack(I4);U.hack(D4);U.hack(q4);U.hack(R4);U.hack(L4);U.hack(B4);U.hack(M4);U.hack(F4);U.hack(N4);U.hack(z4);U.hack($4);U.hack(j4);U.hack(U4);U.hack(V4);U.hack(W4);U.hack(G4);U.hack(H4);ot.hack(Y4);ot.hack(Q4);ot.hack(J4);ot.hack(X4);ot.hack(K4);ot.hack(Z4);ot.hack(e3);ot.hack(t3);var Rf=new Map,Vi=class{constructor(e,r,i={}){this.data=e,this.browsers=r,this.options=i,[this.add,this.remove]=this.preprocess(this.select(this.data)),this.transition=new J5(this),this.processor=new X5(this)}cleaner(){if(this.cleanerCache)return this.cleanerCache;if(this.browsers.selected.length){let e=new qf(this.browsers.data,[]);this.cleanerCache=new Vi(this.data,e,this.options)}else return this;return this.cleanerCache}select(e){let r={add:{},remove:{}};for(let i in e){let n=e[i],s=n.browsers.map(u=>{let c=u.split(" ");return{browser:`${c[0]} ${c[1]}`,note:c[2]}}),a=s.filter(u=>u.note).map(u=>`${this.browsers.prefix(u.browser)} ${u.note}`);a=Br.uniq(a),s=s.filter(u=>this.browsers.isSelected(u.browser)).map(u=>{let c=this.browsers.prefix(u.browser);return u.note?`${c} ${u.note}`:c}),s=this.sort(Br.uniq(s)),this.options.flexbox==="no-2009"&&(s=s.filter(u=>!u.includes("2009")));let o=n.browsers.map(u=>this.browsers.prefix(u));n.mistakes&&(o=o.concat(n.mistakes)),o=o.concat(a),o=Br.uniq(o),s.length?(r.add[i]=s,s.length<o.length&&(r.remove[i]=o.filter(u=>!s.includes(u)))):r.remove[i]=o}return r}sort(e){return e.sort((r,i)=>{let n=Br.removeNote(r).length,s=Br.removeNote(i).length;return n===s?i.length-r.length:s-n})}preprocess(e){let r={selectors:[],"@supports":new K5(Vi,this)};for(let n in e.add){let s=e.add[n];if(n==="@keyframes"||n==="@viewport")r[n]=new Z5(n,s,this);else if(n==="@resolution")r[n]=new Pb(n,s,this);else if(this.data[n].selector)r.selectors.push(Lr.load(n,s,this));else{let a=this.data[n].props;if(a){let o=ot.load(n,s,this);for(let u of a)r[u]||(r[u]={values:[]}),r[u].values.push(o)}else{let o=r[n]&&r[n].values||[];r[n]=U.load(n,s,this),r[n].values=o}}}let i={selectors:[]};for(let n in e.remove){let s=e.remove[n];if(this.data[n].selector){let a=Lr.load(n,s);for(let o of s)i.selectors.push(a.old(o))}else if(n==="@keyframes"||n==="@viewport")for(let a of s){let o=`@${a}${n.slice(1)}`;i[o]={remove:!0}}else if(n==="@resolution")i[n]=new Pb(n,s,this);else{let a=this.data[n].props;if(a){let o=ot.load(n,[],this);for(let u of s){let c=o.old(u);if(c)for(let f of a)i[f]||(i[f]={}),i[f].values||(i[f].values=[]),i[f].values.push(c)}}else for(let o of s){let u=this.decl(n).old(n,o);if(n==="align-self"){let c=r[n]&&r[n].prefixes;if(c){if(o==="-webkit- 2009"&&c.includes("-webkit-"))continue;if(o==="-webkit-"&&c.includes("-webkit- 2009"))continue}}for(let c of u)i[c]||(i[c]={}),i[c].remove=!0}}}return[r,i]}decl(e){return Rf.has(e)||Rf.set(e,U.load(e)),Rf.get(e)}unprefixed(e){let r=this.normalize(Cb.unprefixed(e));return r==="flex-direction"&&(r="flex-flow"),r}normalize(e){return this.decl(e).normalize(e)}prefixed(e,r){return e=Cb.unprefixed(e),this.decl(e).prefixed(e,r)}values(e,r){let i=this[e],n=i["*"]&&i["*"].values,s=i[r]&&i[r].values;return n&&s?Br.uniq(n.concat(s)):n||s||[]}group(e){let r=e.parent,i=r.index(e),{length:n}=r.nodes,s=this.unprefixed(e.prop),a=(o,u)=>{for(i+=o;i>=0&&i<n;){let c=r.nodes[i];if(c.type==="decl"){if(o===-1&&c.prop===s&&!qf.withPrefix(c.value)||this.unprefixed(c.prop)!==s)break;if(u(c)===!0)return!0;if(o===1&&c.prop===s&&!qf.withPrefix(c.value))break}i+=o}return!1};return{up(o){return a(-1,o)},down(o){return a(1,o)}}}};Ib.exports=Vi});var Rb=k((O$,qb)=>{l();qb.exports={"backdrop-filter":{feature:"css-backdrop-filter",browsers:["ios_saf 16.1","ios_saf 16.3","ios_saf 16.4","ios_saf 16.5","safari 16.5"]},element:{props:["background","background-image","border-image","mask","list-style","list-style-image","content","mask-image"],feature:"css-element-function",browsers:["firefox 114"]},"user-select":{mistakes:["-khtml-"],feature:"user-select-none",browsers:["ios_saf 16.1","ios_saf 16.3","ios_saf 16.4","ios_saf 16.5","safari 16.5"]},"background-clip":{feature:"background-clip-text",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},hyphens:{feature:"css-hyphens",browsers:["ios_saf 16.1","ios_saf 16.3","ios_saf 16.4","ios_saf 16.5","safari 16.5"]},fill:{props:["width","min-width","max-width","height","min-height","max-height","inline-size","min-inline-size","max-inline-size","block-size","min-block-size","max-block-size","grid","grid-template","grid-template-rows","grid-template-columns","grid-auto-columns","grid-auto-rows"],feature:"intrinsic-width",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},"fill-available":{props:["width","min-width","max-width","height","min-height","max-height","inline-size","min-inline-size","max-inline-size","block-size","min-block-size","max-block-size","grid","grid-template","grid-template-rows","grid-template-columns","grid-auto-columns","grid-auto-rows"],feature:"intrinsic-width",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},stretch:{props:["width","min-width","max-width","height","min-height","max-height","inline-size","min-inline-size","max-inline-size","block-size","min-block-size","max-block-size","grid","grid-template","grid-template-rows","grid-template-columns","grid-auto-columns","grid-auto-rows"],feature:"intrinsic-width",browsers:["firefox 114"]},"fit-content":{props:["width","min-width","max-width","height","min-height","max-height","inline-size","min-inline-size","max-inline-size","block-size","min-block-size","max-block-size","grid","grid-template","grid-template-rows","grid-template-columns","grid-auto-columns","grid-auto-rows"],feature:"intrinsic-width",browsers:["firefox 114"]},"text-decoration-style":{feature:"text-decoration",browsers:["ios_saf 16.1","ios_saf 16.3","ios_saf 16.4","ios_saf 16.5"]},"text-decoration-color":{feature:"text-decoration",browsers:["ios_saf 16.1","ios_saf 16.3","ios_saf 16.4","ios_saf 16.5"]},"text-decoration-line":{feature:"text-decoration",browsers:["ios_saf 16.1","ios_saf 16.3","ios_saf 16.4","ios_saf 16.5"]},"text-decoration":{feature:"text-decoration",browsers:["ios_saf 16.1","ios_saf 16.3","ios_saf 16.4","ios_saf 16.5"]},"text-decoration-skip":{feature:"text-decoration",browsers:["ios_saf 16.1","ios_saf 16.3","ios_saf 16.4","ios_saf 16.5"]},"text-decoration-skip-ink":{feature:"text-decoration",browsers:["ios_saf 16.1","ios_saf 16.3","ios_saf 16.4","ios_saf 16.5"]},"text-size-adjust":{feature:"text-size-adjust",browsers:["ios_saf 16.1","ios_saf 16.3","ios_saf 16.4","ios_saf 16.5"]},"mask-clip":{feature:"css-masks",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},"mask-composite":{feature:"css-masks",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},"mask-image":{feature:"css-masks",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},"mask-origin":{feature:"css-masks",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},"mask-repeat":{feature:"css-masks",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},"mask-border-repeat":{feature:"css-masks",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},"mask-border-source":{feature:"css-masks",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},mask:{feature:"css-masks",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},"mask-position":{feature:"css-masks",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},"mask-size":{feature:"css-masks",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},"mask-border":{feature:"css-masks",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},"mask-border-outset":{feature:"css-masks",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},"mask-border-width":{feature:"css-masks",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},"mask-border-slice":{feature:"css-masks",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},"clip-path":{feature:"css-clip-path",browsers:["samsung 21"]},"box-decoration-break":{feature:"css-boxdecorationbreak",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","ios_saf 16.1","ios_saf 16.3","ios_saf 16.4","ios_saf 16.5","opera 99","safari 16.5","samsung 21"]},appearance:{feature:"css-appearance",browsers:["samsung 21"]},"image-set":{props:["background","background-image","border-image","cursor","mask","mask-image","list-style","list-style-image","content"],feature:"css-image-set",browsers:["and_uc 15.5","chrome 109","samsung 21"]},"cross-fade":{props:["background","background-image","border-image","mask","list-style","list-style-image","content","mask-image"],feature:"css-cross-fade",browsers:["and_chr 114","and_uc 15.5","chrome 109","chrome 113","chrome 114","edge 114","opera 99","samsung 21"]},isolate:{props:["unicode-bidi"],feature:"css-unicode-bidi",browsers:["ios_saf 16.1","ios_saf 16.3","ios_saf 16.4","ios_saf 16.5","safari 16.5"]},"color-adjust":{feature:"css-color-adjust",browsers:["chrome 109","chrome 113","chrome 114","edge 114","opera 99"]}}});var Bb=k((E$,Lb)=>{l();Lb.exports={}});var zb=k((A$,Nb)=>{l();var r3=Su(),{agents:i3}=(ea(),Zs),Lf=Xy(),n3=Nt(),s3=Db(),a3=Rb(),o3=Bb(),Mb={browsers:i3,prefixes:a3},Fb=`
Replace Autoprefixer \`browsers\` option to Browserslist config.
Use \`browserslist\` key in \`package.json\` or \`.browserslistrc\` file.
Using \`browsers\` option can cause errors. Browserslist config can
be used for Babel, Autoprefixer, postcss-normalize and other tools.
If you really need to use option, rename it to \`overrideBrowserslist\`.
Learn more at:
https://github.com/browserslist/browserslist#readme
https://twitter.com/browserslist
`;function l3(t){return Object.prototype.toString.apply(t)==="[object Object]"}var Bf=new Map;function u3(t,e){e.browsers.selected.length!==0&&(e.add.selectors.length>0||Object.keys(e.add).length>2||t.warn(`Autoprefixer target browsers do not need any prefixes.You do not need Autoprefixer anymore.
Check your Browserslist config to be sure that your targets are set up correctly.
Learn more at:
https://github.com/postcss/autoprefixer#readme
https://github.com/browserslist/browserslist#readme
`))}Nb.exports=Mr;function Mr(...t){let e;if(t.length===1&&l3(t[0])?(e=t[0],t=void 0):t.length===0||t.length===1&&!t[0]?t=void 0:t.length<=2&&(Array.isArray(t[0])||!t[0])?(e=t[1],t=t[0]):typeof t[t.length-1]=="object"&&(e=t.pop()),e||(e={}),e.browser)throw new Error("Change `browser` option to `overrideBrowserslist` in Autoprefixer");if(e.browserslist)throw new Error("Change `browserslist` option to `overrideBrowserslist` in Autoprefixer");e.overrideBrowserslist?t=e.overrideBrowserslist:e.browsers&&(typeof console!="undefined"&&console.warn&&(Lf.red?console.warn(Lf.red(Fb.replace(/`[^`]+`/g,n=>Lf.yellow(n.slice(1,-1))))):console.warn(Fb)),t=e.browsers);let r={ignoreUnknownVersions:e.ignoreUnknownVersions,stats:e.stats,env:e.env};function i(n){let s=Mb,a=new n3(s.browsers,t,n,r),o=a.selected.join(", ")+JSON.stringify(e);return Bf.has(o)||Bf.set(o,new s3(s.prefixes,a,e)),Bf.get(o)}return{postcssPlugin:"autoprefixer",prepare(n){let s=i({from:n.opts.from,env:e.env});return{OnceExit(a){u3(n,s),e.remove!==!1&&s.processor.remove(a,n),e.add!==!1&&s.processor.add(a,n)}}},info(n){return n=n||{},n.from=n.from||g.cwd(),o3(i(n))},options:e,browsers:t}}Mr.postcss=!0;Mr.data=Mb;Mr.defaults=r3.defaults;Mr.info=()=>Mr().info()});var m1=k((Qi,zr)=>{l();var f3=200,$b="__lodash_hash_undefined__",c3=800,p3=16,jb=9007199254740991,Ub="[object Arguments]",d3="[object Array]",h3="[object AsyncFunction]",m3="[object Boolean]",g3="[object Date]",y3="[object Error]",Vb="[object Function]",v3="[object GeneratorFunction]",w3="[object Map]",b3="[object Number]",x3="[object Null]",Wb="[object Object]",k3="[object Proxy]",S3="[object RegExp]",_3="[object Set]",T3="[object String]",O3="[object Undefined]",E3="[object WeakMap]",A3="[object ArrayBuffer]",C3="[object DataView]",P3="[object Float32Array]",I3="[object Float64Array]",D3="[object Int8Array]",q3="[object Int16Array]",R3="[object Int32Array]",L3="[object Uint8Array]",B3="[object Uint8ClampedArray]",M3="[object Uint16Array]",F3="[object Uint32Array]",N3=/[\\^$.*+?()[\]{}|]/g,z3=/^\[object .+?Constructor\]$/,$3=/^(?:0|[1-9]\d*)$/,se={};se[P3]=se[I3]=se[D3]=se[q3]=se[R3]=se[L3]=se[B3]=se[M3]=se[F3]=!0;se[Ub]=se[d3]=se[A3]=se[m3]=se[C3]=se[g3]=se[y3]=se[Vb]=se[w3]=se[b3]=se[Wb]=se[S3]=se[_3]=se[T3]=se[E3]=!1;var Gb=typeof global=="object"&&global&&global.Object===Object&&global,j3=typeof self=="object"&&self&&self.Object===Object&&self,Wi=Gb||j3||Function("return this")(),Hb=typeof Qi=="object"&&Qi&&!Qi.nodeType&&Qi,Gi=Hb&&typeof zr=="object"&&zr&&!zr.nodeType&&zr,Yb=Gi&&Gi.exports===Hb,Mf=Yb&&Gb.process,Qb=function(){try{var t=Gi&&Gi.require&&Gi.require("util").types;return t||Mf&&Mf.binding&&Mf.binding("util")}catch(e){}}(),Jb=Qb&&Qb.isTypedArray;function U3(t,e,r){switch(r.length){case 0:return t.call(e);case 1:return t.call(e,r[0]);case 2:return t.call(e,r[0],r[1]);case 3:return t.call(e,r[0],r[1],r[2])}return t.apply(e,r)}function V3(t,e){for(var r=-1,i=Array(t);++r<t;)i[r]=e(r);return i}function W3(t){return function(e){return t(e)}}function G3(t,e){return t==null?void 0:t[e]}function H3(t,e){return function(r){return t(e(r))}}var Y3=Array.prototype,Q3=Function.prototype,oa=Object.prototype,Ff=Wi["__core-js_shared__"],la=Q3.toString,wt=oa.hasOwnProperty,Xb=function(){var t=/[^.]+$/.exec(Ff&&Ff.keys&&Ff.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),Kb=oa.toString,J3=la.call(Object),X3=RegExp("^"+la.call(wt).replace(N3,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ua=Yb?Wi.Buffer:void 0,Zb=Wi.Symbol,e1=Wi.Uint8Array,t1=ua?ua.allocUnsafe:void 0,r1=H3(Object.getPrototypeOf,Object),i1=Object.create,K3=oa.propertyIsEnumerable,Z3=Y3.splice,Qt=Zb?Zb.toStringTag:void 0,fa=function(){try{var t=$f(Object,"defineProperty");return t({},"",{}),t}catch(e){}}(),e6=ua?ua.isBuffer:void 0,n1=Math.max,t6=Date.now,s1=$f(Wi,"Map"),Hi=$f(Object,"create"),r6=function(){function t(){}return function(e){if(!Xt(e))return{};if(i1)return i1(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();function Jt(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var i=t[e];this.set(i[0],i[1])}}function i6(){this.__data__=Hi?Hi(null):{},this.size=0}function n6(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}function s6(t){var e=this.__data__;if(Hi){var r=e[t];return r===$b?void 0:r}return wt.call(e,t)?e[t]:void 0}function a6(t){var e=this.__data__;return Hi?e[t]!==void 0:wt.call(e,t)}function o6(t,e){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=Hi&&e===void 0?$b:e,this}Jt.prototype.clear=i6;Jt.prototype.delete=n6;Jt.prototype.get=s6;Jt.prototype.has=a6;Jt.prototype.set=o6;function bt(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var i=t[e];this.set(i[0],i[1])}}function l6(){this.__data__=[],this.size=0}function u6(t){var e=this.__data__,r=ca(e,t);if(r<0)return!1;var i=e.length-1;return r==i?e.pop():Z3.call(e,r,1),--this.size,!0}function f6(t){var e=this.__data__,r=ca(e,t);return r<0?void 0:e[r][1]}function c6(t){return ca(this.__data__,t)>-1}function p6(t,e){var r=this.__data__,i=ca(r,t);return i<0?(++this.size,r.push([t,e])):r[i][1]=e,this}bt.prototype.clear=l6;bt.prototype.delete=u6;bt.prototype.get=f6;bt.prototype.has=c6;bt.prototype.set=p6;function Fr(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var i=t[e];this.set(i[0],i[1])}}function d6(){this.size=0,this.__data__={hash:new Jt,map:new(s1||bt),string:new Jt}}function h6(t){var e=da(this,t).delete(t);return this.size-=e?1:0,e}function m6(t){return da(this,t).get(t)}function g6(t){return da(this,t).has(t)}function y6(t,e){var r=da(this,t),i=r.size;return r.set(t,e),this.size+=r.size==i?0:1,this}Fr.prototype.clear=d6;Fr.prototype.delete=h6;Fr.prototype.get=m6;Fr.prototype.has=g6;Fr.prototype.set=y6;function Nr(t){var e=this.__data__=new bt(t);this.size=e.size}function v6(){this.__data__=new bt,this.size=0}function w6(t){var e=this.__data__,r=e.delete(t);return this.size=e.size,r}function b6(t){return this.__data__.get(t)}function x6(t){return this.__data__.has(t)}function k6(t,e){var r=this.__data__;if(r instanceof bt){var i=r.__data__;if(!s1||i.length<f3-1)return i.push([t,e]),this.size=++r.size,this;r=this.__data__=new Fr(i)}return r.set(t,e),this.size=r.size,this}Nr.prototype.clear=v6;Nr.prototype.delete=w6;Nr.prototype.get=b6;Nr.prototype.has=x6;Nr.prototype.set=k6;function S6(t,e){var r=Vf(t),i=!r&&Uf(t),n=!r&&!i&&f1(t),s=!r&&!i&&!n&&p1(t),a=r||i||n||s,o=a?V3(t.length,String):[],u=o.length;for(var c in t)(e||wt.call(t,c))&&!(a&&(c=="length"||n&&(c=="offset"||c=="parent")||s&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||l1(c,u)))&&o.push(c);return o}function Nf(t,e,r){(r!==void 0&&!ha(t[e],r)||r===void 0&&!(e in t))&&zf(t,e,r)}function _6(t,e,r){var i=t[e];(!(wt.call(t,e)&&ha(i,r))||r===void 0&&!(e in t))&&zf(t,e,r)}function ca(t,e){for(var r=t.length;r--;)if(ha(t[r][0],e))return r;return-1}function zf(t,e,r){e=="__proto__"&&fa?fa(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}var T6=F6();function pa(t){return t==null?t===void 0?O3:x3:Qt&&Qt in Object(t)?N6(t):W6(t)}function a1(t){return Yi(t)&&pa(t)==Ub}function O6(t){if(!Xt(t)||U6(t))return!1;var e=Gf(t)?X3:z3;return e.test(Q6(t))}function E6(t){return Yi(t)&&c1(t.length)&&!!se[pa(t)]}function A6(t){if(!Xt(t))return V6(t);var e=u1(t),r=[];for(var i in t)i=="constructor"&&(e||!wt.call(t,i))||r.push(i);return r}function o1(t,e,r,i,n){t!==e&&T6(e,function(s,a){if(n||(n=new Nr),Xt(s))C6(t,e,a,r,o1,i,n);else{var o=i?i(jf(t,a),s,a+"",t,e,n):void 0;o===void 0&&(o=s),Nf(t,a,o)}},d1)}function C6(t,e,r,i,n,s,a){var o=jf(t,r),u=jf(e,r),c=a.get(u);if(c){Nf(t,r,c);return}var f=s?s(o,u,r+"",t,e,a):void 0,p=f===void 0;if(p){var h=Vf(u),m=!h&&f1(u),v=!h&&!m&&p1(u);f=u,h||m||v?Vf(o)?f=o:J6(o)?f=L6(o):m?(p=!1,f=D6(u,!0)):v?(p=!1,f=R6(u,!0)):f=[]:X6(u)||Uf(u)?(f=o,Uf(o)?f=K6(o):(!Xt(o)||Gf(o))&&(f=z6(u))):p=!1}p&&(a.set(u,f),n(f,u,i,s,a),a.delete(u)),Nf(t,r,f)}function P6(t,e){return H6(G6(t,e,h1),t+"")}var I6=fa?function(t,e){return fa(t,"toString",{configurable:!0,enumerable:!1,value:eI(e),writable:!0})}:h1;function D6(t,e){if(e)return t.slice();var r=t.length,i=t1?t1(r):new t.constructor(r);return t.copy(i),i}function q6(t){var e=new t.constructor(t.byteLength);return new e1(e).set(new e1(t)),e}function R6(t,e){var r=e?q6(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.length)}function L6(t,e){var r=-1,i=t.length;for(e||(e=Array(i));++r<i;)e[r]=t[r];return e}function B6(t,e,r,i){var n=!r;r||(r={});for(var s=-1,a=e.length;++s<a;){var o=e[s],u=i?i(r[o],t[o],o,r,t):void 0;u===void 0&&(u=t[o]),n?zf(r,o,u):_6(r,o,u)}return r}function M6(t){return P6(function(e,r){var i=-1,n=r.length,s=n>1?r[n-1]:void 0,a=n>2?r[2]:void 0;for(s=t.length>3&&typeof s=="function"?(n--,s):void 0,a&&$6(r[0],r[1],a)&&(s=n<3?void 0:s,n=1),e=Object(e);++i<n;){var o=r[i];o&&t(e,o,i,s)}return e})}function F6(t){return function(e,r,i){for(var n=-1,s=Object(e),a=i(e),o=a.length;o--;){var u=a[t?o:++n];if(r(s[u],u,s)===!1)break}return e}}function da(t,e){var r=t.__data__;return j6(e)?r[typeof e=="string"?"string":"hash"]:r.map}function $f(t,e){var r=G3(t,e);return O6(r)?r:void 0}function N6(t){var e=wt.call(t,Qt),r=t[Qt];try{t[Qt]=void 0;var i=!0}catch(s){}var n=Kb.call(t);return i&&(e?t[Qt]=r:delete t[Qt]),n}function z6(t){return typeof t.constructor=="function"&&!u1(t)?r6(r1(t)):{}}function l1(t,e){var r=typeof t;return e=e??jb,!!e&&(r=="number"||r!="symbol"&&$3.test(t))&&t>-1&&t%1==0&&t<e}function $6(t,e,r){if(!Xt(r))return!1;var i=typeof e;return(i=="number"?Wf(r)&&l1(e,r.length):i=="string"&&e in r)?ha(r[e],t):!1}function j6(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function U6(t){return!!Xb&&Xb in t}function u1(t){var e=t&&t.constructor,r=typeof e=="function"&&e.prototype||oa;return t===r}function V6(t){var e=[];if(t!=null)for(var r in Object(t))e.push(r);return e}function W6(t){return Kb.call(t)}function G6(t,e,r){return e=n1(e===void 0?t.length-1:e,0),function(){for(var i=arguments,n=-1,s=n1(i.length-e,0),a=Array(s);++n<s;)a[n]=i[e+n];n=-1;for(var o=Array(e+1);++n<e;)o[n]=i[n];return o[e]=r(a),U3(t,this,o)}}function jf(t,e){if(!(e==="constructor"&&typeof t[e]=="function")&&e!="__proto__")return t[e]}var H6=Y6(I6);function Y6(t){var e=0,r=0;return function(){var i=t6(),n=p3-(i-r);if(r=i,n>0){if(++e>=c3)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function Q6(t){if(t!=null){try{return la.call(t)}catch(e){}try{return t+""}catch(e){}}return""}function ha(t,e){return t===e||t!==t&&e!==e}var Uf=a1(function(){return arguments}())?a1:function(t){return Yi(t)&&wt.call(t,"callee")&&!K3.call(t,"callee")},Vf=Array.isArray;function Wf(t){return t!=null&&c1(t.length)&&!Gf(t)}function J6(t){return Yi(t)&&Wf(t)}var f1=e6||tI;function Gf(t){if(!Xt(t))return!1;var e=pa(t);return e==Vb||e==v3||e==h3||e==k3}function c1(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=jb}function Xt(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}function Yi(t){return t!=null&&typeof t=="object"}function X6(t){if(!Yi(t)||pa(t)!=Wb)return!1;var e=r1(t);if(e===null)return!0;var r=wt.call(e,"constructor")&&e.constructor;return typeof r=="function"&&r instanceof r&&la.call(r)==J3}var p1=Jb?W3(Jb):E6;function K6(t){return B6(t,d1(t))}function d1(t){return Wf(t)?S6(t,!0):A6(t)}var Z6=M6(function(t,e,r){o1(t,e,r)});function eI(t){return function(){return t}}function h1(t){return t}function tI(){return!1}zr.exports=Z6});var y1=k((C$,g1)=>{l();function rI(){if(!arguments.length)return[];var t=arguments[0];return iI(t)?t:[t]}var iI=Array.isArray;g1.exports=rI});var w1=k((P$,v1)=>{l();var x=(Tn(),Da).default,$=t=>t.toFixed(7).replace(/(\.[0-9]+?)0+$/,"$1").replace(/\.0$/,""),Ee=t=>`${$(t/16)}rem`,d=(t,e)=>`${$(t/e)}em`,lt=t=>{t=t.replace("#",""),t=t.length===3?t.replace(/./g,"$&$&"):t;let e=parseInt(t.substring(0,2),16),r=parseInt(t.substring(2,4),16),i=parseInt(t.substring(4,6),16);return`${e} ${r} ${i}`},Hf={sm:{css:[{fontSize:Ee(14),lineHeight:$(24/14),p:{marginTop:d(16,14),marginBottom:d(16,14)},'[class~="lead"]':{fontSize:d(18,14),lineHeight:$(28/18),marginTop:d(16,18),marginBottom:d(16,18)},blockquote:{marginTop:d(24,18),marginBottom:d(24,18),paddingLeft:d(20,18)},h1:{fontSize:d(30,14),marginTop:"0",marginBottom:d(24,30),lineHeight:$(36/30)},h2:{fontSize:d(20,14),marginTop:d(32,20),marginBottom:d(16,20),lineHeight:$(28/20)},h3:{fontSize:d(18,14),marginTop:d(28,18),marginBottom:d(8,18),lineHeight:$(28/18)},h4:{marginTop:d(20,14),marginBottom:d(8,14),lineHeight:$(20/14)},img:{marginTop:d(24,14),marginBottom:d(24,14)},picture:{marginTop:d(24,14),marginBottom:d(24,14)},"picture > img":{marginTop:"0",marginBottom:"0"},video:{marginTop:d(24,14),marginBottom:d(24,14)},kbd:{fontSize:d(12,14),borderRadius:Ee(5),paddingTop:d(2,14),paddingRight:d(5,14),paddingBottom:d(2,14),paddingLeft:d(5,14)},code:{fontSize:d(12,14)},"h2 code":{fontSize:d(18,20)},"h3 code":{fontSize:d(16,18)},pre:{fontSize:d(12,14),lineHeight:$(20/12),marginTop:d(20,12),marginBottom:d(20,12),borderRadius:Ee(4),paddingTop:d(8,12),paddingRight:d(12,12),paddingBottom:d(8,12),paddingLeft:d(12,12)},ol:{marginTop:d(16,14),marginBottom:d(16,14),paddingLeft:d(22,14)},ul:{marginTop:d(16,14),marginBottom:d(16,14),paddingLeft:d(22,14)},li:{marginTop:d(4,14),marginBottom:d(4,14)},"ol > li":{paddingLeft:d(6,14)},"ul > li":{paddingLeft:d(6,14)},"> ul > li p":{marginTop:d(8,14),marginBottom:d(8,14)},"> ul > li > *:first-child":{marginTop:d(16,14)},"> ul > li > *:last-child":{marginBottom:d(16,14)},"> ol > li > *:first-child":{marginTop:d(16,14)},"> ol > li > *:last-child":{marginBottom:d(16,14)},"ul ul, ul ol, ol ul, ol ol":{marginTop:d(8,14),marginBottom:d(8,14)},dl:{marginTop:d(16,14),marginBottom:d(16,14)},dt:{marginTop:d(16,14)},dd:{marginTop:d(4,14),paddingLeft:d(22,14)},hr:{marginTop:d(40,14),marginBottom:d(40,14)},"hr + *":{marginTop:"0"},"h2 + *":{marginTop:"0"},"h3 + *":{marginTop:"0"},"h4 + *":{marginTop:"0"},table:{fontSize:d(12,14),lineHeight:$(18/12)},"thead th":{paddingRight:d(12,12),paddingBottom:d(8,12),paddingLeft:d(12,12)},"thead th:first-child":{paddingLeft:"0"},"thead th:last-child":{paddingRight:"0"},"tbody td, tfoot td":{paddingTop:d(8,12),paddingRight:d(12,12),paddingBottom:d(8,12),paddingLeft:d(12,12)},"tbody td:first-child, tfoot td:first-child":{paddingLeft:"0"},"tbody td:last-child, tfoot td:last-child":{paddingRight:"0"},figure:{marginTop:d(24,14),marginBottom:d(24,14)},"figure > *":{marginTop:"0",marginBottom:"0"},figcaption:{fontSize:d(12,14),lineHeight:$(16/12),marginTop:d(8,12)}},{"> :first-child":{marginTop:"0"},"> :last-child":{marginBottom:"0"}}]},base:{css:[{fontSize:Ee(16),lineHeight:$(28/16),p:{marginTop:d(20,16),marginBottom:d(20,16)},'[class~="lead"]':{fontSize:d(20,16),lineHeight:$(32/20),marginTop:d(24,20),marginBottom:d(24,20)},blockquote:{marginTop:d(32,20),marginBottom:d(32,20),paddingLeft:d(20,20)},h1:{fontSize:d(36,16),marginTop:"0",marginBottom:d(32,36),lineHeight:$(40/36)},h2:{fontSize:d(24,16),marginTop:d(48,24),marginBottom:d(24,24),lineHeight:$(32/24)},h3:{fontSize:d(20,16),marginTop:d(32,20),marginBottom:d(12,20),lineHeight:$(32/20)},h4:{marginTop:d(24,16),marginBottom:d(8,16),lineHeight:$(24/16)},img:{marginTop:d(32,16),marginBottom:d(32,16)},picture:{marginTop:d(32,16),marginBottom:d(32,16)},"picture > img":{marginTop:"0",marginBottom:"0"},video:{marginTop:d(32,16),marginBottom:d(32,16)},kbd:{fontSize:d(14,16),borderRadius:Ee(5),paddingTop:d(3,16),paddingRight:d(6,16),paddingBottom:d(3,16),paddingLeft:d(6,16)},code:{fontSize:d(14,16)},"h2 code":{fontSize:d(21,24)},"h3 code":{fontSize:d(18,20)},pre:{fontSize:d(14,16),lineHeight:$(24/14),marginTop:d(24,14),marginBottom:d(24,14),borderRadius:Ee(6),paddingTop:d(12,14),paddingRight:d(16,14),paddingBottom:d(12,14),paddingLeft:d(16,14)},ol:{marginTop:d(20,16),marginBottom:d(20,16),paddingLeft:d(26,16)},ul:{marginTop:d(20,16),marginBottom:d(20,16),paddingLeft:d(26,16)},li:{marginTop:d(8,16),marginBottom:d(8,16)},"ol > li":{paddingLeft:d(6,16)},"ul > li":{paddingLeft:d(6,16)},"> ul > li p":{marginTop:d(12,16),marginBottom:d(12,16)},"> ul > li > *:first-child":{marginTop:d(20,16)},"> ul > li > *:last-child":{marginBottom:d(20,16)},"> ol > li > *:first-child":{marginTop:d(20,16)},"> ol > li > *:last-child":{marginBottom:d(20,16)},"ul ul, ul ol, ol ul, ol ol":{marginTop:d(12,16),marginBottom:d(12,16)},dl:{marginTop:d(20,16),marginBottom:d(20,16)},dt:{marginTop:d(20,16)},dd:{marginTop:d(8,16),paddingLeft:d(26,16)},hr:{marginTop:d(48,16),marginBottom:d(48,16)},"hr + *":{marginTop:"0"},"h2 + *":{marginTop:"0"},"h3 + *":{marginTop:"0"},"h4 + *":{marginTop:"0"},table:{fontSize:d(14,16),lineHeight:$(24/14)},"thead th":{paddingRight:d(8,14),paddingBottom:d(8,14),paddingLeft:d(8,14)},"thead th:first-child":{paddingLeft:"0"},"thead th:last-child":{paddingRight:"0"},"tbody td, tfoot td":{paddingTop:d(8,14),paddingRight:d(8,14),paddingBottom:d(8,14),paddingLeft:d(8,14)},"tbody td:first-child, tfoot td:first-child":{paddingLeft:"0"},"tbody td:last-child, tfoot td:last-child":{paddingRight:"0"},figure:{marginTop:d(32,16),marginBottom:d(32,16)},"figure > *":{marginTop:"0",marginBottom:"0"},figcaption:{fontSize:d(14,16),lineHeight:$(20/14),marginTop:d(12,14)}},{"> :first-child":{marginTop:"0"},"> :last-child":{marginBottom:"0"}}]},lg:{css:[{fontSize:Ee(18),lineHeight:$(32/18),p:{marginTop:d(24,18),marginBottom:d(24,18)},'[class~="lead"]':{fontSize:d(22,18),lineHeight:$(32/22),marginTop:d(24,22),marginBottom:d(24,22)},blockquote:{marginTop:d(40,24),marginBottom:d(40,24),paddingLeft:d(24,24)},h1:{fontSize:d(48,18),marginTop:"0",marginBottom:d(40,48),lineHeight:$(48/48)},h2:{fontSize:d(30,18),marginTop:d(56,30),marginBottom:d(32,30),lineHeight:$(40/30)},h3:{fontSize:d(24,18),marginTop:d(40,24),marginBottom:d(16,24),lineHeight:$(36/24)},h4:{marginTop:d(32,18),marginBottom:d(8,18),lineHeight:$(28/18)},img:{marginTop:d(32,18),marginBottom:d(32,18)},picture:{marginTop:d(32,18),marginBottom:d(32,18)},"picture > img":{marginTop:"0",marginBottom:"0"},video:{marginTop:d(32,18),marginBottom:d(32,18)},kbd:{fontSize:d(16,18),borderRadius:Ee(5),paddingTop:d(4,18),paddingRight:d(8,18),paddingBottom:d(4,18),paddingLeft:d(8,18)},code:{fontSize:d(16,18)},"h2 code":{fontSize:d(26,30)},"h3 code":{fontSize:d(21,24)},pre:{fontSize:d(16,18),lineHeight:$(28/16),marginTop:d(32,16),marginBottom:d(32,16),borderRadius:Ee(6),paddingTop:d(16,16),paddingRight:d(24,16),paddingBottom:d(16,16),paddingLeft:d(24,16)},ol:{marginTop:d(24,18),marginBottom:d(24,18),paddingLeft:d(28,18)},ul:{marginTop:d(24,18),marginBottom:d(24,18),paddingLeft:d(28,18)},li:{marginTop:d(12,18),marginBottom:d(12,18)},"ol > li":{paddingLeft:d(8,18)},"ul > li":{paddingLeft:d(8,18)},"> ul > li p":{marginTop:d(16,18),marginBottom:d(16,18)},"> ul > li > *:first-child":{marginTop:d(24,18)},"> ul > li > *:last-child":{marginBottom:d(24,18)},"> ol > li > *:first-child":{marginTop:d(24,18)},"> ol > li > *:last-child":{marginBottom:d(24,18)},"ul ul, ul ol, ol ul, ol ol":{marginTop:d(16,18),marginBottom:d(16,18)},dl:{marginTop:d(24,18),marginBottom:d(24,18)},dt:{marginTop:d(24,18)},dd:{marginTop:d(12,18),paddingLeft:d(28,18)},hr:{marginTop:d(56,18),marginBottom:d(56,18)},"hr + *":{marginTop:"0"},"h2 + *":{marginTop:"0"},"h3 + *":{marginTop:"0"},"h4 + *":{marginTop:"0"},table:{fontSize:d(16,18),lineHeight:$(24/16)},"thead th":{paddingRight:d(12,16),paddingBottom:d(12,16),paddingLeft:d(12,16)},"thead th:first-child":{paddingLeft:"0"},"thead th:last-child":{paddingRight:"0"},"tbody td, tfoot td":{paddingTop:d(12,16),paddingRight:d(12,16),paddingBottom:d(12,16),paddingLeft:d(12,16)},"tbody td:first-child, tfoot td:first-child":{paddingLeft:"0"},"tbody td:last-child, tfoot td:last-child":{paddingRight:"0"},figure:{marginTop:d(32,18),marginBottom:d(32,18)},"figure > *":{marginTop:"0",marginBottom:"0"},figcaption:{fontSize:d(16,18),lineHeight:$(24/16),marginTop:d(16,16)}},{"> :first-child":{marginTop:"0"},"> :last-child":{marginBottom:"0"}}]},xl:{css:[{fontSize:Ee(20),lineHeight:$(36/20),p:{marginTop:d(24,20),marginBottom:d(24,20)},'[class~="lead"]':{fontSize:d(24,20),lineHeight:$(36/24),marginTop:d(24,24),marginBottom:d(24,24)},blockquote:{marginTop:d(48,30),marginBottom:d(48,30),paddingLeft:d(32,30)},h1:{fontSize:d(56,20),marginTop:"0",marginBottom:d(48,56),lineHeight:$(56/56)},h2:{fontSize:d(36,20),marginTop:d(56,36),marginBottom:d(32,36),lineHeight:$(40/36)},h3:{fontSize:d(30,20),marginTop:d(48,30),marginBottom:d(20,30),lineHeight:$(40/30)},h4:{marginTop:d(36,20),marginBottom:d(12,20),lineHeight:$(32/20)},img:{marginTop:d(40,20),marginBottom:d(40,20)},picture:{marginTop:d(40,20),marginBottom:d(40,20)},"picture > img":{marginTop:"0",marginBottom:"0"},video:{marginTop:d(40,20),marginBottom:d(40,20)},kbd:{fontSize:d(18,20),borderRadius:Ee(5),paddingTop:d(5,20),paddingRight:d(8,20),paddingBottom:d(5,20),paddingLeft:d(8,20)},code:{fontSize:d(18,20)},"h2 code":{fontSize:d(31,36)},"h3 code":{fontSize:d(27,30)},pre:{fontSize:d(18,20),lineHeight:$(32/18),marginTop:d(36,18),marginBottom:d(36,18),borderRadius:Ee(8),paddingTop:d(20,18),paddingRight:d(24,18),paddingBottom:d(20,18),paddingLeft:d(24,18)},ol:{marginTop:d(24,20),marginBottom:d(24,20),paddingLeft:d(32,20)},ul:{marginTop:d(24,20),marginBottom:d(24,20),paddingLeft:d(32,20)},li:{marginTop:d(12,20),marginBottom:d(12,20)},"ol > li":{paddingLeft:d(8,20)},"ul > li":{paddingLeft:d(8,20)},"> ul > li p":{marginTop:d(16,20),marginBottom:d(16,20)},"> ul > li > *:first-child":{marginTop:d(24,20)},"> ul > li > *:last-child":{marginBottom:d(24,20)},"> ol > li > *:first-child":{marginTop:d(24,20)},"> ol > li > *:last-child":{marginBottom:d(24,20)},"ul ul, ul ol, ol ul, ol ol":{marginTop:d(16,20),marginBottom:d(16,20)},dl:{marginTop:d(24,20),marginBottom:d(24,20)},dt:{marginTop:d(24,20)},dd:{marginTop:d(12,20),paddingLeft:d(32,20)},hr:{marginTop:d(56,20),marginBottom:d(56,20)},"hr + *":{marginTop:"0"},"h2 + *":{marginTop:"0"},"h3 + *":{marginTop:"0"},"h4 + *":{marginTop:"0"},table:{fontSize:d(18,20),lineHeight:$(28/18)},"thead th":{paddingRight:d(12,18),paddingBottom:d(16,18),paddingLeft:d(12,18)},"thead th:first-child":{paddingLeft:"0"},"thead th:last-child":{paddingRight:"0"},"tbody td, tfoot td":{paddingTop:d(16,18),paddingRight:d(12,18),paddingBottom:d(16,18),paddingLeft:d(12,18)},"tbody td:first-child, tfoot td:first-child":{paddingLeft:"0"},"tbody td:last-child, tfoot td:last-child":{paddingRight:"0"},figure:{marginTop:d(40,20),marginBottom:d(40,20)},"figure > *":{marginTop:"0",marginBottom:"0"},figcaption:{fontSize:d(18,20),lineHeight:$(28/18),marginTop:d(18,18)}},{"> :first-child":{marginTop:"0"},"> :last-child":{marginBottom:"0"}}]},"2xl":{css:[{fontSize:Ee(24),lineHeight:$(40/24),p:{marginTop:d(32,24),marginBottom:d(32,24)},'[class~="lead"]':{fontSize:d(30,24),lineHeight:$(44/30),marginTop:d(32,30),marginBottom:d(32,30)},blockquote:{marginTop:d(64,36),marginBottom:d(64,36),paddingLeft:d(40,36)},h1:{fontSize:d(64,24),marginTop:"0",marginBottom:d(56,64),lineHeight:$(64/64)},h2:{fontSize:d(48,24),marginTop:d(72,48),marginBottom:d(40,48),lineHeight:$(52/48)},h3:{fontSize:d(36,24),marginTop:d(56,36),marginBottom:d(24,36),lineHeight:$(44/36)},h4:{marginTop:d(40,24),marginBottom:d(16,24),lineHeight:$(36/24)},img:{marginTop:d(48,24),marginBottom:d(48,24)},picture:{marginTop:d(48,24),marginBottom:d(48,24)},"picture > img":{marginTop:"0",marginBottom:"0"},video:{marginTop:d(48,24),marginBottom:d(48,24)},kbd:{fontSize:d(20,24),borderRadius:Ee(6),paddingTop:d(6,24),paddingRight:d(8,24),paddingBottom:d(6,24),paddingLeft:d(8,24)},code:{fontSize:d(20,24)},"h2 code":{fontSize:d(42,48)},"h3 code":{fontSize:d(32,36)},pre:{fontSize:d(20,24),lineHeight:$(36/20),marginTop:d(40,20),marginBottom:d(40,20),borderRadius:Ee(8),paddingTop:d(24,20),paddingRight:d(32,20),paddingBottom:d(24,20),paddingLeft:d(32,20)},ol:{marginTop:d(32,24),marginBottom:d(32,24),paddingLeft:d(38,24)},ul:{marginTop:d(32,24),marginBottom:d(32,24),paddingLeft:d(38,24)},li:{marginTop:d(12,24),marginBottom:d(12,24)},"ol > li":{paddingLeft:d(10,24)},"ul > li":{paddingLeft:d(10,24)},"> ul > li p":{marginTop:d(20,24),marginBottom:d(20,24)},"> ul > li > *:first-child":{marginTop:d(32,24)},"> ul > li > *:last-child":{marginBottom:d(32,24)},"> ol > li > *:first-child":{marginTop:d(32,24)},"> ol > li > *:last-child":{marginBottom:d(32,24)},"ul ul, ul ol, ol ul, ol ol":{marginTop:d(16,24),marginBottom:d(16,24)},dl:{marginTop:d(32,24),marginBottom:d(32,24)},dt:{marginTop:d(32,24)},dd:{marginTop:d(12,24),paddingLeft:d(38,24)},hr:{marginTop:d(72,24),marginBottom:d(72,24)},"hr + *":{marginTop:"0"},"h2 + *":{marginTop:"0"},"h3 + *":{marginTop:"0"},"h4 + *":{marginTop:"0"},table:{fontSize:d(20,24),lineHeight:$(28/20)},"thead th":{paddingRight:d(12,20),paddingBottom:d(16,20),paddingLeft:d(12,20)},"thead th:first-child":{paddingLeft:"0"},"thead th:last-child":{paddingRight:"0"},"tbody td, tfoot td":{paddingTop:d(16,20),paddingRight:d(12,20),paddingBottom:d(16,20),paddingLeft:d(12,20)},"tbody td:first-child, tfoot td:first-child":{paddingLeft:"0"},"tbody td:last-child, tfoot td:last-child":{paddingRight:"0"},figure:{marginTop:d(48,24),marginBottom:d(48,24)},"figure > *":{marginTop:"0",marginBottom:"0"},figcaption:{fontSize:d(20,24),lineHeight:$(32/20),marginTop:d(20,20)}},{"> :first-child":{marginTop:"0"},"> :last-child":{marginBottom:"0"}}]},slate:{css:{"--tw-prose-body":x.slate[700],"--tw-prose-headings":x.slate[900],"--tw-prose-lead":x.slate[600],"--tw-prose-links":x.slate[900],"--tw-prose-bold":x.slate[900],"--tw-prose-counters":x.slate[500],"--tw-prose-bullets":x.slate[300],"--tw-prose-hr":x.slate[200],"--tw-prose-quotes":x.slate[900],"--tw-prose-quote-borders":x.slate[200],"--tw-prose-captions":x.slate[500],"--tw-prose-kbd":x.slate[900],"--tw-prose-kbd-shadows":lt(x.slate[900]),"--tw-prose-code":x.slate[900],"--tw-prose-pre-code":x.slate[200],"--tw-prose-pre-bg":x.slate[800],"--tw-prose-th-borders":x.slate[300],"--tw-prose-td-borders":x.slate[200],"--tw-prose-invert-body":x.slate[300],"--tw-prose-invert-headings":x.white,"--tw-prose-invert-lead":x.slate[400],"--tw-prose-invert-links":x.white,"--tw-prose-invert-bold":x.white,"--tw-prose-invert-counters":x.slate[400],"--tw-prose-invert-bullets":x.slate[600],"--tw-prose-invert-hr":x.slate[700],"--tw-prose-invert-quotes":x.slate[100],"--tw-prose-invert-quote-borders":x.slate[700],"--tw-prose-invert-captions":x.slate[400],"--tw-prose-invert-kbd":x.white,"--tw-prose-invert-kbd-shadows":lt(x.white),"--tw-prose-invert-code":x.white,"--tw-prose-invert-pre-code":x.slate[300],"--tw-prose-invert-pre-bg":"rgb(0 0 0 / 50%)","--tw-prose-invert-th-borders":x.slate[600],"--tw-prose-invert-td-borders":x.slate[700]}},gray:{css:{"--tw-prose-body":x.gray[700],"--tw-prose-headings":x.gray[900],"--tw-prose-lead":x.gray[600],"--tw-prose-links":x.gray[900],"--tw-prose-bold":x.gray[900],"--tw-prose-counters":x.gray[500],"--tw-prose-bullets":x.gray[300],"--tw-prose-hr":x.gray[200],"--tw-prose-quotes":x.gray[900],"--tw-prose-quote-borders":x.gray[200],"--tw-prose-captions":x.gray[500],"--tw-prose-kbd":x.gray[900],"--tw-prose-kbd-shadows":lt(x.gray[900]),"--tw-prose-code":x.gray[900],"--tw-prose-pre-code":x.gray[200],"--tw-prose-pre-bg":x.gray[800],"--tw-prose-th-borders":x.gray[300],"--tw-prose-td-borders":x.gray[200],"--tw-prose-invert-body":x.gray[300],"--tw-prose-invert-headings":x.white,"--tw-prose-invert-lead":x.gray[400],"--tw-prose-invert-links":x.white,"--tw-prose-invert-bold":x.white,"--tw-prose-invert-counters":x.gray[400],"--tw-prose-invert-bullets":x.gray[600],"--tw-prose-invert-hr":x.gray[700],"--tw-prose-invert-quotes":x.gray[100],"--tw-prose-invert-quote-borders":x.gray[700],"--tw-prose-invert-captions":x.gray[400],"--tw-prose-invert-kbd":x.white,"--tw-prose-invert-kbd-shadows":lt(x.white),"--tw-prose-invert-code":x.white,"--tw-prose-invert-pre-code":x.gray[300],"--tw-prose-invert-pre-bg":"rgb(0 0 0 / 50%)","--tw-prose-invert-th-borders":x.gray[600],"--tw-prose-invert-td-borders":x.gray[700]}},zinc:{css:{"--tw-prose-body":x.zinc[700],"--tw-prose-headings":x.zinc[900],"--tw-prose-lead":x.zinc[600],"--tw-prose-links":x.zinc[900],"--tw-prose-bold":x.zinc[900],"--tw-prose-counters":x.zinc[500],"--tw-prose-bullets":x.zinc[300],"--tw-prose-hr":x.zinc[200],"--tw-prose-quotes":x.zinc[900],"--tw-prose-quote-borders":x.zinc[200],"--tw-prose-captions":x.zinc[500],"--tw-prose-kbd":x.zinc[900],"--tw-prose-kbd-shadows":lt(x.zinc[900]),"--tw-prose-code":x.zinc[900],"--tw-prose-pre-code":x.zinc[200],"--tw-prose-pre-bg":x.zinc[800],"--tw-prose-th-borders":x.zinc[300],"--tw-prose-td-borders":x.zinc[200],"--tw-prose-invert-body":x.zinc[300],"--tw-prose-invert-headings":x.white,"--tw-prose-invert-lead":x.zinc[400],"--tw-prose-invert-links":x.white,"--tw-prose-invert-bold":x.white,"--tw-prose-invert-counters":x.zinc[400],"--tw-prose-invert-bullets":x.zinc[600],"--tw-prose-invert-hr":x.zinc[700],"--tw-prose-invert-quotes":x.zinc[100],"--tw-prose-invert-quote-borders":x.zinc[700],"--tw-prose-invert-captions":x.zinc[400],"--tw-prose-invert-kbd":x.white,"--tw-prose-invert-kbd-shadows":lt(x.white),"--tw-prose-invert-code":x.white,"--tw-prose-invert-pre-code":x.zinc[300],"--tw-prose-invert-pre-bg":"rgb(0 0 0 / 50%)","--tw-prose-invert-th-borders":x.zinc[600],"--tw-prose-invert-td-borders":x.zinc[700]}},neutral:{css:{"--tw-prose-body":x.neutral[700],"--tw-prose-headings":x.neutral[900],"--tw-prose-lead":x.neutral[600],"--tw-prose-links":x.neutral[900],"--tw-prose-bold":x.neutral[900],"--tw-prose-counters":x.neutral[500],"--tw-prose-bullets":x.neutral[300],"--tw-prose-hr":x.neutral[200],"--tw-prose-quotes":x.neutral[900],"--tw-prose-quote-borders":x.neutral[200],"--tw-prose-captions":x.neutral[500],"--tw-prose-kbd":x.neutral[900],"--tw-prose-kbd-shadows":lt(x.neutral[900]),"--tw-prose-code":x.neutral[900],"--tw-prose-pre-code":x.neutral[200],"--tw-prose-pre-bg":x.neutral[800],"--tw-prose-th-borders":x.neutral[300],"--tw-prose-td-borders":x.neutral[200],"--tw-prose-invert-body":x.neutral[300],"--tw-prose-invert-headings":x.white,"--tw-prose-invert-lead":x.neutral[400],"--tw-prose-invert-links":x.white,"--tw-prose-invert-bold":x.white,"--tw-prose-invert-counters":x.neutral[400],"--tw-prose-invert-bullets":x.neutral[600],"--tw-prose-invert-hr":x.neutral[700],"--tw-prose-invert-quotes":x.neutral[100],"--tw-prose-invert-quote-borders":x.neutral[700],"--tw-prose-invert-captions":x.neutral[400],"--tw-prose-invert-kbd":x.white,"--tw-prose-invert-kbd-shadows":lt(x.white),"--tw-prose-invert-code":x.white,"--tw-prose-invert-pre-code":x.neutral[300],"--tw-prose-invert-pre-bg":"rgb(0 0 0 / 50%)","--tw-prose-invert-th-borders":x.neutral[600],"--tw-prose-invert-td-borders":x.neutral[700]}},stone:{css:{"--tw-prose-body":x.stone[700],"--tw-prose-headings":x.stone[900],"--tw-prose-lead":x.stone[600],"--tw-prose-links":x.stone[900],"--tw-prose-bold":x.stone[900],"--tw-prose-counters":x.stone[500],"--tw-prose-bullets":x.stone[300],"--tw-prose-hr":x.stone[200],"--tw-prose-quotes":x.stone[900],"--tw-prose-quote-borders":x.stone[200],"--tw-prose-captions":x.stone[500],"--tw-prose-kbd":x.stone[900],"--tw-prose-kbd-shadows":lt(x.stone[900]),"--tw-prose-code":x.stone[900],"--tw-prose-pre-code":x.stone[200],"--tw-prose-pre-bg":x.stone[800],"--tw-prose-th-borders":x.stone[300],"--tw-prose-td-borders":x.stone[200],"--tw-prose-invert-body":x.stone[300],"--tw-prose-invert-headings":x.white,"--tw-prose-invert-lead":x.stone[400],"--tw-prose-invert-links":x.white,"--tw-prose-invert-bold":x.white,"--tw-prose-invert-counters":x.stone[400],"--tw-prose-invert-bullets":x.stone[600],"--tw-prose-invert-hr":x.stone[700],"--tw-prose-invert-quotes":x.stone[100],"--tw-prose-invert-quote-borders":x.stone[700],"--tw-prose-invert-captions":x.stone[400],"--tw-prose-invert-kbd":x.white,"--tw-prose-invert-kbd-shadows":lt(x.white),"--tw-prose-invert-code":x.white,"--tw-prose-invert-pre-code":x.stone[300],"--tw-prose-invert-pre-bg":"rgb(0 0 0 / 50%)","--tw-prose-invert-th-borders":x.stone[600],"--tw-prose-invert-td-borders":x.stone[700]}},red:{css:{"--tw-prose-links":x.red[600],"--tw-prose-invert-links":x.red[500]}},orange:{css:{"--tw-prose-links":x.orange[600],"--tw-prose-invert-links":x.orange[500]}},amber:{css:{"--tw-prose-links":x.amber[600],"--tw-prose-invert-links":x.amber[500]}},yellow:{css:{"--tw-prose-links":x.yellow[600],"--tw-prose-invert-links":x.yellow[500]}},lime:{css:{"--tw-prose-links":x.lime[600],"--tw-prose-invert-links":x.lime[500]}},green:{css:{"--tw-prose-links":x.green[600],"--tw-prose-invert-links":x.green[500]}},emerald:{css:{"--tw-prose-links":x.emerald[600],"--tw-prose-invert-links":x.emerald[500]}},teal:{css:{"--tw-prose-links":x.teal[600],"--tw-prose-invert-links":x.teal[500]}},cyan:{css:{"--tw-prose-links":x.cyan[600],"--tw-prose-invert-links":x.cyan[500]}},sky:{css:{"--tw-prose-links":x.sky[600],"--tw-prose-invert-links":x.sky[500]}},blue:{css:{"--tw-prose-links":x.blue[600],"--tw-prose-invert-links":x.blue[500]}},indigo:{css:{"--tw-prose-links":x.indigo[600],"--tw-prose-invert-links":x.indigo[500]}},violet:{css:{"--tw-prose-links":x.violet[600],"--tw-prose-invert-links":x.violet[500]}},purple:{css:{"--tw-prose-links":x.purple[600],"--tw-prose-invert-links":x.purple[500]}},fuchsia:{css:{"--tw-prose-links":x.fuchsia[600],"--tw-prose-invert-links":x.fuchsia[500]}},pink:{css:{"--tw-prose-links":x.pink[600],"--tw-prose-invert-links":x.pink[500]}},rose:{css:{"--tw-prose-links":x.rose[600],"--tw-prose-invert-links":x.rose[500]}},invert:{css:{"--tw-prose-body":"var(--tw-prose-invert-body)","--tw-prose-headings":"var(--tw-prose-invert-headings)","--tw-prose-lead":"var(--tw-prose-invert-lead)","--tw-prose-links":"var(--tw-prose-invert-links)","--tw-prose-bold":"var(--tw-prose-invert-bold)","--tw-prose-counters":"var(--tw-prose-invert-counters)","--tw-prose-bullets":"var(--tw-prose-invert-bullets)","--tw-prose-hr":"var(--tw-prose-invert-hr)","--tw-prose-quotes":"var(--tw-prose-invert-quotes)","--tw-prose-quote-borders":"var(--tw-prose-invert-quote-borders)","--tw-prose-captions":"var(--tw-prose-invert-captions)","--tw-prose-kbd":"var(--tw-prose-invert-kbd)","--tw-prose-kbd-shadows":"var(--tw-prose-invert-kbd-shadows)","--tw-prose-code":"var(--tw-prose-invert-code)","--tw-prose-pre-code":"var(--tw-prose-invert-pre-code)","--tw-prose-pre-bg":"var(--tw-prose-invert-pre-bg)","--tw-prose-th-borders":"var(--tw-prose-invert-th-borders)","--tw-prose-td-borders":"var(--tw-prose-invert-td-borders)"}}};v1.exports={DEFAULT:{css:[{color:"var(--tw-prose-body)",maxWidth:"65ch",p:{},'[class~="lead"]':{color:"var(--tw-prose-lead)"},a:{color:"var(--tw-prose-links)",textDecoration:"underline",fontWeight:"500"},strong:{color:"var(--tw-prose-bold)",fontWeight:"600"},"a strong":{color:"inherit"},"blockquote strong":{color:"inherit"},"thead th strong":{color:"inherit"},ol:{listStyleType:"decimal"},'ol[type="A"]':{listStyleType:"upper-alpha"},'ol[type="a"]':{listStyleType:"lower-alpha"},'ol[type="A" s]':{listStyleType:"upper-alpha"},'ol[type="a" s]':{listStyleType:"lower-alpha"},'ol[type="I"]':{listStyleType:"upper-roman"},'ol[type="i"]':{listStyleType:"lower-roman"},'ol[type="I" s]':{listStyleType:"upper-roman"},'ol[type="i" s]':{listStyleType:"lower-roman"},'ol[type="1"]':{listStyleType:"decimal"},ul:{listStyleType:"disc"},"ol > li::marker":{fontWeight:"400",color:"var(--tw-prose-counters)"},"ul > li::marker":{color:"var(--tw-prose-bullets)"},dt:{color:"var(--tw-prose-headings)",fontWeight:"600"},hr:{borderColor:"var(--tw-prose-hr)",borderTopWidth:1},blockquote:{fontWeight:"500",fontStyle:"italic",color:"var(--tw-prose-quotes)",borderLeftWidth:"0.25rem",borderLeftColor:"var(--tw-prose-quote-borders)",quotes:'"\\201C""\\201D""\\2018""\\2019"'},"blockquote p:first-of-type::before":{content:"open-quote"},"blockquote p:last-of-type::after":{content:"close-quote"},h1:{color:"var(--tw-prose-headings)",fontWeight:"800"},"h1 strong":{fontWeight:"900",color:"inherit"},h2:{color:"var(--tw-prose-headings)",fontWeight:"700"},"h2 strong":{fontWeight:"800",color:"inherit"},h3:{color:"var(--tw-prose-headings)",fontWeight:"600"},"h3 strong":{fontWeight:"700",color:"inherit"},h4:{color:"var(--tw-prose-headings)",fontWeight:"600"},"h4 strong":{fontWeight:"700",color:"inherit"},img:{},picture:{display:"block"},kbd:{fontWeight:"500",fontFamily:"inherit",color:"var(--tw-prose-kbd)",boxShadow:"0 0 0 1px rgb(var(--tw-prose-kbd-shadows) / 10%), 0 3px 0 rgb(var(--tw-prose-kbd-shadows) / 10%)"},code:{color:"var(--tw-prose-code)",fontWeight:"600"},"code::before":{content:'"`"'},"code::after":{content:'"`"'},"a code":{color:"inherit"},"h1 code":{color:"inherit"},"h2 code":{color:"inherit"},"h3 code":{color:"inherit"},"h4 code":{color:"inherit"},"blockquote code":{color:"inherit"},"thead th code":{color:"inherit"},pre:{color:"var(--tw-prose-pre-code)",backgroundColor:"var(--tw-prose-pre-bg)",overflowX:"auto",fontWeight:"400"},"pre code":{backgroundColor:"transparent",borderWidth:"0",borderRadius:"0",padding:"0",fontWeight:"inherit",color:"inherit",fontSize:"inherit",fontFamily:"inherit",lineHeight:"inherit"},"pre code::before":{content:"none"},"pre code::after":{content:"none"},table:{width:"100%",tableLayout:"auto",textAlign:"left",marginTop:d(32,16),marginBottom:d(32,16)},thead:{borderBottomWidth:"1px",borderBottomColor:"var(--tw-prose-th-borders)"},"thead th":{color:"var(--tw-prose-headings)",fontWeight:"600",verticalAlign:"bottom"},"tbody tr":{borderBottomWidth:"1px",borderBottomColor:"var(--tw-prose-td-borders)"},"tbody tr:last-child":{borderBottomWidth:"0"},"tbody td":{verticalAlign:"baseline"},tfoot:{borderTopWidth:"1px",borderTopColor:"var(--tw-prose-th-borders)"},"tfoot td":{verticalAlign:"top"},"figure > *":{},figcaption:{color:"var(--tw-prose-captions)"}},Hf.gray.css,...Hf.base.css]},...Hf}});var S1=k((I$,k1)=>{l();var nI="[object Object]";function sI(t){var e=!1;if(t!=null&&typeof t.toString!="function")try{e=!!(t+"")}catch(r){}return e}function aI(t,e){return function(r){return t(e(r))}}var oI=Function.prototype,b1=Object.prototype,x1=oI.toString,lI=b1.hasOwnProperty,uI=x1.call(Object),fI=b1.toString,cI=aI(Object.getPrototypeOf,Object);function pI(t){return!!t&&typeof t=="object"}function dI(t){if(!pI(t)||fI.call(t)!=nI||sI(t))return!1;var e=cI(t);if(e===null)return!0;var r=lI.call(e,"constructor")&&e.constructor;return typeof r=="function"&&r instanceof r&&x1.call(r)==uI}k1.exports=dI});var Yf=k((ma,_1)=>{l();"use strict";ma.__esModule=!0;ma.default=gI;function hI(t){for(var e=t.toLowerCase(),r="",i=!1,n=0;n<6&&e[n]!==void 0;n++){var s=e.charCodeAt(n),a=s>=97&&s<=102||s>=48&&s<=57;if(i=s===32,!a)break;r+=e[n]}if(r.length!==0){var o=parseInt(r,16),u=o>=55296&&o<=57343;return u||o===0||o>1114111?["\uFFFD",r.length+(i?1:0)]:[String.fromCodePoint(o),r.length+(i?1:0)]}}var mI=/\\/;function gI(t){var e=mI.test(t);if(!e)return t;for(var r="",i=0;i<t.length;i++){if(t[i]==="\\"){var n=hI(t.slice(i+1,i+7));if(n!==void 0){r+=n[0],i+=n[1];continue}if(t[i+1]==="\\"){r+="\\",i++;continue}t.length===i+1&&(r+=t[i]);continue}r+=t[i]}return r}_1.exports=ma.default});var O1=k((ga,T1)=>{l();"use strict";ga.__esModule=!0;ga.default=yI;function yI(t){for(var e=arguments.length,r=new Array(e>1?e-1:0),i=1;i<e;i++)r[i-1]=arguments[i];for(;r.length>0;){var n=r.shift();if(!t[n])return;t=t[n]}return t}T1.exports=ga.default});var A1=k((ya,E1)=>{l();"use strict";ya.__esModule=!0;ya.default=vI;function vI(t){for(var e=arguments.length,r=new Array(e>1?e-1:0),i=1;i<e;i++)r[i-1]=arguments[i];for(;r.length>0;){var n=r.shift();t[n]||(t[n]={}),t=t[n]}}E1.exports=ya.default});var P1=k((va,C1)=>{l();"use strict";va.__esModule=!0;va.default=wI;function wI(t){for(var e="",r=t.indexOf("/*"),i=0;r>=0;){e=e+t.slice(i,r);var n=t.indexOf("*/",r+2);if(n<0)return e;i=n+2,r=t.indexOf("/*",i)}return e=e+t.slice(i),e}C1.exports=va.default});var Ji=k(ut=>{l();"use strict";ut.__esModule=!0;ut.stripComments=ut.ensureObject=ut.getProp=ut.unesc=void 0;var bI=wa(Yf());ut.unesc=bI.default;var xI=wa(O1());ut.getProp=xI.default;var kI=wa(A1());ut.ensureObject=kI.default;var SI=wa(P1());ut.stripComments=SI.default;function wa(t){return t&&t.__esModule?t:{default:t}}});var xt=k((Xi,q1)=>{l();"use strict";Xi.__esModule=!0;Xi.default=void 0;var I1=Ji();function D1(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}function _I(t,e,r){return e&&D1(t.prototype,e),r&&D1(t,r),t}var TI=function t(e,r){if(typeof e!="object"||e===null)return e;var i=new e.constructor;for(var n in e)if(!!e.hasOwnProperty(n)){var s=e[n],a=typeof s;n==="parent"&&a==="object"?r&&(i[n]=r):s instanceof Array?i[n]=s.map(function(o){return t(o,i)}):i[n]=t(s,i)}return i},OI=function(){function t(r){r===void 0&&(r={}),Object.assign(this,r),this.spaces=this.spaces||{},this.spaces.before=this.spaces.before||"",this.spaces.after=this.spaces.after||""}var e=t.prototype;return e.remove=function(){return this.parent&&this.parent.removeChild(this),this.parent=void 0,this},e.replaceWith=function(){if(this.parent){for(var i in arguments)this.parent.insertBefore(this,arguments[i]);this.remove()}return this},e.next=function(){return this.parent.at(this.parent.index(this)+1)},e.prev=function(){return this.parent.at(this.parent.index(this)-1)},e.clone=function(i){i===void 0&&(i={});var n=TI(this);for(var s in i)n[s]=i[s];return n},e.appendToPropertyAndEscape=function(i,n,s){this.raws||(this.raws={});var a=this[i],o=this.raws[i];this[i]=a+n,o||s!==n?this.raws[i]=(o||a)+s:delete this.raws[i]},e.setPropertyAndEscape=function(i,n,s){this.raws||(this.raws={}),this[i]=n,this.raws[i]=s},e.setPropertyWithoutEscape=function(i,n){this[i]=n,this.raws&&delete this.raws[i]},e.isAtPosition=function(i,n){if(this.source&&this.source.start&&this.source.end)return!(this.source.start.line>i||this.source.end.line<i||this.source.start.line===i&&this.source.start.column>n||this.source.end.line===i&&this.source.end.column<n)},e.stringifyProperty=function(i){return this.raws&&this.raws[i]||this[i]},e.valueToString=function(){return String(this.stringifyProperty("value"))},e.toString=function(){return[this.rawSpaceBefore,this.valueToString(),this.rawSpaceAfter].join("")},_I(t,[{key:"rawSpaceBefore",get:function(){var i=this.raws&&this.raws.spaces&&this.raws.spaces.before;return i===void 0&&(i=this.spaces&&this.spaces.before),i||""},set:function(i){(0,I1.ensureObject)(this,"raws","spaces"),this.raws.spaces.before=i}},{key:"rawSpaceAfter",get:function(){var i=this.raws&&this.raws.spaces&&this.raws.spaces.after;return i===void 0&&(i=this.spaces.after),i||""},set:function(i){(0,I1.ensureObject)(this,"raws","spaces"),this.raws.spaces.after=i}}]),t}();Xi.default=OI;q1.exports=Xi.default});var ke=k(ie=>{l();"use strict";ie.__esModule=!0;ie.UNIVERSAL=ie.ATTRIBUTE=ie.CLASS=ie.COMBINATOR=ie.COMMENT=ie.ID=ie.NESTING=ie.PSEUDO=ie.ROOT=ie.SELECTOR=ie.STRING=ie.TAG=void 0;var EI="tag";ie.TAG=EI;var AI="string";ie.STRING=AI;var CI="selector";ie.SELECTOR=CI;var PI="root";ie.ROOT=PI;var II="pseudo";ie.PSEUDO=II;var DI="nesting";ie.NESTING=DI;var qI="id";ie.ID=qI;var RI="comment";ie.COMMENT=RI;var LI="combinator";ie.COMBINATOR=LI;var BI="class";ie.CLASS=BI;var MI="attribute";ie.ATTRIBUTE=MI;var FI="universal";ie.UNIVERSAL=FI});var ba=k((Ki,M1)=>{l();"use strict";Ki.__esModule=!0;Ki.default=void 0;var NI=$I(xt()),kt=zI(ke());function R1(){if(typeof WeakMap!="function")return null;var t=new WeakMap;return R1=function(){return t},t}function zI(t){if(t&&t.__esModule)return t;if(t===null||typeof t!="object"&&typeof t!="function")return{default:t};var e=R1();if(e&&e.has(t))return e.get(t);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){var s=i?Object.getOwnPropertyDescriptor(t,n):null;s&&(s.get||s.set)?Object.defineProperty(r,n,s):r[n]=t[n]}return r.default=t,e&&e.set(t,r),r}function $I(t){return t&&t.__esModule?t:{default:t}}function jI(t,e){var r;if(typeof Symbol=="undefined"||t[Symbol.iterator]==null){if(Array.isArray(t)||(r=UI(t))||e&&t&&typeof t.length=="number"){r&&(t=r);var i=0;return function(){return i>=t.length?{done:!0}:{done:!1,value:t[i++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}return r=t[Symbol.iterator](),r.next.bind(r)}function UI(t,e){if(!!t){if(typeof t=="string")return L1(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return L1(t,e)}}function L1(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,i=new Array(e);r<e;r++)i[r]=t[r];return i}function B1(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}function VI(t,e,r){return e&&B1(t.prototype,e),r&&B1(t,r),t}function WI(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,Qf(t,e)}function Qf(t,e){return Qf=Object.setPrototypeOf||function(i,n){return i.__proto__=n,i},Qf(t,e)}var GI=function(t){WI(e,t);function e(i){var n;return n=t.call(this,i)||this,n.nodes||(n.nodes=[]),n}var r=e.prototype;return r.append=function(n){return n.parent=this,this.nodes.push(n),this},r.prepend=function(n){return n.parent=this,this.nodes.unshift(n),this},r.at=function(n){return this.nodes[n]},r.index=function(n){return typeof n=="number"?n:this.nodes.indexOf(n)},r.removeChild=function(n){n=this.index(n),this.at(n).parent=void 0,this.nodes.splice(n,1);var s;for(var a in this.indexes)s=this.indexes[a],s>=n&&(this.indexes[a]=s-1);return this},r.removeAll=function(){for(var n=jI(this.nodes),s;!(s=n()).done;){var a=s.value;a.parent=void 0}return this.nodes=[],this},r.empty=function(){return this.removeAll()},r.insertAfter=function(n,s){s.parent=this;var a=this.index(n);this.nodes.splice(a+1,0,s),s.parent=this;var o;for(var u in this.indexes)o=this.indexes[u],a<=o&&(this.indexes[u]=o+1);return this},r.insertBefore=function(n,s){s.parent=this;var a=this.index(n);this.nodes.splice(a,0,s),s.parent=this;var o;for(var u in this.indexes)o=this.indexes[u],o<=a&&(this.indexes[u]=o+1);return this},r._findChildAtPosition=function(n,s){var a=void 0;return this.each(function(o){if(o.atPosition){var u=o.atPosition(n,s);if(u)return a=u,!1}else if(o.isAtPosition(n,s))return a=o,!1}),a},r.atPosition=function(n,s){if(this.isAtPosition(n,s))return this._findChildAtPosition(n,s)||this},r._inferEndPosition=function(){this.last&&this.last.source&&this.last.source.end&&(this.source=this.source||{},this.source.end=this.source.end||{},Object.assign(this.source.end,this.last.source.end))},r.each=function(n){this.lastEach||(this.lastEach=0),this.indexes||(this.indexes={}),this.lastEach++;var s=this.lastEach;if(this.indexes[s]=0,!!this.length){for(var a,o;this.indexes[s]<this.length&&(a=this.indexes[s],o=n(this.at(a),a),o!==!1);)this.indexes[s]+=1;if(delete this.indexes[s],o===!1)return!1}},r.walk=function(n){return this.each(function(s,a){var o=n(s,a);if(o!==!1&&s.length&&(o=s.walk(n)),o===!1)return!1})},r.walkAttributes=function(n){var s=this;return this.walk(function(a){if(a.type===kt.ATTRIBUTE)return n.call(s,a)})},r.walkClasses=function(n){var s=this;return this.walk(function(a){if(a.type===kt.CLASS)return n.call(s,a)})},r.walkCombinators=function(n){var s=this;return this.walk(function(a){if(a.type===kt.COMBINATOR)return n.call(s,a)})},r.walkComments=function(n){var s=this;return this.walk(function(a){if(a.type===kt.COMMENT)return n.call(s,a)})},r.walkIds=function(n){var s=this;return this.walk(function(a){if(a.type===kt.ID)return n.call(s,a)})},r.walkNesting=function(n){var s=this;return this.walk(function(a){if(a.type===kt.NESTING)return n.call(s,a)})},r.walkPseudos=function(n){var s=this;return this.walk(function(a){if(a.type===kt.PSEUDO)return n.call(s,a)})},r.walkTags=function(n){var s=this;return this.walk(function(a){if(a.type===kt.TAG)return n.call(s,a)})},r.walkUniversals=function(n){var s=this;return this.walk(function(a){if(a.type===kt.UNIVERSAL)return n.call(s,a)})},r.split=function(n){var s=this,a=[];return this.reduce(function(o,u,c){var f=n.call(s,u);return a.push(u),f?(o.push(a),a=[]):c===s.length-1&&o.push(a),o},[])},r.map=function(n){return this.nodes.map(n)},r.reduce=function(n,s){return this.nodes.reduce(n,s)},r.every=function(n){return this.nodes.every(n)},r.some=function(n){return this.nodes.some(n)},r.filter=function(n){return this.nodes.filter(n)},r.sort=function(n){return this.nodes.sort(n)},r.toString=function(){return this.map(String).join("")},VI(e,[{key:"first",get:function(){return this.at(0)}},{key:"last",get:function(){return this.at(this.length-1)}},{key:"length",get:function(){return this.nodes.length}}]),e}(NI.default);Ki.default=GI;M1.exports=Ki.default});var Xf=k((Zi,N1)=>{l();"use strict";Zi.__esModule=!0;Zi.default=void 0;var HI=QI(ba()),YI=ke();function QI(t){return t&&t.__esModule?t:{default:t}}function F1(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}function JI(t,e,r){return e&&F1(t.prototype,e),r&&F1(t,r),t}function XI(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,Jf(t,e)}function Jf(t,e){return Jf=Object.setPrototypeOf||function(i,n){return i.__proto__=n,i},Jf(t,e)}var KI=function(t){XI(e,t);function e(i){var n;return n=t.call(this,i)||this,n.type=YI.ROOT,n}var r=e.prototype;return r.toString=function(){var n=this.reduce(function(s,a){return s.push(String(a)),s},[]).join(",");return this.trailingComma?n+",":n},r.error=function(n,s){return this._error?this._error(n,s):new Error(n)},JI(e,[{key:"errorGenerator",set:function(n){this._error=n}}]),e}(HI.default);Zi.default=KI;N1.exports=Zi.default});var Zf=k((en,z1)=>{l();"use strict";en.__esModule=!0;en.default=void 0;var ZI=tD(ba()),eD=ke();function tD(t){return t&&t.__esModule?t:{default:t}}function rD(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,Kf(t,e)}function Kf(t,e){return Kf=Object.setPrototypeOf||function(i,n){return i.__proto__=n,i},Kf(t,e)}var iD=function(t){rD(e,t);function e(r){var i;return i=t.call(this,r)||this,i.type=eD.SELECTOR,i}return e}(ZI.default);en.default=iD;z1.exports=en.default});var tc=k((tn,U1)=>{l();"use strict";tn.__esModule=!0;tn.default=void 0;var nD=$1(Wt()),sD=Ji(),aD=$1(xt()),oD=ke();function $1(t){return t&&t.__esModule?t:{default:t}}function j1(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}function lD(t,e,r){return e&&j1(t.prototype,e),r&&j1(t,r),t}function uD(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,ec(t,e)}function ec(t,e){return ec=Object.setPrototypeOf||function(i,n){return i.__proto__=n,i},ec(t,e)}var fD=function(t){uD(e,t);function e(i){var n;return n=t.call(this,i)||this,n.type=oD.CLASS,n._constructed=!0,n}var r=e.prototype;return r.valueToString=function(){return"."+t.prototype.valueToString.call(this)},lD(e,[{key:"value",get:function(){return this._value},set:function(n){if(this._constructed){var s=(0,nD.default)(n,{isIdentifier:!0});s!==n?((0,sD.ensureObject)(this,"raws"),this.raws.value=s):this.raws&&delete this.raws.value}this._value=n}}]),e}(aD.default);tn.default=fD;U1.exports=tn.default});var ic=k((rn,V1)=>{l();"use strict";rn.__esModule=!0;rn.default=void 0;var cD=dD(xt()),pD=ke();function dD(t){return t&&t.__esModule?t:{default:t}}function hD(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,rc(t,e)}function rc(t,e){return rc=Object.setPrototypeOf||function(i,n){return i.__proto__=n,i},rc(t,e)}var mD=function(t){hD(e,t);function e(r){var i;return i=t.call(this,r)||this,i.type=pD.COMMENT,i}return e}(cD.default);rn.default=mD;V1.exports=rn.default});var sc=k((nn,W1)=>{l();"use strict";nn.__esModule=!0;nn.default=void 0;var gD=vD(xt()),yD=ke();function vD(t){return t&&t.__esModule?t:{default:t}}function wD(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,nc(t,e)}function nc(t,e){return nc=Object.setPrototypeOf||function(i,n){return i.__proto__=n,i},nc(t,e)}var bD=function(t){wD(e,t);function e(i){var n;return n=t.call(this,i)||this,n.type=yD.ID,n}var r=e.prototype;return r.valueToString=function(){return"#"+t.prototype.valueToString.call(this)},e}(gD.default);nn.default=bD;W1.exports=nn.default});var xa=k((sn,Y1)=>{l();"use strict";sn.__esModule=!0;sn.default=void 0;var xD=G1(Wt()),kD=Ji(),SD=G1(xt());function G1(t){return t&&t.__esModule?t:{default:t}}function H1(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}function _D(t,e,r){return e&&H1(t.prototype,e),r&&H1(t,r),t}function TD(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,ac(t,e)}function ac(t,e){return ac=Object.setPrototypeOf||function(i,n){return i.__proto__=n,i},ac(t,e)}var OD=function(t){TD(e,t);function e(){return t.apply(this,arguments)||this}var r=e.prototype;return r.qualifiedName=function(n){return this.namespace?this.namespaceString+"|"+n:n},r.valueToString=function(){return this.qualifiedName(t.prototype.valueToString.call(this))},_D(e,[{key:"namespace",get:function(){return this._namespace},set:function(n){if(n===!0||n==="*"||n==="&"){this._namespace=n,this.raws&&delete this.raws.namespace;return}var s=(0,xD.default)(n,{isIdentifier:!0});this._namespace=n,s!==n?((0,kD.ensureObject)(this,"raws"),this.raws.namespace=s):this.raws&&delete this.raws.namespace}},{key:"ns",get:function(){return this._namespace},set:function(n){this.namespace=n}},{key:"namespaceString",get:function(){if(this.namespace){var n=this.stringifyProperty("namespace");return n===!0?"":n}else return""}}]),e}(SD.default);sn.default=OD;Y1.exports=sn.default});var lc=k((an,Q1)=>{l();"use strict";an.__esModule=!0;an.default=void 0;var ED=CD(xa()),AD=ke();function CD(t){return t&&t.__esModule?t:{default:t}}function PD(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,oc(t,e)}function oc(t,e){return oc=Object.setPrototypeOf||function(i,n){return i.__proto__=n,i},oc(t,e)}var ID=function(t){PD(e,t);function e(r){var i;return i=t.call(this,r)||this,i.type=AD.TAG,i}return e}(ED.default);an.default=ID;Q1.exports=an.default});var fc=k((on,J1)=>{l();"use strict";on.__esModule=!0;on.default=void 0;var DD=RD(xt()),qD=ke();function RD(t){return t&&t.__esModule?t:{default:t}}function LD(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,uc(t,e)}function uc(t,e){return uc=Object.setPrototypeOf||function(i,n){return i.__proto__=n,i},uc(t,e)}var BD=function(t){LD(e,t);function e(r){var i;return i=t.call(this,r)||this,i.type=qD.STRING,i}return e}(DD.default);on.default=BD;J1.exports=on.default});var pc=k((ln,X1)=>{l();"use strict";ln.__esModule=!0;ln.default=void 0;var MD=ND(ba()),FD=ke();function ND(t){return t&&t.__esModule?t:{default:t}}function zD(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,cc(t,e)}function cc(t,e){return cc=Object.setPrototypeOf||function(i,n){return i.__proto__=n,i},cc(t,e)}var $D=function(t){zD(e,t);function e(i){var n;return n=t.call(this,i)||this,n.type=FD.PSEUDO,n}var r=e.prototype;return r.toString=function(){var n=this.length?"("+this.map(String).join(",")+")":"";return[this.rawSpaceBefore,this.stringifyProperty("value"),n,this.rawSpaceAfter].join("")},e}(MD.default);ln.default=$D;X1.exports=ln.default});var vc=k(cn=>{l();"use strict";cn.__esModule=!0;cn.unescapeValue=gc;cn.default=void 0;var un=hc(Wt()),jD=hc(Yf()),UD=hc(xa()),VD=ke(),dc;function hc(t){return t&&t.__esModule?t:{default:t}}function K1(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}function WD(t,e,r){return e&&K1(t.prototype,e),r&&K1(t,r),t}function GD(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,mc(t,e)}function mc(t,e){return mc=Object.setPrototypeOf||function(i,n){return i.__proto__=n,i},mc(t,e)}var fn=No(),HD=/^('|")([^]*)\1$/,YD=fn(function(){},"Assigning an attribute a value containing characters that might need to be escaped is deprecated. Call attribute.setValue() instead."),QD=fn(function(){},"Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead."),JD=fn(function(){},"Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");function gc(t){var e=!1,r=null,i=t,n=i.match(HD);return n&&(r=n[1],i=n[2]),i=(0,jD.default)(i),i!==t&&(e=!0),{deprecatedUsage:e,unescaped:i,quoteMark:r}}function XD(t){if(t.quoteMark!==void 0||t.value===void 0)return t;JD();var e=gc(t.value),r=e.quoteMark,i=e.unescaped;return t.raws||(t.raws={}),t.raws.value===void 0&&(t.raws.value=t.value),t.value=i,t.quoteMark=r,t}var ka=function(t){GD(e,t);function e(i){var n;return i===void 0&&(i={}),n=t.call(this,XD(i))||this,n.type=VD.ATTRIBUTE,n.raws=n.raws||{},Object.defineProperty(n.raws,"unquoted",{get:fn(function(){return n.value},"attr.raws.unquoted is deprecated. Call attr.value instead."),set:fn(function(){return n.value},"Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")}),n._constructed=!0,n}var r=e.prototype;return r.getQuotedValue=function(n){n===void 0&&(n={});var s=this._determineQuoteMark(n),a=yc[s],o=(0,un.default)(this._value,a);return o},r._determineQuoteMark=function(n){return n.smart?this.smartQuoteMark(n):this.preferredQuoteMark(n)},r.setValue=function(n,s){s===void 0&&(s={}),this._value=n,this._quoteMark=this._determineQuoteMark(s),this._syncRawValue()},r.smartQuoteMark=function(n){var s=this.value,a=s.replace(/[^']/g,"").length,o=s.replace(/[^"]/g,"").length;if(a+o===0){var u=(0,un.default)(s,{isIdentifier:!0});if(u===s)return e.NO_QUOTE;var c=this.preferredQuoteMark(n);if(c===e.NO_QUOTE){var f=this.quoteMark||n.quoteMark||e.DOUBLE_QUOTE,p=yc[f],h=(0,un.default)(s,p);if(h.length<u.length)return f}return c}else return o===a?this.preferredQuoteMark(n):o<a?e.DOUBLE_QUOTE:e.SINGLE_QUOTE},r.preferredQuoteMark=function(n){var s=n.preferCurrentQuoteMark?this.quoteMark:n.quoteMark;return s===void 0&&(s=n.preferCurrentQuoteMark?n.quoteMark:this.quoteMark),s===void 0&&(s=e.DOUBLE_QUOTE),s},r._syncRawValue=function(){var n=(0,un.default)(this._value,yc[this.quoteMark]);n===this._value?this.raws&&delete this.raws.value:this.raws.value=n},r._handleEscapes=function(n,s){if(this._constructed){var a=(0,un.default)(s,{isIdentifier:!0});a!==s?this.raws[n]=a:delete this.raws[n]}},r._spacesFor=function(n){var s={before:"",after:""},a=this.spaces[n]||{},o=this.raws.spaces&&this.raws.spaces[n]||{};return Object.assign(s,a,o)},r._stringFor=function(n,s,a){s===void 0&&(s=n),a===void 0&&(a=Z1);var o=this._spacesFor(s);return a(this.stringifyProperty(n),o)},r.offsetOf=function(n){var s=1,a=this._spacesFor("attribute");if(s+=a.before.length,n==="namespace"||n==="ns")return this.namespace?s:-1;if(n==="attributeNS"||(s+=this.namespaceString.length,this.namespace&&(s+=1),n==="attribute"))return s;s+=this.stringifyProperty("attribute").length,s+=a.after.length;var o=this._spacesFor("operator");s+=o.before.length;var u=this.stringifyProperty("operator");if(n==="operator")return u?s:-1;s+=u.length,s+=o.after.length;var c=this._spacesFor("value");s+=c.before.length;var f=this.stringifyProperty("value");if(n==="value")return f?s:-1;s+=f.length,s+=c.after.length;var p=this._spacesFor("insensitive");return s+=p.before.length,n==="insensitive"&&this.insensitive?s:-1},r.toString=function(){var n=this,s=[this.rawSpaceBefore,"["];return s.push(this._stringFor("qualifiedAttribute","attribute")),this.operator&&(this.value||this.value==="")&&(s.push(this._stringFor("operator")),s.push(this._stringFor("value")),s.push(this._stringFor("insensitiveFlag","insensitive",function(a,o){return a.length>0&&!n.quoted&&o.before.length===0&&!(n.spaces.value&&n.spaces.value.after)&&(o.before=" "),Z1(a,o)}))),s.push("]"),s.push(this.rawSpaceAfter),s.join("")},WD(e,[{key:"quoted",get:function(){var n=this.quoteMark;return n==="'"||n==='"'},set:function(n){QD()}},{key:"quoteMark",get:function(){return this._quoteMark},set:function(n){if(!this._constructed){this._quoteMark=n;return}this._quoteMark!==n&&(this._quoteMark=n,this._syncRawValue())}},{key:"qualifiedAttribute",get:function(){return this.qualifiedName(this.raws.attribute||this.attribute)}},{key:"insensitiveFlag",get:function(){return this.insensitive?"i":""}},{key:"value",get:function(){return this._value},set:function(n){if(this._constructed){var s=gc(n),a=s.deprecatedUsage,o=s.unescaped,u=s.quoteMark;if(a&&YD(),o===this._value&&u===this._quoteMark)return;this._value=o,this._quoteMark=u,this._syncRawValue()}else this._value=n}},{key:"attribute",get:function(){return this._attribute},set:function(n){this._handleEscapes("attribute",n),this._attribute=n}}]),e}(UD.default);cn.default=ka;ka.NO_QUOTE=null;ka.SINGLE_QUOTE="'";ka.DOUBLE_QUOTE='"';var yc=(dc={"'":{quotes:"single",wrap:!0},'"':{quotes:"double",wrap:!0}},dc[null]={isIdentifier:!0},dc);function Z1(t,e){return""+e.before+t+e.after}});var bc=k((pn,ex)=>{l();"use strict";pn.__esModule=!0;pn.default=void 0;var KD=eq(xa()),ZD=ke();function eq(t){return t&&t.__esModule?t:{default:t}}function tq(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,wc(t,e)}function wc(t,e){return wc=Object.setPrototypeOf||function(i,n){return i.__proto__=n,i},wc(t,e)}var rq=function(t){tq(e,t);function e(r){var i;return i=t.call(this,r)||this,i.type=ZD.UNIVERSAL,i.value="*",i}return e}(KD.default);pn.default=rq;ex.exports=pn.default});var kc=k((dn,tx)=>{l();"use strict";dn.__esModule=!0;dn.default=void 0;var iq=sq(xt()),nq=ke();function sq(t){return t&&t.__esModule?t:{default:t}}function aq(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,xc(t,e)}function xc(t,e){return xc=Object.setPrototypeOf||function(i,n){return i.__proto__=n,i},xc(t,e)}var oq=function(t){aq(e,t);function e(r){var i;return i=t.call(this,r)||this,i.type=nq.COMBINATOR,i}return e}(iq.default);dn.default=oq;tx.exports=dn.default});var _c=k((hn,rx)=>{l();"use strict";hn.__esModule=!0;hn.default=void 0;var lq=fq(xt()),uq=ke();function fq(t){return t&&t.__esModule?t:{default:t}}function cq(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,Sc(t,e)}function Sc(t,e){return Sc=Object.setPrototypeOf||function(i,n){return i.__proto__=n,i},Sc(t,e)}var pq=function(t){cq(e,t);function e(r){var i;return i=t.call(this,r)||this,i.type=uq.NESTING,i.value="&",i}return e}(lq.default);hn.default=pq;rx.exports=hn.default});var nx=k((Sa,ix)=>{l();"use strict";Sa.__esModule=!0;Sa.default=dq;function dq(t){return t.sort(function(e,r){return e-r})}ix.exports=Sa.default});var Tc=k(M=>{l();"use strict";M.__esModule=!0;M.combinator=M.word=M.comment=M.str=M.tab=M.newline=M.feed=M.cr=M.backslash=M.bang=M.slash=M.doubleQuote=M.singleQuote=M.space=M.greaterThan=M.pipe=M.equals=M.plus=M.caret=M.tilde=M.dollar=M.closeSquare=M.openSquare=M.closeParenthesis=M.openParenthesis=M.semicolon=M.colon=M.comma=M.at=M.asterisk=M.ampersand=void 0;var hq=38;M.ampersand=hq;var mq=42;M.asterisk=mq;var gq=64;M.at=gq;var yq=44;M.comma=yq;var vq=58;M.colon=vq;var wq=59;M.semicolon=wq;var bq=40;M.openParenthesis=bq;var xq=41;M.closeParenthesis=xq;var kq=91;M.openSquare=kq;var Sq=93;M.closeSquare=Sq;var _q=36;M.dollar=_q;var Tq=126;M.tilde=Tq;var Oq=94;M.caret=Oq;var Eq=43;M.plus=Eq;var Aq=61;M.equals=Aq;var Cq=124;M.pipe=Cq;var Pq=62;M.greaterThan=Pq;var Iq=32;M.space=Iq;var sx=39;M.singleQuote=sx;var Dq=34;M.doubleQuote=Dq;var qq=47;M.slash=qq;var Rq=33;M.bang=Rq;var Lq=92;M.backslash=Lq;var Bq=13;M.cr=Bq;var Mq=12;M.feed=Mq;var Fq=10;M.newline=Fq;var Nq=9;M.tab=Nq;var zq=sx;M.str=zq;var $q=-1;M.comment=$q;var jq=-2;M.word=jq;var Uq=-3;M.combinator=Uq});var lx=k(mn=>{l();"use strict";mn.__esModule=!0;mn.default=Jq;mn.FIELDS=void 0;var D=Vq(Tc()),$r,Z;function ax(){if(typeof WeakMap!="function")return null;var t=new WeakMap;return ax=function(){return t},t}function Vq(t){if(t&&t.__esModule)return t;if(t===null||typeof t!="object"&&typeof t!="function")return{default:t};var e=ax();if(e&&e.has(t))return e.get(t);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){var s=i?Object.getOwnPropertyDescriptor(t,n):null;s&&(s.get||s.set)?Object.defineProperty(r,n,s):r[n]=t[n]}return r.default=t,e&&e.set(t,r),r}var Wq=($r={},$r[D.tab]=!0,$r[D.newline]=!0,$r[D.cr]=!0,$r[D.feed]=!0,$r),Gq=(Z={},Z[D.space]=!0,Z[D.tab]=!0,Z[D.newline]=!0,Z[D.cr]=!0,Z[D.feed]=!0,Z[D.ampersand]=!0,Z[D.asterisk]=!0,Z[D.bang]=!0,Z[D.comma]=!0,Z[D.colon]=!0,Z[D.semicolon]=!0,Z[D.openParenthesis]=!0,Z[D.closeParenthesis]=!0,Z[D.openSquare]=!0,Z[D.closeSquare]=!0,Z[D.singleQuote]=!0,Z[D.doubleQuote]=!0,Z[D.plus]=!0,Z[D.pipe]=!0,Z[D.tilde]=!0,Z[D.greaterThan]=!0,Z[D.equals]=!0,Z[D.dollar]=!0,Z[D.caret]=!0,Z[D.slash]=!0,Z),Oc={},ox="0123456789abcdefABCDEF";for(_a=0;_a<ox.length;_a++)Oc[ox.charCodeAt(_a)]=!0;var _a;function Hq(t,e){var r=e,i;do{if(i=t.charCodeAt(r),Gq[i])return r-1;i===D.backslash?r=Yq(t,r)+1:r++}while(r<t.length);return r-1}function Yq(t,e){var r=e,i=t.charCodeAt(r+1);if(!Wq[i])if(Oc[i]){var n=0;do r++,n++,i=t.charCodeAt(r+1);while(Oc[i]&&n<6);n<6&&i===D.space&&r++}else r++;return r}var Qq={TYPE:0,START_LINE:1,START_COL:2,END_LINE:3,END_COL:4,START_POS:5,END_POS:6};mn.FIELDS=Qq;function Jq(t){var e=[],r=t.css.valueOf(),i=r,n=i.length,s=-1,a=1,o=0,u=0,c,f,p,h,m,v,S,b,w,_,T,O,E;function F(z,N){if(t.safe)r+=N,w=r.length-1;else throw t.error("Unclosed "+z,a,o-s,o)}for(;o<n;){switch(c=r.charCodeAt(o),c===D.newline&&(s=o,a+=1),c){case D.space:case D.tab:case D.newline:case D.cr:case D.feed:w=o;do w+=1,c=r.charCodeAt(w),c===D.newline&&(s=w,a+=1);while(c===D.space||c===D.newline||c===D.tab||c===D.cr||c===D.feed);E=D.space,h=a,p=w-s-1,u=w;break;case D.plus:case D.greaterThan:case D.tilde:case D.pipe:w=o;do w+=1,c=r.charCodeAt(w);while(c===D.plus||c===D.greaterThan||c===D.tilde||c===D.pipe);E=D.combinator,h=a,p=o-s,u=w;break;case D.asterisk:case D.ampersand:case D.bang:case D.comma:case D.equals:case D.dollar:case D.caret:case D.openSquare:case D.closeSquare:case D.colon:case D.semicolon:case D.openParenthesis:case D.closeParenthesis:w=o,E=c,h=a,p=o-s,u=w+1;break;case D.singleQuote:case D.doubleQuote:O=c===D.singleQuote?"'":'"',w=o;do for(m=!1,w=r.indexOf(O,w+1),w===-1&&F("quote",O),v=w;r.charCodeAt(v-1)===D.backslash;)v-=1,m=!m;while(m);E=D.str,h=a,p=o-s,u=w+1;break;default:c===D.slash&&r.charCodeAt(o+1)===D.asterisk?(w=r.indexOf("*/",o+2)+1,w===0&&F("comment","*/"),f=r.slice(o,w+1),b=f.split(`
`),S=b.length-1,S>0?(_=a+S,T=w-b[S].length):(_=a,T=s),E=D.comment,a=_,h=_,p=w-T):c===D.slash?(w=o,E=c,h=a,p=o-s,u=w+1):(w=Hq(r,o),E=D.word,h=a,p=w-s),u=w+1;break}e.push([E,a,o-s,h,p,o,u]),T&&(s=T,T=null),o=u}return e}});var gx=k((gn,mx)=>{l();"use strict";gn.__esModule=!0;gn.default=void 0;var Xq=$e(Xf()),Ec=$e(Zf()),Kq=$e(tc()),ux=$e(ic()),Zq=$e(sc()),eR=$e(lc()),Ac=$e(fc()),tR=$e(pc()),fx=Ta(vc()),rR=$e(bc()),Cc=$e(kc()),iR=$e(_c()),nR=$e(nx()),P=Ta(lx()),R=Ta(Tc()),sR=Ta(ke()),le=Ji(),Kt,Pc;function cx(){if(typeof WeakMap!="function")return null;var t=new WeakMap;return cx=function(){return t},t}function Ta(t){if(t&&t.__esModule)return t;if(t===null||typeof t!="object"&&typeof t!="function")return{default:t};var e=cx();if(e&&e.has(t))return e.get(t);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){var s=i?Object.getOwnPropertyDescriptor(t,n):null;s&&(s.get||s.set)?Object.defineProperty(r,n,s):r[n]=t[n]}return r.default=t,e&&e.set(t,r),r}function $e(t){return t&&t.__esModule?t:{default:t}}function px(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}function aR(t,e,r){return e&&px(t.prototype,e),r&&px(t,r),t}var Ic=(Kt={},Kt[R.space]=!0,Kt[R.cr]=!0,Kt[R.feed]=!0,Kt[R.newline]=!0,Kt[R.tab]=!0,Kt),oR=Object.assign({},Ic,(Pc={},Pc[R.comment]=!0,Pc));function dx(t){return{line:t[P.FIELDS.START_LINE],column:t[P.FIELDS.START_COL]}}function hx(t){return{line:t[P.FIELDS.END_LINE],column:t[P.FIELDS.END_COL]}}function Zt(t,e,r,i){return{start:{line:t,column:e},end:{line:r,column:i}}}function jr(t){return Zt(t[P.FIELDS.START_LINE],t[P.FIELDS.START_COL],t[P.FIELDS.END_LINE],t[P.FIELDS.END_COL])}function Dc(t,e){if(!!t)return Zt(t[P.FIELDS.START_LINE],t[P.FIELDS.START_COL],e[P.FIELDS.END_LINE],e[P.FIELDS.END_COL])}function Ur(t,e){var r=t[e];if(typeof r=="string")return r.indexOf("\\")!==-1&&((0,le.ensureObject)(t,"raws"),t[e]=(0,le.unesc)(r),t.raws[e]===void 0&&(t.raws[e]=r)),t}function qc(t,e){for(var r=-1,i=[];(r=t.indexOf(e,r+1))!==-1;)i.push(r);return i}function lR(){var t=Array.prototype.concat.apply([],arguments);return t.filter(function(e,r){return r===t.indexOf(e)})}var uR=function(){function t(r,i){i===void 0&&(i={}),this.rule=r,this.options=Object.assign({lossy:!1,safe:!1},i),this.position=0,this.css=typeof this.rule=="string"?this.rule:this.rule.selector,this.tokens=(0,P.default)({css:this.css,error:this._errorGenerator(),safe:this.options.safe});var n=Dc(this.tokens[0],this.tokens[this.tokens.length-1]);this.root=new Xq.default({source:n}),this.root.errorGenerator=this._errorGenerator();var s=new Ec.default({source:{start:{line:1,column:1}}});this.root.append(s),this.current=s,this.loop()}var e=t.prototype;return e._errorGenerator=function(){var i=this;return function(n,s){return typeof i.rule=="string"?new Error(n):i.rule.error(n,s)}},e.attribute=function(){var i=[],n=this.currToken;for(this.position++;this.position<this.tokens.length&&this.currToken[P.FIELDS.TYPE]!==R.closeSquare;)i.push(this.currToken),this.position++;if(this.currToken[P.FIELDS.TYPE]!==R.closeSquare)return this.expected("closing square bracket",this.currToken[P.FIELDS.START_POS]);var s=i.length,a={source:Zt(n[1],n[2],this.currToken[3],this.currToken[4]),sourceIndex:n[P.FIELDS.START_POS]};if(s===1&&!~[R.word].indexOf(i[0][P.FIELDS.TYPE]))return this.expected("attribute",i[0][P.FIELDS.START_POS]);for(var o=0,u="",c="",f=null,p=!1;o<s;){var h=i[o],m=this.content(h),v=i[o+1];switch(h[P.FIELDS.TYPE]){case R.space:if(p=!0,this.options.lossy)break;if(f){(0,le.ensureObject)(a,"spaces",f);var S=a.spaces[f].after||"";a.spaces[f].after=S+m;var b=(0,le.getProp)(a,"raws","spaces",f,"after")||null;b&&(a.raws.spaces[f].after=b+m)}else u=u+m,c=c+m;break;case R.asterisk:if(v[P.FIELDS.TYPE]===R.equals)a.operator=m,f="operator";else if((!a.namespace||f==="namespace"&&!p)&&v){u&&((0,le.ensureObject)(a,"spaces","attribute"),a.spaces.attribute.before=u,u=""),c&&((0,le.ensureObject)(a,"raws","spaces","attribute"),a.raws.spaces.attribute.before=u,c=""),a.namespace=(a.namespace||"")+m;var w=(0,le.getProp)(a,"raws","namespace")||null;w&&(a.raws.namespace+=m),f="namespace"}p=!1;break;case R.dollar:if(f==="value"){var _=(0,le.getProp)(a,"raws","value");a.value+="$",_&&(a.raws.value=_+"$");break}case R.caret:v[P.FIELDS.TYPE]===R.equals&&(a.operator=m,f="operator"),p=!1;break;case R.combinator:if(m==="~"&&v[P.FIELDS.TYPE]===R.equals&&(a.operator=m,f="operator"),m!=="|"){p=!1;break}v[P.FIELDS.TYPE]===R.equals?(a.operator=m,f="operator"):!a.namespace&&!a.attribute&&(a.namespace=!0),p=!1;break;case R.word:if(v&&this.content(v)==="|"&&i[o+2]&&i[o+2][P.FIELDS.TYPE]!==R.equals&&!a.operator&&!a.namespace)a.namespace=m,f="namespace";else if(!a.attribute||f==="attribute"&&!p){u&&((0,le.ensureObject)(a,"spaces","attribute"),a.spaces.attribute.before=u,u=""),c&&((0,le.ensureObject)(a,"raws","spaces","attribute"),a.raws.spaces.attribute.before=c,c=""),a.attribute=(a.attribute||"")+m;var T=(0,le.getProp)(a,"raws","attribute")||null;T&&(a.raws.attribute+=m),f="attribute"}else if(!a.value&&a.value!==""||f==="value"&&!p){var O=(0,le.unesc)(m),E=(0,le.getProp)(a,"raws","value")||"",F=a.value||"";a.value=F+O,a.quoteMark=null,(O!==m||E)&&((0,le.ensureObject)(a,"raws"),a.raws.value=(E||F)+m),f="value"}else{var z=m==="i"||m==="I";(a.value||a.value==="")&&(a.quoteMark||p)?(a.insensitive=z,(!z||m==="I")&&((0,le.ensureObject)(a,"raws"),a.raws.insensitiveFlag=m),f="insensitive",u&&((0,le.ensureObject)(a,"spaces","insensitive"),a.spaces.insensitive.before=u,u=""),c&&((0,le.ensureObject)(a,"raws","spaces","insensitive"),a.raws.spaces.insensitive.before=c,c="")):(a.value||a.value==="")&&(f="value",a.value+=m,a.raws.value&&(a.raws.value+=m))}p=!1;break;case R.str:if(!a.attribute||!a.operator)return this.error("Expected an attribute followed by an operator preceding the string.",{index:h[P.FIELDS.START_POS]});var N=(0,fx.unescapeValue)(m),fe=N.unescaped,ye=N.quoteMark;a.value=fe,a.quoteMark=ye,f="value",(0,le.ensureObject)(a,"raws"),a.raws.value=m,p=!1;break;case R.equals:if(!a.attribute)return this.expected("attribute",h[P.FIELDS.START_POS],m);if(a.value)return this.error('Unexpected "=" found; an operator was already defined.',{index:h[P.FIELDS.START_POS]});a.operator=a.operator?a.operator+m:m,f="operator",p=!1;break;case R.comment:if(f)if(p||v&&v[P.FIELDS.TYPE]===R.space||f==="insensitive"){var Se=(0,le.getProp)(a,"spaces",f,"after")||"",Ve=(0,le.getProp)(a,"raws","spaces",f,"after")||Se;(0,le.ensureObject)(a,"raws","spaces",f),a.raws.spaces[f].after=Ve+m}else{var W=a[f]||"",ve=(0,le.getProp)(a,"raws",f)||W;(0,le.ensureObject)(a,"raws"),a.raws[f]=ve+m}else c=c+m;break;default:return this.error('Unexpected "'+m+'" found.',{index:h[P.FIELDS.START_POS]})}o++}Ur(a,"attribute"),Ur(a,"namespace"),this.newNode(new fx.default(a)),this.position++},e.parseWhitespaceEquivalentTokens=function(i){i<0&&(i=this.tokens.length);var n=this.position,s=[],a="",o=void 0;do if(Ic[this.currToken[P.FIELDS.TYPE]])this.options.lossy||(a+=this.content());else if(this.currToken[P.FIELDS.TYPE]===R.comment){var u={};a&&(u.before=a,a=""),o=new ux.default({value:this.content(),source:jr(this.currToken),sourceIndex:this.currToken[P.FIELDS.START_POS],spaces:u}),s.push(o)}while(++this.position<i);if(a){if(o)o.spaces.after=a;else if(!this.options.lossy){var c=this.tokens[n],f=this.tokens[this.position-1];s.push(new Ac.default({value:"",source:Zt(c[P.FIELDS.START_LINE],c[P.FIELDS.START_COL],f[P.FIELDS.END_LINE],f[P.FIELDS.END_COL]),sourceIndex:c[P.FIELDS.START_POS],spaces:{before:a,after:""}}))}}return s},e.convertWhitespaceNodesToSpace=function(i,n){var s=this;n===void 0&&(n=!1);var a="",o="";i.forEach(function(c){var f=s.lossySpace(c.spaces.before,n),p=s.lossySpace(c.rawSpaceBefore,n);a+=f+s.lossySpace(c.spaces.after,n&&f.length===0),o+=f+c.value+s.lossySpace(c.rawSpaceAfter,n&&p.length===0)}),o===a&&(o=void 0);var u={space:a,rawSpace:o};return u},e.isNamedCombinator=function(i){return i===void 0&&(i=this.position),this.tokens[i+0]&&this.tokens[i+0][P.FIELDS.TYPE]===R.slash&&this.tokens[i+1]&&this.tokens[i+1][P.FIELDS.TYPE]===R.word&&this.tokens[i+2]&&this.tokens[i+2][P.FIELDS.TYPE]===R.slash},e.namedCombinator=function(){if(this.isNamedCombinator()){var i=this.content(this.tokens[this.position+1]),n=(0,le.unesc)(i).toLowerCase(),s={};n!==i&&(s.value="/"+i+"/");var a=new Cc.default({value:"/"+n+"/",source:Zt(this.currToken[P.FIELDS.START_LINE],this.currToken[P.FIELDS.START_COL],this.tokens[this.position+2][P.FIELDS.END_LINE],this.tokens[this.position+2][P.FIELDS.END_COL]),sourceIndex:this.currToken[P.FIELDS.START_POS],raws:s});return this.position=this.position+3,a}else this.unexpected()},e.combinator=function(){var i=this;if(this.content()==="|")return this.namespace();var n=this.locateNextMeaningfulToken(this.position);if(n<0||this.tokens[n][P.FIELDS.TYPE]===R.comma){var s=this.parseWhitespaceEquivalentTokens(n);if(s.length>0){var a=this.current.last;if(a){var o=this.convertWhitespaceNodesToSpace(s),u=o.space,c=o.rawSpace;c!==void 0&&(a.rawSpaceAfter+=c),a.spaces.after+=u}else s.forEach(function(E){return i.newNode(E)})}return}var f=this.currToken,p=void 0;n>this.position&&(p=this.parseWhitespaceEquivalentTokens(n));var h;if(this.isNamedCombinator()?h=this.namedCombinator():this.currToken[P.FIELDS.TYPE]===R.combinator?(h=new Cc.default({value:this.content(),source:jr(this.currToken),sourceIndex:this.currToken[P.FIELDS.START_POS]}),this.position++):Ic[this.currToken[P.FIELDS.TYPE]]||p||this.unexpected(),h){if(p){var m=this.convertWhitespaceNodesToSpace(p),v=m.space,S=m.rawSpace;h.spaces.before=v,h.rawSpaceBefore=S}}else{var b=this.convertWhitespaceNodesToSpace(p,!0),w=b.space,_=b.rawSpace;_||(_=w);var T={},O={spaces:{}};w.endsWith(" ")&&_.endsWith(" ")?(T.before=w.slice(0,w.length-1),O.spaces.before=_.slice(0,_.length-1)):w.startsWith(" ")&&_.startsWith(" ")?(T.after=w.slice(1),O.spaces.after=_.slice(1)):O.value=_,h=new Cc.default({value:" ",source:Dc(f,this.tokens[this.position-1]),sourceIndex:f[P.FIELDS.START_POS],spaces:T,raws:O})}return this.currToken&&this.currToken[P.FIELDS.TYPE]===R.space&&(h.spaces.after=this.optionalSpace(this.content()),this.position++),this.newNode(h)},e.comma=function(){if(this.position===this.tokens.length-1){this.root.trailingComma=!0,this.position++;return}this.current._inferEndPosition();var i=new Ec.default({source:{start:dx(this.tokens[this.position+1])}});this.current.parent.append(i),this.current=i,this.position++},e.comment=function(){var i=this.currToken;this.newNode(new ux.default({value:this.content(),source:jr(i),sourceIndex:i[P.FIELDS.START_POS]})),this.position++},e.error=function(i,n){throw this.root.error(i,n)},e.missingBackslash=function(){return this.error("Expected a backslash preceding the semicolon.",{index:this.currToken[P.FIELDS.START_POS]})},e.missingParenthesis=function(){return this.expected("opening parenthesis",this.currToken[P.FIELDS.START_POS])},e.missingSquareBracket=function(){return this.expected("opening square bracket",this.currToken[P.FIELDS.START_POS])},e.unexpected=function(){return this.error("Unexpected '"+this.content()+"'. Escaping special characters with \\ may help.",this.currToken[P.FIELDS.START_POS])},e.namespace=function(){var i=this.prevToken&&this.content(this.prevToken)||!0;if(this.nextToken[P.FIELDS.TYPE]===R.word)return this.position++,this.word(i);if(this.nextToken[P.FIELDS.TYPE]===R.asterisk)return this.position++,this.universal(i)},e.nesting=function(){if(this.nextToken){var i=this.content(this.nextToken);if(i==="|"){this.position++;return}}var n=this.currToken;this.newNode(new iR.default({value:this.content(),source:jr(n),sourceIndex:n[P.FIELDS.START_POS]})),this.position++},e.parentheses=function(){var i=this.current.last,n=1;if(this.position++,i&&i.type===sR.PSEUDO){var s=new Ec.default({source:{start:dx(this.tokens[this.position-1])}}),a=this.current;for(i.append(s),this.current=s;this.position<this.tokens.length&&n;)this.currToken[P.FIELDS.TYPE]===R.openParenthesis&&n++,this.currToken[P.FIELDS.TYPE]===R.closeParenthesis&&n--,n?this.parse():(this.current.source.end=hx(this.currToken),this.current.parent.source.end=hx(this.currToken),this.position++);this.current=a}else{for(var o=this.currToken,u="(",c;this.position<this.tokens.length&&n;)this.currToken[P.FIELDS.TYPE]===R.openParenthesis&&n++,this.currToken[P.FIELDS.TYPE]===R.closeParenthesis&&n--,c=this.currToken,u+=this.parseParenthesisToken(this.currToken),this.position++;i?i.appendToPropertyAndEscape("value",u,u):this.newNode(new Ac.default({value:u,source:Zt(o[P.FIELDS.START_LINE],o[P.FIELDS.START_COL],c[P.FIELDS.END_LINE],c[P.FIELDS.END_COL]),sourceIndex:o[P.FIELDS.START_POS]}))}if(n)return this.expected("closing parenthesis",this.currToken[P.FIELDS.START_POS])},e.pseudo=function(){for(var i=this,n="",s=this.currToken;this.currToken&&this.currToken[P.FIELDS.TYPE]===R.colon;)n+=this.content(),this.position++;if(!this.currToken)return this.expected(["pseudo-class","pseudo-element"],this.position-1);if(this.currToken[P.FIELDS.TYPE]===R.word)this.splitWord(!1,function(a,o){n+=a,i.newNode(new tR.default({value:n,source:Dc(s,i.currToken),sourceIndex:s[P.FIELDS.START_POS]})),o>1&&i.nextToken&&i.nextToken[P.FIELDS.TYPE]===R.openParenthesis&&i.error("Misplaced parenthesis.",{index:i.nextToken[P.FIELDS.START_POS]})});else return this.expected(["pseudo-class","pseudo-element"],this.currToken[P.FIELDS.START_POS])},e.space=function(){var i=this.content();this.position===0||this.prevToken[P.FIELDS.TYPE]===R.comma||this.prevToken[P.FIELDS.TYPE]===R.openParenthesis||this.current.nodes.every(function(n){return n.type==="comment"})?(this.spaces=this.optionalSpace(i),this.position++):this.position===this.tokens.length-1||this.nextToken[P.FIELDS.TYPE]===R.comma||this.nextToken[P.FIELDS.TYPE]===R.closeParenthesis?(this.current.last.spaces.after=this.optionalSpace(i),this.position++):this.combinator()},e.string=function(){var i=this.currToken;this.newNode(new Ac.default({value:this.content(),source:jr(i),sourceIndex:i[P.FIELDS.START_POS]})),this.position++},e.universal=function(i){var n=this.nextToken;if(n&&this.content(n)==="|")return this.position++,this.namespace();var s=this.currToken;this.newNode(new rR.default({value:this.content(),source:jr(s),sourceIndex:s[P.FIELDS.START_POS]}),i),this.position++},e.splitWord=function(i,n){for(var s=this,a=this.nextToken,o=this.content();a&&~[R.dollar,R.caret,R.equals,R.word].indexOf(a[P.FIELDS.TYPE]);){this.position++;var u=this.content();if(o+=u,u.lastIndexOf("\\")===u.length-1){var c=this.nextToken;c&&c[P.FIELDS.TYPE]===R.space&&(o+=this.requiredSpace(this.content(c)),this.position++)}a=this.nextToken}var f=qc(o,".").filter(function(v){var S=o[v-1]==="\\",b=/^\d+\.\d+%$/.test(o);return!S&&!b}),p=qc(o,"#").filter(function(v){return o[v-1]!=="\\"}),h=qc(o,"#{");h.length&&(p=p.filter(function(v){return!~h.indexOf(v)}));var m=(0,nR.default)(lR([0].concat(f,p)));m.forEach(function(v,S){var b=m[S+1]||o.length,w=o.slice(v,b);if(S===0&&n)return n.call(s,w,m.length);var _,T=s.currToken,O=T[P.FIELDS.START_POS]+m[S],E=Zt(T[1],T[2]+v,T[3],T[2]+(b-1));if(~f.indexOf(v)){var F={value:w.slice(1),source:E,sourceIndex:O};_=new Kq.default(Ur(F,"value"))}else if(~p.indexOf(v)){var z={value:w.slice(1),source:E,sourceIndex:O};_=new Zq.default(Ur(z,"value"))}else{var N={value:w,source:E,sourceIndex:O};Ur(N,"value"),_=new eR.default(N)}s.newNode(_,i),i=null}),this.position++},e.word=function(i){var n=this.nextToken;return n&&this.content(n)==="|"?(this.position++,this.namespace()):this.splitWord(i)},e.loop=function(){for(;this.position<this.tokens.length;)this.parse(!0);return this.current._inferEndPosition(),this.root},e.parse=function(i){switch(this.currToken[P.FIELDS.TYPE]){case R.space:this.space();break;case R.comment:this.comment();break;case R.openParenthesis:this.parentheses();break;case R.closeParenthesis:i&&this.missingParenthesis();break;case R.openSquare:this.attribute();break;case R.dollar:case R.caret:case R.equals:case R.word:this.word();break;case R.colon:this.pseudo();break;case R.comma:this.comma();break;case R.asterisk:this.universal();break;case R.ampersand:this.nesting();break;case R.slash:case R.combinator:this.combinator();break;case R.str:this.string();break;case R.closeSquare:this.missingSquareBracket();case R.semicolon:this.missingBackslash();default:this.unexpected()}},e.expected=function(i,n,s){if(Array.isArray(i)){var a=i.pop();i=i.join(", ")+" or "+a}var o=/^[aeiou]/.test(i[0])?"an":"a";return s?this.error("Expected "+o+" "+i+', found "'+s+'" instead.',{index:n}):this.error("Expected "+o+" "+i+".",{index:n})},e.requiredSpace=function(i){return this.options.lossy?" ":i},e.optionalSpace=function(i){return this.options.lossy?"":i},e.lossySpace=function(i,n){return this.options.lossy?n?" ":"":i},e.parseParenthesisToken=function(i){var n=this.content(i);return i[P.FIELDS.TYPE]===R.space?this.requiredSpace(n):n},e.newNode=function(i,n){return n&&(/^ +$/.test(n)&&(this.options.lossy||(this.spaces=(this.spaces||"")+n),n=!0),i.namespace=n,Ur(i,"namespace")),this.spaces&&(i.spaces.before=this.spaces,this.spaces=""),this.current.append(i)},e.content=function(i){return i===void 0&&(i=this.currToken),this.css.slice(i[P.FIELDS.START_POS],i[P.FIELDS.END_POS])},e.locateNextMeaningfulToken=function(i){i===void 0&&(i=this.position+1);for(var n=i;n<this.tokens.length;)if(oR[this.tokens[n][P.FIELDS.TYPE]]){n++;continue}else return n;return-1},aR(t,[{key:"currToken",get:function(){return this.tokens[this.position]}},{key:"nextToken",get:function(){return this.tokens[this.position+1]}},{key:"prevToken",get:function(){return this.tokens[this.position-1]}}]),t}();gn.default=uR;mx.exports=gn.default});var vx=k((yn,yx)=>{l();"use strict";yn.__esModule=!0;yn.default=void 0;var fR=cR(gx());function cR(t){return t&&t.__esModule?t:{default:t}}var pR=function(){function t(r,i){this.func=r||function(){},this.funcRes=null,this.options=i}var e=t.prototype;return e._shouldUpdateSelector=function(i,n){n===void 0&&(n={});var s=Object.assign({},this.options,n);return s.updateSelector===!1?!1:typeof i!="string"},e._isLossy=function(i){i===void 0&&(i={});var n=Object.assign({},this.options,i);return n.lossless===!1},e._root=function(i,n){n===void 0&&(n={});var s=new fR.default(i,this._parseOptions(n));return s.root},e._parseOptions=function(i){return{lossy:this._isLossy(i)}},e._run=function(i,n){var s=this;return n===void 0&&(n={}),new Promise(function(a,o){try{var u=s._root(i,n);Promise.resolve(s.func(u)).then(function(c){var f=void 0;return s._shouldUpdateSelector(i,n)&&(f=u.toString(),i.selector=f),{transform:c,root:u,string:f}}).then(a,o)}catch(c){o(c);return}})},e._runSync=function(i,n){n===void 0&&(n={});var s=this._root(i,n),a=this.func(s);if(a&&typeof a.then=="function")throw new Error("Selector processor returned a promise to a synchronous call.");var o=void 0;return n.updateSelector&&typeof i!="string"&&(o=s.toString(),i.selector=o),{transform:a,root:s,string:o}},e.ast=function(i,n){return this._run(i,n).then(function(s){return s.root})},e.astSync=function(i,n){return this._runSync(i,n).root},e.transform=function(i,n){return this._run(i,n).then(function(s){return s.transform})},e.transformSync=function(i,n){return this._runSync(i,n).transform},e.process=function(i,n){return this._run(i,n).then(function(s){return s.string||s.root.toString()})},e.processSync=function(i,n){var s=this._runSync(i,n);return s.string||s.root.toString()},t}();yn.default=pR;yx.exports=yn.default});var wx=k(ne=>{l();"use strict";ne.__esModule=!0;ne.universal=ne.tag=ne.string=ne.selector=ne.root=ne.pseudo=ne.nesting=ne.id=ne.comment=ne.combinator=ne.className=ne.attribute=void 0;var dR=je(vc()),hR=je(tc()),mR=je(kc()),gR=je(ic()),yR=je(sc()),vR=je(_c()),wR=je(pc()),bR=je(Xf()),xR=je(Zf()),kR=je(fc()),SR=je(lc()),_R=je(bc());function je(t){return t&&t.__esModule?t:{default:t}}var TR=function(e){return new dR.default(e)};ne.attribute=TR;var OR=function(e){return new hR.default(e)};ne.className=OR;var ER=function(e){return new mR.default(e)};ne.combinator=ER;var AR=function(e){return new gR.default(e)};ne.comment=AR;var CR=function(e){return new yR.default(e)};ne.id=CR;var PR=function(e){return new vR.default(e)};ne.nesting=PR;var IR=function(e){return new wR.default(e)};ne.pseudo=IR;var DR=function(e){return new bR.default(e)};ne.root=DR;var qR=function(e){return new xR.default(e)};ne.selector=qR;var RR=function(e){return new kR.default(e)};ne.string=RR;var LR=function(e){return new SR.default(e)};ne.tag=LR;var BR=function(e){return new _R.default(e)};ne.universal=BR});var Sx=k(Q=>{l();"use strict";Q.__esModule=!0;Q.isNode=Rc;Q.isPseudoElement=kx;Q.isPseudoClass=HR;Q.isContainer=YR;Q.isNamespace=QR;Q.isUniversal=Q.isTag=Q.isString=Q.isSelector=Q.isRoot=Q.isPseudo=Q.isNesting=Q.isIdentifier=Q.isComment=Q.isCombinator=Q.isClassName=Q.isAttribute=void 0;var ue=ke(),Ie,MR=(Ie={},Ie[ue.ATTRIBUTE]=!0,Ie[ue.CLASS]=!0,Ie[ue.COMBINATOR]=!0,Ie[ue.COMMENT]=!0,Ie[ue.ID]=!0,Ie[ue.NESTING]=!0,Ie[ue.PSEUDO]=!0,Ie[ue.ROOT]=!0,Ie[ue.SELECTOR]=!0,Ie[ue.STRING]=!0,Ie[ue.TAG]=!0,Ie[ue.UNIVERSAL]=!0,Ie);function Rc(t){return typeof t=="object"&&MR[t.type]}function Ue(t,e){return Rc(e)&&e.type===t}var bx=Ue.bind(null,ue.ATTRIBUTE);Q.isAttribute=bx;var FR=Ue.bind(null,ue.CLASS);Q.isClassName=FR;var NR=Ue.bind(null,ue.COMBINATOR);Q.isCombinator=NR;var zR=Ue.bind(null,ue.COMMENT);Q.isComment=zR;var $R=Ue.bind(null,ue.ID);Q.isIdentifier=$R;var jR=Ue.bind(null,ue.NESTING);Q.isNesting=jR;var Lc=Ue.bind(null,ue.PSEUDO);Q.isPseudo=Lc;var UR=Ue.bind(null,ue.ROOT);Q.isRoot=UR;var VR=Ue.bind(null,ue.SELECTOR);Q.isSelector=VR;var WR=Ue.bind(null,ue.STRING);Q.isString=WR;var xx=Ue.bind(null,ue.TAG);Q.isTag=xx;var GR=Ue.bind(null,ue.UNIVERSAL);Q.isUniversal=GR;function kx(t){return Lc(t)&&t.value&&(t.value.startsWith("::")||t.value.toLowerCase()===":before"||t.value.toLowerCase()===":after"||t.value.toLowerCase()===":first-letter"||t.value.toLowerCase()===":first-line")}function HR(t){return Lc(t)&&!kx(t)}function YR(t){return!!(Rc(t)&&t.walk)}function QR(t){return bx(t)||xx(t)}});var _x=k(Ke=>{l();"use strict";Ke.__esModule=!0;var Bc=ke();Object.keys(Bc).forEach(function(t){t==="default"||t==="__esModule"||t in Ke&&Ke[t]===Bc[t]||(Ke[t]=Bc[t])});var Mc=wx();Object.keys(Mc).forEach(function(t){t==="default"||t==="__esModule"||t in Ke&&Ke[t]===Mc[t]||(Ke[t]=Mc[t])});var Fc=Sx();Object.keys(Fc).forEach(function(t){t==="default"||t==="__esModule"||t in Ke&&Ke[t]===Fc[t]||(Ke[t]=Fc[t])})});var Ex=k((vn,Ox)=>{l();"use strict";vn.__esModule=!0;vn.default=void 0;var JR=ZR(vx()),XR=KR(_x());function Tx(){if(typeof WeakMap!="function")return null;var t=new WeakMap;return Tx=function(){return t},t}function KR(t){if(t&&t.__esModule)return t;if(t===null||typeof t!="object"&&typeof t!="function")return{default:t};var e=Tx();if(e&&e.has(t))return e.get(t);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){var s=i?Object.getOwnPropertyDescriptor(t,n):null;s&&(s.get||s.set)?Object.defineProperty(r,n,s):r[n]=t[n]}return r.default=t,e&&e.set(t,r),r}function ZR(t){return t&&t.__esModule?t:{default:t}}var Nc=function(e){return new JR.default(e)};Object.assign(Nc,XR);delete Nc.__esModule;var eL=Nc;vn.default=eL;Ox.exports=vn.default});var Px=k((z$,Cx)=>{l();var tL=S1(),Ax=Ex(),rL=Ax();Cx.exports={isUsableColor(t,e){return tL(e)&&t!=="gray"&&e[600]},commonTrailingPseudos(t){let e=rL.astSync(t),r=[];for(let[n,s]of e.nodes.entries())for(let[a,o]of[...s.nodes].reverse().entries()){if(o.type!=="pseudo"||!o.value.startsWith("::"))break;r[a]=r[a]||[],r[a][n]=o}let i=Ax.selector();for(let n of r){if(!n)continue;if(new Set([...n.map(a=>a.value)]).size>1)break;n.forEach(a=>a.remove()),i.prepend(n[0])}return i.nodes.length?[i.toString(),e.toString()]:[null,t]}}});var Rx=k(($$,qx)=>{l();var iL=($s(),zs).default,nL=m1(),sL=y1(),aL=w1(),{commonTrailingPseudos:oL}=Px(),Ix={};function zc(t,{className:e,modifier:r,prefix:i}){let n=i(`.not-${e}`).slice(1),s=t.startsWith(">")?`${r==="DEFAULT"?`.${e}`:`.${e}-${r}`} `:"",[a,o]=oL(t);return a?`:where(${s}${o}):not(:where([class~="${n}"],[class~="${n}"] *))${a}`:`:where(${s}${t}):not(:where([class~="${n}"],[class~="${n}"] *))`}function Dx(t){return typeof t=="object"&&t!==null}function lL(t={},{target:e,className:r,modifier:i,prefix:n}){function s(a,o){return e==="legacy"?[a,o]:Array.isArray(o)?[a,o]:Dx(o)?Object.values(o).some(Dx)?[zc(a,{className:r,modifier:i,prefix:n}),o,Object.fromEntries(Object.entries(o).map(([c,f])=>s(c,f)))]:[zc(a,{className:r,modifier:i,prefix:n}),o]:[a,o]}return Object.fromEntries(Object.entries(nL({},...Object.keys(t).filter(a=>Ix[a]).map(a=>Ix[a](t[a])),...sL(t.css||{}))).map(([a,o])=>s(a,o)))}qx.exports=iL.withOptions(({className:t="prose",target:e="modern"}={})=>function({addVariant:r,addComponents:i,theme:n,prefix:s}){let a=n("typography"),o={className:t,prefix:s};for(let[u,...c]of[["headings","h1","h2","h3","h4","h5","h6","th"],["h1"],["h2"],["h3"],["h4"],["h5"],["h6"],["p"],["a"],["blockquote"],["figure"],["figcaption"],["strong"],["em"],["code"],["pre"],["ol"],["ul"],["li"],["table"],["thead"],["tr"],["th"],["td"],["img"],["video"],["hr"],["lead",'[class~="lead"]']]){c=c.length===0?[u]:c;let f=e==="legacy"?c.map(p=>`& ${p}`):c.join(", ");r(`${t}-${u}`,e==="legacy"?f:`& :is(${zc(f,o)})`)}i(Object.keys(a).map(u=>({[u==="DEFAULT"?`.${t}`:`.${t}-${u}`]:lL(a[u],{target:e,className:t,modifier:u,prefix:s})})))},()=>({theme:{typography:aL}}))});var Lx={};Ge(Lx,{default:()=>uL});var uL,Bx=A(()=>{l();uL=[Rx()]});var Fx={};Ge(Fx,{default:()=>fL});var Mx,fL,Nx=A(()=>{l();An();Mx=ce(qn()),fL=Ot(Mx.default.theme)});var $x={};Ge($x,{default:()=>cL});var zx,cL,jx=A(()=>{l();An();zx=ce(qn()),cL=Ot(zx.default)});l();"use strict";var pL=St(Qy()),dL=St(qe()),hL=St(zb()),mL=St((Bx(),Lx)),gL=St((Nx(),Fx)),yL=St((jx(),$x)),vL=St((Tn(),Da)),wL=St(($s(),zs)),bL=St((Ha(),Mp));function St(t){return t&&t.__esModule?t:{default:t}};var Oa="tailwind",$c="text/tailwindcss",Ux="/template.html",er,Vx=!0,Wx=0,jc=new Set,Uc,Gx="",Hx=(t=!1)=>({get(e,r){return(!t||r==="config")&&typeof e[r]=="object"&&e[r]!==null?new Proxy(e[r],Hx()):e[r]},set(e,r,i){return e[r]=i,(!t||r==="config")&&Vc(!0),!0}});window[Oa]=new Proxy({config:{},defaultTheme:gL.default,defaultConfig:yL.default,colors:vL.default,plugin:wL.default,resolveConfig:bL.default},Hx(!0));function Yx(t){Uc.observe(t,{attributes:!0,attributeFilter:["type"],characterData:!0,subtree:!0,childList:!0})}new MutationObserver(async t=>{let e=!1;if(!Uc){Uc=new MutationObserver(async()=>await Vc(!0));for(let r of document.querySelectorAll(`style[type="${$c}"]`))Yx(r)}for(let r of t)for(let i of r.addedNodes)i.nodeType===1&&i.tagName==="STYLE"&&i.getAttribute("type")===$c&&(Yx(i),e=!0);await Vc(e)}).observe(document.documentElement,{attributes:!0,attributeFilter:["class"],childList:!0,subtree:!0});async function Vc(t=!1){t&&(Wx++,jc.clear());let e="";for(let i of document.querySelectorAll(`style[type="${$c}"]`))e+=i.textContent;let r=new Set;for(let i of document.querySelectorAll("[class]"))for(let n of i.classList)jc.has(n)||r.add(n);if(document.body&&(Vx||r.size>0||e!==Gx||!er||!er.isConnected)){for(let n of r)jc.add(n);Vx=!1,Gx=e,self[Ux]=Array.from(r).join(" ");let{css:i}=await(0,dL.default)([(0,pL.default)({...window[Oa].config,_hash:Wx,content:[Ux],plugins:[...mL.default,...Array.isArray(window[Oa].config.plugins)?window[Oa].config.plugins:[]]}),(0,hL.default)({remove:!1})]).process(`@tailwind base;@tailwind components;@tailwind utilities;${e}`);(!er||!er.isConnected)&&(er=document.createElement("style"),document.head.append(er)),er.textContent=i}}})();
/*! https://mths.be/cssesc v3.0.0 by @mathias */
tailwind.config={
darkMode: ["class"],
theme: {
container: {
center: true,
padding: "2rem",
screens: {
"2xl": "1400px",
},
},
extend: {
colors: {
border: "hsl(var(--border))",
input: "hsl(var(--input))",
ring: "hsl(var(--ring))",
background: "hsl(var(--background))",
foreground: "hsl(var(--foreground))",
primary: {
DEFAULT: "hsl(var(--primary))",
foreground: "hsl(var(--primary-foreground))",
},
secondary: {
DEFAULT: "hsl(var(--secondary))",
foreground: "hsl(var(--secondary-foreground))",
},
destructive: {
DEFAULT: "hsl(var(--destructive))",
foreground: "hsl(var(--destructive-foreground))",
},
muted: {
DEFAULT: "hsl(var(--muted))",
foreground: "hsl(var(--muted-foreground))",
},
accent: {
DEFAULT: "hsl(var(--accent))",
foreground: "hsl(var(--accent-foreground))",
},
popover: {
DEFAULT: "hsl(var(--popover))",
foreground: "hsl(var(--popover-foreground))",
},
card: {
DEFAULT: "hsl(var(--card))",
foreground: "hsl(var(--card-foreground))",
},
},
borderRadius: {
lg: "var(--radius)",
md: "calc(var(--radius) - 2px)",
sm: "calc(var(--radius) - 4px)",
},
keyframes: {
"accordion-down": {
from: { height: 0 },
to: { height: "var(--radix-accordion-content-height)" },
},
"accordion-up": {
from: { height: "var(--radix-accordion-content-height)" },
to: { height: 0 },
},
"collapsible-down": {
from: { height: 0 },
to: { height: 'var(--radix-collapsible-content-height)' },
},
"collapsible-up": {
from: { height: 'var(--radix-collapsible-content-height)' },
to: { height: 0 },
},
},
animation: {
"accordion-down": "accordion-down 0.2s ease-out",
"accordion-up": "accordion-up 0.2s ease-out",
"collapsible-down": "collapsible-down 0.2s ease-in-out",
"collapsible-up": "collapsible-up 0.2s ease-in-out",
},
},
},
} | zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/api/auth/github.get.ts | TypeScript | declare module '#auth-utils' {
interface UserSession {
// define the type here
id: number
email: string
name: string
avatar_url: string
login: string
}
}
export {}
export default oauth.githubEventHandler({
config: {
emailRequired: true,
},
async onSuccess(event, { user }) {
try {
await useDB().insert(tables.users).values({
id: user.id,
email: user.email,
name: user.login ?? user.name,
avatarUrl: user.avatar_url,
})
}
catch (err) {
console.log('err', err)
}
// @ts-expect-error package type issue
await setUserSession(event, { user })
return sendRedirect(event, '/')
},
})
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/api/component/[slug].get.ts | TypeScript | import { desc, eq } from 'drizzle-orm'
export default defineEventHandler(async (event) => {
const slug = event.context.params?.slug ?? ''
const { components, users } = tables
const res = await useDB()
// @ts-expect-error fetch latest components
.select({
...components,
user: users,
})
.from(components)
.leftJoin(users, eq(components.userId, users.id))
.orderBy(desc(components.createdAt))
.where(eq(components.slug, slug))
return res
})
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/api/component/all.get.ts | TypeScript | import { desc, eq, max } from 'drizzle-orm'
export default defineEventHandler(async (_event) => {
const { components, users } = tables
const res = await useDB()
// @ts-expect-error fetch latest components
.select({
...components,
user: users,
value: max(components.createdAt),
})
.from(components)
.leftJoin(users, eq(components.userId, users.id))
.where(eq(components.completed, true))
.orderBy(desc(components.createdAt))
.groupBy(components.slug)
.all()
return res
})
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/api/component/delete.post.ts | TypeScript | import { eq } from 'drizzle-orm'
import { z } from 'zod'
import { validateBody, validateUser } from '~/server/utils/validateBody'
export default defineEventHandler(async (event) => {
const { id, slug } = await validateBody(event, z.object({
id: z.string(),
slug: z.string().optional(),
}).safeParse)
const user = await validateUser(event)
const { components } = tables
const res = await useDB()
.select()
.from(components)
.where(eq(components.id, id))
.get()
if (res?.userId !== user.id)
return createError('This generation cannot be deleted by this user')
try {
if (slug) {
return useDB()
.delete(components)
.where(eq(components.slug, slug))
}
else {
return useDB()
.delete(components)
.where(eq(components.id, id))
}
}
catch (err) {
if (err instanceof Error)
return createError(err.message)
}
})
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/api/component/fork.post.ts | TypeScript | import { desc, eq } from 'drizzle-orm'
import { z } from 'zod'
import { validateBody, validateUser } from '~/server/utils/validateBody'
export default defineEventHandler(async (event) => {
const { id, slug } = await validateBody(event, z.object({
id: z.string(),
slug: z.string(),
}).safeParse)
const user = await validateUser(event)
const { components } = tables
const res = await useDB()
.select()
.from(components)
.orderBy(desc(components.createdAt))
.where(eq(components.slug, slug))
const selectedVersion = res.find(i => i.id === id)
if (res.length && selectedVersion) {
const { code, metadata, completed } = selectedVersion
const { description } = res[res.length - 1] // get the first prompt
return await useDB()
.insert(components)
.values({
description,
code,
metadata,
completed,
userId: user?.id,
})
.returning().get()
}
else if (res.length) {
return createError('No selected version found')
}
else {
return createError('No component found')
}
})
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/api/component/id/[id].get.ts | TypeScript | import { desc, eq } from 'drizzle-orm'
export default defineEventHandler(async (event) => {
const id = event.context.params?.id ?? ''
const { components, users } = tables
const res = await useDB()
// @ts-expect-error fetch latest components
.select({
...components,
user: users,
})
.from(components)
.leftJoin(users, eq(components.userId, users.id))
.orderBy(desc(components.createdAt))
.where(eq(components.id, id))
return res
})
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/api/component/user/[name].get.ts | TypeScript | import { and, desc, eq, max } from 'drizzle-orm'
export default defineEventHandler(async (event) => {
const name = event.context.params?.name ?? ''
const { components, users } = tables
const res = await useDB()
// @ts-expect-error fetch latest components
.select({
...components,
value: max(components.createdAt),
user: users,
})
.from(components)
.leftJoin(users, eq(components.userId, users.id))
.orderBy(desc(components.createdAt))
.groupBy(components.slug)
.where(and(eq(users.name, name), eq(components.completed, true)))
return res
})
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/api/create.post.ts | TypeScript | import { eq } from 'drizzle-orm'
import { z } from 'zod'
export default defineEventHandler(async (event) => {
const { id } = await validateBody(event, z.object({
id: z.string(),
prompt: z.string(),
}).safeParse)
const { close } = useSSE(event)
try {
await designComponentNew(event)
await buildComponentGeneration(event)
await generateComponentNew(event)
await storeComponent(event, id)
close()
}
catch (err) {
if (err instanceof Error) {
console.log('error caught ', err.message)
await useDB().update(tables.components).set({ id, error: err.message }).where(eq(tables.components.id, id))
event.node.res.write(`[Error]: ${err.message}`)
}
close()
}
})
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/api/image/[id].ts | TypeScript | import { and, desc, eq, max } from 'drizzle-orm'
export default defineEventHandler(async (event) => {
const { id } = getRouterParams(event)
const { slug } = getQuery(event)
const { components, images } = tables
if (id) {
let result: typeof images.$inferSelect | undefined
// If slug is true, meaning the id being passed is actually slug's id
if (slug) {
const test = await useDB()
.select()
.from(images)
.leftJoin(components, eq(images.id, components.id))
.where(and(eq(components.completed, true), eq(components.slug, id)))
.orderBy(desc(components.createdAt))
.get()
result = test?.images
}
else {
result = await useDB().select().from(images).where(eq(images.id, id)).get()
}
if (result) {
setHeaders(event, {
'Content-Type': 'image/jpeg',
'Cache-Control': 'max-age=604800, public',
})
return result.buffer
}
else {
sendRedirect(event, '/placeholder.svg')
// return createError('Invalid id found')
}
}
else {
return createError('Missing id')
}
})
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/api/init.post.ts | TypeScript | import { z } from 'zod'
import { readValidatedBody } from 'h3'
export default defineEventHandler(async (event) => {
const result = await readValidatedBody(event, z.object({
slug: z.string().optional(),
prompt: z.string(),
basedOnResultId: z.string().optional(),
}).safeParse)
const user = await validateUser(event)
if (result.success) {
const { slug, prompt, basedOnResultId } = result.data
return useDB().insert(tables.components).values({
slug,
description: prompt,
userId: user.id,
basedOnId: basedOnResultId,
}).returning().get()
}
else {
return createError(result.error.message)
}
})
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/api/iterate.post.ts | TypeScript | import { eq } from 'drizzle-orm'
import { alias } from 'drizzle-orm/sqlite-core'
import { z } from 'zod'
export default defineEventHandler(async (event) => {
const { id } = await validateBody(event, z.object({
id: z.string(),
prompt: z.string(),
}).safeParse)
const { components } = tables
const componentAlias = alias(components, 'baseComponent')
const result = await useDB().select()
.from(components)
.leftJoin(componentAlias, eq(components.basedOnId, componentAlias.id))
.where(eq(components.id, id))
const previousResult = result?.[0].baseComponent
if (!previousResult?.code)
return createError('Previous code not found')
const { close } = useSSE(event)
try {
await designComponentIteration(event, previousResult)
await buildComponentGeneration(event)
await generateComponentIteration(event, previousResult)
await storeComponent(event, id, previousResult.slug)
close()
}
catch (err) {
if (err instanceof Error) {
console.log('error caught ', err.message)
await useDB().update(tables.components).set({ id, error: err.message }).where(eq(tables.components.id, id))
event.node.res.write(`[Error]: ${err.message}`)
}
close()
}
})
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/database/migrations/0000_lying_nomad.sql | SQL | CREATE TABLE `components` (
`id` text PRIMARY KEY NOT NULL,
`slug` text,
`description` text NOT NULL,
`code` text,
`created_at` integer
);
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/database/migrations/0001_stale_gideon.sql | SQL | ALTER TABLE components ADD `metadata` text;--> statement-breakpoint
ALTER TABLE components ADD `completed` integer; | zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/database/migrations/0004_needy_dark_phoenix.sql | SQL | CREATE TABLE `users` (
`id` integer PRIMARY KEY NOT NULL,
`email` text NOT NULL,
`avatar_url` text
);
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/database/migrations/0006_secret_fallen_one.sql | SQL | ALTER TABLE components ADD `user_id` integer; | zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/database/migrations/0008_breezy_zarda.sql | SQL | ALTER TABLE `components` DROP COLUMN `user_id`; | zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/database/migrations/0009_slimy_sunfire.sql | SQL | ALTER TABLE components ADD `user_id` integer REFERENCES users(id); | zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/database/migrations/0010_remarkable_loki.sql | SQL | ALTER TABLE users ADD `name` text; | zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/database/migrations/0011_plain_randall_flagg.sql | SQL | CREATE TABLE `images` (
`id` text PRIMARY KEY NOT NULL,
`buffer` blob
);
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/database/migrations/0012_cute_layla_miller.sql | SQL | ALTER TABLE components ADD `error` text; | zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/database/migrations/0013_whole_the_liberteens.sql | SQL | ALTER TABLE components ADD `based_on_id` text REFERENCES components(id); | zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/database/schema.ts | TypeScript | import type { AnySQLiteColumn } from 'drizzle-orm/sqlite-core'
import { blob, integer, sqliteTable, text } from 'drizzle-orm/sqlite-core'
import { init } from '@paralleldrive/cuid2'
const createId = init({
length: 12,
})
export const users = sqliteTable('users', {
id: integer('id').notNull().primaryKey(),
email: text('email').notNull(),
name: text('name'),
avatarUrl: text('avatar_url'),
})
export const components = sqliteTable('components', {
id: text('id').$defaultFn(() => createId()).primaryKey(),
slug: text('slug').$defaultFn(() => createId()),
description: text('description').notNull(),
code: text('code'),
createdAt: integer('created_at', { mode: 'timestamp_ms' }).$default(() => new Date()),
userId: integer('user_id').references(() => users.id),
metadata: text('metadata', { mode: 'json' }),
completed: integer('completed', { mode: 'boolean' }),
error: text('error'),
basedOnId: text('based_on_id').references((): AnySQLiteColumn => components.id),
})
export const images = sqliteTable('images', {
id: text('id').primaryKey(),
buffer: blob('buffer', { mode: 'buffer' }),
})
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/middleware/openai.ts | TypeScript | export default defineEventHandler((event) => {
const protectedPath = ['/api/create', '/api/init', '/api/iterate']
if (protectedPath.includes(getRequestURL(event).pathname)) {
if (!event.node.req.headers['x-openai-key']?.toString().includes('sk-'))
return createError('Missing Open AI key')
}
})
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/plugins/migrations.ts | TypeScript | import type { BetterSQLite3Database } from 'drizzle-orm/better-sqlite3'
import { migrate } from 'drizzle-orm/better-sqlite3/migrator'
export default defineNitroPlugin(async () => {
// if (process.dev)
// migrate(useDB() as BetterSQLite3Database, { migrationsFolder: 'server/database/migrations' })
})
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/utils/common.ts | TypeScript | import type { EventHandlerRequest, H3Event } from 'h3'
import { OpenAI } from 'openai'
export { upperFirst as capitalize } from 'scule'
export function useOpenAI(event: H3Event<EventHandlerRequest>) {
const apiKey = process.env.NUXT_OPENAI_API_KEY || event.node.req.headers['x-openai-key']?.toString()
return new OpenAI({
apiKey,
})
}
export function useSSE(event: H3Event<EventHandlerRequest>) {
// Enable SSE endpoint
setHeader(event, 'cache-control', 'no-cache')
setHeader(event, 'connection', 'keep-alive')
setHeader(event, 'content-type', 'text/event-stream')
setResponseStatus(event, 200)
// Let the connection opened
event._handled = true
const close = () => {
// Close connection, trigger release locked
event.node.res.end()
}
// event.node.req.on('close', close)
return {
close,
}
}
export const randomString = (length = 5) => Math.random().toString(36).substr(2, length)
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/utils/db.ts | TypeScript | import { createClient as createLibSQLClient } from '@libsql/client/http'
import Database from 'better-sqlite3'
import type { BetterSQLite3Database } from 'drizzle-orm/better-sqlite3'
import { drizzle } from 'drizzle-orm/better-sqlite3'
import type { LibSQLDatabase } from 'drizzle-orm/libsql'
import { drizzle as drizzleLibSQL } from 'drizzle-orm/libsql'
import { join } from 'pathe'
export * as tables from '~/server/database/schema'
export type DBComponent = typeof tables.components.$inferSelect & {
user?: typeof tables.users.$inferSelect
}
let _db: BetterSQLite3Database | LibSQLDatabase | null = null
export function useDB() {
if (!_db) {
if (process.env.TURSO_DB_URL && process.env.TURSO_DB_TOKEN) {
// Turso in production
_db = drizzleLibSQL(createLibSQLClient({
url: process.env.TURSO_DB_URL,
authToken: process.env.TURSO_DB_TOKEN,
}))
}
else if (process.dev) {
// local sqlite in development
const sqlite = new Database(join(process.cwd(), './db.sqlite'))
_db = drizzle(sqlite)
}
else {
throw new Error('No database configured for production')
}
}
return _db
}
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/utils/encoding.ts | TypeScript | import { getEncoding } from 'js-tiktoken'
export function encoding() {
return getEncoding('cl100k_base')
}
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/utils/multipass/buildComponentGeneration.ts | TypeScript | import type { EventHandlerRequest, H3Event } from 'h3'
import type { OpenAI } from 'openai'
declare module 'h3' {
interface NodeIncomingMessage {
componentDesignContext: OpenAI.ChatCompletionMessageParam[]
}
}
export default async (event: H3Event<EventHandlerRequest>) => {
console.log('> init : building component generation')
const TOKEN_LIMIT = 600
const componentDesignTask = event.node.req.componentDesignTask
const components = (await import('@/template/shadcn-vue/metadata.json')).default
const retrievedComponent = components.filter(i => componentDesignTask.components.find(j => j.name === i.name))
const encoder = encoding()
const mappedComponent = retrievedComponent.map((component) => {
const componentExamples = [...component.examples]
const examples: typeof componentExamples = []
let totalTokens = 0
while (totalTokens < TOKEN_LIMIT && componentExamples.length) {
const randomExample = componentExamples.splice(
Math.floor(Math.random() * componentExamples.length),
1,
)[0]
totalTokens += encoder.encode(randomExample.code).length
if (totalTokens < TOKEN_LIMIT)
examples.push(randomExample)
console.log(
`tokens for context entry ${component.name} : ${totalTokens} `
+ `(limit : ${TOKEN_LIMIT})`,
)
}
return {
...component,
examples,
}
})
const componentContext = mappedComponent.map((component, idx) => {
const examplesBlock = !component.examples.length
? ''
: `\n\n`
+ `# full code examples of Vue components that use ${component.name} :\n${
component.examples
.map((example) => {
return (
`\`\`\`${example.source}\n${example.code.trim()}\n\`\`\``
)
})
.join(`\n\n`)}`
return {
role: 'user',
content: `Library components can be used while making the new Vue component\n\n`
+ `Suggested library component (${idx + 1}/${mappedComponent.length}) : ${component.name} - ${component.description}\n`
+ `Suggested usage : ${component.usage}\n\n\n`
+ `# examples of how ${component.name} can be used inside the new component:\n${examplesBlock}`
+ `\n\nIcon elements can optionally be used when making the Vue component\n`
+ `Example for using 'lucide-vue-next' (Only use icon from the library) \n`
+ `\`\`\`1. ArrowRight\n2. Check\n3. Home\n4. User\n5. Search`
+ `\`\`\``,
} satisfies OpenAI.ChatCompletionMessageParam
})
event.node.req.componentDesignContext = componentContext
}
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/utils/multipass/designComponentIteration.ts | TypeScript | import type { EventHandlerRequest, H3Event } from 'h3'
import { z } from 'zod'
import { zodToJsonSchema } from 'zod-to-json-schema'
import type { OpenAI } from 'openai'
export default async (event: H3Event<EventHandlerRequest>, component: DBComponent) => {
console.log('> init : design component iteration')
const { prompt } = await readBody(event)
const components = (await import('@/template/shadcn-vue/metadata.json')).default
const functionSchema = z.object({
new_component_description: z.string().describe(`Write a description for Vue component design task based on the user query. Stick strictly to what the user wants in their request - do not go off track`),
use_library_components: z.array(z.object({
library_component_name: z.enum(components.map(i => i.name) as [string]),
library_component_usage_reason: z.string(),
})),
})
const context: OpenAI.ChatCompletionMessageParam[] = [
{
role: `system`,
content:
`Your task is to modify a Vue component for a web app, according to the user's request.\n`
+ `If you judge it is relevant to do so, you can specify pre-made library components to use in the component update.\n`
+ `You can also specify the use of icons if you see that the user's update request requires it.`,
},
{
role: `user`,
content:
`Multiple library components can be used while creating a new component update in order to help you do a better design job, faster.\n\nAVAILABLE LIBRARY COMPONENTS:\n\`\`\`\n${
components
.map((e) => {
return `${e.name} : ${e.description};`
})
.join('\n')
}\n\`\`\``,
},
{
role: `user`,
content:
`- Component description : \`${component.description}\`\n`
+ `- New component updates query : \n\`\`\`\n${prompt}\n\`\`\`\n\n`
+ `Design the Vue component updates for the user, as the creative genius you are`,
},
]
const stream = useOpenAI(event).beta.chat.completions.stream({
model: 'gpt-4-1106-preview', // 'gpt-3.5-turbo-1106',
messages: context,
tools: [
{
type: 'function',
function: {
name: `design_new_component_api`,
description: `generate the required design details to create a new component`,
parameters: zodToJsonSchema(functionSchema),
},
},
],
stream: true,
})
let completion = ''
stream.on('chunk', (part) => {
const chunk = part.choices[0]?.delta?.tool_calls?.[0]?.function?.arguments || ''
completion += chunk
event.node.res.write(chunk)
})
await stream.done()
try {
const parsed = JSON.parse(completion) as z.infer<typeof functionSchema>
if (parsed) {
event.node.req.componentDesignTask = {
description: {
user: prompt,
llm: parsed.new_component_description,
},
components: parsed.use_library_components?.map(i => ({ name: i.library_component_name, usage: i.library_component_usage_reason })),
}
}
}
catch (err) {
throw createError({
statusCode: 400,
statusMessage: 'OpenAI doesnt return expected data',
})
}
}
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/utils/multipass/designComponentNew.ts | TypeScript | import type { EventHandlerRequest, H3Event } from 'h3'
import { z } from 'zod'
import { zodToJsonSchema } from 'zod-to-json-schema'
import type { OpenAI } from 'openai'
declare module 'h3' {
interface NodeIncomingMessage {
componentDesignTask: {
description: {
user: string
llm: string
}
components: Array<{
name: string
usage: string
}>
}
}
}
export default async (event: H3Event<EventHandlerRequest>) => {
console.log('> init : design new component')
const { prompt } = await readBody(event)
const components = (await import('@/template/shadcn-vue/metadata.json')).default
const functionSchema = z.object({
new_component_description: z.string().describe(`Write a description for Vue component design task based on the user query. Stick strictly to what the user wants in their request - do not go off track`),
use_library_components: z.array(z.object({
library_component_name: z.enum(components.map(i => i.name) as [string]),
library_component_usage_reason: z.string(),
})),
})
const context: OpenAI.ChatCompletionMessageParam[] = [
{
role: `system`,
content:
`Your task is to design a new Vue component for a web app, according to the user's request.\n`
+ `If you judge it is relevant to do so, you can specify pre-made library components to use in the task.\n`
+ `You can also specify the use of icons if you see that the user's request requires it.`,
},
{
role: `user`,
content:
`Multiple library components can be used while creating a new component in order to help you do a better design job, faster.\n\nAVAILABLE LIBRARY COMPONENTS:\n\`\`\`\n${
components
.map((e) => {
return `${e.name} : ${e.description};`
})
.join('\n')
}\n\`\`\``,
},
{
role: `user`,
content:
`USER QUERY : \n\`\`\`\n${prompt}\n\`\`\`\n\n`
+ `Design the new Vue web component task for the user as the creative genius you are`,
},
]
const stream = useOpenAI(event).beta.chat.completions.stream({
model: 'gpt-4-1106-preview', // 'gpt-3.5-turbo-1106',
messages: context,
tools: [
{
type: 'function',
function: {
name: `design_new_component_api`,
description: `generate the required design details to create a new component`,
parameters: zodToJsonSchema(functionSchema),
},
},
],
stream: true,
})
let completion = ''
stream.on('chunk', (part) => {
const chunk = part.choices[0]?.delta?.tool_calls?.[0]?.function?.arguments || ''
completion += chunk
event.node.res.write(chunk)
})
await stream.done()
try {
const parsed = JSON.parse(completion) as z.infer<typeof functionSchema>
if (parsed) {
event.node.req.componentDesignTask = {
description: {
user: prompt,
llm: parsed.new_component_description,
},
components: parsed.use_library_components?.map(i => ({ name: i.library_component_name, usage: i.library_component_usage_reason })),
}
}
}
catch (err) {
throw createError({
statusCode: 400,
statusMessage: 'OpenAI doesnt return expected data',
})
}
}
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/utils/multipass/generateComponentIteration.ts | TypeScript | import type { EventHandlerRequest, H3Event } from 'h3'
import type { OpenAI } from 'openai'
declare module 'h3' {
interface NodeIncomingMessage {
componentGeneratedCode: string
}
}
export default async (event: H3Event<EventHandlerRequest>, component: DBComponent) => {
console.log('> init : generate component iteration')
const encoder = encoding()
const componentDesignContext = event.node.req.componentDesignContext
const componentDesignTask = event.node.req.componentDesignTask
const context: OpenAI.ChatCompletionMessageParam[] = [
{
role: `system`,
content:
`You are an expert at writing Vue components.\n`
+ `Your task is to write a new update for the provided Vue component for a web app, according to the provided task details.\n`
+ `The Vue component you write can make use of Tailwind classes for styling.\n`
+ `If you judge it is relevant to do so, you can use library components and icons.\n\n`
+ `If the component is using imported component, dont overwrite the style for background color and text color.\n`
+ `You will write the full Vue component code, which should include all imports.`
+ `The code should always start with <script setup lang="ts"> first, then only <template>. Do not use additional <script></script>`
+ `Your generated code will be directly written to a .vue component file and used in production. So make sure all keys are unique.`,
},
...componentDesignContext,
{
role: `user`,
content:
`- COMPONENT DESCRIPTION :\n`
+ `\`\`\`\n${component.description}\n\`\`\`\n\n`
+ `- CURRENT COMPONENT CODE :\n\n`
+ `\`\`\`vue\n${component.code}\n\`\`\``
+ `- DESIRED COMPONENT UPDATES :\n\n`
+ `\`\`\`\n${componentDesignTask.description.user}\n\`\`\`\n\n\n`
+ `- additional component suggestions :\n`
+ `\`\`\`\n${componentDesignTask.description.llm}\n\`\`\`\n\n\n`
+ `Write the full code for the new Vue component, which uses Tailwind classes if needed (add tailwind dark: classes too if you can; backgrounds in dark: classes should be black), and optionally, library components and icons, based on the provided design task.\n`
+ `The full code of the new Vue component that you write will be written directly to a .vue file inside the Vue project.\n`
+ `Answer with generated code only. DO NOT ADD ANY EXTRA TEXT DESCRIPTION OR COMMENTS BESIDES THE CODE. Your answer contains code only ! component code only !\n`
+ `Important :\n`
+ `- Make sure you import provided components libraries and icons that are provided to you if you use them !\n`
+ `- Tailwind classes should be written directly in the elements class tags. DO NOT WRITE ANY CSS OUTSIDE OF CLASSES. DO NOT USE ANY <style> IN THE CODE ! CLASSES STYLING ONLY !\n`
+ `- Do not use libraries or imports except what is provided in this task; otherwise it would crash the component because not installed. Do not import extra libraries besides what is provided above !\n`
+ `- DO NOT HAVE ANY DYNAMIC DATA OR DATA PROPS ! Components are meant to be working as is without supplying any variable to them when importing them ! Only write a component that render directly with placeholders as data, component not supplied with any dynamic data.\n`
+ `- DO NOT HAVE ANY DYNAMIC DATA OR DATA PROPS OR defineProps ! `
+ `- Only write the code for the component; Do not write extra code to import it! The code will directly be stored in an individual .vue file !\n`
+ `- Placeholder image must use src="/placeholder.svg"`
+ `Write the Vue component code as the creative genius and Vue component genius you are - with good ui formatting.\n`,
},
]
const contextPromptToken = encoder.encode(context.map(i => i.content).join('')).length
console.log(`> total context prompt tokens (estimate) : ${contextPromptToken}`)
const stream = useOpenAI(event).beta.chat.completions.stream({
model: 'gpt-4-1106-preview',
messages: context,
stream: true,
})
let completion = ''
stream.on('chunk', (part) => {
const chunk = part.choices[0].delta.content || ''
completion += chunk
event.node.res.write(chunk)
})
await stream.done()
const totalUsage = await stream.totalUsage()
console.log(`> total usage: ${totalUsage.total_tokens}`)
event.node.req.componentGeneratedCode = completion.replace('```vue', '').replaceAll('```', '')
}
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/utils/multipass/generateComponentNew.ts | TypeScript | import type { EventHandlerRequest, H3Event } from 'h3'
import type { OpenAI } from 'openai'
declare module 'h3' {
interface NodeIncomingMessage {
componentGeneratedCode: string
}
}
export default async (event: H3Event<EventHandlerRequest>) => {
console.log('> init : generate new component')
const encoder = encoding()
const componentDesignContext = event.node.req.componentDesignContext
const componentDesignTask = event.node.req.componentDesignTask
const context: OpenAI.ChatCompletionMessageParam[] = [
{
role: `system`,
content:
`You are an expert at writing Vue components.\n`
+ `Your task is to write a new Vue component for a web app, according to the provided task details.\n`
+ `The Vue component you write can make use of Tailwind classes for styling.\n`
+ `If you judge it is relevant to do so, you can use library components and icons.\n\n`
+ `If the component is using imported component, dont overwrite the style for background color and text color.\n`
+ `You will write the full Vue component code, which should include all imports.`
+ `The code should always start with <script setup lang="ts"> first, then only <template>. Do not use additional <script></script>`
+ `Your generated code will be directly written to a .vue component file and used in production. So make sure all keys are unique.`,
},
...componentDesignContext,
{
role: `user`,
content:
`- COMPONENT DESCRIPTION :\n`
+ `\`\`\`\n${componentDesignTask.description.user}\n\`\`\`\n\n`
+ `- additional component suggestions :\n`
+ `\`\`\`\n${componentDesignTask.description.llm}\n\`\`\`\n\n\n`
+ `Write the full code for the new Vue component, which uses Tailwind classes if needed (add tailwind dark: classes too if you can; backgrounds in dark: classes should be black), and optionally, library components and icons, based on the provided design task.\n`
+ `The full code of the new Vue component that you write will be written directly to a .vue file inside the Vue project.\n`
+ `Answer with generated code only. DO NOT ADD ANY EXTRA TEXT DESCRIPTION OR COMMENTS BESIDES THE CODE. Your answer contains code only ! component code only !\n`
+ `Important :\n`
+ `- Make sure you import provided components libraries and icons that are provided to you if you use them !\n`
+ `- Tailwind classes should be written directly in the elements class tags. DO NOT WRITE ANY CSS OUTSIDE OF CLASSES. DO NOT USE ANY <style> IN THE CODE ! CLASSES STYLING ONLY !\n`
+ `- Do not use libraries or imports except what is provided in this task; otherwise it would crash the component because not installed. Do not import extra libraries besides what is provided above !\n`
+ `- DO NOT HAVE ANY DYNAMIC DATA OR DATA PROPS ! Components are meant to be working as is without supplying any variable to them when importing them ! Only write a component that render directly with placeholders as data, component not supplied with any dynamic data.\n`
+ `- DO NOT HAVE ANY DYNAMIC DATA OR DATA PROPS OR defineProps ! `
+ `- Only write the code for the component; Do not write extra code to import it! The code will directly be stored in an individual .vue file !\n`
+ `- Placeholder image must use src="/placeholder.svg"`
+ `Write the Vue component code as the creative genius and Vue component genius you are - with good ui formatting.\n`,
},
]
const contextPromptToken = encoder.encode(context.map(i => i.content).join('')).length
console.log(`> total context prompt tokens (estimate) : ${contextPromptToken}`)
const stream = useOpenAI(event).beta.chat.completions.stream({
model: 'gpt-4-1106-preview',
messages: context,
stream: true,
})
let completion = ''
stream.on('chunk', (part) => {
const chunk = part.choices[0].delta.content || ''
completion += chunk
event.node.res.write(chunk)
})
await stream.done()
const totalUsage = await stream.totalUsage()
console.log(`> total usage: ${totalUsage.total_tokens}`)
event.node.req.componentGeneratedCode = completion.replace('```vue', '').replaceAll('```', '')
}
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/utils/multipass/storeComponent.ts | TypeScript | import type { EventHandlerRequest, H3Event } from 'h3'
import { eq } from 'drizzle-orm'
declare module 'h3' {
interface NodeIncomingMessage {
componentGeneratedCode: string
}
}
export default async (event: H3Event<EventHandlerRequest>, id: string, slug?: string | null) => {
console.log('> init : store component')
const componentDesignTask = event.node.req.componentDesignTask
const componentGeneratedCode = event.node.req.componentGeneratedCode
const result = await useDB().update(tables.components).set({
slug,
code: componentGeneratedCode,
description: componentDesignTask.description.user,
metadata: componentDesignTask,
completed: true,
error: null,
}).where(eq(tables.components.id, id)).returning().get()
await screenshot(result.id)
console.dir(result)
return result
}
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/utils/screenshot.ts | TypeScript | import { connect, launch } from 'puppeteer-core'
const chromeExecutables = {
linux: '/usr/bin/chromium-browser',
win32: 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
darwin: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
}
export async function screenshot(id: string) {
const IS_PRODUCTION = process.env.NODE_ENV === 'production'
const url = IS_PRODUCTION ? `${useRuntimeConfig().public.siteUrl}/s/${id}` : `http://localhost:3000/s/${id}`
const browserlessApiKey = useRuntimeConfig().browserlessApiKey
const getBrowser = () =>
IS_PRODUCTION
? connect({ browserWSEndpoint: `wss://chrome.browserless.io?token=${browserlessApiKey}&--window-size=1280,720` })
: launch({
executablePath: chromeExecutables[process.platform as keyof typeof chromeExecutables],
headless: true,
})
const browser = await getBrowser()
try {
const page = await browser.newPage()
await page.goto(url, { waitUntil: 'networkidle2' })
await page.setViewport({ width: 1280, height: 720, deviceScaleFactor: 0.5 })
const buffer = await page.screenshot({
type: 'jpeg',
})
await browser.close()
await useDB().insert(tables.images)
.values({
id,
buffer,
})
return buffer
}
catch (err) {
await browser.close()
if (err instanceof Error)
return createError(err)
}
}
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
server/utils/validateBody.ts | TypeScript | import type { z } from 'zod'
import type { EventHandlerRequest, H3Event, ValidateFunction } from 'h3'
import { readValidatedBody } from 'h3'
import type { UserSession } from '#auth-utils'
export async function validateBody<T, U>(event: H3Event<EventHandlerRequest>, validate: ValidateFunction<z.SafeParseReturnType<T, U>>) {
const result = await readValidatedBody(event, validate)
if (result.success) { return result.data }
else {
throw createError({
statusCode: 400,
statusMessage: result.error.message,
})
}
}
export async function validateUser(event: H3Event<EventHandlerRequest>) {
const session = await getUserSession(event)
// @ts-expect-error user session types
if (!session.user?.id) {
throw createError({
statusCode: 400,
statusMessage: 'No user session found',
})
}
else {
return session.user as UserSession
}
}
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
tailwind.config.js | JavaScript | const animate = require('tailwindcss-animate')
const typography = require('@tailwindcss/typography')
/** @type {import('tailwindcss').Config} */
module.exports = {
darkMode: ['class'],
theme: {
container: {
center: true,
padding: '2rem',
screens: {
'2xl': '1400px',
},
},
extend: {
colors: {
border: 'hsl(var(--border))',
input: 'hsl(var(--input))',
ring: 'hsl(var(--ring))',
background: 'hsl(var(--background))',
foreground: 'hsl(var(--foreground))',
primary: {
DEFAULT: 'hsl(var(--primary))',
foreground: 'hsl(var(--primary-foreground))',
},
secondary: {
DEFAULT: 'hsl(var(--secondary))',
foreground: 'hsl(var(--secondary-foreground))',
},
destructive: {
DEFAULT: 'hsl(var(--destructive))',
foreground: 'hsl(var(--destructive-foreground))',
},
muted: {
DEFAULT: 'hsl(var(--muted))',
foreground: 'hsl(var(--muted-foreground))',
},
accent: {
DEFAULT: 'hsl(var(--accent))',
foreground: 'hsl(var(--accent-foreground))',
},
popover: {
DEFAULT: 'hsl(var(--popover))',
foreground: 'hsl(var(--popover-foreground))',
},
card: {
DEFAULT: 'hsl(var(--card))',
foreground: 'hsl(var(--card-foreground))',
},
},
borderRadius: {
lg: 'var(--radius)',
md: 'calc(var(--radius) - 2px)',
sm: 'calc(var(--radius) - 4px)',
},
keyframes: {
'accordion-down': {
from: { height: 0 },
to: { height: 'var(--radix-accordion-content-height)' },
},
'accordion-up': {
from: { height: 'var(--radix-accordion-content-height)' },
to: { height: 0 },
},
'collapsible-down': {
from: { height: 0 },
to: { height: 'var(--radix-collapsible-content-height)' },
},
'collapsible-up': {
from: { height: 'var(--radix-collapsible-content-height)' },
to: { height: 0 },
},
},
animation: {
'accordion-down': 'accordion-down 0.2s ease-out',
'accordion-up': 'accordion-up 0.2s ease-out',
'collapsible-down': 'collapsible-down 0.2s ease-in-out',
'collapsible-up': 'collapsible-up 0.2s ease-in-out',
},
},
},
plugins: [animate, typography],
}
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
template/downloadRepo.ts | TypeScript | import { downloadTemplate } from 'giget'
downloadTemplate('gh:radix-vue/shadcn-vue/apps/www/src#dev', {
dir: 'shadcn-vue/.repo',
force: true,
forceClean: true,
})
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
template/shadcn-vue/parseMeta.ts | TypeScript | import * as fs from 'node:fs'
import { kebabCase } from 'scule'
import matter from 'gray-matter'
const componentMds = fs.readdirSync('template/shadcn-vue/.repo/content/docs/components')
const exampleMds = fs.readdirSync('template/shadcn-vue/.repo/lib/registry/default/example').filter(file => file.endsWith('.vue'))
const components = componentMds
.map((file) => {
const componentName = file.split('.')[0]
const { content, data: frontmatter } = matter(fs.readFileSync(`template/shadcn-vue/.repo/content/docs/components/${file}`, 'utf-8'))
const usage = content.split(`## Usage`)[1]?.split(`##`)[0]?.trim().replace('```vue\n', '').replace('```', '')
const examples = exampleMds
.filter(file => kebabCase(file).startsWith(componentName))
.map((file) => {
return {
source: file,
code: fs
.readFileSync(`template/shadcn-vue/.repo/lib/registry/default/example/${file}`, 'utf-8')
.trim()
.replaceAll('@/lib/registry/default/ui', '@/components/ui'),
}
})
return {
name: componentName,
description: frontmatter.description ?? '',
usage,
examples,
}
})
// Only show component with usage/examples
.filter(i => !!i.usage && !!i.examples.length)
fs.writeFileSync(
'template/shadcn-vue/metadata.json',
JSON.stringify(components),
)
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
utils/index.ts | TypeScript | import { type ClassValue, clsx } from 'clsx'
import { twMerge } from 'tailwind-merge'
export type { DBComponent } from '@/server/utils/db'
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
utils/types.ts | TypeScript | export interface IframeData {
code: string
error?: string | null | undefined
}
| zernonia/vue0 | 823 | Vue version open source alternative for v0.dev | Vue | zernonia | zernonia | Troop Travel |
demo/ansi.c | C | /* This file makes sure the library can be used by C89 code */
#include "../src/meshoptimizer.h"
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
demo/clusterlod.h | C/C++ Header | /**
* clusterlod - a small "library"/example built on top of meshoptimizer to generate cluster LOD hierarchies
* This is intended to either be used as is, or as a reference for implementing similar functionality in your engine.
*
* To use this code, you need to have one source file which includes meshoptimizer.h and defines CLUSTERLOD_IMPLEMENTATION
* before including this file. Other source files in your project can just include this file and use the provided functions.
*
* Copyright (C) 2016-2026, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
* This code is distributed under the MIT License. See notice at the end of this file.
*/
#pragma once
#include <stddef.h>
struct clodConfig
{
// configuration of each cluster; maps to meshopt_buildMeshlets* parameters
size_t max_vertices;
size_t min_triangles;
size_t max_triangles;
// partitioning setup; maps to meshopt_partitionClusters parameters (plus optional partition sorting)
// note: partition size is the target size, not maximum; actual partitions may be up to 1/3 larger (e.g. target 24 results in maximum 32)
bool partition_spatial;
bool partition_sort;
size_t partition_size;
// clusterization setup; maps to meshopt_buildMeshletsSpatial / meshopt_buildMeshletsFlex
bool cluster_spatial;
float cluster_fill_weight;
float cluster_split_factor;
// every level aims to reduce the number of triangles by ratio, and considers clusters that don't reach the threshold stuck
float simplify_ratio;
float simplify_threshold;
// to compute the error of simplified clusters, we use the formula that combines previous accumulated error as follows:
// max(previous_error * simplify_error_merge_previous, current_error) + current_error * simplify_error_merge_additive
float simplify_error_merge_previous;
float simplify_error_merge_additive;
// amplify the error of clusters that go through sloppy simplification to account for appearance degradation
float simplify_error_factor_sloppy;
// experimental: limit error by edge length, aiming to remove subpixel triangles even if the attribute error is high
float simplify_error_edge_limit;
// use permissive simplification instead of regular simplification (make sure to use attribute_protect_mask if this is set!)
bool simplify_permissive;
// use permissive or sloppy simplification but only if regular simplification gets stuck
bool simplify_fallback_permissive;
bool simplify_fallback_sloppy;
// use regularization during simplification to make triangle density more uniform, at some cost to overall triangle count; recommended for deformable objects
bool simplify_regularize;
// should clodCluster::bounds be computed based on the geometry of each cluster
bool optimize_bounds;
// should clodCluster::indices be optimized for locality; helps with rasterization performance and ray tracing performance in fast-build modes
bool optimize_clusters;
};
struct clodMesh
{
// input triangle indices
const unsigned int* indices;
size_t index_count;
// total vertex count
size_t vertex_count;
// input vertex positions; must be 3 floats per vertex
const float* vertex_positions;
size_t vertex_positions_stride;
// input vertex attributes; used for attribute-aware simplification and permissive simplification
const float* vertex_attributes;
size_t vertex_attributes_stride;
// input vertex locks; allows to preserve additional seams (when not using attribute_protect_mask) or lock vertices via meshopt_SimplifyVertex_* flags
const unsigned char* vertex_lock;
// attribute weights for attribute-aware simplification; maps to meshopt_simplifyWithAttributes parameters
const float* attribute_weights;
size_t attribute_count;
// attribute mask to flag attribute discontinuities for permissive simplification; mask (1<<K) corresponds to attribute K
unsigned int attribute_protect_mask;
};
// To compute approximate (perspective) projection error of a cluster in screen space (0..1; multiply by screen height to get pixels):
// - camera_proj is projection[1][1], or cot(fovy/2); camera_znear is *positive* near plane distance
// - for simplicity, we ignore perspective distortion and use rotationally invariant projection size estimation
// - return: bounds.error / max(distance(bounds.center, camera_position) - bounds.radius, camera_znear) * (camera_proj * 0.5f)
struct clodBounds
{
// sphere bounds, in mesh coordinate space
float center[3];
float radius;
// combined simplification error, in mesh coordinate space
float error;
};
struct clodCluster
{
// index of more refined group (with more triangles) that produced this cluster during simplification, or -1 for original geometry
int refined;
// cluster bounds; should only be used for culling, as bounds.error is not monotonic across DAG
clodBounds bounds;
// cluster indices; refer to the original mesh vertex buffer
const unsigned int* indices;
size_t index_count;
// cluster vertex count; indices[] has vertex_count unique entries
size_t vertex_count;
};
struct clodGroup
{
// DAG level the group was generated at
int depth;
// simplified group bounds (reflects error for clusters with clodCluster::refined == group id; error is FLT_MAX for terminal groups)
// cluster should be rendered if:
// 1. clodGroup::simplified for the group it's in is over error threshold
// 2. cluster.refined is -1 *or* clodGroup::simplified for groups[cluster.refined].simplified is at or under error threshold
clodBounds simplified;
};
// gets called for each group in sequence
// returned value gets saved for clusters emitted from this group (clodCluster::refined)
typedef int (*clodOutput)(void* output_context, clodGroup group, const clodCluster* clusters, size_t cluster_count);
#ifdef __cplusplus
extern "C"
{
#endif
// default configuration optimized for rasterization / raytracing
clodConfig clodDefaultConfig(size_t max_triangles);
clodConfig clodDefaultConfigRT(size_t max_triangles);
// build cluster LOD hierarchy, calling output callbacks as new clusters and groups are generated
// returns the total number of clusters produced
size_t clodBuild(clodConfig config, clodMesh mesh, void* output_context, clodOutput output_callback);
// extract meshlet-local indices from cluster indices produced by clodBuild
// fills triangles[] and vertices[] such that vertices[triangles[i]] == indices[i]
// returns number of unique vertices (which will be equal to clodCluster::vertex_count)
size_t clodLocalIndices(unsigned int* vertices, unsigned char* triangles, const unsigned int* indices, size_t index_count);
#ifdef __cplusplus
} // extern "C"
template <typename Output>
size_t clodBuild(clodConfig config, clodMesh mesh, Output output)
{
struct Call
{
static int output(void* output_context, clodGroup group, const clodCluster* clusters, size_t cluster_count)
{
return (*static_cast<Output*>(output_context))(group, clusters, cluster_count);
}
};
return clodBuild(config, mesh, &output, &Call::output);
}
#endif
#ifdef CLUSTERLOD_IMPLEMENTATION
// For reference, see the original Nanite paper:
// Brian Karis. Nanite: A Deep Dive. 2021
#include <float.h>
#include <math.h>
#include <string.h>
#include <algorithm>
#include <vector>
namespace clod
{
struct Cluster
{
size_t vertices;
std::vector<unsigned int> indices;
int group;
int refined;
clodBounds bounds;
};
static clodBounds boundsCompute(const clodMesh& mesh, const std::vector<unsigned int>& indices, float error)
{
meshopt_Bounds bounds = meshopt_computeClusterBounds(&indices[0], indices.size(), mesh.vertex_positions, mesh.vertex_count, mesh.vertex_positions_stride);
clodBounds result;
result.center[0] = bounds.center[0];
result.center[1] = bounds.center[1];
result.center[2] = bounds.center[2];
result.radius = bounds.radius;
result.error = error;
return result;
}
static clodBounds boundsMerge(const std::vector<Cluster>& clusters, const std::vector<int>& group)
{
std::vector<clodBounds> bounds(group.size());
for (size_t j = 0; j < group.size(); ++j)
bounds[j] = clusters[group[j]].bounds;
meshopt_Bounds merged = meshopt_computeSphereBounds(&bounds[0].center[0], bounds.size(), sizeof(clodBounds), &bounds[0].radius, sizeof(clodBounds));
clodBounds result = {};
result.center[0] = merged.center[0];
result.center[1] = merged.center[1];
result.center[2] = merged.center[2];
result.radius = merged.radius;
// merged bounds error must be conservative wrt cluster errors
result.error = 0.f;
for (size_t j = 0; j < group.size(); ++j)
result.error = std::max(result.error, clusters[group[j]].bounds.error);
return result;
}
static std::vector<Cluster> clusterize(const clodConfig& config, const clodMesh& mesh, const unsigned int* indices, size_t index_count)
{
size_t max_meshlets = meshopt_buildMeshletsBound(index_count, config.max_vertices, config.min_triangles);
std::vector<meshopt_Meshlet> meshlets(max_meshlets);
std::vector<unsigned int> meshlet_vertices(index_count);
#if MESHOPTIMIZER_VERSION < 1000
std::vector<unsigned char> meshlet_triangles(index_count + max_meshlets * 3); // account for 4b alignment
#else
std::vector<unsigned char> meshlet_triangles(index_count);
#endif
if (config.cluster_spatial)
meshlets.resize(meshopt_buildMeshletsSpatial(meshlets.data(), meshlet_vertices.data(), meshlet_triangles.data(), indices, index_count,
mesh.vertex_positions, mesh.vertex_count, mesh.vertex_positions_stride,
config.max_vertices, config.min_triangles, config.max_triangles, config.cluster_fill_weight));
else
meshlets.resize(meshopt_buildMeshletsFlex(meshlets.data(), meshlet_vertices.data(), meshlet_triangles.data(), indices, index_count,
mesh.vertex_positions, mesh.vertex_count, mesh.vertex_positions_stride,
config.max_vertices, config.min_triangles, config.max_triangles, 0.f, config.cluster_split_factor));
std::vector<Cluster> clusters(meshlets.size());
for (size_t i = 0; i < meshlets.size(); ++i)
{
const meshopt_Meshlet& meshlet = meshlets[i];
if (config.optimize_clusters)
meshopt_optimizeMeshlet(&meshlet_vertices[meshlet.vertex_offset], &meshlet_triangles[meshlet.triangle_offset], meshlet.triangle_count, meshlet.vertex_count);
clusters[i].vertices = meshlet.vertex_count;
// note: we discard meshlet-local indices; they can be recovered by the caller using clodLocalIndices
clusters[i].indices.resize(meshlet.triangle_count * 3);
for (size_t j = 0; j < meshlet.triangle_count * 3; ++j)
clusters[i].indices[j] = meshlet_vertices[meshlet.vertex_offset + meshlet_triangles[meshlet.triangle_offset + j]];
clusters[i].group = -1;
clusters[i].refined = -1;
}
return clusters;
}
static std::vector<std::vector<int> > partition(const clodConfig& config, const clodMesh& mesh, const std::vector<Cluster>& clusters, const std::vector<int>& pending, const std::vector<unsigned int>& remap)
{
if (pending.size() <= config.partition_size)
return {pending};
std::vector<unsigned int> cluster_indices;
std::vector<unsigned int> cluster_counts(pending.size());
// copy cluster index data into a flat array for partitioning
size_t total_index_count = 0;
for (size_t i = 0; i < pending.size(); ++i)
total_index_count += clusters[pending[i]].indices.size();
cluster_indices.reserve(total_index_count);
for (size_t i = 0; i < pending.size(); ++i)
{
const Cluster& cluster = clusters[pending[i]];
cluster_counts[i] = unsigned(cluster.indices.size());
for (size_t j = 0; j < cluster.indices.size(); ++j)
cluster_indices.push_back(remap[cluster.indices[j]]);
}
// partition clusters into groups; the output is a partition id per cluster
std::vector<unsigned int> cluster_part(pending.size());
size_t partition_count = meshopt_partitionClusters(&cluster_part[0], &cluster_indices[0], cluster_indices.size(), &cluster_counts[0], cluster_counts.size(),
config.partition_spatial ? mesh.vertex_positions : NULL, remap.size(), mesh.vertex_positions_stride, config.partition_size);
// preallocate partitions for worst case
std::vector<std::vector<int> > partitions(partition_count);
for (size_t i = 0; i < partition_count; ++i)
partitions[i].reserve(config.partition_size + config.partition_size / 3);
std::vector<unsigned int> partition_remap;
if (config.partition_sort)
{
// compute partition points for sorting; any representative point will do, we use last cluster center for simplicity
std::vector<float> partition_point(partition_count * 3);
for (size_t i = 0; i < pending.size(); ++i)
memcpy(&partition_point[cluster_part[i] * 3], clusters[pending[i]].bounds.center, sizeof(float) * 3);
// sort partitions spatially; the output is a remap table from old index (partition id) to new index
partition_remap.resize(partition_count);
meshopt_spatialSortRemap(partition_remap.data(), partition_point.data(), partition_count, sizeof(float) * 3);
}
// distribute clusters into partitions, applying spatial order if requested
for (size_t i = 0; i < pending.size(); ++i)
partitions[partition_remap.empty() ? cluster_part[i] : partition_remap[cluster_part[i]]].push_back(pending[i]);
return partitions;
}
static void lockBoundary(std::vector<unsigned char>& locks, const std::vector<std::vector<int> >& groups, const std::vector<Cluster>& clusters, const std::vector<unsigned int>& remap, const unsigned char* vertex_lock)
{
// for each remapped vertex, use bit 7 as temporary storage to indicate that the vertex has been used by a different group previously
for (size_t i = 0; i < locks.size(); ++i)
locks[i] &= ~((1 << 0) | (1 << 7));
for (size_t i = 0; i < groups.size(); ++i)
{
// mark all remapped vertices as locked if seen by a prior group
for (size_t j = 0; j < groups[i].size(); ++j)
{
const Cluster& cluster = clusters[groups[i][j]];
for (size_t k = 0; k < cluster.indices.size(); ++k)
{
unsigned int v = cluster.indices[k];
unsigned int r = remap[v];
locks[r] |= locks[r] >> 7;
}
}
// mark all remapped vertices as seen
for (size_t j = 0; j < groups[i].size(); ++j)
{
const Cluster& cluster = clusters[groups[i][j]];
for (size_t k = 0; k < cluster.indices.size(); ++k)
{
unsigned int v = cluster.indices[k];
unsigned int r = remap[v];
locks[r] |= 1 << 7;
}
}
}
for (size_t i = 0; i < locks.size(); ++i)
{
unsigned int r = remap[i];
// consistently lock all vertices with the same position; keep protect bit if set
locks[i] = (locks[r] & 1) | (locks[i] & meshopt_SimplifyVertex_Protect);
if (vertex_lock)
locks[i] |= vertex_lock[i];
}
}
struct SloppyVertex
{
float x, y, z;
unsigned int id;
};
static void simplifyFallback(std::vector<unsigned int>& lod, const clodMesh& mesh, const std::vector<unsigned int>& indices, const std::vector<unsigned char>& locks, size_t target_count, float* error)
{
std::vector<SloppyVertex> subset(indices.size());
std::vector<unsigned char> subset_locks(indices.size());
lod.resize(indices.size());
size_t positions_stride = mesh.vertex_positions_stride / sizeof(float);
// deindex the mesh subset to avoid calling simplifySloppy on the entire vertex buffer (which is prohibitively expensive without sparsity)
for (size_t i = 0; i < indices.size(); ++i)
{
unsigned int v = indices[i];
assert(v < mesh.vertex_count);
subset[i].x = mesh.vertex_positions[v * positions_stride + 0];
subset[i].y = mesh.vertex_positions[v * positions_stride + 1];
subset[i].z = mesh.vertex_positions[v * positions_stride + 2];
subset[i].id = v;
subset_locks[i] = locks[v];
lod[i] = unsigned(i);
}
lod.resize(meshopt_simplifySloppy(&lod[0], &lod[0], lod.size(), &subset[0].x, subset.size(), sizeof(SloppyVertex), subset_locks.data(), target_count, FLT_MAX, error));
// convert error to absolute
*error *= meshopt_simplifyScale(&subset[0].x, subset.size(), sizeof(SloppyVertex));
// restore original vertex indices
for (size_t i = 0; i < lod.size(); ++i)
lod[i] = subset[lod[i]].id;
}
static std::vector<unsigned int> simplify(const clodConfig& config, const clodMesh& mesh, const std::vector<unsigned int>& indices, const std::vector<unsigned char>& locks, size_t target_count, float* error)
{
if (target_count > indices.size())
return indices;
std::vector<unsigned int> lod(indices.size());
unsigned int options = meshopt_SimplifySparse | meshopt_SimplifyErrorAbsolute | (config.simplify_permissive ? meshopt_SimplifyPermissive : 0) | (config.simplify_regularize ? meshopt_SimplifyRegularize : 0);
lod.resize(meshopt_simplifyWithAttributes(&lod[0], &indices[0], indices.size(),
mesh.vertex_positions, mesh.vertex_count, mesh.vertex_positions_stride,
mesh.vertex_attributes, mesh.vertex_attributes_stride, mesh.attribute_weights, mesh.attribute_count,
&locks[0], target_count, FLT_MAX, options, error));
if (lod.size() > target_count && config.simplify_fallback_permissive && !config.simplify_permissive)
lod.resize(meshopt_simplifyWithAttributes(&lod[0], &indices[0], indices.size(),
mesh.vertex_positions, mesh.vertex_count, mesh.vertex_positions_stride,
mesh.vertex_attributes, mesh.vertex_attributes_stride, mesh.attribute_weights, mesh.attribute_count,
&locks[0], target_count, FLT_MAX, options | meshopt_SimplifyPermissive, error));
// while it's possible to call simplifySloppy directly, it doesn't support sparsity or absolute error, so we need to do some extra work
if (lod.size() > target_count && config.simplify_fallback_sloppy)
{
simplifyFallback(lod, mesh, indices, locks, target_count, error);
*error *= config.simplify_error_factor_sloppy; // scale error up to account for appearance degradation
}
// optionally limit error by edge length, aiming to remove subpixel triangles even if the attribute error is high
if (config.simplify_error_edge_limit > 0)
{
float max_edge_sq = 0;
for (size_t i = 0; i < indices.size(); i += 3)
{
unsigned int a = indices[i + 0], b = indices[i + 1], c = indices[i + 2];
assert(a < mesh.vertex_count && b < mesh.vertex_count && c < mesh.vertex_count);
const float* va = &mesh.vertex_positions[a * (mesh.vertex_positions_stride / sizeof(float))];
const float* vb = &mesh.vertex_positions[b * (mesh.vertex_positions_stride / sizeof(float))];
const float* vc = &mesh.vertex_positions[c * (mesh.vertex_positions_stride / sizeof(float))];
// compute squared edge lengths
float eab = (va[0] - vb[0]) * (va[0] - vb[0]) + (va[1] - vb[1]) * (va[1] - vb[1]) + (va[2] - vb[2]) * (va[2] - vb[2]);
float eac = (va[0] - vc[0]) * (va[0] - vc[0]) + (va[1] - vc[1]) * (va[1] - vc[1]) + (va[2] - vc[2]) * (va[2] - vc[2]);
float ebc = (vb[0] - vc[0]) * (vb[0] - vc[0]) + (vb[1] - vc[1]) * (vb[1] - vc[1]) + (vb[2] - vc[2]) * (vb[2] - vc[2]);
float emax = std::max(std::max(eab, eac), ebc);
float emin = std::min(std::min(eab, eac), ebc);
// we prefer using min edge length to reduce the number of triangles <1px thick, but need some stopgap for thin and long triangles like wires
max_edge_sq = std::max(max_edge_sq, std::max(emin, emax / 4));
}
// adjust the error to limit it for dense clusters based on edge lengths
*error = std::min(*error, sqrtf(max_edge_sq) * config.simplify_error_edge_limit);
}
return lod;
}
static int outputGroup(const clodConfig& config, const clodMesh& mesh, const std::vector<Cluster>& clusters, const std::vector<int>& group, const clodBounds& simplified, int depth, void* output_context, clodOutput output_callback)
{
std::vector<clodCluster> group_clusters(group.size());
for (size_t i = 0; i < group.size(); ++i)
{
const Cluster& cluster = clusters[group[i]];
clodCluster& result = group_clusters[i];
result.refined = cluster.refined;
result.bounds = (config.optimize_bounds && cluster.refined != -1) ? boundsCompute(mesh, cluster.indices, cluster.bounds.error) : cluster.bounds;
result.indices = cluster.indices.data();
result.index_count = cluster.indices.size();
result.vertex_count = cluster.vertices;
}
return output_callback ? output_callback(output_context, {depth, simplified}, group_clusters.data(), group_clusters.size()) : -1;
}
} // namespace clod
clodConfig clodDefaultConfig(size_t max_triangles)
{
assert(max_triangles >= 4 && max_triangles <= 256);
clodConfig config = {};
config.max_vertices = max_triangles;
config.min_triangles = max_triangles / 3;
config.max_triangles = max_triangles;
#if MESHOPTIMIZER_VERSION < 1000
config.min_triangles &= ~3; // account for 4b alignment
#endif
config.partition_spatial = true;
config.partition_size = 16;
config.cluster_spatial = false;
config.cluster_split_factor = 2.0f;
config.optimize_clusters = true;
config.simplify_ratio = 0.5f;
config.simplify_threshold = 0.85f;
config.simplify_error_merge_previous = 1.0f;
config.simplify_error_factor_sloppy = 2.0f;
config.simplify_permissive = true;
config.simplify_fallback_permissive = false; // note: by default we run in permissive mode, but it's also possible to disable that and use it only as a fallback
config.simplify_fallback_sloppy = true;
return config;
}
clodConfig clodDefaultConfigRT(size_t max_triangles)
{
clodConfig config = clodDefaultConfig(max_triangles);
// for ray tracing, we may want smaller clusters when that improves BVH quality further; for maximum ray tracing performance this could be reduced even further
config.min_triangles = max_triangles / 4;
// by default, we use larger max_vertices for RT; the vertex count is not important for ray tracing performance, and this helps improve cluster utilization
config.max_vertices = std::min(size_t(256), max_triangles * 2);
config.cluster_spatial = true;
config.cluster_fill_weight = 0.5f;
return config;
}
size_t clodBuild(clodConfig config, clodMesh mesh, void* output_context, clodOutput output_callback)
{
using namespace clod;
assert(mesh.vertex_attributes_stride % sizeof(float) == 0);
assert(mesh.attribute_count * sizeof(float) <= mesh.vertex_attributes_stride);
assert(mesh.attribute_protect_mask < (1u << (mesh.vertex_attributes_stride / sizeof(float))));
std::vector<unsigned char> locks(mesh.vertex_count);
// for cluster connectivity, we need a position-only remap that maps vertices with the same position to the same index
std::vector<unsigned int> remap(mesh.vertex_count);
meshopt_generatePositionRemap(&remap[0], mesh.vertex_positions, mesh.vertex_count, mesh.vertex_positions_stride);
// set up protect bits on UV seams for permissive mode
if (mesh.attribute_protect_mask)
{
size_t max_attributes = mesh.vertex_attributes_stride / sizeof(float);
for (size_t i = 0; i < mesh.vertex_count; ++i)
{
unsigned int r = remap[i]; // canonical vertex with the same position
for (size_t j = 0; j < max_attributes; ++j)
if (r != i && (mesh.attribute_protect_mask & (1u << j)) && mesh.vertex_attributes[i * max_attributes + j] != mesh.vertex_attributes[r * max_attributes + j])
locks[i] |= meshopt_SimplifyVertex_Protect;
}
}
// initial clusterization splits the original mesh
std::vector<Cluster> clusters = clusterize(config, mesh, mesh.indices, mesh.index_count);
// compute initial precise bounds; subsequent bounds will be using group-merged bounds
for (Cluster& cluster : clusters)
cluster.bounds = boundsCompute(mesh, cluster.indices, 0.f);
std::vector<int> pending(clusters.size());
for (size_t i = 0; i < clusters.size(); ++i)
pending[i] = int(i);
int depth = 0;
// merge and simplify clusters until we can't merge anymore
while (pending.size() > 1)
{
std::vector<std::vector<int> > groups = partition(config, mesh, clusters, pending, remap);
pending.clear();
// mark boundaries between groups with a lock bit to avoid gaps in simplified result
lockBoundary(locks, groups, clusters, remap, mesh.vertex_lock);
// every group needs to be simplified now
for (size_t i = 0; i < groups.size(); ++i)
{
std::vector<unsigned int> merged;
merged.reserve(groups[i].size() * config.max_triangles * 3);
for (size_t j = 0; j < groups[i].size(); ++j)
merged.insert(merged.end(), clusters[groups[i][j]].indices.begin(), clusters[groups[i][j]].indices.end());
size_t target_size = size_t((merged.size() / 3) * config.simplify_ratio) * 3;
// enforce bounds and error monotonicity
// note: it is incorrect to use the precise bounds of the merged or simplified mesh, because this may violate monotonicity
clodBounds bounds = boundsMerge(clusters, groups[i]);
float error = 0.f;
std::vector<unsigned int> simplified = simplify(config, mesh, merged, locks, target_size, &error);
if (simplified.size() > merged.size() * config.simplify_threshold)
{
bounds.error = FLT_MAX; // terminal group, won't simplify further
outputGroup(config, mesh, clusters, groups[i], bounds, depth, output_context, output_callback);
continue; // simplification is stuck; abandon the merge
}
// enforce error monotonicity (with an optional hierarchical factor to separate transitions more)
bounds.error = std::max(bounds.error * config.simplify_error_merge_previous, error) + error * config.simplify_error_merge_additive;
// output the new group with all clusters; the resulting id will be recorded in new clusters as clodCluster::refined
int refined = outputGroup(config, mesh, clusters, groups[i], bounds, depth, output_context, output_callback);
// discard clusters from the group - they won't be used anymore
for (size_t j = 0; j < groups[i].size(); ++j)
clusters[groups[i][j]].indices = std::vector<unsigned int>();
std::vector<Cluster> split = clusterize(config, mesh, simplified.data(), simplified.size());
for (Cluster& cluster : split)
{
cluster.refined = refined;
// update cluster group bounds to the group-merged bounds; this ensures that we compute the group bounds for whatever group this cluster will be part of conservatively
cluster.bounds = bounds;
// enqueue new cluster for further processing
clusters.push_back(std::move(cluster));
pending.push_back(int(clusters.size()) - 1);
}
}
depth++;
}
if (pending.size())
{
assert(pending.size() == 1);
const Cluster& cluster = clusters[pending[0]];
clodBounds bounds = cluster.bounds;
bounds.error = FLT_MAX; // terminal group, won't simplify further
outputGroup(config, mesh, clusters, pending, bounds, depth, output_context, output_callback);
}
return clusters.size();
}
size_t clodLocalIndices(unsigned int* vertices, unsigned char* triangles, const unsigned int* indices, size_t index_count)
{
size_t unique = 0;
// direct mapped cache for fast lookups based on low index bits; inspired by vk_lod_clusters from NVIDIA
short cache[1024];
memset(cache, -1, sizeof(cache));
for (size_t i = 0; i < index_count; ++i)
{
unsigned int v = indices[i];
unsigned int key = v & (sizeof(cache) / sizeof(cache[0]) - 1);
short c = cache[key];
// fast path: vertex has been seen before
if (c >= 0 && vertices[c] == v)
{
triangles[i] = (unsigned char)c;
continue;
}
// fast path: vertex has never been seen before
if (c < 0)
{
cache[key] = short(unique);
triangles[i] = (unsigned char)unique;
vertices[unique++] = v;
continue;
}
// slow path: hash collision with a different vertex, so we need to look through all vertices
int pos = -1;
for (size_t j = 0; j < unique; ++j)
if (vertices[j] == v)
{
pos = int(j);
break;
}
if (pos < 0)
{
pos = int(unique);
vertices[unique++] = v;
}
cache[key] = short(pos);
triangles[i] = (unsigned char)pos;
}
assert(unique <= 256);
return unique;
}
#endif
/**
* Copyright (c) 2016-2026 Arseny Kapoulkine
*
* 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.
*/
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
demo/index.html | HTML | <!doctype html>
<html lang="en">
<head>
<title>meshoptimizer - demo</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0" />
<style>
body {
font-family: Monospace;
background-color: #000;
color: #fff;
margin: 0px;
overflow: hidden;
}
#info {
color: #fff;
position: absolute;
top: 10px;
width: 100%;
text-align: center;
z-index: 100;
display: block;
}
#info a,
.button {
color: #f00;
font-weight: bold;
text-decoration: underline;
cursor: pointer;
}
</style>
<script async src="https://cdn.jsdelivr.net/npm/es-module-shims@2.0.10/dist/es-module-shims.min.js"></script>
<script type="importmap">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.174.0/build/three.module.js",
"three-examples/": "https://cdn.jsdelivr.net/npm/three@0.174.0/examples/jsm/"
}
}
</script>
</head>
<body>
<div id="info">
<a href="https://github.com/zeux/meshoptimizer" target="_blank" rel="noopener">meshoptimizer</a>
</div>
<script type="module">
import * as THREE from 'three';
import { GLTFLoader } from 'three-examples/loaders/GLTFLoader.js';
import { MeshoptDecoder } from '../js/meshopt_decoder.mjs';
var container;
var camera, scene, renderer, mixer, clock;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
init();
animate();
function init() {
container = document.createElement('div');
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.01, 100);
camera.position.y = 1.0;
camera.position.z = 3.0;
scene = new THREE.Scene();
scene.background = new THREE.Color(0x300a24);
var ambientLight = new THREE.AmbientLight(0xcccccc, 1);
scene.add(ambientLight);
var pointLight = new THREE.PointLight(0xffffff, 4);
pointLight.position.set(3, 3, 0);
pointLight.decay = 0.5;
camera.add(pointLight);
scene.add(camera);
var onProgress = function (xhr) {};
var onError = function (e) {
console.log(e);
};
var loader = new GLTFLoader();
loader.setMeshoptDecoder(MeshoptDecoder);
loader.load(
'pirate.glb',
function (gltf) {
var bbox = new THREE.Box3().setFromObject(gltf.scene);
var scale = 2 / (bbox.max.y - bbox.min.y);
gltf.scene.scale.set(scale, scale, scale);
gltf.scene.position.set(0, 0, 0);
scene.add(gltf.scene);
mixer = new THREE.AnimationMixer(gltf.scene);
if (gltf.animations.length) {
mixer.clipAction(gltf.animations[gltf.animations.length - 1]).play();
}
},
onProgress,
onError
);
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
window.addEventListener('resize', onWindowResize, false);
clock = new THREE.Clock();
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
if (mixer) {
mixer.update(clock.getDelta());
}
requestAnimationFrame(animate);
render();
}
function render() {
renderer.render(scene, camera);
}
</script>
</body>
</html>
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
demo/main.cpp | C++ | #include "../src/meshoptimizer.h"
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <vector>
#include "../extern/fast_obj.h"
#define SDEFL_IMPLEMENTATION
#include "../extern/sdefl.h"
// This file uses assert() to verify algorithm correctness
#undef NDEBUG
#include <assert.h>
#if defined(__linux__)
double timestamp()
{
timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return double(ts.tv_sec) + 1e-9 * double(ts.tv_nsec);
}
#elif defined(_WIN32)
struct LARGE_INTEGER
{
__int64 QuadPart;
};
extern "C" __declspec(dllimport) int __stdcall QueryPerformanceCounter(LARGE_INTEGER* lpPerformanceCount);
extern "C" __declspec(dllimport) int __stdcall QueryPerformanceFrequency(LARGE_INTEGER* lpFrequency);
double timestamp()
{
LARGE_INTEGER freq, counter;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&counter);
return double(counter.QuadPart) / double(freq.QuadPart);
}
#else
double timestamp()
{
return double(clock()) / double(CLOCKS_PER_SEC);
}
#endif
struct Vertex
{
float px, py, pz;
float nx, ny, nz;
float tx, ty;
};
struct Mesh
{
std::vector<Vertex> vertices;
std::vector<unsigned int> indices;
};
union Triangle
{
Vertex v[3];
char data[sizeof(Vertex) * 3];
};
Mesh parseObj(const char* path, double& reindex)
{
fastObjMesh* obj = fast_obj_read(path);
if (!obj)
{
printf("Error loading %s: file not found\n", path);
return Mesh();
}
size_t total_indices = 0;
for (unsigned int i = 0; i < obj->face_count; ++i)
if (obj->face_vertices[i] > 2)
total_indices += 3 * (obj->face_vertices[i] - 2);
std::vector<Vertex> vertices(total_indices);
size_t vertex_offset = 0;
size_t index_offset = 0;
for (unsigned int i = 0; i < obj->face_count; ++i)
{
if (obj->face_vertices[i] <= 2)
continue;
for (unsigned int j = 0; j < obj->face_vertices[i]; ++j)
{
fastObjIndex gi = obj->indices[index_offset + j];
Vertex v =
{
obj->positions[gi.p * 3 + 0],
obj->positions[gi.p * 3 + 1],
obj->positions[gi.p * 3 + 2],
obj->normals[gi.n * 3 + 0],
obj->normals[gi.n * 3 + 1],
obj->normals[gi.n * 3 + 2],
obj->texcoords[gi.t * 2 + 0],
obj->texcoords[gi.t * 2 + 1],
};
// triangulate polygon on the fly; offset-3 is always the first polygon vertex
if (j >= 3)
{
vertices[vertex_offset + 0] = vertices[vertex_offset - 3];
vertices[vertex_offset + 1] = vertices[vertex_offset - 1];
vertex_offset += 2;
}
vertices[vertex_offset] = v;
vertex_offset++;
}
index_offset += obj->face_vertices[i];
}
fast_obj_destroy(obj);
reindex = timestamp();
Mesh result;
// empty mesh
if (total_indices == 0)
return result;
std::vector<unsigned int> remap(total_indices);
size_t total_vertices = meshopt_generateVertexRemap(&remap[0], NULL, total_indices, &vertices[0], total_indices, sizeof(Vertex));
result.indices.resize(total_indices);
meshopt_remapIndexBuffer(&result.indices[0], NULL, total_indices, &remap[0]);
result.vertices.resize(total_vertices);
meshopt_remapVertexBuffer(&result.vertices[0], &vertices[0], total_indices, sizeof(Vertex), &remap[0]);
return result;
}
void dumpObj(const std::vector<Vertex>& vertices, const std::vector<unsigned int>& indices, bool recomputeNormals = false)
{
std::vector<float> normals;
if (recomputeNormals)
{
normals.resize(vertices.size() * 3);
for (size_t i = 0; i < indices.size(); i += 3)
{
unsigned int a = indices[i], b = indices[i + 1], c = indices[i + 2];
const Vertex& va = vertices[a];
const Vertex& vb = vertices[b];
const Vertex& vc = vertices[c];
float nx = (vb.py - va.py) * (vc.pz - va.pz) - (vb.pz - va.pz) * (vc.py - va.py);
float ny = (vb.pz - va.pz) * (vc.px - va.px) - (vb.px - va.px) * (vc.pz - va.pz);
float nz = (vb.px - va.px) * (vc.py - va.py) - (vb.py - va.py) * (vc.px - va.px);
for (int k = 0; k < 3; ++k)
{
unsigned int index = indices[i + k];
normals[index * 3 + 0] += nx;
normals[index * 3 + 1] += ny;
normals[index * 3 + 2] += nz;
}
}
}
for (size_t i = 0; i < vertices.size(); ++i)
{
const Vertex& v = vertices[i];
float nx = v.nx, ny = v.ny, nz = v.nz;
if (recomputeNormals)
{
nx = normals[i * 3 + 0];
ny = normals[i * 3 + 1];
nz = normals[i * 3 + 2];
float l = sqrtf(nx * nx + ny * ny + nz * nz);
float s = l == 0.f ? 0.f : 1.f / l;
nx *= s;
ny *= s;
nz *= s;
}
fprintf(stderr, "v %f %f %f\n", v.px, v.py, v.pz);
fprintf(stderr, "vn %f %f %f\n", nx, ny, nz);
}
for (size_t i = 0; i < indices.size(); i += 3)
{
unsigned int a = indices[i], b = indices[i + 1], c = indices[i + 2];
fprintf(stderr, "f %d//%d %d//%d %d//%d\n", a + 1, a + 1, b + 1, b + 1, c + 1, c + 1);
}
}
void dumpObj(const char* section, const std::vector<unsigned int>& indices)
{
fprintf(stderr, "o %s\n", section);
for (size_t j = 0; j < indices.size(); j += 3)
{
unsigned int a = indices[j], b = indices[j + 1], c = indices[j + 2];
fprintf(stderr, "f %d//%d %d//%d %d//%d\n", a + 1, a + 1, b + 1, b + 1, c + 1, c + 1);
}
}
struct PackedVertex
{
unsigned short px, py, pz;
unsigned short pw; // padding to 4b boundary
signed char nx, ny, nz, nw;
unsigned short tx, ty;
};
void packMesh(std::vector<PackedVertex>& pv, const std::vector<Vertex>& vertices)
{
for (size_t i = 0; i < vertices.size(); ++i)
{
const Vertex& vi = vertices[i];
PackedVertex& pvi = pv[i];
pvi.px = meshopt_quantizeHalf(vi.px);
pvi.py = meshopt_quantizeHalf(vi.py);
pvi.pz = meshopt_quantizeHalf(vi.pz);
pvi.pw = 0;
pvi.nx = char(meshopt_quantizeSnorm(vi.nx, 8));
pvi.ny = char(meshopt_quantizeSnorm(vi.ny, 8));
pvi.nz = char(meshopt_quantizeSnorm(vi.nz, 8));
pvi.nw = 0;
pvi.tx = meshopt_quantizeHalf(vi.tx);
pvi.ty = meshopt_quantizeHalf(vi.ty);
}
}
struct PackedVertexOct
{
unsigned short px, py, pz;
signed char nu, nv; // octahedron encoded normal, aliases .pw
unsigned short tx, ty;
};
void packMesh(std::vector<PackedVertexOct>& pv, const std::vector<Vertex>& vertices)
{
for (size_t i = 0; i < vertices.size(); ++i)
{
const Vertex& vi = vertices[i];
PackedVertexOct& pvi = pv[i];
pvi.px = meshopt_quantizeHalf(vi.px);
pvi.py = meshopt_quantizeHalf(vi.py);
pvi.pz = meshopt_quantizeHalf(vi.pz);
float nsum = fabsf(vi.nx) + fabsf(vi.ny) + fabsf(vi.nz);
float nx = vi.nx / nsum;
float ny = vi.ny / nsum;
float nz = vi.nz;
float nu = nz >= 0 ? nx : (1 - fabsf(ny)) * (nx >= 0 ? 1 : -1);
float nv = nz >= 0 ? ny : (1 - fabsf(nx)) * (ny >= 0 ? 1 : -1);
pvi.nu = char(meshopt_quantizeSnorm(nu, 8));
pvi.nv = char(meshopt_quantizeSnorm(nv, 8));
pvi.tx = meshopt_quantizeHalf(vi.tx);
pvi.ty = meshopt_quantizeHalf(vi.ty);
}
}
void simplify(const Mesh& mesh, float threshold = 0.2f, unsigned int options = 0)
{
Mesh lod;
double start = timestamp();
size_t target_index_count = size_t(mesh.indices.size() * threshold);
float target_error = 1e-2f;
float result_error = 0;
lod.indices.resize(mesh.indices.size()); // note: simplify needs space for index_count elements in the destination array, not target_index_count
lod.indices.resize(meshopt_simplify(&lod.indices[0], &mesh.indices[0], mesh.indices.size(), &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex), target_index_count, target_error, options, &result_error));
lod.vertices.resize(lod.indices.size() < mesh.vertices.size() ? lod.indices.size() : mesh.vertices.size()); // note: this is just to reduce the cost of resize()
lod.vertices.resize(meshopt_optimizeVertexFetch(&lod.vertices[0], &lod.indices[0], lod.indices.size(), &mesh.vertices[0], mesh.vertices.size(), sizeof(Vertex)));
double end = timestamp();
printf("%-9s: %d triangles => %d triangles (%.2f%% deviation) in %.2f msec\n",
"Simplify",
int(mesh.indices.size() / 3), int(lod.indices.size() / 3),
result_error * 100,
(end - start) * 1000);
}
void simplifyAttr(const Mesh& mesh, float threshold = 0.2f, unsigned int options = 0)
{
Mesh lod;
double start = timestamp();
size_t target_index_count = size_t(mesh.indices.size() * threshold);
float target_error = 1e-2f;
float result_error = 0;
const float nrm_weight = 0.5f;
const float attr_weights[3] = {nrm_weight, nrm_weight, nrm_weight};
lod.indices.resize(mesh.indices.size()); // note: simplify needs space for index_count elements in the destination array, not target_index_count
lod.indices.resize(meshopt_simplifyWithAttributes(&lod.indices[0], &mesh.indices[0], mesh.indices.size(), &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex), &mesh.vertices[0].nx, sizeof(Vertex), attr_weights, 3, NULL, target_index_count, target_error, options, &result_error));
lod.vertices.resize(lod.indices.size() < mesh.vertices.size() ? lod.indices.size() : mesh.vertices.size()); // note: this is just to reduce the cost of resize()
lod.vertices.resize(meshopt_optimizeVertexFetch(&lod.vertices[0], &lod.indices[0], lod.indices.size(), &mesh.vertices[0], mesh.vertices.size(), sizeof(Vertex)));
double end = timestamp();
printf("%-9s: %d triangles => %d triangles (%.2f%% deviation) in %.2f msec\n",
"SimplifyAttr",
int(mesh.indices.size() / 3), int(lod.indices.size() / 3),
result_error * 100,
(end - start) * 1000);
}
void simplifyUpdate(const Mesh& mesh, float threshold = 0.2f, unsigned int options = 0)
{
Mesh lod;
double start = timestamp();
size_t target_index_count = size_t(mesh.indices.size() * threshold);
float target_error = 1e-2f;
float result_error = 0;
const float nrm_weight = 0.5f;
const float attr_weights[3] = {nrm_weight, nrm_weight, nrm_weight};
lod = mesh; // start from the original mesh
lod.indices.resize(meshopt_simplifyWithUpdate(&lod.indices[0], mesh.indices.size(), &lod.vertices[0].px, mesh.vertices.size(), sizeof(Vertex), &lod.vertices[0].nx, sizeof(Vertex), attr_weights, 3, NULL, target_index_count, target_error, options, &result_error));
lod.vertices.resize(meshopt_optimizeVertexFetch(&lod.vertices[0], &lod.indices[0], lod.indices.size(), &mesh.vertices[0], mesh.vertices.size(), sizeof(Vertex)));
for (size_t i = 0; i < lod.vertices.size(); ++i)
{
// update normals
Vertex& v = lod.vertices[i];
float nl = sqrtf(v.nx * v.nx + v.ny * v.ny + v.nz * v.nz);
if (nl > 0)
{
v.nx /= nl;
v.ny /= nl;
v.nz /= nl;
}
}
double end = timestamp();
printf("%-9s: %d triangles => %d triangles (%.2f%% deviation) in %.2f msec\n",
"SimplifyUpdt",
int(mesh.indices.size() / 3), int(lod.indices.size() / 3),
result_error * 100,
(end - start) * 1000);
}
void simplifySloppy(const Mesh& mesh, float threshold = 0.2f)
{
Mesh lod;
double start = timestamp();
size_t target_index_count = size_t(mesh.indices.size() * threshold);
float target_error = 1e-1f;
float result_error = 0;
lod.indices.resize(mesh.indices.size()); // note: simplify needs space for index_count elements in the destination array, not target_index_count
lod.indices.resize(meshopt_simplifySloppy(&lod.indices[0], &mesh.indices[0], mesh.indices.size(), &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex), target_index_count, target_error, &result_error));
lod.vertices.resize(lod.indices.size() < mesh.vertices.size() ? lod.indices.size() : mesh.vertices.size()); // note: this is just to reduce the cost of resize()
lod.vertices.resize(meshopt_optimizeVertexFetch(&lod.vertices[0], &lod.indices[0], lod.indices.size(), &mesh.vertices[0], mesh.vertices.size(), sizeof(Vertex)));
double end = timestamp();
printf("%-9s: %d triangles => %d triangles (%.2f%% deviation) in %.2f msec\n",
"SimplifyS",
int(mesh.indices.size() / 3), int(lod.indices.size() / 3),
result_error * 100,
(end - start) * 1000);
}
void simplifyPoints(const Mesh& mesh, float threshold = 0.2f)
{
double start = timestamp();
size_t target_vertex_count = size_t(mesh.vertices.size() * threshold);
if (target_vertex_count == 0)
return;
std::vector<unsigned int> indices(target_vertex_count);
indices.resize(meshopt_simplifyPoints(&indices[0], &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex), NULL, 0, 0, target_vertex_count));
double end = timestamp();
printf("%-9s: %d points => %d points in %.2f msec\n",
"SimplifyP",
int(mesh.vertices.size()), int(indices.size()), (end - start) * 1000);
}
void simplifyComplete(const Mesh& mesh)
{
static const size_t lod_count = 5;
double start = timestamp();
// generate 4 LOD levels (1-4), with each subsequent LOD using 70% triangles
// note that each LOD uses the same (shared) vertex buffer
std::vector<unsigned int> lods[lod_count];
lods[0] = mesh.indices;
for (size_t i = 1; i < lod_count; ++i)
{
std::vector<unsigned int>& lod = lods[i];
float threshold = powf(0.7f, float(i));
size_t target_index_count = size_t(mesh.indices.size() * threshold) / 3 * 3;
float target_error = 1e-2f;
// we can simplify all the way from base level or from the last result
// simplifying from the base level sometimes produces better results, but simplifying from last level is faster
const std::vector<unsigned int>& source = lods[i - 1];
if (source.size() < target_index_count)
target_index_count = source.size();
lod.resize(source.size());
lod.resize(meshopt_simplify(&lod[0], &source[0], source.size(), &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex), target_index_count, target_error));
}
double middle = timestamp();
// optimize each individual LOD for vertex cache & overdraw
for (size_t i = 0; i < lod_count; ++i)
{
std::vector<unsigned int>& lod = lods[i];
meshopt_optimizeVertexCache(&lod[0], &lod[0], lod.size(), mesh.vertices.size());
meshopt_optimizeOverdraw(&lod[0], &lod[0], lod.size(), &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex), 1.0f);
}
// concatenate all LODs into one IB
// note: the order of concatenation is important - since we optimize the entire IB for vertex fetch,
// putting coarse LODs first makes sure that the vertex range referenced by them is as small as possible
// some GPUs process the entire range referenced by the index buffer region so doing this optimizes the vertex transform
// cost for coarse LODs
// this order also produces much better vertex fetch cache coherency for coarse LODs (since they're essentially optimized first)
// somewhat surprisingly, the vertex fetch cache coherency for fine LODs doesn't seem to suffer that much.
size_t lod_index_offsets[lod_count] = {};
size_t lod_index_counts[lod_count] = {};
size_t total_index_count = 0;
for (int i = lod_count - 1; i >= 0; --i)
{
lod_index_offsets[i] = total_index_count;
lod_index_counts[i] = lods[i].size();
total_index_count += lods[i].size();
}
std::vector<unsigned int> indices(total_index_count);
for (size_t i = 0; i < lod_count; ++i)
{
memcpy(&indices[lod_index_offsets[i]], &lods[i][0], lods[i].size() * sizeof(lods[i][0]));
}
std::vector<Vertex> vertices = mesh.vertices;
// vertex fetch optimization should go last as it depends on the final index order
// note that the order of LODs above affects vertex fetch results
meshopt_optimizeVertexFetch(&vertices[0], &indices[0], indices.size(), &vertices[0], vertices.size(), sizeof(Vertex));
double end = timestamp();
printf("%-9s: %d triangles => %d LOD levels down to %d triangles in %.2f msec, optimized in %.2f msec\n",
"SimplifyC",
int(lod_index_counts[0]) / 3, int(lod_count), int(lod_index_counts[lod_count - 1]) / 3,
(middle - start) * 1000, (end - middle) * 1000);
// for using LOD data at runtime, in addition to vertices and indices you have to save lod_index_offsets/lod_index_counts.
{
meshopt_VertexCacheStatistics vcs0 = meshopt_analyzeVertexCache(&indices[lod_index_offsets[0]], lod_index_counts[0], vertices.size(), 16, 0, 0);
meshopt_VertexFetchStatistics vfs0 = meshopt_analyzeVertexFetch(&indices[lod_index_offsets[0]], lod_index_counts[0], vertices.size(), sizeof(Vertex));
meshopt_VertexCacheStatistics vcsN = meshopt_analyzeVertexCache(&indices[lod_index_offsets[lod_count - 1]], lod_index_counts[lod_count - 1], vertices.size(), 16, 0, 0);
meshopt_VertexFetchStatistics vfsN = meshopt_analyzeVertexFetch(&indices[lod_index_offsets[lod_count - 1]], lod_index_counts[lod_count - 1], vertices.size(), sizeof(Vertex));
typedef PackedVertexOct PV;
std::vector<PV> pv(vertices.size());
packMesh(pv, vertices);
std::vector<unsigned char> vbuf(meshopt_encodeVertexBufferBound(vertices.size(), sizeof(PV)));
vbuf.resize(meshopt_encodeVertexBuffer(&vbuf[0], vbuf.size(), &pv[0], vertices.size(), sizeof(PV)));
std::vector<unsigned char> ibuf(meshopt_encodeIndexBufferBound(indices.size(), vertices.size()));
ibuf.resize(meshopt_encodeIndexBuffer(&ibuf[0], ibuf.size(), &indices[0], indices.size()));
printf("%-9s ACMR %f...%f Overfetch %f..%f Codec VB %.1f bits/vertex IB %.1f bits/triangle\n",
"",
vcs0.acmr, vcsN.acmr, vfs0.overfetch, vfsN.overfetch,
double(vbuf.size()) / double(vertices.size()) * 8,
double(ibuf.size()) / double(indices.size() / 3) * 8);
}
}
void simplifyClusters(const Mesh& mesh, float threshold = 0.2f)
{
const size_t max_vertices = 64;
const size_t max_triangles = 64;
const size_t target_group_size = 8;
double start = timestamp();
// build clusters (meshlets) out of the mesh
size_t max_meshlets = meshopt_buildMeshletsBound(mesh.indices.size(), max_vertices, max_triangles);
std::vector<meshopt_Meshlet> meshlets(max_meshlets);
std::vector<unsigned int> meshlet_vertices(mesh.indices.size());
std::vector<unsigned char> meshlet_triangles(mesh.indices.size());
meshlets.resize(meshopt_buildMeshlets(&meshlets[0], &meshlet_vertices[0], &meshlet_triangles[0], &mesh.indices[0], mesh.indices.size(), &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex), max_vertices, max_triangles, 0.f));
double middle = timestamp();
// generate position remap; we'll use that to partition clusters using position-only adjacency
std::vector<unsigned int> remap(mesh.vertices.size());
meshopt_generatePositionRemap(&remap[0], &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex));
// partition clusters in groups; each group will be simplified separately and the boundaries between groups will be preserved
std::vector<unsigned int> cluster_indices;
cluster_indices.reserve(mesh.indices.size()); // slight underestimate, vector should realloc once
std::vector<unsigned int> cluster_sizes(meshlets.size());
for (size_t i = 0; i < meshlets.size(); ++i)
{
const meshopt_Meshlet& m = meshlets[i];
for (size_t j = 0; j < m.triangle_count * 3; ++j)
{
unsigned int v = meshlet_vertices[m.vertex_offset + meshlet_triangles[m.triangle_offset + j]];
// use the first vertex with equivalent position so that cluster adjacency ignores attribute seams
cluster_indices.push_back(remap[v]);
}
cluster_sizes[i] = m.triangle_count * 3;
}
std::vector<unsigned int> partition(meshlets.size());
size_t partition_count = meshopt_partitionClusters(&partition[0], &cluster_indices[0], cluster_indices.size(), &cluster_sizes[0], cluster_sizes.size(), &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex), target_group_size);
// convert partitions to linked lists to make it easier to iterate over (vectors of vectors would work too)
std::vector<int> partnext(meshlets.size(), -1);
std::vector<int> partlast(partition_count, -1);
for (size_t i = 0; i < meshlets.size(); ++i)
{
unsigned int part = partition[i];
if (partlast[part] >= 0)
partnext[partlast[part]] = int(i);
partlast[part] = int(i);
partnext[i] = -1;
}
double parttime = timestamp();
float scale = meshopt_simplifyScale(&mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex));
std::vector<unsigned int> lod;
lod.reserve(mesh.indices.size());
float error = 0.f;
for (size_t i = 0; i < meshlets.size(); ++i)
{
if (partlast[partition[i]] < 0)
continue; // part of a group that was already processed
// mark group as processed
partlast[partition[i]] = -1;
size_t group_offset = lod.size();
for (int j = int(i); j >= 0; j = partnext[j])
{
const meshopt_Meshlet& m = meshlets[j];
for (size_t k = 0; k < m.triangle_count * 3; ++k)
lod.push_back(meshlet_vertices[m.vertex_offset + meshlet_triangles[m.triangle_offset + k]]);
}
size_t group_triangles = (lod.size() - group_offset) / 3;
// simplify the group, preserving the border vertices
// note: this technically also locks the exterior border; a full mesh analysis (see clusterlod.h / lockBoundary) would work better for some meshes
unsigned int options = meshopt_SimplifyLockBorder | meshopt_SimplifySparse | meshopt_SimplifyErrorAbsolute;
float group_target_error = 1e-2f * scale;
size_t group_target = size_t(float(group_triangles) * threshold) * 3;
float group_error = 0.f;
size_t group_size = meshopt_simplify(&lod[group_offset], &lod[group_offset], group_triangles * 3, &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex), group_target, group_target_error, options, &group_error);
error = group_error > error ? group_error : error;
// simplified group is available in lod[group_offset..group_offset + group_size]
lod.resize(group_offset + group_size);
}
double end = timestamp();
printf("%-9s: %d triangles => %d triangles (%.2f%% deviation) in %.2f msec, clusterized in %.2f msec, partitioned in %.2f msec (%d clusters in %d groups, %.1f avg)\n",
"SimplifyG",
int(mesh.indices.size() / 3), int(lod.size() / 3),
error / scale * 100,
(end - parttime) * 1000, (middle - start) * 1000, (parttime - middle) * 1000,
int(meshlets.size()), int(partition_count), double(meshlets.size()) / double(partition_count));
}
void optimize(const Mesh& mesh, bool fifo = false)
{
Mesh copy = mesh;
// note: we assume that the mesh is already optimally indexed (via parseObj); if that is not the case, you'd need to reindex first
double start = timestamp();
// vertex cache optimization should go first as it provides starting order for overdraw
// note: fifo optimization is not recommended as a default, since it produces worse results, but it's faster to run so it can be useful for procedural meshes
if (fifo)
meshopt_optimizeVertexCacheFifo(©.indices[0], ©.indices[0], copy.indices.size(), copy.vertices.size(), /* cache_size= */ 16);
else
meshopt_optimizeVertexCache(©.indices[0], ©.indices[0], copy.indices.size(), copy.vertices.size());
// reorder indices for overdraw, balancing overdraw and vertex cache efficiency
const float kThreshold = 1.01f; // allow up to 1% worse ACMR to get more reordering opportunities for overdraw
meshopt_optimizeOverdraw(©.indices[0], ©.indices[0], copy.indices.size(), ©.vertices[0].px, copy.vertices.size(), sizeof(Vertex), kThreshold);
// vertex fetch optimization should go last as it depends on the final index order
meshopt_optimizeVertexFetch(©.vertices[0], ©.indices[0], copy.indices.size(), ©.vertices[0], copy.vertices.size(), sizeof(Vertex));
double end = timestamp();
meshopt_VertexCacheStatistics vcs = meshopt_analyzeVertexCache(©.indices[0], copy.indices.size(), copy.vertices.size(), 16, 0, 0);
meshopt_VertexFetchStatistics vfs = meshopt_analyzeVertexFetch(©.indices[0], copy.indices.size(), copy.vertices.size(), sizeof(Vertex));
meshopt_OverdrawStatistics os = meshopt_analyzeOverdraw(©.indices[0], copy.indices.size(), ©.vertices[0].px, copy.vertices.size(), sizeof(Vertex));
meshopt_VertexCacheStatistics vcs_nv = meshopt_analyzeVertexCache(©.indices[0], copy.indices.size(), copy.vertices.size(), 32, 32, 32);
meshopt_VertexCacheStatistics vcs_amd = meshopt_analyzeVertexCache(©.indices[0], copy.indices.size(), copy.vertices.size(), 14, 64, 128);
meshopt_VertexCacheStatistics vcs_intel = meshopt_analyzeVertexCache(©.indices[0], copy.indices.size(), copy.vertices.size(), 128, 0, 0);
printf("Optimize%s: ACMR %f ATVR %f (NV %f AMD %f Intel %f) overfetch %f overdraw %f in %.2f msec\n",
fifo ? "F" : " ",
vcs.acmr, vcs.atvr, vcs_nv.atvr, vcs_amd.atvr, vcs_intel.atvr, vfs.overfetch, os.overdraw, (end - start) * 1000);
}
template <typename T>
size_t compress(const std::vector<T>& data, int level = SDEFL_LVL_DEF)
{
std::vector<unsigned char> cbuf(sdefl_bound(int(data.size() * sizeof(T))));
sdefl s = {};
return sdeflate(&s, &cbuf[0], reinterpret_cast<const unsigned char*>(&data[0]), int(data.size() * sizeof(T)), level);
}
void encodeIndex(const std::vector<unsigned int>& indices, size_t vertex_count, char desc)
{
// allocate result outside of the timing loop to exclude memset() from decode timing
std::vector<unsigned int> result(indices.size());
double start = timestamp();
std::vector<unsigned char> buffer(meshopt_encodeIndexBufferBound(indices.size(), vertex_count));
buffer.resize(meshopt_encodeIndexBuffer(&buffer[0], buffer.size(), &indices[0], indices.size()));
double middle = timestamp();
int res = meshopt_decodeIndexBuffer(&result[0], indices.size(), &buffer[0], buffer.size());
assert(res == 0);
(void)res;
double end = timestamp();
size_t csize = compress(buffer);
for (size_t i = 0; i < indices.size(); i += 3)
{
assert(
(result[i + 0] == indices[i + 0] && result[i + 1] == indices[i + 1] && result[i + 2] == indices[i + 2]) ||
(result[i + 1] == indices[i + 0] && result[i + 2] == indices[i + 1] && result[i + 0] == indices[i + 2]) ||
(result[i + 2] == indices[i + 0] && result[i + 0] == indices[i + 1] && result[i + 1] == indices[i + 2]));
}
printf("IdxCodec%c: %.1f bits/triangle (post-deflate %.1f bits/triangle); encode %.2f msec (%.3f GB/s), decode %.2f msec (%.2f GB/s)\n",
desc,
double(buffer.size() * 8) / double(indices.size() / 3),
double(csize * 8) / double(indices.size() / 3),
(middle - start) * 1000,
(double(result.size() * 4) / 1e9) / (middle - start),
(end - middle) * 1000,
(double(result.size() * 4) / 1e9) / (end - middle));
}
void encodeIndex(const Mesh& mesh, char desc)
{
encodeIndex(mesh.indices, mesh.vertices.size(), desc);
}
void encodeIndexSequence(const std::vector<unsigned int>& data, size_t vertex_count, char desc)
{
// allocate result outside of the timing loop to exclude memset() from decode timing
std::vector<unsigned int> result(data.size());
double start = timestamp();
std::vector<unsigned char> buffer(meshopt_encodeIndexSequenceBound(data.size(), vertex_count));
buffer.resize(meshopt_encodeIndexSequence(&buffer[0], buffer.size(), &data[0], data.size()));
double middle = timestamp();
int res = meshopt_decodeIndexSequence(&result[0], data.size(), &buffer[0], buffer.size());
assert(res == 0);
(void)res;
double end = timestamp();
size_t csize = compress(buffer);
assert(memcmp(&data[0], &result[0], data.size() * sizeof(unsigned int)) == 0);
printf("IdxCodec%c: %.1f bits/index (post-deflate %.1f bits/index); encode %.2f msec (%.3f GB/s), decode %.2f msec (%.2f GB/s)\n",
desc,
double(buffer.size() * 8) / double(data.size()),
double(csize * 8) / double(data.size()),
(middle - start) * 1000,
(double(result.size() * 4) / 1e9) / (middle - start),
(end - middle) * 1000,
(double(result.size() * 4) / 1e9) / (end - middle));
}
template <typename V, typename T>
static void validateDecodeMeshlet(const unsigned char* data, size_t size, const unsigned int* vertices, size_t vertex_count, const unsigned char* triangles, size_t triangle_count)
{
V rv[256];
T rt[sizeof(T) == 1 ? 256 * 3 : 256];
int rc = meshopt_decodeMeshlet(rv, vertex_count, rt, triangle_count, data, size);
assert(rc == 0);
for (size_t j = 0; j < vertex_count; ++j)
assert(rv[j] == V(vertices[j]));
for (size_t j = 0; j < triangle_count; ++j)
{
unsigned int a = triangles[j * 3 + 0];
unsigned int b = triangles[j * 3 + 1];
unsigned int c = triangles[j * 3 + 2];
unsigned int tri = sizeof(T) == 1 ? rt[j * 3] | (rt[j * 3 + 1] << 8) | (rt[j * 3 + 2] << 16) : rt[j];
unsigned int abc = (a << 0) | (b << 8) | (c << 16);
unsigned int bca = (b << 0) | (c << 8) | (a << 16);
unsigned int cba = (c << 0) | (a << 8) | (b << 16);
assert(tri == abc || tri == bca || tri == cba);
}
}
void encodeMeshlets(const Mesh& mesh, size_t max_vertices, size_t max_triangles, bool reorder = true)
{
size_t max_meshlets = meshopt_buildMeshletsBound(mesh.indices.size(), max_vertices, max_triangles);
std::vector<meshopt_Meshlet> meshlets(max_meshlets);
std::vector<unsigned int> meshlet_vertices(mesh.indices.size());
std::vector<unsigned char> meshlet_triangles(mesh.indices.size());
meshlets.resize(meshopt_buildMeshlets(&meshlets[0], &meshlet_vertices[0], &meshlet_triangles[0], &mesh.indices[0], mesh.indices.size(), &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex), max_vertices, max_triangles, 0.f));
if (meshlets.size())
{
const meshopt_Meshlet& last = meshlets.back();
// this is an example of how to trim the vertex/triangle arrays when copying data out to GPU storage
meshlet_vertices.resize(last.vertex_offset + last.vertex_count);
meshlet_triangles.resize(last.triangle_offset + last.triangle_count * 3);
// TODO: over-allocate meshlet_vertices to multiple of 3 to make meshopt_optimizeVertexFetch below work without assertions
meshlet_vertices.resize((meshlet_vertices.size() + 2) / 3 * 3);
}
std::vector<unsigned char> cbuf(meshopt_encodeMeshletBound(max_vertices, max_triangles));
// optimize each meshlet for locality; this is important for performance, and critical for good compression
for (size_t i = 0; i < meshlets.size(); ++i)
meshopt_optimizeMeshlet(&meshlet_vertices[meshlets[i].vertex_offset], &meshlet_triangles[meshlets[i].triangle_offset], meshlets[i].triangle_count, meshlets[i].vertex_count);
// optimize the order of vertex references within each meshlet and globally; this is valuable for access locality and critical for compression of vertex references
// note that this reorders the vertex buffer too, so if a traditional index buffer is required it would need to be reconstructed from the meshlet data for optimal locality
std::vector<Vertex> vertices = mesh.vertices;
if (reorder)
meshopt_optimizeVertexFetch(&vertices[0], &meshlet_vertices[0], meshlet_vertices.size(), &mesh.vertices[0], mesh.vertices.size(), sizeof(Vertex));
size_t mbst = 0;
std::vector<unsigned char> packed;
for (size_t i = 0; i < meshlets.size(); ++i)
{
const meshopt_Meshlet& meshlet = meshlets[i];
size_t mbs = meshopt_encodeMeshlet(&cbuf[0], cbuf.size(), &meshlet_vertices[meshlet.vertex_offset], meshlet.vertex_count, &meshlet_triangles[meshlet.triangle_offset], meshlet.triangle_count);
assert(mbs > 0);
// 24-bit header: 7 bit (vertex_count-1), 7 bit (triangle_count-1), 10 bit size
// fits up to 128v/128t meshlet with 1024 bytes of encoded data; meshopt_encodeMeshletBound(128,128) < 1000
assert(size_t(meshlet.vertex_count - 1) < 128 && size_t(meshlet.triangle_count - 1) < 128 && mbs < 1024);
unsigned int header = ((meshlet.vertex_count - 1) & 0x7f) | (((meshlet.triangle_count - 1) & 0x7f) << 7) | ((unsigned(mbs) & 0x3ff) << 14);
packed.push_back((unsigned char)(header & 0xff));
packed.push_back((unsigned char)((header >> 8) & 0xff));
packed.push_back((unsigned char)((header >> 16) & 0xff));
packed.insert(packed.end(), &cbuf[0], &cbuf[mbs]);
validateDecodeMeshlet<unsigned int, unsigned int>(&cbuf[0], mbs, &meshlet_vertices[meshlet.vertex_offset], meshlet.vertex_count, &meshlet_triangles[meshlet.triangle_offset], meshlet.triangle_count);
validateDecodeMeshlet<unsigned int, unsigned char>(&cbuf[0], mbs, &meshlet_vertices[meshlet.vertex_offset], meshlet.vertex_count, &meshlet_triangles[meshlet.triangle_offset], meshlet.triangle_count);
validateDecodeMeshlet<unsigned short, unsigned int>(&cbuf[0], mbs, &meshlet_vertices[meshlet.vertex_offset], meshlet.vertex_count, &meshlet_triangles[meshlet.triangle_offset], meshlet.triangle_count);
validateDecodeMeshlet<unsigned short, unsigned char>(&cbuf[0], mbs, &meshlet_vertices[meshlet.vertex_offset], meshlet.vertex_count, &meshlet_triangles[meshlet.triangle_offset], meshlet.triangle_count);
mbst += mbs;
}
size_t mbc = compress(packed);
printf("MeshletCodec (%d/%d): %d meshlets, %d bytes/meshlet; %d bytes, %.1f bits/triangle\n",
int(max_vertices), int(max_triangles),
int(meshlets.size()),
int(mbst / meshlets.size()),
int(mbst), double(mbst * 8) / double(mesh.indices.size() / 3));
printf("MeshletCodec (%d/%d, packed): %d bytes/meshlet, %.1f bits/triangle; post-deflate: %d bytes/meshlet, %.1f bits/triangle)\n",
int(max_vertices), int(max_triangles),
int(packed.size() / meshlets.size()), double(packed.size() * 8) / double(mesh.indices.size() / 3),
int(mbc / meshlets.size()), double(mbc * 8) / double(mesh.indices.size() / 3));
#if !TRACE
double mbtime = 0;
for (int i = 0; i < 10; ++i)
{
unsigned int rv[256];
unsigned int rt[256];
double t0 = timestamp();
unsigned char* p = &packed[0];
for (size_t j = 0; j < meshlets.size(); ++j)
{
unsigned int header = p[0] | (p[1] << 8) | (p[2] << 16);
size_t vertex_count = (header & 0x7f) + 1;
size_t triangle_count = ((header >> 7) & 0x7f) + 1;
size_t size = (header >> 14) & 0x3ff;
meshopt_decodeMeshletRaw(rv, vertex_count, rt, triangle_count, p + 3, size);
p += 3 + size;
}
double t1 = timestamp();
mbtime = (mbtime == 0 || t1 - t0 < mbtime) ? (t1 - t0) : mbtime;
}
printf("MeshletCodec (%d/%d, packed): decode time %.3f msec, %.3fB tri/sec, %.1f ns/meshlet\n",
int(max_vertices), int(max_triangles),
mbtime * 1000, double(mesh.indices.size() / 3) / 1e9 / mbtime, mbtime * 1e9 / double(meshlets.size()));
#endif
}
template <typename PV>
void packVertex(const Mesh& mesh, const char* pvn)
{
std::vector<PV> pv(mesh.vertices.size());
packMesh(pv, mesh.vertices);
size_t csize = compress(pv);
printf("VtxPack%s : %.1f bits/vertex (post-deflate %.1f bits/vertex)\n", pvn,
double(pv.size() * sizeof(PV) * 8) / double(mesh.vertices.size()),
double(csize * 8) / double(mesh.vertices.size()));
}
template <typename PV>
void encodeVertex(const Mesh& mesh, const char* pvn, int level = 2)
{
std::vector<PV> pv(mesh.vertices.size());
packMesh(pv, mesh.vertices);
// allocate result outside of the timing loop to exclude memset() from decode timing
std::vector<PV> result(mesh.vertices.size());
double start = timestamp();
std::vector<unsigned char> vbuf(meshopt_encodeVertexBufferBound(mesh.vertices.size(), sizeof(PV)));
vbuf.resize(meshopt_encodeVertexBufferLevel(&vbuf[0], vbuf.size(), &pv[0], mesh.vertices.size(), sizeof(PV), level, -1));
double middle = timestamp();
int res = meshopt_decodeVertexBuffer(&result[0], mesh.vertices.size(), sizeof(PV), &vbuf[0], vbuf.size());
assert(res == 0);
(void)res;
double end = timestamp();
assert(memcmp(&pv[0], &result[0], pv.size() * sizeof(PV)) == 0);
size_t csize = compress(vbuf);
printf("VtxCodec%1s: %.1f bits/vertex (post-deflate %.1f bits/vertex); encode %.2f msec (%.3f GB/s), decode %.2f msec (%.2f GB/s)\n", pvn,
double(vbuf.size() * 8) / double(mesh.vertices.size()),
double(csize * 8) / double(mesh.vertices.size()),
(middle - start) * 1000,
(double(result.size() * sizeof(PV)) / 1e9) / (middle - start),
(end - middle) * 1000,
(double(result.size() * sizeof(PV)) / 1e9) / (end - middle));
}
void stripify(const Mesh& mesh, bool use_restart, char desc)
{
unsigned int restart_index = use_restart ? ~0u : 0;
// note: input mesh is assumed to be optimized for vertex cache and vertex fetch
double start = timestamp();
std::vector<unsigned int> strip(meshopt_stripifyBound(mesh.indices.size()));
strip.resize(meshopt_stripify(&strip[0], &mesh.indices[0], mesh.indices.size(), mesh.vertices.size(), restart_index));
double end = timestamp();
size_t restarts = 0;
for (size_t i = 0; i < strip.size(); ++i)
restarts += use_restart && strip[i] == restart_index;
Mesh copy = mesh;
copy.indices.resize(meshopt_unstripify(©.indices[0], &strip[0], strip.size(), restart_index));
assert(copy.indices.size() <= meshopt_unstripifyBound(strip.size()));
meshopt_VertexCacheStatistics vcs = meshopt_analyzeVertexCache(©.indices[0], mesh.indices.size(), mesh.vertices.size(), 16, 0, 0);
meshopt_VertexCacheStatistics vcs_nv = meshopt_analyzeVertexCache(©.indices[0], mesh.indices.size(), mesh.vertices.size(), 32, 32, 32);
meshopt_VertexCacheStatistics vcs_amd = meshopt_analyzeVertexCache(©.indices[0], mesh.indices.size(), mesh.vertices.size(), 14, 64, 128);
meshopt_VertexCacheStatistics vcs_intel = meshopt_analyzeVertexCache(©.indices[0], mesh.indices.size(), mesh.vertices.size(), 128, 0, 0);
printf("Stripify%c: ACMR %f ATVR %f (NV %f AMD %f Intel %f); %.1f run avg, %d strip indices (%.1f%%) in %.2f msec\n",
desc,
vcs.acmr, vcs.atvr, vcs_nv.atvr, vcs_amd.atvr, vcs_intel.atvr,
use_restart ? double(strip.size() - restarts) / double(restarts + 1) : 0,
int(strip.size()), double(strip.size()) / double(mesh.indices.size()) * 100,
(end - start) * 1000);
}
void shadow(const Mesh& mesh)
{
// note: input mesh is assumed to be optimized for vertex cache and vertex fetch
double start = timestamp();
// this index buffer can be used for position-only rendering using the same vertex data that the original index buffer uses
std::vector<unsigned int> shadow_indices(mesh.indices.size());
meshopt_generateShadowIndexBuffer(&shadow_indices[0], &mesh.indices[0], mesh.indices.size(), &mesh.vertices[0], mesh.vertices.size(), sizeof(float) * 3, sizeof(Vertex));
double end = timestamp();
// while you can't optimize the vertex data after shadow IB was constructed, you can and should optimize the shadow IB for vertex cache
// this is valuable even if the original indices array was optimized for vertex cache!
meshopt_optimizeVertexCache(&shadow_indices[0], &shadow_indices[0], shadow_indices.size(), mesh.vertices.size());
meshopt_VertexCacheStatistics vcs = meshopt_analyzeVertexCache(&mesh.indices[0], mesh.indices.size(), mesh.vertices.size(), 16, 0, 0);
meshopt_VertexCacheStatistics vcss = meshopt_analyzeVertexCache(&shadow_indices[0], shadow_indices.size(), mesh.vertices.size(), 16, 0, 0);
std::vector<char> shadow_flags(mesh.vertices.size());
size_t shadow_vertices = 0;
for (size_t i = 0; i < shadow_indices.size(); ++i)
{
unsigned int index = shadow_indices[i];
shadow_vertices += 1 - shadow_flags[index];
shadow_flags[index] = 1;
}
printf("ShadowIB : ACMR %f (%.2fx improvement); %d shadow vertices (%.2fx improvement) in %.2f msec\n",
vcss.acmr, double(vcs.vertices_transformed) / double(vcss.vertices_transformed),
int(shadow_vertices), double(mesh.vertices.size()) / double(shadow_vertices),
(end - start) * 1000);
}
static int follow(int* parents, int index)
{
while (index != parents[index])
{
int parent = parents[index];
parents[index] = parents[parent];
index = parent;
}
return index;
}
void meshlets(const Mesh& mesh, bool scan = false, bool uniform = false, bool flex = false, bool spatial = false, bool dump = false)
{
// NVidia recommends 64/126; we also test uniform configuration with 64/64 which is better for earlier AMD GPUs
const size_t max_vertices = 64;
const size_t max_triangles = uniform ? 64 : 126;
const size_t min_triangles = spatial ? 16 : (uniform ? 24 : 32); // only used in flex/spatial modes
// note: should be set to 0 unless cone culling is used at runtime!
const float cone_weight = 0.25f;
const float split_factor = flex ? 2.0f : 0.0f;
// note: input mesh is assumed to be optimized for vertex cache and vertex fetch
double start = timestamp();
size_t max_meshlets = meshopt_buildMeshletsBound(mesh.indices.size(), max_vertices, min_triangles);
std::vector<meshopt_Meshlet> meshlets(max_meshlets);
std::vector<unsigned int> meshlet_vertices(mesh.indices.size());
std::vector<unsigned char> meshlet_triangles(mesh.indices.size());
if (scan)
meshlets.resize(meshopt_buildMeshletsScan(&meshlets[0], &meshlet_vertices[0], &meshlet_triangles[0], &mesh.indices[0], mesh.indices.size(), mesh.vertices.size(), max_vertices, max_triangles));
else if (flex)
meshlets.resize(meshopt_buildMeshletsFlex(&meshlets[0], &meshlet_vertices[0], &meshlet_triangles[0], &mesh.indices[0], mesh.indices.size(), &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex), max_vertices, min_triangles, max_triangles, cone_weight, split_factor));
else if (spatial)
meshlets.resize(meshopt_buildMeshletsSpatial(&meshlets[0], &meshlet_vertices[0], &meshlet_triangles[0], &mesh.indices[0], mesh.indices.size(), &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex), max_vertices, min_triangles, max_triangles, 0.f));
else // note: equivalent to the call of buildMeshletsFlex() with split_factor = 0 and min_triangles = max_triangles
meshlets.resize(meshopt_buildMeshlets(&meshlets[0], &meshlet_vertices[0], &meshlet_triangles[0], &mesh.indices[0], mesh.indices.size(), &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex), max_vertices, max_triangles, cone_weight));
if (!dump)
for (size_t i = 0; i < meshlets.size(); ++i)
meshopt_optimizeMeshlet(&meshlet_vertices[meshlets[i].vertex_offset], &meshlet_triangles[meshlets[i].triangle_offset], meshlets[i].triangle_count, meshlets[i].vertex_count);
if (meshlets.size())
{
const meshopt_Meshlet& last = meshlets.back();
// this is an example of how to trim the vertex/triangle arrays when copying data out to GPU storage
meshlet_vertices.resize(last.vertex_offset + last.vertex_count);
meshlet_triangles.resize(last.triangle_offset + last.triangle_count * 3);
}
double end = timestamp();
if (dump)
dumpObj(mesh.vertices, std::vector<unsigned>());
double avg_vertices = 0;
double avg_triangles = 0;
double avg_boundary = 0;
double avg_connected = 0;
size_t not_full = 0;
std::vector<int> boundary(mesh.vertices.size());
for (size_t i = 0; i < meshlets.size(); ++i)
{
const meshopt_Meshlet& m = meshlets[i];
for (unsigned int j = 0; j < m.vertex_count; ++j)
boundary[meshlet_vertices[m.vertex_offset + j]]++;
}
std::vector<unsigned int> cluster;
for (size_t i = 0; i < meshlets.size(); ++i)
{
const meshopt_Meshlet& m = meshlets[i];
if (dump)
{
cluster.clear();
for (unsigned int j = 0; j < m.triangle_count * 3; ++j)
cluster.push_back(meshlet_vertices[m.vertex_offset + meshlet_triangles[m.triangle_offset + j]]);
char cname[32];
snprintf(cname, sizeof(cname), "ml_%d\n", int(i));
dumpObj(cname, cluster);
}
avg_vertices += m.vertex_count;
avg_triangles += m.triangle_count;
not_full += uniform ? m.triangle_count < max_triangles : m.vertex_count < max_vertices;
for (unsigned int j = 0; j < m.vertex_count; ++j)
if (boundary[meshlet_vertices[m.vertex_offset + j]] > 1)
avg_boundary += 1;
// union-find vertices to check if the meshlet is connected
int parents[256];
for (unsigned int j = 0; j < m.vertex_count; ++j)
parents[j] = int(j);
for (unsigned int j = 0; j < m.triangle_count * 3; ++j)
{
int v0 = meshlet_triangles[m.triangle_offset + j];
int v1 = meshlet_triangles[m.triangle_offset + j + (j % 3 == 2 ? -2 : 1)];
v0 = follow(parents, v0);
v1 = follow(parents, v1);
parents[v0] = v1;
}
int roots = 0;
for (unsigned int j = 0; j < m.vertex_count; ++j)
roots += follow(parents, j) == int(j);
assert(roots != 0);
avg_connected += roots;
}
avg_vertices /= double(meshlets.size());
avg_triangles /= double(meshlets.size());
avg_boundary /= double(meshlets.size());
avg_connected /= double(meshlets.size());
printf("Meshlets%c: %d meshlets (avg vertices %.1f, avg triangles %.1f, avg boundary %.1f, avg connected %.2f, not full %d) in %.2f msec\n",
scan ? 'S' : (flex ? 'F' : (spatial ? 'X' : (uniform ? 'U' : ' '))),
int(meshlets.size()), avg_vertices, avg_triangles, avg_boundary, avg_connected, int(not_full), (end - start) * 1000);
float camera[3] = {100, 100, 100};
size_t rejected = 0;
size_t accepted = 0;
double radius_mean = 0;
double cone_mean = 0;
std::vector<float> radii(meshlets.size());
std::vector<float> cones(meshlets.size());
double startc = timestamp();
for (size_t i = 0; i < meshlets.size(); ++i)
{
const meshopt_Meshlet& m = meshlets[i];
meshopt_Bounds bounds = meshopt_computeMeshletBounds(&meshlet_vertices[m.vertex_offset], &meshlet_triangles[m.triangle_offset], m.triangle_count, &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex));
radii[i] = bounds.radius;
cones[i] = 90.f - acosf(bounds.cone_cutoff) * (180.f / 3.1415926f);
radius_mean += radii[i];
cone_mean += cones[i];
// trivial accept: we can't ever backface cull this meshlet
accepted += (bounds.cone_cutoff >= 1);
// perspective projection: dot(normalize(cone_apex - camera_position), cone_axis) > cone_cutoff
// alternative formulation for perspective projection that doesn't use apex (and uses cluster bounding sphere instead):
// dot(normalize(center - camera_position), cone_axis) > cone_cutoff + radius / length(center - camera_position)
float cview[3] = {bounds.center[0] - camera[0], bounds.center[1] - camera[1], bounds.center[2] - camera[2]};
float cviewlength = sqrtf(cview[0] * cview[0] + cview[1] * cview[1] + cview[2] * cview[2]);
rejected += cview[0] * bounds.cone_axis[0] + cview[1] * bounds.cone_axis[1] + cview[2] * bounds.cone_axis[2] >= bounds.cone_cutoff * cviewlength + bounds.radius;
}
double endc = timestamp();
radius_mean /= double(meshlets.size());
cone_mean /= double(meshlets.size());
double radius_variance = 0;
for (size_t i = 0; i < meshlets.size(); ++i)
radius_variance += (radii[i] - radius_mean) * (radii[i] - radius_mean);
radius_variance /= double(meshlets.size() - 1);
double radius_stddev = sqrt(radius_variance);
size_t meshlets_std = 0;
for (size_t i = 0; i < meshlets.size(); ++i)
meshlets_std += radii[i] < radius_mean + radius_stddev;
printf("Bounds : radius mean %f stddev %f; %.1f%% meshlets under 1σ; cone angle %.1f°; cone reject %.1f%% trivial accept %.1f%% in %.2f msec\n",
radius_mean, radius_stddev,
double(meshlets_std) / double(meshlets.size()) * 100,
cone_mean, double(rejected) / double(meshlets.size()) * 100, double(accepted) / double(meshlets.size()) * 100,
(endc - startc) * 1000);
}
void spatialSort(const Mesh& mesh)
{
typedef PackedVertexOct PV;
std::vector<PV> pv(mesh.vertices.size());
packMesh(pv, mesh.vertices);
double start = timestamp();
std::vector<unsigned int> remap(mesh.vertices.size());
meshopt_spatialSortRemap(&remap[0], &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex));
double end = timestamp();
meshopt_remapVertexBuffer(&pv[0], &pv[0], mesh.vertices.size(), sizeof(PV), &remap[0]);
std::vector<unsigned char> vbuf(meshopt_encodeVertexBufferBound(mesh.vertices.size(), sizeof(PV)));
vbuf.resize(meshopt_encodeVertexBuffer(&vbuf[0], vbuf.size(), &pv[0], mesh.vertices.size(), sizeof(PV)));
size_t csize = compress(vbuf);
printf("Spatial : %.1f bits/vertex (post-deflate %.1f bits/vertex); sort %.2f msec\n",
double(vbuf.size() * 8) / double(mesh.vertices.size()),
double(csize * 8) / double(mesh.vertices.size()),
(end - start) * 1000);
}
void spatialSortTriangles(const Mesh& mesh)
{
typedef PackedVertexOct PV;
Mesh copy = mesh;
double start = timestamp();
meshopt_spatialSortTriangles(©.indices[0], ©.indices[0], mesh.indices.size(), ©.vertices[0].px, copy.vertices.size(), sizeof(Vertex));
double end = timestamp();
meshopt_optimizeVertexCache(©.indices[0], ©.indices[0], copy.indices.size(), copy.vertices.size());
meshopt_optimizeVertexFetch(©.vertices[0], ©.indices[0], copy.indices.size(), ©.vertices[0], copy.vertices.size(), sizeof(Vertex));
std::vector<PV> pv(mesh.vertices.size());
packMesh(pv, copy.vertices);
std::vector<unsigned char> vbuf(meshopt_encodeVertexBufferBound(mesh.vertices.size(), sizeof(PV)));
vbuf.resize(meshopt_encodeVertexBuffer(&vbuf[0], vbuf.size(), &pv[0], mesh.vertices.size(), sizeof(PV)));
std::vector<unsigned char> ibuf(meshopt_encodeIndexBufferBound(mesh.indices.size(), mesh.vertices.size()));
ibuf.resize(meshopt_encodeIndexBuffer(&ibuf[0], ibuf.size(), ©.indices[0], mesh.indices.size()));
size_t csizev = compress(vbuf);
size_t csizei = compress(ibuf);
printf("SpatialT : %.1f bits/vertex (post-deflate %.1f bits/vertex); %.1f bits/triangle (post-deflate %.1f bits/triangle); sort %.2f msec\n",
double(vbuf.size() * 8) / double(mesh.vertices.size()),
double(csizev * 8) / double(mesh.vertices.size()),
double(ibuf.size() * 8) / double(mesh.indices.size() / 3),
double(csizei * 8) / double(mesh.indices.size() / 3),
(end - start) * 1000);
}
void spatialClusterPoints(const Mesh& mesh, size_t cluster_size)
{
typedef PackedVertexOct PV;
double start = timestamp();
std::vector<unsigned int> index(mesh.vertices.size());
meshopt_spatialClusterPoints(&index[0], &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex), cluster_size);
double end = timestamp();
std::vector<PV> pv(mesh.vertices.size());
packMesh(pv, mesh.vertices);
std::vector<PV> pvo(mesh.vertices.size());
for (size_t i = 0; i < index.size(); ++i)
pvo[i] = pv[index[i]];
std::vector<unsigned char> vbuf(meshopt_encodeVertexBufferBound(mesh.vertices.size(), sizeof(PV)));
vbuf.resize(meshopt_encodeVertexBuffer(&vbuf[0], vbuf.size(), &pvo[0], mesh.vertices.size(), sizeof(PV)));
size_t csize = compress(vbuf);
printf("SpatialCP: %.1f bits/vertex (post-deflate %.1f bits/vertex); sort %.2f msec\n",
double(vbuf.size() * 8) / double(mesh.vertices.size()),
double(csize * 8) / double(mesh.vertices.size()),
(end - start) * 1000);
}
void tessellationAdjacency(const Mesh& mesh)
{
double start = timestamp();
// 12 indices per input triangle
std::vector<unsigned int> tessib(mesh.indices.size() * 4);
meshopt_generateTessellationIndexBuffer(&tessib[0], &mesh.indices[0], mesh.indices.size(), &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex));
double middle = timestamp();
// 6 indices per input triangle
std::vector<unsigned int> adjib(mesh.indices.size() * 2);
meshopt_generateAdjacencyIndexBuffer(&adjib[0], &mesh.indices[0], mesh.indices.size(), &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex));
double end = timestamp();
printf("Tesselltn: %d patches in %.2f msec\n", int(mesh.indices.size() / 3), (middle - start) * 1000);
printf("Adjacency: %d patches in %.2f msec\n", int(mesh.indices.size() / 3), (end - middle) * 1000);
}
void provoking(const Mesh& mesh)
{
double start = timestamp();
// worst case number of vertices: vertex count + triangle count
std::vector<unsigned int> pib(mesh.indices.size());
std::vector<unsigned int> reorder(mesh.vertices.size() + mesh.indices.size() / 3);
size_t pcount = meshopt_generateProvokingIndexBuffer(&pib[0], &reorder[0], &mesh.indices[0], mesh.indices.size(), mesh.vertices.size());
reorder.resize(pcount);
double end = timestamp();
// validate invariant: pib[i] == i/3 for provoking vertices
for (size_t i = 0; i < mesh.indices.size(); i += 3)
assert(pib[i] == i / 3);
// validate invariant: reorder[pib[x]] == ib[x] modulo triangle rotation
// note: this is technically not promised by the interface (it may reorder triangles!), it just happens to hold right now
for (size_t i = 0; i < mesh.indices.size(); i += 3)
{
unsigned int a = mesh.indices[i + 0], b = mesh.indices[i + 1], c = mesh.indices[i + 2];
unsigned int ra = reorder[pib[i + 0]], rb = reorder[pib[i + 1]], rc = reorder[pib[i + 2]];
assert((a == ra && b == rb && c == rc) || (a == rb && b == rc && c == ra) || (a == rc && b == ra && c == rb));
}
// best case number of vertices: max(vertex count, triangle count), assuming non-redundant indexing (all vertices are used)
// note: this is a lower bound, and it's not theoretically possible on some meshes;
// for example, a union of a flat shaded cube (12t 24v) and a smooth shaded icosahedron (20t 12v) will have 36 vertices and 32 triangles
// however, the best case for that union is 44 vertices (24 cube vertices + 20 icosahedron vertices due to provoking invariant)
size_t bestv = mesh.vertices.size() > mesh.indices.size() / 3 ? mesh.vertices.size() : mesh.indices.size() / 3;
printf("Provoking: %d triangles / %d vertices (+%.1f%% extra) in %.2f msec\n",
int(mesh.indices.size() / 3), int(pcount), double(pcount) / double(bestv) * 100.0 - 100.0, (end - start) * 1000);
}
static int reindexCompare(void* context, unsigned int lhs, unsigned int rhs)
{
const Vertex* vertices = static_cast<Vertex*>(context);
const Vertex& lv = vertices[lhs];
const Vertex& rv = vertices[rhs];
float ln = lv.nx * lv.nx + lv.ny * lv.ny + lv.nz * lv.nz;
float rn = rv.nx * rv.nx + rv.ny * rv.ny + rv.nz * rv.nz;
// 1/1024px UV tolerance, 3 degree normal tolerance
return fabsf(lv.tx - rv.tx) < 1e-3f &&
fabsf(lv.ty - rv.ty) < 1e-3f &&
(lv.nx * rv.nx + lv.ny * rv.ny + lv.nz * rv.nz >= 0.9986f * sqrtf(ln * rn));
}
void reindexFuzzy(const Mesh& mesh)
{
std::vector<PackedVertex> pv(mesh.vertices.size());
packMesh(pv, mesh.vertices);
std::vector<unsigned int> remap(mesh.vertices.size());
double start = timestamp();
size_t up = meshopt_generateVertexRemap(&remap[0], &mesh.indices[0], mesh.indices.size(), &pv[0], mesh.vertices.size(), sizeof(PackedVertex));
double middle = timestamp();
size_t uf = meshopt_generateVertexRemapCustom(&remap[0], &mesh.indices[0], mesh.indices.size(), &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex), reindexCompare, const_cast<Vertex*>(&mesh.vertices[0]));
double end = timestamp();
printf("ReindexQ : %d vertices => %d unique vertices in %.2f msec\n",
int(mesh.vertices.size()), int(up), (middle - start) * 1000);
printf("ReindexF : %d vertices => %d unique vertices in %.2f msec\n",
int(mesh.vertices.size()), int(uf), (end - middle) * 1000);
}
void coverage(const Mesh& mesh)
{
double start = timestamp();
meshopt_CoverageStatistics cs = meshopt_analyzeCoverage(&mesh.indices[0], mesh.indices.size(), &mesh.vertices[0].px, mesh.vertices.size(), sizeof(Vertex));
double end = timestamp();
printf("Coverage : X %.1f%% Y %.1f%% Z %.1f%% in %.2f msec\n",
cs.coverage[0] * 100, cs.coverage[1] * 100, cs.coverage[2] * 100, (end - start) * 1000);
}
void nanite(const std::vector<Vertex>& vertices, const std::vector<unsigned int>& indices); // nanite.cpp
bool loadMesh(Mesh& mesh, const char* path)
{
double start = timestamp();
double middle;
mesh = parseObj(path, middle);
double end = timestamp();
if (mesh.vertices.empty())
{
printf("Mesh %s is empty, skipping\n", path);
return false;
}
printf("# %s: %d vertices, %d triangles; read in %.2f msec; indexed in %.2f msec\n", path, int(mesh.vertices.size()), int(mesh.indices.size() / 3), (middle - start) * 1000, (end - middle) * 1000);
return true;
}
void processDeinterleaved(const char* path)
{
// Most algorithms in the library work out of the box with deinterleaved geometry, but some require slightly special treatment;
// this code runs a simplified version of complete opt. pipeline using deinterleaved geo. There's no compression performed but you
// can trivially run it by quantizing all elements and running meshopt_encodeVertexBuffer once for each vertex stream.
fastObjMesh* obj = fast_obj_read(path);
if (!obj)
{
printf("Error loading %s: file not found\n", path);
return;
}
size_t total_indices = 0;
for (unsigned int i = 0; i < obj->face_count; ++i)
total_indices += 3 * (obj->face_vertices[i] - 2);
std::vector<float> unindexed_pos(total_indices * 3);
std::vector<float> unindexed_nrm(total_indices * 3);
std::vector<float> unindexed_uv(total_indices * 2);
size_t vertex_offset = 0;
size_t index_offset = 0;
for (unsigned int i = 0; i < obj->face_count; ++i)
{
for (unsigned int j = 0; j < obj->face_vertices[i]; ++j)
{
fastObjIndex gi = obj->indices[index_offset + j];
// triangulate polygon on the fly; offset-3 is always the first polygon vertex
if (j >= 3)
{
memcpy(&unindexed_pos[(vertex_offset + 0) * 3], &unindexed_pos[(vertex_offset - 3) * 3], 3 * sizeof(float));
memcpy(&unindexed_nrm[(vertex_offset + 0) * 3], &unindexed_nrm[(vertex_offset - 3) * 3], 3 * sizeof(float));
memcpy(&unindexed_uv[(vertex_offset + 0) * 2], &unindexed_uv[(vertex_offset - 3) * 2], 2 * sizeof(float));
memcpy(&unindexed_pos[(vertex_offset + 1) * 3], &unindexed_pos[(vertex_offset - 1) * 3], 3 * sizeof(float));
memcpy(&unindexed_nrm[(vertex_offset + 1) * 3], &unindexed_nrm[(vertex_offset - 1) * 3], 3 * sizeof(float));
memcpy(&unindexed_uv[(vertex_offset + 1) * 2], &unindexed_uv[(vertex_offset - 1) * 2], 2 * sizeof(float));
vertex_offset += 2;
}
memcpy(&unindexed_pos[vertex_offset * 3], &obj->positions[gi.p * 3], 3 * sizeof(float));
memcpy(&unindexed_nrm[vertex_offset * 3], &obj->normals[gi.n * 3], 3 * sizeof(float));
memcpy(&unindexed_uv[vertex_offset * 2], &obj->texcoords[gi.t * 2], 2 * sizeof(float));
vertex_offset++;
}
index_offset += obj->face_vertices[i];
}
fast_obj_destroy(obj);
double start = timestamp();
meshopt_Stream streams[] = {
{&unindexed_pos[0], sizeof(float) * 3, sizeof(float) * 3},
{&unindexed_nrm[0], sizeof(float) * 3, sizeof(float) * 3},
{&unindexed_uv[0], sizeof(float) * 2, sizeof(float) * 2},
};
std::vector<unsigned int> remap(total_indices);
size_t total_vertices = meshopt_generateVertexRemapMulti(&remap[0], NULL, total_indices, total_indices, streams, sizeof(streams) / sizeof(streams[0]));
std::vector<unsigned int> indices(total_indices);
meshopt_remapIndexBuffer(&indices[0], NULL, total_indices, &remap[0]);
std::vector<float> pos(total_vertices * 3);
meshopt_remapVertexBuffer(&pos[0], &unindexed_pos[0], total_indices, sizeof(float) * 3, &remap[0]);
std::vector<float> nrm(total_vertices * 3);
meshopt_remapVertexBuffer(&nrm[0], &unindexed_nrm[0], total_indices, sizeof(float) * 3, &remap[0]);
std::vector<float> uv(total_vertices * 2);
meshopt_remapVertexBuffer(&uv[0], &unindexed_uv[0], total_indices, sizeof(float) * 2, &remap[0]);
double reindex = timestamp();
meshopt_optimizeVertexCache(&indices[0], &indices[0], total_indices, total_vertices);
meshopt_optimizeVertexFetchRemap(&remap[0], &indices[0], total_indices, total_vertices);
meshopt_remapVertexBuffer(&pos[0], &pos[0], total_vertices, sizeof(float) * 3, &remap[0]);
meshopt_remapVertexBuffer(&nrm[0], &nrm[0], total_vertices, sizeof(float) * 3, &remap[0]);
meshopt_remapVertexBuffer(&uv[0], &uv[0], total_vertices, sizeof(float) * 2, &remap[0]);
double optimize = timestamp();
// note: since shadow index buffer is computed based on regular vertex/index buffer, the stream points at the indexed data - not unindexed_pos
meshopt_Stream shadow_stream = {&pos[0], sizeof(float) * 3, sizeof(float) * 3};
std::vector<unsigned int> shadow_indices(total_indices);
meshopt_generateShadowIndexBufferMulti(&shadow_indices[0], &indices[0], total_indices, total_vertices, &shadow_stream, 1);
meshopt_optimizeVertexCache(&shadow_indices[0], &shadow_indices[0], total_indices, total_vertices);
double shadow = timestamp();
printf("Deintrlvd: %d vertices, reindexed in %.2f msec, optimized in %.2f msec, generated & optimized shadow indices in %.2f msec\n",
int(total_vertices), (reindex - start) * 1000, (optimize - reindex) * 1000, (shadow - optimize) * 1000);
}
void process(const char* path)
{
Mesh mesh;
if (!loadMesh(mesh, path))
return;
optimize(mesh);
optimize(mesh, /* fifo= */ true);
Mesh copy = mesh;
meshopt_optimizeVertexCache(©.indices[0], ©.indices[0], copy.indices.size(), copy.vertices.size());
meshopt_optimizeVertexFetch(©.vertices[0], ©.indices[0], copy.indices.size(), ©.vertices[0], copy.vertices.size(), sizeof(Vertex));
Mesh copystrip = mesh;
meshopt_optimizeVertexCacheStrip(©strip.indices[0], ©strip.indices[0], copystrip.indices.size(), copystrip.vertices.size());
meshopt_optimizeVertexFetch(©strip.vertices[0], ©strip.indices[0], copystrip.indices.size(), ©strip.vertices[0], copystrip.vertices.size(), sizeof(Vertex));
stripify(copy, false, ' ');
stripify(copy, /* use_restart= */ true, 'R');
stripify(copystrip, /* use_restart= */ true, 'S');
meshlets(copy, /* scan= */ true);
meshlets(copy, /* scan= */ false);
meshlets(copy, /* scan= */ false, /* uniform= */ true);
meshlets(copy, /* scan= */ false, /* uniform= */ false, /* flex= */ true);
meshlets(copy, /* scan= */ false, /* uniform= */ true, /* flex= */ false, /* spatial= */ true);
shadow(copy);
tessellationAdjacency(copy);
provoking(copy);
encodeIndex(copy, ' ');
encodeIndex(copystrip, 'S');
std::vector<unsigned int> strip(meshopt_stripifyBound(copystrip.indices.size()));
strip.resize(meshopt_stripify(&strip[0], ©strip.indices[0], copystrip.indices.size(), copystrip.vertices.size(), 0));
encodeIndexSequence(strip, copystrip.vertices.size(), 'D');
packVertex<PackedVertex>(copy, "");
encodeVertex<PackedVertex>(copy, "");
encodeVertex<PackedVertexOct>(copy, "O");
encodeMeshlets(mesh, 64, 96);
simplify(mesh);
simplify(mesh, 0.1f, meshopt_SimplifyPrune);
simplifyAttr(mesh);
simplifyAttr(mesh, 0.1f, meshopt_SimplifyPermissive);
simplifyUpdate(mesh);
simplifyUpdate(mesh, 0.1f, meshopt_SimplifyPermissive);
simplifySloppy(mesh);
simplifyComplete(mesh);
simplifyPoints(mesh);
simplifyClusters(mesh);
spatialSort(mesh);
spatialSortTriangles(mesh);
spatialClusterPoints(mesh, 64);
reindexFuzzy(mesh);
coverage(mesh);
if (path)
processDeinterleaved(path);
}
void processDev(const char* path)
{
Mesh mesh;
if (!loadMesh(mesh, path))
return;
encodeMeshlets(mesh, 32, 48);
encodeMeshlets(mesh, 64, 64);
encodeMeshlets(mesh, 64, 96);
}
void processNanite(const char* path)
{
Mesh mesh;
if (!loadMesh(mesh, path))
return;
nanite(mesh.vertices, mesh.indices);
}
int main(int argc, char** argv)
{
void runTests();
if (argc == 1)
{
runTests();
}
else
{
if (strcmp(argv[1], "-d") == 0)
{
for (int i = 2; i < argc; ++i)
processDev(argv[i]);
}
else if (strcmp(argv[1], "-n") == 0)
{
for (int i = 2; i < argc; ++i)
processNanite(argv[i]);
}
else
{
for (int i = 1; i < argc; ++i)
process(argv[i]);
runTests();
}
}
}
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
demo/nanite.cpp | C++ | // For reference, see the original Nanite paper:
// Brian Karis. Nanite: A Deep Dive. 2021
#include "../src/meshoptimizer.h"
#include <float.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <vector>
#define CLUSTERLOD_IMPLEMENTATION
#include "clusterlod.h"
struct Vertex
{
float px, py, pz;
float nx, ny, nz;
float tx, ty;
};
// computes approximate (perspective) projection error of a cluster in screen space (0..1; multiply by screen height to get pixels)
// camera_proj is projection[1][1], or cot(fovy/2); camera_znear is *positive* near plane distance
// for DAG cut to be valid, boundsError must be monotonic: it must return a larger error for parent cluster
// for simplicity, we ignore perspective distortion and use rotationally invariant projection size estimation
static float boundsError(const clodBounds& bounds, float camera_x, float camera_y, float camera_z, float camera_proj, float camera_znear)
{
float dx = bounds.center[0] - camera_x, dy = bounds.center[1] - camera_y, dz = bounds.center[2] - camera_z;
float d = sqrtf(dx * dx + dy * dy + dz * dz) - bounds.radius;
return bounds.error / (d > camera_znear ? d : camera_znear) * (camera_proj * 0.5f);
}
static int measureComponents(std::vector<int>& parents, const std::vector<unsigned int>& indices, const std::vector<unsigned int>& remap);
static size_t measureBoundary(std::vector<int>& used, const std::vector<std::vector<unsigned int> >& clusters, const std::vector<unsigned int>& remap);
static float sahOverhead(const std::vector<std::vector<unsigned int> >& clusters, const std::vector<Vertex>& vertices);
void dumpObj(const std::vector<Vertex>& vertices, const std::vector<unsigned int>& indices, bool recomputeNormals = false);
void dumpObj(const char* section, const std::vector<unsigned int>& indices);
void nanite(const std::vector<Vertex>& vertices, const std::vector<unsigned int>& indices)
{
#ifdef _MSC_VER
static const char* dump = NULL; // tired of C4996
static const char* clrt = NULL;
#else
static const char* dump = getenv("DUMP");
static const char* clrt = getenv("CLRT");
#endif
clodConfig config = clodDefaultConfig(/*max_triangles=*/128);
if (clrt)
{
config = clodDefaultConfigRT(config.max_triangles);
config.cluster_fill_weight = float(atof(clrt));
}
const float attribute_weights[3] = {0.5f, 0.5f, 0.5f};
clodMesh mesh = {};
mesh.indices = indices.data();
mesh.index_count = indices.size();
mesh.vertex_count = vertices.size();
mesh.vertex_positions = &vertices[0].px;
mesh.vertex_positions_stride = sizeof(Vertex);
mesh.vertex_attributes = &vertices[0].nx;
mesh.vertex_attributes_stride = sizeof(Vertex);
mesh.attribute_weights = attribute_weights;
mesh.attribute_count = sizeof(attribute_weights) / sizeof(attribute_weights[0]);
mesh.attribute_protect_mask = (1 << 3) | (1 << 4); // protect UV seams, maps to Vertex::tx/ty
struct Stats
{
size_t groups;
size_t clusters;
size_t triangles;
size_t vertices;
size_t full_clusters;
size_t singleton_groups;
size_t stuck_clusters;
size_t stuck_triangles;
double radius;
std::vector<std::vector<unsigned int> > indices; // for detailed connectivity analysis
};
std::vector<Stats> stats;
std::vector<clodBounds> groups;
std::vector<std::vector<unsigned int> > cut;
int cut_level = dump ? atoi(dump) : -2;
// for testing purposes, we can compute a DAG cut from a given viewpoint and dump it as an OBJ
float maxx = 0.f, maxy = 0.f, maxz = 0.f;
for (size_t i = 0; i < vertices.size(); ++i)
{
maxx = std::max(maxx, vertices[i].px * 2);
maxy = std::max(maxy, vertices[i].py * 2);
maxz = std::max(maxz, vertices[i].pz * 2);
}
float threshold = 2e-3f; // 2 pixels at 1080p
float fovy = 60.f;
float znear = 1e-2f;
float proj = 1.f / tanf(fovy * 3.1415926f / 180.f * 0.5f);
clodBuild(config, mesh, [&](clodGroup group, const clodCluster* clusters, size_t cluster_count) -> int { // clang-format!
if (stats.size() <= size_t(group.depth))
stats.push_back({});
Stats& level = stats[group.depth];
level.groups++;
level.clusters += cluster_count;
if (group.simplified.error == FLT_MAX)
level.stuck_clusters += cluster_count;
level.singleton_groups += cluster_count == 1;
for (size_t i = 0; i < cluster_count; ++i)
{
const clodCluster& cluster = clusters[i];
level.triangles += cluster.index_count / 3;
if (group.simplified.error == FLT_MAX)
level.stuck_triangles += cluster.index_count / 3;
level.vertices += cluster.vertex_count;
level.full_clusters += (cluster.index_count == config.max_triangles * 3);
level.radius += cluster.bounds.radius;
level.indices.push_back(std::vector<unsigned int>(cluster.indices, cluster.indices + cluster.index_count));
// when requesting DAG cut at a given level, we need to render all terminal clusters at lower depth as well
if (cut_level >= 0 && (group.depth == cut_level || (group.depth < cut_level && group.simplified.error == FLT_MAX)))
cut.push_back(std::vector<unsigned int>(cluster.indices, cluster.indices + cluster.index_count));
// when requesting DAG cut from a viewpoint, we need to check if each cluster is the least detailed cluster that passes the error threshold
if (cut_level == -1 && (cluster.refined < 0 || boundsError(groups[cluster.refined], maxx, maxy, maxz, proj, znear) <= threshold) && boundsError(group.simplified, maxx, maxy, maxz, proj, znear) > threshold)
cut.push_back(std::vector<unsigned int>(cluster.indices, cluster.indices + cluster.index_count));
}
level.indices.push_back(std::vector<unsigned int>()); // mark end of group for measureBoundary
groups.push_back(group.simplified);
return int(groups.size() - 1);
});
// for cluster connectivity analysis and boundary statistics, we need a position-only remap that maps vertices with the same position to the same index
std::vector<unsigned int> remap(vertices.size());
meshopt_generatePositionRemap(&remap[0], &vertices[0].px, vertices.size(), sizeof(Vertex));
std::vector<int> used(vertices.size());
size_t lowest_clusters = 0;
size_t lowest_triangles = 0;
for (size_t i = 0; i < stats.size(); ++i)
{
Stats& level = stats[i];
lowest_clusters += level.stuck_clusters;
lowest_triangles += level.stuck_triangles;
size_t connected = 0;
for (const auto& cluster : level.indices)
connected += measureComponents(used, cluster, remap);
size_t boundary = measureBoundary(used, level.indices, remap);
float saho = clrt ? sahOverhead(level.indices, vertices) : 0.f;
double inv_clusters = 1.0 / double(level.clusters);
printf("lod %d: %d clusters (%.1f%% full, %.1f tri/cl, %.1f vtx/cl, %.2f connected, %.1f boundary, %.1f partition, %d singletons, %.3f sah overhead, %f radius), %d triangles",
int(i), int(level.clusters),
double(level.full_clusters) * inv_clusters * 100, double(level.triangles) * inv_clusters, double(level.vertices) * inv_clusters,
double(connected) * inv_clusters, double(boundary) * inv_clusters,
double(level.clusters) / double(level.groups), int(level.singleton_groups),
saho, level.radius * inv_clusters,
int(level.triangles));
if (level.stuck_clusters && level.clusters > 1)
printf("; stuck %d clusters (%d triangles)", int(level.stuck_clusters), int(level.stuck_triangles));
printf("\n");
}
printf("lowest lod: %d clusters, %d triangles\n", int(lowest_clusters), int(lowest_triangles));
if (cut_level >= -1)
{
size_t cut_tris = 0;
for (auto& cluster : cut)
cut_tris += cluster.size() / 3;
if (cut_level >= 0)
printf("cut (level %d): %d triangles\n", cut_level, int(cut_tris));
else
printf("cut (error %.3f): %d triangles\n", threshold, int(cut_tris));
dumpObj(vertices, std::vector<unsigned int>());
for (auto& cluster : cut)
dumpObj("cluster", cluster);
}
}
// What follows is code that is helpful for collecting metrics, visualizing cuts, etc.
// This code is not used in the actual clustering implementation and can be ignored.
static int follow(std::vector<int>& parents, int index)
{
while (index != parents[index])
{
int parent = parents[index];
parents[index] = parents[parent];
index = parent;
}
return index;
}
static int measureComponents(std::vector<int>& parents, const std::vector<unsigned int>& indices, const std::vector<unsigned int>& remap)
{
assert(parents.size() == remap.size());
for (size_t i = 0; i < indices.size(); ++i)
{
unsigned int v = remap[indices[i]];
parents[v] = v;
}
for (size_t i = 0; i < indices.size(); ++i)
{
int v0 = remap[indices[i]];
int v1 = remap[indices[i + (i % 3 == 2 ? -2 : 1)]];
v0 = follow(parents, v0);
v1 = follow(parents, v1);
parents[v0] = v1;
}
for (size_t i = 0; i < indices.size(); ++i)
{
unsigned int v = remap[indices[i]];
parents[v] = follow(parents, v);
}
int roots = 0;
for (size_t i = 0; i < indices.size(); ++i)
{
unsigned int v = remap[indices[i]];
roots += parents[v] == int(v);
parents[v] = -1; // make sure we only count each root once
}
return roots;
}
static size_t measureBoundary(std::vector<int>& used, const std::vector<std::vector<unsigned int> >& clusters, const std::vector<unsigned int>& remap)
{
for (size_t i = 0; i < used.size(); ++i)
used[i] = -1;
// mark vertices that are used by multiple groups with -2
int group = 0;
for (size_t i = 0; i < clusters.size(); ++i)
{
group += clusters[i].empty();
for (size_t j = 0; j < clusters[i].size(); ++j)
{
unsigned int v = remap[clusters[i][j]];
used[v] = (used[v] == -1 || used[v] == group) ? group : -2;
}
}
size_t result = 0;
for (size_t i = 0; i < clusters.size(); ++i)
{
// count vertices that are used by multiple groups and change marks to -1
for (size_t j = 0; j < clusters[i].size(); ++j)
{
unsigned int v = remap[clusters[i][j]];
result += (used[v] == -2);
used[v] = (used[v] == -2) ? -1 : used[v];
}
// change marks back from -1 to -2 for the next pass
for (size_t j = 0; j < clusters[i].size(); ++j)
{
unsigned int v = remap[clusters[i][j]];
used[v] = (used[v] == -1) ? -2 : used[v];
}
}
return int(result);
}
struct Box
{
float min[3];
float max[3];
};
static const Box kDummyBox = {{FLT_MAX, FLT_MAX, FLT_MAX}, {-FLT_MAX, -FLT_MAX, -FLT_MAX}};
static void mergeBox(Box& box, const Box& other)
{
for (int k = 0; k < 3; ++k)
{
box.min[k] = other.min[k] < box.min[k] ? other.min[k] : box.min[k];
box.max[k] = other.max[k] > box.max[k] ? other.max[k] : box.max[k];
}
}
inline float surface(const Box& box)
{
float sx = box.max[0] - box.min[0], sy = box.max[1] - box.min[1], sz = box.max[2] - box.min[2];
return sx * sy + sx * sz + sy * sz;
}
static float sahCost(const Box* boxes, unsigned int* order, unsigned int* temp, size_t count)
{
Box total = boxes[order[0]];
for (size_t i = 1; i < count; ++i)
mergeBox(total, boxes[order[i]]);
int best_axis = -1;
int best_bin = -1;
float best_cost = FLT_MAX;
const int kBins = 15;
for (int axis = 0; axis < 3; ++axis)
{
Box bins[kBins];
unsigned int counts[kBins] = {};
float extent = total.max[axis] - total.min[axis];
if (extent <= 0.f)
continue;
for (int i = 0; i < kBins; ++i)
bins[i] = kDummyBox;
for (size_t i = 0; i < count; ++i)
{
unsigned int index = order[i];
float p = (boxes[index].min[axis] + boxes[index].max[axis]) * 0.5f;
int bin = int((p - total.min[axis]) / extent * (kBins - 1) + 0.5f);
assert(bin >= 0 && bin < kBins);
mergeBox(bins[bin], boxes[index]);
counts[bin]++;
}
Box laccum = kDummyBox, raccum = kDummyBox;
size_t lcount = 0, rcount = 0;
float costs[kBins] = {};
for (int i = 0; i < kBins - 1; ++i)
{
mergeBox(laccum, bins[i]);
mergeBox(raccum, bins[kBins - 1 - i]);
lcount += counts[i];
costs[i] += lcount ? surface(laccum) * lcount : 0.f;
rcount += counts[kBins - 1 - i];
costs[kBins - 2 - i] += rcount ? surface(raccum) * rcount : 0.f;
}
for (int i = 0; i < kBins - 1; ++i)
if (costs[i] < best_cost)
{
best_cost = costs[i];
best_bin = i;
best_axis = axis;
}
}
if (best_axis == -1)
return surface(total) * float(count);
float best_extent = total.max[best_axis] - total.min[best_axis];
size_t offset0 = 0, offset1 = count;
for (size_t i = 0; i < count; ++i)
{
unsigned int index = order[i];
float p = (boxes[index].min[best_axis] + boxes[index].max[best_axis]) * 0.5f;
int bin = int((p - total.min[best_axis]) / best_extent * (kBins - 1) + 0.5f);
assert(bin >= 0 && bin < kBins);
if (bin <= best_bin)
temp[offset0++] = index;
else
temp[--offset1] = index;
}
assert(offset0 == offset1);
if (offset0 == 0 || offset0 == count)
return surface(total) * float(count);
return surface(total) + sahCost(boxes, temp, order, offset0) + sahCost(boxes, temp + offset0, order + offset0, count - offset0);
}
static float sahCost(const Box* boxes, size_t count)
{
if (count == 0)
return 0.f;
std::vector<unsigned int> order(count);
for (size_t i = 0; i < count; ++i)
order[i] = unsigned(i);
std::vector<unsigned int> temp(count);
return sahCost(boxes, &order[0], &temp[0], count);
}
static float sahOverhead(const std::vector<std::vector<unsigned int> >& clusters, const std::vector<Vertex>& vertices)
{
std::vector<Box> all_tris, cluster_tris, cluster_boxes;
float sahc = 0.f;
for (size_t i = 0; i < clusters.size(); ++i)
{
if (clusters[i].empty())
continue;
cluster_tris.clear();
Box cluster_box = kDummyBox;
for (size_t k = 0; k < clusters[i].size(); k += 3)
{
Box box = kDummyBox;
for (int v = 0; v < 3; ++v)
{
const Vertex& vertex = vertices[clusters[i][k + v]];
Box p = {{vertex.px, vertex.py, vertex.pz}, {vertex.px, vertex.py, vertex.pz}};
mergeBox(box, p);
}
mergeBox(cluster_box, box);
all_tris.push_back(box);
cluster_tris.push_back(box);
}
cluster_boxes.push_back(cluster_box);
sahc += sahCost(&cluster_tris[0], cluster_tris.size());
sahc -= surface(cluster_box); // box will be accounted for in tlas
}
sahc += sahCost(&cluster_boxes[0], cluster_boxes.size());
float saht = sahCost(all_tris.data(), all_tris.size());
return sahc / saht;
}
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
demo/simplify.html | HTML | <!doctype html>
<html lang="en">
<head>
<title>meshoptimizer - demo</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0" />
<style>
body {
font-family: Monospace;
background-color: #300a24;
color: #fff;
margin: 0px;
overflow: hidden;
display: flex;
flex-direction: column;
height: 100vh;
}
#info {
color: #fff;
position: absolute;
top: 10px;
width: 100%;
text-align: center;
z-index: 100;
display: block;
}
#info a,
.button {
color: #f00;
font-weight: bold;
text-decoration: underline;
cursor: pointer;
}
#grid-container {
width: 100%;
flex: 1;
display: grid;
grid-template-columns: repeat(var(--grid-columns, 1), 1fr);
grid-auto-rows: minmax(300px, 1fr);
overflow-y: auto;
}
.renderer-container {
position: relative;
width: 100%;
height: 100%;
}
.renderer-container canvas {
width: 100% !important;
height: 100% !important;
display: block;
user-select: none;
}
.renderer-label {
position: absolute;
top: 10px;
left: 10px;
background-color: rgba(0, 0, 0, 0.5);
padding: 5px 10px;
border-radius: 5px;
pointer-events: auto;
font-size: 14px;
transition: background-color 0.2s;
}
.renderer-label:hover {
background-color: rgba(0, 0, 0, 0.7);
}
.renderer-label.focused {
background-color: rgba(255, 100, 100, 0.7);
color: white;
}
.renderer-label.clickable {
cursor: pointer;
}
.stats-label {
position: absolute;
top: 45px;
left: 10px;
background-color: rgba(0, 0, 0, 0.5);
padding: 5px 10px;
border-radius: 5px;
pointer-events: none;
font-size: 12px;
line-height: 1.4;
}
.renderer-container.hidden {
display: none;
}
/* Custom scrollbar styling */
#grid-container::-webkit-scrollbar {
width: 16px;
}
#grid-container::-webkit-scrollbar-track {
background: rgba(255, 255, 255, 0.1);
}
#grid-container::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.3);
border-radius: 8px;
}
#grid-container::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.5);
}
</style>
<script type="importmap">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.174.0/build/three.module.js",
"three-examples/": "https://cdn.jsdelivr.net/npm/three@0.174.0/examples/jsm/",
"lil-gui": "https://cdn.jsdelivr.net/npm/lil-gui@0.20.0/dist/lil-gui.esm.js"
}
}
</script>
</head>
<body>
<div id="grid-container"></div>
<input type="file" id="fileInput" style="display: none" accept=".obj,.glb" multiple />
<script type="module">
import * as THREE from 'three';
import { GLTFLoader } from 'three-examples/loaders/GLTFLoader.js';
import { OBJLoader } from 'three-examples/loaders/OBJLoader.js';
import { OrbitControls } from 'three-examples/controls/OrbitControls.js';
import { mergeGeometries, mergeVertices } from 'three-examples/utils/BufferGeometryUtils.js';
import { MeshoptDecoder } from '../js/meshopt_decoder.mjs';
import { MeshoptSimplifier } from '../js/meshopt_simplifier.js';
import { GUI } from 'lil-gui';
var container, gridContainer;
var camera, clock;
var renderers = [];
var scenes = [];
var controls = [];
var models = [];
var mixers = [];
var viewStats = [];
// Focus tracking
var focusedViewIndex = -1; // -1 means no focus (show all)
// Track camera distance for autoLod
var lastCameraDistance = 0;
var settings = {
wireframe: false,
wireframeOverlay: false,
animate: false,
pointSize: 1.0,
ratio: 1.0,
debugOverlay: false,
sloppy: false,
permissive: false,
permissiveProtection: 2, // uvs
lockBorder: false,
preprune: 0.0,
prune: true,
regularize: false,
solve: false,
useAttributes: true,
autoTextureWeight: false,
errorThresholdLog10: 1,
errorScaled: true,
normalWeight: 1.0,
colorWeight: 1.0,
textureWeight: 0.0,
autoLod: false,
autoLodFactor: 1.0,
gridColumns: 2,
debugCheckerboard: false,
loadFile: function () {
var input = document.getElementById('fileInput');
input.onchange = function () {
var files = Array.from(input.files).sort(function (a, b) {
var an = a.name.split('.')[0];
var bn = b.name.split('.')[0];
return an.localeCompare(bn);
});
loadFiles(files);
};
input.click();
},
updateModule: function () {
reload();
simplify();
},
autoUpdate: false,
autoUpdateStatus: '',
};
var gui = new GUI({ width: 300 });
var guiDisplay = gui.addFolder('Display');
guiDisplay.add(settings, 'wireframe').onChange(update);
guiDisplay.add(settings, 'wireframeOverlay').onChange(simplify); // requires debug data rebuild
guiDisplay.add(settings, 'animate').onChange(update);
guiDisplay.add(settings, 'pointSize', 1, 16).onChange(update);
guiDisplay.add(settings, 'debugOverlay').onChange(simplify); // requires debug data rebuild
guiDisplay.add(settings, 'gridColumns', 1, 6, 1).onChange(updateGridLayout);
var guiSimplify = gui.addFolder('Simplify');
guiSimplify.add(settings, 'ratio', 0, 1, 0.01).onChange(simplify);
guiSimplify.add(settings, 'sloppy').onChange(simplify);
guiSimplify.add(settings, 'permissive').onChange(simplify);
guiSimplify.add(settings, 'permissiveProtection', { none: 0, uvs: 2, normals: 1, all: 3 }).onChange(simplify);
guiSimplify.add(settings, 'lockBorder').onChange(simplify);
guiSimplify.add(settings, 'prune').onChange(simplify);
guiSimplify.add(settings, 'regularize').onChange(simplify);
guiSimplify.add(settings, 'solve').onChange(simplify);
guiSimplify.add(settings, 'preprune', 0, 0.2, 0.01).onChange(simplify);
guiSimplify.add(settings, 'useAttributes').onChange(simplify).onFinishChange(updateSettings);
var guiAttributes = [];
guiAttributes.push(guiSimplify.add(settings, 'normalWeight', 0, 2, 0.01).onChange(simplify));
guiAttributes.push(guiSimplify.add(settings, 'colorWeight', 0, 2, 0.01).onChange(simplify));
guiAttributes.push(guiSimplify.add(settings, 'textureWeight', 0, 100, 0.1).onChange(simplify));
guiSimplify.add(settings, 'autoTextureWeight').onChange(simplify);
guiSimplify.add(settings, 'errorScaled').onChange(simplify);
guiSimplify.add(settings, 'errorThresholdLog10', 0, 3, 0.1).onChange(simplify);
var guiLod = gui.addFolder('LOD');
guiLod.add(settings, 'autoLod').onChange(simplify);
guiLod.add(settings, 'autoLodFactor', 0, 10, 0.01).onChange(simplify);
var guiLoad = gui.addFolder('Load');
guiLoad.add(settings, 'loadFile');
guiLoad.add(settings, 'updateModule');
guiLoad.add(settings, 'debugCheckerboard');
guiLoad.add(settings, 'autoUpdate').onChange(autoReload);
guiLoad.add(settings, 'autoUpdateStatus').listen();
updateSettings();
init();
loadDefault();
animate();
function loadFiles(files) {
// Clear existing views
clearViews();
if (files.length > 0) {
// Set grid columns based on the number of files, up to the max setting
const columns = Math.min(files.length, settings.gridColumns);
document.documentElement.style.setProperty('--grid-columns', columns);
// Load each file into a separate view
for (var i = 0; i < files.length; i++) {
var file = files[i];
var uri = URL.createObjectURL(file);
var ext = file.name.split('.').pop().toLowerCase();
createView(i, file.name);
loadIntoView(i, uri, ext);
}
}
}
function updateGridLayout() {
if (renderers.length > 0) {
var visibleViews = focusedViewIndex >= 0 ? 1 : renderers.length;
var columns = Math.min(visibleViews, settings.gridColumns);
document.documentElement.style.setProperty('--grid-columns', columns);
// Set grid cell height based on whether we're in single view or grid mode
if (columns > 1) {
// In grid mode, make cells square by calculating height based on viewport width
var cellWidth = Math.floor(window.innerWidth / columns);
document.documentElement.style.setProperty('--grid-cell-height', cellWidth + 'px');
} else {
// Single view mode, use full height
document.documentElement.style.setProperty('--grid-cell-height', '100vh');
}
updateRendererSizes();
}
}
// Helper function to handle autoLOD updates - no longer tied to camera rotation
function updateAutoLod() {
if (settings.autoLod) {
// Check if distance has changed significantly
var center = new THREE.Vector3();
var currentDistance = camera.position.distanceTo(center);
if (Math.abs(currentDistance - lastCameraDistance) > 1e-3) {
lastCameraDistance = currentDistance;
simplify();
}
}
}
function updateSettings() {
for (var i = 0; i < guiAttributes.length; ++i) {
guiAttributes[i].enable(settings.useAttributes);
}
}
function clearViews() {
// Remove all existing renderers and clear arrays
for (var i = 0; i < renderers.length; i++) {
var container = renderers[i].domElement.parentElement;
if (container) {
container.parentElement.removeChild(container);
}
}
renderers = [];
scenes = [];
controls = [];
models = [];
mixers = [];
viewStats = [];
// Reset focus state
focusedViewIndex = -1;
// Clear the grid container
gridContainer.innerHTML = '';
}
function updateLabelsClickability() {
var isClickable = renderers.length > 1;
for (var i = 0; i < renderers.length; i++) {
var container = renderers[i].domElement.parentElement;
var label = container.querySelector('.renderer-label');
if (isClickable) {
label.classList.add('clickable');
label.title = 'Click to focus on this view';
} else {
label.classList.remove('clickable');
label.title = '';
}
}
}
function toggleFocus(viewIndex) {
if (focusedViewIndex === viewIndex) {
// Currently focused on this view, unfocus (show all)
focusedViewIndex = -1;
} else {
// Focus on this view
focusedViewIndex = viewIndex;
}
updateFocusDisplay();
simplify(); // Re-run simplify with new focus state
}
function updateFocusDisplay() {
for (var i = 0; i < renderers.length; i++) {
var container = renderers[i].domElement.parentElement;
var label = container.querySelector('.renderer-label');
if (focusedViewIndex === -1) {
// No focus - show all containers
container.classList.remove('hidden');
label.classList.remove('focused');
if (renderers.length > 1) {
label.title = 'Click to focus on this view';
}
} else if (focusedViewIndex === i) {
// This is the focused view
container.classList.remove('hidden');
label.classList.add('focused');
label.title = 'Click to exit focus mode';
} else {
// Hide non-focused views
container.classList.add('hidden');
label.classList.remove('focused');
}
}
// Update grid layout when focus changes
updateGridLayout();
}
function createView(index, name) {
// Create renderer container
var rendererContainer = document.createElement('div');
rendererContainer.className = 'renderer-container';
gridContainer.appendChild(rendererContainer);
// Add label with file name
var label = document.createElement('div');
label.className = 'renderer-label';
label.textContent = name;
label.onclick = function () {
if (renderers.length > 1) {
toggleFocus(index);
}
};
rendererContainer.appendChild(label);
// Add stats label
var statsLabel = document.createElement('div');
statsLabel.className = 'stats-label';
rendererContainer.appendChild(statsLabel);
// Initialize stats for this view
viewStats.push({
triangles: 0,
vertices: 0,
error: 0,
ratio: 0,
label: statsLabel,
});
// Create renderer
var renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
rendererContainer.appendChild(renderer.domElement);
renderers.push(renderer);
// Create scene
var scene = new THREE.Scene();
scene.background = new THREE.Color(0x300a24);
scenes.push(scene);
// Add lighting
var ambientLight = new THREE.AmbientLight(0xcccccc, 1);
scene.add(ambientLight);
var pointLightR = new THREE.PointLight(0xffffff, 4);
pointLightR.position.set(3, 3, 0);
pointLightR.decay = 0.5;
scene.add(pointLightR);
var pointLightL = new THREE.PointLight(0xffffff, 1);
pointLightL.position.set(-3, 5, 0);
pointLightL.decay = 0.5;
scene.add(pointLightL);
// Create controls
var control = new OrbitControls(camera, renderer.domElement);
control.addEventListener('change', updateAutoLod);
controls.push(control);
// Set null placeholders
models.push(null);
mixers.push(null);
// Adjust renderer size
updateRendererSizes();
// Update label clickability for all views
updateLabelsClickability();
}
function simplifyMesh(geo, threshold, scale) {
var attributes = 8; // 3 color, 3 normal, 2 uv
var positions = new Float32Array(geo.attributes.position.array).slice(); // clone for solve
var indices = new Uint32Array(geo.index.array).slice(); // clone for solve, upcast 16-bit indices for _InternalDebug
var target = settings.autoLod ? 0 : Math.floor((indices.length * settings.ratio) / 3) * 3;
var stride = geo.attributes.position instanceof THREE.InterleavedBufferAttribute ? geo.attributes.position.data.stride : 3;
if (settings.useAttributes) {
var attrib = new Float32Array(geo.attributes.position.count * attributes);
for (var i = 0, e = geo.attributes.position.count; i < e; ++i) {
if (geo.attributes.normal) {
attrib[i * attributes + 0] = geo.attributes.normal.getX(i);
attrib[i * attributes + 1] = geo.attributes.normal.getY(i);
attrib[i * attributes + 2] = geo.attributes.normal.getZ(i);
}
if (geo.attributes.color) {
attrib[i * attributes + 3] = geo.attributes.color.getX(i);
attrib[i * attributes + 4] = geo.attributes.color.getY(i);
attrib[i * attributes + 5] = geo.attributes.color.getZ(i);
}
if (geo.attributes.uv) {
attrib[i * attributes + 6] = geo.attributes.uv.getX(i);
attrib[i * attributes + 7] = geo.attributes.uv.getY(i);
}
}
var autoTextureWeight = 0;
if (settings.autoTextureWeight && geo.attributes.uv) {
for (var i = 0, e = geo.index.count; i < e; i += 3) {
var a = geo.index.getX(i),
b = geo.index.getX(i + 1),
c = geo.index.getX(i + 2);
var au = geo.attributes.uv.getX(a),
av = geo.attributes.uv.getY(a);
var bu = geo.attributes.uv.getX(b),
bv = geo.attributes.uv.getY(b);
var cu = geo.attributes.uv.getX(c),
cv = geo.attributes.uv.getY(c);
var uvarea = Math.abs((bu - au) * (cv - av) - (cu - au) * (bv - av)) * 0.5;
autoTextureWeight += uvarea;
}
autoTextureWeight /= geo.index.count / 3;
autoTextureWeight = autoTextureWeight > 0 ? 1 / Math.sqrt(autoTextureWeight) : 0;
}
var attrib_weights = [
settings.normalWeight,
settings.normalWeight,
settings.normalWeight,
settings.colorWeight,
settings.colorWeight,
settings.colorWeight,
settings.autoTextureWeight ? autoTextureWeight : settings.textureWeight,
settings.autoTextureWeight ? autoTextureWeight : settings.textureWeight,
];
} else {
var attrib = new Float32Array();
var attrib_weights = [];
attributes = 0;
}
var flags = [];
if (settings.lockBorder) {
flags.push('LockBorder');
}
if (settings.prune) {
flags.push('Prune');
}
if (settings.regularize) {
flags.push('Regularize');
}
if (settings.permissive) {
flags.push('Permissive');
}
if (settings.debugOverlay) {
flags.push('_InternalDebug');
}
var locks = new Uint8Array(geo.attributes.position.count);
if (settings.permissive) {
var pos_remap = MeshoptSimplifier.generatePositionRemap(positions, stride);
var protect_bit = 2;
if (geo.attributes.normal && (settings.permissiveProtection & 1) != 0) {
for (var i = 0, e = geo.attributes.position.count; i < e; ++i) {
if (pos_remap[i] != i) {
var rx = geo.attributes.normal.getX(pos_remap[i]),
ry = geo.attributes.normal.getY(pos_remap[i]),
rz = geo.attributes.normal.getZ(pos_remap[i]);
var nx = geo.attributes.normal.getX(i),
ny = geo.attributes.normal.getY(i),
nz = geo.attributes.normal.getZ(i);
// keep sharp edges
if (rx * nx + ry * ny + rz * nz < 0.25) {
locks[i] |= protect_bit;
}
}
}
}
if (geo.attributes.uv && (settings.permissiveProtection & 2) != 0) {
for (var i = 0, e = geo.attributes.position.count; i < e; ++i) {
if (pos_remap[i] != i) {
var ru = geo.attributes.uv.getX(pos_remap[i]),
rv = geo.attributes.uv.getY(pos_remap[i]);
var u = geo.attributes.uv.getX(i),
v = geo.attributes.uv.getY(i);
// keep UV seams
if (u != ru || v != rv) {
locks[i] |= protect_bit;
}
}
}
}
}
if (settings.preprune > 0) {
indices = MeshoptSimplifier.simplifyPrune(indices, positions, stride, settings.preprune / scale);
target = Math.min(target, indices.length);
}
var S = MeshoptSimplifier; // to avoid line breaks below...
var res = settings.sloppy
? S.simplifySloppy(indices, positions, stride, null, target, threshold)
: settings.solve
? S.simplifyWithUpdate(indices, positions, stride, attrib, attributes, attrib_weights, locks, target, threshold, flags)
: S.simplifyWithAttributes(indices, positions, stride, attrib, attributes, attrib_weights, locks, target, threshold, flags);
if (!settings.sloppy && settings.solve) {
res[0] = indices.slice(0, res[0]);
}
var rgeo = geo.clone();
var dind = res[0];
var dlen = dind.length;
if (settings.debugOverlay) {
// we need extra indices for debug overlay
dind = Array.from(dind);
var mask = (1 << 28) - 1;
for (var kind = 1; kind <= 6; ++kind) {
var offset = dind.length;
for (var i = 0; i < dlen; i += 3) {
for (var e = 0; e < 3; ++e) {
var a = dind[i + e],
b = dind[i + ((e + 1) % 3)];
var ak = (a >> 28) & 7,
bk = (b >> 28) & 7;
if (a >> 31 != 0 && (ak == kind || bk == kind) && (ak == kind || ak == 4) && (bk == kind || bk == 4)) {
// loop edge of current kind (allow one of the vertices to be locked)
// note: complex edges ignore loop metadata
dind.push(a & mask);
dind.push(a & mask);
dind.push(b & mask);
} else if (a >> 31 != 0 && kind == 5 && ak != bk && ak != 4 && bk != 4) {
// mixed edge (neither vertex is locked, and they are of different kinds)
dind.push(a & mask);
dind.push(a & mask);
dind.push(b & mask);
} else if (a >> 31 == 0 && kind == 4 && ak == kind && bk == kind) {
// locked edge (not marked as a loop)
dind.push(a & mask);
dind.push(a & mask);
dind.push(b & mask);
} else if (a >> 31 == 0 && kind == 6 && ak == 3 && bk == 3) {
// complex edge (not marked as a loop)
dind.push(a & mask);
dind.push(a & mask);
dind.push(b & mask);
}
}
}
if (offset != dind.length) {
rgeo.addGroup(offset, dind.length - offset, kind + 1); // +1 to skip overlay
offset = dind.length;
}
}
// clear debug bits for actual indices
for (var i = 0; i < dlen; i++) {
dind[i] &= mask;
}
if (settings.wireframeOverlay) {
rgeo.addGroup(0, dlen, 1); // 1=overlay
}
} else if (settings.wireframeOverlay) {
rgeo.addGroup(0, dind.length, 1); // 1=overlay
}
rgeo.index.array = new Uint32Array(dind);
rgeo.index.count = dind.length;
rgeo.index.needsUpdate = true;
if (settings.solve) {
rgeo.attributes.position = new THREE.BufferAttribute(positions, stride);
if (settings.useAttributes) {
for (var i = 0, e = geo.attributes.position.count; i < e; ++i) {
var nx = attrib[i * attributes + 0];
var ny = attrib[i * attributes + 1];
var nz = attrib[i * attributes + 2];
var nl = Math.sqrt(nx * nx + ny * ny + nz * nz);
if (nl > 0) {
attrib[i * attributes + 0] = nx / nl;
attrib[i * attributes + 1] = ny / nl;
attrib[i * attributes + 2] = nz / nl;
}
}
var attribbuf = new THREE.InterleavedBuffer(attrib, attrib_weights.length);
if (geo.attributes.normal) {
rgeo.attributes.normal = new THREE.InterleavedBufferAttribute(attribbuf, 3, 0, false);
}
if (geo.attributes.color) {
rgeo.attributes.color = new THREE.InterleavedBufferAttribute(attribbuf, 3, 3, false);
}
if (geo.attributes.uv) {
rgeo.attributes.uv = new THREE.InterleavedBufferAttribute(attribbuf, 2, 6, false);
}
}
}
rgeo.addGroup(0, dlen, 0);
return [rgeo, dlen / 3, res[1]];
}
function simplifyPoints(geo) {
var positions = new Float32Array(geo.attributes.position.array);
var colors = undefined;
var target = Math.floor(geo.attributes.position.count * settings.ratio);
if (settings.useAttributes && geo.attributes.color) {
colors = new Float32Array(geo.attributes.color.array);
}
var pos_stride = geo.attributes.position instanceof THREE.InterleavedBufferAttribute ? geo.attributes.position.data.stride : 3;
var col_stride =
geo.attributes.color instanceof THREE.InterleavedBufferAttribute
? geo.attributes.color.data.stride
: geo.attributes.color.itemSize;
// note: we are converting source color array without normalization; if the color data is quantized, we need to divide by 255 to normalize it
var colorScale = geo.attributes.color && geo.attributes.color.normalized ? 255 : 1;
console.time('simplify');
var res = MeshoptSimplifier.simplifyPoints(positions, pos_stride, target, colors, col_stride, settings.colorWeight / colorScale);
console.timeEnd('simplify');
console.log('simplified to', res.length);
geo.index = new THREE.BufferAttribute(res, 1);
}
function getRadius(obj) {
var box = new THREE.Box3().setFromObject(obj);
return box.max.sub(box.min).length() / 2;
}
function simplify() {
MeshoptSimplifier.ready.then(function () {
var threshold = Math.pow(10, -settings.errorThresholdLog10);
if (settings.autoLod) {
// compute distance to model sphere
// ideally this should actually use the real radius and center :) but we rescale/center the model when loading
var center = new THREE.Vector3();
var radius = 1;
var distance = Math.max(camera.position.distanceTo(center) - radius, 0);
var loderrortarget = 1e-3 * (2 * Math.tan(camera.fov * 0.5 * (Math.PI / 180))); // ~1 pixel at 1k x 1k
// note: we are currently cutting corners wrt handling the actual mesh scale
// since we rescale the entire scene to fit a unit box, we can directly feed the threshold
// this works correctly if there's just one mesh or scales match; ideally we tweak this to compute
// threshold per mesh based on relative scale between mesh and scene.
// this also computes distance to model *center* instead of surface boundary so features on the boundary
// might be simplified more than they should be.
threshold = distance * loderrortarget * settings.autoLodFactor;
}
// Process each scene
for (var sceneIndex = 0; sceneIndex < scenes.length; sceneIndex++) {
var scene = scenes[sceneIndex];
if (focusedViewIndex >= 0 && sceneIndex != focusedViewIndex) {
continue;
}
// Reset stats for this view
var stats = viewStats[sceneIndex];
stats.triangles = 0;
stats.vertices = 0;
stats.error = 0;
stats.ratio = 0;
var rnum = 0;
var rden = 0;
var extent = getRadius(scene);
scene.traverse(function (object) {
if (object.isMesh && object.geometry.index) {
if (!object.original) {
object.original = object.geometry.clone();
// use small depth offset to avoid overlay z-fighting with the original mesh
// has to be done on the main material as overlays use lines that don't support depth offset
object.material.polygonOffset = true;
object.material.polygonOffsetFactor = 0.5;
object.material.polygonOffsetUnits = 16;
object.material = [
object.material,
new THREE.MeshBasicMaterial({ color: 0xffffff, wireframe: true }), // overlay
new THREE.MeshBasicMaterial({ color: 0x0000ff, wireframe: true }), // border
new THREE.MeshBasicMaterial({ color: 0x00ff00, wireframe: true }), // seam
new THREE.MeshBasicMaterial({ color: 0x009f9f, wireframe: true }), // complex
new THREE.MeshBasicMaterial({ color: 0xff0000, wireframe: true }), // locked
new THREE.MeshBasicMaterial({ color: 0xff9f00, wireframe: true }), // mixed edge
new THREE.MeshBasicMaterial({ color: 0x9f5f9f, wireframe: true }), // complex, no loop
];
}
var scale = settings.errorScaled ? getRadius(object) / extent : 1.0;
var [geo, tri, err] = simplifyMesh(object.original, threshold / scale, scale);
object.geometry = geo;
stats.error = Math.max(stats.error, err * scale);
stats.triangles += tri;
stats.vertices += object.geometry.attributes.position.count;
rnum += tri;
rden += object.original.index.count / 3;
}
if (object.isPoints) {
simplifyPoints(object.geometry);
stats.vertices += object.geometry.index.count;
rnum += object.geometry.index.count;
rden += object.geometry.attributes.position.count;
}
});
stats.ratio = rden > 0 ? (rnum / rden) * 100 : 0;
// Update stats display for this view
updateStatsDisplay(sceneIndex);
}
});
}
function updateStatsDisplay(viewIndex) {
if (viewIndex >= 0 && viewIndex < viewStats.length) {
var stats = viewStats[viewIndex];
stats.label.innerHTML =
'Triangles: ' +
stats.triangles +
'<br>' +
'Vertices: ' +
stats.vertices +
'<br>' +
'Error: ' +
stats.error.toExponential(3) +
'<br>' +
'Ratio: ' +
stats.ratio.toFixed(1) +
'%';
}
}
function reload() {
var simp = import('/js/meshopt_simplifier.js?x=' + Date.now());
MeshoptSimplifier.ready = simp.then(function (s) {
return s.MeshoptSimplifier.ready.then(function () {
for (var prop in s.MeshoptSimplifier) {
MeshoptSimplifier[prop] = s.MeshoptSimplifier[prop];
}
});
});
}
var moduleLastModified = 0;
function autoReload() {
if (!settings.autoUpdate) return;
fetch('/js/meshopt_simplifier.js?x=' + Date.now(), { method: 'HEAD' })
.then(function (r) {
var last = r.headers.get('Last-Modified');
if (last != moduleLastModified) {
moduleLastModified = last;
reload();
simplify();
}
settings.autoUpdateStatus = new Date(last).toLocaleTimeString();
setTimeout(autoReload, 1000);
})
.catch(function (e) {
settings.autoUpdateStatus = 'error';
setTimeout(autoReload, 5000);
});
}
function update() {
for (var sceneIndex = 0; sceneIndex < scenes.length; sceneIndex++) {
var scene = scenes[sceneIndex];
scene.traverse(function (child) {
if (child.isMesh) {
if (Array.isArray(child.material)) {
child.material[0].wireframe = settings.wireframe;
} else {
child.material.wireframe = settings.wireframe;
}
}
if (child.isPoints) {
child.material.size = settings.pointSize;
}
});
}
}
function loadIntoView(viewIndex, path, ext) {
if (models[viewIndex]) {
scenes[viewIndex].remove(models[viewIndex]);
models[viewIndex] = undefined;
mixers[viewIndex] = undefined;
}
var onProgress = function (xhr) {};
var onError = function (e) {
console.log(e);
};
function center(model) {
var bbox = new THREE.Box3().setFromObject(model);
var scale = 2 / Math.max(bbox.max.x - bbox.min.x, bbox.max.y - bbox.min.y, bbox.max.z - bbox.min.z);
var offset = new THREE.Vector3().addVectors(bbox.max, bbox.min).multiplyScalar(scale / 2);
model.scale.set(scale, scale, scale);
model.position.set(-offset.x, -offset.y, -offset.z);
}
if (ext == 'gltf' || ext == 'glb') {
var loader = new GLTFLoader();
loader.setMeshoptDecoder(MeshoptDecoder);
loader.load(
path,
function (gltf) {
models[viewIndex] = gltf.scene;
center(models[viewIndex]);
scenes[viewIndex].add(models[viewIndex]);
mixers[viewIndex] = new THREE.AnimationMixer(models[viewIndex]);
if (gltf.animations.length) {
mixers[viewIndex].clipAction(gltf.animations[gltf.animations.length - 1]).play();
}
// Apply simplification
simplify();
},
onProgress,
onError
);
} else if (ext == 'obj') {
var loader = new OBJLoader();
loader.load(
path,
function (obj) {
var geos = [];
obj.traverse(function (node) {
if (node.isMesh) {
// obj loader does not index the geometry, so we need to do it ourselves
node.geometry = mergeVertices(node.geometry);
// we use groups and multiple materials for debug visualization, so merge all of the source ones for now
if (Array.isArray(node.material)) {
node.material = node.material[0];
node.geometry.clearGroups();
}
geos.push(node.geometry);
}
});
// try to merge geometries into a single mesh; this cleanly handles material boundaries and separate objects
// it may fail if the geometries are incompatible (different attributes), in which case we just use the original object
var merged = mergeGeometries(geos);
if (merged) {
if (settings.debugCheckerboard) {
var cb = new THREE.TextureLoader().load(
'https://threejs.org/examples/textures/floors/FloorsCheckerboard_S_Diffuse.jpg'
);
cb.wrapS = THREE.RepeatWrapping;
cb.wrapT = THREE.RepeatWrapping;
cb.repeat.set(8, 8); // Adjust for number of repetitions
var mat = new THREE.MeshStandardMaterial({ map: cb });
} else {
var mat = new THREE.MeshStandardMaterial({ color: 0xdddddd });
}
models[viewIndex] = new THREE.Mesh(merged, mat);
} else {
models[viewIndex] = obj;
}
center(models[viewIndex]);
scenes[viewIndex].add(models[viewIndex]);
// Apply simplification
simplify();
},
onProgress,
onError
);
} else {
console.error('Unsupported file format');
}
}
function loadDefault() {
// Create a single view with the default model
document.documentElement.style.setProperty('--grid-columns', 1);
createView(0, 'pirate.glb');
loadIntoView(0, 'pirate.glb', 'glb');
}
function init() {
container = document.createElement('div');
document.body.appendChild(container);
gridContainer = document.getElementById('grid-container');
// Create a single camera shared by all views
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.y = 1.0;
camera.position.z = 3.0;
clock = new THREE.Clock();
window.addEventListener('resize', updateRendererSizes, false);
}
function updateRendererSizes() {
// Calculate the correct aspect ratio based on a visible view
var container = renderers[focusedViewIndex >= 0 ? focusedViewIndex : 0].domElement.parentElement;
var aspectRatio = container.clientWidth / container.clientHeight;
// Update camera aspect ratio once
camera.aspect = aspectRatio;
camera.updateProjectionMatrix();
// Update all renderer sizes
for (var i = 0; i < renderers.length; i++) {
var domElement = renderers[i].domElement;
var container = domElement.parentElement;
// Use the container's actual dimensions
var width = container.clientWidth;
var height = container.clientHeight;
renderers[i].setSize(width, height);
}
}
function animate() {
requestAnimationFrame(animate);
// Update all controls
for (var i = 0; i < controls.length; i++) {
controls[i].update();
}
// Update animation mixers
if (settings.animate) {
var delta = clock.getDelta();
for (var i = 0; i < mixers.length; i++) {
if (mixers[i]) {
mixers[i].update(delta);
}
}
}
// Render only visible views
for (var i = 0; i < renderers.length; i++) {
// Only render if view is visible (not hidden by focus mode)
if (focusedViewIndex === -1 || focusedViewIndex === i) {
renderers[i].render(scenes[i], camera);
}
}
}
</script>
</body>
</html>
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
demo/tests.cpp | C++ | #include "../src/meshoptimizer.h"
#include <assert.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
// This file uses assert() to verify algorithm correctness
#undef NDEBUG
#include <assert.h>
struct PV
{
unsigned short px, py, pz;
unsigned char nu, nv; // octahedron encoded normal, aliases .pw
unsigned short tx, ty;
};
// note: 4 6 5 triangle here is a combo-breaker:
// we encode it without rotating, a=next, c=next - this means we do *not* bump next to 6
// which means that the next triangle can't be encoded via next sequencing!
static const unsigned int kIndexBuffer[] = {0, 1, 2, 2, 1, 3, 4, 6, 5, 7, 8, 9};
static const unsigned char kIndexDataV0[] = {
0xe0, 0xf0, 0x10, 0xfe, 0xff, 0xf0, 0x0c, 0xff, 0x02, 0x02, 0x02, 0x00, 0x76, 0x87, 0x56, 0x67,
0x78, 0xa9, 0x86, 0x65, 0x89, 0x68, 0x98, 0x01, 0x69, 0x00, 0x00, // clang-format :-/
};
// note: this exercises two features of v1 format, restarts (0 1 2) and last
static const unsigned int kIndexBufferTricky[] = {0, 1, 2, 2, 1, 3, 0, 1, 2, 2, 1, 5, 2, 1, 4};
static const unsigned char kIndexDataV1[] = {
0xe1, 0xf0, 0x10, 0xfe, 0x1f, 0x3d, 0x00, 0x0a, 0x00, 0x76, 0x87, 0x56, 0x67, 0x78, 0xa9, 0x86,
0x65, 0x89, 0x68, 0x98, 0x01, 0x69, 0x00, 0x00, // clang-format :-/
};
static const unsigned int kIndexSequence[] = {0, 1, 51, 2, 49, 1000};
static const unsigned char kIndexSequenceV1[] = {
0xd1, 0x00, 0x04, 0xcd, 0x01, 0x04, 0x07, 0x98, 0x1f, 0x00, 0x00, 0x00, 0x00, // clang-format :-/
};
static const PV kVertexBuffer[] = {
{0, 0, 0, 0, 0, 0, 0},
{300, 0, 0, 0, 0, 500, 0},
{0, 300, 0, 0, 0, 0, 500},
{300, 300, 0, 0, 0, 500, 500},
};
static const unsigned char kVertexDataV0[] = {
0xa0, 0x01, 0x3f, 0x00, 0x00, 0x00, 0x58, 0x57, 0x58, 0x01, 0x26, 0x00, 0x00, 0x00, 0x01, 0x0c,
0x00, 0x00, 0x00, 0x58, 0x01, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x3f, 0x00,
0x00, 0x00, 0x17, 0x18, 0x17, 0x01, 0x26, 0x00, 0x00, 0x00, 0x01, 0x0c, 0x00, 0x00, 0x00, 0x17,
0x01, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, // clang-format :-/
};
static const unsigned char kVertexDataV1[] = {
0xa1, 0xee, 0xaa, 0xee, 0x00, 0x4b, 0x4b, 0x4b, 0x00, 0x00, 0x4b, 0x00, 0x00, 0x7d, 0x7d, 0x7d,
0x00, 0x00, 0x7d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x00, 0x62, // clang-format :-/
};
// This binary blob is a valid v1 encoding of vertex buffer but it used a custom version of
// the encoder that exercised all features of the format; because of this it is much larger
// and will never be produced by the encoder itself.
static const unsigned char kVertexDataV1Custom[] = {
0xa1, 0xd4, 0x94, 0xd4, 0x01, 0x0e, 0x00, 0x58, 0x57, 0x58, 0x02, 0x02, 0x12, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x58, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x0e, 0x00, 0x7d, 0x7d, 0x7d, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7d, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x62, // clang-format :-/
};
static void decodeIndexV0()
{
const size_t index_count = sizeof(kIndexBuffer) / sizeof(kIndexBuffer[0]);
std::vector<unsigned char> buffer(kIndexDataV0, kIndexDataV0 + sizeof(kIndexDataV0));
unsigned int decoded[index_count];
assert(meshopt_decodeIndexBuffer(decoded, index_count, &buffer[0], buffer.size()) == 0);
assert(memcmp(decoded, kIndexBuffer, sizeof(kIndexBuffer)) == 0);
}
static void decodeIndexV1()
{
const size_t index_count = sizeof(kIndexBufferTricky) / sizeof(kIndexBufferTricky[0]);
std::vector<unsigned char> buffer(kIndexDataV1, kIndexDataV1 + sizeof(kIndexDataV1));
unsigned int decoded[index_count];
assert(meshopt_decodeIndexBuffer(decoded, index_count, &buffer[0], buffer.size()) == 0);
assert(memcmp(decoded, kIndexBufferTricky, sizeof(kIndexBufferTricky)) == 0);
}
static void decodeIndexV1More()
{
const unsigned char input[] = {
0xe1, 0xf0, 0x10, 0xfe, 0xff, 0xf0, 0x0c, 0xff, 0x02, 0x02, 0x02, 0x00, 0x76, 0x87, 0x56, 0x67,
0x78, 0xa9, 0x86, 0x65, 0x89, 0x68, 0x98, 0x01, 0x69, 0x00, 0x00, // clang-format
};
const unsigned int ib[] = {0, 1, 2, 2, 1, 3, 4, 6, 5, 7, 8, 9};
const size_t index_count = sizeof(ib) / sizeof(ib[0]);
std::vector<unsigned char> buffer(input, input + sizeof(input));
unsigned int decoded[index_count];
assert(meshopt_decodeIndexBuffer(decoded, index_count, 4, &buffer[0], buffer.size()) == 0);
assert(memcmp(decoded, ib, sizeof(ib)) == 0);
}
static void decodeIndexV1ThreeEdges()
{
const unsigned char input[] = {
0xe1, 0xf0, 0x20, 0x30, 0x40, 0x00, 0x76, 0x87, 0x56, 0x67, 0x78, 0xa9, 0x86, 0x65, 0x89, 0x68,
0x98, 0x01, 0x69, 0x00, 0x00, // clang-format
};
const unsigned int ib[] = {0, 1, 2, 1, 0, 3, 2, 1, 4, 0, 2, 5};
const size_t index_count = sizeof(ib) / sizeof(ib[0]);
std::vector<unsigned char> buffer(input, input + sizeof(input));
unsigned int decoded[index_count];
assert(meshopt_decodeIndexBuffer(decoded, index_count, 4, &buffer[0], buffer.size()) == 0);
assert(memcmp(decoded, ib, sizeof(ib)) == 0);
}
static void decodeIndex16()
{
const size_t index_count = sizeof(kIndexBuffer) / sizeof(kIndexBuffer[0]);
const size_t vertex_count = 10;
std::vector<unsigned char> buffer(meshopt_encodeIndexBufferBound(index_count, vertex_count));
buffer.resize(meshopt_encodeIndexBuffer(&buffer[0], buffer.size(), kIndexBuffer, index_count));
unsigned short decoded[index_count];
assert(meshopt_decodeIndexBuffer(decoded, index_count, &buffer[0], buffer.size()) == 0);
for (size_t i = 0; i < index_count; ++i)
assert(decoded[i] == kIndexBuffer[i]);
}
static void encodeIndexMemorySafe()
{
const size_t index_count = sizeof(kIndexBuffer) / sizeof(kIndexBuffer[0]);
const size_t vertex_count = 10;
std::vector<unsigned char> buffer(meshopt_encodeIndexBufferBound(index_count, vertex_count));
buffer.resize(meshopt_encodeIndexBuffer(&buffer[0], buffer.size(), kIndexBuffer, index_count));
// check that encode is memory-safe; note that we reallocate the buffer for each try to make sure ASAN can verify buffer access
for (size_t i = 0; i <= buffer.size(); ++i)
{
std::vector<unsigned char> shortbuffer(i);
size_t result = meshopt_encodeIndexBuffer(i == 0 ? NULL : &shortbuffer[0], i, kIndexBuffer, index_count);
if (i == buffer.size())
assert(result == buffer.size());
else
assert(result == 0);
}
}
static void decodeIndexMemorySafe()
{
const size_t index_count = sizeof(kIndexBuffer) / sizeof(kIndexBuffer[0]);
const size_t vertex_count = 10;
std::vector<unsigned char> buffer(meshopt_encodeIndexBufferBound(index_count, vertex_count));
buffer.resize(meshopt_encodeIndexBuffer(&buffer[0], buffer.size(), kIndexBuffer, index_count));
// check that decode is memory-safe; note that we reallocate the buffer for each try to make sure ASAN can verify buffer access
unsigned int decoded[index_count];
for (size_t i = 0; i <= buffer.size(); ++i)
{
std::vector<unsigned char> shortbuffer(buffer.begin(), buffer.begin() + i);
int result = meshopt_decodeIndexBuffer(decoded, index_count, i == 0 ? NULL : &shortbuffer[0], i);
if (i == buffer.size())
assert(result == 0);
else
assert(result < 0);
}
}
static void decodeIndexRejectExtraBytes()
{
const size_t index_count = sizeof(kIndexBuffer) / sizeof(kIndexBuffer[0]);
const size_t vertex_count = 10;
std::vector<unsigned char> buffer(meshopt_encodeIndexBufferBound(index_count, vertex_count));
buffer.resize(meshopt_encodeIndexBuffer(&buffer[0], buffer.size(), kIndexBuffer, index_count));
// check that decoder doesn't accept extra bytes after a valid stream
std::vector<unsigned char> largebuffer(buffer);
largebuffer.push_back(0);
unsigned int decoded[index_count];
assert(meshopt_decodeIndexBuffer(decoded, index_count, &largebuffer[0], largebuffer.size()) < 0);
}
static void decodeIndexRejectMalformedHeaders()
{
const size_t index_count = sizeof(kIndexBuffer) / sizeof(kIndexBuffer[0]);
const size_t vertex_count = 10;
std::vector<unsigned char> buffer(meshopt_encodeIndexBufferBound(index_count, vertex_count));
buffer.resize(meshopt_encodeIndexBuffer(&buffer[0], buffer.size(), kIndexBuffer, index_count));
// check that decoder doesn't accept malformed headers
std::vector<unsigned char> brokenbuffer(buffer);
brokenbuffer[0] = 0;
unsigned int decoded[index_count];
assert(meshopt_decodeIndexBuffer(decoded, index_count, &brokenbuffer[0], brokenbuffer.size()) < 0);
}
static void decodeIndexRejectInvalidVersion()
{
const size_t index_count = sizeof(kIndexBuffer) / sizeof(kIndexBuffer[0]);
const size_t vertex_count = 10;
std::vector<unsigned char> buffer(meshopt_encodeIndexBufferBound(index_count, vertex_count));
buffer.resize(meshopt_encodeIndexBuffer(&buffer[0], buffer.size(), kIndexBuffer, index_count));
// check that decoder doesn't accept invalid version
std::vector<unsigned char> brokenbuffer(buffer);
brokenbuffer[0] |= 0x0f;
unsigned int decoded[index_count];
assert(meshopt_decodeIndexBuffer(decoded, index_count, &brokenbuffer[0], brokenbuffer.size()) < 0);
}
static void decodeIndexMalformedVByte()
{
const unsigned char input[] = {
0xe1, 0x20, 0x20, 0x20, 0xff, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0xff, 0xff, 0xff, 0xff, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, // clang-format :-/
};
unsigned int decoded[66];
assert(meshopt_decodeIndexBuffer(decoded, 66, input, sizeof(input)) < 0);
}
static void roundtripIndexTricky()
{
const size_t index_count = sizeof(kIndexBufferTricky) / sizeof(kIndexBufferTricky[0]);
const size_t vertex_count = 6;
std::vector<unsigned char> buffer(meshopt_encodeIndexBufferBound(index_count, vertex_count));
buffer.resize(meshopt_encodeIndexBuffer(&buffer[0], buffer.size(), kIndexBufferTricky, index_count));
unsigned int decoded[index_count];
assert(meshopt_decodeIndexBuffer(decoded, index_count, &buffer[0], buffer.size()) == 0);
assert(memcmp(decoded, kIndexBufferTricky, sizeof(kIndexBufferTricky)) == 0);
}
static void encodeIndexEmpty()
{
std::vector<unsigned char> buffer(meshopt_encodeIndexBufferBound(0, 0));
buffer.resize(meshopt_encodeIndexBuffer(&buffer[0], buffer.size(), NULL, 0));
assert(meshopt_decodeIndexBuffer(static_cast<unsigned int*>(NULL), 0, &buffer[0], buffer.size()) == 0);
}
static void decodeIndexSequence()
{
const size_t index_count = sizeof(kIndexSequence) / sizeof(kIndexSequence[0]);
std::vector<unsigned char> buffer(kIndexSequenceV1, kIndexSequenceV1 + sizeof(kIndexSequenceV1));
unsigned int decoded[index_count];
assert(meshopt_decodeIndexSequence(decoded, index_count, &buffer[0], buffer.size()) == 0);
assert(memcmp(decoded, kIndexSequence, sizeof(kIndexSequence)) == 0);
}
static void decodeIndexSequence16()
{
const size_t index_count = sizeof(kIndexSequence) / sizeof(kIndexSequence[0]);
const size_t vertex_count = 1001;
std::vector<unsigned char> buffer(meshopt_encodeIndexSequenceBound(index_count, vertex_count));
buffer.resize(meshopt_encodeIndexSequence(&buffer[0], buffer.size(), kIndexSequence, index_count));
unsigned short decoded[index_count];
assert(meshopt_decodeIndexSequence(decoded, index_count, &buffer[0], buffer.size()) == 0);
for (size_t i = 0; i < index_count; ++i)
assert(decoded[i] == kIndexSequence[i]);
}
static void encodeIndexSequenceMemorySafe()
{
const size_t index_count = sizeof(kIndexSequence) / sizeof(kIndexSequence[0]);
const size_t vertex_count = 1001;
std::vector<unsigned char> buffer(meshopt_encodeIndexSequenceBound(index_count, vertex_count));
buffer.resize(meshopt_encodeIndexSequence(&buffer[0], buffer.size(), kIndexSequence, index_count));
// check that encode is memory-safe; note that we reallocate the buffer for each try to make sure ASAN can verify buffer access
for (size_t i = 0; i <= buffer.size(); ++i)
{
std::vector<unsigned char> shortbuffer(i);
size_t result = meshopt_encodeIndexSequence(i == 0 ? NULL : &shortbuffer[0], i, kIndexSequence, index_count);
if (i == buffer.size())
assert(result == buffer.size());
else
assert(result == 0);
}
}
static void decodeIndexSequenceMemorySafe()
{
const size_t index_count = sizeof(kIndexSequence) / sizeof(kIndexSequence[0]);
const size_t vertex_count = 1001;
std::vector<unsigned char> buffer(meshopt_encodeIndexSequenceBound(index_count, vertex_count));
buffer.resize(meshopt_encodeIndexSequence(&buffer[0], buffer.size(), kIndexSequence, index_count));
// check that decode is memory-safe; note that we reallocate the buffer for each try to make sure ASAN can verify buffer access
unsigned int decoded[index_count];
for (size_t i = 0; i <= buffer.size(); ++i)
{
std::vector<unsigned char> shortbuffer(buffer.begin(), buffer.begin() + i);
int result = meshopt_decodeIndexSequence(decoded, index_count, i == 0 ? NULL : &shortbuffer[0], i);
if (i == buffer.size())
assert(result == 0);
else
assert(result < 0);
}
}
static void decodeIndexSequenceRejectExtraBytes()
{
const size_t index_count = sizeof(kIndexSequence) / sizeof(kIndexSequence[0]);
const size_t vertex_count = 1001;
std::vector<unsigned char> buffer(meshopt_encodeIndexSequenceBound(index_count, vertex_count));
buffer.resize(meshopt_encodeIndexSequence(&buffer[0], buffer.size(), kIndexSequence, index_count));
// check that decoder doesn't accept extra bytes after a valid stream
std::vector<unsigned char> largebuffer(buffer);
largebuffer.push_back(0);
unsigned int decoded[index_count];
assert(meshopt_decodeIndexSequence(decoded, index_count, &largebuffer[0], largebuffer.size()) < 0);
}
static void decodeIndexSequenceRejectMalformedHeaders()
{
const size_t index_count = sizeof(kIndexSequence) / sizeof(kIndexSequence[0]);
const size_t vertex_count = 1001;
std::vector<unsigned char> buffer(meshopt_encodeIndexSequenceBound(index_count, vertex_count));
buffer.resize(meshopt_encodeIndexSequence(&buffer[0], buffer.size(), kIndexSequence, index_count));
// check that decoder doesn't accept malformed headers
std::vector<unsigned char> brokenbuffer(buffer);
brokenbuffer[0] = 0;
unsigned int decoded[index_count];
assert(meshopt_decodeIndexSequence(decoded, index_count, &brokenbuffer[0], brokenbuffer.size()) < 0);
}
static void decodeIndexSequenceRejectInvalidVersion()
{
const size_t index_count = sizeof(kIndexSequence) / sizeof(kIndexSequence[0]);
const size_t vertex_count = 1001;
std::vector<unsigned char> buffer(meshopt_encodeIndexSequenceBound(index_count, vertex_count));
buffer.resize(meshopt_encodeIndexSequence(&buffer[0], buffer.size(), kIndexSequence, index_count));
// check that decoder doesn't accept invalid version
std::vector<unsigned char> brokenbuffer(buffer);
brokenbuffer[0] |= 0x0f;
unsigned int decoded[index_count];
assert(meshopt_decodeIndexSequence(decoded, index_count, &brokenbuffer[0], brokenbuffer.size()) < 0);
}
static void encodeIndexSequenceEmpty()
{
std::vector<unsigned char> buffer(meshopt_encodeIndexSequenceBound(0, 0));
buffer.resize(meshopt_encodeIndexSequence(&buffer[0], buffer.size(), NULL, 0));
assert(meshopt_decodeIndexSequence(static_cast<unsigned int*>(NULL), 0, &buffer[0], buffer.size()) == 0);
}
static void decodeVertexV0()
{
const size_t vertex_count = sizeof(kVertexBuffer) / sizeof(kVertexBuffer[0]);
std::vector<unsigned char> buffer(kVertexDataV0, kVertexDataV0 + sizeof(kVertexDataV0));
PV decoded[vertex_count];
assert(meshopt_decodeVertexBuffer(decoded, vertex_count, sizeof(PV), &buffer[0], buffer.size()) == 0);
assert(memcmp(decoded, kVertexBuffer, sizeof(kVertexBuffer)) == 0);
}
static void decodeVertexV0More()
{
const unsigned char expected[] = {
0, 0, 0, 0, 0, 1, 2, 8, 0, 2, 4, 16, 0, 3, 6, 24,
0, 4, 8, 32, 0, 5, 10, 40, 0, 6, 12, 48, 0, 7, 14, 56,
0, 8, 16, 64, 0, 9, 18, 72, 0, 10, 20, 80, 0, 11, 22, 88,
0, 12, 24, 96, 0, 13, 26, 104, 0, 14, 28, 112, 0, 15, 30, 120, // clang-format :-/
};
const unsigned char input[] = {
0xa0, 0x00, 0x01, 0x2a, 0xaa, 0xaa, 0xaa, 0x02, 0x04, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44,
0x03, 0x00, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, // clang-format :-/
};
unsigned char decoded[sizeof(expected)];
assert(meshopt_decodeVertexBuffer(decoded, 16, 4, input, sizeof(input)) == 0);
assert(memcmp(decoded, expected, sizeof(expected)) == 0);
}
static void decodeVertexV0Mode2()
{
const unsigned char expected[] = {
0, 0, 0, 0, 4, 5, 6, 7, 8, 10, 12, 14, 12, 15, 18, 21,
16, 20, 24, 28, 20, 25, 30, 35, 24, 30, 36, 42, 28, 35, 42, 49,
32, 40, 48, 56, 36, 45, 54, 63, 40, 50, 60, 70, 44, 55, 66, 77,
48, 60, 72, 84, 52, 65, 78, 91, 56, 70, 84, 98, 60, 75, 90, 105, // clang-format :-/
};
const unsigned char input[] = {
0xa0, 0x02, 0x08, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x02, 0x0a, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0x02, 0x0c, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x02, 0x0e, 0xee, 0xee,
0xee, 0xee, 0xee, 0xee, 0xee, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, // clang-format :-/
};
unsigned char decoded[sizeof(expected)];
assert(meshopt_decodeVertexBuffer(decoded, 16, 4, input, sizeof(input)) == 0);
assert(memcmp(decoded, expected, sizeof(expected)) == 0);
}
static void decodeVertexV1()
{
const size_t vertex_count = sizeof(kVertexBuffer) / sizeof(kVertexBuffer[0]);
std::vector<unsigned char> buffer(kVertexDataV1, kVertexDataV1 + sizeof(kVertexDataV1));
PV decoded[vertex_count];
assert(meshopt_decodeVertexBuffer(decoded, vertex_count, sizeof(PV), &buffer[0], buffer.size()) == 0);
assert(memcmp(decoded, kVertexBuffer, sizeof(kVertexBuffer)) == 0);
}
static void decodeVertexV1Custom()
{
const size_t vertex_count = sizeof(kVertexBuffer) / sizeof(kVertexBuffer[0]);
std::vector<unsigned char> buffer(kVertexDataV1Custom, kVertexDataV1Custom + sizeof(kVertexDataV1Custom));
PV decoded[vertex_count];
assert(meshopt_decodeVertexBuffer(decoded, vertex_count, sizeof(PV), &buffer[0], buffer.size()) == 0);
assert(memcmp(decoded, kVertexBuffer, sizeof(kVertexBuffer)) == 0);
}
static void decodeVertexV1Deltas()
{
const unsigned short expected[] = {
248, 248, 240, 240, 249, 250, 243, 244, 250, 252, 246, 248, 251, 254, 249, 252,
252, 256, 252, 256, 253, 258, 255, 260, 254, 260, 258, 264, 255, 262, 261, 268,
256, 264, 264, 272, 257, 262, 267, 268, 258, 260, 270, 264, 259, 258, 273, 260,
260, 256, 276, 256, 261, 254, 279, 252, 262, 252, 282, 248, 263, 250, 285, 244, // clang-format :-/
};
const unsigned char input[] = {
0xa1, 0x99, 0x99, 0x01, 0x2a, 0xaa, 0xaa, 0xaa, 0x02, 0x04, 0x44, 0x44, 0x44, 0x43, 0x33, 0x33,
0x33, 0x02, 0x06, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x02, 0x08, 0x88, 0x88, 0x88, 0x87,
0x77, 0x77, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xf8, 0x00, 0xf8, 0x00, 0xf0, 0x00, 0xf0, 0x00, 0x01, 0x01, // clang-format :-/
};
unsigned short decoded[sizeof(expected) / sizeof(expected[0])];
assert(meshopt_decodeVertexBuffer(decoded, 16, 8, input, sizeof(input)) == 0);
assert(memcmp(decoded, expected, sizeof(expected)) == 0);
}
static void encodeVertexMemorySafe()
{
const size_t vertex_count = sizeof(kVertexBuffer) / sizeof(kVertexBuffer[0]);
std::vector<unsigned char> buffer(meshopt_encodeVertexBufferBound(vertex_count, sizeof(PV)));
buffer.resize(meshopt_encodeVertexBuffer(&buffer[0], buffer.size(), kVertexBuffer, vertex_count, sizeof(PV)));
// check that encode is memory-safe; note that we reallocate the buffer for each try to make sure ASAN can verify buffer access
for (size_t i = 0; i <= buffer.size(); ++i)
{
std::vector<unsigned char> shortbuffer(i);
size_t result = meshopt_encodeVertexBuffer(i == 0 ? NULL : &shortbuffer[0], i, kVertexBuffer, vertex_count, sizeof(PV));
if (i == buffer.size())
assert(result == buffer.size());
else
assert(result == 0);
}
}
static void decodeVertexMemorySafe()
{
const size_t vertex_count = sizeof(kVertexBuffer) / sizeof(kVertexBuffer[0]);
std::vector<unsigned char> buffer(meshopt_encodeVertexBufferBound(vertex_count, sizeof(PV)));
buffer.resize(meshopt_encodeVertexBuffer(&buffer[0], buffer.size(), kVertexBuffer, vertex_count, sizeof(PV)));
// check that decode is memory-safe; note that we reallocate the buffer for each try to make sure ASAN can verify buffer access
PV decoded[vertex_count];
for (size_t i = 0; i <= buffer.size(); ++i)
{
std::vector<unsigned char> shortbuffer(buffer.begin(), buffer.begin() + i);
int result = meshopt_decodeVertexBuffer(decoded, vertex_count, sizeof(PV), i == 0 ? NULL : &shortbuffer[0], i);
(void)result;
if (i == buffer.size())
assert(result == 0);
else
assert(result < 0);
}
}
static void decodeVertexRejectExtraBytes()
{
const size_t vertex_count = sizeof(kVertexBuffer) / sizeof(kVertexBuffer[0]);
std::vector<unsigned char> buffer(meshopt_encodeVertexBufferBound(vertex_count, sizeof(PV)));
buffer.resize(meshopt_encodeVertexBuffer(&buffer[0], buffer.size(), kVertexBuffer, vertex_count, sizeof(PV)));
// check that decoder doesn't accept extra bytes after a valid stream
std::vector<unsigned char> largebuffer(buffer);
largebuffer.push_back(0);
PV decoded[vertex_count];
assert(meshopt_decodeVertexBuffer(decoded, vertex_count, sizeof(PV), &largebuffer[0], largebuffer.size()) < 0);
}
static void decodeVertexRejectMalformedHeaders()
{
const size_t vertex_count = sizeof(kVertexBuffer) / sizeof(kVertexBuffer[0]);
std::vector<unsigned char> buffer(meshopt_encodeVertexBufferBound(vertex_count, sizeof(PV)));
buffer.resize(meshopt_encodeVertexBuffer(&buffer[0], buffer.size(), kVertexBuffer, vertex_count, sizeof(PV)));
// check that decoder doesn't accept malformed headers
std::vector<unsigned char> brokenbuffer(buffer);
brokenbuffer[0] = 0;
PV decoded[vertex_count];
assert(meshopt_decodeVertexBuffer(decoded, vertex_count, sizeof(PV), &brokenbuffer[0], brokenbuffer.size()) < 0);
}
static void decodeVertexBitGroups()
{
unsigned char data[16 * 4];
// this tests 0/2/4/8 bit groups in one stream
for (size_t i = 0; i < 16; ++i)
{
data[i * 4 + 0] = 0;
data[i * 4 + 1] = (unsigned char)(i * 1);
data[i * 4 + 2] = (unsigned char)(i * 2);
data[i * 4 + 3] = (unsigned char)(i * 8);
}
std::vector<unsigned char> buffer(meshopt_encodeVertexBufferBound(16, 4));
buffer.resize(meshopt_encodeVertexBuffer(&buffer[0], buffer.size(), data, 16, 4));
unsigned char decoded[16 * 4];
assert(meshopt_decodeVertexBuffer(decoded, 16, 4, &buffer[0], buffer.size()) == 0);
assert(memcmp(decoded, data, sizeof(data)) == 0);
}
static void decodeVertexBitGroupSentinels()
{
unsigned char data[16 * 4];
// this tests 0/2/4/8 bit groups and sentinels in one stream
for (size_t i = 0; i < 16; ++i)
{
if (i == 7 || i == 13)
{
data[i * 4 + 0] = 42;
data[i * 4 + 1] = 42;
data[i * 4 + 2] = 42;
data[i * 4 + 3] = 42;
}
else
{
data[i * 4 + 0] = 0;
data[i * 4 + 1] = (unsigned char)(i * 1);
data[i * 4 + 2] = (unsigned char)(i * 2);
data[i * 4 + 3] = (unsigned char)(i * 8);
}
}
std::vector<unsigned char> buffer(meshopt_encodeVertexBufferBound(16, 4));
buffer.resize(meshopt_encodeVertexBuffer(&buffer[0], buffer.size(), data, 16, 4));
unsigned char decoded[16 * 4];
assert(meshopt_decodeVertexBuffer(decoded, 16, 4, &buffer[0], buffer.size()) == 0);
assert(memcmp(decoded, data, sizeof(data)) == 0);
}
static void decodeVertexDeltas()
{
unsigned short data[16 * 4];
// this forces wider deltas by using values that cross byte boundary
for (size_t i = 0; i < 16; ++i)
{
data[i * 4 + 0] = (unsigned short)(0xf8 + i * 1);
data[i * 4 + 1] = (unsigned short)(0xf8 + (i < 8 ? i : 16 - i) * 2);
data[i * 4 + 2] = (unsigned short)(0xf0 + i * 3);
data[i * 4 + 3] = (unsigned short)(0xf0 + (i < 8 ? i : 16 - i) * 4);
}
std::vector<unsigned char> buffer(meshopt_encodeVertexBufferBound(16, 8));
buffer.resize(meshopt_encodeVertexBufferLevel(&buffer[0], buffer.size(), data, 16, 8, 2, -1));
unsigned short decoded[16 * 4];
assert(meshopt_decodeVertexBuffer(decoded, 16, 8, &buffer[0], buffer.size()) == 0);
assert(memcmp(decoded, data, sizeof(data)) == 0);
}
static void decodeVertexBitXor()
{
unsigned int data[16 * 4];
// this forces xors by using bit values at an offset
for (size_t i = 0; i < 16; ++i)
{
data[i * 4 + 0] = unsigned(i << 0);
data[i * 4 + 1] = unsigned(i << 2);
data[i * 4 + 2] = unsigned(i << 15);
data[i * 4 + 3] = unsigned(i << 28);
}
std::vector<unsigned char> buffer(meshopt_encodeVertexBufferBound(16, 16));
buffer.resize(meshopt_encodeVertexBufferLevel(&buffer[0], buffer.size(), data, 16, 16, 3, -1));
unsigned int decoded[16 * 4];
assert(meshopt_decodeVertexBuffer(decoded, 16, 16, &buffer[0], buffer.size()) == 0);
assert(memcmp(decoded, data, sizeof(data)) == 0);
}
static void decodeVertexLarge()
{
unsigned char data[128 * 4];
// this tests 0/2/4/8 bit groups in one stream
for (size_t i = 0; i < 128; ++i)
{
data[i * 4 + 0] = 0;
data[i * 4 + 1] = (unsigned char)(i * 1);
data[i * 4 + 2] = (unsigned char)(i * 2);
data[i * 4 + 3] = (unsigned char)(i * 8);
}
std::vector<unsigned char> buffer(meshopt_encodeVertexBufferBound(128, 4));
buffer.resize(meshopt_encodeVertexBuffer(&buffer[0], buffer.size(), data, 128, 4));
unsigned char decoded[128 * 4];
assert(meshopt_decodeVertexBuffer(decoded, 128, 4, &buffer[0], buffer.size()) == 0);
assert(memcmp(decoded, data, sizeof(data)) == 0);
}
static void decodeVertexSmall()
{
unsigned char data[13 * 4];
// this tests 0/2/4/8 bit groups in one stream
for (size_t i = 0; i < 13; ++i)
{
data[i * 4 + 0] = 0;
data[i * 4 + 1] = (unsigned char)(i * 1);
data[i * 4 + 2] = (unsigned char)(i * 2);
data[i * 4 + 3] = (unsigned char)(i * 8);
}
std::vector<unsigned char> buffer(meshopt_encodeVertexBufferBound(13, 4));
buffer.resize(meshopt_encodeVertexBuffer(&buffer[0], buffer.size(), data, 13, 4));
unsigned char decoded[13 * 4];
assert(meshopt_decodeVertexBuffer(decoded, 13, 4, &buffer[0], buffer.size()) == 0);
assert(memcmp(decoded, data, sizeof(data)) == 0);
}
static void encodeVertexEmpty()
{
std::vector<unsigned char> buffer(meshopt_encodeVertexBufferBound(0, 16));
buffer.resize(meshopt_encodeVertexBuffer(&buffer[0], buffer.size(), NULL, 0, 16));
assert(meshopt_decodeVertexBuffer(NULL, 0, 16, &buffer[0], buffer.size()) == 0);
}
static void decodeVersion()
{
assert(meshopt_decodeVertexVersion(reinterpret_cast<const unsigned char*>("\xa0"), 1) == 0);
assert(meshopt_decodeVertexVersion(reinterpret_cast<const unsigned char*>("\xa1"), 1) == 1);
assert(meshopt_decodeVertexVersion(reinterpret_cast<const unsigned char*>("\xa1hello"), 6) == 1);
assert(meshopt_decodeVertexVersion(NULL, 0) == -1);
assert(meshopt_decodeVertexVersion(reinterpret_cast<const unsigned char*>("\xa7"), 1) == -1);
assert(meshopt_decodeVertexVersion(reinterpret_cast<const unsigned char*>("\xb1"), 1) == -1);
assert(meshopt_decodeIndexVersion(reinterpret_cast<const unsigned char*>("\xe0"), 1) == 0);
assert(meshopt_decodeIndexVersion(reinterpret_cast<const unsigned char*>("\xd1"), 1) == 1);
assert(meshopt_decodeIndexVersion(reinterpret_cast<const unsigned char*>("\xe1hello"), 6) == 1);
assert(meshopt_decodeIndexVersion(NULL, 0) == -1);
assert(meshopt_decodeIndexVersion(reinterpret_cast<const unsigned char*>("\xa7"), 1) == -1);
assert(meshopt_decodeIndexVersion(reinterpret_cast<const unsigned char*>("\xa1"), 1) == -1);
}
static void decodeFilterOct8()
{
const unsigned char data[4 * 4] = {
0, 1, 127, 0,
0, 187, 127, 1,
255, 1, 127, 0,
14, 130, 127, 1, // clang-format :-/
};
const unsigned char expected[4 * 4] = {
0, 1, 127, 0,
0, 159, 82, 1,
255, 1, 127, 0,
1, 130, 241, 1, // clang-format :-/
};
// Aligned by 4
unsigned char full[4 * 4];
memcpy(full, data, sizeof(full));
meshopt_decodeFilterOct(full, 4, 4);
assert(memcmp(full, expected, sizeof(full)) == 0);
// Tail processing for unaligned data
unsigned char tail[3 * 4];
memcpy(tail, data, sizeof(tail));
meshopt_decodeFilterOct(tail, 3, 4);
assert(memcmp(tail, expected, sizeof(tail)) == 0);
}
static void decodeFilterOct12()
{
const unsigned short data[4 * 4] = {
0, 1, 2047, 0,
0, 1870, 2047, 1,
2017, 1, 2047, 0,
14, 1300, 2047, 1, // clang-format :-/
};
const unsigned short expected[4 * 4] = {
0, 16, 32767, 0,
0, 32621, 3088, 1,
32764, 16, 471, 0,
307, 28541, 16093, 1, // clang-format :-/
};
// Aligned by 4
unsigned short full[4 * 4];
memcpy(full, data, sizeof(full));
meshopt_decodeFilterOct(full, 4, 8);
assert(memcmp(full, expected, sizeof(full)) == 0);
// Tail processing for unaligned data
unsigned short tail[3 * 4];
memcpy(tail, data, sizeof(tail));
meshopt_decodeFilterOct(tail, 3, 8);
assert(memcmp(tail, expected, sizeof(tail)) == 0);
}
static void decodeFilterQuat12()
{
const unsigned short data[4 * 4] = {
0, 1, 0, 0x7fc,
0, 1870, 0, 0x7fd,
2017, 1, 0, 0x7fe,
14, 1300, 0, 0x7ff, // clang-format :-/
};
const unsigned short expected[4 * 4] = {
32767, 0, 11, 0,
0, 25013, 0, 21166,
11, 0, 23504, 22830,
158, 14715, 0, 29277, // clang-format :-/
};
// Aligned by 4
unsigned short full[4 * 4];
memcpy(full, data, sizeof(full));
meshopt_decodeFilterQuat(full, 4, 8);
assert(memcmp(full, expected, sizeof(full)) == 0);
// Tail processing for unaligned data
unsigned short tail[3 * 4];
memcpy(tail, data, sizeof(tail));
meshopt_decodeFilterQuat(tail, 3, 8);
assert(memcmp(tail, expected, sizeof(tail)) == 0);
}
static void decodeFilterExp()
{
const unsigned int data[4] = {
0,
0xff000003,
0x02fffff7,
0xfe7fffff, // clang-format :-/
};
const unsigned int expected[4] = {
0,
0x3fc00000,
0xc2100000,
0x49fffffe, // clang-format :-/
};
// Aligned by 4
unsigned int full[4];
memcpy(full, data, sizeof(full));
meshopt_decodeFilterExp(full, 4, 4);
assert(memcmp(full, expected, sizeof(full)) == 0);
// Tail processing for unaligned data
unsigned int tail[3];
memcpy(tail, data, sizeof(tail));
meshopt_decodeFilterExp(tail, 3, 4);
assert(memcmp(tail, expected, sizeof(tail)) == 0);
}
static void encodeFilterOct8()
{
const float data[4 * 4] = {
1, 0, 0, 0,
0, -1, 0, 0,
0.7071068f, 0, 0.707168f, 1,
-0.7071068f, 0, -0.707168f, 1, // clang-format :-/
};
const unsigned char expected[4 * 4] = {
0x7f, 0, 0x7f, 0,
0, 0x81, 0x7f, 0,
0x3f, 0, 0x7f, 0x7f,
0x81, 0x40, 0x7f, 0x7f, // clang-format :-/
};
unsigned char encoded[4 * 4];
meshopt_encodeFilterOct(encoded, 4, 4, 8, data);
assert(memcmp(encoded, expected, sizeof(expected)) == 0);
signed char decoded[4 * 4];
memcpy(decoded, encoded, sizeof(decoded));
meshopt_decodeFilterOct(decoded, 4, 4);
for (size_t i = 0; i < 4 * 4; ++i)
assert(fabsf(decoded[i] / 127.f - data[i]) < 1e-2f);
}
static void encodeFilterOct12()
{
const float data[4 * 4] = {
1, 0, 0, 0,
0, -1, 0, 0,
0.7071068f, 0, 0.707168f, 1,
-0.7071068f, 0, -0.707168f, 1, // clang-format :-/
};
const unsigned short expected[4 * 4] = {
0x7ff, 0, 0x7ff, 0,
0x0, 0xf801, 0x7ff, 0,
0x3ff, 0, 0x7ff, 0x7fff,
0xf801, 0x400, 0x7ff, 0x7fff, // clang-format :-/
};
unsigned short encoded[4 * 4];
meshopt_encodeFilterOct(encoded, 4, 8, 12, data);
assert(memcmp(encoded, expected, sizeof(expected)) == 0);
short decoded[4 * 4];
memcpy(decoded, encoded, sizeof(decoded));
meshopt_decodeFilterOct(decoded, 4, 8);
for (size_t i = 0; i < 4 * 4; ++i)
assert(fabsf(decoded[i] / 32767.f - data[i]) < 1e-3f);
}
static void encodeFilterQuat12()
{
const float data[4 * 4] = {
1, 0, 0, 0,
0, -1, 0, 0,
0.7071068f, 0, 0, 0.707168f,
-0.7071068f, 0, 0, -0.707168f, // clang-format :-/
};
const unsigned short expected[4 * 4] = {
0, 0, 0, 0x7fc,
0, 0, 0, 0x7fd,
0x7ff, 0, 0, 0x7ff,
0x7ff, 0, 0, 0x7ff, // clang-format :-/
};
unsigned short encoded[4 * 4];
meshopt_encodeFilterQuat(encoded, 4, 8, 12, data);
assert(memcmp(encoded, expected, sizeof(expected)) == 0);
short decoded[4 * 4];
memcpy(decoded, encoded, sizeof(decoded));
meshopt_decodeFilterQuat(decoded, 4, 8);
for (size_t i = 0; i < 4; ++i)
{
float dx = decoded[i * 4 + 0] / 32767.f;
float dy = decoded[i * 4 + 1] / 32767.f;
float dz = decoded[i * 4 + 2] / 32767.f;
float dw = decoded[i * 4 + 3] / 32767.f;
float dp =
data[i * 4 + 0] * dx +
data[i * 4 + 1] * dy +
data[i * 4 + 2] * dz +
data[i * 4 + 3] * dw;
assert(fabsf(fabsf(dp) - 1.f) < 1e-4f);
}
}
static void encodeFilterExp()
{
const float data[4] = {
1,
-23.4f,
-0.1f,
11.0f,
};
// separate exponents: each component gets its own value
const unsigned int expected1[4] = {
0xf3002000,
0xf7ffd133,
0xefffcccd,
0xf6002c00,
};
// shared exponents (vector): all components of each vector get the same value
const unsigned int expected2[4] = {
0xf7000200,
0xf7ffd133,
0xf6ffff9a,
0xf6002c00,
};
// shared exponents (component): each component gets the same value across all vectors
const unsigned int expected3[4] = {
0xf3002000,
0xf7ffd133,
0xf3fffccd,
0xf7001600,
};
unsigned int encoded1[4];
meshopt_encodeFilterExp(encoded1, 2, 8, 15, data, meshopt_EncodeExpSeparate);
unsigned int encoded2[4];
meshopt_encodeFilterExp(encoded2, 2, 8, 15, data, meshopt_EncodeExpSharedVector);
unsigned int encoded3[4];
meshopt_encodeFilterExp(encoded3, 2, 8, 15, data, meshopt_EncodeExpSharedComponent);
assert(memcmp(encoded1, expected1, sizeof(expected1)) == 0);
assert(memcmp(encoded2, expected2, sizeof(expected2)) == 0);
assert(memcmp(encoded3, expected3, sizeof(expected3)) == 0);
float decoded1[4];
memcpy(decoded1, encoded1, sizeof(decoded1));
meshopt_decodeFilterExp(decoded1, 2, 8);
float decoded2[4];
memcpy(decoded2, encoded2, sizeof(decoded2));
meshopt_decodeFilterExp(decoded2, 2, 8);
float decoded3[4];
memcpy(decoded3, encoded3, sizeof(decoded3));
meshopt_decodeFilterExp(decoded3, 2, 8);
for (size_t i = 0; i < 4; ++i)
{
assert(fabsf(decoded1[i] - data[i]) < 1e-3f);
assert(fabsf(decoded2[i] - data[i]) < 1e-3f);
assert(fabsf(decoded3[i] - data[i]) < 1e-3f);
}
}
static void encodeFilterExpZero()
{
const float data[4] = {
0.f,
-0.f,
1.1754944e-38f,
-1.1754944e-38f,
};
const unsigned int expected[4] = {
0xf2000000,
0xf2000000,
0x8e000000,
0x8e000000,
};
unsigned int encoded[4];
meshopt_encodeFilterExp(encoded, 4, 4, 15, data, meshopt_EncodeExpSeparate);
assert(memcmp(encoded, expected, sizeof(expected)) == 0);
float decoded[4];
memcpy(decoded, encoded, sizeof(decoded));
meshopt_decodeFilterExp(&decoded, 4, 4);
for (size_t i = 0; i < 4; ++i)
assert(decoded[i] == 0);
}
static void encodeFilterExpAlias()
{
const float data[4] = {
1,
-23.4f,
-0.1f,
11.0f,
};
// separate exponents: each component gets its own value
const unsigned int expected1[4] = {
0xf3002000,
0xf7ffd133,
0xefffcccd,
0xf6002c00,
};
// shared exponents (vector): all components of each vector get the same value
const unsigned int expected2[4] = {
0xf7000200,
0xf7ffd133,
0xf6ffff9a,
0xf6002c00,
};
// shared exponents (component): each component gets the same value across all vectors
const unsigned int expected3[4] = {
0xf3002000,
0xf7ffd133,
0xf3fffccd,
0xf7001600,
};
unsigned int encoded1[4];
memcpy(encoded1, data, sizeof(data));
meshopt_encodeFilterExp(encoded1, 2, 8, 15, reinterpret_cast<float*>(encoded1), meshopt_EncodeExpSeparate);
unsigned int encoded2[4];
memcpy(encoded2, data, sizeof(data));
meshopt_encodeFilterExp(encoded2, 2, 8, 15, reinterpret_cast<float*>(encoded2), meshopt_EncodeExpSharedVector);
unsigned int encoded3[4];
memcpy(encoded3, data, sizeof(data));
meshopt_encodeFilterExp(encoded3, 2, 8, 15, reinterpret_cast<float*>(encoded3), meshopt_EncodeExpSharedComponent);
assert(memcmp(encoded1, expected1, sizeof(expected1)) == 0);
assert(memcmp(encoded2, expected2, sizeof(expected2)) == 0);
assert(memcmp(encoded3, expected3, sizeof(expected3)) == 0);
}
static void encodeFilterExpClamp()
{
const float data[4] = {
1,
-23.4f,
-0.1f,
11.0f,
};
// separate exponents: each component gets its own value
// note: third value is exponent clamped
const unsigned int expected[4] = {
0xf3002000,
0xf7ffd133,
0xf2fff99a,
0xf6002c00,
};
unsigned int encoded[4];
meshopt_encodeFilterExp(encoded, 2, 8, 15, data, meshopt_EncodeExpClamped);
assert(memcmp(encoded, expected, sizeof(expected)) == 0);
float decoded[4];
memcpy(decoded, encoded, sizeof(decoded));
meshopt_decodeFilterExp(decoded, 2, 8);
for (size_t i = 0; i < 4; ++i)
assert(fabsf(decoded[i] - data[i]) < 1e-3f);
}
static void encodeFilterColor8()
{
const float data[4 * 4] = {
1.0f, 0.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 0.5f,
0.0f, 0.0f, 1.0f, 0.25f,
0.4f, 0.4f, 0.4f, 0.75f, // clang-format :-/
};
const unsigned char expected[4 * 4] = {
0x40, 0x7f, 0xc1, 0xff,
0x7f, 0x00, 0x7f, 0xc0,
0x40, 0x81, 0xc0, 0xa0,
0x66, 0x00, 0x00, 0xdf, // clang-format :-/
};
unsigned char encoded[4 * 4];
meshopt_encodeFilterColor(encoded, 4, 4, 8, data);
assert(memcmp(encoded, expected, sizeof(expected)) == 0);
unsigned char decoded[4 * 4];
memcpy(decoded, encoded, sizeof(decoded));
meshopt_decodeFilterColor(decoded, 4, 4);
for (size_t i = 0; i < 4 * 4; ++i)
assert(fabsf(decoded[i] / 255.f - data[i]) < 1e-2f);
// ensure grayscale is preserved
assert(decoded[12] == decoded[13] && decoded[12] == decoded[14]);
}
static void encodeFilterColor12()
{
const float data[4 * 4] = {
1.0f, 0.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 0.5f,
0.0f, 0.0f, 1.0f, 0.25f,
0.4f, 0.4f, 0.4f, 0.75f, // clang-format :-/
};
const unsigned short expected[4 * 4] = {
0x0400, 0x07ff, 0xfc01, 0x0fff,
0x07ff, 0x0000, 0x07ff, 0x0c00,
0x0400, 0xf801, 0xfc00, 0x0a00,
0x0666, 0x0000, 0x0000, 0x0dff, // clang-format :-/
};
unsigned short encoded[4 * 4];
meshopt_encodeFilterColor(encoded, 4, 8, 12, data);
assert(memcmp(encoded, expected, sizeof(expected)) == 0);
unsigned short decoded[4 * 4];
memcpy(decoded, encoded, sizeof(decoded));
meshopt_decodeFilterColor(decoded, 4, 8);
for (size_t i = 0; i < 4 * 4; ++i)
assert(fabsf(decoded[i] / 65535.f - data[i]) < 1e-3f);
// ensure grayscale is preserved
assert(decoded[12] == decoded[13] && decoded[12] == decoded[14]);
}
static void clusterBoundsDegenerate()
{
const float vbd[] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
const unsigned int ibd[] = {0, 0, 0};
const unsigned int ib1[] = {0, 1, 2};
// all of the bounds below are degenerate as they use 0 triangles, one topology-degenerate triangle and one position-degenerate triangle respectively
meshopt_Bounds bounds0 = meshopt_computeClusterBounds(NULL, 0, NULL, 0, 12);
meshopt_Bounds boundsd = meshopt_computeClusterBounds(ibd, 3, vbd, 3, 12);
meshopt_Bounds bounds1 = meshopt_computeClusterBounds(ib1, 3, vbd, 3, 12);
assert(bounds0.center[0] == 0 && bounds0.center[1] == 0 && bounds0.center[2] == 0 && bounds0.radius == 0);
assert(boundsd.center[0] == 0 && boundsd.center[1] == 0 && boundsd.center[2] == 0 && boundsd.radius == 0);
assert(bounds1.center[0] == 0 && bounds1.center[1] == 0 && bounds1.center[2] == 0 && bounds1.radius == 0);
const float vb1[] = {1, 0, 0, 0, 1, 0, 0, 0, 1};
const unsigned int ib2[] = {0, 1, 2, 0, 2, 1};
// these bounds have a degenerate cone since the cluster has two triangles with opposite normals
meshopt_Bounds bounds2 = meshopt_computeClusterBounds(ib2, 6, vb1, 3, 12);
assert(bounds2.cone_apex[0] == 0 && bounds2.cone_apex[1] == 0 && bounds2.cone_apex[2] == 0);
assert(bounds2.cone_axis[0] == 0 && bounds2.cone_axis[1] == 0 && bounds2.cone_axis[2] == 0);
assert(bounds2.cone_cutoff == 1);
assert(bounds2.cone_axis_s8[0] == 0 && bounds2.cone_axis_s8[1] == 0 && bounds2.cone_axis_s8[2] == 0);
assert(bounds2.cone_cutoff_s8 == 127);
// however, the bounding sphere needs to be in tact (here we only check bbox for simplicity)
assert(bounds2.center[0] - bounds2.radius <= 0 && bounds2.center[0] + bounds2.radius >= 1);
assert(bounds2.center[1] - bounds2.radius <= 0 && bounds2.center[1] + bounds2.radius >= 1);
assert(bounds2.center[2] - bounds2.radius <= 0 && bounds2.center[2] + bounds2.radius >= 1);
}
static void sphereBounds()
{
const float vbr[] = {
0, 0, 0, 0,
0, 1, 0, 1,
0, 0, 1, 2,
1, 0, 1, 3, // clang-format
};
// without the radius, the center is inside the tetrahedron
meshopt_Bounds bounds = meshopt_computeSphereBounds(vbr, 4, sizeof(float) * 4, NULL, 0);
assert(fabsf(bounds.center[0] - 0.5f) < 1e-2f);
assert(fabsf(bounds.center[1] - 0.5f) < 1e-2f);
assert(fabsf(bounds.center[2] - 0.5f) < 1e-2f);
assert(bounds.radius < 0.87f);
// when using the radius, the last sphere envelops the entire set
meshopt_Bounds boundsr = meshopt_computeSphereBounds(vbr, 4, sizeof(float) * 4, vbr + 3, sizeof(float) * 4);
assert(fabsf(boundsr.center[0] - 1.f) < 1e-2f);
assert(fabsf(boundsr.center[1] - 0.f) < 1e-2f);
assert(fabsf(boundsr.center[2] - 1.f) < 1e-2f);
assert(fabsf(boundsr.radius - 3.f) < 1e-2f);
}
static void meshletsEmpty()
{
const float vbd[4 * 3] = {};
meshopt_Meshlet ml[1];
unsigned int mv[4];
unsigned char mt[8];
size_t mc = meshopt_buildMeshlets(ml, mv, mt, NULL, 0, vbd, 4, sizeof(float) * 3, 64, 64, 0.f);
assert(mc == 0);
}
static void meshletsDense()
{
const float vbd[4 * 3] = {};
const unsigned int ibd[6] = {0, 2, 1, 1, 2, 3};
meshopt_Meshlet ml[1];
unsigned int mv[4];
unsigned char mt[8];
size_t mc = meshopt_buildMeshlets(ml, mv, mt, ibd, 6, vbd, 4, sizeof(float) * 3, 64, 64, 0.f);
assert(mc == 1);
assert(ml[0].triangle_count == 2);
assert(ml[0].vertex_count == 4);
unsigned int tri0[3] = {mv[mt[0]], mv[mt[1]], mv[mt[2]]};
unsigned int tri1[3] = {mv[mt[3]], mv[mt[4]], mv[mt[5]]};
// technically triangles could also be flipped in the meshlet but for now just assume they aren't
assert(memcmp(tri0, ibd + 0, 3 * sizeof(unsigned int)) == 0);
assert(memcmp(tri1, ibd + 3, 3 * sizeof(unsigned int)) == 0);
}
static void meshletsSparse()
{
const float vbd[16 * 3] = {};
const unsigned int ibd[6] = {0, 7, 15, 15, 7, 3};
meshopt_Meshlet ml[1];
unsigned int mv[4];
unsigned char mt[8];
size_t mc = meshopt_buildMeshlets(ml, mv, mt, ibd, 6, vbd, 16, sizeof(float) * 3, 64, 64, 0.f);
assert(mc == 1);
assert(ml[0].triangle_count == 2);
assert(ml[0].vertex_count == 4);
unsigned int tri0[3] = {mv[mt[0]], mv[mt[1]], mv[mt[2]]};
unsigned int tri1[3] = {mv[mt[3]], mv[mt[4]], mv[mt[5]]};
// technically triangles could also be flipped in the meshlet but for now just assume they aren't
assert(memcmp(tri0, ibd + 0, 3 * sizeof(unsigned int)) == 0);
assert(memcmp(tri1, ibd + 3, 3 * sizeof(unsigned int)) == 0);
}
static void meshletsFlex()
{
// two tetrahedrons far apart
float vb[2 * 4 * 3] = {
0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1,
10, 0, 0, 11, 0, 0, 10, 1, 0, 10, 0, 1, // clang-format :-/
};
unsigned int ib[2 * 4 * 3] = {
0, 1, 2, 0, 2, 3, 0, 3, 1, 1, 3, 2,
4, 5, 6, 4, 6, 7, 4, 7, 5, 5, 7, 6, // clang-format :-/
};
// up to 2 meshlets with min_triangles=4
assert(meshopt_buildMeshletsBound(2 * 4 * 3, 16, 4) == 2);
meshopt_Meshlet ml[2];
unsigned int mv[2 * 16];
unsigned char mt[2 * 8 * 3]; // 2 meshlets with up to 8 triangles
// with regular function, we should get one meshlet (maxt=8) or two (maxt=4)
assert(meshopt_buildMeshlets(ml, mv, mt, ib, sizeof(ib) / sizeof(ib[0]), vb, 8, sizeof(float) * 3, 16, 8, 0.f) == 1);
assert(ml[0].triangle_count == 8);
assert(ml[0].vertex_count == 8);
assert(meshopt_buildMeshlets(ml, mv, mt, ib, sizeof(ib) / sizeof(ib[0]), vb, 8, sizeof(float) * 3, 16, 4, 0.f) == 2);
assert(ml[0].triangle_count == 4);
assert(ml[0].vertex_count == 4);
assert(ml[1].triangle_count == 4);
assert(ml[1].vertex_count == 4);
// with flex function and mint=4 maxt=8 we should get one meshlet if split_factor is zero, or large enough to accomodate both
assert(meshopt_buildMeshletsFlex(ml, mv, mt, ib, sizeof(ib) / sizeof(ib[0]), vb, 8, sizeof(float) * 3, 16, 4, 8, 0.f, 0.f) == 1);
assert(ml[0].triangle_count == 8);
assert(ml[0].vertex_count == 8);
assert(meshopt_buildMeshletsFlex(ml, mv, mt, ib, sizeof(ib) / sizeof(ib[0]), vb, 8, sizeof(float) * 3, 16, 4, 8, 0.f, 10.f) == 1);
assert(ml[0].triangle_count == 8);
assert(ml[0].vertex_count == 8);
// however, with a smaller split factor we should get two meshlets
assert(meshopt_buildMeshletsFlex(ml, mv, mt, ib, sizeof(ib) / sizeof(ib[0]), vb, 8, sizeof(float) * 3, 16, 4, 8, 0.f, 1.f) == 2);
assert(ml[0].triangle_count == 4);
assert(ml[0].vertex_count == 4);
assert(ml[1].triangle_count == 4);
assert(ml[1].vertex_count == 4);
}
static void meshletsMax()
{
float vb[16 * 16 * 3];
unsigned int ib[15 * 15 * 2 * 3];
// 16x16 grid of vertices, 15x15 grid of triangles
for (int y = 0; y < 16; ++y)
for (int x = 0; x < 16; ++x)
{
vb[(y * 16 + x) * 3 + 0] = float(x);
vb[(y * 16 + x) * 3 + 1] = float(y);
vb[(y * 16 + x) * 3 + 2] = 0;
}
for (int y = 0; y < 15; ++y)
for (int x = 0; x < 15; ++x)
{
ib[(y * 15 + x) * 2 * 3 + 0] = (y + 0) * 16 + (x + 0);
ib[(y * 15 + x) * 2 * 3 + 1] = (y + 0) * 16 + (x + 1);
ib[(y * 15 + x) * 2 * 3 + 2] = (y + 1) * 16 + (x + 0);
ib[(y * 15 + x) * 2 * 3 + 3] = (y + 1) * 16 + (x + 0);
ib[(y * 15 + x) * 2 * 3 + 4] = (y + 0) * 16 + (x + 1);
ib[(y * 15 + x) * 2 * 3 + 5] = (y + 1) * 16 + (x + 1);
}
meshopt_Meshlet ml[1];
unsigned int mv[16 * 16];
unsigned char mt[15 * 15 * 2 * 3 + 3];
size_t mc = meshopt_buildMeshlets(ml, mv, mt, ib, sizeof(ib) / sizeof(ib[0]), vb, 16 * 16, sizeof(float) * 3, 256, 512, 0.f);
assert(mc == 1);
assert(ml[0].triangle_count == 450);
assert(ml[0].vertex_count == 256);
meshopt_optimizeMeshlet(mv, mt, ml[0].triangle_count, ml[0].vertex_count);
// check sequential ordering of remapped indices
int vmax = -1;
for (size_t i = 0; i < 450 * 3; ++i)
{
assert(mt[i] <= vmax + 1);
vmax = vmax < mt[i] ? mt[i] : vmax;
}
}
static void meshletsSpatial()
{
// two tetrahedrons far apart
float vb[2 * 4 * 3] = {
0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1,
10, 0, 0, 11, 0, 0, 10, 1, 0, 10, 0, 1, // clang-format :-/
};
unsigned int ib[2 * 4 * 3] = {
0, 1, 2, 0, 2, 3, 0, 3, 1, 1, 3, 2,
4, 5, 6, 4, 6, 7, 4, 7, 5, 5, 7, 6, // clang-format :-/
};
// up to 2 meshlets with min_triangles=4
assert(meshopt_buildMeshletsBound(2 * 4 * 3, 16, 4) == 2);
meshopt_Meshlet ml[2];
unsigned int mv[2 * 16];
unsigned char mt[2 * 8 * 3]; // 2 meshlets with up to 8 triangles
// with strict limits, we should get one meshlet (maxt=8) or two (maxt=4)
assert(meshopt_buildMeshletsSpatial(ml, mv, mt, ib, sizeof(ib) / sizeof(ib[0]), vb, 8, sizeof(float) * 3, 16, 8, 8, 0.f) == 1);
assert(ml[0].triangle_count == 8);
assert(ml[0].vertex_count == 8);
assert(meshopt_buildMeshletsSpatial(ml, mv, mt, ib, sizeof(ib) / sizeof(ib[0]), vb, 8, sizeof(float) * 3, 16, 4, 4, 0.f) == 2);
assert(ml[0].triangle_count == 4);
assert(ml[0].vertex_count == 4);
assert(ml[1].triangle_count == 4);
assert(ml[1].vertex_count == 4);
// with maxv=4 we should get two meshlets since we can't accomodate both
assert(meshopt_buildMeshletsSpatial(ml, mv, mt, ib, sizeof(ib) / sizeof(ib[0]), vb, 8, sizeof(float) * 3, 4, 4, 8, 0.f) == 2);
assert(ml[0].triangle_count == 4);
assert(ml[0].vertex_count == 4);
assert(ml[1].triangle_count == 4);
assert(ml[1].vertex_count == 4);
}
static void meshletsSpatialDeep()
{
const int N = 400;
const size_t max_vertices = 4;
const size_t max_triangles = 4;
float vb[(N + 1) * 3];
unsigned int ib[N * 3];
vb[0] = vb[1] = vb[2] = 0;
for (size_t i = 0; i < N; ++i)
{
vb[(i + 1) * 3 + 0] = vb[(i + 1) * 3 + 1] = vb[(i + 1) * 3 + 2] = powf(1.2f, float(i));
ib[i * 3 + 0] = 0;
ib[i * 3 + 1] = ib[i * 3 + 2] = unsigned(i + 1);
}
size_t max_meshlets = meshopt_buildMeshletsBound(N * 3, max_vertices, max_triangles);
std::vector<meshopt_Meshlet> meshlets(max_meshlets);
std::vector<unsigned int> meshlet_vertices(N * 3);
std::vector<unsigned char> meshlet_triangles(N * 3);
size_t result = meshopt_buildMeshletsSpatial(&meshlets[0], &meshlet_vertices[0], &meshlet_triangles[0], &ib[0], N * 3, &vb[0], N + 1, sizeof(float) * 3, max_vertices, max_triangles, max_triangles, 0.f);
assert(result == N);
}
static void partitionBasic()
{
// 0 1 2
// 3
// 4 5 6 7 8
// 9
// 10 11 12
const unsigned int ci[] = {
0, 1, 3, 4, 5, 6,
1, 2, 3, 6, 7, 8,
4, 5, 6, 9, 10, 11,
6, 7, 8, 9, 11, 12, // clang-format :-/
};
const unsigned int cc[4] = {6, 6, 6, 6};
unsigned int part[4];
assert(meshopt_partitionClusters(part, ci, sizeof(ci) / sizeof(ci[0]), cc, 4, NULL, 13, 0, 1) == 4);
assert(part[0] == 0 && part[1] == 1 && part[2] == 2 && part[3] == 3);
assert(meshopt_partitionClusters(part, ci, sizeof(ci) / sizeof(ci[0]), cc, 4, NULL, 13, 0, 2) == 2);
assert(part[0] == 0 && part[1] == 0 && part[2] == 1 && part[3] == 1);
assert(meshopt_partitionClusters(part, ci, sizeof(ci) / sizeof(ci[0]), cc, 4, NULL, 13, 0, 4) == 1);
assert(part[0] == 0 && part[1] == 0 && part[2] == 0 && part[3] == 0);
}
static void partitionSpatial()
{
const unsigned int ci[] = {
0, 1, 2,
0, 3, 4,
0, 5, 6, // clang-format :-/
};
const float vb[] = {
0, 0, 0,
1, 0, 0, 0, 1, 0,
0, 2, 0, 2, 0, 0,
-1, 0, 0, 0, -1, 0, // clang-format :-/
};
const unsigned int cc[3] = {3, 3, 3};
unsigned int part[3];
assert(meshopt_partitionClusters(part, ci, sizeof(ci) / sizeof(ci[0]), cc, 3, NULL, 7, 0, 2) == 2);
assert(part[0] == 0 && part[1] == 0 && part[2] == 1);
assert(meshopt_partitionClusters(part, ci, sizeof(ci) / sizeof(ci[0]), cc, 3, vb, 7, sizeof(float) * 3, 2) == 2);
assert(part[0] == 0 && part[1] == 1 && part[2] == 0);
}
static void partitionSpatialMerge()
{
const unsigned int ci[] = {
0, 1, 2,
3, 4, 5,
6, 7, 8, // clang-format :-/
};
const float vb[] = {
0, 0, 0, 1, 0, 0, 0, 1, 0,
0, 0, 0, 0, 2, 0, 2, 0, 0,
10, 0, 0, 10, 1, 0, 10, 2, 0, // clang-format :-/
};
const unsigned int cc[3] = {3, 3, 3};
unsigned int part[3];
assert(meshopt_partitionClusters(part, ci, sizeof(ci) / sizeof(ci[0]), cc, 3, NULL, 9, 0, 2) == 3);
assert(part[0] == 0 && part[1] == 1 && part[2] == 2);
assert(meshopt_partitionClusters(part, ci, sizeof(ci) / sizeof(ci[0]), cc, 3, vb, 9, sizeof(float) * 3, 2) == 2);
assert(part[0] == 0 && part[1] == 0 && part[2] == 1);
}
static int remapCustomFalse(void*, unsigned int, unsigned int)
{
return 0;
}
static int remapCustomTrue(void*, unsigned int, unsigned int)
{
return 1;
}
static void remapCustom()
{
const float vb[] = {
0, 0, 0,
1, 0, 0,
0, 1, 0,
0, 0, 1,
1, 0, 0,
0, -0.f, 1, // clang-format
};
unsigned int remap[6];
size_t res;
res = meshopt_generateVertexRemapCustom(remap, NULL, 6, vb, 6, sizeof(float) * 3, NULL, NULL);
assert(res == 4);
for (int i = 0; i < 4; ++i)
assert(remap[i] == unsigned(i));
assert(remap[4] == 1);
assert(remap[5] == 3);
res = meshopt_generateVertexRemapCustom(remap, NULL, 6, vb, 6, sizeof(float) * 3, remapCustomTrue, NULL);
assert(res == 4);
for (int i = 0; i < 4; ++i)
assert(remap[i] == unsigned(i));
assert(remap[4] == 1);
assert(remap[5] == 3);
res = meshopt_generateVertexRemapCustom(remap, NULL, 6, vb, 6, sizeof(float) * 3, remapCustomFalse, NULL);
assert(res == 6);
for (int i = 0; i < 6; ++i)
assert(remap[i] == unsigned(i));
}
static size_t allocCount;
static size_t freeCount;
static void* customAlloc(size_t size)
{
allocCount++;
return malloc(size);
}
static void customFree(void* ptr)
{
freeCount++;
free(ptr);
}
static void customAllocator()
{
meshopt_setAllocator(customAlloc, customFree);
assert(allocCount == 0 && freeCount == 0);
float vb[] = {1, 0, 0, 0, 1, 0, 0, 0, 1};
unsigned int ib[] = {0, 1, 2};
unsigned short ibs[] = {0, 1, 2};
// meshopt_computeClusterBounds doesn't allocate
meshopt_computeClusterBounds(ib, 3, vb, 3, 12);
assert(allocCount == 0 && freeCount == 0);
// ... unless IndexAdapter is used
meshopt_computeClusterBounds(ibs, 3, vb, 3, 12);
assert(allocCount == 1 && freeCount == 1);
// meshopt_optimizeVertexFetch allocates internal remap table and temporary storage for in-place remaps
meshopt_optimizeVertexFetch(vb, ib, 3, vb, 3, 12);
assert(allocCount == 3 && freeCount == 3);
// ... plus one for IndexAdapter
meshopt_optimizeVertexFetch(vb, ibs, 3, vb, 3, 12);
assert(allocCount == 6 && freeCount == 6);
meshopt_setAllocator(operator new, operator delete);
// customAlloc & customFree should not get called anymore
meshopt_optimizeVertexFetch(vb, ib, 3, vb, 3, 12);
assert(allocCount == 6 && freeCount == 6);
allocCount = freeCount = 0;
}
static void emptyMesh()
{
meshopt_optimizeVertexCache(NULL, NULL, 0, 0);
meshopt_optimizeVertexCacheFifo(NULL, NULL, 0, 0, 16);
meshopt_optimizeOverdraw(NULL, NULL, 0, NULL, 0, 12, 1.f);
}
static void simplify()
{
// 0
// 1 2
// 3 4 5
unsigned int ib[] = {
0, 2, 1,
1, 2, 3,
3, 2, 4,
2, 5, 4, // clang-format :-/
};
float vb[] = {
0, 4, 0,
0, 1, 0,
2, 2, 0,
0, 0, 0,
1, 0, 0,
4, 0, 0, // clang-format :-/
};
unsigned int expected[] = {
0,
5,
3,
};
float error;
assert(meshopt_simplify(ib, ib, 12, vb, 6, 12, 3, 1e-2f, 0, &error) == 3);
assert(error < 1e-4f);
assert(memcmp(ib, expected, sizeof(expected)) == 0);
}
static void simplifyStuck()
{
// tetrahedron can't be simplified due to collapse error restrictions
float vb1[] = {0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1};
unsigned int ib1[] = {0, 1, 2, 0, 2, 3, 0, 3, 1, 2, 1, 3};
assert(meshopt_simplify(ib1, ib1, 12, vb1, 4, 12, 6, 1e-3f) == 12);
// 5-vertex strip can't be simplified due to topology restriction since middle triangle has flipped winding
float vb2[] = {0, 0, 0, 1, 0, 0, 2, 0, 0, 0.5f, 1, 0, 1.5f, 1, 0};
unsigned int ib2[] = {0, 1, 3, 3, 1, 4, 1, 2, 4}; // ok
unsigned int ib3[] = {0, 1, 3, 1, 3, 4, 1, 2, 4}; // flipped
assert(meshopt_simplify(ib2, ib2, 9, vb2, 5, 12, 6, 1e-3f) == 6);
assert(meshopt_simplify(ib3, ib3, 9, vb2, 5, 12, 6, 1e-3f) == 9);
// 4-vertex quad with a locked corner can't be simplified due to border error-induced restriction
float vb4[] = {0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0};
unsigned int ib4[] = {0, 1, 3, 0, 3, 2};
assert(meshopt_simplify(ib4, ib4, 6, vb4, 4, 12, 3, 1e-3f) == 6);
// 4-vertex quad with a locked corner can't be simplified due to border error-induced restriction
float vb5[] = {0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0};
unsigned int ib5[] = {0, 1, 4, 0, 3, 2};
assert(meshopt_simplify(ib5, ib5, 6, vb5, 5, 12, 3, 1e-3f) == 6);
}
static void simplifySloppyStuck()
{
const float vb[] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
const unsigned int ib[] = {0, 1, 2, 0, 1, 2};
unsigned int* target = NULL;
// simplifying down to 0 triangles results in 0 immediately
assert(meshopt_simplifySloppy(target, ib, 3, vb, 3, 12, 0, 0.f) == 0);
// simplifying down to 2 triangles given that all triangles are degenerate results in 0 as well
assert(meshopt_simplifySloppy(target, ib, 6, vb, 3, 12, 6, 0.f) == 0);
}
static void simplifySloppyLocks()
{
// 0
// 1 2
// 3 4 5
unsigned int ib[] = {
0, 2, 1,
1, 2, 3,
3, 2, 4,
2, 5, 4, // clang-format :-/
};
float vb[] = {
0, 4, 0,
0, 1, 0,
2, 2, 0,
0, 0, 0,
1, 0, 0,
4, 0, 0, // clang-format :-/
};
// lock spine
unsigned char locks[] = {1, 0, 1, 0, 0, 1};
unsigned int expected[] = {
0,
2,
1,
1,
2,
5,
};
float error;
assert(meshopt_simplifySloppy(ib, ib, 12, vb, 6, 12, locks, 3, 1.f, &error) == 6);
assert(error == 0.f);
assert(memcmp(ib, expected, sizeof(expected)) == 0);
}
static void simplifyPointsStuck()
{
const float vb[] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
// simplifying down to 0 points results in 0 immediately
assert(meshopt_simplifyPoints(NULL, vb, 3, 12, NULL, 0, 0, 0) == 0);
}
static void simplifyFlip()
{
// this mesh has been constructed by taking a tessellated irregular grid with a square cutout
// and progressively collapsing edges until the only ones left violate border or flip constraints.
// there is only one valid non-flip collapse, so we validate that we take it; when flips are allowed,
// the wrong collapse is picked instead.
float vb[] = {
1.000000f, 1.000000f, -1.000000f,
1.000000f, 1.000000f, 1.000000f,
1.000000f, -1.000000f, 1.000000f,
1.000000f, -0.200000f, -0.200000f,
1.000000f, 0.200000f, -0.200000f,
1.000000f, -0.200000f, 0.200000f,
1.000000f, 0.200000f, 0.200000f,
1.000000f, 0.500000f, -0.500000f,
1.000000f, -1.000000f, 0.000000f, // clang-format :-/
};
// the collapse we expect is 7 -> 0
unsigned int ib[] = {
7, 4, 3,
1, 2, 5,
7, 1, 6,
7, 8, 0, // gets removed
7, 6, 4,
8, 5, 2,
8, 7, 3,
8, 3, 5,
5, 6, 1,
7, 0, 1, // gets removed
};
unsigned int expected[] = {
0, 4, 3,
1, 2, 5,
0, 1, 6,
0, 6, 4,
8, 5, 2,
8, 0, 3,
8, 3, 5,
5, 6, 1, // clang-format :-/
};
assert(meshopt_simplify(ib, ib, 30, vb, 9, 12, 3, 1e-3f) == 24);
assert(memcmp(ib, expected, sizeof(expected)) == 0);
}
static void simplifyScale()
{
const float vb[] = {0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3};
assert(meshopt_simplifyScale(vb, 4, 12) == 3.f);
}
static void simplifyDegenerate()
{
float vb[] = {
0.000000f, 0.000000f, 0.000000f,
0.000000f, 1.000000f, 0.000000f,
0.000000f, 2.000000f, 0.000000f,
1.000000f, 0.000000f, 0.000000f,
2.000000f, 0.000000f, 0.000000f,
1.000000f, 1.000000f, 0.000000f, // clang-format :-/
};
// 0 1 2
// 3 5
// 4
unsigned int ib[] = {
0, 1, 3,
3, 1, 5,
1, 2, 5,
3, 5, 4,
1, 0, 1, // these two degenerate triangles create a fake reverse edge
0, 3, 0, // which breaks border classification
};
unsigned int expected[] = {
0, 1, 4,
4, 1, 2, // clang-format :-/
};
assert(meshopt_simplify(ib, ib, 18, vb, 6, 12, 3, 1e-3f) == 6);
assert(memcmp(ib, expected, sizeof(expected)) == 0);
}
static void simplifyLockBorder()
{
float vb[] = {
0.000000f, 0.000000f, 0.000000f,
0.000000f, 1.000000f, 0.000000f,
0.000000f, 2.000000f, 0.000000f,
1.000000f, 0.000000f, 0.000000f,
1.000000f, 1.000000f, 0.000000f,
1.000000f, 2.000000f, 0.000000f,
2.000000f, 0.000000f, 0.000000f,
2.000000f, 1.000000f, 0.000000f,
2.000000f, 2.000000f, 0.000000f, // clang-format :-/
};
// 0 1 2
// 3 4 5
// 6 7 8
unsigned int ib[] = {
0, 1, 3,
3, 1, 4,
1, 2, 4,
4, 2, 5,
3, 4, 6,
6, 4, 7,
4, 5, 7,
7, 5, 8, // clang-format :-/
};
unsigned int expected[] = {
0, 1, 3,
1, 2, 3,
3, 2, 5,
6, 3, 7,
3, 5, 7,
7, 5, 8, // clang-format :-/
};
assert(meshopt_simplify(ib, ib, 24, vb, 9, 12, 3, 1e-3f, meshopt_SimplifyLockBorder) == 18);
assert(memcmp(ib, expected, sizeof(expected)) == 0);
}
static void simplifyAttr(bool skip_g)
{
float vb[8 * 3][6];
for (int y = 0; y < 8; ++y)
{
// first four rows are a blue gradient, next four rows are a yellow gradient
float r = (y < 4) ? 0.8f + y * 0.05f : 0.f;
float g = (y < 4) ? 0.8f + y * 0.05f : 0.f;
float b = (y < 4) ? 0.f : 0.8f + (7 - y) * 0.05f;
for (int x = 0; x < 3; ++x)
{
vb[y * 3 + x][0] = float(x);
vb[y * 3 + x][1] = float(y);
vb[y * 3 + x][2] = 0.03f * x + 0.03f * (y % 2) + (x == 2 && y == 7) * 0.03f;
vb[y * 3 + x][3] = r;
vb[y * 3 + x][4] = g;
vb[y * 3 + x][5] = b;
}
}
unsigned int ib[7 * 2][6];
for (int y = 0; y < 7; ++y)
{
for (int x = 0; x < 2; ++x)
{
ib[y * 2 + x][0] = (y + 0) * 3 + (x + 0);
ib[y * 2 + x][1] = (y + 0) * 3 + (x + 1);
ib[y * 2 + x][2] = (y + 1) * 3 + (x + 0);
ib[y * 2 + x][3] = (y + 1) * 3 + (x + 0);
ib[y * 2 + x][4] = (y + 0) * 3 + (x + 1);
ib[y * 2 + x][5] = (y + 1) * 3 + (x + 1);
}
}
float attr_weights[3] = {0.5f, skip_g ? 0.f : 0.5f, 0.5f};
// *0 1 *2
// 3 4 5
// 6 7 8
// *9 10 *11
// *12 13 *14
// 15 16 17
// 18 19 20
// *21 22 *23
unsigned int expected[3][6] = {
{0, 2, 11, 0, 11, 9},
{9, 11, 12, 12, 11, 14},
{12, 14, 23, 12, 23, 21},
};
assert(meshopt_simplifyWithAttributes(ib[0], ib[0], 7 * 2 * 6, vb[0], 8 * 3, 6 * sizeof(float), vb[0] + 3, 6 * sizeof(float), attr_weights, 3, NULL, 6 * 3, 1e-2f) == 18);
assert(memcmp(ib, expected, sizeof(expected)) == 0);
}
static void simplifyLockFlags()
{
float vb[] = {
0, 0, 0,
0, 1, 0,
0, 2, 0,
1, 0, 0,
1, 1, 0,
1, 2, 0,
2, 0, 0,
2, 1, 0,
2, 2, 0, // clang-format :-/
};
unsigned char lock[9] = {
1, 1, 1,
1, 0, 1,
1, 1, 1, // clang-format :-/
};
// 0 1 2
// 3 4 5
// 6 7 8
unsigned int ib[] = {
0, 1, 3,
3, 1, 4,
1, 2, 4,
4, 2, 5,
3, 4, 6,
6, 4, 7,
4, 5, 7,
7, 5, 8, // clang-format :-/
};
unsigned int expected[] = {
0, 1, 3,
1, 2, 3,
3, 2, 5,
6, 3, 7,
3, 5, 7,
7, 5, 8, // clang-format :-/
};
assert(meshopt_simplifyWithAttributes(ib, ib, 24, vb, 9, 12, NULL, 0, NULL, 0, lock, 3, 1e-3f, 0) == 18);
assert(memcmp(ib, expected, sizeof(expected)) == 0);
}
static void simplifyLockFlagsSeam()
{
float vb[] = {
0, 0, 0,
0, 1, 0,
0, 1, 0,
0, 2, 0,
1, 0, 0,
1, 1, 0,
1, 1, 0,
1, 2, 0,
2, 0, 0,
2, 1, 0,
2, 1, 0,
2, 2, 0, // clang-format :-/
};
unsigned char lock0[12] = {
1, 0, 0, 1,
0, 0, 0, 0,
1, 0, 0, 1, // clang-format :-/
};
unsigned char lock1[12] = {
1, 0, 0, 1,
1, 0, 0, 1,
1, 0, 0, 1, // clang-format :-/
};
unsigned char lock2[12] = {
1, 0, 1, 1,
1, 0, 1, 1,
1, 0, 1, 1, // clang-format :-/
};
unsigned char lock3[12] = {
1, 1, 0, 1,
1, 1, 0, 1,
1, 1, 0, 1, // clang-format :-/
};
// 0 1-2 3
// 4 5-6 7
// 8 9-10 11
unsigned int ib[] = {
0, 1, 4,
4, 1, 5,
4, 5, 8,
8, 5, 9,
2, 3, 6,
6, 3, 7,
6, 7, 10,
10, 7, 11, // clang-format :-/
};
unsigned int res[24];
// with no locks, we should be able to collapse the entire mesh (vertices 1-2 and 9-10 are locked but others can move towards them)
assert(meshopt_simplifyWithAttributes(res, ib, 24, vb, 12, 12, NULL, 0, NULL, 0, NULL, 0, 1.f, 0) == 0);
// with corners locked, we should get two quads
assert(meshopt_simplifyWithAttributes(res, ib, 24, vb, 12, 12, NULL, 0, NULL, 0, lock0, 0, 1.f, 0) == 12);
// with both sides locked, we can only collapse the seam spine
assert(meshopt_simplifyWithAttributes(res, ib, 24, vb, 12, 12, NULL, 0, NULL, 0, lock1, 0, 1.f, 0) == 18);
// with seam spine locked, we can collapse nothing; note that we intentionally test two different lock configurations
// they each lock only one side of the seam spine, which should be equivalent
assert(meshopt_simplifyWithAttributes(res, ib, 24, vb, 12, 12, NULL, 0, NULL, 0, lock2, 0, 1.f, 0) == 24);
assert(meshopt_simplifyWithAttributes(res, ib, 24, vb, 12, 12, NULL, 0, NULL, 0, lock3, 0, 1.f, 0) == 24);
}
static void simplifySparse()
{
float vb[] = {
0, 0, 100,
0, 1, 0,
0, 2, 100,
1, 0, 0.1f,
1, 1, 0.1f,
1, 2, 0.1f,
2, 0, 100,
2, 1, 0,
2, 2, 100, // clang-format :-/
};
float vba[] = {
100,
0.5f,
100,
0.5f,
0.5f,
0,
100,
0.5f,
100, // clang-format :-/
};
float aw[] = {
0.5f};
unsigned char lock[9] = {
8, 1, 8,
1, 0, 1,
8, 1, 8, // clang-format :-/
};
// 1
// 3 4 5
// 7
unsigned int ib[] = {
3, 1, 4,
1, 5, 4,
3, 4, 7,
4, 5, 7, // clang-format :-/
};
unsigned int res[12];
// vertices 3-4-5 are slightly elevated along Z which guides the collapses when only using geometry
unsigned int expected[] = {
1, 5, 3,
3, 5, 7, // clang-format :-/
};
assert(meshopt_simplify(res, ib, 12, vb, 9, 12, 6, 1e-3f, meshopt_SimplifySparse) == 6);
assert(memcmp(res, expected, sizeof(expected)) == 0);
// vertices 1-4-7 have a crease in the attribute value which guides the collapses the opposite way when weighing attributes sufficiently
unsigned int expecteda[] = {
3, 1, 7,
1, 5, 7, // clang-format :-/
};
assert(meshopt_simplifyWithAttributes(res, ib, 12, vb, 9, 12, vba, sizeof(float), aw, 1, lock, 6, 1e-1f, meshopt_SimplifySparse) == 6);
assert(memcmp(res, expecteda, sizeof(expecteda)) == 0);
// a final test validates that destination can alias when using sparsity
assert(meshopt_simplify(ib, ib, 12, vb, 9, 12, 6, 1e-3f, meshopt_SimplifySparse) == 6);
assert(memcmp(ib, expected, sizeof(expected)) == 0);
}
static void simplifyErrorAbsolute()
{
float vb[] = {
0, 0, 0,
0, 1, 0,
0, 2, 0,
1, 0, 0,
1, 1, 1,
1, 2, 0,
2, 0, 0,
2, 1, 0,
2, 2, 0, // clang-format :-/
};
// 0 1 2
// 3 4 5
// 6 7 8
unsigned int ib[] = {
0, 1, 3,
3, 1, 4,
1, 2, 4,
4, 2, 5,
3, 4, 6,
6, 4, 7,
4, 5, 7,
7, 5, 8, // clang-format :-/
};
float error = 0.f;
assert(meshopt_simplify(ib, ib, 24, vb, 9, 12, 18, 2.f, meshopt_SimplifyLockBorder | meshopt_SimplifyErrorAbsolute, &error) == 18);
assert(fabsf(error - 0.85f) < 0.01f);
}
static void simplifySeam()
{
// xyz+attr
float vb[] = {
0, 0, 0, 0,
0, 1, 0, 0,
0, 1, 0, 1,
0, 2, 0, 1,
1, 0, 0, 0,
1, 1, 0.3f, 0,
1, 1, 0.3f, 1,
1, 2, 0, 1,
2, 0, 0, 0,
2, 1, 0.1f, 0,
2, 1, 0.1f, 1,
2, 2, 0, 1,
3, 0, 0, 0,
3, 1, 0, 0,
3, 1, 0, 1,
3, 2, 0, 1, // clang-format :-/
};
// 0 1-2 3
// 4 5-6 7
// 8 9-10 11
// 12 13-14 15
unsigned int ib[] = {
0, 1, 4,
4, 1, 5,
2, 3, 6,
6, 3, 7,
4, 5, 8,
8, 5, 9,
6, 7, 10,
10, 7, 11,
8, 9, 12,
12, 9, 13,
10, 11, 14,
14, 11, 15, // clang-format :-/
};
// note: vertices 1-2 and 13-14 are classified as locked, because they are on a seam & a border
// 0 1-2 3
// 5-6
// 9-10
// 12 13-14 15
unsigned int expected[] = {
0, 1, 13,
2, 3, 14,
0, 13, 12,
14, 3, 15, // clang-format :-/
};
unsigned int res[36];
float error = 0.f;
assert(meshopt_simplify(res, ib, 36, vb, 16, 16, 12, 1.f, 0, &error) == 12);
assert(memcmp(res, expected, sizeof(expected)) == 0);
assert(fabsf(error - 0.1f) < 0.01f); // note: the error is not zero because there is a difference in height between the seam vertices
float aw = 1;
assert(meshopt_simplifyWithAttributes(res, ib, 36, vb, 16, 16, vb + 3, 16, &aw, 1, NULL, 12, 2.f, 0, &error) == 12);
assert(memcmp(res, expected, sizeof(expected)) == 0);
assert(fabsf(error - 0.1f) < 0.01f); // note: this is the same error as above because the attribute is constant on either side of the seam
}
static void simplifySeamFake()
{
// xyz+attr
float vb[] = {
0, 0, 0, 0,
1, 0, 0, 1,
1, 0, 0, 2,
0, 0, 0, 3, // clang-format :-/
};
unsigned int ib[] = {
0, 1, 2,
2, 1, 3, // clang-format :-/
};
assert(meshopt_simplify(ib, ib, 6, vb, 4, 16, 0, 1.f, 0, NULL) == 6);
}
static void simplifySeamAttr()
{
// xyz+attr
float vb[] = {
0, 0, 0, 0,
0, 1, 0, 0,
0, 1, 0, 0,
0, 2, 0, 0,
1, 0, 0, 1,
1, 1, 0, 1,
1, 1, 0, 1,
1, 2, 0, 1,
4, 0, 0, 2,
4, 1, 0, 2,
4, 1, 0, 2,
4, 2, 0, 2, // clang-format :-/
};
// 0 1-2 3
// 4 5-6 7
// 8 9-10 11
unsigned int ib[] = {
0, 1, 4,
4, 1, 5,
2, 3, 6,
6, 3, 7,
4, 5, 8,
8, 5, 9,
6, 7, 10,
10, 7, 11, // clang-format :-/
};
// note: vertices 1-2 and 9-10 are classified as locked, because they are on a seam & a border
// 0 1-2 3
// 4 7
// 8 9-10 11
unsigned int expected[] = {
0, 1, 4,
2, 3, 7,
4, 1, 8,
8, 1, 9,
2, 7, 10,
10, 7, 11, // clang-format :-/
};
unsigned int res[24];
float error = 0.f;
float aw = 1;
assert(meshopt_simplifyWithAttributes(res, ib, 24, vb, 12, 16, vb + 3, 16, &aw, 1, NULL, 12, 2.f, meshopt_SimplifyLockBorder, &error) == 18);
assert(memcmp(res, expected, sizeof(expected)) == 0);
assert(fabsf(error - 0.35f) < 0.01f);
}
static void simplifyDebug()
{
// 0
// 1 2
// 3 4 5
unsigned int ib[] = {
0, 2, 1,
1, 2, 3,
3, 2, 4,
2, 5, 4, // clang-format :-/
};
float vb[] = {
0, 4, 0,
0, 1, 0,
2, 2, 0,
0, 0, 0,
1, 0, 0,
4, 0, 0, // clang-format :-/
};
unsigned int expected[] = {
0 | (9u << 28),
5 | (9u << 28),
3 | (9u << 28),
};
const unsigned int meshopt_SimplifyInternalDebug = 1 << 30;
float error;
assert(meshopt_simplify(ib, ib, 12, vb, 6, 12, 3, 1e-2f, meshopt_SimplifyInternalDebug, &error) == 3);
assert(error < 1e-4f);
assert(memcmp(ib, expected, sizeof(expected)) == 0);
}
static void simplifyPrune()
{
// 0
// 1 2
// 3 4 5
// +
// 6 7 8 (same position)
unsigned int ib[] = {
3, 2, 4,
0, 2, 1,
1, 2, 3,
2, 5, 4,
6, 7, 8, // clang-format :-/
};
float vb[] = {
0, 4, 0,
0, 1, 0,
2, 2, 0,
0, 0, 0,
1, 0, 0,
4, 0, 0,
1, 1, 1,
1, 1, 1,
1, 1, 1, // clang-format :-/
};
unsigned int expected[] = {
0,
5,
3,
};
float error;
assert(meshopt_simplify(ib, ib, 15, vb, 9, 12, 3, 1e-2f, meshopt_SimplifyPrune, &error) == 3);
assert(error < 1e-4f);
assert(memcmp(ib, expected, sizeof(expected)) == 0);
// re-run prune with and without sparsity on a small subset to make sure the component code correctly handles sparse subsets
assert(meshopt_simplify(ib, ib, 3, vb, 9, 12, 3, 1e-2f, meshopt_SimplifyPrune, &error) == 3);
assert(meshopt_simplify(ib, ib, 3, vb, 9, 12, 3, 1e-2f, meshopt_SimplifyPrune | meshopt_SimplifySparse, &error) == 3);
assert(memcmp(ib, expected, sizeof(expected)) == 0);
}
static void simplifyPruneCleanup()
{
unsigned int ib[] = {
0, 1, 2,
3, 4, 5,
6, 7, 8, // clang-format :-/
};
float vb[] = {
0, 0, 0,
0, 1, 0,
1, 0, 0,
0, 0, 1,
0, 2, 1,
2, 0, 1,
0, 0, 2,
0, 4, 2,
4, 0, 2, // clang-format :-/
};
unsigned int expected[] = {
6,
7,
8,
};
float error;
assert(meshopt_simplify(ib, ib, 9, vb, 9, 12, 3, 1.f, meshopt_SimplifyLockBorder | meshopt_SimplifyPrune, &error) == 3);
assert(fabsf(error - 0.37f) < 0.01f);
assert(memcmp(ib, expected, sizeof(expected)) == 0);
}
static void simplifyPruneFunc()
{
unsigned int ib[] = {
0, 1, 2,
3, 4, 5,
6, 7, 8, // clang-format :-/
};
float vb[] = {
0, 0, 0,
0, 1, 0,
1, 0, 0,
0, 0, 1,
0, 2, 1,
2, 0, 1,
0, 0, 2,
0, 4, 2,
4, 0, 2, // clang-format :-/
};
unsigned int expected[] = {
6,
7,
8,
};
assert(meshopt_simplifyPrune(ib, ib, 9, vb, 9, 12, 0.5f) == 3);
assert(memcmp(ib, expected, sizeof(expected)) == 0);
}
static void simplifyUpdate()
{
float vb[5][4] = {
{0, 0, 0, 0},
{1, 1, 0, 0},
{2, 0, 0, 0},
{0.9f, 0.2f, 0.1f, 0.2f},
{1.1f, 0.2f, 0.1f, 0.1f},
};
// 1
// 3 4
// 0 2
unsigned int ib[15] = {
0, 1, 3, 3, 1, 4, 4, 1, 2, 0, 3, 2, 3, 4, 2, //
};
float attr_weight = 1.f;
assert(meshopt_simplifyWithUpdate(ib, 15, vb[0], 5, 4 * sizeof(float), vb[0] + 3, 4 * sizeof(float), &attr_weight, 1, NULL, 9, 1.f) == 9);
unsigned int expected[] = {
0, 1, 3, 3, 1, 2, 0, 3, 2, //
};
assert(memcmp(ib, expected, sizeof(expected)) == 0);
// border vertices haven't moved but may have small floating point drift
for (int i = 0; i < 3; ++i)
assert(fabsf(vb[i][3]) < 1e-6f);
// center vertex got updated
assert(fabsf(vb[3][0] - 0.88f) < 1e-2f);
assert(fabsf(vb[3][1] - 0.19f) < 1e-2f);
assert(fabsf(vb[3][2] - 0.11f) < 1e-2f);
assert(fabsf(vb[3][3] - 0.18f) < 1e-2f);
}
static void simplifyUpdateLocked(unsigned int options)
{
float vb[5][4] = {
{0, 0, 0, 0},
{1, 1, 0, 0},
{2, 0, 0, 0},
{0.9f, 0.2f, 0.1f, 0.2f},
{1.1f, 0.2f, 0.1f, 0.1f},
};
// 1
// 3 4
// 0 2
unsigned int ib[15] = {
0, 1, 3, 3, 1, 4, 4, 1, 2, 0, 3, 2, 3, 4, 2, //
};
float attr_weight = 1.f;
unsigned char vertex_lock[5] = {0, 0, 0, 1, 0};
assert(meshopt_simplifyWithUpdate(ib, 15, vb[0], 5, 4 * sizeof(float), vb[0] + 3, 4 * sizeof(float), &attr_weight, 1, vertex_lock, 9, 1.f, options) == 9);
unsigned int expected[] = {
0, 1, 3, 3, 1, 2, 0, 3, 2, //
};
assert(memcmp(ib, expected, sizeof(expected)) == 0);
for (int i = 0; i < 3; ++i)
assert(fabsf(vb[i][3]) < 1e-6f);
// locking guarantees exact result
assert(vb[3][0] == 0.9f);
assert(vb[3][1] == 0.2f);
assert(vb[3][2] == 0.1f);
assert(vb[3][3] == 0.2f);
}
static void adjacency()
{
// 0 1/4
// 2/5 3
const float vb[] = {0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0};
const unsigned int ib[] = {0, 1, 2, 5, 4, 3};
unsigned int adjib[12];
meshopt_generateAdjacencyIndexBuffer(adjib, ib, 6, vb, 6, 12);
unsigned int expected[] = {
// patch 0
0, 0,
1, 3,
2, 2,
// patch 1
5, 0,
4, 4,
3, 3,
// clang-format :-/
};
assert(memcmp(adjib, expected, sizeof(expected)) == 0);
}
static void tessellation()
{
// 0 1/4
// 2/5 3
const float vb[] = {0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0};
const unsigned int ib[] = {0, 1, 2, 5, 4, 3};
unsigned int tessib[24];
meshopt_generateTessellationIndexBuffer(tessib, ib, 6, vb, 6, 12);
unsigned int expected[] = {
// patch 0
0, 1, 2,
0, 1,
4, 5,
2, 0,
0, 1, 2,
// patch 1
5, 4, 3,
2, 1,
4, 3,
3, 5,
2, 1, 3,
// clang-format :-/
};
assert(memcmp(tessib, expected, sizeof(expected)) == 0);
}
static void provoking()
{
// 0 1 2
// 3 4 5
const unsigned int ib[] = {
0, 1, 3,
3, 1, 4,
1, 2, 4,
4, 2, 5,
0, 2, 4,
// clang-format :-/
};
unsigned int pib[15];
unsigned int pre[6 + 5]; // limit is vertex count + triangle count
size_t res = meshopt_generateProvokingIndexBuffer(pib, pre, ib, 15, 6);
unsigned int expectedib[] = {
0, 5, 1,
1, 4, 0,
2, 4, 1,
3, 4, 2,
4, 5, 2,
// clang-format :-/
};
unsigned int expectedre[] = {
3, 1, 2, 5, 4, 0,
// clang-format :-/
};
assert(res == 6);
assert(memcmp(pib, expectedib, sizeof(expectedib)) == 0);
assert(memcmp(pre, expectedre, sizeof(expectedre)) == 0);
}
static void quantizeFloat()
{
volatile float zero = 0.f; // avoids div-by-zero warnings
assert(meshopt_quantizeFloat(1.2345f, 23) == 1.2345f);
assert(meshopt_quantizeFloat(1.2345f, 16) == 1.2344971f);
assert(meshopt_quantizeFloat(1.2345f, 8) == 1.2343750f);
assert(meshopt_quantizeFloat(1.2345f, 4) == 1.25f);
assert(meshopt_quantizeFloat(1.2345f, 1) == 1.0);
assert(meshopt_quantizeFloat(1.f, 0) == 1.0f);
assert(meshopt_quantizeFloat(1.f / zero, 0) == 1.f / zero);
assert(meshopt_quantizeFloat(-1.f / zero, 0) == -1.f / zero);
float nanf = meshopt_quantizeFloat(zero / zero, 8);
assert(nanf != nanf);
}
static void quantizeHalf()
{
volatile float zero = 0.f; // avoids div-by-zero warnings
// normal
assert(meshopt_quantizeHalf(1.2345f) == 0x3cf0);
// overflow
assert(meshopt_quantizeHalf(65535.f) == 0x7c00);
assert(meshopt_quantizeHalf(-65535.f) == 0xfc00);
// large
assert(meshopt_quantizeHalf(65000.f) == 0x7bef);
assert(meshopt_quantizeHalf(-65000.f) == 0xfbef);
// small
assert(meshopt_quantizeHalf(0.125f) == 0x3000);
assert(meshopt_quantizeHalf(-0.125f) == 0xb000);
// very small
assert(meshopt_quantizeHalf(1e-4f) == 0x068e);
assert(meshopt_quantizeHalf(-1e-4f) == 0x868e);
// underflow
assert(meshopt_quantizeHalf(1e-5f) == 0x0000);
assert(meshopt_quantizeHalf(-1e-5f) == 0x8000);
// exponent underflow
assert(meshopt_quantizeHalf(1e-20f) == 0x0000);
assert(meshopt_quantizeHalf(-1e-20f) == 0x8000);
// exponent overflow
assert(meshopt_quantizeHalf(1e20f) == 0x7c00);
assert(meshopt_quantizeHalf(-1e20f) == 0xfc00);
// inf
assert(meshopt_quantizeHalf(1.f / zero) == 0x7c00);
assert(meshopt_quantizeHalf(-1.f / zero) == 0xfc00);
// nan
unsigned short nanh = meshopt_quantizeHalf(zero / zero);
assert(nanh == 0x7e00 || nanh == 0xfe00);
}
static void dequantizeHalf()
{
volatile float zero = 0.f; // avoids div-by-zero warnings
// normal
assert(meshopt_dequantizeHalf(0x3cf0) == 1.234375f);
// large
assert(meshopt_dequantizeHalf(0x7bef) == 64992.f);
assert(meshopt_dequantizeHalf(0xfbef) == -64992.f);
// small
assert(meshopt_dequantizeHalf(0x3000) == 0.125f);
assert(meshopt_dequantizeHalf(0xb000) == -0.125f);
// very small
assert(meshopt_dequantizeHalf(0x068e) == 1.00016594e-4f);
assert(meshopt_dequantizeHalf(0x868e) == -1.00016594e-4f);
// denormal
assert(meshopt_dequantizeHalf(0x00ff) == 0.f);
assert(meshopt_dequantizeHalf(0x80ff) == 0.f); // actually this is -0.f
assert(1.f / meshopt_dequantizeHalf(0x80ff) == -1.f / zero);
// inf
assert(meshopt_dequantizeHalf(0x7c00) == 1.f / zero);
assert(meshopt_dequantizeHalf(0xfc00) == -1.f / zero);
// nan
float nanf = meshopt_dequantizeHalf(0x7e00);
assert(nanf != nanf);
}
static void encodeMeshletBound()
{
const unsigned char triangles[5 * 3] = {
0, 1, 2,
2, 1, 3,
3, 5, 4,
2, 0, 6,
7, 7, 7, // clang-format :-/
};
const unsigned int vertices[7] = {
5,
12,
140,
0,
12389,
123456789,
7,
};
size_t bound = meshopt_encodeMeshletBound(7, 5);
unsigned char enc[256];
size_t size = meshopt_encodeMeshlet(enc, sizeof(enc), vertices, 7, triangles, 5);
assert(size > 0 && size <= bound);
assert(meshopt_encodeMeshlet(enc, size - 1, vertices, 7, triangles, 5) == 0);
}
template <typename V, typename T, size_t VS, size_t TS>
static void validateDecodeMeshlet(const unsigned char* data, size_t size, const unsigned int* vertices, size_t vertex_count, const unsigned char* triangles, size_t triangle_count)
{
V rv[VS];
T rt[TS];
int rc = meshopt_decodeMeshlet(rv, vertex_count, rt, triangle_count, data, size);
assert(rc == 0);
for (size_t j = 0; j < vertex_count; ++j)
assert(rv[j] == V(vertices[j]));
for (size_t j = 0; j < triangle_count; ++j)
{
unsigned int a = triangles[j * 3 + 0];
unsigned int b = triangles[j * 3 + 1];
unsigned int c = triangles[j * 3 + 2];
unsigned int tri = sizeof(T) == 1 ? rt[j * 3] | (rt[j * 3 + 1] << 8) | (rt[j * 3 + 2] << 16) : rt[j];
unsigned int abc = (a << 0) | (b << 8) | (c << 16);
unsigned int bca = (b << 0) | (c << 8) | (a << 16);
unsigned int cba = (c << 0) | (a << 8) | (b << 16);
assert(tri == abc || tri == bca || tri == cba);
}
}
static void decodeMeshletSafety()
{
const unsigned char triangles[5 * 3] = {
0, 1, 2,
2, 1, 3,
3, 5, 4,
2, 0, 6,
6, 6, 6, // clang-format :-/
};
const unsigned int vertices[7] = {
5,
12,
140,
0,
12389,
123456789,
7,
};
unsigned char encb[256];
size_t size = meshopt_encodeMeshlet(encb, sizeof(encb), vertices, 7, triangles, 5);
assert(size > 0);
// move encoded buffer to the end to make sure any over-reads trigger sanitizers
unsigned char* enc = encb + sizeof(encb) - size;
memmove(enc, encb, size);
validateDecodeMeshlet<unsigned int, unsigned int, /* VS= */ 7, /* TS= */ 5>(enc, size, vertices, 7, triangles, 5);
// decodeMeshlet uses aligned 32-bit writes => must round vertex/triangle storage up when using short/char decoding
// note the +1 in triangle storage is because align(5*3, 4) = 16; it's up to +3 in general case
validateDecodeMeshlet<unsigned int, unsigned char, /* VS= */ 7, /* TS= */ 5 * 3 + 1>(enc, size, vertices, 7, triangles, 5);
validateDecodeMeshlet<unsigned short, unsigned int, /* VS= */ 7 + 1, /* TS= */ 5>(enc, size, vertices, 7, triangles, 5);
validateDecodeMeshlet<unsigned short, unsigned char, /* VS= */ 7 + 1, /* TS= */ 5 * 3 + 1>(enc, size, vertices, 7, triangles, 5);
// any truncated input should not be decodable; we check both prefix and suffix truncation
unsigned int rv[7], rt[5];
for (size_t i = 1; i < size; ++i)
assert(meshopt_decodeMeshlet(rv, 7, rt, 5, enc, i) < 0);
for (size_t i = 1; i < size; ++i)
assert(meshopt_decodeMeshlet(rv, 7, rt, 5, enc + i, size - i) < 0);
// because SIMD implementation is specialized by size, we need to test truncated inputs for short representations
unsigned short rvs[7 + 1]; // 32b alignment
unsigned char rts[5 * 3 + 1]; // 32b alignment
for (size_t i = 1; i < size; ++i)
assert(meshopt_decodeMeshlet(rvs, 7, rts, 5, enc, i) < 0);
for (size_t i = 1; i < size; ++i)
assert(meshopt_decodeMeshlet(rvs, 7, rts, 5, enc + i, size - i) < 0);
// when using decodeMeshletRaw, the output buffer sizes must be 16b aligned
unsigned int rvr[8], rtr[8];
for (size_t i = 1; i < size; ++i)
assert(meshopt_decodeMeshletRaw(rvr, 7, rtr, 5, enc, i) < 0);
for (size_t i = 1; i < size; ++i)
assert(meshopt_decodeMeshletRaw(rvr, 7, rtr, 5, enc + i, size - i) < 0);
// otherwise, decodeMeshlet and decodeMeshletRaw should agree
int rc = meshopt_decodeMeshlet(rv, 7, rt, 5, enc, size);
int rcr = meshopt_decodeMeshletRaw(rvr, 7, rtr, 5, enc, size);
assert(rc == 0 && rcr == 0);
assert(memcmp(rv, rvr, 7 * sizeof(unsigned int)) == 0);
assert(memcmp(rt, rtr, 5 * sizeof(unsigned int)) == 0);
}
static void decodeMeshletBasic()
{
const unsigned char triangles[5 * 3] = {
0, 1, 2,
2, 1, 3,
4, 3, 5,
2, 0, 6,
6, 6, 6, // clang-format :-/
};
const unsigned int vertices[7] = {
5,
12,
140,
0,
12389,
123456789,
7,
};
const unsigned char encoded[46] = {
0x0a, 0x0c, 0xfe, 0x19, 0x01, 0xc8, 0x60, 0x00, 0x00, 0x5e, 0x39, 0xb7, 0x0e, 0x1d, 0x9a, 0xb7,
0x0e, 0x00, 0x00, 0x00, 0x00, 0x04, 0x03, 0x05, 0x02, 0x00, 0x06, 0x06, 0x06, 0x06, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x87, 0xff, 0x2c, 0xff, 0x0f, // clang-format :-/
};
unsigned int rv[7];
unsigned char rt[5 * 3 + 1];
int rc = meshopt_decodeMeshlet(rv, 7, rt, 5, encoded, sizeof(encoded));
assert(rc == 0);
assert(memcmp(rv, vertices, sizeof(vertices)) == 0);
assert(memcmp(rt, triangles, sizeof(triangles)) == 0);
}
static void decodeMeshletTypical()
{
const unsigned char triangles[44 * 3] = {
0, 1, 2, 0, 2, 3, 3, 2, 4, 3, 4, 5, 0, 3, 6, 6, 3, 5, 0, 6, 7, 7, 6, 8,
8, 6, 5, 7, 8, 9, 8, 5, 10, 10, 5, 4, 10, 4, 11, 11, 4, 12, 11, 12, 13, 10, 11, 14,
10, 14, 8, 14, 11, 15, 15, 11, 13, 15, 13, 16, 15, 16, 14, 16, 13, 17, 14, 16, 18, 14, 18, 8,
18, 16, 19, 19, 16, 20, 20, 16, 17, 20, 17, 21, 20, 21, 22, 20, 22, 19, 22, 21, 23, 19, 22, 24,
19, 24, 25, 19, 25, 18, 18, 25, 26, 18, 26, 8, 8, 26, 9, 22, 23, 27, 22, 27, 24, 27, 23, 28,
27, 28, 29, 27, 29, 24, 29, 28, 30, 24, 29, 31, // clang-format :-/
};
const unsigned int vertices[32] = {
10, 11, 9, 12, 8, 13, 14, 15, 16, 17, 18, 19, 0, 20, 21, 22,
23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // clang-format :-/
};
const unsigned char encoded[53] = {
0x14, 0x05, 0x04, 0x09, 0x08, 0x27, 0x26, 0x05, 0x05, 0x04, 0x08, 0x0d, 0x0e, 0x08, 0x11, 0x13,
0x12, 0x08, 0x09, 0x16, 0x17, 0x18, 0x18, 0x0d, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x0c,
0x02, 0x38, 0x24, 0x43, 0x34, 0x20, 0x80, 0x61, 0x03, 0x61, 0x16, 0x26, 0x03, 0x10, 0x66, 0x10,
0x12, 0xe3, 0x61, 0x10, 0x66, // clang-format :-/
};
unsigned int rv[32];
unsigned char rt[44 * 3];
int rc = meshopt_decodeMeshlet(rv, 32, rt, 44, encoded, sizeof(encoded));
assert(rc == 0);
assert(memcmp(rv, vertices, sizeof(vertices)) == 0);
assert(memcmp(rt, triangles, sizeof(triangles)) == 0);
}
void runTests()
{
decodeIndexV0();
decodeIndexV1();
decodeIndexV1More();
decodeIndexV1ThreeEdges();
decodeIndex16();
encodeIndexMemorySafe();
decodeIndexMemorySafe();
decodeIndexRejectExtraBytes();
decodeIndexRejectMalformedHeaders();
decodeIndexRejectInvalidVersion();
decodeIndexMalformedVByte();
roundtripIndexTricky();
encodeIndexEmpty();
decodeIndexSequence();
decodeIndexSequence16();
encodeIndexSequenceMemorySafe();
decodeIndexSequenceMemorySafe();
decodeIndexSequenceRejectExtraBytes();
decodeIndexSequenceRejectMalformedHeaders();
decodeIndexSequenceRejectInvalidVersion();
encodeIndexSequenceEmpty();
decodeVertexV0();
decodeVertexV0More();
decodeVertexV0Mode2();
decodeVertexV1();
decodeVertexV1Custom();
decodeVertexV1Deltas();
for (int version = 0; version <= 1; ++version)
{
meshopt_encodeVertexVersion(version);
decodeVertexMemorySafe();
decodeVertexRejectExtraBytes();
decodeVertexRejectMalformedHeaders();
decodeVertexBitGroups();
decodeVertexBitGroupSentinels();
decodeVertexDeltas();
decodeVertexBitXor();
decodeVertexLarge();
decodeVertexSmall();
encodeVertexEmpty();
encodeVertexMemorySafe();
}
decodeVersion();
decodeFilterOct8();
decodeFilterOct12();
decodeFilterQuat12();
decodeFilterExp();
encodeFilterOct8();
encodeFilterOct12();
encodeFilterQuat12();
encodeFilterExp();
encodeFilterExpZero();
encodeFilterExpAlias();
encodeFilterExpClamp();
encodeFilterColor8();
encodeFilterColor12();
clusterBoundsDegenerate();
sphereBounds();
meshletsEmpty();
meshletsDense();
meshletsSparse();
meshletsFlex();
meshletsMax();
meshletsSpatial();
meshletsSpatialDeep();
partitionBasic();
partitionSpatial();
partitionSpatialMerge();
remapCustom();
customAllocator();
emptyMesh();
simplify();
simplifyStuck();
simplifySloppyStuck();
simplifySloppyLocks();
simplifyPointsStuck();
simplifyFlip();
simplifyScale();
simplifyDegenerate();
simplifyLockBorder();
simplifyAttr(/* skip_g= */ false);
simplifyAttr(/* skip_g= */ true);
simplifyLockFlags();
simplifyLockFlagsSeam();
simplifySparse();
simplifyErrorAbsolute();
simplifySeam();
simplifySeamFake();
simplifySeamAttr();
simplifyDebug();
simplifyPrune();
simplifyPruneCleanup();
simplifyPruneFunc();
simplifyUpdate();
simplifyUpdateLocked(0);
simplifyUpdateLocked(meshopt_SimplifySparse);
adjacency();
tessellation();
provoking();
quantizeFloat();
quantizeHalf();
dequantizeHalf();
encodeMeshletBound();
decodeMeshletSafety();
decodeMeshletBasic();
decodeMeshletTypical();
}
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
extern/cgltf.h | C/C++ Header | /**
* cgltf - a single-file glTF 2.0 parser written in C99.
*
* Version: 1.15
*
* Website: https://github.com/jkuhlmann/cgltf
*
* Distributed under the MIT License, see notice at the end of this file.
*
* Building:
* Include this file where you need the struct and function
* declarations. Have exactly one source file where you define
* `CGLTF_IMPLEMENTATION` before including this file to get the
* function definitions.
*
* Reference:
* `cgltf_result cgltf_parse(const cgltf_options*, const void*,
* cgltf_size, cgltf_data**)` parses both glTF and GLB data. If
* this function returns `cgltf_result_success`, you have to call
* `cgltf_free()` on the created `cgltf_data*` variable.
* Note that contents of external files for buffers and images are not
* automatically loaded. You'll need to read these files yourself using
* URIs in the `cgltf_data` structure.
*
* `cgltf_options` is the struct passed to `cgltf_parse()` to control
* parts of the parsing process. You can use it to force the file type
* and provide memory allocation as well as file operation callbacks.
* Should be zero-initialized to trigger default behavior.
*
* `cgltf_data` is the struct allocated and filled by `cgltf_parse()`.
* It generally mirrors the glTF format as described by the spec (see
* https://github.com/KhronosGroup/glTF/tree/master/specification/2.0).
*
* `void cgltf_free(cgltf_data*)` frees the allocated `cgltf_data`
* variable.
*
* `cgltf_result cgltf_load_buffers(const cgltf_options*, cgltf_data*,
* const char* gltf_path)` can be optionally called to open and read buffer
* files using the `FILE*` APIs. The `gltf_path` argument is the path to
* the original glTF file, which allows the parser to resolve the path to
* buffer files.
*
* `cgltf_result cgltf_load_buffer_base64(const cgltf_options* options,
* cgltf_size size, const char* base64, void** out_data)` decodes
* base64-encoded data content. Used internally by `cgltf_load_buffers()`.
* This is useful when decoding data URIs in images.
*
* `cgltf_result cgltf_parse_file(const cgltf_options* options, const
* char* path, cgltf_data** out_data)` can be used to open the given
* file using `FILE*` APIs and parse the data using `cgltf_parse()`.
*
* `cgltf_result cgltf_validate(cgltf_data*)` can be used to do additional
* checks to make sure the parsed glTF data is valid.
*
* `cgltf_node_transform_local` converts the translation / rotation / scale properties of a node
* into a mat4.
*
* `cgltf_node_transform_world` calls `cgltf_node_transform_local` on every ancestor in order
* to compute the root-to-node transformation.
*
* `cgltf_accessor_unpack_floats` reads in the data from an accessor, applies sparse data (if any),
* and converts them to floating point. Assumes that `cgltf_load_buffers` has already been called.
* By passing null for the output pointer, users can find out how many floats are required in the
* output buffer.
*
* `cgltf_accessor_unpack_indices` reads in the index data from an accessor. Assumes that
* `cgltf_load_buffers` has already been called. By passing null for the output pointer, users can
* find out how many indices are required in the output buffer. Returns 0 if the accessor is
* sparse or if the output component size is less than the accessor's component size.
*
* `cgltf_num_components` is a tiny utility that tells you the dimensionality of
* a certain accessor type. This can be used before `cgltf_accessor_unpack_floats` to help allocate
* the necessary amount of memory. `cgltf_component_size` and `cgltf_calc_size` exist for
* similar purposes.
*
* `cgltf_accessor_read_float` reads a certain element from a non-sparse accessor and converts it to
* floating point, assuming that `cgltf_load_buffers` has already been called. The passed-in element
* size is the number of floats in the output buffer, which should be in the range [1, 16]. Returns
* false if the passed-in element_size is too small, or if the accessor is sparse.
*
* `cgltf_accessor_read_uint` is similar to its floating-point counterpart, but limited to reading
* vector types and does not support matrix types. The passed-in element size is the number of uints
* in the output buffer, which should be in the range [1, 4]. Returns false if the passed-in
* element_size is too small, or if the accessor is sparse.
*
* `cgltf_accessor_read_index` is similar to its floating-point counterpart, but it returns size_t
* and only works with single-component data types.
*
* `cgltf_copy_extras_json` allows users to retrieve the "extras" data that can be attached to many
* glTF objects (which can be arbitrary JSON data). This is a legacy function, consider using
* cgltf_extras::data directly instead. You can parse this data using your own JSON parser
* or, if you've included the cgltf implementation using the integrated JSMN JSON parser.
*/
#ifndef CGLTF_H_INCLUDED__
#define CGLTF_H_INCLUDED__
#include <stddef.h>
#include <stdint.h> /* For uint8_t, uint32_t */
#ifdef __cplusplus
extern "C" {
#endif
typedef size_t cgltf_size;
typedef long long int cgltf_ssize;
typedef float cgltf_float;
typedef int cgltf_int;
typedef unsigned int cgltf_uint;
typedef int cgltf_bool;
typedef enum cgltf_file_type
{
cgltf_file_type_invalid,
cgltf_file_type_gltf,
cgltf_file_type_glb,
cgltf_file_type_max_enum
} cgltf_file_type;
typedef enum cgltf_result
{
cgltf_result_success,
cgltf_result_data_too_short,
cgltf_result_unknown_format,
cgltf_result_invalid_json,
cgltf_result_invalid_gltf,
cgltf_result_invalid_options,
cgltf_result_file_not_found,
cgltf_result_io_error,
cgltf_result_out_of_memory,
cgltf_result_legacy_gltf,
cgltf_result_max_enum
} cgltf_result;
typedef struct cgltf_memory_options
{
void* (*alloc_func)(void* user, cgltf_size size);
void (*free_func) (void* user, void* ptr);
void* user_data;
} cgltf_memory_options;
typedef struct cgltf_file_options
{
cgltf_result(*read)(const struct cgltf_memory_options* memory_options, const struct cgltf_file_options* file_options, const char* path, cgltf_size* size, void** data);
void (*release)(const struct cgltf_memory_options* memory_options, const struct cgltf_file_options* file_options, void* data, cgltf_size size);
void* user_data;
} cgltf_file_options;
typedef struct cgltf_options
{
cgltf_file_type type; /* invalid == auto detect */
cgltf_size json_token_count; /* 0 == auto */
cgltf_memory_options memory;
cgltf_file_options file;
} cgltf_options;
typedef enum cgltf_buffer_view_type
{
cgltf_buffer_view_type_invalid,
cgltf_buffer_view_type_indices,
cgltf_buffer_view_type_vertices,
cgltf_buffer_view_type_max_enum
} cgltf_buffer_view_type;
typedef enum cgltf_attribute_type
{
cgltf_attribute_type_invalid,
cgltf_attribute_type_position,
cgltf_attribute_type_normal,
cgltf_attribute_type_tangent,
cgltf_attribute_type_texcoord,
cgltf_attribute_type_color,
cgltf_attribute_type_joints,
cgltf_attribute_type_weights,
cgltf_attribute_type_custom,
cgltf_attribute_type_max_enum
} cgltf_attribute_type;
typedef enum cgltf_component_type
{
cgltf_component_type_invalid,
cgltf_component_type_r_8, /* BYTE */
cgltf_component_type_r_8u, /* UNSIGNED_BYTE */
cgltf_component_type_r_16, /* SHORT */
cgltf_component_type_r_16u, /* UNSIGNED_SHORT */
cgltf_component_type_r_32u, /* UNSIGNED_INT */
cgltf_component_type_r_32f, /* FLOAT */
cgltf_component_type_max_enum
} cgltf_component_type;
typedef enum cgltf_type
{
cgltf_type_invalid,
cgltf_type_scalar,
cgltf_type_vec2,
cgltf_type_vec3,
cgltf_type_vec4,
cgltf_type_mat2,
cgltf_type_mat3,
cgltf_type_mat4,
cgltf_type_max_enum
} cgltf_type;
typedef enum cgltf_primitive_type
{
cgltf_primitive_type_invalid,
cgltf_primitive_type_points,
cgltf_primitive_type_lines,
cgltf_primitive_type_line_loop,
cgltf_primitive_type_line_strip,
cgltf_primitive_type_triangles,
cgltf_primitive_type_triangle_strip,
cgltf_primitive_type_triangle_fan,
cgltf_primitive_type_max_enum
} cgltf_primitive_type;
typedef enum cgltf_alpha_mode
{
cgltf_alpha_mode_opaque,
cgltf_alpha_mode_mask,
cgltf_alpha_mode_blend,
cgltf_alpha_mode_max_enum
} cgltf_alpha_mode;
typedef enum cgltf_animation_path_type {
cgltf_animation_path_type_invalid,
cgltf_animation_path_type_translation,
cgltf_animation_path_type_rotation,
cgltf_animation_path_type_scale,
cgltf_animation_path_type_weights,
cgltf_animation_path_type_max_enum
} cgltf_animation_path_type;
typedef enum cgltf_interpolation_type {
cgltf_interpolation_type_linear,
cgltf_interpolation_type_step,
cgltf_interpolation_type_cubic_spline,
cgltf_interpolation_type_max_enum
} cgltf_interpolation_type;
typedef enum cgltf_camera_type {
cgltf_camera_type_invalid,
cgltf_camera_type_perspective,
cgltf_camera_type_orthographic,
cgltf_camera_type_max_enum
} cgltf_camera_type;
typedef enum cgltf_light_type {
cgltf_light_type_invalid,
cgltf_light_type_directional,
cgltf_light_type_point,
cgltf_light_type_spot,
cgltf_light_type_max_enum
} cgltf_light_type;
typedef enum cgltf_data_free_method {
cgltf_data_free_method_none,
cgltf_data_free_method_file_release,
cgltf_data_free_method_memory_free,
cgltf_data_free_method_max_enum
} cgltf_data_free_method;
typedef struct cgltf_extras {
cgltf_size start_offset; /* this field is deprecated and will be removed in the future; use data instead */
cgltf_size end_offset; /* this field is deprecated and will be removed in the future; use data instead */
char* data;
} cgltf_extras;
typedef struct cgltf_extension {
char* name;
char* data;
} cgltf_extension;
typedef struct cgltf_buffer
{
char* name;
cgltf_size size;
char* uri;
void* data; /* loaded by cgltf_load_buffers */
cgltf_data_free_method data_free_method;
cgltf_extras extras;
cgltf_size extensions_count;
cgltf_extension* extensions;
} cgltf_buffer;
typedef enum cgltf_meshopt_compression_mode {
cgltf_meshopt_compression_mode_invalid,
cgltf_meshopt_compression_mode_attributes,
cgltf_meshopt_compression_mode_triangles,
cgltf_meshopt_compression_mode_indices,
cgltf_meshopt_compression_mode_max_enum
} cgltf_meshopt_compression_mode;
typedef enum cgltf_meshopt_compression_filter {
cgltf_meshopt_compression_filter_none,
cgltf_meshopt_compression_filter_octahedral,
cgltf_meshopt_compression_filter_quaternion,
cgltf_meshopt_compression_filter_exponential,
cgltf_meshopt_compression_filter_color,
cgltf_meshopt_compression_filter_max_enum
} cgltf_meshopt_compression_filter;
typedef struct cgltf_meshopt_compression
{
cgltf_buffer* buffer;
cgltf_size offset;
cgltf_size size;
cgltf_size stride;
cgltf_size count;
cgltf_meshopt_compression_mode mode;
cgltf_meshopt_compression_filter filter;
cgltf_bool is_khr;
} cgltf_meshopt_compression;
typedef struct cgltf_buffer_view
{
char *name;
cgltf_buffer* buffer;
cgltf_size offset;
cgltf_size size;
cgltf_size stride; /* 0 == automatically determined by accessor */
cgltf_buffer_view_type type;
void* data; /* overrides buffer->data if present, filled by extensions */
cgltf_bool has_meshopt_compression;
cgltf_meshopt_compression meshopt_compression;
cgltf_extras extras;
cgltf_size extensions_count;
cgltf_extension* extensions;
} cgltf_buffer_view;
typedef struct cgltf_accessor_sparse
{
cgltf_size count;
cgltf_buffer_view* indices_buffer_view;
cgltf_size indices_byte_offset;
cgltf_component_type indices_component_type;
cgltf_buffer_view* values_buffer_view;
cgltf_size values_byte_offset;
} cgltf_accessor_sparse;
typedef struct cgltf_accessor
{
char* name;
cgltf_component_type component_type;
cgltf_bool normalized;
cgltf_type type;
cgltf_size offset;
cgltf_size count;
cgltf_size stride;
cgltf_buffer_view* buffer_view;
cgltf_bool has_min;
cgltf_float min[16];
cgltf_bool has_max;
cgltf_float max[16];
cgltf_bool is_sparse;
cgltf_accessor_sparse sparse;
cgltf_extras extras;
cgltf_size extensions_count;
cgltf_extension* extensions;
} cgltf_accessor;
typedef struct cgltf_attribute
{
char* name;
cgltf_attribute_type type;
cgltf_int index;
cgltf_accessor* data;
} cgltf_attribute;
typedef struct cgltf_image
{
char* name;
char* uri;
cgltf_buffer_view* buffer_view;
char* mime_type;
cgltf_extras extras;
cgltf_size extensions_count;
cgltf_extension* extensions;
} cgltf_image;
typedef enum cgltf_filter_type {
cgltf_filter_type_undefined = 0,
cgltf_filter_type_nearest = 9728,
cgltf_filter_type_linear = 9729,
cgltf_filter_type_nearest_mipmap_nearest = 9984,
cgltf_filter_type_linear_mipmap_nearest = 9985,
cgltf_filter_type_nearest_mipmap_linear = 9986,
cgltf_filter_type_linear_mipmap_linear = 9987
} cgltf_filter_type;
typedef enum cgltf_wrap_mode {
cgltf_wrap_mode_clamp_to_edge = 33071,
cgltf_wrap_mode_mirrored_repeat = 33648,
cgltf_wrap_mode_repeat = 10497
} cgltf_wrap_mode;
typedef struct cgltf_sampler
{
char* name;
cgltf_filter_type mag_filter;
cgltf_filter_type min_filter;
cgltf_wrap_mode wrap_s;
cgltf_wrap_mode wrap_t;
cgltf_extras extras;
cgltf_size extensions_count;
cgltf_extension* extensions;
} cgltf_sampler;
typedef struct cgltf_texture
{
char* name;
cgltf_image* image;
cgltf_sampler* sampler;
cgltf_bool has_basisu;
cgltf_image* basisu_image;
cgltf_bool has_webp;
cgltf_image* webp_image;
cgltf_extras extras;
cgltf_size extensions_count;
cgltf_extension* extensions;
} cgltf_texture;
typedef struct cgltf_texture_transform
{
cgltf_float offset[2];
cgltf_float rotation;
cgltf_float scale[2];
cgltf_bool has_texcoord;
cgltf_int texcoord;
} cgltf_texture_transform;
typedef struct cgltf_texture_view
{
cgltf_texture* texture;
cgltf_int texcoord;
cgltf_float scale; /* equivalent to strength for occlusion_texture */
cgltf_bool has_transform;
cgltf_texture_transform transform;
} cgltf_texture_view;
typedef struct cgltf_pbr_metallic_roughness
{
cgltf_texture_view base_color_texture;
cgltf_texture_view metallic_roughness_texture;
cgltf_float base_color_factor[4];
cgltf_float metallic_factor;
cgltf_float roughness_factor;
} cgltf_pbr_metallic_roughness;
typedef struct cgltf_pbr_specular_glossiness
{
cgltf_texture_view diffuse_texture;
cgltf_texture_view specular_glossiness_texture;
cgltf_float diffuse_factor[4];
cgltf_float specular_factor[3];
cgltf_float glossiness_factor;
} cgltf_pbr_specular_glossiness;
typedef struct cgltf_clearcoat
{
cgltf_texture_view clearcoat_texture;
cgltf_texture_view clearcoat_roughness_texture;
cgltf_texture_view clearcoat_normal_texture;
cgltf_float clearcoat_factor;
cgltf_float clearcoat_roughness_factor;
} cgltf_clearcoat;
typedef struct cgltf_transmission
{
cgltf_texture_view transmission_texture;
cgltf_float transmission_factor;
} cgltf_transmission;
typedef struct cgltf_ior
{
cgltf_float ior;
} cgltf_ior;
typedef struct cgltf_specular
{
cgltf_texture_view specular_texture;
cgltf_texture_view specular_color_texture;
cgltf_float specular_color_factor[3];
cgltf_float specular_factor;
} cgltf_specular;
typedef struct cgltf_volume
{
cgltf_texture_view thickness_texture;
cgltf_float thickness_factor;
cgltf_float attenuation_color[3];
cgltf_float attenuation_distance;
} cgltf_volume;
typedef struct cgltf_sheen
{
cgltf_texture_view sheen_color_texture;
cgltf_float sheen_color_factor[3];
cgltf_texture_view sheen_roughness_texture;
cgltf_float sheen_roughness_factor;
} cgltf_sheen;
typedef struct cgltf_emissive_strength
{
cgltf_float emissive_strength;
} cgltf_emissive_strength;
typedef struct cgltf_iridescence
{
cgltf_float iridescence_factor;
cgltf_texture_view iridescence_texture;
cgltf_float iridescence_ior;
cgltf_float iridescence_thickness_min;
cgltf_float iridescence_thickness_max;
cgltf_texture_view iridescence_thickness_texture;
} cgltf_iridescence;
typedef struct cgltf_diffuse_transmission
{
cgltf_texture_view diffuse_transmission_texture;
cgltf_float diffuse_transmission_factor;
cgltf_float diffuse_transmission_color_factor[3];
cgltf_texture_view diffuse_transmission_color_texture;
} cgltf_diffuse_transmission;
typedef struct cgltf_anisotropy
{
cgltf_float anisotropy_strength;
cgltf_float anisotropy_rotation;
cgltf_texture_view anisotropy_texture;
} cgltf_anisotropy;
typedef struct cgltf_dispersion
{
cgltf_float dispersion;
} cgltf_dispersion;
typedef struct cgltf_material
{
char* name;
cgltf_bool has_pbr_metallic_roughness;
cgltf_bool has_pbr_specular_glossiness;
cgltf_bool has_clearcoat;
cgltf_bool has_transmission;
cgltf_bool has_volume;
cgltf_bool has_ior;
cgltf_bool has_specular;
cgltf_bool has_sheen;
cgltf_bool has_emissive_strength;
cgltf_bool has_iridescence;
cgltf_bool has_diffuse_transmission;
cgltf_bool has_anisotropy;
cgltf_bool has_dispersion;
cgltf_pbr_metallic_roughness pbr_metallic_roughness;
cgltf_pbr_specular_glossiness pbr_specular_glossiness;
cgltf_clearcoat clearcoat;
cgltf_ior ior;
cgltf_specular specular;
cgltf_sheen sheen;
cgltf_transmission transmission;
cgltf_volume volume;
cgltf_emissive_strength emissive_strength;
cgltf_iridescence iridescence;
cgltf_diffuse_transmission diffuse_transmission;
cgltf_anisotropy anisotropy;
cgltf_dispersion dispersion;
cgltf_texture_view normal_texture;
cgltf_texture_view occlusion_texture;
cgltf_texture_view emissive_texture;
cgltf_float emissive_factor[3];
cgltf_alpha_mode alpha_mode;
cgltf_float alpha_cutoff;
cgltf_bool double_sided;
cgltf_bool unlit;
cgltf_extras extras;
cgltf_size extensions_count;
cgltf_extension* extensions;
} cgltf_material;
typedef struct cgltf_material_mapping
{
cgltf_size variant;
cgltf_material* material;
cgltf_extras extras;
} cgltf_material_mapping;
typedef struct cgltf_morph_target {
cgltf_attribute* attributes;
cgltf_size attributes_count;
} cgltf_morph_target;
typedef struct cgltf_draco_mesh_compression {
cgltf_buffer_view* buffer_view;
cgltf_attribute* attributes;
cgltf_size attributes_count;
} cgltf_draco_mesh_compression;
typedef struct cgltf_mesh_gpu_instancing {
cgltf_attribute* attributes;
cgltf_size attributes_count;
} cgltf_mesh_gpu_instancing;
typedef struct cgltf_primitive {
cgltf_primitive_type type;
cgltf_accessor* indices;
cgltf_material* material;
cgltf_attribute* attributes;
cgltf_size attributes_count;
cgltf_morph_target* targets;
cgltf_size targets_count;
cgltf_extras extras;
cgltf_bool has_draco_mesh_compression;
cgltf_draco_mesh_compression draco_mesh_compression;
cgltf_material_mapping* mappings;
cgltf_size mappings_count;
cgltf_size extensions_count;
cgltf_extension* extensions;
} cgltf_primitive;
typedef struct cgltf_mesh {
char* name;
cgltf_primitive* primitives;
cgltf_size primitives_count;
cgltf_float* weights;
cgltf_size weights_count;
char** target_names;
cgltf_size target_names_count;
cgltf_extras extras;
cgltf_size extensions_count;
cgltf_extension* extensions;
} cgltf_mesh;
typedef struct cgltf_node cgltf_node;
typedef struct cgltf_skin {
char* name;
cgltf_node** joints;
cgltf_size joints_count;
cgltf_node* skeleton;
cgltf_accessor* inverse_bind_matrices;
cgltf_extras extras;
cgltf_size extensions_count;
cgltf_extension* extensions;
} cgltf_skin;
typedef struct cgltf_camera_perspective {
cgltf_bool has_aspect_ratio;
cgltf_float aspect_ratio;
cgltf_float yfov;
cgltf_bool has_zfar;
cgltf_float zfar;
cgltf_float znear;
cgltf_extras extras;
} cgltf_camera_perspective;
typedef struct cgltf_camera_orthographic {
cgltf_float xmag;
cgltf_float ymag;
cgltf_float zfar;
cgltf_float znear;
cgltf_extras extras;
} cgltf_camera_orthographic;
typedef struct cgltf_camera {
char* name;
cgltf_camera_type type;
union {
cgltf_camera_perspective perspective;
cgltf_camera_orthographic orthographic;
} data;
cgltf_extras extras;
cgltf_size extensions_count;
cgltf_extension* extensions;
} cgltf_camera;
typedef struct cgltf_light {
char* name;
cgltf_float color[3];
cgltf_float intensity;
cgltf_light_type type;
cgltf_float range;
cgltf_float spot_inner_cone_angle;
cgltf_float spot_outer_cone_angle;
cgltf_extras extras;
} cgltf_light;
struct cgltf_node {
char* name;
cgltf_node* parent;
cgltf_node** children;
cgltf_size children_count;
cgltf_skin* skin;
cgltf_mesh* mesh;
cgltf_camera* camera;
cgltf_light* light;
cgltf_float* weights;
cgltf_size weights_count;
cgltf_bool has_translation;
cgltf_bool has_rotation;
cgltf_bool has_scale;
cgltf_bool has_matrix;
cgltf_float translation[3];
cgltf_float rotation[4];
cgltf_float scale[3];
cgltf_float matrix[16];
cgltf_extras extras;
cgltf_bool has_mesh_gpu_instancing;
cgltf_mesh_gpu_instancing mesh_gpu_instancing;
cgltf_size extensions_count;
cgltf_extension* extensions;
};
typedef struct cgltf_scene {
char* name;
cgltf_node** nodes;
cgltf_size nodes_count;
cgltf_extras extras;
cgltf_size extensions_count;
cgltf_extension* extensions;
} cgltf_scene;
typedef struct cgltf_animation_sampler {
cgltf_accessor* input;
cgltf_accessor* output;
cgltf_interpolation_type interpolation;
cgltf_extras extras;
cgltf_size extensions_count;
cgltf_extension* extensions;
} cgltf_animation_sampler;
typedef struct cgltf_animation_channel {
cgltf_animation_sampler* sampler;
cgltf_node* target_node;
cgltf_animation_path_type target_path;
cgltf_extras extras;
cgltf_size extensions_count;
cgltf_extension* extensions;
} cgltf_animation_channel;
typedef struct cgltf_animation {
char* name;
cgltf_animation_sampler* samplers;
cgltf_size samplers_count;
cgltf_animation_channel* channels;
cgltf_size channels_count;
cgltf_extras extras;
cgltf_size extensions_count;
cgltf_extension* extensions;
} cgltf_animation;
typedef struct cgltf_material_variant
{
char* name;
cgltf_extras extras;
} cgltf_material_variant;
typedef struct cgltf_asset {
char* copyright;
char* generator;
char* version;
char* min_version;
cgltf_extras extras;
cgltf_size extensions_count;
cgltf_extension* extensions;
} cgltf_asset;
typedef struct cgltf_data
{
cgltf_file_type file_type;
void* file_data;
cgltf_size file_size;
cgltf_asset asset;
cgltf_mesh* meshes;
cgltf_size meshes_count;
cgltf_material* materials;
cgltf_size materials_count;
cgltf_accessor* accessors;
cgltf_size accessors_count;
cgltf_buffer_view* buffer_views;
cgltf_size buffer_views_count;
cgltf_buffer* buffers;
cgltf_size buffers_count;
cgltf_image* images;
cgltf_size images_count;
cgltf_texture* textures;
cgltf_size textures_count;
cgltf_sampler* samplers;
cgltf_size samplers_count;
cgltf_skin* skins;
cgltf_size skins_count;
cgltf_camera* cameras;
cgltf_size cameras_count;
cgltf_light* lights;
cgltf_size lights_count;
cgltf_node* nodes;
cgltf_size nodes_count;
cgltf_scene* scenes;
cgltf_size scenes_count;
cgltf_scene* scene;
cgltf_animation* animations;
cgltf_size animations_count;
cgltf_material_variant* variants;
cgltf_size variants_count;
cgltf_extras extras;
cgltf_size data_extensions_count;
cgltf_extension* data_extensions;
char** extensions_used;
cgltf_size extensions_used_count;
char** extensions_required;
cgltf_size extensions_required_count;
const char* json;
cgltf_size json_size;
const void* bin;
cgltf_size bin_size;
cgltf_memory_options memory;
cgltf_file_options file;
} cgltf_data;
cgltf_result cgltf_parse(
const cgltf_options* options,
const void* data,
cgltf_size size,
cgltf_data** out_data);
cgltf_result cgltf_parse_file(
const cgltf_options* options,
const char* path,
cgltf_data** out_data);
cgltf_result cgltf_load_buffers(
const cgltf_options* options,
cgltf_data* data,
const char* gltf_path);
cgltf_result cgltf_load_buffer_base64(const cgltf_options* options, cgltf_size size, const char* base64, void** out_data);
cgltf_size cgltf_decode_string(char* string);
cgltf_size cgltf_decode_uri(char* uri);
cgltf_result cgltf_validate(cgltf_data* data);
void cgltf_free(cgltf_data* data);
void cgltf_node_transform_local(const cgltf_node* node, cgltf_float* out_matrix);
void cgltf_node_transform_world(const cgltf_node* node, cgltf_float* out_matrix);
const uint8_t* cgltf_buffer_view_data(const cgltf_buffer_view* view);
const cgltf_accessor* cgltf_find_accessor(const cgltf_primitive* prim, cgltf_attribute_type type, cgltf_int index);
cgltf_bool cgltf_accessor_read_float(const cgltf_accessor* accessor, cgltf_size index, cgltf_float* out, cgltf_size element_size);
cgltf_bool cgltf_accessor_read_uint(const cgltf_accessor* accessor, cgltf_size index, cgltf_uint* out, cgltf_size element_size);
cgltf_size cgltf_accessor_read_index(const cgltf_accessor* accessor, cgltf_size index);
cgltf_size cgltf_num_components(cgltf_type type);
cgltf_size cgltf_component_size(cgltf_component_type component_type);
cgltf_size cgltf_calc_size(cgltf_type type, cgltf_component_type component_type);
cgltf_size cgltf_accessor_unpack_floats(const cgltf_accessor* accessor, cgltf_float* out, cgltf_size float_count);
cgltf_size cgltf_accessor_unpack_indices(const cgltf_accessor* accessor, void* out, cgltf_size out_component_size, cgltf_size index_count);
/* this function is deprecated and will be removed in the future; use cgltf_extras::data instead */
cgltf_result cgltf_copy_extras_json(const cgltf_data* data, const cgltf_extras* extras, char* dest, cgltf_size* dest_size);
cgltf_size cgltf_mesh_index(const cgltf_data* data, const cgltf_mesh* object);
cgltf_size cgltf_material_index(const cgltf_data* data, const cgltf_material* object);
cgltf_size cgltf_accessor_index(const cgltf_data* data, const cgltf_accessor* object);
cgltf_size cgltf_buffer_view_index(const cgltf_data* data, const cgltf_buffer_view* object);
cgltf_size cgltf_buffer_index(const cgltf_data* data, const cgltf_buffer* object);
cgltf_size cgltf_image_index(const cgltf_data* data, const cgltf_image* object);
cgltf_size cgltf_texture_index(const cgltf_data* data, const cgltf_texture* object);
cgltf_size cgltf_sampler_index(const cgltf_data* data, const cgltf_sampler* object);
cgltf_size cgltf_skin_index(const cgltf_data* data, const cgltf_skin* object);
cgltf_size cgltf_camera_index(const cgltf_data* data, const cgltf_camera* object);
cgltf_size cgltf_light_index(const cgltf_data* data, const cgltf_light* object);
cgltf_size cgltf_node_index(const cgltf_data* data, const cgltf_node* object);
cgltf_size cgltf_scene_index(const cgltf_data* data, const cgltf_scene* object);
cgltf_size cgltf_animation_index(const cgltf_data* data, const cgltf_animation* object);
cgltf_size cgltf_animation_sampler_index(const cgltf_animation* animation, const cgltf_animation_sampler* object);
cgltf_size cgltf_animation_channel_index(const cgltf_animation* animation, const cgltf_animation_channel* object);
#ifdef __cplusplus
}
#endif
#endif /* #ifndef CGLTF_H_INCLUDED__ */
/*
*
* Stop now, if you are only interested in the API.
* Below, you find the implementation.
*
*/
#if defined(__INTELLISENSE__) || defined(__JETBRAINS_IDE__)
/* This makes MSVC/CLion intellisense work. */
#define CGLTF_IMPLEMENTATION
#endif
#ifdef CGLTF_IMPLEMENTATION
#include <assert.h> /* For assert */
#include <string.h> /* For strncpy */
#include <stdio.h> /* For fopen */
#include <limits.h> /* For UINT_MAX etc */
#include <float.h> /* For FLT_MAX */
#if !defined(CGLTF_MALLOC) || !defined(CGLTF_FREE) || !defined(CGLTF_ATOI) || !defined(CGLTF_ATOF) || !defined(CGLTF_ATOLL)
#include <stdlib.h> /* For malloc, free, atoi, atof */
#endif
/* JSMN_PARENT_LINKS is necessary to make parsing large structures linear in input size */
#define JSMN_PARENT_LINKS
/* JSMN_STRICT is necessary to reject invalid JSON documents */
#define JSMN_STRICT
/*
* -- jsmn.h start --
* Source: https://github.com/zserge/jsmn
* License: MIT
*/
typedef enum {
JSMN_UNDEFINED = 0,
JSMN_OBJECT = 1,
JSMN_ARRAY = 2,
JSMN_STRING = 3,
JSMN_PRIMITIVE = 4
} jsmntype_t;
enum jsmnerr {
/* Not enough tokens were provided */
JSMN_ERROR_NOMEM = -1,
/* Invalid character inside JSON string */
JSMN_ERROR_INVAL = -2,
/* The string is not a full JSON packet, more bytes expected */
JSMN_ERROR_PART = -3
};
typedef struct {
jsmntype_t type;
ptrdiff_t start;
ptrdiff_t end;
int size;
#ifdef JSMN_PARENT_LINKS
int parent;
#endif
} jsmntok_t;
typedef struct {
size_t pos; /* offset in the JSON string */
unsigned int toknext; /* next token to allocate */
int toksuper; /* superior token node, e.g parent object or array */
} jsmn_parser;
static void jsmn_init(jsmn_parser *parser);
static int jsmn_parse(jsmn_parser *parser, const char *js, size_t len, jsmntok_t *tokens, size_t num_tokens);
/*
* -- jsmn.h end --
*/
#ifndef CGLTF_CONSTS
#define GlbHeaderSize 12
#define GlbChunkHeaderSize 8
static const uint32_t GlbVersion = 2;
static const uint32_t GlbMagic = 0x46546C67;
static const uint32_t GlbMagicJsonChunk = 0x4E4F534A;
static const uint32_t GlbMagicBinChunk = 0x004E4942;
#define CGLTF_CONSTS
#endif
#ifndef CGLTF_MALLOC
#define CGLTF_MALLOC(size) malloc(size)
#endif
#ifndef CGLTF_FREE
#define CGLTF_FREE(ptr) free(ptr)
#endif
#ifndef CGLTF_ATOI
#define CGLTF_ATOI(str) atoi(str)
#endif
#ifndef CGLTF_ATOF
#define CGLTF_ATOF(str) atof(str)
#endif
#ifndef CGLTF_ATOLL
#define CGLTF_ATOLL(str) atoll(str)
#endif
#ifndef CGLTF_VALIDATE_ENABLE_ASSERTS
#define CGLTF_VALIDATE_ENABLE_ASSERTS 0
#endif
static void* cgltf_default_alloc(void* user, cgltf_size size)
{
(void)user;
return CGLTF_MALLOC(size);
}
static void cgltf_default_free(void* user, void* ptr)
{
(void)user;
CGLTF_FREE(ptr);
}
static void* cgltf_calloc(cgltf_options* options, size_t element_size, cgltf_size count)
{
if (SIZE_MAX / element_size < count)
{
return NULL;
}
void* result = options->memory.alloc_func(options->memory.user_data, element_size * count);
if (!result)
{
return NULL;
}
memset(result, 0, element_size * count);
return result;
}
static cgltf_result cgltf_default_file_read(const struct cgltf_memory_options* memory_options, const struct cgltf_file_options* file_options, const char* path, cgltf_size* size, void** data)
{
(void)file_options;
void* (*memory_alloc)(void*, cgltf_size) = memory_options->alloc_func ? memory_options->alloc_func : &cgltf_default_alloc;
void (*memory_free)(void*, void*) = memory_options->free_func ? memory_options->free_func : &cgltf_default_free;
FILE* file = fopen(path, "rb");
if (!file)
{
return cgltf_result_file_not_found;
}
cgltf_size file_size = size ? *size : 0;
if (file_size == 0)
{
fseek(file, 0, SEEK_END);
#ifdef _MSC_VER
__int64 length = _ftelli64(file);
#else
long length = ftell(file);
#endif
if (length < 0)
{
fclose(file);
return cgltf_result_io_error;
}
fseek(file, 0, SEEK_SET);
file_size = (cgltf_size)length;
}
char* file_data = (char*)memory_alloc(memory_options->user_data, file_size);
if (!file_data)
{
fclose(file);
return cgltf_result_out_of_memory;
}
cgltf_size read_size = fread(file_data, 1, file_size, file);
fclose(file);
if (read_size != file_size)
{
memory_free(memory_options->user_data, file_data);
return cgltf_result_io_error;
}
if (size)
{
*size = file_size;
}
if (data)
{
*data = file_data;
}
return cgltf_result_success;
}
static void cgltf_default_file_release(const struct cgltf_memory_options* memory_options, const struct cgltf_file_options* file_options, void* data, cgltf_size size)
{
(void)file_options;
(void)size;
void (*memfree)(void*, void*) = memory_options->free_func ? memory_options->free_func : &cgltf_default_free;
memfree(memory_options->user_data, data);
}
static cgltf_result cgltf_parse_json(cgltf_options* options, const uint8_t* json_chunk, cgltf_size size, cgltf_data** out_data);
cgltf_result cgltf_parse(const cgltf_options* options, const void* data, cgltf_size size, cgltf_data** out_data)
{
if (size < GlbHeaderSize)
{
return cgltf_result_data_too_short;
}
if (options == NULL)
{
return cgltf_result_invalid_options;
}
cgltf_options fixed_options = *options;
if (fixed_options.memory.alloc_func == NULL)
{
fixed_options.memory.alloc_func = &cgltf_default_alloc;
}
if (fixed_options.memory.free_func == NULL)
{
fixed_options.memory.free_func = &cgltf_default_free;
}
uint32_t tmp;
// Magic
memcpy(&tmp, data, 4);
if (tmp != GlbMagic)
{
if (fixed_options.type == cgltf_file_type_invalid)
{
fixed_options.type = cgltf_file_type_gltf;
}
else if (fixed_options.type == cgltf_file_type_glb)
{
return cgltf_result_unknown_format;
}
}
if (fixed_options.type == cgltf_file_type_gltf)
{
cgltf_result json_result = cgltf_parse_json(&fixed_options, (const uint8_t*)data, size, out_data);
if (json_result != cgltf_result_success)
{
return json_result;
}
(*out_data)->file_type = cgltf_file_type_gltf;
return cgltf_result_success;
}
const uint8_t* ptr = (const uint8_t*)data;
// Version
memcpy(&tmp, ptr + 4, 4);
uint32_t version = tmp;
if (version != GlbVersion)
{
return version < GlbVersion ? cgltf_result_legacy_gltf : cgltf_result_unknown_format;
}
// Total length
memcpy(&tmp, ptr + 8, 4);
if (tmp > size)
{
return cgltf_result_data_too_short;
}
const uint8_t* json_chunk = ptr + GlbHeaderSize;
if (GlbHeaderSize + GlbChunkHeaderSize > size)
{
return cgltf_result_data_too_short;
}
// JSON chunk: length
uint32_t json_length;
memcpy(&json_length, json_chunk, 4);
if (json_length > size - GlbHeaderSize - GlbChunkHeaderSize)
{
return cgltf_result_data_too_short;
}
// JSON chunk: magic
memcpy(&tmp, json_chunk + 4, 4);
if (tmp != GlbMagicJsonChunk)
{
return cgltf_result_unknown_format;
}
json_chunk += GlbChunkHeaderSize;
const void* bin = NULL;
cgltf_size bin_size = 0;
if (GlbChunkHeaderSize <= size - GlbHeaderSize - GlbChunkHeaderSize - json_length)
{
// We can read another chunk
const uint8_t* bin_chunk = json_chunk + json_length;
// Bin chunk: length
uint32_t bin_length;
memcpy(&bin_length, bin_chunk, 4);
if (bin_length > size - GlbHeaderSize - GlbChunkHeaderSize - json_length - GlbChunkHeaderSize)
{
return cgltf_result_data_too_short;
}
// Bin chunk: magic
memcpy(&tmp, bin_chunk + 4, 4);
if (tmp != GlbMagicBinChunk)
{
return cgltf_result_unknown_format;
}
bin_chunk += GlbChunkHeaderSize;
bin = bin_chunk;
bin_size = bin_length;
}
cgltf_result json_result = cgltf_parse_json(&fixed_options, json_chunk, json_length, out_data);
if (json_result != cgltf_result_success)
{
return json_result;
}
(*out_data)->file_type = cgltf_file_type_glb;
(*out_data)->bin = bin;
(*out_data)->bin_size = bin_size;
return cgltf_result_success;
}
cgltf_result cgltf_parse_file(const cgltf_options* options, const char* path, cgltf_data** out_data)
{
if (options == NULL)
{
return cgltf_result_invalid_options;
}
cgltf_result (*file_read)(const struct cgltf_memory_options*, const struct cgltf_file_options*, const char*, cgltf_size*, void**) = options->file.read ? options->file.read : &cgltf_default_file_read;
void (*file_release)(const struct cgltf_memory_options*, const struct cgltf_file_options*, void* data, cgltf_size size) = options->file.release ? options->file.release : cgltf_default_file_release;
void* file_data = NULL;
cgltf_size file_size = 0;
cgltf_result result = file_read(&options->memory, &options->file, path, &file_size, &file_data);
if (result != cgltf_result_success)
{
return result;
}
result = cgltf_parse(options, file_data, file_size, out_data);
if (result != cgltf_result_success)
{
file_release(&options->memory, &options->file, file_data, file_size);
return result;
}
(*out_data)->file_data = file_data;
(*out_data)->file_size = file_size;
return cgltf_result_success;
}
static void cgltf_combine_paths(char* path, const char* base, const char* uri)
{
const char* s0 = strrchr(base, '/');
const char* s1 = strrchr(base, '\\');
const char* slash = s0 ? (s1 && s1 > s0 ? s1 : s0) : s1;
if (slash)
{
size_t prefix = slash - base + 1;
strncpy(path, base, prefix);
strcpy(path + prefix, uri);
}
else
{
strcpy(path, uri);
}
}
static cgltf_result cgltf_load_buffer_file(const cgltf_options* options, cgltf_size size, const char* uri, const char* gltf_path, void** out_data)
{
void* (*memory_alloc)(void*, cgltf_size) = options->memory.alloc_func ? options->memory.alloc_func : &cgltf_default_alloc;
void (*memory_free)(void*, void*) = options->memory.free_func ? options->memory.free_func : &cgltf_default_free;
cgltf_result (*file_read)(const struct cgltf_memory_options*, const struct cgltf_file_options*, const char*, cgltf_size*, void**) = options->file.read ? options->file.read : &cgltf_default_file_read;
char* path = (char*)memory_alloc(options->memory.user_data, strlen(uri) + strlen(gltf_path) + 1);
if (!path)
{
return cgltf_result_out_of_memory;
}
cgltf_combine_paths(path, gltf_path, uri);
// after combining, the tail of the resulting path is a uri; decode_uri converts it into path
cgltf_decode_uri(path + strlen(path) - strlen(uri));
void* file_data = NULL;
cgltf_result result = file_read(&options->memory, &options->file, path, &size, &file_data);
memory_free(options->memory.user_data, path);
*out_data = (result == cgltf_result_success) ? file_data : NULL;
return result;
}
cgltf_result cgltf_load_buffer_base64(const cgltf_options* options, cgltf_size size, const char* base64, void** out_data)
{
void* (*memory_alloc)(void*, cgltf_size) = options->memory.alloc_func ? options->memory.alloc_func : &cgltf_default_alloc;
void (*memory_free)(void*, void*) = options->memory.free_func ? options->memory.free_func : &cgltf_default_free;
unsigned char* data = (unsigned char*)memory_alloc(options->memory.user_data, size);
if (!data)
{
return cgltf_result_out_of_memory;
}
unsigned int buffer = 0;
unsigned int buffer_bits = 0;
for (cgltf_size i = 0; i < size; ++i)
{
while (buffer_bits < 8)
{
char ch = *base64++;
int index =
(unsigned)(ch - 'A') < 26 ? (ch - 'A') :
(unsigned)(ch - 'a') < 26 ? (ch - 'a') + 26 :
(unsigned)(ch - '0') < 10 ? (ch - '0') + 52 :
ch == '+' ? 62 :
ch == '/' ? 63 :
-1;
if (index < 0)
{
memory_free(options->memory.user_data, data);
return cgltf_result_io_error;
}
buffer = (buffer << 6) | index;
buffer_bits += 6;
}
data[i] = (unsigned char)(buffer >> (buffer_bits - 8));
buffer_bits -= 8;
}
*out_data = data;
return cgltf_result_success;
}
static int cgltf_unhex(char ch)
{
return
(unsigned)(ch - '0') < 10 ? (ch - '0') :
(unsigned)(ch - 'A') < 6 ? (ch - 'A') + 10 :
(unsigned)(ch - 'a') < 6 ? (ch - 'a') + 10 :
-1;
}
cgltf_size cgltf_decode_string(char* string)
{
char* read = string + strcspn(string, "\\");
if (*read == 0)
{
return read - string;
}
char* write = string;
char* last = string;
for (;;)
{
// Copy characters since last escaped sequence
cgltf_size written = read - last;
memmove(write, last, written);
write += written;
if (*read++ == 0)
{
break;
}
// jsmn already checked that all escape sequences are valid
switch (*read++)
{
case '\"': *write++ = '\"'; break;
case '/': *write++ = '/'; break;
case '\\': *write++ = '\\'; break;
case 'b': *write++ = '\b'; break;
case 'f': *write++ = '\f'; break;
case 'r': *write++ = '\r'; break;
case 'n': *write++ = '\n'; break;
case 't': *write++ = '\t'; break;
case 'u':
{
// UCS-2 codepoint \uXXXX to UTF-8
int character = 0;
for (cgltf_size i = 0; i < 4; ++i)
{
character = (character << 4) + cgltf_unhex(*read++);
}
if (character <= 0x7F)
{
*write++ = character & 0xFF;
}
else if (character <= 0x7FF)
{
*write++ = 0xC0 | ((character >> 6) & 0xFF);
*write++ = 0x80 | (character & 0x3F);
}
else
{
*write++ = 0xE0 | ((character >> 12) & 0xFF);
*write++ = 0x80 | ((character >> 6) & 0x3F);
*write++ = 0x80 | (character & 0x3F);
}
break;
}
default:
break;
}
last = read;
read += strcspn(read, "\\");
}
*write = 0;
return write - string;
}
cgltf_size cgltf_decode_uri(char* uri)
{
char* write = uri;
char* i = uri;
while (*i)
{
if (*i == '%')
{
int ch1 = cgltf_unhex(i[1]);
if (ch1 >= 0)
{
int ch2 = cgltf_unhex(i[2]);
if (ch2 >= 0)
{
*write++ = (char)(ch1 * 16 + ch2);
i += 3;
continue;
}
}
}
*write++ = *i++;
}
*write = 0;
return write - uri;
}
cgltf_result cgltf_load_buffers(const cgltf_options* options, cgltf_data* data, const char* gltf_path)
{
if (options == NULL)
{
return cgltf_result_invalid_options;
}
if (data->buffers_count && data->buffers[0].data == NULL && data->buffers[0].uri == NULL && data->bin)
{
if (data->bin_size < data->buffers[0].size)
{
return cgltf_result_data_too_short;
}
data->buffers[0].data = (void*)data->bin;
data->buffers[0].data_free_method = cgltf_data_free_method_none;
}
for (cgltf_size i = 0; i < data->buffers_count; ++i)
{
if (data->buffers[i].data)
{
continue;
}
const char* uri = data->buffers[i].uri;
if (uri == NULL)
{
continue;
}
if (strncmp(uri, "data:", 5) == 0)
{
const char* comma = strchr(uri, ',');
if (comma && comma - uri >= 7 && strncmp(comma - 7, ";base64", 7) == 0)
{
cgltf_result res = cgltf_load_buffer_base64(options, data->buffers[i].size, comma + 1, &data->buffers[i].data);
data->buffers[i].data_free_method = cgltf_data_free_method_memory_free;
if (res != cgltf_result_success)
{
return res;
}
}
else
{
return cgltf_result_unknown_format;
}
}
else if (strstr(uri, "://") == NULL && gltf_path)
{
cgltf_result res = cgltf_load_buffer_file(options, data->buffers[i].size, uri, gltf_path, &data->buffers[i].data);
data->buffers[i].data_free_method = cgltf_data_free_method_file_release;
if (res != cgltf_result_success)
{
return res;
}
}
else
{
return cgltf_result_unknown_format;
}
}
return cgltf_result_success;
}
static cgltf_size cgltf_calc_index_bound(cgltf_buffer_view* buffer_view, cgltf_size offset, cgltf_component_type component_type, cgltf_size count)
{
char* data = (char*)buffer_view->buffer->data + offset + buffer_view->offset;
cgltf_size bound = 0;
switch (component_type)
{
case cgltf_component_type_r_8u:
for (size_t i = 0; i < count; ++i)
{
cgltf_size v = ((unsigned char*)data)[i];
bound = bound > v ? bound : v;
}
break;
case cgltf_component_type_r_16u:
for (size_t i = 0; i < count; ++i)
{
cgltf_size v = ((unsigned short*)data)[i];
bound = bound > v ? bound : v;
}
break;
case cgltf_component_type_r_32u:
for (size_t i = 0; i < count; ++i)
{
cgltf_size v = ((unsigned int*)data)[i];
bound = bound > v ? bound : v;
}
break;
default:
;
}
return bound;
}
#if CGLTF_VALIDATE_ENABLE_ASSERTS
#define CGLTF_ASSERT_IF(cond, result) assert(!(cond)); if (cond) return result;
#else
#define CGLTF_ASSERT_IF(cond, result) if (cond) return result;
#endif
cgltf_result cgltf_validate(cgltf_data* data)
{
for (cgltf_size i = 0; i < data->accessors_count; ++i)
{
cgltf_accessor* accessor = &data->accessors[i];
CGLTF_ASSERT_IF(data->accessors[i].component_type == cgltf_component_type_invalid, cgltf_result_invalid_gltf);
CGLTF_ASSERT_IF(data->accessors[i].type == cgltf_type_invalid, cgltf_result_invalid_gltf);
cgltf_size element_size = cgltf_calc_size(accessor->type, accessor->component_type);
if (accessor->buffer_view)
{
cgltf_size req_size = accessor->offset + accessor->stride * (accessor->count - 1) + element_size;
CGLTF_ASSERT_IF(accessor->buffer_view->size < req_size, cgltf_result_data_too_short);
}
if (accessor->is_sparse)
{
cgltf_accessor_sparse* sparse = &accessor->sparse;
cgltf_size indices_component_size = cgltf_component_size(sparse->indices_component_type);
cgltf_size indices_req_size = sparse->indices_byte_offset + indices_component_size * sparse->count;
cgltf_size values_req_size = sparse->values_byte_offset + element_size * sparse->count;
CGLTF_ASSERT_IF(sparse->indices_buffer_view->size < indices_req_size ||
sparse->values_buffer_view->size < values_req_size, cgltf_result_data_too_short);
CGLTF_ASSERT_IF(sparse->indices_component_type != cgltf_component_type_r_8u &&
sparse->indices_component_type != cgltf_component_type_r_16u &&
sparse->indices_component_type != cgltf_component_type_r_32u, cgltf_result_invalid_gltf);
if (sparse->indices_buffer_view->buffer->data)
{
cgltf_size index_bound = cgltf_calc_index_bound(sparse->indices_buffer_view, sparse->indices_byte_offset, sparse->indices_component_type, sparse->count);
CGLTF_ASSERT_IF(index_bound >= accessor->count, cgltf_result_data_too_short);
}
}
}
for (cgltf_size i = 0; i < data->buffer_views_count; ++i)
{
cgltf_size req_size = data->buffer_views[i].offset + data->buffer_views[i].size;
CGLTF_ASSERT_IF(data->buffer_views[i].buffer && data->buffer_views[i].buffer->size < req_size, cgltf_result_data_too_short);
if (data->buffer_views[i].has_meshopt_compression)
{
cgltf_meshopt_compression* mc = &data->buffer_views[i].meshopt_compression;
CGLTF_ASSERT_IF(mc->buffer == NULL || mc->buffer->size < mc->offset + mc->size, cgltf_result_data_too_short);
CGLTF_ASSERT_IF(data->buffer_views[i].stride && mc->stride != data->buffer_views[i].stride, cgltf_result_invalid_gltf);
CGLTF_ASSERT_IF(data->buffer_views[i].size != mc->stride * mc->count, cgltf_result_invalid_gltf);
CGLTF_ASSERT_IF(mc->mode == cgltf_meshopt_compression_mode_invalid, cgltf_result_invalid_gltf);
CGLTF_ASSERT_IF(mc->mode == cgltf_meshopt_compression_mode_attributes && !(mc->stride % 4 == 0 && mc->stride <= 256), cgltf_result_invalid_gltf);
CGLTF_ASSERT_IF(mc->mode == cgltf_meshopt_compression_mode_triangles && mc->count % 3 != 0, cgltf_result_invalid_gltf);
CGLTF_ASSERT_IF((mc->mode == cgltf_meshopt_compression_mode_triangles || mc->mode == cgltf_meshopt_compression_mode_indices) && mc->stride != 2 && mc->stride != 4, cgltf_result_invalid_gltf);
CGLTF_ASSERT_IF((mc->mode == cgltf_meshopt_compression_mode_triangles || mc->mode == cgltf_meshopt_compression_mode_indices) && mc->filter != cgltf_meshopt_compression_filter_none, cgltf_result_invalid_gltf);
CGLTF_ASSERT_IF(mc->filter == cgltf_meshopt_compression_filter_octahedral && mc->stride != 4 && mc->stride != 8, cgltf_result_invalid_gltf);
CGLTF_ASSERT_IF(mc->filter == cgltf_meshopt_compression_filter_quaternion && mc->stride != 8, cgltf_result_invalid_gltf);
CGLTF_ASSERT_IF(mc->filter == cgltf_meshopt_compression_filter_color && mc->stride != 4 && mc->stride != 8, cgltf_result_invalid_gltf);
}
}
for (cgltf_size i = 0; i < data->meshes_count; ++i)
{
if (data->meshes[i].weights)
{
CGLTF_ASSERT_IF(data->meshes[i].primitives_count && data->meshes[i].primitives[0].targets_count != data->meshes[i].weights_count, cgltf_result_invalid_gltf);
}
if (data->meshes[i].target_names)
{
CGLTF_ASSERT_IF(data->meshes[i].primitives_count && data->meshes[i].primitives[0].targets_count != data->meshes[i].target_names_count, cgltf_result_invalid_gltf);
}
for (cgltf_size j = 0; j < data->meshes[i].primitives_count; ++j)
{
CGLTF_ASSERT_IF(data->meshes[i].primitives[j].type == cgltf_primitive_type_invalid, cgltf_result_invalid_gltf);
CGLTF_ASSERT_IF(data->meshes[i].primitives[j].targets_count != data->meshes[i].primitives[0].targets_count, cgltf_result_invalid_gltf);
CGLTF_ASSERT_IF(data->meshes[i].primitives[j].attributes_count == 0, cgltf_result_invalid_gltf);
cgltf_accessor* first = data->meshes[i].primitives[j].attributes[0].data;
CGLTF_ASSERT_IF(first->count == 0, cgltf_result_invalid_gltf);
for (cgltf_size k = 0; k < data->meshes[i].primitives[j].attributes_count; ++k)
{
CGLTF_ASSERT_IF(data->meshes[i].primitives[j].attributes[k].data->count != first->count, cgltf_result_invalid_gltf);
}
for (cgltf_size k = 0; k < data->meshes[i].primitives[j].targets_count; ++k)
{
for (cgltf_size m = 0; m < data->meshes[i].primitives[j].targets[k].attributes_count; ++m)
{
CGLTF_ASSERT_IF(data->meshes[i].primitives[j].targets[k].attributes[m].data->count != first->count, cgltf_result_invalid_gltf);
}
}
cgltf_accessor* indices = data->meshes[i].primitives[j].indices;
CGLTF_ASSERT_IF(indices &&
indices->component_type != cgltf_component_type_r_8u &&
indices->component_type != cgltf_component_type_r_16u &&
indices->component_type != cgltf_component_type_r_32u, cgltf_result_invalid_gltf);
CGLTF_ASSERT_IF(indices && indices->type != cgltf_type_scalar, cgltf_result_invalid_gltf);
CGLTF_ASSERT_IF(indices && indices->stride != cgltf_component_size(indices->component_type), cgltf_result_invalid_gltf);
if (indices && indices->buffer_view && indices->buffer_view->buffer->data)
{
cgltf_size index_bound = cgltf_calc_index_bound(indices->buffer_view, indices->offset, indices->component_type, indices->count);
CGLTF_ASSERT_IF(index_bound >= first->count, cgltf_result_data_too_short);
}
for (cgltf_size k = 0; k < data->meshes[i].primitives[j].mappings_count; ++k)
{
CGLTF_ASSERT_IF(data->meshes[i].primitives[j].mappings[k].variant >= data->variants_count, cgltf_result_invalid_gltf);
}
}
}
for (cgltf_size i = 0; i < data->nodes_count; ++i)
{
if (data->nodes[i].weights && data->nodes[i].mesh)
{
CGLTF_ASSERT_IF(data->nodes[i].mesh->primitives_count && data->nodes[i].mesh->primitives[0].targets_count != data->nodes[i].weights_count, cgltf_result_invalid_gltf);
}
if (data->nodes[i].has_mesh_gpu_instancing)
{
CGLTF_ASSERT_IF(data->nodes[i].mesh == NULL, cgltf_result_invalid_gltf);
CGLTF_ASSERT_IF(data->nodes[i].mesh_gpu_instancing.attributes_count == 0, cgltf_result_invalid_gltf);
cgltf_accessor* first = data->nodes[i].mesh_gpu_instancing.attributes[0].data;
for (cgltf_size k = 0; k < data->nodes[i].mesh_gpu_instancing.attributes_count; ++k)
{
CGLTF_ASSERT_IF(data->nodes[i].mesh_gpu_instancing.attributes[k].data->count != first->count, cgltf_result_invalid_gltf);
}
}
}
for (cgltf_size i = 0; i < data->nodes_count; ++i)
{
cgltf_node* p1 = data->nodes[i].parent;
cgltf_node* p2 = p1 ? p1->parent : NULL;
while (p1 && p2)
{
CGLTF_ASSERT_IF(p1 == p2, cgltf_result_invalid_gltf);
p1 = p1->parent;
p2 = p2->parent ? p2->parent->parent : NULL;
}
}
for (cgltf_size i = 0; i < data->scenes_count; ++i)
{
for (cgltf_size j = 0; j < data->scenes[i].nodes_count; ++j)
{
CGLTF_ASSERT_IF(data->scenes[i].nodes[j]->parent, cgltf_result_invalid_gltf);
}
}
for (cgltf_size i = 0; i < data->animations_count; ++i)
{
for (cgltf_size j = 0; j < data->animations[i].channels_count; ++j)
{
cgltf_animation_channel* channel = &data->animations[i].channels[j];
if (!channel->target_node)
{
continue;
}
cgltf_size components = 1;
if (channel->target_path == cgltf_animation_path_type_weights)
{
CGLTF_ASSERT_IF(!channel->target_node->mesh || !channel->target_node->mesh->primitives_count, cgltf_result_invalid_gltf);
components = channel->target_node->mesh->primitives[0].targets_count;
}
cgltf_size values = channel->sampler->interpolation == cgltf_interpolation_type_cubic_spline ? 3 : 1;
CGLTF_ASSERT_IF(channel->sampler->input->count * components * values != channel->sampler->output->count, cgltf_result_invalid_gltf);
}
}
for (cgltf_size i = 0; i < data->variants_count; ++i)
{
CGLTF_ASSERT_IF(!data->variants[i].name, cgltf_result_invalid_gltf);
}
return cgltf_result_success;
}
cgltf_result cgltf_copy_extras_json(const cgltf_data* data, const cgltf_extras* extras, char* dest, cgltf_size* dest_size)
{
cgltf_size json_size = extras->end_offset - extras->start_offset;
if (!dest)
{
if (dest_size)
{
*dest_size = json_size + 1;
return cgltf_result_success;
}
return cgltf_result_invalid_options;
}
if (*dest_size + 1 < json_size)
{
strncpy(dest, data->json + extras->start_offset, *dest_size - 1);
dest[*dest_size - 1] = 0;
}
else
{
strncpy(dest, data->json + extras->start_offset, json_size);
dest[json_size] = 0;
}
return cgltf_result_success;
}
static void cgltf_free_extras(cgltf_data* data, cgltf_extras* extras)
{
data->memory.free_func(data->memory.user_data, extras->data);
}
static void cgltf_free_extensions(cgltf_data* data, cgltf_extension* extensions, cgltf_size extensions_count)
{
for (cgltf_size i = 0; i < extensions_count; ++i)
{
data->memory.free_func(data->memory.user_data, extensions[i].name);
data->memory.free_func(data->memory.user_data, extensions[i].data);
}
data->memory.free_func(data->memory.user_data, extensions);
}
void cgltf_free(cgltf_data* data)
{
if (!data)
{
return;
}
void (*file_release)(const struct cgltf_memory_options*, const struct cgltf_file_options*, void* data, cgltf_size size) = data->file.release ? data->file.release : cgltf_default_file_release;
data->memory.free_func(data->memory.user_data, data->asset.copyright);
data->memory.free_func(data->memory.user_data, data->asset.generator);
data->memory.free_func(data->memory.user_data, data->asset.version);
data->memory.free_func(data->memory.user_data, data->asset.min_version);
cgltf_free_extensions(data, data->asset.extensions, data->asset.extensions_count);
cgltf_free_extras(data, &data->asset.extras);
for (cgltf_size i = 0; i < data->accessors_count; ++i)
{
data->memory.free_func(data->memory.user_data, data->accessors[i].name);
cgltf_free_extensions(data, data->accessors[i].extensions, data->accessors[i].extensions_count);
cgltf_free_extras(data, &data->accessors[i].extras);
}
data->memory.free_func(data->memory.user_data, data->accessors);
for (cgltf_size i = 0; i < data->buffer_views_count; ++i)
{
data->memory.free_func(data->memory.user_data, data->buffer_views[i].name);
data->memory.free_func(data->memory.user_data, data->buffer_views[i].data);
cgltf_free_extensions(data, data->buffer_views[i].extensions, data->buffer_views[i].extensions_count);
cgltf_free_extras(data, &data->buffer_views[i].extras);
}
data->memory.free_func(data->memory.user_data, data->buffer_views);
for (cgltf_size i = 0; i < data->buffers_count; ++i)
{
data->memory.free_func(data->memory.user_data, data->buffers[i].name);
if (data->buffers[i].data_free_method == cgltf_data_free_method_file_release)
{
file_release(&data->memory, &data->file, data->buffers[i].data, data->buffers[i].size);
}
else if (data->buffers[i].data_free_method == cgltf_data_free_method_memory_free)
{
data->memory.free_func(data->memory.user_data, data->buffers[i].data);
}
data->memory.free_func(data->memory.user_data, data->buffers[i].uri);
cgltf_free_extensions(data, data->buffers[i].extensions, data->buffers[i].extensions_count);
cgltf_free_extras(data, &data->buffers[i].extras);
}
data->memory.free_func(data->memory.user_data, data->buffers);
for (cgltf_size i = 0; i < data->meshes_count; ++i)
{
data->memory.free_func(data->memory.user_data, data->meshes[i].name);
for (cgltf_size j = 0; j < data->meshes[i].primitives_count; ++j)
{
for (cgltf_size k = 0; k < data->meshes[i].primitives[j].attributes_count; ++k)
{
data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].attributes[k].name);
}
data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].attributes);
for (cgltf_size k = 0; k < data->meshes[i].primitives[j].targets_count; ++k)
{
for (cgltf_size m = 0; m < data->meshes[i].primitives[j].targets[k].attributes_count; ++m)
{
data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].targets[k].attributes[m].name);
}
data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].targets[k].attributes);
}
data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].targets);
if (data->meshes[i].primitives[j].has_draco_mesh_compression)
{
for (cgltf_size k = 0; k < data->meshes[i].primitives[j].draco_mesh_compression.attributes_count; ++k)
{
data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].draco_mesh_compression.attributes[k].name);
}
data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].draco_mesh_compression.attributes);
}
for (cgltf_size k = 0; k < data->meshes[i].primitives[j].mappings_count; ++k)
{
cgltf_free_extras(data, &data->meshes[i].primitives[j].mappings[k].extras);
}
data->memory.free_func(data->memory.user_data, data->meshes[i].primitives[j].mappings);
cgltf_free_extensions(data, data->meshes[i].primitives[j].extensions, data->meshes[i].primitives[j].extensions_count);
cgltf_free_extras(data, &data->meshes[i].primitives[j].extras);
}
data->memory.free_func(data->memory.user_data, data->meshes[i].primitives);
data->memory.free_func(data->memory.user_data, data->meshes[i].weights);
for (cgltf_size j = 0; j < data->meshes[i].target_names_count; ++j)
{
data->memory.free_func(data->memory.user_data, data->meshes[i].target_names[j]);
}
cgltf_free_extensions(data, data->meshes[i].extensions, data->meshes[i].extensions_count);
cgltf_free_extras(data, &data->meshes[i].extras);
data->memory.free_func(data->memory.user_data, data->meshes[i].target_names);
}
data->memory.free_func(data->memory.user_data, data->meshes);
for (cgltf_size i = 0; i < data->materials_count; ++i)
{
data->memory.free_func(data->memory.user_data, data->materials[i].name);
cgltf_free_extensions(data, data->materials[i].extensions, data->materials[i].extensions_count);
cgltf_free_extras(data, &data->materials[i].extras);
}
data->memory.free_func(data->memory.user_data, data->materials);
for (cgltf_size i = 0; i < data->images_count; ++i)
{
data->memory.free_func(data->memory.user_data, data->images[i].name);
data->memory.free_func(data->memory.user_data, data->images[i].uri);
data->memory.free_func(data->memory.user_data, data->images[i].mime_type);
cgltf_free_extensions(data, data->images[i].extensions, data->images[i].extensions_count);
cgltf_free_extras(data, &data->images[i].extras);
}
data->memory.free_func(data->memory.user_data, data->images);
for (cgltf_size i = 0; i < data->textures_count; ++i)
{
data->memory.free_func(data->memory.user_data, data->textures[i].name);
cgltf_free_extensions(data, data->textures[i].extensions, data->textures[i].extensions_count);
cgltf_free_extras(data, &data->textures[i].extras);
}
data->memory.free_func(data->memory.user_data, data->textures);
for (cgltf_size i = 0; i < data->samplers_count; ++i)
{
data->memory.free_func(data->memory.user_data, data->samplers[i].name);
cgltf_free_extensions(data, data->samplers[i].extensions, data->samplers[i].extensions_count);
cgltf_free_extras(data, &data->samplers[i].extras);
}
data->memory.free_func(data->memory.user_data, data->samplers);
for (cgltf_size i = 0; i < data->skins_count; ++i)
{
data->memory.free_func(data->memory.user_data, data->skins[i].name);
data->memory.free_func(data->memory.user_data, data->skins[i].joints);
cgltf_free_extensions(data, data->skins[i].extensions, data->skins[i].extensions_count);
cgltf_free_extras(data, &data->skins[i].extras);
}
data->memory.free_func(data->memory.user_data, data->skins);
for (cgltf_size i = 0; i < data->cameras_count; ++i)
{
data->memory.free_func(data->memory.user_data, data->cameras[i].name);
if (data->cameras[i].type == cgltf_camera_type_perspective)
{
cgltf_free_extras(data, &data->cameras[i].data.perspective.extras);
}
else if (data->cameras[i].type == cgltf_camera_type_orthographic)
{
cgltf_free_extras(data, &data->cameras[i].data.orthographic.extras);
}
cgltf_free_extensions(data, data->cameras[i].extensions, data->cameras[i].extensions_count);
cgltf_free_extras(data, &data->cameras[i].extras);
}
data->memory.free_func(data->memory.user_data, data->cameras);
for (cgltf_size i = 0; i < data->lights_count; ++i)
{
data->memory.free_func(data->memory.user_data, data->lights[i].name);
cgltf_free_extras(data, &data->lights[i].extras);
}
data->memory.free_func(data->memory.user_data, data->lights);
for (cgltf_size i = 0; i < data->nodes_count; ++i)
{
data->memory.free_func(data->memory.user_data, data->nodes[i].name);
data->memory.free_func(data->memory.user_data, data->nodes[i].children);
data->memory.free_func(data->memory.user_data, data->nodes[i].weights);
if (data->nodes[i].has_mesh_gpu_instancing)
{
for (cgltf_size j = 0; j < data->nodes[i].mesh_gpu_instancing.attributes_count; ++j)
{
data->memory.free_func(data->memory.user_data, data->nodes[i].mesh_gpu_instancing.attributes[j].name);
}
data->memory.free_func(data->memory.user_data, data->nodes[i].mesh_gpu_instancing.attributes);
}
cgltf_free_extensions(data, data->nodes[i].extensions, data->nodes[i].extensions_count);
cgltf_free_extras(data, &data->nodes[i].extras);
}
data->memory.free_func(data->memory.user_data, data->nodes);
for (cgltf_size i = 0; i < data->scenes_count; ++i)
{
data->memory.free_func(data->memory.user_data, data->scenes[i].name);
data->memory.free_func(data->memory.user_data, data->scenes[i].nodes);
cgltf_free_extensions(data, data->scenes[i].extensions, data->scenes[i].extensions_count);
cgltf_free_extras(data, &data->scenes[i].extras);
}
data->memory.free_func(data->memory.user_data, data->scenes);
for (cgltf_size i = 0; i < data->animations_count; ++i)
{
data->memory.free_func(data->memory.user_data, data->animations[i].name);
for (cgltf_size j = 0; j < data->animations[i].samplers_count; ++j)
{
cgltf_free_extensions(data, data->animations[i].samplers[j].extensions, data->animations[i].samplers[j].extensions_count);
cgltf_free_extras(data, &data->animations[i].samplers[j].extras);
}
data->memory.free_func(data->memory.user_data, data->animations[i].samplers);
for (cgltf_size j = 0; j < data->animations[i].channels_count; ++j)
{
cgltf_free_extensions(data, data->animations[i].channels[j].extensions, data->animations[i].channels[j].extensions_count);
cgltf_free_extras(data, &data->animations[i].channels[j].extras);
}
data->memory.free_func(data->memory.user_data, data->animations[i].channels);
cgltf_free_extensions(data, data->animations[i].extensions, data->animations[i].extensions_count);
cgltf_free_extras(data, &data->animations[i].extras);
}
data->memory.free_func(data->memory.user_data, data->animations);
for (cgltf_size i = 0; i < data->variants_count; ++i)
{
data->memory.free_func(data->memory.user_data, data->variants[i].name);
cgltf_free_extras(data, &data->variants[i].extras);
}
data->memory.free_func(data->memory.user_data, data->variants);
cgltf_free_extensions(data, data->data_extensions, data->data_extensions_count);
cgltf_free_extras(data, &data->extras);
for (cgltf_size i = 0; i < data->extensions_used_count; ++i)
{
data->memory.free_func(data->memory.user_data, data->extensions_used[i]);
}
data->memory.free_func(data->memory.user_data, data->extensions_used);
for (cgltf_size i = 0; i < data->extensions_required_count; ++i)
{
data->memory.free_func(data->memory.user_data, data->extensions_required[i]);
}
data->memory.free_func(data->memory.user_data, data->extensions_required);
file_release(&data->memory, &data->file, data->file_data, data->file_size);
data->memory.free_func(data->memory.user_data, data);
}
void cgltf_node_transform_local(const cgltf_node* node, cgltf_float* out_matrix)
{
cgltf_float* lm = out_matrix;
if (node->has_matrix)
{
memcpy(lm, node->matrix, sizeof(float) * 16);
}
else
{
float tx = node->translation[0];
float ty = node->translation[1];
float tz = node->translation[2];
float qx = node->rotation[0];
float qy = node->rotation[1];
float qz = node->rotation[2];
float qw = node->rotation[3];
float sx = node->scale[0];
float sy = node->scale[1];
float sz = node->scale[2];
lm[0] = (1 - 2 * qy*qy - 2 * qz*qz) * sx;
lm[1] = (2 * qx*qy + 2 * qz*qw) * sx;
lm[2] = (2 * qx*qz - 2 * qy*qw) * sx;
lm[3] = 0.f;
lm[4] = (2 * qx*qy - 2 * qz*qw) * sy;
lm[5] = (1 - 2 * qx*qx - 2 * qz*qz) * sy;
lm[6] = (2 * qy*qz + 2 * qx*qw) * sy;
lm[7] = 0.f;
lm[8] = (2 * qx*qz + 2 * qy*qw) * sz;
lm[9] = (2 * qy*qz - 2 * qx*qw) * sz;
lm[10] = (1 - 2 * qx*qx - 2 * qy*qy) * sz;
lm[11] = 0.f;
lm[12] = tx;
lm[13] = ty;
lm[14] = tz;
lm[15] = 1.f;
}
}
void cgltf_node_transform_world(const cgltf_node* node, cgltf_float* out_matrix)
{
cgltf_float* lm = out_matrix;
cgltf_node_transform_local(node, lm);
const cgltf_node* parent = node->parent;
while (parent)
{
float pm[16];
cgltf_node_transform_local(parent, pm);
for (int i = 0; i < 4; ++i)
{
float l0 = lm[i * 4 + 0];
float l1 = lm[i * 4 + 1];
float l2 = lm[i * 4 + 2];
float r0 = l0 * pm[0] + l1 * pm[4] + l2 * pm[8];
float r1 = l0 * pm[1] + l1 * pm[5] + l2 * pm[9];
float r2 = l0 * pm[2] + l1 * pm[6] + l2 * pm[10];
lm[i * 4 + 0] = r0;
lm[i * 4 + 1] = r1;
lm[i * 4 + 2] = r2;
}
lm[12] += pm[12];
lm[13] += pm[13];
lm[14] += pm[14];
parent = parent->parent;
}
}
static cgltf_ssize cgltf_component_read_integer(const void* in, cgltf_component_type component_type)
{
switch (component_type)
{
case cgltf_component_type_r_16:
return *((const int16_t*) in);
case cgltf_component_type_r_16u:
return *((const uint16_t*) in);
case cgltf_component_type_r_32u:
return *((const uint32_t*) in);
case cgltf_component_type_r_8:
return *((const int8_t*) in);
case cgltf_component_type_r_8u:
return *((const uint8_t*) in);
default:
return 0;
}
}
static cgltf_size cgltf_component_read_index(const void* in, cgltf_component_type component_type)
{
switch (component_type)
{
case cgltf_component_type_r_16u:
return *((const uint16_t*) in);
case cgltf_component_type_r_32u:
return *((const uint32_t*) in);
case cgltf_component_type_r_8u:
return *((const uint8_t*) in);
default:
return 0;
}
}
static cgltf_float cgltf_component_read_float(const void* in, cgltf_component_type component_type, cgltf_bool normalized)
{
if (component_type == cgltf_component_type_r_32f)
{
return *((const float*) in);
}
if (normalized)
{
switch (component_type)
{
// note: glTF spec doesn't currently define normalized conversions for 32-bit integers
case cgltf_component_type_r_16:
return *((const int16_t*) in) / (cgltf_float)32767;
case cgltf_component_type_r_16u:
return *((const uint16_t*) in) / (cgltf_float)65535;
case cgltf_component_type_r_8:
return *((const int8_t*) in) / (cgltf_float)127;
case cgltf_component_type_r_8u:
return *((const uint8_t*) in) / (cgltf_float)255;
default:
return 0;
}
}
return (cgltf_float)cgltf_component_read_integer(in, component_type);
}
static cgltf_bool cgltf_element_read_float(const uint8_t* element, cgltf_type type, cgltf_component_type component_type, cgltf_bool normalized, cgltf_float* out, cgltf_size element_size)
{
cgltf_size num_components = cgltf_num_components(type);
if (element_size < num_components) {
return 0;
}
// There are three special cases for component extraction, see #data-alignment in the 2.0 spec.
cgltf_size component_size = cgltf_component_size(component_type);
if (type == cgltf_type_mat2 && component_size == 1)
{
out[0] = cgltf_component_read_float(element, component_type, normalized);
out[1] = cgltf_component_read_float(element + 1, component_type, normalized);
out[2] = cgltf_component_read_float(element + 4, component_type, normalized);
out[3] = cgltf_component_read_float(element + 5, component_type, normalized);
return 1;
}
if (type == cgltf_type_mat3 && component_size == 1)
{
out[0] = cgltf_component_read_float(element, component_type, normalized);
out[1] = cgltf_component_read_float(element + 1, component_type, normalized);
out[2] = cgltf_component_read_float(element + 2, component_type, normalized);
out[3] = cgltf_component_read_float(element + 4, component_type, normalized);
out[4] = cgltf_component_read_float(element + 5, component_type, normalized);
out[5] = cgltf_component_read_float(element + 6, component_type, normalized);
out[6] = cgltf_component_read_float(element + 8, component_type, normalized);
out[7] = cgltf_component_read_float(element + 9, component_type, normalized);
out[8] = cgltf_component_read_float(element + 10, component_type, normalized);
return 1;
}
if (type == cgltf_type_mat3 && component_size == 2)
{
out[0] = cgltf_component_read_float(element, component_type, normalized);
out[1] = cgltf_component_read_float(element + 2, component_type, normalized);
out[2] = cgltf_component_read_float(element + 4, component_type, normalized);
out[3] = cgltf_component_read_float(element + 8, component_type, normalized);
out[4] = cgltf_component_read_float(element + 10, component_type, normalized);
out[5] = cgltf_component_read_float(element + 12, component_type, normalized);
out[6] = cgltf_component_read_float(element + 16, component_type, normalized);
out[7] = cgltf_component_read_float(element + 18, component_type, normalized);
out[8] = cgltf_component_read_float(element + 20, component_type, normalized);
return 1;
}
for (cgltf_size i = 0; i < num_components; ++i)
{
out[i] = cgltf_component_read_float(element + component_size * i, component_type, normalized);
}
return 1;
}
const uint8_t* cgltf_buffer_view_data(const cgltf_buffer_view* view)
{
if (view->data)
return (const uint8_t*)view->data;
if (!view->buffer->data)
return NULL;
const uint8_t* result = (const uint8_t*)view->buffer->data;
result += view->offset;
return result;
}
const cgltf_accessor* cgltf_find_accessor(const cgltf_primitive* prim, cgltf_attribute_type type, cgltf_int index)
{
for (cgltf_size i = 0; i < prim->attributes_count; ++i)
{
const cgltf_attribute* attr = &prim->attributes[i];
if (attr->type == type && attr->index == index)
return attr->data;
}
return NULL;
}
static const uint8_t* cgltf_find_sparse_index(const cgltf_accessor* accessor, cgltf_size needle)
{
const cgltf_accessor_sparse* sparse = &accessor->sparse;
const uint8_t* index_data = cgltf_buffer_view_data(sparse->indices_buffer_view);
const uint8_t* value_data = cgltf_buffer_view_data(sparse->values_buffer_view);
if (index_data == NULL || value_data == NULL)
return NULL;
index_data += sparse->indices_byte_offset;
value_data += sparse->values_byte_offset;
cgltf_size index_stride = cgltf_component_size(sparse->indices_component_type);
cgltf_size offset = 0;
cgltf_size length = sparse->count;
while (length)
{
cgltf_size rem = length % 2;
length /= 2;
cgltf_size index = cgltf_component_read_index(index_data + (offset + length) * index_stride, sparse->indices_component_type);
offset += index < needle ? length + rem : 0;
}
if (offset == sparse->count)
return NULL;
cgltf_size index = cgltf_component_read_index(index_data + offset * index_stride, sparse->indices_component_type);
return index == needle ? value_data + offset * accessor->stride : NULL;
}
cgltf_bool cgltf_accessor_read_float(const cgltf_accessor* accessor, cgltf_size index, cgltf_float* out, cgltf_size element_size)
{
if (accessor->is_sparse)
{
const uint8_t* element = cgltf_find_sparse_index(accessor, index);
if (element)
return cgltf_element_read_float(element, accessor->type, accessor->component_type, accessor->normalized, out, element_size);
}
if (accessor->buffer_view == NULL)
{
memset(out, 0, element_size * sizeof(cgltf_float));
return 1;
}
const uint8_t* element = cgltf_buffer_view_data(accessor->buffer_view);
if (element == NULL)
{
return 0;
}
element += accessor->offset + accessor->stride * index;
return cgltf_element_read_float(element, accessor->type, accessor->component_type, accessor->normalized, out, element_size);
}
cgltf_size cgltf_accessor_unpack_floats(const cgltf_accessor* accessor, cgltf_float* out, cgltf_size float_count)
{
cgltf_size floats_per_element = cgltf_num_components(accessor->type);
cgltf_size available_floats = accessor->count * floats_per_element;
if (out == NULL)
{
return available_floats;
}
float_count = available_floats < float_count ? available_floats : float_count;
cgltf_size element_count = float_count / floats_per_element;
// First pass: convert each element in the base accessor.
if (accessor->buffer_view == NULL)
{
memset(out, 0, element_count * floats_per_element * sizeof(cgltf_float));
}
else
{
const uint8_t* element = cgltf_buffer_view_data(accessor->buffer_view);
if (element == NULL)
{
return 0;
}
element += accessor->offset;
if (accessor->component_type == cgltf_component_type_r_32f && accessor->stride == floats_per_element * sizeof(cgltf_float))
{
memcpy(out, element, element_count * floats_per_element * sizeof(cgltf_float));
}
else
{
cgltf_float* dest = out;
for (cgltf_size index = 0; index < element_count; index++, dest += floats_per_element, element += accessor->stride)
{
if (!cgltf_element_read_float(element, accessor->type, accessor->component_type, accessor->normalized, dest, floats_per_element))
{
return 0;
}
}
}
}
// Second pass: write out each element in the sparse accessor.
if (accessor->is_sparse)
{
const cgltf_accessor_sparse* sparse = &accessor->sparse;
const uint8_t* index_data = cgltf_buffer_view_data(sparse->indices_buffer_view);
const uint8_t* reader_head = cgltf_buffer_view_data(sparse->values_buffer_view);
if (index_data == NULL || reader_head == NULL)
{
return 0;
}
index_data += sparse->indices_byte_offset;
reader_head += sparse->values_byte_offset;
cgltf_size index_stride = cgltf_component_size(sparse->indices_component_type);
for (cgltf_size reader_index = 0; reader_index < sparse->count; reader_index++, index_data += index_stride, reader_head += accessor->stride)
{
size_t writer_index = cgltf_component_read_index(index_data, sparse->indices_component_type);
float* writer_head = out + writer_index * floats_per_element;
if (!cgltf_element_read_float(reader_head, accessor->type, accessor->component_type, accessor->normalized, writer_head, floats_per_element))
{
return 0;
}
}
}
return element_count * floats_per_element;
}
static cgltf_uint cgltf_component_read_uint(const void* in, cgltf_component_type component_type)
{
switch (component_type)
{
case cgltf_component_type_r_8:
return *((const int8_t*) in);
case cgltf_component_type_r_8u:
return *((const uint8_t*) in);
case cgltf_component_type_r_16:
return *((const int16_t*) in);
case cgltf_component_type_r_16u:
return *((const uint16_t*) in);
case cgltf_component_type_r_32u:
return *((const uint32_t*) in);
default:
return 0;
}
}
static cgltf_bool cgltf_element_read_uint(const uint8_t* element, cgltf_type type, cgltf_component_type component_type, cgltf_uint* out, cgltf_size element_size)
{
cgltf_size num_components = cgltf_num_components(type);
if (element_size < num_components)
{
return 0;
}
// Reading integer matrices is not a valid use case
if (type == cgltf_type_mat2 || type == cgltf_type_mat3 || type == cgltf_type_mat4)
{
return 0;
}
cgltf_size component_size = cgltf_component_size(component_type);
for (cgltf_size i = 0; i < num_components; ++i)
{
out[i] = cgltf_component_read_uint(element + component_size * i, component_type);
}
return 1;
}
cgltf_bool cgltf_accessor_read_uint(const cgltf_accessor* accessor, cgltf_size index, cgltf_uint* out, cgltf_size element_size)
{
if (accessor->is_sparse)
{
const uint8_t* element = cgltf_find_sparse_index(accessor, index);
if (element)
return cgltf_element_read_uint(element, accessor->type, accessor->component_type, out, element_size);
}
if (accessor->buffer_view == NULL)
{
memset(out, 0, element_size * sizeof(cgltf_uint));
return 1;
}
const uint8_t* element = cgltf_buffer_view_data(accessor->buffer_view);
if (element == NULL)
{
return 0;
}
element += accessor->offset + accessor->stride * index;
return cgltf_element_read_uint(element, accessor->type, accessor->component_type, out, element_size);
}
cgltf_size cgltf_accessor_read_index(const cgltf_accessor* accessor, cgltf_size index)
{
if (accessor->is_sparse)
{
const uint8_t* element = cgltf_find_sparse_index(accessor, index);
if (element)
return cgltf_component_read_index(element, accessor->component_type);
}
if (accessor->buffer_view == NULL)
{
return 0;
}
const uint8_t* element = cgltf_buffer_view_data(accessor->buffer_view);
if (element == NULL)
{
return 0; // This is an error case, but we can't communicate the error with existing interface.
}
element += accessor->offset + accessor->stride * index;
return cgltf_component_read_index(element, accessor->component_type);
}
cgltf_size cgltf_mesh_index(const cgltf_data* data, const cgltf_mesh* object)
{
assert(object && (cgltf_size)(object - data->meshes) < data->meshes_count);
return (cgltf_size)(object - data->meshes);
}
cgltf_size cgltf_material_index(const cgltf_data* data, const cgltf_material* object)
{
assert(object && (cgltf_size)(object - data->materials) < data->materials_count);
return (cgltf_size)(object - data->materials);
}
cgltf_size cgltf_accessor_index(const cgltf_data* data, const cgltf_accessor* object)
{
assert(object && (cgltf_size)(object - data->accessors) < data->accessors_count);
return (cgltf_size)(object - data->accessors);
}
cgltf_size cgltf_buffer_view_index(const cgltf_data* data, const cgltf_buffer_view* object)
{
assert(object && (cgltf_size)(object - data->buffer_views) < data->buffer_views_count);
return (cgltf_size)(object - data->buffer_views);
}
cgltf_size cgltf_buffer_index(const cgltf_data* data, const cgltf_buffer* object)
{
assert(object && (cgltf_size)(object - data->buffers) < data->buffers_count);
return (cgltf_size)(object - data->buffers);
}
cgltf_size cgltf_image_index(const cgltf_data* data, const cgltf_image* object)
{
assert(object && (cgltf_size)(object - data->images) < data->images_count);
return (cgltf_size)(object - data->images);
}
cgltf_size cgltf_texture_index(const cgltf_data* data, const cgltf_texture* object)
{
assert(object && (cgltf_size)(object - data->textures) < data->textures_count);
return (cgltf_size)(object - data->textures);
}
cgltf_size cgltf_sampler_index(const cgltf_data* data, const cgltf_sampler* object)
{
assert(object && (cgltf_size)(object - data->samplers) < data->samplers_count);
return (cgltf_size)(object - data->samplers);
}
cgltf_size cgltf_skin_index(const cgltf_data* data, const cgltf_skin* object)
{
assert(object && (cgltf_size)(object - data->skins) < data->skins_count);
return (cgltf_size)(object - data->skins);
}
cgltf_size cgltf_camera_index(const cgltf_data* data, const cgltf_camera* object)
{
assert(object && (cgltf_size)(object - data->cameras) < data->cameras_count);
return (cgltf_size)(object - data->cameras);
}
cgltf_size cgltf_light_index(const cgltf_data* data, const cgltf_light* object)
{
assert(object && (cgltf_size)(object - data->lights) < data->lights_count);
return (cgltf_size)(object - data->lights);
}
cgltf_size cgltf_node_index(const cgltf_data* data, const cgltf_node* object)
{
assert(object && (cgltf_size)(object - data->nodes) < data->nodes_count);
return (cgltf_size)(object - data->nodes);
}
cgltf_size cgltf_scene_index(const cgltf_data* data, const cgltf_scene* object)
{
assert(object && (cgltf_size)(object - data->scenes) < data->scenes_count);
return (cgltf_size)(object - data->scenes);
}
cgltf_size cgltf_animation_index(const cgltf_data* data, const cgltf_animation* object)
{
assert(object && (cgltf_size)(object - data->animations) < data->animations_count);
return (cgltf_size)(object - data->animations);
}
cgltf_size cgltf_animation_sampler_index(const cgltf_animation* animation, const cgltf_animation_sampler* object)
{
assert(object && (cgltf_size)(object - animation->samplers) < animation->samplers_count);
return (cgltf_size)(object - animation->samplers);
}
cgltf_size cgltf_animation_channel_index(const cgltf_animation* animation, const cgltf_animation_channel* object)
{
assert(object && (cgltf_size)(object - animation->channels) < animation->channels_count);
return (cgltf_size)(object - animation->channels);
}
cgltf_size cgltf_accessor_unpack_indices(const cgltf_accessor* accessor, void* out, cgltf_size out_component_size, cgltf_size index_count)
{
if (out == NULL)
{
return accessor->count;
}
cgltf_size numbers_per_element = cgltf_num_components(accessor->type);
cgltf_size available_numbers = accessor->count * numbers_per_element;
index_count = available_numbers < index_count ? available_numbers : index_count;
cgltf_size index_component_size = cgltf_component_size(accessor->component_type);
if (accessor->is_sparse)
{
return 0;
}
if (accessor->buffer_view == NULL)
{
return 0;
}
if (index_component_size > out_component_size)
{
return 0;
}
const uint8_t* element = cgltf_buffer_view_data(accessor->buffer_view);
if (element == NULL)
{
return 0;
}
element += accessor->offset;
if (index_component_size == out_component_size && accessor->stride == out_component_size * numbers_per_element)
{
memcpy(out, element, index_count * index_component_size);
return index_count;
}
// Data couldn't be copied with memcpy due to stride being larger than the component size.
// OR
// The component size of the output array is larger than the component size of the index data, so index data will be padded.
switch (out_component_size)
{
case 1:
for (cgltf_size index = 0; index < index_count; index++, element += accessor->stride)
{
((uint8_t*)out)[index] = (uint8_t)cgltf_component_read_index(element, accessor->component_type);
}
break;
case 2:
for (cgltf_size index = 0; index < index_count; index++, element += accessor->stride)
{
((uint16_t*)out)[index] = (uint16_t)cgltf_component_read_index(element, accessor->component_type);
}
break;
case 4:
for (cgltf_size index = 0; index < index_count; index++, element += accessor->stride)
{
((uint32_t*)out)[index] = (uint32_t)cgltf_component_read_index(element, accessor->component_type);
}
break;
default:
return 0;
}
return index_count;
}
#define CGLTF_ERROR_JSON -1
#define CGLTF_ERROR_NOMEM -2
#define CGLTF_ERROR_LEGACY -3
#define CGLTF_CHECK_TOKTYPE(tok_, type_) if ((tok_).type != (type_)) { return CGLTF_ERROR_JSON; }
#define CGLTF_CHECK_TOKTYPE_RET(tok_, type_, ret_) if ((tok_).type != (type_)) { return ret_; }
#define CGLTF_CHECK_KEY(tok_) if ((tok_).type != JSMN_STRING || (tok_).size == 0) { return CGLTF_ERROR_JSON; } /* checking size for 0 verifies that a value follows the key */
#define CGLTF_PTRINDEX(type, idx) (type*)((cgltf_size)idx + 1)
#define CGLTF_PTRFIXUP(var, data, size) if (var) { if ((cgltf_size)var > size) { return CGLTF_ERROR_JSON; } var = &data[(cgltf_size)var-1]; }
#define CGLTF_PTRFIXUP_REQ(var, data, size) if (!var || (cgltf_size)var > size) { return CGLTF_ERROR_JSON; } var = &data[(cgltf_size)var-1];
static int cgltf_json_strcmp(jsmntok_t const* tok, const uint8_t* json_chunk, const char* str)
{
CGLTF_CHECK_TOKTYPE(*tok, JSMN_STRING);
size_t const str_len = strlen(str);
size_t const name_length = (size_t)(tok->end - tok->start);
return (str_len == name_length) ? strncmp((const char*)json_chunk + tok->start, str, str_len) : 128;
}
static int cgltf_json_to_int(jsmntok_t const* tok, const uint8_t* json_chunk)
{
CGLTF_CHECK_TOKTYPE(*tok, JSMN_PRIMITIVE);
char tmp[128];
int size = (size_t)(tok->end - tok->start) < sizeof(tmp) ? (int)(tok->end - tok->start) : (int)(sizeof(tmp) - 1);
strncpy(tmp, (const char*)json_chunk + tok->start, size);
tmp[size] = 0;
return CGLTF_ATOI(tmp);
}
static cgltf_size cgltf_json_to_size(jsmntok_t const* tok, const uint8_t* json_chunk)
{
CGLTF_CHECK_TOKTYPE_RET(*tok, JSMN_PRIMITIVE, 0);
char tmp[128];
int size = (size_t)(tok->end - tok->start) < sizeof(tmp) ? (int)(tok->end - tok->start) : (int)(sizeof(tmp) - 1);
strncpy(tmp, (const char*)json_chunk + tok->start, size);
tmp[size] = 0;
long long res = CGLTF_ATOLL(tmp);
return res < 0 ? 0 : (cgltf_size)res;
}
static cgltf_float cgltf_json_to_float(jsmntok_t const* tok, const uint8_t* json_chunk)
{
CGLTF_CHECK_TOKTYPE(*tok, JSMN_PRIMITIVE);
char tmp[128];
int size = (size_t)(tok->end - tok->start) < sizeof(tmp) ? (int)(tok->end - tok->start) : (int)(sizeof(tmp) - 1);
strncpy(tmp, (const char*)json_chunk + tok->start, size);
tmp[size] = 0;
return (cgltf_float)CGLTF_ATOF(tmp);
}
static cgltf_bool cgltf_json_to_bool(jsmntok_t const* tok, const uint8_t* json_chunk)
{
int size = (int)(tok->end - tok->start);
return size == 4 && memcmp(json_chunk + tok->start, "true", 4) == 0;
}
static int cgltf_skip_json(jsmntok_t const* tokens, int i)
{
int end = i + 1;
while (i < end)
{
switch (tokens[i].type)
{
case JSMN_OBJECT:
end += tokens[i].size * 2;
break;
case JSMN_ARRAY:
end += tokens[i].size;
break;
case JSMN_PRIMITIVE:
case JSMN_STRING:
break;
default:
return -1;
}
i++;
}
return i;
}
static void cgltf_fill_float_array(float* out_array, int size, float value)
{
for (int j = 0; j < size; ++j)
{
out_array[j] = value;
}
}
static int cgltf_parse_json_float_array(jsmntok_t const* tokens, int i, const uint8_t* json_chunk, float* out_array, int size)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_ARRAY);
if (tokens[i].size != size)
{
return CGLTF_ERROR_JSON;
}
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE);
out_array[j] = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
return i;
}
static int cgltf_parse_json_string(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, char** out_string)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_STRING);
if (*out_string)
{
return CGLTF_ERROR_JSON;
}
int size = (int)(tokens[i].end - tokens[i].start);
char* result = (char*)options->memory.alloc_func(options->memory.user_data, size + 1);
if (!result)
{
return CGLTF_ERROR_NOMEM;
}
strncpy(result, (const char*)json_chunk + tokens[i].start, size);
result[size] = 0;
*out_string = result;
return i + 1;
}
static int cgltf_parse_json_array(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, size_t element_size, void** out_array, cgltf_size* out_size)
{
(void)json_chunk;
if (tokens[i].type != JSMN_ARRAY)
{
return tokens[i].type == JSMN_OBJECT ? CGLTF_ERROR_LEGACY : CGLTF_ERROR_JSON;
}
if (*out_array)
{
return CGLTF_ERROR_JSON;
}
int size = tokens[i].size;
void* result = cgltf_calloc(options, element_size, size);
if (!result)
{
return CGLTF_ERROR_NOMEM;
}
*out_array = result;
*out_size = size;
return i + 1;
}
static int cgltf_parse_json_string_array(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, char*** out_array, cgltf_size* out_size)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_ARRAY);
i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(char*), (void**)out_array, out_size);
if (i < 0)
{
return i;
}
for (cgltf_size j = 0; j < *out_size; ++j)
{
i = cgltf_parse_json_string(options, tokens, i, json_chunk, j + (*out_array));
if (i < 0)
{
return i;
}
}
return i;
}
static void cgltf_parse_attribute_type(const char* name, cgltf_attribute_type* out_type, int* out_index)
{
if (*name == '_')
{
*out_type = cgltf_attribute_type_custom;
return;
}
const char* us = strchr(name, '_');
size_t len = us ? (size_t)(us - name) : strlen(name);
if (len == 8 && strncmp(name, "POSITION", 8) == 0)
{
*out_type = cgltf_attribute_type_position;
}
else if (len == 6 && strncmp(name, "NORMAL", 6) == 0)
{
*out_type = cgltf_attribute_type_normal;
}
else if (len == 7 && strncmp(name, "TANGENT", 7) == 0)
{
*out_type = cgltf_attribute_type_tangent;
}
else if (len == 8 && strncmp(name, "TEXCOORD", 8) == 0)
{
*out_type = cgltf_attribute_type_texcoord;
}
else if (len == 5 && strncmp(name, "COLOR", 5) == 0)
{
*out_type = cgltf_attribute_type_color;
}
else if (len == 6 && strncmp(name, "JOINTS", 6) == 0)
{
*out_type = cgltf_attribute_type_joints;
}
else if (len == 7 && strncmp(name, "WEIGHTS", 7) == 0)
{
*out_type = cgltf_attribute_type_weights;
}
else
{
*out_type = cgltf_attribute_type_invalid;
}
if (us && *out_type != cgltf_attribute_type_invalid)
{
*out_index = CGLTF_ATOI(us + 1);
if (*out_index < 0)
{
*out_type = cgltf_attribute_type_invalid;
*out_index = 0;
}
}
}
static int cgltf_parse_json_attribute_list(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_attribute** out_attributes, cgltf_size* out_attributes_count)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
if (*out_attributes)
{
return CGLTF_ERROR_JSON;
}
*out_attributes_count = tokens[i].size;
*out_attributes = (cgltf_attribute*)cgltf_calloc(options, sizeof(cgltf_attribute), *out_attributes_count);
++i;
if (!*out_attributes)
{
return CGLTF_ERROR_NOMEM;
}
for (cgltf_size j = 0; j < *out_attributes_count; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
i = cgltf_parse_json_string(options, tokens, i, json_chunk, &(*out_attributes)[j].name);
if (i < 0)
{
return CGLTF_ERROR_JSON;
}
cgltf_parse_attribute_type((*out_attributes)[j].name, &(*out_attributes)[j].type, &(*out_attributes)[j].index);
(*out_attributes)[j].data = CGLTF_PTRINDEX(cgltf_accessor, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
return i;
}
static int cgltf_parse_json_extras(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_extras* out_extras)
{
if (out_extras->data)
{
return CGLTF_ERROR_JSON;
}
/* fill deprecated fields for now, this will be removed in the future */
out_extras->start_offset = tokens[i].start;
out_extras->end_offset = tokens[i].end;
size_t start = tokens[i].start;
size_t size = tokens[i].end - start;
out_extras->data = (char*)options->memory.alloc_func(options->memory.user_data, size + 1);
if (!out_extras->data)
{
return CGLTF_ERROR_NOMEM;
}
strncpy(out_extras->data, (const char*)json_chunk + start, size);
out_extras->data[size] = '\0';
i = cgltf_skip_json(tokens, i);
return i;
}
static int cgltf_parse_json_unprocessed_extension(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_extension* out_extension)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_STRING);
CGLTF_CHECK_TOKTYPE(tokens[i+1], JSMN_OBJECT);
if (out_extension->name)
{
return CGLTF_ERROR_JSON;
}
cgltf_size name_length = tokens[i].end - tokens[i].start;
out_extension->name = (char*)options->memory.alloc_func(options->memory.user_data, name_length + 1);
if (!out_extension->name)
{
return CGLTF_ERROR_NOMEM;
}
strncpy(out_extension->name, (const char*)json_chunk + tokens[i].start, name_length);
out_extension->name[name_length] = 0;
i++;
size_t start = tokens[i].start;
size_t size = tokens[i].end - start;
out_extension->data = (char*)options->memory.alloc_func(options->memory.user_data, size + 1);
if (!out_extension->data)
{
return CGLTF_ERROR_NOMEM;
}
strncpy(out_extension->data, (const char*)json_chunk + start, size);
out_extension->data[size] = '\0';
i = cgltf_skip_json(tokens, i);
return i;
}
static int cgltf_parse_json_unprocessed_extensions(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_size* out_extensions_count, cgltf_extension** out_extensions)
{
++i;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
if(*out_extensions)
{
return CGLTF_ERROR_JSON;
}
int extensions_size = tokens[i].size;
*out_extensions_count = 0;
*out_extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size);
if (!*out_extensions)
{
return CGLTF_ERROR_NOMEM;
}
++i;
for (int j = 0; j < extensions_size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
cgltf_size extension_index = (*out_extensions_count)++;
cgltf_extension* extension = &((*out_extensions)[extension_index]);
i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, extension);
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_draco_mesh_compression(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_draco_mesh_compression* out_draco_mesh_compression)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens + i, json_chunk, "attributes") == 0)
{
i = cgltf_parse_json_attribute_list(options, tokens, i + 1, json_chunk, &out_draco_mesh_compression->attributes, &out_draco_mesh_compression->attributes_count);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "bufferView") == 0)
{
++i;
out_draco_mesh_compression->buffer_view = CGLTF_PTRINDEX(cgltf_buffer_view, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_mesh_gpu_instancing(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_mesh_gpu_instancing* out_mesh_gpu_instancing)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens + i, json_chunk, "attributes") == 0)
{
i = cgltf_parse_json_attribute_list(options, tokens, i + 1, json_chunk, &out_mesh_gpu_instancing->attributes, &out_mesh_gpu_instancing->attributes_count);
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_material_mapping_data(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_material_mapping* out_mappings, cgltf_size* offset)
{
(void)options;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_ARRAY);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int obj_size = tokens[i].size;
++i;
int material = -1;
int variants_tok = -1;
int extras_tok = -1;
for (int k = 0; k < obj_size; ++k)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens + i, json_chunk, "material") == 0)
{
++i;
material = cgltf_json_to_int(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "variants") == 0)
{
variants_tok = i+1;
CGLTF_CHECK_TOKTYPE(tokens[variants_tok], JSMN_ARRAY);
i = cgltf_skip_json(tokens, i+1);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
{
extras_tok = i + 1;
i = cgltf_skip_json(tokens, extras_tok);
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
if (material < 0 || variants_tok < 0)
{
return CGLTF_ERROR_JSON;
}
if (out_mappings)
{
for (int k = 0; k < tokens[variants_tok].size; ++k)
{
int variant = cgltf_json_to_int(&tokens[variants_tok + 1 + k], json_chunk);
if (variant < 0)
return variant;
out_mappings[*offset].material = CGLTF_PTRINDEX(cgltf_material, material);
out_mappings[*offset].variant = variant;
if (extras_tok >= 0)
{
int e = cgltf_parse_json_extras(options, tokens, extras_tok, json_chunk, &out_mappings[*offset].extras);
if (e < 0)
return e;
}
(*offset)++;
}
}
else
{
(*offset) += tokens[variants_tok].size;
}
}
return i;
}
static int cgltf_parse_json_material_mappings(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_primitive* out_prim)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens + i, json_chunk, "mappings") == 0)
{
if (out_prim->mappings)
{
return CGLTF_ERROR_JSON;
}
cgltf_size mappings_offset = 0;
int k = cgltf_parse_json_material_mapping_data(options, tokens, i + 1, json_chunk, NULL, &mappings_offset);
if (k < 0)
{
return k;
}
out_prim->mappings_count = mappings_offset;
out_prim->mappings = (cgltf_material_mapping*)cgltf_calloc(options, sizeof(cgltf_material_mapping), out_prim->mappings_count);
mappings_offset = 0;
i = cgltf_parse_json_material_mapping_data(options, tokens, i + 1, json_chunk, out_prim->mappings, &mappings_offset);
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static cgltf_primitive_type cgltf_json_to_primitive_type(jsmntok_t const* tok, const uint8_t* json_chunk)
{
int type = cgltf_json_to_int(tok, json_chunk);
switch (type)
{
case 0:
return cgltf_primitive_type_points;
case 1:
return cgltf_primitive_type_lines;
case 2:
return cgltf_primitive_type_line_loop;
case 3:
return cgltf_primitive_type_line_strip;
case 4:
return cgltf_primitive_type_triangles;
case 5:
return cgltf_primitive_type_triangle_strip;
case 6:
return cgltf_primitive_type_triangle_fan;
default:
return cgltf_primitive_type_invalid;
}
}
static int cgltf_parse_json_primitive(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_primitive* out_prim)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
out_prim->type = cgltf_primitive_type_triangles;
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "mode") == 0)
{
++i;
out_prim->type = cgltf_json_to_primitive_type(tokens+i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "indices") == 0)
{
++i;
out_prim->indices = CGLTF_PTRINDEX(cgltf_accessor, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "material") == 0)
{
++i;
out_prim->material = CGLTF_PTRINDEX(cgltf_material, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "attributes") == 0)
{
i = cgltf_parse_json_attribute_list(options, tokens, i + 1, json_chunk, &out_prim->attributes, &out_prim->attributes_count);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "targets") == 0)
{
i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_morph_target), (void**)&out_prim->targets, &out_prim->targets_count);
if (i < 0)
{
return i;
}
for (cgltf_size k = 0; k < out_prim->targets_count; ++k)
{
i = cgltf_parse_json_attribute_list(options, tokens, i, json_chunk, &out_prim->targets[k].attributes, &out_prim->targets[k].attributes_count);
if (i < 0)
{
return i;
}
}
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
{
i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_prim->extras);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
{
++i;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
if(out_prim->extensions)
{
return CGLTF_ERROR_JSON;
}
int extensions_size = tokens[i].size;
out_prim->extensions_count = 0;
out_prim->extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size);
if (!out_prim->extensions)
{
return CGLTF_ERROR_NOMEM;
}
++i;
for (int k = 0; k < extensions_size; ++k)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_draco_mesh_compression") == 0)
{
out_prim->has_draco_mesh_compression = 1;
i = cgltf_parse_json_draco_mesh_compression(options, tokens, i + 1, json_chunk, &out_prim->draco_mesh_compression);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_variants") == 0)
{
i = cgltf_parse_json_material_mappings(options, tokens, i + 1, json_chunk, out_prim);
}
else
{
i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_prim->extensions[out_prim->extensions_count++]));
}
if (i < 0)
{
return i;
}
}
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_mesh(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_mesh* out_mesh)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0)
{
i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_mesh->name);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "primitives") == 0)
{
i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_primitive), (void**)&out_mesh->primitives, &out_mesh->primitives_count);
if (i < 0)
{
return i;
}
for (cgltf_size prim_index = 0; prim_index < out_mesh->primitives_count; ++prim_index)
{
i = cgltf_parse_json_primitive(options, tokens, i, json_chunk, &out_mesh->primitives[prim_index]);
if (i < 0)
{
return i;
}
}
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "weights") == 0)
{
i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_float), (void**)&out_mesh->weights, &out_mesh->weights_count);
if (i < 0)
{
return i;
}
i = cgltf_parse_json_float_array(tokens, i - 1, json_chunk, out_mesh->weights, (int)out_mesh->weights_count);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
{
++i;
out_mesh->extras.start_offset = tokens[i].start;
out_mesh->extras.end_offset = tokens[i].end;
if (tokens[i].type == JSMN_OBJECT)
{
int extras_size = tokens[i].size;
++i;
for (int k = 0; k < extras_size; ++k)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "targetNames") == 0 && tokens[i+1].type == JSMN_ARRAY)
{
i = cgltf_parse_json_string_array(options, tokens, i + 1, json_chunk, &out_mesh->target_names, &out_mesh->target_names_count);
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
}
else
{
i = cgltf_skip_json(tokens, i);
}
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
{
i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_mesh->extensions_count, &out_mesh->extensions);
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_meshes(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
{
i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_mesh), (void**)&out_data->meshes, &out_data->meshes_count);
if (i < 0)
{
return i;
}
for (cgltf_size j = 0; j < out_data->meshes_count; ++j)
{
i = cgltf_parse_json_mesh(options, tokens, i, json_chunk, &out_data->meshes[j]);
if (i < 0)
{
return i;
}
}
return i;
}
static cgltf_component_type cgltf_json_to_component_type(jsmntok_t const* tok, const uint8_t* json_chunk)
{
int type = cgltf_json_to_int(tok, json_chunk);
switch (type)
{
case 5120:
return cgltf_component_type_r_8;
case 5121:
return cgltf_component_type_r_8u;
case 5122:
return cgltf_component_type_r_16;
case 5123:
return cgltf_component_type_r_16u;
case 5125:
return cgltf_component_type_r_32u;
case 5126:
return cgltf_component_type_r_32f;
default:
return cgltf_component_type_invalid;
}
}
static int cgltf_parse_json_accessor_sparse(jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_accessor_sparse* out_sparse)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "count") == 0)
{
++i;
out_sparse->count = cgltf_json_to_size(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "indices") == 0)
{
++i;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int indices_size = tokens[i].size;
++i;
for (int k = 0; k < indices_size; ++k)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "bufferView") == 0)
{
++i;
out_sparse->indices_buffer_view = CGLTF_PTRINDEX(cgltf_buffer_view, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteOffset") == 0)
{
++i;
out_sparse->indices_byte_offset = cgltf_json_to_size(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "componentType") == 0)
{
++i;
out_sparse->indices_component_type = cgltf_json_to_component_type(tokens + i, json_chunk);
++i;
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "values") == 0)
{
++i;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int values_size = tokens[i].size;
++i;
for (int k = 0; k < values_size; ++k)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "bufferView") == 0)
{
++i;
out_sparse->values_buffer_view = CGLTF_PTRINDEX(cgltf_buffer_view, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteOffset") == 0)
{
++i;
out_sparse->values_byte_offset = cgltf_json_to_size(tokens + i, json_chunk);
++i;
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_accessor(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_accessor* out_accessor)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens + i, json_chunk, "name") == 0)
{
i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_accessor->name);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "bufferView") == 0)
{
++i;
out_accessor->buffer_view = CGLTF_PTRINDEX(cgltf_buffer_view, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteOffset") == 0)
{
++i;
out_accessor->offset =
cgltf_json_to_size(tokens+i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "componentType") == 0)
{
++i;
out_accessor->component_type = cgltf_json_to_component_type(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "normalized") == 0)
{
++i;
out_accessor->normalized = cgltf_json_to_bool(tokens+i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "count") == 0)
{
++i;
out_accessor->count = cgltf_json_to_size(tokens+i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "type") == 0)
{
++i;
if (cgltf_json_strcmp(tokens+i, json_chunk, "SCALAR") == 0)
{
out_accessor->type = cgltf_type_scalar;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "VEC2") == 0)
{
out_accessor->type = cgltf_type_vec2;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "VEC3") == 0)
{
out_accessor->type = cgltf_type_vec3;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "VEC4") == 0)
{
out_accessor->type = cgltf_type_vec4;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "MAT2") == 0)
{
out_accessor->type = cgltf_type_mat2;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "MAT3") == 0)
{
out_accessor->type = cgltf_type_mat3;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "MAT4") == 0)
{
out_accessor->type = cgltf_type_mat4;
}
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "min") == 0)
{
++i;
out_accessor->has_min = 1;
// note: we can't parse the precise number of elements since type may not have been computed yet
int min_size = tokens[i].size > 16 ? 16 : tokens[i].size;
i = cgltf_parse_json_float_array(tokens, i, json_chunk, out_accessor->min, min_size);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "max") == 0)
{
++i;
out_accessor->has_max = 1;
// note: we can't parse the precise number of elements since type may not have been computed yet
int max_size = tokens[i].size > 16 ? 16 : tokens[i].size;
i = cgltf_parse_json_float_array(tokens, i, json_chunk, out_accessor->max, max_size);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "sparse") == 0)
{
out_accessor->is_sparse = 1;
i = cgltf_parse_json_accessor_sparse(tokens, i + 1, json_chunk, &out_accessor->sparse);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
{
i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_accessor->extras);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
{
i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_accessor->extensions_count, &out_accessor->extensions);
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_texture_transform(jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_texture_transform* out_texture_transform)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens + i, json_chunk, "offset") == 0)
{
i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_texture_transform->offset, 2);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "rotation") == 0)
{
++i;
out_texture_transform->rotation = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "scale") == 0)
{
i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_texture_transform->scale, 2);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "texCoord") == 0)
{
++i;
out_texture_transform->has_texcoord = 1;
out_texture_transform->texcoord = cgltf_json_to_int(tokens + i, json_chunk);
++i;
}
else
{
i = cgltf_skip_json(tokens, i + 1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_texture_view(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_texture_view* out_texture_view)
{
(void)options;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
out_texture_view->scale = 1.0f;
cgltf_fill_float_array(out_texture_view->transform.scale, 2, 1.0f);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens + i, json_chunk, "index") == 0)
{
++i;
out_texture_view->texture = CGLTF_PTRINDEX(cgltf_texture, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "texCoord") == 0)
{
++i;
out_texture_view->texcoord = cgltf_json_to_int(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "scale") == 0)
{
++i;
out_texture_view->scale = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "strength") == 0)
{
++i;
out_texture_view->scale = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
{
++i;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int extensions_size = tokens[i].size;
++i;
for (int k = 0; k < extensions_size; ++k)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_texture_transform") == 0)
{
out_texture_view->has_transform = 1;
i = cgltf_parse_json_texture_transform(tokens, i + 1, json_chunk, &out_texture_view->transform);
}
else
{
i = cgltf_skip_json(tokens, i + 1);
}
if (i < 0)
{
return i;
}
}
}
else
{
i = cgltf_skip_json(tokens, i + 1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_pbr_metallic_roughness(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_pbr_metallic_roughness* out_pbr)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "metallicFactor") == 0)
{
++i;
out_pbr->metallic_factor =
cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "roughnessFactor") == 0)
{
++i;
out_pbr->roughness_factor =
cgltf_json_to_float(tokens+i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "baseColorFactor") == 0)
{
i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_pbr->base_color_factor, 4);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "baseColorTexture") == 0)
{
i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_pbr->base_color_texture);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "metallicRoughnessTexture") == 0)
{
i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_pbr->metallic_roughness_texture);
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_pbr_specular_glossiness(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_pbr_specular_glossiness* out_pbr)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "diffuseFactor") == 0)
{
i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_pbr->diffuse_factor, 4);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "specularFactor") == 0)
{
i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_pbr->specular_factor, 3);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "glossinessFactor") == 0)
{
++i;
out_pbr->glossiness_factor = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "diffuseTexture") == 0)
{
i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_pbr->diffuse_texture);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "specularGlossinessTexture") == 0)
{
i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_pbr->specular_glossiness_texture);
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_clearcoat(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_clearcoat* out_clearcoat)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "clearcoatFactor") == 0)
{
++i;
out_clearcoat->clearcoat_factor = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "clearcoatRoughnessFactor") == 0)
{
++i;
out_clearcoat->clearcoat_roughness_factor = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "clearcoatTexture") == 0)
{
i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_clearcoat->clearcoat_texture);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "clearcoatRoughnessTexture") == 0)
{
i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_clearcoat->clearcoat_roughness_texture);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "clearcoatNormalTexture") == 0)
{
i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_clearcoat->clearcoat_normal_texture);
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_ior(jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_ior* out_ior)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
// Default values
out_ior->ior = 1.5f;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "ior") == 0)
{
++i;
out_ior->ior = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_specular(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_specular* out_specular)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
// Default values
out_specular->specular_factor = 1.0f;
cgltf_fill_float_array(out_specular->specular_color_factor, 3, 1.0f);
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "specularFactor") == 0)
{
++i;
out_specular->specular_factor = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "specularColorFactor") == 0)
{
i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_specular->specular_color_factor, 3);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "specularTexture") == 0)
{
i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_specular->specular_texture);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "specularColorTexture") == 0)
{
i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_specular->specular_color_texture);
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_transmission(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_transmission* out_transmission)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "transmissionFactor") == 0)
{
++i;
out_transmission->transmission_factor = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "transmissionTexture") == 0)
{
i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_transmission->transmission_texture);
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_volume(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_volume* out_volume)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens + i, json_chunk, "thicknessFactor") == 0)
{
++i;
out_volume->thickness_factor = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "thicknessTexture") == 0)
{
i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_volume->thickness_texture);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "attenuationColor") == 0)
{
i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_volume->attenuation_color, 3);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "attenuationDistance") == 0)
{
++i;
out_volume->attenuation_distance = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else
{
i = cgltf_skip_json(tokens, i + 1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_sheen(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_sheen* out_sheen)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "sheenColorFactor") == 0)
{
i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_sheen->sheen_color_factor, 3);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "sheenColorTexture") == 0)
{
i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_sheen->sheen_color_texture);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "sheenRoughnessFactor") == 0)
{
++i;
out_sheen->sheen_roughness_factor = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "sheenRoughnessTexture") == 0)
{
i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_sheen->sheen_roughness_texture);
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_emissive_strength(jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_emissive_strength* out_emissive_strength)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
// Default
out_emissive_strength->emissive_strength = 1.f;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens + i, json_chunk, "emissiveStrength") == 0)
{
++i;
out_emissive_strength->emissive_strength = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else
{
i = cgltf_skip_json(tokens, i + 1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_iridescence(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_iridescence* out_iridescence)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
// Default
out_iridescence->iridescence_ior = 1.3f;
out_iridescence->iridescence_thickness_min = 100.f;
out_iridescence->iridescence_thickness_max = 400.f;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens + i, json_chunk, "iridescenceFactor") == 0)
{
++i;
out_iridescence->iridescence_factor = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "iridescenceTexture") == 0)
{
i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_iridescence->iridescence_texture);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "iridescenceIor") == 0)
{
++i;
out_iridescence->iridescence_ior = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "iridescenceThicknessMinimum") == 0)
{
++i;
out_iridescence->iridescence_thickness_min = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "iridescenceThicknessMaximum") == 0)
{
++i;
out_iridescence->iridescence_thickness_max = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "iridescenceThicknessTexture") == 0)
{
i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_iridescence->iridescence_thickness_texture);
}
else
{
i = cgltf_skip_json(tokens, i + 1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_diffuse_transmission(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_diffuse_transmission* out_diff_transmission)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
// Defaults
cgltf_fill_float_array(out_diff_transmission->diffuse_transmission_color_factor, 3, 1.0f);
out_diff_transmission->diffuse_transmission_factor = 0.f;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens + i, json_chunk, "diffuseTransmissionFactor") == 0)
{
++i;
out_diff_transmission->diffuse_transmission_factor = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "diffuseTransmissionTexture") == 0)
{
i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_diff_transmission->diffuse_transmission_texture);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "diffuseTransmissionColorFactor") == 0)
{
i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_diff_transmission->diffuse_transmission_color_factor, 3);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "diffuseTransmissionColorTexture") == 0)
{
i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_diff_transmission->diffuse_transmission_color_texture);
}
else
{
i = cgltf_skip_json(tokens, i + 1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_anisotropy(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_anisotropy* out_anisotropy)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens + i, json_chunk, "anisotropyStrength") == 0)
{
++i;
out_anisotropy->anisotropy_strength = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "anisotropyRotation") == 0)
{
++i;
out_anisotropy->anisotropy_rotation = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "anisotropyTexture") == 0)
{
i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_anisotropy->anisotropy_texture);
}
else
{
i = cgltf_skip_json(tokens, i + 1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_dispersion(jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_dispersion* out_dispersion)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens + i, json_chunk, "dispersion") == 0)
{
++i;
out_dispersion->dispersion = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else
{
i = cgltf_skip_json(tokens, i + 1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_image(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_image* out_image)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens + i, json_chunk, "uri") == 0)
{
i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_image->uri);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "bufferView") == 0)
{
++i;
out_image->buffer_view = CGLTF_PTRINDEX(cgltf_buffer_view, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "mimeType") == 0)
{
i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_image->mime_type);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "name") == 0)
{
i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_image->name);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
{
i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_image->extras);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
{
i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_image->extensions_count, &out_image->extensions);
}
else
{
i = cgltf_skip_json(tokens, i + 1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_sampler(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_sampler* out_sampler)
{
(void)options;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
out_sampler->wrap_s = cgltf_wrap_mode_repeat;
out_sampler->wrap_t = cgltf_wrap_mode_repeat;
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens + i, json_chunk, "name") == 0)
{
i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_sampler->name);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "magFilter") == 0)
{
++i;
out_sampler->mag_filter
= (cgltf_filter_type)cgltf_json_to_int(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "minFilter") == 0)
{
++i;
out_sampler->min_filter
= (cgltf_filter_type)cgltf_json_to_int(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "wrapS") == 0)
{
++i;
out_sampler->wrap_s
= (cgltf_wrap_mode)cgltf_json_to_int(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "wrapT") == 0)
{
++i;
out_sampler->wrap_t
= (cgltf_wrap_mode)cgltf_json_to_int(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
{
i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_sampler->extras);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
{
i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_sampler->extensions_count, &out_sampler->extensions);
}
else
{
i = cgltf_skip_json(tokens, i + 1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_texture(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_texture* out_texture)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0)
{
i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_texture->name);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "sampler") == 0)
{
++i;
out_texture->sampler = CGLTF_PTRINDEX(cgltf_sampler, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "source") == 0)
{
++i;
out_texture->image = CGLTF_PTRINDEX(cgltf_image, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
{
i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_texture->extras);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
{
++i;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
if (out_texture->extensions)
{
return CGLTF_ERROR_JSON;
}
int extensions_size = tokens[i].size;
++i;
out_texture->extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size);
out_texture->extensions_count = 0;
if (!out_texture->extensions)
{
return CGLTF_ERROR_NOMEM;
}
for (int k = 0; k < extensions_size; ++k)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens + i, json_chunk, "KHR_texture_basisu") == 0)
{
out_texture->has_basisu = 1;
++i;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int num_properties = tokens[i].size;
++i;
for (int t = 0; t < num_properties; ++t)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens + i, json_chunk, "source") == 0)
{
++i;
out_texture->basisu_image = CGLTF_PTRINDEX(cgltf_image, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
else
{
i = cgltf_skip_json(tokens, i + 1);
}
if (i < 0)
{
return i;
}
}
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "EXT_texture_webp") == 0)
{
out_texture->has_webp = 1;
++i;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int num_properties = tokens[i].size;
++i;
for (int t = 0; t < num_properties; ++t)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens + i, json_chunk, "source") == 0)
{
++i;
out_texture->webp_image = CGLTF_PTRINDEX(cgltf_image, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
else
{
i = cgltf_skip_json(tokens, i + 1);
}
if (i < 0)
{
return i;
}
}
}
else
{
i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_texture->extensions[out_texture->extensions_count++]));
}
if (i < 0)
{
return i;
}
}
}
else
{
i = cgltf_skip_json(tokens, i + 1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_material(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_material* out_material)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
cgltf_fill_float_array(out_material->pbr_metallic_roughness.base_color_factor, 4, 1.0f);
out_material->pbr_metallic_roughness.metallic_factor = 1.0f;
out_material->pbr_metallic_roughness.roughness_factor = 1.0f;
cgltf_fill_float_array(out_material->pbr_specular_glossiness.diffuse_factor, 4, 1.0f);
cgltf_fill_float_array(out_material->pbr_specular_glossiness.specular_factor, 3, 1.0f);
out_material->pbr_specular_glossiness.glossiness_factor = 1.0f;
cgltf_fill_float_array(out_material->volume.attenuation_color, 3, 1.0f);
out_material->volume.attenuation_distance = FLT_MAX;
out_material->alpha_cutoff = 0.5f;
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0)
{
i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_material->name);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "pbrMetallicRoughness") == 0)
{
out_material->has_pbr_metallic_roughness = 1;
i = cgltf_parse_json_pbr_metallic_roughness(options, tokens, i + 1, json_chunk, &out_material->pbr_metallic_roughness);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "emissiveFactor") == 0)
{
i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_material->emissive_factor, 3);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "normalTexture") == 0)
{
i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk,
&out_material->normal_texture);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "occlusionTexture") == 0)
{
i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk,
&out_material->occlusion_texture);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "emissiveTexture") == 0)
{
i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk,
&out_material->emissive_texture);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "alphaMode") == 0)
{
++i;
if (cgltf_json_strcmp(tokens + i, json_chunk, "OPAQUE") == 0)
{
out_material->alpha_mode = cgltf_alpha_mode_opaque;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "MASK") == 0)
{
out_material->alpha_mode = cgltf_alpha_mode_mask;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "BLEND") == 0)
{
out_material->alpha_mode = cgltf_alpha_mode_blend;
}
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "alphaCutoff") == 0)
{
++i;
out_material->alpha_cutoff = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "doubleSided") == 0)
{
++i;
out_material->double_sided =
cgltf_json_to_bool(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
{
i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_material->extras);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
{
++i;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
if(out_material->extensions)
{
return CGLTF_ERROR_JSON;
}
int extensions_size = tokens[i].size;
++i;
out_material->extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size);
out_material->extensions_count= 0;
if (!out_material->extensions)
{
return CGLTF_ERROR_NOMEM;
}
for (int k = 0; k < extensions_size; ++k)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_pbrSpecularGlossiness") == 0)
{
out_material->has_pbr_specular_glossiness = 1;
i = cgltf_parse_json_pbr_specular_glossiness(options, tokens, i + 1, json_chunk, &out_material->pbr_specular_glossiness);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_unlit") == 0)
{
out_material->unlit = 1;
i = cgltf_skip_json(tokens, i+1);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_clearcoat") == 0)
{
out_material->has_clearcoat = 1;
i = cgltf_parse_json_clearcoat(options, tokens, i + 1, json_chunk, &out_material->clearcoat);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_ior") == 0)
{
out_material->has_ior = 1;
i = cgltf_parse_json_ior(tokens, i + 1, json_chunk, &out_material->ior);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_specular") == 0)
{
out_material->has_specular = 1;
i = cgltf_parse_json_specular(options, tokens, i + 1, json_chunk, &out_material->specular);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_transmission") == 0)
{
out_material->has_transmission = 1;
i = cgltf_parse_json_transmission(options, tokens, i + 1, json_chunk, &out_material->transmission);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "KHR_materials_volume") == 0)
{
out_material->has_volume = 1;
i = cgltf_parse_json_volume(options, tokens, i + 1, json_chunk, &out_material->volume);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_sheen") == 0)
{
out_material->has_sheen = 1;
i = cgltf_parse_json_sheen(options, tokens, i + 1, json_chunk, &out_material->sheen);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "KHR_materials_emissive_strength") == 0)
{
out_material->has_emissive_strength = 1;
i = cgltf_parse_json_emissive_strength(tokens, i + 1, json_chunk, &out_material->emissive_strength);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "KHR_materials_iridescence") == 0)
{
out_material->has_iridescence = 1;
i = cgltf_parse_json_iridescence(options, tokens, i + 1, json_chunk, &out_material->iridescence);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "KHR_materials_diffuse_transmission") == 0)
{
out_material->has_diffuse_transmission = 1;
i = cgltf_parse_json_diffuse_transmission(options, tokens, i + 1, json_chunk, &out_material->diffuse_transmission);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "KHR_materials_anisotropy") == 0)
{
out_material->has_anisotropy = 1;
i = cgltf_parse_json_anisotropy(options, tokens, i + 1, json_chunk, &out_material->anisotropy);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "KHR_materials_dispersion") == 0)
{
out_material->has_dispersion = 1;
i = cgltf_parse_json_dispersion(tokens, i + 1, json_chunk, &out_material->dispersion);
}
else
{
i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_material->extensions[out_material->extensions_count++]));
}
if (i < 0)
{
return i;
}
}
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_accessors(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
{
i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_accessor), (void**)&out_data->accessors, &out_data->accessors_count);
if (i < 0)
{
return i;
}
for (cgltf_size j = 0; j < out_data->accessors_count; ++j)
{
i = cgltf_parse_json_accessor(options, tokens, i, json_chunk, &out_data->accessors[j]);
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_materials(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
{
i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_material), (void**)&out_data->materials, &out_data->materials_count);
if (i < 0)
{
return i;
}
for (cgltf_size j = 0; j < out_data->materials_count; ++j)
{
i = cgltf_parse_json_material(options, tokens, i, json_chunk, &out_data->materials[j]);
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_images(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
{
i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_image), (void**)&out_data->images, &out_data->images_count);
if (i < 0)
{
return i;
}
for (cgltf_size j = 0; j < out_data->images_count; ++j)
{
i = cgltf_parse_json_image(options, tokens, i, json_chunk, &out_data->images[j]);
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_textures(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
{
i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_texture), (void**)&out_data->textures, &out_data->textures_count);
if (i < 0)
{
return i;
}
for (cgltf_size j = 0; j < out_data->textures_count; ++j)
{
i = cgltf_parse_json_texture(options, tokens, i, json_chunk, &out_data->textures[j]);
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_samplers(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
{
i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_sampler), (void**)&out_data->samplers, &out_data->samplers_count);
if (i < 0)
{
return i;
}
for (cgltf_size j = 0; j < out_data->samplers_count; ++j)
{
i = cgltf_parse_json_sampler(options, tokens, i, json_chunk, &out_data->samplers[j]);
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_meshopt_compression(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_meshopt_compression* out_meshopt_compression)
{
(void)options;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "buffer") == 0)
{
++i;
out_meshopt_compression->buffer = CGLTF_PTRINDEX(cgltf_buffer, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteOffset") == 0)
{
++i;
out_meshopt_compression->offset = cgltf_json_to_size(tokens+i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteLength") == 0)
{
++i;
out_meshopt_compression->size = cgltf_json_to_size(tokens+i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteStride") == 0)
{
++i;
out_meshopt_compression->stride = cgltf_json_to_size(tokens+i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "count") == 0)
{
++i;
out_meshopt_compression->count = cgltf_json_to_size(tokens+i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "mode") == 0)
{
++i;
if (cgltf_json_strcmp(tokens+i, json_chunk, "ATTRIBUTES") == 0)
{
out_meshopt_compression->mode = cgltf_meshopt_compression_mode_attributes;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "TRIANGLES") == 0)
{
out_meshopt_compression->mode = cgltf_meshopt_compression_mode_triangles;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "INDICES") == 0)
{
out_meshopt_compression->mode = cgltf_meshopt_compression_mode_indices;
}
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "filter") == 0)
{
++i;
if (cgltf_json_strcmp(tokens+i, json_chunk, "NONE") == 0)
{
out_meshopt_compression->filter = cgltf_meshopt_compression_filter_none;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "OCTAHEDRAL") == 0)
{
out_meshopt_compression->filter = cgltf_meshopt_compression_filter_octahedral;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "QUATERNION") == 0)
{
out_meshopt_compression->filter = cgltf_meshopt_compression_filter_quaternion;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "EXPONENTIAL") == 0)
{
out_meshopt_compression->filter = cgltf_meshopt_compression_filter_exponential;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "COLOR") == 0)
{
out_meshopt_compression->filter = cgltf_meshopt_compression_filter_color;
}
++i;
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_buffer_view(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_buffer_view* out_buffer_view)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens + i, json_chunk, "name") == 0)
{
i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_buffer_view->name);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "buffer") == 0)
{
++i;
out_buffer_view->buffer = CGLTF_PTRINDEX(cgltf_buffer, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteOffset") == 0)
{
++i;
out_buffer_view->offset =
cgltf_json_to_size(tokens+i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteLength") == 0)
{
++i;
out_buffer_view->size =
cgltf_json_to_size(tokens+i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteStride") == 0)
{
++i;
out_buffer_view->stride =
cgltf_json_to_size(tokens+i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "target") == 0)
{
++i;
int type = cgltf_json_to_int(tokens+i, json_chunk);
switch (type)
{
case 34962:
type = cgltf_buffer_view_type_vertices;
break;
case 34963:
type = cgltf_buffer_view_type_indices;
break;
default:
type = cgltf_buffer_view_type_invalid;
break;
}
out_buffer_view->type = (cgltf_buffer_view_type)type;
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
{
i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_buffer_view->extras);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
{
++i;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
if(out_buffer_view->extensions)
{
return CGLTF_ERROR_JSON;
}
int extensions_size = tokens[i].size;
out_buffer_view->extensions_count = 0;
out_buffer_view->extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size);
if (!out_buffer_view->extensions)
{
return CGLTF_ERROR_NOMEM;
}
++i;
for (int k = 0; k < extensions_size; ++k)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "EXT_meshopt_compression") == 0)
{
out_buffer_view->has_meshopt_compression = 1;
i = cgltf_parse_json_meshopt_compression(options, tokens, i + 1, json_chunk, &out_buffer_view->meshopt_compression);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_meshopt_compression") == 0)
{
out_buffer_view->has_meshopt_compression = 1;
out_buffer_view->meshopt_compression.is_khr = 1;
i = cgltf_parse_json_meshopt_compression(options, tokens, i + 1, json_chunk, &out_buffer_view->meshopt_compression);
}
else
{
i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_buffer_view->extensions[out_buffer_view->extensions_count++]));
}
if (i < 0)
{
return i;
}
}
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_buffer_views(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
{
i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_buffer_view), (void**)&out_data->buffer_views, &out_data->buffer_views_count);
if (i < 0)
{
return i;
}
for (cgltf_size j = 0; j < out_data->buffer_views_count; ++j)
{
i = cgltf_parse_json_buffer_view(options, tokens, i, json_chunk, &out_data->buffer_views[j]);
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_buffer(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_buffer* out_buffer)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens + i, json_chunk, "name") == 0)
{
i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_buffer->name);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteLength") == 0)
{
++i;
out_buffer->size =
cgltf_json_to_size(tokens+i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "uri") == 0)
{
i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_buffer->uri);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
{
i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_buffer->extras);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
{
i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_buffer->extensions_count, &out_buffer->extensions);
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_buffers(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
{
i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_buffer), (void**)&out_data->buffers, &out_data->buffers_count);
if (i < 0)
{
return i;
}
for (cgltf_size j = 0; j < out_data->buffers_count; ++j)
{
i = cgltf_parse_json_buffer(options, tokens, i, json_chunk, &out_data->buffers[j]);
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_skin(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_skin* out_skin)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0)
{
i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_skin->name);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "joints") == 0)
{
i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_node*), (void**)&out_skin->joints, &out_skin->joints_count);
if (i < 0)
{
return i;
}
for (cgltf_size k = 0; k < out_skin->joints_count; ++k)
{
out_skin->joints[k] = CGLTF_PTRINDEX(cgltf_node, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "skeleton") == 0)
{
++i;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE);
out_skin->skeleton = CGLTF_PTRINDEX(cgltf_node, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "inverseBindMatrices") == 0)
{
++i;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE);
out_skin->inverse_bind_matrices = CGLTF_PTRINDEX(cgltf_accessor, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
{
i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_skin->extras);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
{
i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_skin->extensions_count, &out_skin->extensions);
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_skins(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
{
i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_skin), (void**)&out_data->skins, &out_data->skins_count);
if (i < 0)
{
return i;
}
for (cgltf_size j = 0; j < out_data->skins_count; ++j)
{
i = cgltf_parse_json_skin(options, tokens, i, json_chunk, &out_data->skins[j]);
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_camera(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_camera* out_camera)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0)
{
i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_camera->name);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "perspective") == 0)
{
++i;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int data_size = tokens[i].size;
++i;
if (out_camera->type != cgltf_camera_type_invalid)
{
return CGLTF_ERROR_JSON;
}
out_camera->type = cgltf_camera_type_perspective;
for (int k = 0; k < data_size; ++k)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "aspectRatio") == 0)
{
++i;
out_camera->data.perspective.has_aspect_ratio = 1;
out_camera->data.perspective.aspect_ratio = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "yfov") == 0)
{
++i;
out_camera->data.perspective.yfov = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "zfar") == 0)
{
++i;
out_camera->data.perspective.has_zfar = 1;
out_camera->data.perspective.zfar = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "znear") == 0)
{
++i;
out_camera->data.perspective.znear = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
{
i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_camera->data.perspective.extras);
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "orthographic") == 0)
{
++i;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int data_size = tokens[i].size;
++i;
if (out_camera->type != cgltf_camera_type_invalid)
{
return CGLTF_ERROR_JSON;
}
out_camera->type = cgltf_camera_type_orthographic;
for (int k = 0; k < data_size; ++k)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "xmag") == 0)
{
++i;
out_camera->data.orthographic.xmag = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "ymag") == 0)
{
++i;
out_camera->data.orthographic.ymag = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "zfar") == 0)
{
++i;
out_camera->data.orthographic.zfar = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "znear") == 0)
{
++i;
out_camera->data.orthographic.znear = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
{
i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_camera->data.orthographic.extras);
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
{
i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_camera->extras);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
{
i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_camera->extensions_count, &out_camera->extensions);
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_cameras(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
{
i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_camera), (void**)&out_data->cameras, &out_data->cameras_count);
if (i < 0)
{
return i;
}
for (cgltf_size j = 0; j < out_data->cameras_count; ++j)
{
i = cgltf_parse_json_camera(options, tokens, i, json_chunk, &out_data->cameras[j]);
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_light(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_light* out_light)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
out_light->color[0] = 1.f;
out_light->color[1] = 1.f;
out_light->color[2] = 1.f;
out_light->intensity = 1.f;
out_light->spot_inner_cone_angle = 0.f;
out_light->spot_outer_cone_angle = 3.1415926535f / 4.0f;
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0)
{
i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_light->name);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "color") == 0)
{
i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_light->color, 3);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "intensity") == 0)
{
++i;
out_light->intensity = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "type") == 0)
{
++i;
if (cgltf_json_strcmp(tokens + i, json_chunk, "directional") == 0)
{
out_light->type = cgltf_light_type_directional;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "point") == 0)
{
out_light->type = cgltf_light_type_point;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "spot") == 0)
{
out_light->type = cgltf_light_type_spot;
}
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "range") == 0)
{
++i;
out_light->range = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "spot") == 0)
{
++i;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int data_size = tokens[i].size;
++i;
for (int k = 0; k < data_size; ++k)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "innerConeAngle") == 0)
{
++i;
out_light->spot_inner_cone_angle = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "outerConeAngle") == 0)
{
++i;
out_light->spot_outer_cone_angle = cgltf_json_to_float(tokens + i, json_chunk);
++i;
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
{
i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_light->extras);
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_lights(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
{
i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_light), (void**)&out_data->lights, &out_data->lights_count);
if (i < 0)
{
return i;
}
for (cgltf_size j = 0; j < out_data->lights_count; ++j)
{
i = cgltf_parse_json_light(options, tokens, i, json_chunk, &out_data->lights[j]);
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_node(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_node* out_node)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
out_node->rotation[3] = 1.0f;
out_node->scale[0] = 1.0f;
out_node->scale[1] = 1.0f;
out_node->scale[2] = 1.0f;
out_node->matrix[0] = 1.0f;
out_node->matrix[5] = 1.0f;
out_node->matrix[10] = 1.0f;
out_node->matrix[15] = 1.0f;
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0)
{
i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_node->name);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "children") == 0)
{
i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_node*), (void**)&out_node->children, &out_node->children_count);
if (i < 0)
{
return i;
}
for (cgltf_size k = 0; k < out_node->children_count; ++k)
{
out_node->children[k] = CGLTF_PTRINDEX(cgltf_node, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "mesh") == 0)
{
++i;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE);
out_node->mesh = CGLTF_PTRINDEX(cgltf_mesh, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "skin") == 0)
{
++i;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE);
out_node->skin = CGLTF_PTRINDEX(cgltf_skin, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "camera") == 0)
{
++i;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE);
out_node->camera = CGLTF_PTRINDEX(cgltf_camera, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "translation") == 0)
{
out_node->has_translation = 1;
i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_node->translation, 3);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "rotation") == 0)
{
out_node->has_rotation = 1;
i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_node->rotation, 4);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "scale") == 0)
{
out_node->has_scale = 1;
i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_node->scale, 3);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "matrix") == 0)
{
out_node->has_matrix = 1;
i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_node->matrix, 16);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "weights") == 0)
{
i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_float), (void**)&out_node->weights, &out_node->weights_count);
if (i < 0)
{
return i;
}
i = cgltf_parse_json_float_array(tokens, i - 1, json_chunk, out_node->weights, (int)out_node->weights_count);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
{
i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_node->extras);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
{
++i;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
if(out_node->extensions)
{
return CGLTF_ERROR_JSON;
}
int extensions_size = tokens[i].size;
out_node->extensions_count= 0;
out_node->extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size);
if (!out_node->extensions)
{
return CGLTF_ERROR_NOMEM;
}
++i;
for (int k = 0; k < extensions_size; ++k)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_lights_punctual") == 0)
{
++i;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int data_size = tokens[i].size;
++i;
for (int m = 0; m < data_size; ++m)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens + i, json_chunk, "light") == 0)
{
++i;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE);
out_node->light = CGLTF_PTRINDEX(cgltf_light, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
else
{
i = cgltf_skip_json(tokens, i + 1);
}
if (i < 0)
{
return i;
}
}
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "EXT_mesh_gpu_instancing") == 0)
{
out_node->has_mesh_gpu_instancing = 1;
i = cgltf_parse_json_mesh_gpu_instancing(options, tokens, i + 1, json_chunk, &out_node->mesh_gpu_instancing);
}
else
{
i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_node->extensions[out_node->extensions_count++]));
}
if (i < 0)
{
return i;
}
}
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_nodes(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
{
i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_node), (void**)&out_data->nodes, &out_data->nodes_count);
if (i < 0)
{
return i;
}
for (cgltf_size j = 0; j < out_data->nodes_count; ++j)
{
i = cgltf_parse_json_node(options, tokens, i, json_chunk, &out_data->nodes[j]);
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_scene(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_scene* out_scene)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0)
{
i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_scene->name);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "nodes") == 0)
{
i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_node*), (void**)&out_scene->nodes, &out_scene->nodes_count);
if (i < 0)
{
return i;
}
for (cgltf_size k = 0; k < out_scene->nodes_count; ++k)
{
out_scene->nodes[k] = CGLTF_PTRINDEX(cgltf_node, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
{
i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_scene->extras);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
{
i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_scene->extensions_count, &out_scene->extensions);
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_scenes(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
{
i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_scene), (void**)&out_data->scenes, &out_data->scenes_count);
if (i < 0)
{
return i;
}
for (cgltf_size j = 0; j < out_data->scenes_count; ++j)
{
i = cgltf_parse_json_scene(options, tokens, i, json_chunk, &out_data->scenes[j]);
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_animation_sampler(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_animation_sampler* out_sampler)
{
(void)options;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "input") == 0)
{
++i;
out_sampler->input = CGLTF_PTRINDEX(cgltf_accessor, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "output") == 0)
{
++i;
out_sampler->output = CGLTF_PTRINDEX(cgltf_accessor, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "interpolation") == 0)
{
++i;
if (cgltf_json_strcmp(tokens + i, json_chunk, "LINEAR") == 0)
{
out_sampler->interpolation = cgltf_interpolation_type_linear;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "STEP") == 0)
{
out_sampler->interpolation = cgltf_interpolation_type_step;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "CUBICSPLINE") == 0)
{
out_sampler->interpolation = cgltf_interpolation_type_cubic_spline;
}
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
{
i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_sampler->extras);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
{
i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_sampler->extensions_count, &out_sampler->extensions);
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_animation_channel(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_animation_channel* out_channel)
{
(void)options;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "sampler") == 0)
{
++i;
out_channel->sampler = CGLTF_PTRINDEX(cgltf_animation_sampler, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "target") == 0)
{
++i;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int target_size = tokens[i].size;
++i;
for (int k = 0; k < target_size; ++k)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "node") == 0)
{
++i;
out_channel->target_node = CGLTF_PTRINDEX(cgltf_node, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "path") == 0)
{
++i;
if (cgltf_json_strcmp(tokens+i, json_chunk, "translation") == 0)
{
out_channel->target_path = cgltf_animation_path_type_translation;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "rotation") == 0)
{
out_channel->target_path = cgltf_animation_path_type_rotation;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "scale") == 0)
{
out_channel->target_path = cgltf_animation_path_type_scale;
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "weights") == 0)
{
out_channel->target_path = cgltf_animation_path_type_weights;
}
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
{
i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_channel->extras);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
{
i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_channel->extensions_count, &out_channel->extensions);
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_animation(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_animation* out_animation)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0)
{
i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_animation->name);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "samplers") == 0)
{
i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_animation_sampler), (void**)&out_animation->samplers, &out_animation->samplers_count);
if (i < 0)
{
return i;
}
for (cgltf_size k = 0; k < out_animation->samplers_count; ++k)
{
i = cgltf_parse_json_animation_sampler(options, tokens, i, json_chunk, &out_animation->samplers[k]);
if (i < 0)
{
return i;
}
}
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "channels") == 0)
{
i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_animation_channel), (void**)&out_animation->channels, &out_animation->channels_count);
if (i < 0)
{
return i;
}
for (cgltf_size k = 0; k < out_animation->channels_count; ++k)
{
i = cgltf_parse_json_animation_channel(options, tokens, i, json_chunk, &out_animation->channels[k]);
if (i < 0)
{
return i;
}
}
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
{
i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_animation->extras);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
{
i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_animation->extensions_count, &out_animation->extensions);
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_animations(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
{
i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_animation), (void**)&out_data->animations, &out_data->animations_count);
if (i < 0)
{
return i;
}
for (cgltf_size j = 0; j < out_data->animations_count; ++j)
{
i = cgltf_parse_json_animation(options, tokens, i, json_chunk, &out_data->animations[j]);
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_variant(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_material_variant* out_variant)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0)
{
i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_variant->name);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
{
i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_variant->extras);
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_variants(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
{
i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_material_variant), (void**)&out_data->variants, &out_data->variants_count);
if (i < 0)
{
return i;
}
for (cgltf_size j = 0; j < out_data->variants_count; ++j)
{
i = cgltf_parse_json_variant(options, tokens, i, json_chunk, &out_data->variants[j]);
if (i < 0)
{
return i;
}
}
return i;
}
static int cgltf_parse_json_asset(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_asset* out_asset)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "copyright") == 0)
{
i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_asset->copyright);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "generator") == 0)
{
i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_asset->generator);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "version") == 0)
{
i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_asset->version);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "minVersion") == 0)
{
i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_asset->min_version);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0)
{
i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_asset->extras);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
{
i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_asset->extensions_count, &out_asset->extensions);
}
else
{
i = cgltf_skip_json(tokens, i+1);
}
if (i < 0)
{
return i;
}
}
if (out_asset->version && CGLTF_ATOF(out_asset->version) < 2)
{
return CGLTF_ERROR_LEGACY;
}
return i;
}
cgltf_size cgltf_num_components(cgltf_type type) {
switch (type)
{
case cgltf_type_vec2:
return 2;
case cgltf_type_vec3:
return 3;
case cgltf_type_vec4:
return 4;
case cgltf_type_mat2:
return 4;
case cgltf_type_mat3:
return 9;
case cgltf_type_mat4:
return 16;
case cgltf_type_invalid:
case cgltf_type_scalar:
default:
return 1;
}
}
cgltf_size cgltf_component_size(cgltf_component_type component_type) {
switch (component_type)
{
case cgltf_component_type_r_8:
case cgltf_component_type_r_8u:
return 1;
case cgltf_component_type_r_16:
case cgltf_component_type_r_16u:
return 2;
case cgltf_component_type_r_32u:
case cgltf_component_type_r_32f:
return 4;
case cgltf_component_type_invalid:
default:
return 0;
}
}
cgltf_size cgltf_calc_size(cgltf_type type, cgltf_component_type component_type)
{
cgltf_size component_size = cgltf_component_size(component_type);
if (type == cgltf_type_mat2 && component_size == 1)
{
return 8 * component_size;
}
else if (type == cgltf_type_mat3 && (component_size == 1 || component_size == 2))
{
return 12 * component_size;
}
return component_size * cgltf_num_components(type);
}
static int cgltf_fixup_pointers(cgltf_data* out_data);
static int cgltf_parse_json_root(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data)
{
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int size = tokens[i].size;
++i;
for (int j = 0; j < size; ++j)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens + i, json_chunk, "asset") == 0)
{
i = cgltf_parse_json_asset(options, tokens, i + 1, json_chunk, &out_data->asset);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "meshes") == 0)
{
i = cgltf_parse_json_meshes(options, tokens, i + 1, json_chunk, out_data);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "accessors") == 0)
{
i = cgltf_parse_json_accessors(options, tokens, i + 1, json_chunk, out_data);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "bufferViews") == 0)
{
i = cgltf_parse_json_buffer_views(options, tokens, i + 1, json_chunk, out_data);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "buffers") == 0)
{
i = cgltf_parse_json_buffers(options, tokens, i + 1, json_chunk, out_data);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "materials") == 0)
{
i = cgltf_parse_json_materials(options, tokens, i + 1, json_chunk, out_data);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "images") == 0)
{
i = cgltf_parse_json_images(options, tokens, i + 1, json_chunk, out_data);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "textures") == 0)
{
i = cgltf_parse_json_textures(options, tokens, i + 1, json_chunk, out_data);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "samplers") == 0)
{
i = cgltf_parse_json_samplers(options, tokens, i + 1, json_chunk, out_data);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "skins") == 0)
{
i = cgltf_parse_json_skins(options, tokens, i + 1, json_chunk, out_data);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "cameras") == 0)
{
i = cgltf_parse_json_cameras(options, tokens, i + 1, json_chunk, out_data);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "nodes") == 0)
{
i = cgltf_parse_json_nodes(options, tokens, i + 1, json_chunk, out_data);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "scenes") == 0)
{
i = cgltf_parse_json_scenes(options, tokens, i + 1, json_chunk, out_data);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "scene") == 0)
{
++i;
out_data->scene = CGLTF_PTRINDEX(cgltf_scene, cgltf_json_to_int(tokens + i, json_chunk));
++i;
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "animations") == 0)
{
i = cgltf_parse_json_animations(options, tokens, i + 1, json_chunk, out_data);
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "extras") == 0)
{
i = cgltf_parse_json_extras(options, tokens, i + 1, json_chunk, &out_data->extras);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0)
{
++i;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
if(out_data->data_extensions)
{
return CGLTF_ERROR_JSON;
}
int extensions_size = tokens[i].size;
out_data->data_extensions_count = 0;
out_data->data_extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size);
if (!out_data->data_extensions)
{
return CGLTF_ERROR_NOMEM;
}
++i;
for (int k = 0; k < extensions_size; ++k)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_lights_punctual") == 0)
{
++i;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int data_size = tokens[i].size;
++i;
for (int m = 0; m < data_size; ++m)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens + i, json_chunk, "lights") == 0)
{
i = cgltf_parse_json_lights(options, tokens, i + 1, json_chunk, out_data);
}
else
{
i = cgltf_skip_json(tokens, i + 1);
}
if (i < 0)
{
return i;
}
}
}
else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_variants") == 0)
{
++i;
CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT);
int data_size = tokens[i].size;
++i;
for (int m = 0; m < data_size; ++m)
{
CGLTF_CHECK_KEY(tokens[i]);
if (cgltf_json_strcmp(tokens + i, json_chunk, "variants") == 0)
{
i = cgltf_parse_json_variants(options, tokens, i + 1, json_chunk, out_data);
}
else
{
i = cgltf_skip_json(tokens, i + 1);
}
if (i < 0)
{
return i;
}
}
}
else
{
i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_data->data_extensions[out_data->data_extensions_count++]));
}
if (i < 0)
{
return i;
}
}
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensionsUsed") == 0)
{
i = cgltf_parse_json_string_array(options, tokens, i + 1, json_chunk, &out_data->extensions_used, &out_data->extensions_used_count);
}
else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensionsRequired") == 0)
{
i = cgltf_parse_json_string_array(options, tokens, i + 1, json_chunk, &out_data->extensions_required, &out_data->extensions_required_count);
}
else
{
i = cgltf_skip_json(tokens, i + 1);
}
if (i < 0)
{
return i;
}
}
return i;
}
cgltf_result cgltf_parse_json(cgltf_options* options, const uint8_t* json_chunk, cgltf_size size, cgltf_data** out_data)
{
jsmn_parser parser = { 0, 0, 0 };
if (options->json_token_count == 0)
{
int token_count = jsmn_parse(&parser, (const char*)json_chunk, size, NULL, 0);
if (token_count <= 0)
{
return cgltf_result_invalid_json;
}
options->json_token_count = token_count;
}
jsmntok_t* tokens = (jsmntok_t*)options->memory.alloc_func(options->memory.user_data, sizeof(jsmntok_t) * (options->json_token_count + 1));
if (!tokens)
{
return cgltf_result_out_of_memory;
}
jsmn_init(&parser);
int token_count = jsmn_parse(&parser, (const char*)json_chunk, size, tokens, options->json_token_count);
if (token_count <= 0)
{
options->memory.free_func(options->memory.user_data, tokens);
return cgltf_result_invalid_json;
}
// this makes sure that we always have an UNDEFINED token at the end of the stream
// for invalid JSON inputs this makes sure we don't perform out of bound reads of token data
tokens[token_count].type = JSMN_UNDEFINED;
cgltf_data* data = (cgltf_data*)options->memory.alloc_func(options->memory.user_data, sizeof(cgltf_data));
if (!data)
{
options->memory.free_func(options->memory.user_data, tokens);
return cgltf_result_out_of_memory;
}
memset(data, 0, sizeof(cgltf_data));
data->memory = options->memory;
data->file = options->file;
int i = cgltf_parse_json_root(options, tokens, 0, json_chunk, data);
options->memory.free_func(options->memory.user_data, tokens);
if (i < 0)
{
cgltf_free(data);
switch (i)
{
case CGLTF_ERROR_NOMEM: return cgltf_result_out_of_memory;
case CGLTF_ERROR_LEGACY: return cgltf_result_legacy_gltf;
default: return cgltf_result_invalid_gltf;
}
}
if (cgltf_fixup_pointers(data) < 0)
{
cgltf_free(data);
return cgltf_result_invalid_gltf;
}
data->json = (const char*)json_chunk;
data->json_size = size;
*out_data = data;
return cgltf_result_success;
}
static int cgltf_fixup_pointers(cgltf_data* data)
{
for (cgltf_size i = 0; i < data->meshes_count; ++i)
{
for (cgltf_size j = 0; j < data->meshes[i].primitives_count; ++j)
{
CGLTF_PTRFIXUP(data->meshes[i].primitives[j].indices, data->accessors, data->accessors_count);
CGLTF_PTRFIXUP(data->meshes[i].primitives[j].material, data->materials, data->materials_count);
for (cgltf_size k = 0; k < data->meshes[i].primitives[j].attributes_count; ++k)
{
CGLTF_PTRFIXUP_REQ(data->meshes[i].primitives[j].attributes[k].data, data->accessors, data->accessors_count);
}
for (cgltf_size k = 0; k < data->meshes[i].primitives[j].targets_count; ++k)
{
for (cgltf_size m = 0; m < data->meshes[i].primitives[j].targets[k].attributes_count; ++m)
{
CGLTF_PTRFIXUP_REQ(data->meshes[i].primitives[j].targets[k].attributes[m].data, data->accessors, data->accessors_count);
}
}
if (data->meshes[i].primitives[j].has_draco_mesh_compression)
{
CGLTF_PTRFIXUP_REQ(data->meshes[i].primitives[j].draco_mesh_compression.buffer_view, data->buffer_views, data->buffer_views_count);
for (cgltf_size m = 0; m < data->meshes[i].primitives[j].draco_mesh_compression.attributes_count; ++m)
{
CGLTF_PTRFIXUP_REQ(data->meshes[i].primitives[j].draco_mesh_compression.attributes[m].data, data->accessors, data->accessors_count);
}
}
for (cgltf_size k = 0; k < data->meshes[i].primitives[j].mappings_count; ++k)
{
CGLTF_PTRFIXUP_REQ(data->meshes[i].primitives[j].mappings[k].material, data->materials, data->materials_count);
}
}
}
for (cgltf_size i = 0; i < data->accessors_count; ++i)
{
CGLTF_PTRFIXUP(data->accessors[i].buffer_view, data->buffer_views, data->buffer_views_count);
if (data->accessors[i].is_sparse)
{
CGLTF_PTRFIXUP_REQ(data->accessors[i].sparse.indices_buffer_view, data->buffer_views, data->buffer_views_count);
CGLTF_PTRFIXUP_REQ(data->accessors[i].sparse.values_buffer_view, data->buffer_views, data->buffer_views_count);
}
if (data->accessors[i].buffer_view)
{
data->accessors[i].stride = data->accessors[i].buffer_view->stride;
}
if (data->accessors[i].stride == 0)
{
data->accessors[i].stride = cgltf_calc_size(data->accessors[i].type, data->accessors[i].component_type);
}
}
for (cgltf_size i = 0; i < data->textures_count; ++i)
{
CGLTF_PTRFIXUP(data->textures[i].image, data->images, data->images_count);
CGLTF_PTRFIXUP(data->textures[i].basisu_image, data->images, data->images_count);
CGLTF_PTRFIXUP(data->textures[i].webp_image, data->images, data->images_count);
CGLTF_PTRFIXUP(data->textures[i].sampler, data->samplers, data->samplers_count);
}
for (cgltf_size i = 0; i < data->images_count; ++i)
{
CGLTF_PTRFIXUP(data->images[i].buffer_view, data->buffer_views, data->buffer_views_count);
}
for (cgltf_size i = 0; i < data->materials_count; ++i)
{
CGLTF_PTRFIXUP(data->materials[i].normal_texture.texture, data->textures, data->textures_count);
CGLTF_PTRFIXUP(data->materials[i].emissive_texture.texture, data->textures, data->textures_count);
CGLTF_PTRFIXUP(data->materials[i].occlusion_texture.texture, data->textures, data->textures_count);
CGLTF_PTRFIXUP(data->materials[i].pbr_metallic_roughness.base_color_texture.texture, data->textures, data->textures_count);
CGLTF_PTRFIXUP(data->materials[i].pbr_metallic_roughness.metallic_roughness_texture.texture, data->textures, data->textures_count);
CGLTF_PTRFIXUP(data->materials[i].pbr_specular_glossiness.diffuse_texture.texture, data->textures, data->textures_count);
CGLTF_PTRFIXUP(data->materials[i].pbr_specular_glossiness.specular_glossiness_texture.texture, data->textures, data->textures_count);
CGLTF_PTRFIXUP(data->materials[i].clearcoat.clearcoat_texture.texture, data->textures, data->textures_count);
CGLTF_PTRFIXUP(data->materials[i].clearcoat.clearcoat_roughness_texture.texture, data->textures, data->textures_count);
CGLTF_PTRFIXUP(data->materials[i].clearcoat.clearcoat_normal_texture.texture, data->textures, data->textures_count);
CGLTF_PTRFIXUP(data->materials[i].specular.specular_texture.texture, data->textures, data->textures_count);
CGLTF_PTRFIXUP(data->materials[i].specular.specular_color_texture.texture, data->textures, data->textures_count);
CGLTF_PTRFIXUP(data->materials[i].transmission.transmission_texture.texture, data->textures, data->textures_count);
CGLTF_PTRFIXUP(data->materials[i].volume.thickness_texture.texture, data->textures, data->textures_count);
CGLTF_PTRFIXUP(data->materials[i].sheen.sheen_color_texture.texture, data->textures, data->textures_count);
CGLTF_PTRFIXUP(data->materials[i].sheen.sheen_roughness_texture.texture, data->textures, data->textures_count);
CGLTF_PTRFIXUP(data->materials[i].iridescence.iridescence_texture.texture, data->textures, data->textures_count);
CGLTF_PTRFIXUP(data->materials[i].iridescence.iridescence_thickness_texture.texture, data->textures, data->textures_count);
CGLTF_PTRFIXUP(data->materials[i].diffuse_transmission.diffuse_transmission_texture.texture, data->textures, data->textures_count);
CGLTF_PTRFIXUP(data->materials[i].diffuse_transmission.diffuse_transmission_color_texture.texture, data->textures, data->textures_count);
CGLTF_PTRFIXUP(data->materials[i].anisotropy.anisotropy_texture.texture, data->textures, data->textures_count);
}
for (cgltf_size i = 0; i < data->buffer_views_count; ++i)
{
CGLTF_PTRFIXUP_REQ(data->buffer_views[i].buffer, data->buffers, data->buffers_count);
if (data->buffer_views[i].has_meshopt_compression)
{
CGLTF_PTRFIXUP_REQ(data->buffer_views[i].meshopt_compression.buffer, data->buffers, data->buffers_count);
}
}
for (cgltf_size i = 0; i < data->skins_count; ++i)
{
for (cgltf_size j = 0; j < data->skins[i].joints_count; ++j)
{
CGLTF_PTRFIXUP_REQ(data->skins[i].joints[j], data->nodes, data->nodes_count);
}
CGLTF_PTRFIXUP(data->skins[i].skeleton, data->nodes, data->nodes_count);
CGLTF_PTRFIXUP(data->skins[i].inverse_bind_matrices, data->accessors, data->accessors_count);
}
for (cgltf_size i = 0; i < data->nodes_count; ++i)
{
for (cgltf_size j = 0; j < data->nodes[i].children_count; ++j)
{
CGLTF_PTRFIXUP_REQ(data->nodes[i].children[j], data->nodes, data->nodes_count);
if (data->nodes[i].children[j]->parent)
{
return CGLTF_ERROR_JSON;
}
data->nodes[i].children[j]->parent = &data->nodes[i];
}
CGLTF_PTRFIXUP(data->nodes[i].mesh, data->meshes, data->meshes_count);
CGLTF_PTRFIXUP(data->nodes[i].skin, data->skins, data->skins_count);
CGLTF_PTRFIXUP(data->nodes[i].camera, data->cameras, data->cameras_count);
CGLTF_PTRFIXUP(data->nodes[i].light, data->lights, data->lights_count);
if (data->nodes[i].has_mesh_gpu_instancing)
{
for (cgltf_size m = 0; m < data->nodes[i].mesh_gpu_instancing.attributes_count; ++m)
{
CGLTF_PTRFIXUP_REQ(data->nodes[i].mesh_gpu_instancing.attributes[m].data, data->accessors, data->accessors_count);
}
}
}
for (cgltf_size i = 0; i < data->scenes_count; ++i)
{
for (cgltf_size j = 0; j < data->scenes[i].nodes_count; ++j)
{
CGLTF_PTRFIXUP_REQ(data->scenes[i].nodes[j], data->nodes, data->nodes_count);
if (data->scenes[i].nodes[j]->parent)
{
return CGLTF_ERROR_JSON;
}
}
}
CGLTF_PTRFIXUP(data->scene, data->scenes, data->scenes_count);
for (cgltf_size i = 0; i < data->animations_count; ++i)
{
for (cgltf_size j = 0; j < data->animations[i].samplers_count; ++j)
{
CGLTF_PTRFIXUP_REQ(data->animations[i].samplers[j].input, data->accessors, data->accessors_count);
CGLTF_PTRFIXUP_REQ(data->animations[i].samplers[j].output, data->accessors, data->accessors_count);
}
for (cgltf_size j = 0; j < data->animations[i].channels_count; ++j)
{
CGLTF_PTRFIXUP_REQ(data->animations[i].channels[j].sampler, data->animations[i].samplers, data->animations[i].samplers_count);
CGLTF_PTRFIXUP(data->animations[i].channels[j].target_node, data->nodes, data->nodes_count);
}
}
return 0;
}
/*
* -- jsmn.c start --
* Source: https://github.com/zserge/jsmn
* License: MIT
*
* Copyright (c) 2010 Serge A. Zaitsev
* 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.
*/
/**
* Allocates a fresh unused token from the token pull.
*/
static jsmntok_t *jsmn_alloc_token(jsmn_parser *parser,
jsmntok_t *tokens, size_t num_tokens) {
jsmntok_t *tok;
if (parser->toknext >= num_tokens) {
return NULL;
}
tok = &tokens[parser->toknext++];
tok->start = tok->end = -1;
tok->size = 0;
#ifdef JSMN_PARENT_LINKS
tok->parent = -1;
#endif
return tok;
}
/**
* Fills token type and boundaries.
*/
static void jsmn_fill_token(jsmntok_t *token, jsmntype_t type,
ptrdiff_t start, ptrdiff_t end) {
token->type = type;
token->start = start;
token->end = end;
token->size = 0;
}
/**
* Fills next available token with JSON primitive.
*/
static int jsmn_parse_primitive(jsmn_parser *parser, const char *js,
size_t len, jsmntok_t *tokens, size_t num_tokens) {
jsmntok_t *token;
ptrdiff_t start;
start = parser->pos;
for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
switch (js[parser->pos]) {
#ifndef JSMN_STRICT
/* In strict mode primitive must be followed by "," or "}" or "]" */
case ':':
#endif
case '\t' : case '\r' : case '\n' : case ' ' :
case ',' : case ']' : case '}' :
goto found;
}
if (js[parser->pos] < 32 || js[parser->pos] >= 127) {
parser->pos = start;
return JSMN_ERROR_INVAL;
}
}
#ifdef JSMN_STRICT
/* In strict mode primitive must be followed by a comma/object/array */
parser->pos = start;
return JSMN_ERROR_PART;
#endif
found:
if (tokens == NULL) {
parser->pos--;
return 0;
}
token = jsmn_alloc_token(parser, tokens, num_tokens);
if (token == NULL) {
parser->pos = start;
return JSMN_ERROR_NOMEM;
}
jsmn_fill_token(token, JSMN_PRIMITIVE, start, parser->pos);
#ifdef JSMN_PARENT_LINKS
token->parent = parser->toksuper;
#endif
parser->pos--;
return 0;
}
/**
* Fills next token with JSON string.
*/
static int jsmn_parse_string(jsmn_parser *parser, const char *js,
size_t len, jsmntok_t *tokens, size_t num_tokens) {
jsmntok_t *token;
ptrdiff_t start = parser->pos;
parser->pos++;
/* Skip starting quote */
for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
char c = js[parser->pos];
/* Quote: end of string */
if (c == '\"') {
if (tokens == NULL) {
return 0;
}
token = jsmn_alloc_token(parser, tokens, num_tokens);
if (token == NULL) {
parser->pos = start;
return JSMN_ERROR_NOMEM;
}
jsmn_fill_token(token, JSMN_STRING, start+1, parser->pos);
#ifdef JSMN_PARENT_LINKS
token->parent = parser->toksuper;
#endif
return 0;
}
/* Backslash: Quoted symbol expected */
if (c == '\\' && parser->pos + 1 < len) {
int i;
parser->pos++;
switch (js[parser->pos]) {
/* Allowed escaped symbols */
case '\"': case '/' : case '\\' : case 'b' :
case 'f' : case 'r' : case 'n' : case 't' :
break;
/* Allows escaped symbol \uXXXX */
case 'u':
parser->pos++;
for(i = 0; i < 4 && parser->pos < len && js[parser->pos] != '\0'; i++) {
/* If it isn't a hex character we have an error */
if(!((js[parser->pos] >= 48 && js[parser->pos] <= 57) || /* 0-9 */
(js[parser->pos] >= 65 && js[parser->pos] <= 70) || /* A-F */
(js[parser->pos] >= 97 && js[parser->pos] <= 102))) { /* a-f */
parser->pos = start;
return JSMN_ERROR_INVAL;
}
parser->pos++;
}
parser->pos--;
break;
/* Unexpected symbol */
default:
parser->pos = start;
return JSMN_ERROR_INVAL;
}
}
}
parser->pos = start;
return JSMN_ERROR_PART;
}
/**
* Parse JSON string and fill tokens.
*/
static int jsmn_parse(jsmn_parser *parser, const char *js, size_t len,
jsmntok_t *tokens, size_t num_tokens) {
int r;
int i;
jsmntok_t *token;
int count = parser->toknext;
for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
char c;
jsmntype_t type;
c = js[parser->pos];
switch (c) {
case '{': case '[':
count++;
if (tokens == NULL) {
break;
}
token = jsmn_alloc_token(parser, tokens, num_tokens);
if (token == NULL)
return JSMN_ERROR_NOMEM;
if (parser->toksuper != -1) {
tokens[parser->toksuper].size++;
#ifdef JSMN_PARENT_LINKS
token->parent = parser->toksuper;
#endif
}
token->type = (c == '{' ? JSMN_OBJECT : JSMN_ARRAY);
token->start = parser->pos;
parser->toksuper = parser->toknext - 1;
break;
case '}': case ']':
if (tokens == NULL)
break;
type = (c == '}' ? JSMN_OBJECT : JSMN_ARRAY);
#ifdef JSMN_PARENT_LINKS
if (parser->toknext < 1) {
return JSMN_ERROR_INVAL;
}
token = &tokens[parser->toknext - 1];
for (;;) {
if (token->start != -1 && token->end == -1) {
if (token->type != type) {
return JSMN_ERROR_INVAL;
}
token->end = parser->pos + 1;
parser->toksuper = token->parent;
break;
}
if (token->parent == -1) {
if(token->type != type || parser->toksuper == -1) {
return JSMN_ERROR_INVAL;
}
break;
}
token = &tokens[token->parent];
}
#else
for (i = parser->toknext - 1; i >= 0; i--) {
token = &tokens[i];
if (token->start != -1 && token->end == -1) {
if (token->type != type) {
return JSMN_ERROR_INVAL;
}
parser->toksuper = -1;
token->end = parser->pos + 1;
break;
}
}
/* Error if unmatched closing bracket */
if (i == -1) return JSMN_ERROR_INVAL;
for (; i >= 0; i--) {
token = &tokens[i];
if (token->start != -1 && token->end == -1) {
parser->toksuper = i;
break;
}
}
#endif
break;
case '\"':
r = jsmn_parse_string(parser, js, len, tokens, num_tokens);
if (r < 0) return r;
count++;
if (parser->toksuper != -1 && tokens != NULL)
tokens[parser->toksuper].size++;
break;
case '\t' : case '\r' : case '\n' : case ' ':
break;
case ':':
parser->toksuper = parser->toknext - 1;
break;
case ',':
if (tokens != NULL && parser->toksuper != -1 &&
tokens[parser->toksuper].type != JSMN_ARRAY &&
tokens[parser->toksuper].type != JSMN_OBJECT) {
#ifdef JSMN_PARENT_LINKS
parser->toksuper = tokens[parser->toksuper].parent;
#else
for (i = parser->toknext - 1; i >= 0; i--) {
if (tokens[i].type == JSMN_ARRAY || tokens[i].type == JSMN_OBJECT) {
if (tokens[i].start != -1 && tokens[i].end == -1) {
parser->toksuper = i;
break;
}
}
}
#endif
}
break;
#ifdef JSMN_STRICT
/* In strict mode primitives are: numbers and booleans */
case '-': case '0': case '1' : case '2': case '3' : case '4':
case '5': case '6': case '7' : case '8': case '9':
case 't': case 'f': case 'n' :
/* And they must not be keys of the object */
if (tokens != NULL && parser->toksuper != -1) {
jsmntok_t *t = &tokens[parser->toksuper];
if (t->type == JSMN_OBJECT ||
(t->type == JSMN_STRING && t->size != 0)) {
return JSMN_ERROR_INVAL;
}
}
#else
/* In non-strict mode every unquoted value is a primitive */
default:
#endif
r = jsmn_parse_primitive(parser, js, len, tokens, num_tokens);
if (r < 0) return r;
count++;
if (parser->toksuper != -1 && tokens != NULL)
tokens[parser->toksuper].size++;
break;
#ifdef JSMN_STRICT
/* Unexpected char in strict mode */
default:
return JSMN_ERROR_INVAL;
#endif
}
}
if (tokens != NULL) {
for (i = parser->toknext - 1; i >= 0; i--) {
/* Unmatched opened object or array */
if (tokens[i].start != -1 && tokens[i].end == -1) {
return JSMN_ERROR_PART;
}
}
}
return count;
}
/**
* Creates a new parser based over a given buffer with an array of tokens
* available.
*/
static void jsmn_init(jsmn_parser *parser) {
parser->pos = 0;
parser->toknext = 0;
parser->toksuper = -1;
}
/*
* -- jsmn.c end --
*/
#endif /* #ifdef CGLTF_IMPLEMENTATION */
/* cgltf is distributed under MIT license:
*
* Copyright (c) 2018-2021 Johannes Kuhlmann
* 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.
*/
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
extern/fast_obj.h | C/C++ Header | /*
* fast_obj
*
* Version 1.3
*
* MIT License
*
* Copyright (c) 2018-2021 Richard Knight
*
* 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.
*
*/
#ifndef FAST_OBJ_HDR
#define FAST_OBJ_HDR
#define FAST_OBJ_VERSION_MAJOR 1
#define FAST_OBJ_VERSION_MINOR 3
#define FAST_OBJ_VERSION ((FAST_OBJ_VERSION_MAJOR << 8) | FAST_OBJ_VERSION_MINOR)
#include <stdlib.h>
typedef struct
{
/* Texture name from .mtl file */
char* name;
/* Resolved path to texture */
char* path;
} fastObjTexture;
typedef struct
{
/* Material name */
char* name;
/* Parameters */
float Ka[3]; /* Ambient */
float Kd[3]; /* Diffuse */
float Ks[3]; /* Specular */
float Ke[3]; /* Emission */
float Kt[3]; /* Transmittance */
float Ns; /* Shininess */
float Ni; /* Index of refraction */
float Tf[3]; /* Transmission filter */
float d; /* Disolve (alpha) */
int illum; /* Illumination model */
/* Set for materials that don't come from the associated mtllib */
int fallback;
/* Texture map indices in fastObjMesh textures array */
unsigned int map_Ka;
unsigned int map_Kd;
unsigned int map_Ks;
unsigned int map_Ke;
unsigned int map_Kt;
unsigned int map_Ns;
unsigned int map_Ni;
unsigned int map_d;
unsigned int map_bump;
} fastObjMaterial;
/* Allows user override to bigger indexable array */
#ifndef FAST_OBJ_UINT_TYPE
#define FAST_OBJ_UINT_TYPE unsigned int
#endif
typedef FAST_OBJ_UINT_TYPE fastObjUInt;
typedef struct
{
fastObjUInt p;
fastObjUInt t;
fastObjUInt n;
} fastObjIndex;
typedef struct
{
/* Group name */
char* name;
/* Number of faces */
unsigned int face_count;
/* First face in fastObjMesh face_* arrays */
unsigned int face_offset;
/* First index in fastObjMesh indices array */
unsigned int index_offset;
} fastObjGroup;
/* Note: a dummy zero-initialized value is added to the first index
of the positions, texcoords, normals and textures arrays. Hence,
valid indices into these arrays start from 1, with an index of 0
indicating that the attribute is not present. */
typedef struct
{
/* Vertex data */
unsigned int position_count;
float* positions;
unsigned int texcoord_count;
float* texcoords;
unsigned int normal_count;
float* normals;
unsigned int color_count;
float* colors;
/* Face data: one element for each face */
unsigned int face_count;
unsigned int* face_vertices;
unsigned int* face_materials;
unsigned char* face_lines;
/* Index data: one element for each face vertex */
unsigned int index_count;
fastObjIndex* indices;
/* Materials */
unsigned int material_count;
fastObjMaterial* materials;
/* Texture maps */
unsigned int texture_count;
fastObjTexture* textures;
/* Mesh objects ('o' tag in .obj file) */
unsigned int object_count;
fastObjGroup* objects;
/* Mesh groups ('g' tag in .obj file) */
unsigned int group_count;
fastObjGroup* groups;
} fastObjMesh;
typedef struct
{
void* (*file_open)(const char* path, void* user_data);
void (*file_close)(void* file, void* user_data);
size_t (*file_read)(void* file, void* dst, size_t bytes, void* user_data);
unsigned long (*file_size)(void* file, void* user_data);
} fastObjCallbacks;
#ifdef __cplusplus
extern "C" {
#endif
fastObjMesh* fast_obj_read(const char* path);
fastObjMesh* fast_obj_read_with_callbacks(const char* path, const fastObjCallbacks* callbacks, void* user_data);
void fast_obj_destroy(fastObjMesh* mesh);
#ifdef __cplusplus
}
#endif
#endif
#ifdef FAST_OBJ_IMPLEMENTATION
#include <stdio.h>
#include <string.h>
#ifndef FAST_OBJ_REALLOC
#define FAST_OBJ_REALLOC realloc
#endif
#ifndef FAST_OBJ_FREE
#define FAST_OBJ_FREE free
#endif
#ifdef _WIN32
#define FAST_OBJ_SEPARATOR '\\'
#define FAST_OBJ_OTHER_SEP '/'
#else
#define FAST_OBJ_SEPARATOR '/'
#define FAST_OBJ_OTHER_SEP '\\'
#endif
/* Size of buffer to read into */
#define BUFFER_SIZE 65536
/* Max supported power when parsing float */
#define MAX_POWER 20
typedef struct
{
/* Final mesh */
fastObjMesh* mesh;
/* Current object/group */
fastObjGroup object;
fastObjGroup group;
/* Current material index */
unsigned int material;
/* Current line in file */
unsigned int line;
/* Base path for materials/textures */
char* base;
} fastObjData;
static const
double POWER_10_POS[MAX_POWER] =
{
1.0e0, 1.0e1, 1.0e2, 1.0e3, 1.0e4, 1.0e5, 1.0e6, 1.0e7, 1.0e8, 1.0e9,
1.0e10, 1.0e11, 1.0e12, 1.0e13, 1.0e14, 1.0e15, 1.0e16, 1.0e17, 1.0e18, 1.0e19,
};
static const
double POWER_10_NEG[MAX_POWER] =
{
1.0e0, 1.0e-1, 1.0e-2, 1.0e-3, 1.0e-4, 1.0e-5, 1.0e-6, 1.0e-7, 1.0e-8, 1.0e-9,
1.0e-10, 1.0e-11, 1.0e-12, 1.0e-13, 1.0e-14, 1.0e-15, 1.0e-16, 1.0e-17, 1.0e-18, 1.0e-19,
};
static void* memory_realloc(void* ptr, size_t bytes)
{
return FAST_OBJ_REALLOC(ptr, bytes);
}
static
void memory_dealloc(void* ptr)
{
FAST_OBJ_FREE(ptr);
}
#define array_clean(_arr) ((_arr) ? memory_dealloc(_array_header(_arr)), 0 : 0)
#define array_push(_arr, _val) (_array_mgrow(_arr, 1) ? ((_arr)[_array_size(_arr)++] = (_val), _array_size(_arr) - 1) : 0)
#define array_size(_arr) ((_arr) ? _array_size(_arr) : 0)
#define array_capacity(_arr) ((_arr) ? _array_capacity(_arr) : 0)
#define array_empty(_arr) (array_size(_arr) == 0)
#define _array_header(_arr) ((fastObjUInt*)(_arr)-2)
#define _array_size(_arr) (_array_header(_arr)[0])
#define _array_capacity(_arr) (_array_header(_arr)[1])
#define _array_ngrow(_arr, _n) ((_arr) == 0 || (_array_size(_arr) + (_n) >= _array_capacity(_arr)))
#define _array_mgrow(_arr, _n) (_array_ngrow(_arr, _n) ? (_array_grow(_arr, _n) != 0) : 1)
#define _array_grow(_arr, _n) (*((void**)&(_arr)) = array_realloc(_arr, _n, sizeof(*(_arr))))
static void* array_realloc(void* ptr, fastObjUInt n, fastObjUInt b)
{
fastObjUInt sz = array_size(ptr);
fastObjUInt nsz = sz + n;
fastObjUInt cap = array_capacity(ptr);
fastObjUInt ncap = cap + cap / 2;
fastObjUInt* r;
if (ncap < nsz)
ncap = nsz;
ncap = (ncap + 15) & ~15u;
r = (fastObjUInt*)(memory_realloc(ptr ? _array_header(ptr) : 0, (size_t)b * ncap + 2 * sizeof(fastObjUInt)));
if (!r)
return 0;
r[0] = sz;
r[1] = ncap;
return (r + 2);
}
static
void* file_open(const char* path, void* user_data)
{
(void)(user_data);
return fopen(path, "rb");
}
static
void file_close(void* file, void* user_data)
{
FILE* f;
(void)(user_data);
f = (FILE*)(file);
fclose(f);
}
static
size_t file_read(void* file, void* dst, size_t bytes, void* user_data)
{
FILE* f;
(void)(user_data);
f = (FILE*)(file);
return fread(dst, 1, bytes, f);
}
static
unsigned long file_size(void* file, void* user_data)
{
FILE* f;
long p;
long n;
(void)(user_data);
f = (FILE*)(file);
p = ftell(f);
fseek(f, 0, SEEK_END);
n = ftell(f);
fseek(f, p, SEEK_SET);
if (n > 0)
return (unsigned long)(n);
else
return 0;
}
static
char* string_copy(const char* s, const char* e)
{
size_t n;
char* p;
n = (size_t)(e - s);
p = (char*)(memory_realloc(0, n + 1));
if (p)
{
memcpy(p, s, n);
p[n] = '\0';
}
return p;
}
static
char* string_substr(const char* s, size_t a, size_t b)
{
return string_copy(s + a, s + b);
}
static
char* string_concat(const char* a, const char* s, const char* e)
{
size_t an;
size_t sn;
char* p;
an = a ? strlen(a) : 0;
sn = (size_t)(e - s);
p = (char*)(memory_realloc(0, an + sn + 1));
if (p)
{
if (a)
memcpy(p, a, an);
memcpy(p + an, s, sn);
p[an + sn] = '\0';
}
return p;
}
static
int string_equal(const char* a, const char* s, const char* e)
{
size_t an = strlen(a);
size_t sn = (size_t)(e - s);
return an == sn && memcmp(a, s, an) == 0;
}
static
void string_fix_separators(char* s)
{
while (*s)
{
if (*s == FAST_OBJ_OTHER_SEP)
*s = FAST_OBJ_SEPARATOR;
s++;
}
}
static
int is_whitespace(char c)
{
return (c == ' ' || c == '\t' || c == '\r');
}
static
int is_newline(char c)
{
return (c == '\n');
}
static
int is_digit(char c)
{
return (c >= '0' && c <= '9');
}
static
int is_exponent(char c)
{
return (c == 'e' || c == 'E');
}
static
const char* skip_name(const char* ptr)
{
const char* s = ptr;
while (!is_newline(*ptr))
ptr++;
while (ptr > s && is_whitespace(*(ptr - 1)))
ptr--;
return ptr;
}
static
const char* skip_whitespace(const char* ptr)
{
while (is_whitespace(*ptr))
ptr++;
return ptr;
}
static
const char* skip_line(const char* ptr)
{
while (!is_newline(*ptr++))
;
return ptr;
}
static
fastObjGroup object_default(void)
{
fastObjGroup object;
object.name = 0;
object.face_count = 0;
object.face_offset = 0;
object.index_offset = 0;
return object;
}
static
void object_clean(fastObjGroup* object)
{
memory_dealloc(object->name);
}
static
void flush_object(fastObjData* data)
{
/* Add object if not empty */
if (data->object.face_count > 0)
array_push(data->mesh->objects, data->object);
else
object_clean(&data->object);
/* Reset for more data */
data->object = object_default();
data->object.face_offset = array_size(data->mesh->face_vertices);
data->object.index_offset = array_size(data->mesh->indices);
}
static
fastObjGroup group_default(void)
{
fastObjGroup group;
group.name = 0;
group.face_count = 0;
group.face_offset = 0;
group.index_offset = 0;
return group;
}
static
void group_clean(fastObjGroup* group)
{
memory_dealloc(group->name);
}
static
void flush_group(fastObjData* data)
{
/* Add group if not empty */
if (data->group.face_count > 0)
array_push(data->mesh->groups, data->group);
else
group_clean(&data->group);
/* Reset for more data */
data->group = group_default();
data->group.face_offset = array_size(data->mesh->face_vertices);
data->group.index_offset = array_size(data->mesh->indices);
}
static
const char* parse_int(const char* ptr, int* val)
{
int sign;
int num;
if (*ptr == '-')
{
sign = -1;
ptr++;
}
else
{
sign = +1;
}
num = 0;
while (is_digit(*ptr))
num = 10 * num + (*ptr++ - '0');
*val = sign * num;
return ptr;
}
static
const char* parse_float(const char* ptr, float* val)
{
double sign;
double num;
double fra;
double div;
unsigned int eval;
const double* powers;
ptr = skip_whitespace(ptr);
switch (*ptr)
{
case '+':
sign = 1.0;
ptr++;
break;
case '-':
sign = -1.0;
ptr++;
break;
default:
sign = 1.0;
break;
}
num = 0.0;
while (is_digit(*ptr))
num = 10.0 * num + (double)(*ptr++ - '0');
if (*ptr == '.')
ptr++;
fra = 0.0;
div = 1.0;
while (is_digit(*ptr))
{
fra = 10.0 * fra + (double)(*ptr++ - '0');
div *= 10.0;
}
num += fra / div;
if (is_exponent(*ptr))
{
ptr++;
switch (*ptr)
{
case '+':
powers = POWER_10_POS;
ptr++;
break;
case '-':
powers = POWER_10_NEG;
ptr++;
break;
default:
powers = POWER_10_POS;
break;
}
eval = 0;
while (is_digit(*ptr))
eval = 10 * eval + (*ptr++ - '0');
num *= (eval >= MAX_POWER) ? 0.0 : powers[eval];
}
*val = (float)(sign * num);
return ptr;
}
static
const char* parse_vertex(fastObjData* data, const char* ptr)
{
unsigned int ii;
float v;
for (ii = 0; ii < 3; ii++)
{
ptr = parse_float(ptr, &v);
array_push(data->mesh->positions, v);
}
ptr = skip_whitespace(ptr);
if (!is_newline(*ptr))
{
/* Fill the colors array until it matches the size of the positions array */
for (ii = array_size(data->mesh->colors); ii < array_size(data->mesh->positions) - 3; ++ii)
{
array_push(data->mesh->colors, 1.0f);
}
for (ii = 0; ii < 3; ++ii)
{
ptr = parse_float(ptr, &v);
array_push(data->mesh->colors, v);
}
}
return ptr;
}
static
const char* parse_texcoord(fastObjData* data, const char* ptr)
{
unsigned int ii;
float v;
for (ii = 0; ii < 2; ii++)
{
ptr = parse_float(ptr, &v);
array_push(data->mesh->texcoords, v);
}
return ptr;
}
static
const char* parse_normal(fastObjData* data, const char* ptr)
{
unsigned int ii;
float v;
for (ii = 0; ii < 3; ii++)
{
ptr = parse_float(ptr, &v);
array_push(data->mesh->normals, v);
}
return ptr;
}
static
const char* parse_face(fastObjData* data, const char* ptr, unsigned char line)
{
unsigned int count;
fastObjIndex vn;
int v;
int t;
int n;
ptr = skip_whitespace(ptr);
count = 0;
while (!is_newline(*ptr))
{
v = 0;
t = 0;
n = 0;
ptr = parse_int(ptr, &v);
if (*ptr == '/')
{
ptr++;
if (*ptr != '/')
ptr = parse_int(ptr, &t);
if (*ptr == '/')
{
ptr++;
ptr = parse_int(ptr, &n);
}
}
if (v < 0)
vn.p = (array_size(data->mesh->positions) / 3) - (fastObjUInt)(-v);
else if (v > 0)
vn.p = (fastObjUInt)(v);
else
return ptr; /* Skip lines with no valid vertex index */
if (t < 0)
vn.t = (array_size(data->mesh->texcoords) / 2) - (fastObjUInt)(-t);
else if (t > 0)
vn.t = (fastObjUInt)(t);
else
vn.t = 0;
if (n < 0)
vn.n = (array_size(data->mesh->normals) / 3) - (fastObjUInt)(-n);
else if (n > 0)
vn.n = (fastObjUInt)(n);
else
vn.n = 0;
array_push(data->mesh->indices, vn);
count++;
ptr = skip_whitespace(ptr);
}
array_push(data->mesh->face_vertices, count);
array_push(data->mesh->face_materials, data->material);
if (line || data->mesh->face_lines)
{
/* when line info exists, ensure it uses aligned indexing with other face data */
size_t skipped = array_size(data->mesh->face_vertices) - array_size(data->mesh->face_lines);
while (--skipped > 0)
array_push(data->mesh->face_lines, 0);
array_push(data->mesh->face_lines, line);
}
data->group.face_count++;
data->object.face_count++;
return ptr;
}
static
const char* parse_object(fastObjData* data, const char* ptr)
{
const char* s;
const char* e;
ptr = skip_whitespace(ptr);
s = ptr;
ptr = skip_name(ptr);
e = ptr;
flush_object(data);
data->object.name = string_copy(s, e);
return ptr;
}
static
const char* parse_group(fastObjData* data, const char* ptr)
{
const char* s;
const char* e;
ptr = skip_whitespace(ptr);
s = ptr;
ptr = skip_name(ptr);
e = ptr;
flush_group(data);
data->group.name = string_copy(s, e);
return ptr;
}
static
fastObjTexture map_default(void)
{
fastObjTexture map;
map.name = 0;
map.path = 0;
return map;
}
static
fastObjMaterial mtl_default(void)
{
fastObjMaterial mtl;
mtl.name = 0;
mtl.Ka[0] = 0.0;
mtl.Ka[1] = 0.0;
mtl.Ka[2] = 0.0;
mtl.Kd[0] = 1.0;
mtl.Kd[1] = 1.0;
mtl.Kd[2] = 1.0;
mtl.Ks[0] = 0.0;
mtl.Ks[1] = 0.0;
mtl.Ks[2] = 0.0;
mtl.Ke[0] = 0.0;
mtl.Ke[1] = 0.0;
mtl.Ke[2] = 0.0;
mtl.Kt[0] = 0.0;
mtl.Kt[1] = 0.0;
mtl.Kt[2] = 0.0;
mtl.Ns = 1.0;
mtl.Ni = 1.0;
mtl.Tf[0] = 1.0;
mtl.Tf[1] = 1.0;
mtl.Tf[2] = 1.0;
mtl.d = 1.0;
mtl.illum = 1;
mtl.fallback = 0;
mtl.map_Ka = 0;
mtl.map_Kd = 0;
mtl.map_Ks = 0;
mtl.map_Ke = 0;
mtl.map_Kt = 0;
mtl.map_Ns = 0;
mtl.map_Ni = 0;
mtl.map_d = 0;
mtl.map_bump = 0;
return mtl;
}
static
const char* parse_usemtl(fastObjData* data, const char* ptr)
{
const char* s;
const char* e;
unsigned int idx;
fastObjMaterial* mtl;
ptr = skip_whitespace(ptr);
/* Parse the material name */
s = ptr;
ptr = skip_name(ptr);
e = ptr;
/* Find an existing material with the same name */
idx = 0;
while (idx < array_size(data->mesh->materials))
{
mtl = &data->mesh->materials[idx];
if (mtl->name && string_equal(mtl->name, s, e))
break;
idx++;
}
/* If doesn't exist, create a default one with this name
Note: this case happens when OBJ doesn't have its MTL */
if (idx == array_size(data->mesh->materials))
{
fastObjMaterial new_mtl = mtl_default();
new_mtl.name = string_copy(s, e);
new_mtl.fallback = 1;
array_push(data->mesh->materials, new_mtl);
}
data->material = idx;
return ptr;
}
static
void map_clean(fastObjTexture* map)
{
memory_dealloc(map->name);
memory_dealloc(map->path);
}
static
void mtl_clean(fastObjMaterial* mtl)
{
memory_dealloc(mtl->name);
}
static
const char* read_mtl_int(const char* p, int* v)
{
return parse_int(p, v);
}
static
const char* read_mtl_single(const char* p, float* v)
{
return parse_float(p, v);
}
static
const char* read_mtl_triple(const char* p, float v[3])
{
p = read_mtl_single(p, &v[0]);
p = read_mtl_single(p, &v[1]);
p = read_mtl_single(p, &v[2]);
return p;
}
static
const char* read_map(fastObjData* data, const char* ptr, unsigned int* idx)
{
const char* s;
const char* e;
fastObjTexture* map;
ptr = skip_whitespace(ptr);
/* Don't support options at present */
if (*ptr == '-')
return ptr;
/* Read name */
s = ptr;
ptr = skip_name(ptr);
e = ptr;
/* Try to find an existing texture map with the same name */
*idx = 1; /* skip dummy at index 0 */
while (*idx < array_size(data->mesh->textures))
{
map = &data->mesh->textures[*idx];
if (map->name && string_equal(map->name, s, e))
break;
(*idx)++;
}
/* Add it to the texture array if it didn't already exist */
if (*idx == array_size(data->mesh->textures))
{
fastObjTexture new_map = map_default();
new_map.name = string_copy(s, e);
new_map.path = string_concat(data->base, s, e);
string_fix_separators(new_map.path);
array_push(data->mesh->textures, new_map);
}
return e;
}
static
int read_mtllib(fastObjData* data, void* file, const fastObjCallbacks* callbacks, void* user_data)
{
unsigned long n;
const char* s;
char* contents;
size_t l;
const char* p;
const char* e;
int found_d;
fastObjMaterial mtl;
/* Read entire file */
n = callbacks->file_size(file, user_data);
contents = (char*)(memory_realloc(0, n + 1));
if (!contents)
return 0;
l = callbacks->file_read(file, contents, n, user_data);
contents[l] = '\n';
mtl = mtl_default();
found_d = 0;
p = contents;
e = contents + l;
while (p < e)
{
p = skip_whitespace(p);
switch (*p)
{
case 'n':
p++;
if (p[0] == 'e' &&
p[1] == 'w' &&
p[2] == 'm' &&
p[3] == 't' &&
p[4] == 'l' &&
is_whitespace(p[5]))
{
/* Push previous material (if there is one) */
if (mtl.name)
{
array_push(data->mesh->materials, mtl);
mtl = mtl_default();
}
/* Read name */
p += 5;
while (is_whitespace(*p))
p++;
s = p;
p = skip_name(p);
mtl.name = string_copy(s, p);
}
break;
case 'K':
if (p[1] == 'a')
p = read_mtl_triple(p + 2, mtl.Ka);
else if (p[1] == 'd')
p = read_mtl_triple(p + 2, mtl.Kd);
else if (p[1] == 's')
p = read_mtl_triple(p + 2, mtl.Ks);
else if (p[1] == 'e')
p = read_mtl_triple(p + 2, mtl.Ke);
else if (p[1] == 't')
p = read_mtl_triple(p + 2, mtl.Kt);
break;
case 'N':
if (p[1] == 's')
p = read_mtl_single(p + 2, &mtl.Ns);
else if (p[1] == 'i')
p = read_mtl_single(p + 2, &mtl.Ni);
break;
case 'T':
if (p[1] == 'r')
{
float Tr;
p = read_mtl_single(p + 2, &Tr);
if (!found_d)
{
/* Ignore Tr if we've already read d */
mtl.d = 1.0f - Tr;
}
}
else if (p[1] == 'f')
p = read_mtl_triple(p + 2, mtl.Tf);
break;
case 'd':
if (is_whitespace(p[1]))
{
p = read_mtl_single(p + 1, &mtl.d);
found_d = 1;
}
break;
case 'i':
p++;
if (p[0] == 'l' &&
p[1] == 'l' &&
p[2] == 'u' &&
p[3] == 'm' &&
is_whitespace(p[4]))
{
p = read_mtl_int(p + 4, &mtl.illum);
}
break;
case 'm':
p++;
if (p[0] == 'a' &&
p[1] == 'p' &&
p[2] == '_')
{
p += 3;
if (*p == 'K')
{
p++;
if (is_whitespace(p[1]))
{
if (*p == 'a')
p = read_map(data, p + 1, &mtl.map_Ka);
else if (*p == 'd')
p = read_map(data, p + 1, &mtl.map_Kd);
else if (*p == 's')
p = read_map(data, p + 1, &mtl.map_Ks);
else if (*p == 'e')
p = read_map(data, p + 1, &mtl.map_Ke);
else if (*p == 't')
p = read_map(data, p + 1, &mtl.map_Kt);
}
}
else if (*p == 'N')
{
p++;
if (is_whitespace(p[1]))
{
if (*p == 's')
p = read_map(data, p + 1, &mtl.map_Ns);
else if (*p == 'i')
p = read_map(data, p + 1, &mtl.map_Ni);
}
}
else if (*p == 'd')
{
p++;
if (is_whitespace(*p))
p = read_map(data, p, &mtl.map_d);
}
else if ((p[0] == 'b' || p[0] == 'B') &&
p[1] == 'u' &&
p[2] == 'm' &&
p[3] == 'p' &&
is_whitespace(p[4]))
{
p = read_map(data, p + 4, &mtl.map_bump);
}
}
break;
case '#':
break;
}
p = skip_line(p);
}
/* Push final material */
if (mtl.name)
array_push(data->mesh->materials, mtl);
memory_dealloc(contents);
return 1;
}
static
const char* parse_mtllib(fastObjData* data, const char* ptr, const fastObjCallbacks* callbacks, void* user_data)
{
const char* s;
const char* e;
char* lib;
void* file;
ptr = skip_whitespace(ptr);
s = ptr;
ptr = skip_name(ptr);
e = ptr;
lib = string_concat(data->base, s, e);
if (lib)
{
string_fix_separators(lib);
file = callbacks->file_open(lib, user_data);
if (file)
{
read_mtllib(data, file, callbacks, user_data);
callbacks->file_close(file, user_data);
}
memory_dealloc(lib);
}
return ptr;
}
static
void parse_buffer(fastObjData* data, const char* ptr, const char* end, const fastObjCallbacks* callbacks, void* user_data)
{
const char* p;
p = ptr;
while (p != end)
{
p = skip_whitespace(p);
switch (*p)
{
case 'v':
p++;
switch (*p++)
{
case ' ':
case '\t':
p = parse_vertex(data, p);
break;
case 't':
p = parse_texcoord(data, p);
break;
case 'n':
p = parse_normal(data, p);
break;
default:
p--; /* roll p++ back in case *p was a newline */
}
break;
case 'f':
p++;
switch (*p++)
{
case ' ':
case '\t':
p = parse_face(data, p, 0);
break;
default:
p--; /* roll p++ back in case *p was a newline */
}
break;
case 'l':
p++;
switch (*p++)
{
case ' ':
case '\t':
p = parse_face(data, p, 1);
break;
default:
p--; /* roll p++ back in case *p was a newline */
}
break;
case 'o':
p++;
switch (*p++)
{
case ' ':
case '\t':
p = parse_object(data, p);
break;
default:
p--; /* roll p++ back in case *p was a newline */
}
break;
case 'g':
p++;
switch (*p++)
{
case ' ':
case '\t':
p = parse_group(data, p);
break;
default:
p--; /* roll p++ back in case *p was a newline */
}
break;
case 'm':
p++;
if (p[0] == 't' &&
p[1] == 'l' &&
p[2] == 'l' &&
p[3] == 'i' &&
p[4] == 'b' &&
is_whitespace(p[5]))
p = parse_mtllib(data, p + 5, callbacks, user_data);
break;
case 'u':
p++;
if (p[0] == 's' &&
p[1] == 'e' &&
p[2] == 'm' &&
p[3] == 't' &&
p[4] == 'l' &&
is_whitespace(p[5]))
p = parse_usemtl(data, p + 5);
break;
case '#':
break;
}
p = skip_line(p);
data->line++;
}
if (array_size(data->mesh->colors) > 0)
{
/* Fill the remaining slots in the colors array */
unsigned int ii;
for (ii = array_size(data->mesh->colors); ii < array_size(data->mesh->positions); ++ii)
{
array_push(data->mesh->colors, 1.0f);
}
}
}
void fast_obj_destroy(fastObjMesh* m)
{
unsigned int ii;
for (ii = 0; ii < array_size(m->objects); ii++)
object_clean(&m->objects[ii]);
for (ii = 0; ii < array_size(m->groups); ii++)
group_clean(&m->groups[ii]);
for (ii = 0; ii < array_size(m->materials); ii++)
mtl_clean(&m->materials[ii]);
for (ii = 0; ii < array_size(m->textures); ii++)
map_clean(&m->textures[ii]);
array_clean(m->positions);
array_clean(m->texcoords);
array_clean(m->normals);
array_clean(m->colors);
array_clean(m->face_vertices);
array_clean(m->face_materials);
array_clean(m->face_lines);
array_clean(m->indices);
array_clean(m->objects);
array_clean(m->groups);
array_clean(m->materials);
array_clean(m->textures);
memory_dealloc(m);
}
fastObjMesh* fast_obj_read(const char* path)
{
fastObjCallbacks callbacks;
callbacks.file_open = file_open;
callbacks.file_close = file_close;
callbacks.file_read = file_read;
callbacks.file_size = file_size;
return fast_obj_read_with_callbacks(path, &callbacks, 0);
}
fastObjMesh* fast_obj_read_with_callbacks(const char* path, const fastObjCallbacks* callbacks, void* user_data)
{
fastObjData data;
fastObjMesh* m;
void* file;
char* buffer;
char* start;
char* end;
char* last;
fastObjUInt read;
fastObjUInt bytes;
/* Check if callbacks are valid */
if(!callbacks)
return 0;
/* Open file */
file = callbacks->file_open(path, user_data);
if (!file)
return 0;
/* Empty mesh */
m = (fastObjMesh*)(memory_realloc(0, sizeof(fastObjMesh)));
if (!m)
return 0;
m->positions = 0;
m->texcoords = 0;
m->normals = 0;
m->colors = 0;
m->face_vertices = 0;
m->face_materials = 0;
m->face_lines = 0;
m->indices = 0;
m->materials = 0;
m->textures = 0;
m->objects = 0;
m->groups = 0;
/* Add dummy position/texcoord/normal/texture */
array_push(m->positions, 0.0f);
array_push(m->positions, 0.0f);
array_push(m->positions, 0.0f);
array_push(m->texcoords, 0.0f);
array_push(m->texcoords, 0.0f);
array_push(m->normals, 0.0f);
array_push(m->normals, 0.0f);
array_push(m->normals, 1.0f);
array_push(m->textures, map_default());
/* Data needed during parsing */
data.mesh = m;
data.object = object_default();
data.group = group_default();
data.material = 0;
data.line = 1;
data.base = 0;
/* Find base path for materials/textures */
{
const char* sep1 = strrchr(path, FAST_OBJ_SEPARATOR);
const char* sep2 = strrchr(path, FAST_OBJ_OTHER_SEP);
/* Use the last separator in the path */
const char* sep = sep2 && (!sep1 || sep1 < sep2) ? sep2 : sep1;
if (sep)
data.base = string_substr(path, 0, sep - path + 1);
}
/* Create buffer for reading file */
buffer = (char*)(memory_realloc(0, 2 * BUFFER_SIZE * sizeof(char)));
if (!buffer)
return 0;
start = buffer;
for (;;)
{
/* Read another buffer's worth from file */
read = (fastObjUInt)(callbacks->file_read(file, start, BUFFER_SIZE, user_data));
if (read == 0 && start == buffer)
break;
/* Ensure buffer ends in a newline */
if (read < BUFFER_SIZE)
{
if (read == 0 || start[read - 1] != '\n')
start[read++] = '\n';
}
end = start + read;
if (end == buffer)
break;
/* Find last new line */
last = end;
while (last > buffer)
{
last--;
if (*last == '\n')
break;
}
/* Check there actually is a new line */
if (*last != '\n')
break;
last++;
/* Process buffer */
parse_buffer(&data, buffer, last, callbacks, user_data);
/* Copy overflow for next buffer */
bytes = (fastObjUInt)(end - last);
memmove(buffer, last, bytes);
start = buffer + bytes;
}
/* Flush final object/group */
flush_object(&data);
object_clean(&data.object);
flush_group(&data);
group_clean(&data.group);
m->position_count = array_size(m->positions) / 3;
m->texcoord_count = array_size(m->texcoords) / 2;
m->normal_count = array_size(m->normals) / 3;
m->color_count = array_size(m->colors) / 3;
m->face_count = array_size(m->face_vertices);
m->index_count = array_size(m->indices);
m->material_count = array_size(m->materials);
m->texture_count = array_size(m->textures);
m->object_count = array_size(m->objects);
m->group_count = array_size(m->groups);
/* Clean up */
memory_dealloc(buffer);
memory_dealloc(data.base);
callbacks->file_close(file, user_data);
return m;
}
#endif | zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
extern/sdefl.h | C/C++ Header | /*# Small Deflate
`sdefl` is a small bare bone lossless compression library in ANSI C (ISO C90)
which implements the Deflate (RFC 1951) compressed data format specification standard.
It is mainly tuned to get as much speed and compression ratio from as little code
as needed to keep the implementation as concise as possible.
## Features
- Portable single header and source file duo written in ANSI C (ISO C90)
- Dual license with either MIT or public domain
- Small implementation
- Deflate: 525 LoC
- Inflate: 320 LoC
- Webassembly:
- Deflate ~3.7 KB (~2.2KB compressed)
- Inflate ~3.6 KB (~2.2KB compressed)
## Usage:
This file behaves differently depending on what symbols you define
before including it.
Header-File mode:
If you do not define `SDEFL_IMPLEMENTATION` before including this file, it
will operate in header only mode. In this mode it declares all used structs
and the API of the library without including the implementation of the library.
Implementation mode:
If you define `SDEFL_IMPLEMENTATION` before including this file, it will
compile the implementation . Make sure that you only include
this file implementation in *one* C or C++ file to prevent collisions.
### Benchmark
| Compressor name | Compression| Decompress.| Compr. size | Ratio |
| ------------------------| -----------| -----------| ----------- | ----- |
| miniz 1.0 -1 | 122 MB/s | 208 MB/s | 48510028 | 48.51 |
| miniz 1.0 -6 | 27 MB/s | 260 MB/s | 36513697 | 36.51 |
| miniz 1.0 -9 | 23 MB/s | 261 MB/s | 36460101 | 36.46 |
| zlib 1.2.11 -1 | 72 MB/s | 307 MB/s | 42298774 | 42.30 |
| zlib 1.2.11 -6 | 24 MB/s | 313 MB/s | 36548921 | 36.55 |
| zlib 1.2.11 -9 | 20 MB/s | 314 MB/s | 36475792 | 36.48 |
| sdefl 1.0 -0 | 127 MB/s | 355 MB/s | 40004116 | 39.88 |
| sdefl 1.0 -1 | 111 MB/s | 413 MB/s | 38940674 | 38.82 |
| sdefl 1.0 -5 | 45 MB/s | 436 MB/s | 36577183 | 36.46 |
| sdefl 1.0 -7 | 38 MB/s | 432 MB/s | 36523781 | 36.41 |
| libdeflate 1.3 -1 | 147 MB/s | 667 MB/s | 39597378 | 39.60 |
| libdeflate 1.3 -6 | 69 MB/s | 689 MB/s | 36648318 | 36.65 |
| libdeflate 1.3 -9 | 13 MB/s | 672 MB/s | 35197141 | 35.20 |
| libdeflate 1.3 -12 | 8.13 MB/s | 670 MB/s | 35100568 | 35.10 |
### Compression
Results on the [Silesia compression corpus](http://sun.aei.polsl.pl/~sdeor/index.php?page=silesia):
| File | Original | `sdefl 0` | `sdefl 5` | `sdefl 7` |
| --------| -----------| -------------| ---------- | ------------|
| dickens | 10.192.446 | 4,260,187 | 3,845,261 | 3,833,657 |
| mozilla | 51.220.480 | 20,774,706 | 19,607,009 | 19,565,867 |
| mr | 9.970.564 | 3,860,531 | 3,673,460 | 3,665,627 |
| nci | 33.553.445 | 4,030,283 | 3,094,526 | 3,006,075 |
| ooffice | 6.152.192 | 3,320,063 | 3,186,373 | 3,183,815 |
| osdb | 10.085.684 | 3,919,646 | 3,649,510 | 3,649,477 |
| reymont | 6.627.202 | 2,263,378 | 1,857,588 | 1,827,237 |
| samba | 21.606.400 | 6,121,797 | 5,462,670 | 5,450,762 |
| sao | 7.251.944 | 5,612,421 | 5,485,380 | 5,481,765 |
| webster | 41.458.703 | 13,972,648 | 12,059,432 | 11,991,421 |
| xml | 5.345.280 | 886,620 | 674,009 | 662,141 |
| x-ray | 8.474.240 | 6,304,655 | 6,244,779 | 6,244,779 |
## License
```
------------------------------------------------------------------------------
This software is available under 2 licenses -- choose whichever you prefer.
------------------------------------------------------------------------------
ALTERNATIVE A - MIT License
Copyright (c) 2020-2023 Micha Mettke
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.
------------------------------------------------------------------------------
ALTERNATIVE B - Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
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 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.
------------------------------------------------------------------------------
```
*/
#ifndef SDEFL_H_INCLUDED
#define SDEFL_H_INCLUDED
#ifdef __cplusplus
extern "C" {
#endif
#define SDEFL_MAX_OFF (1 << 15)
#define SDEFL_WIN_SIZ SDEFL_MAX_OFF
#define SDEFL_WIN_MSK (SDEFL_WIN_SIZ-1)
#define SDEFL_HASH_BITS 15
#define SDEFL_HASH_SIZ (1 << SDEFL_HASH_BITS)
#define SDEFL_HASH_MSK (SDEFL_HASH_SIZ-1)
#define SDEFL_MIN_MATCH 4
#define SDEFL_BLK_MAX (256*1024)
#define SDEFL_SEQ_SIZ ((SDEFL_BLK_MAX+2)/3)
#define SDEFL_SYM_MAX (288)
#define SDEFL_OFF_MAX (32)
#define SDEFL_PRE_MAX (19)
#define SDEFL_LVL_MIN 0
#define SDEFL_LVL_DEF 5
#define SDEFL_LVL_MAX 8
struct sdefl_freq {
unsigned lit[SDEFL_SYM_MAX];
unsigned off[SDEFL_OFF_MAX];
};
struct sdefl_code_words {
unsigned lit[SDEFL_SYM_MAX];
unsigned off[SDEFL_OFF_MAX];
};
struct sdefl_lens {
unsigned char lit[SDEFL_SYM_MAX];
unsigned char off[SDEFL_OFF_MAX];
};
struct sdefl_codes {
struct sdefl_code_words word;
struct sdefl_lens len;
};
struct sdefl_seqt {
int off, len;
};
struct sdefl {
int bits, bitcnt;
int tbl[SDEFL_HASH_SIZ];
int prv[SDEFL_WIN_SIZ];
int seq_cnt;
struct sdefl_seqt seq[SDEFL_SEQ_SIZ];
struct sdefl_freq freq;
struct sdefl_codes cod;
};
extern int sdefl_bound(int in_len);
extern int sdeflate(struct sdefl *s, void *o, const void *i, int n, int lvl);
extern int zsdeflate(struct sdefl *s, void *o, const void *i, int n, int lvl);
#ifdef __cplusplus
}
#endif
#endif /* SDEFL_H_INCLUDED */
#ifdef SDEFL_IMPLEMENTATION
#include <assert.h> /* assert */
#include <string.h> /* memcpy */
#include <limits.h> /* CHAR_BIT */
#ifdef __cplusplus
extern "C" {
#endif
#define SDEFL_NIL (-1)
#define SDEFL_MAX_MATCH 258
#define SDEFL_MAX_CODE_LEN (15)
#define SDEFL_SYM_BITS (10u)
#define SDEFL_SYM_MSK ((1u << SDEFL_SYM_BITS)-1u)
#define SDEFL_RAW_BLK_SIZE (65535)
#define SDEFL_LIT_LEN_CODES (14)
#define SDEFL_OFF_CODES (15)
#define SDEFL_PRE_CODES (7)
#define SDEFL_CNT_NUM(n) ((((n)+3u/4u)+3u)&~3u)
#define SDEFL_EOB (256)
#define sdefl_npow2(n) (1 << (sdefl_ilog2((n)-1) + 1))
#define sdefl_div_round_up(n,d) (((n)+((d)-1))/(d))
static int
sdefl_ilog2(int n) {
if (!n) return 0;
#ifdef _MSC_VER
unsigned long msbp = 0;
_BitScanReverse(&msbp, (unsigned long)n);
return (int)msbp;
#elif defined(__GNUC__) || defined(__clang__)
return (int)sizeof(unsigned long) * CHAR_BIT - 1 - __builtin_clzl((unsigned long)n);
#else
#define lt(n) n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n
static const char tbl[256] = {
0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,lt(4), lt(5), lt(5), lt(6), lt(6), lt(6), lt(6),
lt(7), lt(7), lt(7), lt(7), lt(7), lt(7), lt(7), lt(7)};
int tt, t;
if ((tt = (n >> 16))) {
return (t = (tt >> 8)) ? 24 + tbl[t] : 16 + tbl[tt];
} else {
return (t = (n >> 8)) ? 8 + tbl[t] : tbl[n];
}
#undef lt
#endif
}
static unsigned
sdefl_uload32(const void *p) {
/* hopefully will be optimized to an unaligned read */
unsigned n = 0;
memcpy(&n, p, sizeof(n));
return n;
}
static unsigned
sdefl_hash32(const void *p) {
unsigned n = sdefl_uload32(p);
return (n * 0x9E377989) >> (32 - SDEFL_HASH_BITS);
}
static void
sdefl_put(unsigned char **dst, struct sdefl *s, int code, int bitcnt) {
s->bits |= (code << s->bitcnt);
s->bitcnt += bitcnt;
while (s->bitcnt >= 8) {
unsigned char *tar = *dst;
*tar = (unsigned char)(s->bits & 0xFF);
s->bits >>= 8;
s->bitcnt -= 8;
*dst = *dst + 1;
}
}
static void
sdefl_heap_sub(unsigned A[], unsigned len, unsigned sub) {
unsigned c, p = sub;
unsigned v = A[sub];
while ((c = p << 1) <= len) {
if (c < len && A[c + 1] > A[c]) c++;
if (v >= A[c]) break;
A[p] = A[c], p = c;
}
A[p] = v;
}
static void
sdefl_heap_array(unsigned *A, unsigned len) {
unsigned sub;
for (sub = len >> 1; sub >= 1; sub--)
sdefl_heap_sub(A, len, sub);
}
static void
sdefl_heap_sort(unsigned *A, unsigned n) {
A--;
sdefl_heap_array(A, n);
while (n >= 2) {
unsigned tmp = A[n];
A[n--] = A[1];
A[1] = tmp;
sdefl_heap_sub(A, n, 1);
}
}
static unsigned
sdefl_sort_sym(unsigned sym_cnt, unsigned *freqs,
unsigned char *lens, unsigned *sym_out) {
unsigned cnts[SDEFL_CNT_NUM(SDEFL_SYM_MAX)] = {0};
unsigned cnt_num = SDEFL_CNT_NUM(sym_cnt);
unsigned used_sym = 0;
unsigned sym, i;
for (sym = 0; sym < sym_cnt; sym++)
cnts[freqs[sym] < cnt_num-1 ? freqs[sym]: cnt_num-1]++;
for (i = 1; i < cnt_num; i++) {
unsigned cnt = cnts[i];
cnts[i] = used_sym;
used_sym += cnt;
}
for (sym = 0; sym < sym_cnt; sym++) {
unsigned freq = freqs[sym];
if (freq) {
unsigned idx = freq < cnt_num-1 ? freq : cnt_num-1;
sym_out[cnts[idx]++] = sym | (freq << SDEFL_SYM_BITS);
} else lens[sym] = 0;
}
sdefl_heap_sort(sym_out + cnts[cnt_num-2], cnts[cnt_num-1] - cnts[cnt_num-2]);
return used_sym;
}
static void
sdefl_build_tree(unsigned *A, unsigned sym_cnt) {
unsigned i = 0, b = 0, e = 0;
do {
unsigned m, n, freq_shift;
if (i != sym_cnt && (b == e || (A[i] >> SDEFL_SYM_BITS) <= (A[b] >> SDEFL_SYM_BITS)))
m = i++;
else m = b++;
if (i != sym_cnt && (b == e || (A[i] >> SDEFL_SYM_BITS) <= (A[b] >> SDEFL_SYM_BITS)))
n = i++;
else n = b++;
freq_shift = (A[m] & ~SDEFL_SYM_MSK) + (A[n] & ~SDEFL_SYM_MSK);
A[m] = (A[m] & SDEFL_SYM_MSK) | (e << SDEFL_SYM_BITS);
A[n] = (A[n] & SDEFL_SYM_MSK) | (e << SDEFL_SYM_BITS);
A[e] = (A[e] & SDEFL_SYM_MSK) | freq_shift;
} while (sym_cnt - ++e > 1);
}
static void
sdefl_gen_len_cnt(unsigned *A, unsigned root, unsigned *len_cnt,
unsigned max_code_len) {
int n;
unsigned i;
for (i = 0; i <= max_code_len; i++)
len_cnt[i] = 0;
len_cnt[1] = 2;
A[root] &= SDEFL_SYM_MSK;
for (n = (int)root - 1; n >= 0; n--) {
unsigned p = A[n] >> SDEFL_SYM_BITS;
unsigned pdepth = A[p] >> SDEFL_SYM_BITS;
unsigned depth = pdepth + 1;
unsigned len = depth;
A[n] = (A[n] & SDEFL_SYM_MSK) | (depth << SDEFL_SYM_BITS);
if (len >= max_code_len) {
len = max_code_len;
do len--; while (!len_cnt[len]);
}
len_cnt[len]--;
len_cnt[len+1] += 2;
}
}
static void
sdefl_gen_codes(unsigned *A, unsigned char *lens, const unsigned *len_cnt,
unsigned max_code_word_len, unsigned sym_cnt) {
unsigned i, sym, len, nxt[SDEFL_MAX_CODE_LEN + 1];
for (i = 0, len = max_code_word_len; len >= 1; len--) {
unsigned cnt = len_cnt[len];
while (cnt--) lens[A[i++] & SDEFL_SYM_MSK] = (unsigned char)len;
}
nxt[0] = nxt[1] = 0;
for (len = 2; len <= max_code_word_len; len++)
nxt[len] = (nxt[len-1] + len_cnt[len-1]) << 1;
for (sym = 0; sym < sym_cnt; sym++)
A[sym] = nxt[lens[sym]]++;
}
static unsigned
sdefl_rev(unsigned c, unsigned char n) {
c = ((c & 0x5555) << 1) | ((c & 0xAAAA) >> 1);
c = ((c & 0x3333) << 2) | ((c & 0xCCCC) >> 2);
c = ((c & 0x0F0F) << 4) | ((c & 0xF0F0) >> 4);
c = ((c & 0x00FF) << 8) | ((c & 0xFF00) >> 8);
return c >> (16-n);
}
static void
sdefl_huff(unsigned char *lens, unsigned *codes, unsigned *freqs,
unsigned num_syms, unsigned max_code_len) {
unsigned c, *A = codes;
unsigned len_cnt[SDEFL_MAX_CODE_LEN + 1];
unsigned used_syms = sdefl_sort_sym(num_syms, freqs, lens, A);
if (!used_syms) return;
if (used_syms == 1) {
unsigned s = A[0] & SDEFL_SYM_MSK;
unsigned i = s ? s : 1;
codes[0] = 0, lens[0] = 1;
codes[i] = 1, lens[i] = 1;
return;
}
sdefl_build_tree(A, used_syms);
sdefl_gen_len_cnt(A, used_syms-2, len_cnt, max_code_len);
sdefl_gen_codes(A, lens, len_cnt, max_code_len, num_syms);
for (c = 0; c < num_syms; c++) {
codes[c] = sdefl_rev(codes[c], lens[c]);
}
}
struct sdefl_symcnt {
int items;
int lit;
int off;
};
static void
sdefl_precode(struct sdefl_symcnt *cnt, unsigned *freqs, unsigned *items,
const unsigned char *litlen, const unsigned char *offlen) {
unsigned *at = items;
unsigned run_start = 0;
unsigned total = 0;
unsigned char lens[SDEFL_SYM_MAX + SDEFL_OFF_MAX];
for (cnt->lit = SDEFL_SYM_MAX; cnt->lit > 257; cnt->lit--)
if (litlen[cnt->lit - 1]) break;
for (cnt->off = SDEFL_OFF_MAX; cnt->off > 1; cnt->off--)
if (offlen[cnt->off - 1]) break;
total = (unsigned)(cnt->lit + cnt->off);
memcpy(lens, litlen, sizeof(unsigned char) * (size_t)cnt->lit);
memcpy(lens + cnt->lit, offlen, sizeof(unsigned char) * (size_t)cnt->off);
do {
unsigned len = lens[run_start];
unsigned run_end = run_start;
do run_end++; while (run_end != total && len == lens[run_end]);
if (!len) {
while ((run_end - run_start) >= 11) {
unsigned n = (run_end - run_start) - 11;
unsigned xbits = n < 0x7f ? n : 0x7f;
freqs[18]++;
*at++ = 18u | (xbits << 5u);
run_start += 11 + xbits;
}
if ((run_end - run_start) >= 3) {
unsigned n = (run_end - run_start) - 3;
unsigned xbits = n < 0x7 ? n : 0x7;
freqs[17]++;
*at++ = 17u | (xbits << 5u);
run_start += 3 + xbits;
}
} else if ((run_end - run_start) >= 4) {
freqs[len]++;
*at++ = len;
run_start++;
do {
unsigned xbits = (run_end - run_start) - 3;
xbits = xbits < 0x03 ? xbits : 0x03;
*at++ = 16 | (xbits << 5);
run_start += 3 + xbits;
freqs[16]++;
} while ((run_end - run_start) >= 3);
}
while (run_start != run_end) {
freqs[len]++;
*at++ = len;
run_start++;
}
} while (run_start != total);
cnt->items = (int)(at - items);
}
struct sdefl_match_codest {
int ls, lc;
int dc, dx;
};
static void
sdefl_match_codes(struct sdefl_match_codest *cod, int dist, int len) {
static const short dxmax[] = {0,6,12,24,48,96,192,384,768,1536,3072,6144,12288,24576};
static const unsigned char lslot[258+1] = {
0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12,
12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16,
16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18,
18, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20,
20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 28
};
assert(len <= 258);
assert(dist <= 32768);
cod->ls = lslot[len];
cod->lc = 257 + cod->ls;
assert(cod->lc <= 285);
cod->dx = sdefl_ilog2(sdefl_npow2(dist) >> 2);
cod->dc = cod->dx ? ((cod->dx + 1) << 1) + (dist > dxmax[cod->dx]) : dist-1;
}
enum sdefl_blk_type {
SDEFL_BLK_UCOMPR,
SDEFL_BLK_DYN
};
static enum sdefl_blk_type
sdefl_blk_type(const struct sdefl *s, int blk_len, int pre_item_len,
const unsigned *pre_freq, const unsigned char *pre_len) {
static const unsigned char x_pre_bits[] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
static const unsigned char x_len_bits[] = {0,0,0,0,0,0,0,0, 1,1,1,1,2,2,2,2,
3,3,3,3,4,4,4,4, 5,5,5,5,0};
static const unsigned char x_off_bits[] = {0,0,0,0,1,1,2,2, 3,3,4,4,5,5,6,6,
7,7,8,8,9,9,10,10, 11,11,12,12,13,13};
int dyn_cost = 0;
int fix_cost = 0;
int sym = 0;
dyn_cost += 5 + 5 + 4 + (3 * pre_item_len);
for (sym = 0; sym < SDEFL_PRE_MAX; sym++)
dyn_cost += pre_freq[sym] * (x_pre_bits[sym] + pre_len[sym]);
for (sym = 0; sym < 256; sym++)
dyn_cost += s->freq.lit[sym] * s->cod.len.lit[sym];
dyn_cost += s->cod.len.lit[SDEFL_EOB];
for (sym = 257; sym < 286; sym++)
dyn_cost += s->freq.lit[sym] * (x_len_bits[sym - 257] + s->cod.len.lit[sym]);
for (sym = 0; sym < 30; sym++)
dyn_cost += s->freq.off[sym] * (x_off_bits[sym] + s->cod.len.off[sym]);
fix_cost += 8*(5 * sdefl_div_round_up(blk_len, SDEFL_RAW_BLK_SIZE) + blk_len + 1 + 2);
return (dyn_cost < fix_cost) ? SDEFL_BLK_DYN : SDEFL_BLK_UCOMPR;
}
static void
sdefl_put16(unsigned char **dst, unsigned short x) {
unsigned char *val = *dst;
val[0] = (unsigned char)(x & 0xff);
val[1] = (unsigned char)(x >> 8);
*dst = val + 2;
}
static void
sdefl_match(unsigned char **dst, struct sdefl *s, int dist, int len) {
static const char lxn[] = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};
static const short lmin[] = {3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,
51,59,67,83,99,115,131,163,195,227,258};
static const short dmin[] = {1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,
385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577};
struct sdefl_match_codest cod;
sdefl_match_codes(&cod, dist, len);
sdefl_put(dst, s, (int)s->cod.word.lit[cod.lc], s->cod.len.lit[cod.lc]);
sdefl_put(dst, s, len - lmin[cod.ls], lxn[cod.ls]);
sdefl_put(dst, s, (int)s->cod.word.off[cod.dc], s->cod.len.off[cod.dc]);
sdefl_put(dst, s, dist - dmin[cod.dc], cod.dx);
}
static void
sdefl_flush(unsigned char **dst, struct sdefl *s, int is_last,
const unsigned char *in, int blk_begin, int blk_end) {
int blk_len = blk_end - blk_begin;
int j, i = 0, item_cnt = 0;
struct sdefl_symcnt symcnt = {0};
unsigned codes[SDEFL_PRE_MAX];
unsigned char lens[SDEFL_PRE_MAX];
unsigned freqs[SDEFL_PRE_MAX] = {0};
unsigned items[SDEFL_SYM_MAX + SDEFL_OFF_MAX];
static const unsigned char perm[SDEFL_PRE_MAX] = {16,17,18,0,8,7,9,6,10,5,11,
4,12,3,13,2,14,1,15};
/* calculate huffman codes */
s->freq.lit[SDEFL_EOB]++;
sdefl_huff(s->cod.len.lit, s->cod.word.lit, s->freq.lit, SDEFL_SYM_MAX, SDEFL_LIT_LEN_CODES);
sdefl_huff(s->cod.len.off, s->cod.word.off, s->freq.off, SDEFL_OFF_MAX, SDEFL_OFF_CODES);
sdefl_precode(&symcnt, freqs, items, s->cod.len.lit, s->cod.len.off);
sdefl_huff(lens, codes, freqs, SDEFL_PRE_MAX, SDEFL_PRE_CODES);
for (item_cnt = SDEFL_PRE_MAX; item_cnt > 4; item_cnt--) {
if (lens[perm[item_cnt - 1]]){
break;
}
}
/* write block */
switch (sdefl_blk_type(s, blk_len, item_cnt, freqs, lens)) {
case SDEFL_BLK_UCOMPR: {
/* uncompressed blocks */
int n = sdefl_div_round_up(blk_len, SDEFL_RAW_BLK_SIZE);
for (i = 0; i < n; ++i) {
int fin = is_last && (i + 1 == n);
int amount = blk_len < SDEFL_RAW_BLK_SIZE ? blk_len : SDEFL_RAW_BLK_SIZE;
sdefl_put(dst, s, !!fin, 1); /* block */
sdefl_put(dst, s, 0x00, 2); /* stored block */
if (s->bitcnt) {
sdefl_put(dst, s, 0x00, 8 - s->bitcnt);
}
assert(s->bitcnt == 0);
sdefl_put16(dst, (unsigned short)amount);
sdefl_put16(dst, ~(unsigned short)amount);
memcpy(*dst, in + blk_begin + i * SDEFL_RAW_BLK_SIZE, amount);
*dst = *dst + amount;
blk_len -= amount;
}
} break;
case SDEFL_BLK_DYN: {
/* dynamic huffman block */
sdefl_put(dst, s, !!is_last, 1); /* block */
sdefl_put(dst, s, 0x02, 2); /* dynamic huffman */
sdefl_put(dst, s, symcnt.lit - 257, 5);
sdefl_put(dst, s, symcnt.off - 1, 5);
sdefl_put(dst, s, item_cnt - 4, 4);
for (i = 0; i < item_cnt; ++i) {
sdefl_put(dst, s, lens[perm[i]], 3);
}
for (i = 0; i < symcnt.items; ++i) {
unsigned sym = items[i] & 0x1F;
sdefl_put(dst, s, (int)codes[sym], lens[sym]);
if (sym < 16) continue;
if (sym == 16) sdefl_put(dst, s, items[i] >> 5, 2);
else if(sym == 17) sdefl_put(dst, s, items[i] >> 5, 3);
else sdefl_put(dst, s, items[i] >> 5, 7);
}
/* block sequences */
for (i = 0; i < s->seq_cnt; ++i) {
if (s->seq[i].off >= 0) {
for (j = 0; j < s->seq[i].len; ++j) {
int c = in[s->seq[i].off + j];
sdefl_put(dst, s, (int)s->cod.word.lit[c], s->cod.len.lit[c]);
}
} else {
sdefl_match(dst, s, -s->seq[i].off, s->seq[i].len);
}
}
sdefl_put(dst, s, (int)(s)->cod.word.lit[SDEFL_EOB], (s)->cod.len.lit[SDEFL_EOB]);
} break;}
memset(&s->freq, 0, sizeof(s->freq));
s->seq_cnt = 0;
}
static void
sdefl_seq(struct sdefl *s, int off, int len) {
assert(s->seq_cnt + 2 < SDEFL_SEQ_SIZ);
s->seq[s->seq_cnt].off = off;
s->seq[s->seq_cnt].len = len;
s->seq_cnt++;
}
static void
sdefl_reg_match(struct sdefl *s, int off, int len) {
struct sdefl_match_codest cod;
sdefl_match_codes(&cod, off, len);
assert(cod.lc < SDEFL_SYM_MAX);
assert(cod.dc < SDEFL_OFF_MAX);
s->freq.lit[cod.lc]++;
s->freq.off[cod.dc]++;
}
struct sdefl_match {
int off;
int len;
};
static void
sdefl_fnd(struct sdefl_match *m, const struct sdefl *s, int chain_len,
int max_match, const unsigned char *in, int p, int e) {
int i = s->tbl[sdefl_hash32(in + p)];
int limit = ((p - SDEFL_WIN_SIZ) < SDEFL_NIL) ? SDEFL_NIL : (p-SDEFL_WIN_SIZ);
(void)e; /* used in assertions */
assert(p < e);
assert(p + max_match <= e);
while (i > limit) {
assert(i + m->len < e);
assert(p + m->len < e);
assert(i + SDEFL_MIN_MATCH < e);
assert(p + SDEFL_MIN_MATCH < e);
if (in[i + m->len] == in[p + m->len] &&
(sdefl_uload32(&in[i]) == sdefl_uload32(&in[p]))) {
int n = SDEFL_MIN_MATCH;
while (n < max_match && in[i + n] == in[p + n]) {
assert(i + n < e);
assert(p + n < e);
n++;
}
if (n > m->len) {
m->len = n, m->off = p - i;
if (n == max_match)
break;
}
}
if (!(--chain_len)) break;
i = s->prv[i & SDEFL_WIN_MSK];
}
}
static int
sdefl_compr(struct sdefl *s, unsigned char *out, const unsigned char *in,
int in_len, int lvl) {
unsigned char *q = out;
static const unsigned char pref[] = {8,10,14,24,30,48,65,96,130};
int max_chain = (lvl < 8) ? (1 << (lvl + 1)): (1 << 13);
int n, i = 0, litlen = 0;
for (n = 0; n < SDEFL_HASH_SIZ; ++n) {
s->tbl[n] = SDEFL_NIL;
}
do {int blk_begin = i;
int blk_end = ((i + SDEFL_BLK_MAX) < in_len) ? (i + SDEFL_BLK_MAX) : in_len;
while (i < blk_end) {
struct sdefl_match m = {0};
int left = blk_end - i;
int max_match = (left > SDEFL_MAX_MATCH) ? SDEFL_MAX_MATCH : left;
int nice_match = pref[lvl] < max_match ? pref[lvl] : max_match;
int run = 1, inc = 1, run_inc = 0;
if (max_match > SDEFL_MIN_MATCH) {
sdefl_fnd(&m, s, max_chain, max_match, in, i, in_len);
}
if (lvl >= 5 && m.len >= SDEFL_MIN_MATCH && m.len + 1 < nice_match){
struct sdefl_match m2 = {0};
sdefl_fnd(&m2, s, max_chain, m.len + 1, in, i + 1, in_len);
m.len = (m2.len > m.len) ? 0 : m.len;
}
if (m.len >= SDEFL_MIN_MATCH) {
if (litlen) {
sdefl_seq(s, i - litlen, litlen);
litlen = 0;
}
sdefl_seq(s, -m.off, m.len);
sdefl_reg_match(s, m.off, m.len);
if (lvl < 2 && m.len >= nice_match) {
inc = m.len;
} else {
run = m.len;
}
} else {
s->freq.lit[in[i]]++;
litlen++;
}
run_inc = run * inc;
if (in_len - (i + run_inc) > SDEFL_MIN_MATCH) {
while (run-- > 0) {
unsigned h = sdefl_hash32(&in[i]);
s->prv[i&SDEFL_WIN_MSK] = s->tbl[h];
s->tbl[h] = i, i += inc;
assert(i <= blk_end);
}
} else {
i += run_inc;
assert(i <= blk_end);
}
}
if (litlen) {
sdefl_seq(s, i - litlen, litlen);
litlen = 0;
}
sdefl_flush(&q, s, blk_end == in_len, in, blk_begin, blk_end);
} while (i < in_len);
if (s->bitcnt) {
sdefl_put(&q, s, 0x00, 8 - s->bitcnt);
}
assert(s->bitcnt == 0);
return (int)(q - out);
}
extern int
sdeflate(struct sdefl *s, void *out, const void *in, int n, int lvl) {
s->bits = s->bitcnt = 0;
return sdefl_compr(s, (unsigned char*)out, (const unsigned char*)in, n, lvl);
}
static unsigned
sdefl_adler32(unsigned adler32, const unsigned char *in, int in_len) {
#define SDEFL_ADLER_INIT (1)
const unsigned ADLER_MOD = 65521;
unsigned s1 = adler32 & 0xffff;
unsigned s2 = adler32 >> 16;
unsigned blk_len, i;
blk_len = in_len % 5552;
while (in_len) {
for (i = 0; i + 7 < blk_len; i += 8) {
s1 += in[0]; s2 += s1;
s1 += in[1]; s2 += s1;
s1 += in[2]; s2 += s1;
s1 += in[3]; s2 += s1;
s1 += in[4]; s2 += s1;
s1 += in[5]; s2 += s1;
s1 += in[6]; s2 += s1;
s1 += in[7]; s2 += s1;
in += 8;
}
for (; i < blk_len; ++i) {
s1 += *in++, s2 += s1;
}
s1 %= ADLER_MOD;
s2 %= ADLER_MOD;
in_len -= blk_len;
blk_len = 5552;
}
return (unsigned)(s2 << 16) + (unsigned)s1;
}
extern int
zsdeflate(struct sdefl *s, void *out, const void *in, int n, int lvl) {
int p = 0;
unsigned a = 0;
unsigned char *q = (unsigned char*)out;
s->bits = s->bitcnt = 0;
sdefl_put(&q, s, 0x78, 8); /* deflate, 32k window */
sdefl_put(&q, s, 0x01, 8); /* fast compression */
q += sdefl_compr(s, q, (const unsigned char*)in, n, lvl);
/* append adler checksum */
a = sdefl_adler32(SDEFL_ADLER_INIT, (const unsigned char*)in, n);
for (p = 0; p < 4; ++p) {
sdefl_put(&q, s, (a >> 24) & 0xFF, 8);
a <<= 8;
}
return (int)(q - (unsigned char*)out);
}
extern int
sdefl_bound(int len) {
int max_blocks = 1 + sdefl_div_round_up(len, SDEFL_RAW_BLK_SIZE);
int bound = 5 * max_blocks + len + 1 + 4 + 8 + 3;
return bound;
}
#ifdef __cplusplus
}
#endif
#endif /* SDEFL_IMPLEMENTATION */
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
gltf/animation.cpp | C++ | // This file is part of gltfpack; see gltfpack.h for version/license details
#include "gltfpack.h"
#include <algorithm>
#include <float.h>
#include <math.h>
#include <string.h>
static float getDelta(const Attr& l, const Attr& r, cgltf_animation_path_type type)
{
switch (type)
{
case cgltf_animation_path_type_translation:
return std::max(std::max(fabsf(l.f[0] - r.f[0]), fabsf(l.f[1] - r.f[1])), fabsf(l.f[2] - r.f[2]));
case cgltf_animation_path_type_rotation:
return 2 * acosf(std::min(1.f, fabsf(l.f[0] * r.f[0] + l.f[1] * r.f[1] + l.f[2] * r.f[2] + l.f[3] * r.f[3])));
case cgltf_animation_path_type_scale:
return std::max(std::max(fabsf(l.f[0] / r.f[0] - 1), fabsf(l.f[1] / r.f[1] - 1)), fabsf(l.f[2] / r.f[2] - 1));
case cgltf_animation_path_type_weights:
return fabsf(l.f[0] - r.f[0]);
default:
assert(!"Uknown animation path");
return 0;
}
}
static float getDeltaTolerance(cgltf_animation_path_type type)
{
switch (type)
{
case cgltf_animation_path_type_translation:
return 0.0001f; // 0.1mm linear
case cgltf_animation_path_type_rotation:
return 0.1f * (3.1415926f / 180.f); // 0.1 degrees
case cgltf_animation_path_type_scale:
return 0.001f; // 0.1% ratio
case cgltf_animation_path_type_weights:
return 0.001f; // 0.1% linear
default:
assert(!"Uknown animation path");
return 0;
}
}
static Attr interpolateLinear(const Attr& l, const Attr& r, float t, cgltf_animation_path_type type)
{
if (type == cgltf_animation_path_type_rotation)
{
// Approximating slerp, https://zeux.io/2015/07/23/approximating-slerp/
// We also handle quaternion double-cover
float ca = l.f[0] * r.f[0] + l.f[1] * r.f[1] + l.f[2] * r.f[2] + l.f[3] * r.f[3];
float d = fabsf(ca);
float A = 1.0904f + d * (-3.2452f + d * (3.55645f - d * 1.43519f));
float B = 0.848013f + d * (-1.06021f + d * 0.215638f);
float k = A * (t - 0.5f) * (t - 0.5f) + B;
float ot = t + t * (t - 0.5f) * (t - 1) * k;
float t0 = 1 - ot;
float t1 = ca > 0 ? ot : -ot;
Attr lerp = {{
l.f[0] * t0 + r.f[0] * t1,
l.f[1] * t0 + r.f[1] * t1,
l.f[2] * t0 + r.f[2] * t1,
l.f[3] * t0 + r.f[3] * t1,
}};
float len = sqrtf(lerp.f[0] * lerp.f[0] + lerp.f[1] * lerp.f[1] + lerp.f[2] * lerp.f[2] + lerp.f[3] * lerp.f[3]);
if (len > 0.f)
{
lerp.f[0] /= len;
lerp.f[1] /= len;
lerp.f[2] /= len;
lerp.f[3] /= len;
}
return lerp;
}
else
{
Attr lerp = {{
l.f[0] * (1 - t) + r.f[0] * t,
l.f[1] * (1 - t) + r.f[1] * t,
l.f[2] * (1 - t) + r.f[2] * t,
l.f[3] * (1 - t) + r.f[3] * t,
}};
return lerp;
}
}
static Attr interpolateHermite(const Attr& v0, const Attr& t0, const Attr& v1, const Attr& t1, float t, float dt, cgltf_animation_path_type type)
{
float s0 = 1 + t * t * (2 * t - 3);
float s1 = t + t * t * (t - 2);
float s2 = 1 - s0;
float s3 = t * t * (t - 1);
float ts1 = dt * s1;
float ts3 = dt * s3;
Attr lerp = {{
s0 * v0.f[0] + ts1 * t0.f[0] + s2 * v1.f[0] + ts3 * t1.f[0],
s0 * v0.f[1] + ts1 * t0.f[1] + s2 * v1.f[1] + ts3 * t1.f[1],
s0 * v0.f[2] + ts1 * t0.f[2] + s2 * v1.f[2] + ts3 * t1.f[2],
s0 * v0.f[3] + ts1 * t0.f[3] + s2 * v1.f[3] + ts3 * t1.f[3],
}};
if (type == cgltf_animation_path_type_rotation)
{
float len = sqrtf(lerp.f[0] * lerp.f[0] + lerp.f[1] * lerp.f[1] + lerp.f[2] * lerp.f[2] + lerp.f[3] * lerp.f[3]);
if (len > 0.f)
{
lerp.f[0] /= len;
lerp.f[1] /= len;
lerp.f[2] /= len;
lerp.f[3] /= len;
}
}
return lerp;
}
static void resampleKeyframes(std::vector<Attr>& data, const std::vector<float>& input, const std::vector<Attr>& output, cgltf_animation_path_type type, cgltf_interpolation_type interpolation, size_t components, int frames, float mint, int freq)
{
size_t cursor = 0;
for (int i = 0; i < frames; ++i)
{
float time = mint + float(i) / freq;
while (cursor + 1 < input.size())
{
float next_time = input[cursor + 1];
if (next_time > time)
break;
cursor++;
}
if (cursor + 1 < input.size())
{
float cursor_time = input[cursor + 0];
float next_time = input[cursor + 1];
float range = next_time - cursor_time;
float inv_range = (range == 0.f) ? 0.f : 1.f / (next_time - cursor_time);
float t = std::max(0.f, std::min(1.f, (time - cursor_time) * inv_range));
for (size_t j = 0; j < components; ++j)
{
switch (interpolation)
{
case cgltf_interpolation_type_linear:
{
const Attr& v0 = output[(cursor + 0) * components + j];
const Attr& v1 = output[(cursor + 1) * components + j];
data.push_back(interpolateLinear(v0, v1, t, type));
}
break;
case cgltf_interpolation_type_step:
{
const Attr& v = output[cursor * components + j];
data.push_back(v);
}
break;
case cgltf_interpolation_type_cubic_spline:
{
const Attr& v0 = output[(cursor * 3 + 1) * components + j];
const Attr& b0 = output[(cursor * 3 + 2) * components + j];
const Attr& a1 = output[(cursor * 3 + 3) * components + j];
const Attr& v1 = output[(cursor * 3 + 4) * components + j];
data.push_back(interpolateHermite(v0, b0, v1, a1, t, range, type));
}
break;
default:
assert(!"Unknown interpolation type");
}
}
}
else
{
size_t offset = (interpolation == cgltf_interpolation_type_cubic_spline) ? cursor * 3 + 1 : cursor;
for (size_t j = 0; j < components; ++j)
{
const Attr& v = output[offset * components + j];
data.push_back(v);
}
}
}
}
static float getMaxDelta(const std::vector<Attr>& data, cgltf_animation_path_type type, const Attr* value, size_t components)
{
assert(data.size() % components == 0);
float result = 0;
for (size_t i = 0; i < data.size(); i += components)
{
for (size_t j = 0; j < components; ++j)
{
float delta = getDelta(value[j], data[i + j], type);
result = (result < delta) ? delta : result;
}
}
return result;
}
static void getBaseTransform(Attr* result, size_t components, cgltf_animation_path_type type, cgltf_node* node)
{
switch (type)
{
case cgltf_animation_path_type_translation:
memcpy(result->f, node->translation, 3 * sizeof(float));
break;
case cgltf_animation_path_type_rotation:
memcpy(result->f, node->rotation, 4 * sizeof(float));
break;
case cgltf_animation_path_type_scale:
memcpy(result->f, node->scale, 3 * sizeof(float));
break;
case cgltf_animation_path_type_weights:
if (node->weights_count)
{
assert(node->weights_count == components);
memcpy(result->f, node->weights, components * sizeof(float));
}
else if (node->mesh && node->mesh->weights_count)
{
assert(node->mesh->weights_count == components);
memcpy(result->f, node->mesh->weights, components * sizeof(float));
}
break;
default:
assert(!"Unknown animation path");
}
}
static float getWorldScale(cgltf_node* node)
{
float transform[16];
cgltf_node_transform_world(node, transform);
// 3x3 determinant computes scale^3
float a0 = transform[5] * transform[10] - transform[6] * transform[9];
float a1 = transform[4] * transform[10] - transform[6] * transform[8];
float a2 = transform[4] * transform[9] - transform[5] * transform[8];
float det = transform[0] * a0 - transform[1] * a1 + transform[2] * a2;
return powf(fabsf(det), 1.f / 3.f);
}
void processAnimation(Animation& animation, const Settings& settings)
{
float mint = FLT_MAX, maxt = 0;
for (size_t i = 0; i < animation.tracks.size(); ++i)
{
const Track& track = animation.tracks[i];
assert(!track.time.empty());
mint = std::min(mint, track.time.front());
maxt = std::max(maxt, track.time.back());
}
animation.start = mint = std::min(mint, maxt);
if (settings.anim_freq)
{
// round the number of frames to nearest but favor the "up" direction
// this means that at 100 Hz resampling, we will try to preserve the last frame <10ms
// but if the last frame is <2ms we favor just removing this data
int frames = 1 + int((maxt - mint) * settings.anim_freq + 0.8f);
animation.frames = frames;
}
std::vector<Attr> base;
for (size_t i = 0; i < animation.tracks.size(); ++i)
{
Track& track = animation.tracks[i];
if (settings.anim_freq)
{
std::vector<Attr> result;
resampleKeyframes(result, track.time, track.data, track.path, track.interpolation, track.components, animation.frames, animation.start, settings.anim_freq);
track.time.clear();
track.data.swap(result);
track.interpolation = track.interpolation == cgltf_interpolation_type_cubic_spline ? cgltf_interpolation_type_linear : track.interpolation;
}
// getMaxDelta assumes linear/step interpolation for now
if (track.interpolation == cgltf_interpolation_type_cubic_spline)
continue;
float tolerance = getDeltaTolerance(track.path);
// translation tracks use world space tolerance; in the future, we should compute all errors as linear using hierarchy
if (track.node && track.node->parent && track.path == cgltf_animation_path_type_translation)
{
float scale = getWorldScale(track.node->parent);
tolerance /= scale == 0.f ? 1.f : scale;
}
float deviation = getMaxDelta(track.data, track.path, &track.data[0], track.components);
if (deviation <= tolerance)
{
// track is constant (equal to first keyframe), we only need the first keyframe
track.constant = true;
track.time.clear();
track.data.resize(track.components);
// track.dummy is true iff track redundantly sets up the value to be equal to default node transform
base.resize(track.components);
getBaseTransform(&base[0], track.components, track.path, track.node);
track.dummy = getMaxDelta(track.data, track.path, &base[0], track.components) <= tolerance;
}
}
}
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
gltf/cli.js | JavaScript | #!/usr/bin/env node
// This file is part of gltfpack and is distributed under the terms of MIT License.
import { pack } from './library.js';
import fs from 'fs';
var args = process.argv.slice(2);
var iface = {
read: function (path) {
return fs.readFileSync(path);
},
write: function (path, data) {
fs.writeFileSync(path, data);
},
};
pack(args, iface)
.then(function (log) {
process.stdout.write(log);
process.exit(0);
})
.catch(function (err) {
process.stderr.write(err.message);
process.exit(1);
});
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
gltf/encodebasis.cpp | C++ | // This file is part of gltfpack; see gltfpack.h for version/license details
#ifdef WITH_BASISU
#include "gltfpack.h"
#define BASISU_NO_ITERATOR_DEBUG_LEVEL
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wunknown-warning-option"
#pragma GCC diagnostic ignored "-Warray-bounds"
#pragma GCC diagnostic ignored "-Wc++17-extensions"
#pragma GCC diagnostic ignored "-Wdeprecated-builtins"
#endif
#ifdef __GNUC__
#pragma GCC diagnostic ignored "-Wclass-memaccess"
#pragma GCC diagnostic ignored "-Wshadow"
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#pragma GCC diagnostic ignored "-Wunused-value"
#endif
#if defined(__GNUC__) && __GNUC__ >= 12
#pragma GCC diagnostic ignored "-Wc++17-extensions"
#endif
#include "encoder/basisu_comp.h"
struct BasisSettings
{
int etc1s_l;
int etc1s_q;
int uastc_l;
float uastc_q;
};
static const BasisSettings kBasisSettings[10] = {
{1, 1, 0, 4.f},
{1, 32, 0, 3.f},
{1, 64, 1, 2.f},
{1, 96, 1, 1.5f},
{1, 128, 1, 1.f}, // quality arguments aligned with basisu defaults
{1, 150, 1, 0.8f},
{1, 170, 1, 0.6f},
{1, 192, 1, 0.4f}, // gltfpack defaults
{1, 224, 2, 0.2f},
{1, 255, 2, 0.f},
};
static void fillParams(basisu::basis_compressor_params& params, const char* input, const char* output, bool uastc, int width, int height, const BasisSettings& bs, const ImageInfo& info, const Settings& settings)
{
if (uastc)
{
static const uint32_t s_level_flags[basisu::TOTAL_PACK_UASTC_LEVELS] = {basisu::cPackUASTCLevelFastest, basisu::cPackUASTCLevelFaster, basisu::cPackUASTCLevelDefault, basisu::cPackUASTCLevelSlower, basisu::cPackUASTCLevelVerySlow};
params.m_uastc = true;
#if BASISU_LIB_VERSION >= 160
params.m_pack_uastc_ldr_4x4_flags &= ~basisu::cPackUASTCLevelMask;
params.m_pack_uastc_ldr_4x4_flags |= s_level_flags[bs.uastc_l];
params.m_rdo_uastc_ldr_4x4 = bs.uastc_q > 0;
params.m_rdo_uastc_ldr_4x4_quality_scalar = bs.uastc_q;
params.m_rdo_uastc_ldr_4x4_dict_size = 1024;
#else
params.m_pack_uastc_flags &= ~basisu::cPackUASTCLevelMask;
params.m_pack_uastc_flags |= s_level_flags[bs.uastc_l];
params.m_rdo_uastc = bs.uastc_q > 0;
params.m_rdo_uastc_quality_scalar = bs.uastc_q;
params.m_rdo_uastc_dict_size = 1024;
#endif
}
else
{
#if BASISU_LIB_VERSION >= 200
params.m_etc1s_compression_level = bs.etc1s_l;
params.m_quality_level = bs.etc1s_q;
params.m_etc1s_max_endpoint_clusters = 0;
params.m_etc1s_max_selector_clusters = 0;
#elif BASISU_LIB_VERSION >= 160
params.m_compression_level = bs.etc1s_l;
params.m_etc1s_quality_level = bs.etc1s_q;
params.m_etc1s_max_endpoint_clusters = 0;
params.m_etc1s_max_selector_clusters = 0;
#else
params.m_compression_level = bs.etc1s_l;
params.m_quality_level = bs.etc1s_q;
params.m_max_endpoint_clusters = 0;
params.m_max_selector_clusters = 0;
#endif
params.m_no_selector_rdo = info.normal_map;
params.m_no_endpoint_rdo = info.normal_map;
}
params.m_perceptual = info.srgb;
params.m_mip_gen = true;
params.m_mip_srgb = info.srgb;
params.m_resample_width = width;
params.m_resample_height = height;
params.m_y_flip = settings.texture_flipy;
params.m_create_ktx2_file = true;
#if BASISU_LIB_VERSION >= 200
params.m_ktx2_and_basis_srgb_transfer_function = info.srgb;
#else
params.m_ktx2_srgb_transfer_func = info.srgb;
#endif
if (uastc)
{
params.m_ktx2_uastc_supercompression = basist::KTX2_SS_ZSTANDARD;
params.m_ktx2_zstd_supercompression_level = 9;
}
params.m_read_source_images = true;
#if BASISU_LIB_VERSION >= 150
params.m_write_output_basis_or_ktx2_files = true;
#else
params.m_write_output_basis_files = true;
#endif
params.m_source_filenames.resize(1);
params.m_source_filenames[0] = input;
params.m_out_filename = output;
params.m_status_output = false;
}
static const char* prepareEncode(basisu::basis_compressor_params& params, const cgltf_image& image, const char* input_path, const ImageInfo& info, const Settings& settings, const std::string& temp_prefix, std::string& temp_input, std::string& temp_output)
{
std::string img_data;
std::string mime_type;
if (!readImage(image, input_path, img_data, mime_type))
return "error reading source file";
if (mime_type != "image/png" && mime_type != "image/jpeg")
return NULL;
int width = 0, height = 0;
if (!getDimensions(img_data, mime_type.c_str(), width, height))
return "error parsing image header";
adjustDimensions(width, height, settings.texture_scale[info.kind], settings.texture_limit[info.kind], settings.texture_pow2);
temp_input = temp_prefix + mimeExtension(mime_type.c_str());
temp_output = temp_prefix + ".ktx2";
if (!writeFile(temp_input.c_str(), img_data))
return "error writing temporary file";
int quality = settings.texture_quality[info.kind];
bool uastc = settings.texture_mode[info.kind] == TextureMode_UASTC;
const BasisSettings& bs = kBasisSettings[quality - 1];
fillParams(params, temp_input.c_str(), temp_output.c_str(), uastc, width, height, bs, info, settings);
return NULL;
}
void encodeImagesBasis(std::string* encoded, const cgltf_data* data, const std::vector<ImageInfo>& images, const char* input_path, const Settings& settings)
{
basisu::basisu_encoder_init();
basisu::vector<basisu::basis_compressor_params> params(data->images_count);
basisu::vector<basisu::parallel_results> results(data->images_count);
std::string temp_prefix = getTempPrefix();
std::vector<std::string> temp_inputs(data->images_count);
std::vector<std::string> temp_outputs(data->images_count);
for (size_t i = 0; i < data->images_count; ++i)
{
const cgltf_image& image = data->images[i];
ImageInfo info = images[i];
if (settings.texture_mode[info.kind] == TextureMode_ETC1S || settings.texture_mode[info.kind] == TextureMode_UASTC)
if (const char* error = prepareEncode(params[i], image, input_path, info, settings, temp_prefix + "-" + std::to_string(i), temp_inputs[i], temp_outputs[i]))
encoded[i] = error;
}
uint32_t num_threads = settings.texture_jobs == 0 ? std::thread::hardware_concurrency() : settings.texture_jobs;
basisu::basis_parallel_compress(num_threads, params, results);
for (size_t i = 0; i < data->images_count; ++i)
{
if (params[i].m_source_filenames.empty())
; // encoding was skipped or preparation resulted in an error
else if (results[i].m_error_code == basisu::basis_compressor::cECFailedReadingSourceImages)
encoded[i] = "error decoding source image";
else if (results[i].m_error_code != basisu::basis_compressor::cECSuccess)
encoded[i] = "error encoding image";
else if (!readFile(temp_outputs[i].c_str(), encoded[i]))
encoded[i] = "error reading temporary file";
}
for (size_t i = 0; i < data->images_count; ++i)
{
if (!temp_inputs[i].empty())
removeFile(temp_inputs[i].c_str());
if (!temp_outputs[i].empty())
removeFile(temp_outputs[i].c_str());
}
}
#endif
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
gltf/encodewebp.cpp | C++ | // This file is part of gltfpack; see gltfpack.h for version/license details
#ifdef WITH_LIBWEBP
#include "gltfpack.h"
#include "webp/decode.h"
#include "webp/encode.h"
#ifndef WITH_LIBWEBP_BASIS
#include "imageio/image_dec.h"
#endif
#include <atomic>
#include <memory>
#include <thread>
static int writeWebP(const uint8_t* data, size_t data_size, const WebPPicture* picture)
{
std::string* encoded = static_cast<std::string*>(picture->custom_ptr);
encoded->append(reinterpret_cast<const char*>(data), data_size);
return 1;
}
// when gltfpack is built with Basis Universal, we have easy access to its jpeg/png decoders
#ifdef WITH_LIBWEBP_BASIS
namespace pv_png
{
void* load_png(const void* pImage_buf, size_t buf_size, uint32_t desired_chans, uint32_t& width, uint32_t& height, uint32_t& num_chans);
} // namespace pv_png
namespace jpgd
{
static const uint32_t cFlagLinearChromaFiltering = 1;
unsigned char* decompress_jpeg_image_from_memory(const unsigned char* pSrc_data, int src_data_size, int* width, int* height, int* actual_comps, int req_comps, uint32_t flags = 0);
} // namespace jpgd
typedef int (*WebPImageReader)(const uint8_t* const data, size_t data_size, struct WebPPicture* const pic, int keep_alpha, struct Metadata* const metadata);
static int readPngBasis(const uint8_t* const data, size_t data_size, struct WebPPicture* const pic, int keep_alpha, struct Metadata* const metadata)
{
(void)keep_alpha;
(void)metadata;
uint32_t width = 0, height = 0, channels = 0;
void* img = pv_png::load_png(data, data_size, 4, width, height, channels);
if (!img)
return 0;
pic->width = width;
pic->height = height;
int ok = WebPPictureImportRGBA(pic, static_cast<uint8_t*>(img), width * 4);
free(img);
return ok;
}
static int readJpegBasis(const uint8_t* const data, size_t data_size, struct WebPPicture* const pic, int keep_alpha, struct Metadata* const metadata)
{
(void)keep_alpha;
(void)metadata;
int width = 0, height = 0, channels = 0;
unsigned char* img = jpgd::decompress_jpeg_image_from_memory(data, int(data_size), &width, &height, &channels, 4, jpgd::cFlagLinearChromaFiltering);
if (!img)
return 0;
pic->width = width;
pic->height = height;
int ok = WebPPictureImportRGBA(pic, img, width * 4);
free(img);
return ok;
}
#endif
static const char* encodeWebP(const cgltf_image& image, const char* input_path, const ImageInfo& info, const Settings& settings, std::string& encoded)
{
WebPConfig config;
if (!WebPConfigInit(&config))
return "error initializing WebP";
std::string img_data;
std::string mime_type;
if (!readImage(image, input_path, img_data, mime_type))
return "error reading source file";
if (mime_type != "image/png" && mime_type != "image/jpeg")
return NULL;
int width = 0, height = 0;
if (!getDimensions(img_data, mime_type.c_str(), width, height))
return "error parsing image header";
adjustDimensions(width, height, settings.texture_scale[info.kind], settings.texture_limit[info.kind], settings.texture_pow2);
#ifdef WITH_LIBWEBP_BASIS
WebPImageReader reader = (mime_type == "image/jpeg") ? readJpegBasis : readPngBasis;
#else
WebPInputFileFormat format = (mime_type == "image/jpeg") ? WEBP_JPEG_FORMAT : WEBP_PNG_FORMAT;
WebPImageReader reader = WebPGetImageReader(format);
if (!reader)
return "unsupported image format";
#endif
WebPPicture pic;
if (!WebPPictureInit(&pic))
return "error initializing picture";
std::unique_ptr<WebPPicture, void (*)(WebPPicture*)> pic_storage(&pic, WebPPictureFree);
if (!reader(reinterpret_cast<const uint8_t*>(img_data.data()), img_data.size(), &pic, 1, NULL))
return "error decoding source image";
if ((width != pic.width || height != pic.height) && !WebPPictureRescale(&pic, width, height))
return "error resizing image";
int quality = settings.texture_quality[info.kind];
if (info.normal_map)
config.quality = float(50 + quality * 5); // map 1-10 to 55-100
else
config.quality = float(20 + quality * 8); // map 1-10 to 28-100
config.emulate_jpeg_size = 1; // for flatter quality curve
pic.writer = writeWebP;
pic.custom_ptr = &encoded;
encoded.clear();
if (!WebPEncode(&config, &pic))
return "error encoding image";
return NULL;
}
void encodeImagesWebP(std::string* encoded, const cgltf_data* data, const std::vector<ImageInfo>& images, const char* input_path, const Settings& settings)
{
std::atomic<size_t> next_image{0};
auto encode = [&]()
{
for (;;)
{
size_t i = next_image++;
if (i >= data->images_count)
break;
const cgltf_image& image = data->images[i];
ImageInfo info = images[i];
if (settings.texture_mode[info.kind] == TextureMode_WebP)
if (const char* error = encodeWebP(image, input_path, info, settings, encoded[i]))
encoded[i] = error;
}
};
// we use main thread as a worker as well
size_t worker_count = settings.texture_jobs == 0 ? std::thread::hardware_concurrency() : settings.texture_jobs;
size_t thread_count = worker_count > 0 ? worker_count - 1 : 0;
std::vector<std::thread> threads;
for (size_t i = 0; i < thread_count; ++i)
threads.emplace_back(encode);
encode();
for (size_t i = 0; i < thread_count; ++i)
threads[i].join();
}
#endif
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
gltf/fileio.cpp | C++ | // This file is part of gltfpack; see gltfpack.h for version/license details
#include "gltfpack.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <process.h>
#else
#include <unistd.h>
#endif
std::string getTempPrefix()
{
#if defined(_WIN32)
const char* temp_dir = getenv("TEMP");
std::string path = temp_dir ? temp_dir : ".";
path += "\\gltfpack-temp";
path += std::to_string(_getpid());
return path;
#elif defined(__wasi__)
return "gltfpack-temp";
#else
std::string path = "/tmp/gltfpack-temp";
path += std::to_string(getpid());
return path;
#endif
}
std::string getFullPath(const char* path, const char* base_path)
{
std::string result = base_path;
std::string::size_type slash = result.find_last_of("/\\");
result.erase(slash == std::string::npos ? 0 : slash + 1);
result += path;
return result;
}
std::string getFileName(const char* path)
{
std::string result = path;
std::string::size_type slash = result.find_last_of("/\\");
if (slash != std::string::npos)
result.erase(0, slash + 1);
std::string::size_type dot = result.find_last_of('.');
if (dot != std::string::npos)
result.erase(dot);
return result;
}
std::string getExtension(const char* path)
{
std::string result = path;
std::string::size_type slash = result.find_last_of("/\\");
std::string::size_type dot = result.find_last_of('.');
if (slash != std::string::npos && dot != std::string::npos && dot < slash)
dot = std::string::npos;
result.erase(0, dot);
for (size_t i = 0; i < result.length(); ++i)
if (unsigned(result[i] - 'A') < 26)
result[i] = (result[i] - 'A') + 'a';
return result;
}
bool readFile(const char* path, std::string& data)
{
FILE* file = fopen(path, "rb");
if (!file)
return false;
fseek(file, 0, SEEK_END);
long length = ftell(file);
fseek(file, 0, SEEK_SET);
if (length <= 0)
{
fclose(file);
return false;
}
data.resize(length);
size_t result = fread(&data[0], 1, data.size(), file);
int rc = fclose(file);
return rc == 0 && result == data.size();
}
bool writeFile(const char* path, const std::string& data)
{
FILE* file = fopen(path, "wb");
if (!file)
return false;
size_t result = fwrite(&data[0], 1, data.size(), file);
int rc = fclose(file);
return rc == 0 && result == data.size();
}
void removeFile(const char* path)
{
remove(path);
}
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
gltf/gltfpack.cpp | C++ | // This file is part of gltfpack; see gltfpack.h for version/license details
#include "gltfpack.h"
#include <algorithm>
#include <unordered_map>
#include <locale.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __wasi__
#include <unistd.h>
#endif
#include "../src/meshoptimizer.h"
std::string getVersion()
{
char result[32];
snprintf(result, sizeof(result), "%d.%d", MESHOPTIMIZER_VERSION / 1000, (MESHOPTIMIZER_VERSION % 1000) / 10);
return result;
}
static void finalizeBufferViews(std::string& json, std::vector<BufferView>& views, std::string& bin, std::string* fallback, size_t& fallback_size, const char* meshopt_ext, int attribute_level)
{
for (size_t i = 0; i < views.size(); ++i)
{
BufferView& view = views[i];
size_t bin_offset = bin.size();
size_t fallback_offset = fallback_size;
size_t count = view.data.size() / view.stride;
if (view.compression == BufferView::Compression_None)
{
bin += view.data;
}
else
{
switch (view.compression)
{
case BufferView::Compression_Attribute:
compressVertexStream(bin, view.data, count, view.stride, attribute_level);
break;
case BufferView::Compression_Index:
compressIndexStream(bin, view.data, count, view.stride);
break;
case BufferView::Compression_IndexSequence:
compressIndexSequence(bin, view.data, count, view.stride);
break;
default:
assert(!"Unknown compression type");
}
if (fallback)
*fallback += view.data;
fallback_size += view.data.size();
}
size_t raw_offset = (view.compression != BufferView::Compression_None) ? fallback_offset : bin_offset;
comma(json);
writeBufferView(json, view.kind, view.filter, count, view.stride, raw_offset, view.data.size(), view.compression, bin_offset, bin.size() - bin_offset, meshopt_ext);
// record written bytes for statistics
view.bytes = bin.size() - bin_offset;
// align each bufferView by 4 bytes
bin.resize((bin.size() + 3) & ~3);
if (fallback)
fallback->resize((fallback->size() + 3) & ~3);
fallback_size = (fallback_size + 3) & ~3;
}
}
static void printMeshStats(const std::vector<Mesh>& meshes, const char* name)
{
size_t mesh_triangles = 0;
size_t mesh_vertices = 0;
size_t total_triangles = 0;
size_t total_instances = 0;
size_t total_draws = 0;
for (size_t i = 0; i < meshes.size(); ++i)
{
const Mesh& mesh = meshes[i];
size_t triangles = mesh.type == cgltf_primitive_type_triangles ? mesh.indices.size() / 3 : 0;
mesh_triangles += triangles;
mesh_vertices += mesh.streams.empty() ? 0 : mesh.streams[0].data.size();
size_t instances = std::max(size_t(1), mesh.nodes.size() + mesh.instances.size());
total_triangles += triangles * instances;
total_instances += instances;
total_draws += std::max(size_t(1), mesh.nodes.size());
}
printf("%s: %d mesh primitives (%d triangles, %d vertices); %d draw calls (%d instances, %lld triangles)\n", name,
int(meshes.size()), int(mesh_triangles), int(mesh_vertices),
int(total_draws), int(total_instances), (long long)total_triangles);
}
static void printSceneStats(const std::vector<BufferView>& views, const std::vector<Mesh>& meshes, size_t node_offset, size_t mesh_offset, size_t material_offset, size_t json_size, size_t bin_size)
{
size_t bytes[BufferView::Kind_Count] = {};
for (size_t i = 0; i < views.size(); ++i)
{
const BufferView& view = views[i];
bytes[view.kind] += view.bytes;
}
printf("output: %d nodes, %d meshes (%d primitives), %d materials\n", int(node_offset), int(mesh_offset), int(meshes.size()), int(material_offset));
printf("output: JSON %d bytes, buffers %d bytes\n", int(json_size), int(bin_size));
printf("output: buffers: vertex %d bytes, index %d bytes, skin %d bytes, time %d bytes, keyframe %d bytes, instance %d bytes, image %d bytes\n",
int(bytes[BufferView::Kind_Vertex]), int(bytes[BufferView::Kind_Index]), int(bytes[BufferView::Kind_Skin]),
int(bytes[BufferView::Kind_Time]), int(bytes[BufferView::Kind_Keyframe]), int(bytes[BufferView::Kind_Instance]),
int(bytes[BufferView::Kind_Image]));
}
static void printAttributeStats(const std::vector<BufferView>& views, BufferView::Kind kind, const char* name)
{
for (size_t i = 0; i < views.size(); ++i)
{
const BufferView& view = views[i];
if (view.kind != kind)
continue;
const char* variant = "unknown";
switch (kind)
{
case BufferView::Kind_Vertex:
variant = attributeType(cgltf_attribute_type(view.variant));
break;
case BufferView::Kind_Index:
variant = "index";
break;
case BufferView::Kind_Keyframe:
case BufferView::Kind_Instance:
variant = animationPath(cgltf_animation_path_type(view.variant));
break;
default:;
}
size_t count = view.data.size() / view.stride;
if (view.compression == BufferView::Compression_None)
printf("stats: %s %s: %d bytes (%.1f bits)\n",
name, variant, int(view.bytes), double(view.bytes) / double(count) * 8);
else
printf("stats: %s %s: compressed %d bytes (%.1f bits), raw %d bytes (%d bits)\n",
name, variant,
int(view.bytes), double(view.bytes) / double(count) * 8,
int(view.data.size()), int(view.stride * 8));
}
}
static void printImageStats(const std::vector<BufferView>& views, TextureKind kind, const char* name)
{
size_t bytes = 0;
size_t count = 0;
for (size_t i = 0; i < views.size(); ++i)
{
const BufferView& view = views[i];
if (view.kind != BufferView::Kind_Image)
continue;
if (view.variant != -1 - kind)
continue;
count += 1;
bytes += view.data.size();
}
if (count)
printf("stats: image %s: %d bytes in %d images\n", name, int(bytes), int(count));
}
static bool printReport(const char* path, const std::vector<BufferView>& views, const std::vector<Mesh>& meshes, size_t node_count, size_t mesh_count, size_t texture_count, size_t material_count, size_t animation_count, size_t json_size, size_t bin_size)
{
size_t bytes[BufferView::Kind_Count] = {};
for (size_t i = 0; i < views.size(); ++i)
{
const BufferView& view = views[i];
bytes[view.kind] += view.bytes;
}
size_t total_triangles = 0;
size_t total_instances = 0;
size_t total_draws = 0;
for (size_t i = 0; i < meshes.size(); ++i)
{
const Mesh& mesh = meshes[i];
size_t triangles = mesh.type == cgltf_primitive_type_triangles ? mesh.indices.size() / 3 : 0;
size_t instances = std::max(size_t(1), mesh.nodes.size() + mesh.instances.size());
total_triangles += triangles * instances;
total_instances += instances;
total_draws += std::max(size_t(1), mesh.nodes.size());
}
FILE* out = fopen(path, "wb");
if (!out)
return false;
fprintf(out, "{\n");
fprintf(out, "\t\"generator\": \"gltfpack %s\",\n", getVersion().c_str());
fprintf(out, "\t\"scene\": {\n");
fprintf(out, "\t\t\"nodeCount\": %d,\n", int(node_count));
fprintf(out, "\t\t\"meshCount\": %d,\n", int(mesh_count));
fprintf(out, "\t\t\"materialCount\": %d,\n", int(material_count));
fprintf(out, "\t\t\"textureCount\": %d,\n", int(texture_count));
fprintf(out, "\t\t\"animationCount\": %d\n", int(animation_count));
fprintf(out, "\t},\n");
fprintf(out, "\t\"render\": {\n");
fprintf(out, "\t\t\"drawCount\": %d,\n", int(total_draws));
fprintf(out, "\t\t\"instanceCount\": %d,\n", int(total_instances));
fprintf(out, "\t\t\"triangleCount\": %lld\n", (long long)total_triangles);
fprintf(out, "\t},\n");
fprintf(out, "\t\"data\": {\n");
fprintf(out, "\t\t\"json\": %d,\n", int(json_size));
fprintf(out, "\t\t\"binary\": %d,\n", int(bin_size));
fprintf(out, "\t\t\"buffers\": {\n");
fprintf(out, "\t\t\t\"vertex\": %d,\n", int(bytes[BufferView::Kind_Vertex]));
fprintf(out, "\t\t\t\"index\": %d,\n", int(bytes[BufferView::Kind_Index]));
fprintf(out, "\t\t\t\"animation\": %d,\n", int(bytes[BufferView::Kind_Time] + bytes[BufferView::Kind_Keyframe]));
fprintf(out, "\t\t\t\"transform\": %d,\n", int(bytes[BufferView::Kind_Skin] + bytes[BufferView::Kind_Instance]));
fprintf(out, "\t\t\t\"image\": %d\n", int(bytes[BufferView::Kind_Image]));
fprintf(out, "\t\t}\n");
fprintf(out, "\t}\n");
fprintf(out, "}\n");
int rc = fclose(out);
return rc == 0;
}
static bool canTransformMesh(const Mesh& mesh)
{
// volume thickness is specified in mesh coordinate space; to avoid modifying materials we prohibit transforming meshes with volume materials
if (mesh.material && mesh.material->has_volume && mesh.material->volume.thickness_factor > 0.f)
return false;
return true;
}
static void detachMesh(Mesh& mesh, cgltf_data* data, const std::vector<NodeInfo>& nodes, const Settings& settings)
{
// mesh is already instanced, skip
if (!mesh.instances.empty())
return;
// mesh is already world space, skip
if (mesh.nodes.empty())
return;
// note: when -kn is specified, we keep mesh-node attachment so that named nodes can be transformed
if (settings.keep_nodes)
return;
// we keep skinned meshes or meshes with morph targets as is
// in theory we could transform both, but in practice transforming morph target meshes is more involved,
// and reparenting skinned meshes leads to incorrect bounding box generated in three.js
if (mesh.skin || mesh.targets)
return;
bool any_animated = false;
for (size_t j = 0; j < mesh.nodes.size(); ++j)
any_animated |= nodes[mesh.nodes[j] - data->nodes].animated;
// animated meshes will be anchored to the same node that they used to be in to retain the animation
if (any_animated)
return;
int scene = nodes[mesh.nodes[0] - data->nodes].scene;
bool any_other_scene = false;
for (size_t j = 0; j < mesh.nodes.size(); ++j)
any_other_scene |= scene != nodes[mesh.nodes[j] - data->nodes].scene;
// we only merge instances when all nodes have a single consistent scene
if (scene < 0 || any_other_scene)
return;
// we only merge multiple instances together if requested
// this often makes the scenes faster to render by reducing the draw call count, but can result in larger files
if (mesh.nodes.size() > 1 && !settings.mesh_merge && !settings.mesh_instancing)
return;
// mesh has duplicate geometry; detaching it would increase the size due to unique world-space transforms
if (mesh.nodes.size() == 1 && mesh.geometry_duplicate && !settings.mesh_merge)
return;
// prefer instancing if possible, use merging otherwise
if (mesh.nodes.size() > 1 && settings.mesh_instancing)
{
mesh.instances.resize(mesh.nodes.size());
for (size_t j = 0; j < mesh.nodes.size(); ++j)
{
Instance& obj = mesh.instances[j];
cgltf_node_transform_world(mesh.nodes[j], obj.transform);
obj.color[0] = obj.color[1] = obj.color[2] = obj.color[3] = 1.0f;
}
mesh.nodes.clear();
mesh.scene = scene;
}
else if (canTransformMesh(mesh))
{
mergeMeshInstances(mesh);
assert(mesh.nodes.empty());
mesh.scene = scene;
}
}
static bool isExtensionSupported(const ExtensionInfo* extensions, size_t count, const char* name)
{
for (size_t i = 0; i < count; ++i)
if (strcmp(extensions[i].name, name) == 0)
return true;
return false;
}
namespace std
{
template <>
struct hash<std::pair<uint64_t, uint64_t> >
{
size_t operator()(const std::pair<uint64_t, uint64_t>& x) const
{
return std::hash<uint64_t>()(x.first ^ x.second);
}
};
} // namespace std
static size_t process(cgltf_data* data, const char* input_path, const char* output_path, const char* report_path, std::vector<Mesh>& meshes, std::vector<Animation>& animations, const Settings& settings, std::string& json, std::string& bin, std::string& fallback, size_t& fallback_size, const char* meshopt_ext)
{
if (settings.verbose)
{
printf("input: %d nodes, %d meshes (%d primitives), %d materials, %d skins, %d animations, %d images\n",
int(data->nodes_count), int(data->meshes_count), int(meshes.size()), int(data->materials_count), int(data->skins_count), int(animations.size()), int(data->images_count));
printMeshStats(meshes, "input");
}
for (size_t i = 0; i < animations.size(); ++i)
processAnimation(animations[i], settings);
std::vector<NodeInfo> nodes(data->nodes_count);
markScenes(data, nodes);
markAnimated(data, nodes, animations);
mergeMeshMaterials(data, meshes, settings);
if (settings.mesh_dedup)
dedupMeshes(meshes, settings);
for (size_t i = 0; i < meshes.size(); ++i)
detachMesh(meshes[i], data, nodes, settings);
// material information is required for mesh and image processing
std::vector<MaterialInfo> materials(data->materials_count);
std::vector<TextureInfo> textures(data->textures_count);
std::vector<ImageInfo> images(data->images_count);
// mark materials that need to keep blending due to mesh vertex colors
for (size_t i = 0; i < meshes.size(); ++i)
{
Mesh& mesh = meshes[i];
// skip hasAlpha check unless it's required
if ((((mesh.material && mesh.material->alpha_mode != cgltf_alpha_mode_opaque) || mesh.variants.size()) && hasVertexAlpha(mesh)) || hasInstanceAlpha(mesh.instances))
{
if (mesh.material)
materials[mesh.material - data->materials].mesh_alpha = true;
for (size_t j = 0; j < mesh.variants.size(); ++j)
materials[mesh.variants[j].material - data->materials].mesh_alpha = true;
}
}
analyzeMaterials(data, materials, textures, images);
mergeTextures(data, textures);
optimizeMaterials(data, materials, images, input_path);
// streams need to be filtered before mesh merging (or processing) to make sure we can merge meshes with redundant streams
for (size_t i = 0; i < meshes.size(); ++i)
{
Mesh& mesh = meshes[i];
MaterialInfo mi = mesh.material ? materials[mesh.material - data->materials] : MaterialInfo();
// merge material requirements across all variants
for (size_t j = 0; j < mesh.variants.size(); ++j)
{
MaterialInfo vi = materials[mesh.variants[j].material - data->materials];
mi.needs_tangents |= vi.needs_tangents;
mi.texture_set_mask |= vi.texture_set_mask;
mi.unlit &= vi.unlit;
}
if (!settings.keep_attributes)
filterStreams(mesh, mi);
}
mergeMeshes(meshes, settings);
filterEmptyMeshes(meshes);
markNeededNodes(data, nodes, meshes, animations, settings);
markNeededMaterials(data, materials, meshes, settings);
if (settings.simplify_scaled && settings.simplify_ratio < 1)
computeMeshQuality(meshes);
for (size_t i = 0; i < meshes.size(); ++i)
{
Mesh& mesh = meshes[i];
processMesh(mesh, settings);
if (mesh.geometry_duplicate)
hashMesh(mesh);
}
filterEmptyMeshes(meshes); // some meshes may become empty after processing
QuantizationPosition qp = prepareQuantizationPosition(meshes, settings);
std::vector<QuantizationTexture> qt_materials(materials.size());
std::vector<size_t> qt_meshes(meshes.size(), size_t(-1));
prepareQuantizationTexture(data, qt_materials, qt_meshes, meshes, settings);
QuantizationTexture qt_dummy = {};
qt_dummy.bits = settings.tex_bits;
std::string json_images;
std::string json_samplers;
std::string json_textures;
std::string json_materials;
std::string json_accessors;
std::string json_meshes;
std::string json_nodes;
std::string json_skins;
std::vector<std::string> json_roots(data->scenes_count);
std::string json_animations;
std::string json_cameras;
std::string json_extensions;
std::vector<BufferView> views;
bool ext_pbr_specular_glossiness = false;
bool ext_clearcoat = false;
bool ext_transmission = false;
bool ext_ior = false;
bool ext_specular = false;
bool ext_sheen = false;
bool ext_volume = false;
bool ext_emissive_strength = false;
bool ext_iridescence = false;
bool ext_anisotropy = false;
bool ext_dispersion = false;
bool ext_diffuse_transmission = false;
bool ext_unlit = false;
bool ext_instancing = false;
bool ext_texture_transform = false;
bool ext_texture_basisu = false;
bool ext_texture_webp = false;
size_t accr_offset = 0;
size_t node_offset = 0;
size_t mesh_offset = 0;
size_t texture_offset = 0;
size_t material_offset = 0;
for (size_t i = 0; i < data->samplers_count; ++i)
{
const cgltf_sampler& sampler = data->samplers[i];
comma(json_samplers);
append(json_samplers, "{");
writeSampler(json_samplers, sampler);
append(json_samplers, "}");
}
std::vector<std::string> encoded_images(data->images_count);
#ifdef WITH_BASISU
if (data->images_count && settings.texture_ktx2)
encodeImagesBasis(encoded_images.data(), data, images, input_path, settings);
#endif
#ifdef WITH_LIBWEBP
if (data->images_count && settings.texture_webp)
encodeImagesWebP(encoded_images.data(), data, images, input_path, settings);
#endif
for (size_t i = 0; i < data->images_count; ++i)
{
const cgltf_image& image = data->images[i];
std::string* encoded = !encoded_images[i].empty() ? &encoded_images[i] : NULL;
comma(json_images);
append(json_images, "{");
writeImage(json_images, views, image, images[i], encoded, i, input_path, output_path, settings);
append(json_images, "}");
if (encoded)
*encoded = std::string(); // reclaim memory early
}
for (size_t i = 0; i < data->textures_count; ++i)
{
const cgltf_texture& texture = data->textures[i];
if (!textures[i].keep)
continue;
comma(json_textures);
append(json_textures, "{");
writeTexture(json_textures, texture, texture.image ? &images[texture.image - data->images] : NULL, data, settings);
append(json_textures, "}");
assert(textures[i].remap == int(texture_offset));
texture_offset++;
ext_texture_basisu = ext_texture_basisu || texture.has_basisu;
ext_texture_webp = ext_texture_webp || texture.has_webp;
}
for (size_t i = 0; i < data->materials_count; ++i)
{
MaterialInfo& mi = materials[i];
if (!mi.keep)
continue;
const cgltf_material& material = data->materials[i];
comma(json_materials);
append(json_materials, "{");
writeMaterial(json_materials, data, material, settings.quantize && !settings.pos_float ? &qp : NULL, settings.quantize && !settings.tex_float ? &qt_materials[i] : NULL, textures);
if (settings.keep_extras)
writeExtras(json_materials, material.extras);
append(json_materials, "}");
mi.remap = int(material_offset);
material_offset++;
ext_pbr_specular_glossiness = ext_pbr_specular_glossiness || material.has_pbr_specular_glossiness;
ext_clearcoat = ext_clearcoat || material.has_clearcoat;
ext_transmission = ext_transmission || material.has_transmission;
ext_ior = ext_ior || material.has_ior;
ext_specular = ext_specular || material.has_specular;
ext_sheen = ext_sheen || material.has_sheen;
ext_volume = ext_volume || material.has_volume;
ext_emissive_strength = ext_emissive_strength || material.has_emissive_strength;
ext_iridescence = ext_iridescence || material.has_iridescence;
ext_diffuse_transmission = ext_diffuse_transmission || material.has_diffuse_transmission;
ext_anisotropy = ext_anisotropy || material.has_anisotropy;
ext_dispersion = ext_dispersion || material.has_dispersion;
ext_unlit = ext_unlit || material.unlit;
ext_texture_transform = ext_texture_transform || mi.uses_texture_transform;
}
std::unordered_map<std::pair<uint64_t, uint64_t>, std::pair<size_t, size_t> > primitive_cache;
for (size_t i = 0; i < meshes.size(); ++i)
{
const Mesh& mesh = meshes[i];
comma(json_meshes);
append(json_meshes, "{\"primitives\":[");
size_t pi = i;
for (; pi < meshes.size(); ++pi)
{
const Mesh& prim = meshes[pi];
if (prim.scene != mesh.scene || prim.skin != mesh.skin || prim.targets != mesh.targets)
break;
if (pi > i && (mesh.instances.size() || prim.instances.size()))
break;
if (!compareMeshNodes(mesh, prim))
break;
if (!compareMeshTargets(mesh, prim))
break;
const QuantizationTexture& qt = qt_meshes[pi] == size_t(-1) ? qt_dummy : qt_materials[qt_meshes[pi]];
comma(json_meshes);
if (prim.geometry_duplicate)
{
std::pair<size_t, size_t>& primitive_json = primitive_cache[std::make_pair(prim.geometry_hash[0], prim.geometry_hash[1])];
if (primitive_json.second)
{
// reuse previously written accessors
json_meshes.append(json_meshes, primitive_json.first, primitive_json.second);
}
else
{
primitive_json.first = json_meshes.size();
writeMeshGeometry(json_meshes, views, json_accessors, accr_offset, prim, qp, qt, settings);
primitive_json.second = json_meshes.size() - primitive_json.first;
}
}
else
{
writeMeshGeometry(json_meshes, views, json_accessors, accr_offset, prim, qp, qt, settings);
}
if (prim.material)
{
MaterialInfo& mi = materials[prim.material - data->materials];
assert(mi.keep);
append(json_meshes, ",\"material\":");
append(json_meshes, size_t(mi.remap));
}
if (prim.variants.size())
{
append(json_meshes, ",\"extensions\":{\"KHR_materials_variants\":{\"mappings\":[");
for (size_t j = 0; j < prim.variants.size(); ++j)
{
const cgltf_material_mapping& variant = prim.variants[j];
MaterialInfo& mi = materials[variant.material - data->materials];
assert(mi.keep);
comma(json_meshes);
append(json_meshes, "{\"material\":");
append(json_meshes, size_t(mi.remap));
append(json_meshes, ",\"variants\":[");
append(json_meshes, size_t(variant.variant));
append(json_meshes, "]}");
}
append(json_meshes, "]}}");
}
if (settings.keep_extras)
writeExtras(json_meshes, prim.extras);
append(json_meshes, "}");
}
append(json_meshes, "]");
if (mesh.target_weights.size())
{
append(json_meshes, ",\"weights\":");
append(json_meshes, mesh.target_weights.data(), mesh.target_weights.size());
}
if (mesh.target_names.size())
{
append(json_meshes, ",\"extras\":{\"targetNames\":[");
for (size_t j = 0; j < mesh.target_names.size(); ++j)
{
comma(json_meshes);
append(json_meshes, "\"");
append(json_meshes, mesh.target_names[j]);
append(json_meshes, "\"");
}
append(json_meshes, "]}");
}
append(json_meshes, "}");
if (mesh.nodes.size())
{
for (size_t j = 0; j < mesh.nodes.size(); ++j)
{
NodeInfo& ni = nodes[mesh.nodes[j] - data->nodes];
assert(ni.keep);
// if we don't use position quantization, prefer attaching the mesh to its node directly
if (!ni.has_mesh && (!settings.quantize || settings.pos_float || (qp.offset[0] == 0.f && qp.offset[1] == 0.f && qp.offset[2] == 0 && qp.node_scale == 1.f)))
{
ni.has_mesh = true;
ni.mesh_index = mesh_offset;
ni.mesh_skin = mesh.skin;
}
else
{
ni.mesh_nodes.push_back(node_offset);
writeMeshNode(json_nodes, mesh_offset, mesh.nodes[j], mesh.skin, data, settings.quantize && !settings.pos_float ? &qp : NULL);
node_offset++;
}
}
}
if (mesh.instances.size())
{
assert(mesh.scene >= 0);
comma(json_roots[mesh.scene]);
append(json_roots[mesh.scene], node_offset);
bool has_color = false;
for (const Instance& instance : mesh.instances)
has_color |= (instance.color[0] != 1.f || instance.color[1] != 1.f || instance.color[2] != 1.f || instance.color[3] != 1.f);
size_t instance_accr = writeInstances(views, json_accessors, accr_offset, mesh.instances, qp, has_color, settings);
assert(!mesh.skin);
writeMeshNodeInstanced(json_nodes, mesh_offset, instance_accr, has_color);
node_offset++;
}
if (mesh.nodes.empty() && mesh.instances.empty())
{
assert(mesh.scene >= 0);
comma(json_roots[mesh.scene]);
append(json_roots[mesh.scene], node_offset);
writeMeshNode(json_nodes, mesh_offset, NULL, mesh.skin, data, settings.quantize && !settings.pos_float ? &qp : NULL);
node_offset++;
}
mesh_offset++;
ext_instancing = ext_instancing || !mesh.instances.empty();
// skip all meshes that we've written in this iteration
assert(pi > i);
i = pi - 1;
}
remapNodes(data, nodes, node_offset);
for (size_t i = 0; i < data->nodes_count; ++i)
{
NodeInfo& ni = nodes[i];
if (!ni.keep)
continue;
const cgltf_node& node = data->nodes[i];
comma(json_nodes);
append(json_nodes, "{");
writeNode(json_nodes, node, nodes, data);
if (settings.keep_extras)
writeExtras(json_nodes, node.extras);
append(json_nodes, "}");
}
for (size_t i = 0; i < data->scenes_count; ++i)
{
for (size_t j = 0; j < data->scenes[i].nodes_count; ++j)
{
NodeInfo& ni = nodes[data->scenes[i].nodes[j] - data->nodes];
if (ni.keep)
{
comma(json_roots[i]);
append(json_roots[i], size_t(ni.remap));
}
}
}
for (size_t i = 0; i < data->skins_count; ++i)
{
const cgltf_skin& skin = data->skins[i];
size_t matrix_accr = writeJointBindMatrices(views, json_accessors, accr_offset, skin, qp, settings);
writeSkin(json_skins, skin, matrix_accr, nodes, data);
}
for (size_t i = 0; i < animations.size(); ++i)
{
const Animation& animation = animations[i];
writeAnimation(json_animations, views, json_accessors, accr_offset, animation, i, data, nodes, settings);
}
for (size_t i = 0; i < data->cameras_count; ++i)
{
const cgltf_camera& camera = data->cameras[i];
writeCamera(json_cameras, camera);
}
if (data->lights_count > 0)
{
comma(json_extensions);
append(json_extensions, "\"KHR_lights_punctual\":{\"lights\":[");
for (size_t i = 0; i < data->lights_count; ++i)
{
const cgltf_light& light = data->lights[i];
writeLight(json_extensions, light);
}
append(json_extensions, "]}");
}
if (data->variants_count > 0)
{
comma(json_extensions);
append(json_extensions, "\"KHR_materials_variants\":{\"variants\":[");
for (size_t i = 0; i < data->variants_count; ++i)
{
const cgltf_material_variant& variant = data->variants[i];
comma(json_extensions);
append(json_extensions, "{\"name\":\"");
append(json_extensions, variant.name);
append(json_extensions, "\"}");
}
append(json_extensions, "]}");
}
append(json, "\"asset\":{");
append(json, "\"version\":\"2.0\",\"generator\":\"gltfpack ");
append(json, getVersion());
append(json, "\"");
writeExtras(json, data->asset.extras);
append(json, "}");
const ExtensionInfo extensions[] = {
{"KHR_mesh_quantization", settings.quantize, true},
{meshopt_ext, settings.compress, !settings.fallback},
{"KHR_texture_transform", (settings.quantize && !settings.tex_float && !json_textures.empty()) || ext_texture_transform, false},
{"KHR_materials_pbrSpecularGlossiness", ext_pbr_specular_glossiness, false},
{"KHR_materials_clearcoat", ext_clearcoat, false},
{"KHR_materials_transmission", ext_transmission, false},
{"KHR_materials_ior", ext_ior, false},
{"KHR_materials_specular", ext_specular, false},
{"KHR_materials_sheen", ext_sheen, false},
{"KHR_materials_volume", ext_volume, false},
{"KHR_materials_emissive_strength", ext_emissive_strength, false},
{"KHR_materials_iridescence", ext_iridescence, false},
{"KHR_materials_anisotropy", ext_anisotropy, false},
{"KHR_materials_dispersion", ext_dispersion, false},
{"KHR_materials_diffuse_transmission", ext_diffuse_transmission, false},
{"KHR_materials_unlit", ext_unlit, false},
{"KHR_materials_variants", data->variants_count > 0, false},
{"KHR_lights_punctual", data->lights_count > 0, false},
{"KHR_texture_basisu", (!json_textures.empty() && settings.texture_ktx2) || ext_texture_basisu, true},
{"EXT_texture_webp", (!json_textures.empty() && settings.texture_webp) || ext_texture_webp, true},
{"EXT_mesh_gpu_instancing", ext_instancing, true},
};
for (size_t i = 0; i < data->extensions_required_count; ++i)
{
const char* ext = data->extensions_required[i];
if (!isExtensionSupported(extensions, sizeof(extensions) / sizeof(extensions[0]), ext) && strstr(ext, "_meshopt_compression") == NULL)
fprintf(stderr, "Warning: required extension %s is not supported and will be skipped\n", ext);
}
writeExtensions(json, extensions, sizeof(extensions) / sizeof(extensions[0]));
// buffers[] array to be inserted by the caller
size_t bufferspec_pos = json.size();
std::string json_views;
finalizeBufferViews(json_views, views, bin, settings.fallback ? &fallback : NULL, fallback_size, meshopt_ext, settings.compresskhr ? (settings.compressmore ? 3 : 2) : 0);
writeArray(json, "bufferViews", json_views);
writeArray(json, "accessors", json_accessors);
writeArray(json, "samplers", json_samplers);
writeArray(json, "images", json_images);
writeArray(json, "textures", json_textures);
writeArray(json, "materials", json_materials);
writeArray(json, "meshes", json_meshes);
writeArray(json, "skins", json_skins);
writeArray(json, "animations", json_animations);
writeArray(json, "nodes", json_nodes);
if (!json_roots.empty())
{
append(json, ",\"scenes\":[");
for (size_t i = 0; i < data->scenes_count; ++i)
writeScene(json, data->scenes[i], json_roots[i], settings);
append(json, "]");
}
writeArray(json, "cameras", json_cameras);
if (data->scene)
{
append(json, ",\"scene\":");
append(json, size_t(data->scene - data->scenes));
}
if (!json_extensions.empty())
{
append(json, ",\"extensions\":{");
append(json, json_extensions);
append(json, "}");
}
if (settings.verbose)
{
printMeshStats(meshes, "output");
printSceneStats(views, meshes, node_offset, mesh_offset, material_offset, json.size(), bin.size());
}
if (settings.verbose > 1)
{
printAttributeStats(views, BufferView::Kind_Vertex, "vertex");
printAttributeStats(views, BufferView::Kind_Index, "index");
printAttributeStats(views, BufferView::Kind_Keyframe, "keyframe");
printAttributeStats(views, BufferView::Kind_Instance, "instance");
printImageStats(views, TextureKind_Generic, "generic");
printImageStats(views, TextureKind_Color, "color");
printImageStats(views, TextureKind_Normal, "normal");
printImageStats(views, TextureKind_Attrib, "attrib");
}
if (report_path)
{
if (!printReport(report_path, views, meshes, node_offset, mesh_offset, texture_offset, material_offset, animations.size(), json.size(), bin.size()))
{
fprintf(stderr, "Warning: cannot save report to %s\n", report_path);
}
}
return bufferspec_pos;
}
static void writeU32(FILE* out, uint32_t data)
{
fwrite(&data, 4, 1, out);
}
static const char* getBaseName(const char* path)
{
const char* slash = strrchr(path, '/');
const char* backslash = strrchr(path, '\\');
const char* rs = slash ? slash + 1 : path;
const char* bs = backslash ? backslash + 1 : path;
return std::max(rs, bs);
}
static std::string getBufferSpec(const char* bin_path, size_t bin_size, const char* fallback_path, size_t fallback_size, bool fallback_ref, const char* meshopt_ext)
{
std::string json;
append(json, "\"buffers\":[");
append(json, "{");
if (bin_path)
{
append(json, "\"uri\":\"");
append(json, bin_path);
append(json, "\"");
}
comma(json);
append(json, "\"byteLength\":");
append(json, bin_size);
append(json, "}");
if (fallback_ref)
{
comma(json);
append(json, "{");
if (fallback_path)
{
append(json, "\"uri\":\"");
append(json, fallback_path);
append(json, "\"");
}
comma(json);
append(json, "\"byteLength\":");
append(json, fallback_size);
append(json, ",\"extensions\":{");
append(json, "\"");
append(json, meshopt_ext);
append(json, "\":{");
append(json, "\"fallback\":true");
append(json, "}}");
append(json, "}");
}
append(json, "]");
return json;
}
int gltfpack(const char* input, const char* output, const char* report, Settings settings)
{
cgltf_data* data = NULL;
std::vector<Mesh> meshes;
std::vector<Animation> animations;
std::string iext = getExtension(input);
std::string oext = output ? getExtension(output) : "";
if (output)
{
if (oext != ".gltf" && oext != ".glb")
{
fprintf(stderr, "Error: unsupported output extension '%s' (expected .gltf or .glb)\n", oext.c_str());
return 4;
}
}
if (iext == ".gltf" || iext == ".glb")
{
const char* error = NULL;
data = parseGltf(input, meshes, animations, &error);
if (error)
{
fprintf(stderr, "Error loading %s: %s\n", input, error);
return 2;
}
}
else if (iext == ".obj")
{
const char* error = NULL;
data = parseObj(input, meshes, &error);
if (!data)
{
fprintf(stderr, "Error loading %s: %s\n", input, error);
return 2;
}
}
else
{
fprintf(stderr, "Error loading %s: unknown extension (expected .gltf or .glb or .obj)\n", input);
return 2;
}
#ifndef WITH_BASISU
if (data->images_count && settings.texture_ktx2)
{
fprintf(stderr, "Error: gltfpack was built without BasisU support, texture compression is not available\n");
#ifdef __wasi__
fprintf(stderr, "Note: node.js builds do not support BasisU due to lack of platform features; download a native build from https://github.com/zeux/meshoptimizer/releases\n");
#endif
return 3;
}
#endif
#ifndef WITH_LIBWEBP
if (data->images_count && settings.texture_webp)
{
fprintf(stderr, "Error: gltfpack was built without WebP support, texture compression is not available\n");
#ifdef __wasi__
fprintf(stderr, "Note: node.js builds do not support WebP due to lack of platform features; download a native build from https://github.com/zeux/meshoptimizer/releases\n");
#endif
return 3;
}
#endif
if (oext == ".glb")
{
settings.texture_embed = true;
}
if (data->images_count && !settings.texture_ref && !settings.texture_embed)
{
for (size_t i = 0; i < data->images_count; ++i)
{
const char* uri = data->images[i].uri;
if (!uri || strncmp(uri, "data:", 5) == 0)
continue;
for (size_t j = 0; j < i; ++j)
{
const char* urj = data->images[j].uri;
if (!urj || strncmp(urj, "data:", 5) == 0)
continue;
if (strcmp(uri, urj) != 0 && strcmp(getBaseName(uri), getBaseName(urj)) == 0)
{
fprintf(stderr, "Warning: images %s and %s share the same base name and will overwrite each other\n", uri, urj);
break;
}
}
}
}
const char* meshopt_ext = settings.compresskhr ? "KHR_meshopt_compression" : "EXT_meshopt_compression";
std::string json, bin, fallback;
size_t fallback_size = 0;
json += '{';
size_t bufferspec_pos = process(data, input, output, report, meshes, animations, settings, json, bin, fallback, fallback_size, meshopt_ext);
json += '}';
cgltf_free(data);
if (!output)
{
return 0;
}
if (oext == ".gltf")
{
std::string binpath = output;
binpath.replace(binpath.size() - 5, 5, ".bin");
std::string fbpath = output;
fbpath.replace(fbpath.size() - 5, 5, ".fallback.bin");
FILE* outjson = fopen(output, "wb");
FILE* outbin = fopen(binpath.c_str(), "wb");
FILE* outfb = settings.fallback ? fopen(fbpath.c_str(), "wb") : NULL;
if (!outjson || !outbin || (!outfb && settings.fallback))
{
fprintf(stderr, "Error saving %s\n", output);
return 4;
}
std::string bufferspec = getBufferSpec(getBaseName(binpath.c_str()), bin.size(), settings.fallback ? getBaseName(fbpath.c_str()) : NULL, fallback_size, settings.compress, meshopt_ext);
json.insert(bufferspec_pos, "," + bufferspec);
fwrite(json.c_str(), json.size(), 1, outjson);
fwrite(bin.c_str(), bin.size(), 1, outbin);
if (settings.fallback)
fwrite(fallback.c_str(), fallback.size(), 1, outfb);
int rc = 0;
rc |= fclose(outjson);
rc |= fclose(outbin);
if (outfb)
rc |= fclose(outfb);
if (rc)
{
fprintf(stderr, "Error saving %s\n", output);
return 4;
}
}
else if (oext == ".glb")
{
std::string fbpath = output;
fbpath.replace(fbpath.size() - 4, 4, ".fallback.bin");
FILE* out = fopen(output, "wb");
FILE* outfb = settings.fallback ? fopen(fbpath.c_str(), "wb") : NULL;
if (!out || (!outfb && settings.fallback))
{
fprintf(stderr, "Error saving %s\n", output);
return 4;
}
std::string bufferspec = getBufferSpec(NULL, bin.size(), settings.fallback ? getBaseName(fbpath.c_str()) : NULL, fallback_size, settings.compress, meshopt_ext);
json.insert(bufferspec_pos, "," + bufferspec);
while (json.size() % 4)
json.push_back(' ');
while (bin.size() % 4)
bin.push_back('\0');
writeU32(out, 0x46546C67);
writeU32(out, 2);
writeU32(out, uint32_t(12 + 8 + json.size() + 8 + bin.size()));
writeU32(out, uint32_t(json.size()));
writeU32(out, 0x4E4F534A);
fwrite(json.c_str(), json.size(), 1, out);
writeU32(out, uint32_t(bin.size()));
writeU32(out, 0x004E4942);
fwrite(bin.c_str(), bin.size(), 1, out);
if (settings.fallback)
fwrite(fallback.c_str(), fallback.size(), 1, outfb);
int rc = 0;
rc |= fclose(out);
if (outfb)
rc |= fclose(outfb);
if (rc)
{
fprintf(stderr, "Error saving %s\n", output);
return 4;
}
}
else
{
fprintf(stderr, "Error saving %s: unknown extension (expected .gltf or .glb)\n", output);
return 4;
}
return 0;
}
Settings defaults()
{
Settings settings = {};
settings.quantize = true;
settings.pos_bits = 14;
settings.tex_bits = 12;
settings.nrm_bits = 8;
settings.col_bits = 8;
settings.trn_bits = 16;
settings.rot_bits = 12;
settings.scl_bits = 16;
settings.anim_freq = 30;
settings.mesh_dedup = true;
settings.simplify_ratio = 1.f;
settings.simplify_error = 1e-2f;
settings.simplify_attributes = true;
settings.simplify_scaled = true;
for (int kind = 0; kind < TextureKind__Count; ++kind)
{
settings.texture_mode[kind] = TextureMode_Raw;
settings.texture_scale[kind] = 1.f;
settings.texture_quality[kind] = 8;
}
return settings;
}
template <typename T>
T clamp(T v, T min, T max)
{
return v < min ? min : (v > max ? max : v);
}
unsigned int textureMask(const char* arg)
{
unsigned int result = 0;
while (arg)
{
const char* comma = strchr(arg, ',');
size_t seg = comma ? comma - arg - 1 : strlen(arg);
if (strncmp(arg, "color", seg) == 0)
result |= 1 << TextureKind_Color;
else if (strncmp(arg, "normal", seg) == 0)
result |= 1 << TextureKind_Normal;
else if (strncmp(arg, "attrib", seg) == 0)
result |= 1 << TextureKind_Attrib;
else
fprintf(stderr, "Warning: unrecognized texture class %.*s\n", int(seg), arg);
arg = comma ? comma + 1 : NULL;
}
return result;
}
template <typename T>
void applySetting(T (&data)[TextureKind__Count], T value, unsigned int mask = ~0u)
{
for (int kind = 0; kind < TextureKind__Count; ++kind)
if (mask & (1 << kind))
data[kind] = value;
}
#ifndef GLTFFUZZ
int main(int argc, char** argv)
{
#ifndef __wasi__
setlocale(LC_ALL, "C"); // disable locale specific convention for number parsing/printing
#endif
meshopt_encodeVertexVersion(0);
meshopt_encodeIndexVersion(1);
Settings settings = defaults();
const char* input = NULL;
const char* output = NULL;
const char* report = NULL;
bool help = false;
bool test = false;
bool require_texc = false;
std::vector<const char*> testinputs;
for (int i = 1; i < argc; ++i)
{
const char* arg = argv[i];
if (strcmp(arg, "-vp") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
{
settings.pos_bits = clamp(atoi(argv[++i]), 1, 16);
}
else if (strcmp(arg, "-vt") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
{
settings.tex_bits = clamp(atoi(argv[++i]), 1, 16);
}
else if (strcmp(arg, "-vn") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
{
settings.nrm_bits = clamp(atoi(argv[++i]), 1, 16);
}
else if (strcmp(arg, "-vc") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
{
settings.col_bits = clamp(atoi(argv[++i]), 1, 16);
}
else if (strcmp(arg, "-vpi") == 0)
{
settings.pos_float = false;
settings.pos_normalized = false;
}
else if (strcmp(arg, "-vpn") == 0)
{
settings.pos_float = false;
settings.pos_normalized = true;
}
else if (strcmp(arg, "-vpf") == 0)
{
settings.pos_float = true;
}
else if (strcmp(arg, "-vtf") == 0)
{
settings.tex_float = true;
}
else if (strcmp(arg, "-vnf") == 0)
{
settings.nrm_float = true;
}
else if (strcmp(arg, "-vi") == 0)
{
settings.mesh_interleaved = true;
}
else if (strcmp(arg, "-at") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
{
settings.trn_bits = clamp(atoi(argv[++i]), 1, 24);
}
else if (strcmp(arg, "-ar") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
{
settings.rot_bits = clamp(atoi(argv[++i]), 4, 16);
}
else if (strcmp(arg, "-as") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
{
settings.scl_bits = clamp(atoi(argv[++i]), 1, 24);
}
else if (strcmp(arg, "-af") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
{
settings.anim_freq = clamp(atoi(argv[++i]), 0, 100);
}
else if (strcmp(arg, "-ac") == 0)
{
settings.anim_const = true;
}
else if (strcmp(arg, "-kn") == 0)
{
settings.keep_nodes = true;
}
else if (strcmp(arg, "-km") == 0)
{
settings.keep_materials = true;
}
else if (strcmp(arg, "-ke") == 0)
{
settings.keep_extras = true;
}
else if (strcmp(arg, "-kv") == 0)
{
settings.keep_attributes = true;
}
else if (strcmp(arg, "-mdd") == 0)
{
fprintf(stderr, "Warning: option -mdd disables mesh deduplication and is temporary; avoid production usage\n");
settings.mesh_dedup = false;
}
else if (strcmp(arg, "-mm") == 0)
{
settings.mesh_merge = true;
}
else if (strcmp(arg, "-mi") == 0)
{
settings.mesh_instancing = true;
}
else if (strcmp(arg, "-si") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
{
settings.simplify_ratio = clamp(float(atof(argv[++i])), 0.f, 1.f);
}
else if (strcmp(arg, "-se") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
{
settings.simplify_error = clamp(float(atof(argv[++i])), 0.f, 1.f);
}
else if (strcmp(arg, "-sa") == 0)
{
settings.simplify_aggressive = true;
}
else if (strcmp(arg, "-slb") == 0)
{
settings.simplify_lock_borders = true;
}
else if (strcmp(arg, "-sv") == 0)
{
fprintf(stderr, "Warning: attribute aware simplification is enabled by default; option -sv is only provided for compatibility and may be removed in the future\n");
}
else if (strcmp(arg, "-svd") == 0)
{
fprintf(stderr, "Warning: option -svd disables attribute aware simplification and is temporary; avoid production usage\n");
settings.simplify_attributes = false;
}
else if (strcmp(arg, "-ssd") == 0)
{
fprintf(stderr, "Warning: option -ssd disables scaled simplification error and is temporary; avoid production usage\n");
settings.simplify_scaled = false;
}
else if (strcmp(arg, "-sp") == 0)
{
settings.simplify_permissive = true;
}
else if (strcmp(arg, "-tu") == 0)
{
settings.texture_ktx2 = true;
unsigned int mask = ~0u;
if (i + 1 < argc && isalpha(argv[i + 1][0]))
mask = textureMask(argv[++i]);
applySetting(settings.texture_mode, TextureMode_UASTC, mask);
}
else if (strcmp(arg, "-tc") == 0)
{
settings.texture_ktx2 = true;
unsigned int mask = ~0u;
if (i + 1 < argc && isalpha(argv[i + 1][0]))
mask = textureMask(argv[++i]);
applySetting(settings.texture_mode, TextureMode_ETC1S, mask);
}
else if (strcmp(arg, "-tw") == 0)
{
settings.texture_webp = true;
unsigned int mask = ~0u;
if (i + 1 < argc && isalpha(argv[i + 1][0]))
mask = textureMask(argv[++i]);
applySetting(settings.texture_mode, TextureMode_WebP, mask);
}
else if (strcmp(arg, "-tq") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
{
require_texc = true;
int quality = clamp(atoi(argv[++i]), 1, 10);
applySetting(settings.texture_quality, quality);
}
else if (strcmp(arg, "-tq") == 0 && i + 2 < argc && isalpha(argv[i + 1][0]) && isdigit(argv[i + 2][0]))
{
require_texc = true;
unsigned int mask = textureMask(argv[++i]);
int quality = clamp(atoi(argv[++i]), 1, 10);
applySetting(settings.texture_quality, quality, mask);
}
else if (strcmp(arg, "-ts") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
{
require_texc = true;
float scale = clamp(float(atof(argv[++i])), 0.f, 1.f);
applySetting(settings.texture_scale, scale);
}
else if (strcmp(arg, "-ts") == 0 && i + 2 < argc && isalpha(argv[i + 1][0]) && isdigit(argv[i + 2][0]))
{
require_texc = true;
unsigned int mask = textureMask(argv[++i]);
float scale = clamp(float(atof(argv[++i])), 0.f, 1.f);
applySetting(settings.texture_scale, scale, mask);
}
else if (strcmp(arg, "-tl") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
{
require_texc = true;
int limit = atoi(argv[++i]);
applySetting(settings.texture_limit, limit);
}
else if (strcmp(arg, "-tl") == 0 && i + 2 < argc && isalpha(argv[i + 1][0]) && isdigit(argv[i + 2][0]))
{
require_texc = true;
unsigned int mask = textureMask(argv[++i]);
int limit = atoi(argv[++i]);
applySetting(settings.texture_limit, limit, mask);
}
else if (strcmp(arg, "-tp") == 0)
{
require_texc = true;
settings.texture_pow2 = true;
}
else if (strcmp(arg, "-tfy") == 0)
{
require_texc = true;
settings.texture_flipy = true;
}
else if (strcmp(arg, "-tr") == 0)
{
settings.texture_ref = true;
}
else if (strcmp(arg, "-tj") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
{
settings.texture_jobs = clamp(atoi(argv[++i]), 0, 128);
}
else if (strcmp(arg, "-noq") == 0)
{
// TODO: Warn if -noq is used and suggest -vpf instead; use -noqq to silence
settings.quantize = false;
}
else if (strcmp(arg, "-i") == 0 && i + 1 < argc && !input)
{
input = argv[++i];
}
else if (strcmp(arg, "-o") == 0 && i + 1 < argc && !output)
{
output = argv[++i];
}
else if (strcmp(arg, "-r") == 0 && i + 1 < argc && !report)
{
report = argv[++i];
}
else if (strcmp(arg, "-c") == 0)
{
settings.compress = true;
}
else if (strcmp(arg, "-cc") == 0)
{
settings.compress = true;
settings.compressmore = true;
}
else if (strcmp(arg, "-cf") == 0)
{
settings.compress = true;
settings.fallback = true;
}
else if (strcmp(arg, "-cz") == 0)
{
settings.compress = true;
settings.compressmore = true;
settings.compresskhr = true;
}
else if (strcmp(arg, "-ce") == 0 && i + 1 < argc && (strcmp(argv[i + 1], "khr") == 0 || strcmp(argv[i + 1], "ext") == 0))
{
settings.compress = true;
settings.compresskhr = strcmp(argv[++i], "khr") == 0;
}
else if (strcmp(arg, "-v") == 0)
{
settings.verbose = 1;
}
else if (strcmp(arg, "-vv") == 0)
{
settings.verbose = 2;
}
else if (strcmp(arg, "-h") == 0)
{
help = true;
}
else if (strcmp(arg, "-test") == 0)
{
test = true;
}
else if (arg[0] == '-')
{
fprintf(stderr, "Unrecognized option %s\n", arg);
return 1;
}
else if (test)
{
testinputs.push_back(arg);
}
else
{
fprintf(stderr, "Expected option, got %s instead\n", arg);
return 1;
}
}
// shortcut for gltfpack -v
if (settings.verbose && argc == 2)
{
printf("gltfpack %s\n", getVersion().c_str());
return 0;
}
if (test)
{
for (size_t i = 0; i < testinputs.size(); ++i)
{
const char* path = testinputs[i];
printf("%s\n", path);
gltfpack(path, NULL, NULL, settings);
}
return 0;
}
if (!input || !output || help)
{
fprintf(stderr, "gltfpack %s\n", getVersion().c_str());
fprintf(stderr, "Usage: gltfpack [options] -i input -o output\n");
if (help)
{
fprintf(stderr, "\nBasics:\n");
fprintf(stderr, "\t-i file: input file to process, .obj/.gltf/.glb\n");
fprintf(stderr, "\t-o file: output file path, .gltf/.glb\n");
fprintf(stderr, "\t-c: produce compressed gltf/glb files (-cc/-cz for higher compression ratio)\n");
fprintf(stderr, "\nTextures:\n");
fprintf(stderr, "\t-tc: convert all textures to KTX2 with BasisU supercompression\n");
fprintf(stderr, "\t-tu: use UASTC when encoding textures (much higher quality and much larger size)\n");
fprintf(stderr, "\t-tw: convert all textures to WebP\n");
fprintf(stderr, "\t-tq N: set texture encoding quality (default: 8; N should be between 1 and 10)\n");
fprintf(stderr, "\t-ts R: scale texture dimensions by the ratio R (default: 1; R should be between 0 and 1)\n");
fprintf(stderr, "\t-tl N: limit texture dimensions to N pixels (default: 0 = no limit)\n");
fprintf(stderr, "\t-tp: resize textures to nearest power of 2 to conform to WebGL1 restrictions\n");
fprintf(stderr, "\t-tfy: flip textures along Y axis during BasisU supercompression\n");
fprintf(stderr, "\t-tj N: use N threads when compressing textures\n");
fprintf(stderr, "\t-tr: keep referring to original texture paths instead of copying/embedding images\n");
fprintf(stderr, "\tTexture classes:\n");
fprintf(stderr, "\t-tc C: use ETC1S when encoding textures of class C\n");
fprintf(stderr, "\t-tu C: use UASTC when encoding textures of class C\n");
fprintf(stderr, "\t-tw C: use WebP when encoding textures of class C\n");
fprintf(stderr, "\t-tq C N: set texture encoding quality for class C\n");
fprintf(stderr, "\t-ts C R: scale texture dimensions for class C\n");
fprintf(stderr, "\t-tl C N: limit texture dimensions for class C\n");
fprintf(stderr, "\t... where C is a comma-separated list (no spaces) with valid values color,normal,attrib\n");
fprintf(stderr, "\nSimplification:\n");
fprintf(stderr, "\t-si R: simplify meshes targeting triangle/point count ratio R (default: 1; R should be between 0 and 1)\n");
fprintf(stderr, "\t-se E: limit simplification error to E (default: 0.01 = 1%% deviation; E should be between 0 and 1)\n");
fprintf(stderr, "\t-sp: use permissive simplification mode to allow simplification across attribute discontinuities\n");
fprintf(stderr, "\t-sa: aggressively simplify to the target ratio disregarding quality\n");
fprintf(stderr, "\t-slb: lock border vertices during simplification to avoid gaps on connected meshes\n");
fprintf(stderr, "\nVertex precision:\n");
fprintf(stderr, "\t-vp N: use N-bit quantization for positions (default: 14; N should be between 1 and 16)\n");
fprintf(stderr, "\t-vt N: use N-bit quantization for texture coordinates (default: 12; N should be between 1 and 16)\n");
fprintf(stderr, "\t-vn N: use N-bit quantization for normals (default: 8; N should be between 1 and 16) and tangents (up to 8-bit)\n");
fprintf(stderr, "\t-vc N: use N-bit quantization for colors (default: 8; N should be between 1 and 16)\n");
fprintf(stderr, "\nVertex positions:\n");
fprintf(stderr, "\t-vpi: use integer attributes for positions (default)\n");
fprintf(stderr, "\t-vpn: use normalized attributes for positions\n");
fprintf(stderr, "\t-vpf: use floating point attributes for positions\n");
fprintf(stderr, "\nVertex attributes:\n");
fprintf(stderr, "\t-vtf: use floating point attributes for texture coordinates\n");
fprintf(stderr, "\t-vnf: use floating point attributes for normals\n");
fprintf(stderr, "\t-vi: use interleaved vertex attributes (reduces compression efficiency)\n");
fprintf(stderr, "\t-kv: keep source vertex attributes even if they aren't used\n");
fprintf(stderr, "\nAnimations:\n");
fprintf(stderr, "\t-at N: use N-bit quantization for translations (default: 16; N should be between 1 and 24)\n");
fprintf(stderr, "\t-ar N: use N-bit quantization for rotations (default: 12; N should be between 4 and 16)\n");
fprintf(stderr, "\t-as N: use N-bit quantization for scale (default: 16; N should be between 1 and 24)\n");
fprintf(stderr, "\t-af N: resample animations at N Hz (default: 30; use 0 to disable)\n");
fprintf(stderr, "\t-ac: keep constant animation tracks even if they don't modify the node transform\n");
fprintf(stderr, "\nScene:\n");
fprintf(stderr, "\t-kn: keep named nodes and meshes attached to named nodes so that named nodes can be transformed externally\n");
fprintf(stderr, "\t-km: keep named materials and disable named material merging\n");
fprintf(stderr, "\t-ke: keep extras data\n");
fprintf(stderr, "\t-mm: merge instances of the same mesh together when possible\n");
fprintf(stderr, "\t-mi: use EXT_mesh_gpu_instancing when serializing multiple mesh instances\n");
fprintf(stderr, "\nMiscellaneous:\n");
fprintf(stderr, "\t-cf: produce compressed gltf/glb files with fallback for loaders that don't support compression\n");
fprintf(stderr, "\t-ce ext|khr: use EXT or KHR version of meshopt compression extension for compression\n");
fprintf(stderr, "\t-noq: disable quantization; produces much larger glTF files with no extensions\n");
fprintf(stderr, "\t-v: verbose output (when used with other options)\n");
fprintf(stderr, "\t-v: print version (when used without other options)\n");
fprintf(stderr, "\t-r file: output a JSON report to file\n");
fprintf(stderr, "\t-h: display this help and exit\n");
}
else
{
fprintf(stderr, "\nBasics:\n");
fprintf(stderr, "\t-i file: input file to process, .obj/.gltf/.glb\n");
fprintf(stderr, "\t-o file: output file path, .gltf/.glb\n");
fprintf(stderr, "\t-c: produce compressed gltf/glb files (-cc/-cz for higher compression ratio)\n");
fprintf(stderr, "\t-tc: convert all textures to KTX2 with BasisU supercompression\n");
fprintf(stderr, "\t-tw: convert all textures to WebP\n");
fprintf(stderr, "\t-si R: simplify meshes targeting triangle/point count ratio R (between 0 and 1)\n");
fprintf(stderr, "\nRun gltfpack -h to display a full list of options\n");
}
return 1;
}
if (require_texc && !settings.texture_ktx2 && !settings.texture_webp)
{
fprintf(stderr, "Texture processing is only supported when texture compression is enabled via -tc/-tu/-tw\n");
return 1;
}
if (settings.texture_ref && (settings.texture_ktx2 || settings.texture_webp))
{
fprintf(stderr, "Option -tr currently can not be used together with texture compression\n");
return 1;
}
if (settings.fallback && settings.compressmore)
{
fprintf(stderr, "Option -cf can not be used together with -cc\n");
return 1;
}
if (settings.fallback && (settings.pos_float || settings.tex_float || settings.nrm_float))
{
fprintf(stderr, "Option -cf can not be used together with -vpf, -vtf or -vnf\n");
return 1;
}
if (settings.keep_nodes && (settings.mesh_merge || settings.mesh_instancing))
fprintf(stderr, "Warning: option -kn disables mesh merge (-mm) and mesh instancing (-mi) optimizations\n");
return gltfpack(input, output, report, settings);
}
#endif
#ifdef __wasi__
extern "C" int pack(int argc, char** argv)
{
chdir("/gltfpack-$pwd");
int result = main(argc, argv);
fflush(NULL);
return result;
}
#endif
#ifdef GLTFFUZZ
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* buffer, size_t size)
{
Settings settings = defaults();
settings.texture_embed = true;
std::vector<Mesh> meshes;
std::vector<Animation> animations;
const char* error = NULL;
cgltf_data* data = parseGlb(buffer, size, meshes, animations, &error);
// this is a difficult tradeoff
// returning 0 on files that fail to parse means that fuzzing is more incremental: files with errors are put into the corpus,
// and the subsequent mutations may lead to discovering more interesting inputs, including valid ones that are difficult to find otherwise.
// however, this leads to most of the corpus being invalid, and we very rarely get useful coverage for actual gltfpack processing.
// for now we just focus on valid files, as we expect cgltf parser itself to be bulletproof as it's fuzzed separately.
if (error)
return -1;
std::string json, bin, fallback;
size_t fallback_size = 0;
process(data, NULL, NULL, NULL, meshes, animations, settings, json, bin, fallback, fallback_size, NULL);
cgltf_free(data);
return 0;
}
#endif
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
gltf/gltfpack.h | C/C++ Header | /**
* gltfpack - version 1.0
*
* Copyright (C) 2016-2026, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
* Report bugs and download new versions at https://github.com/zeux/meshoptimizer
*
* This application is distributed under the MIT License. See notice at the end of this file.
*/
#pragma once
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#ifndef _CRT_NONSTDC_NO_WARNINGS
#define _CRT_NONSTDC_NO_WARNINGS
#endif
#include "../extern/cgltf.h"
#include <assert.h>
#include <string>
#include <vector>
struct Attr
{
float f[4];
};
struct Stream
{
cgltf_attribute_type type;
int index;
int target; // 0 = base mesh, 1+ = morph target
const char* custom_name; // only valid for cgltf_attribute_type_custom
std::vector<Attr> data;
};
struct Instance
{
float transform[16];
float color[4];
};
struct Mesh
{
int scene;
std::vector<cgltf_node*> nodes;
std::vector<Instance> instances;
cgltf_material* material;
cgltf_skin* skin;
cgltf_extras extras;
cgltf_primitive_type type;
std::vector<Stream> streams;
std::vector<unsigned int> indices;
bool geometry_duplicate;
uint64_t geometry_hash[2];
size_t targets;
std::vector<float> target_weights;
std::vector<const char*> target_names;
std::vector<cgltf_material_mapping> variants;
float quality;
};
struct Track
{
cgltf_node* node;
cgltf_animation_path_type path;
bool constant;
bool dummy;
size_t components; // 1 unless path is cgltf_animation_path_type_weights
cgltf_interpolation_type interpolation;
std::vector<float> time; // empty for resampled or constant animations
std::vector<Attr> data;
};
struct Animation
{
const char* name;
float start;
int frames;
std::vector<Track> tracks;
};
enum TextureKind
{
TextureKind_Generic,
TextureKind_Color,
TextureKind_Normal,
TextureKind_Attrib,
TextureKind__Count
};
enum TextureMode
{
TextureMode_Raw,
TextureMode_ETC1S,
TextureMode_UASTC,
TextureMode_WebP,
};
struct Settings
{
int pos_bits;
int tex_bits;
int nrm_bits;
int col_bits;
bool pos_normalized;
bool pos_float;
bool tex_float;
bool nrm_float;
int trn_bits;
int rot_bits;
int scl_bits;
int anim_freq;
bool anim_const;
bool keep_nodes;
bool keep_materials;
bool keep_extras;
bool keep_attributes;
bool mesh_dedup;
bool mesh_merge;
bool mesh_instancing;
bool mesh_interleaved;
float simplify_ratio;
float simplify_error;
bool simplify_aggressive;
bool simplify_lock_borders;
bool simplify_attributes;
bool simplify_scaled;
bool simplify_permissive;
bool texture_ktx2;
bool texture_webp;
bool texture_embed;
bool texture_ref;
bool texture_pow2;
bool texture_flipy;
float texture_scale[TextureKind__Count];
int texture_limit[TextureKind__Count];
TextureMode texture_mode[TextureKind__Count];
int texture_quality[TextureKind__Count];
int texture_jobs;
bool quantize;
bool compress;
bool compressmore;
bool compresskhr;
bool fallback;
int verbose;
};
struct QuantizationPosition
{
float offset[3];
float scale;
int bits;
bool normalized;
float node_scale; // computed from scale/bits/normalized
};
struct QuantizationTexture
{
float offset[2];
float scale[2];
int bits;
bool normalized;
};
struct StreamFormat
{
enum Filter
{
Filter_None,
Filter_Oct,
Filter_Quat,
Filter_Exp,
Filter_Color,
};
cgltf_type type;
cgltf_component_type component_type;
bool normalized;
size_t stride;
Filter filter;
};
struct NodeInfo
{
int scene;
bool keep;
bool animated;
unsigned int animated_path_mask;
int remap;
std::vector<size_t> mesh_nodes;
bool has_mesh;
size_t mesh_index;
cgltf_skin* mesh_skin;
};
struct MaterialInfo
{
bool keep;
bool uses_texture_transform;
bool needs_tangents;
bool unlit;
bool mesh_alpha;
unsigned int texture_set_mask;
int remap;
};
struct TextureInfo
{
bool keep;
int remap;
};
struct ImageInfo
{
TextureKind kind;
bool normal_map;
bool srgb;
int channels;
};
struct ExtensionInfo
{
const char* name;
bool used;
bool required;
};
struct BufferView
{
enum Kind
{
Kind_Vertex,
Kind_Index,
Kind_Skin,
Kind_Time,
Kind_Keyframe,
Kind_Instance,
Kind_Image,
Kind_Count
};
enum Compression
{
Compression_None = -1,
Compression_Attribute,
Compression_Index,
Compression_IndexSequence,
};
Kind kind;
StreamFormat::Filter filter;
Compression compression;
size_t stride;
int variant;
std::string data;
size_t bytes;
};
std::string getTempPrefix();
std::string getFullPath(const char* path, const char* base_path);
std::string getFileName(const char* path);
std::string getExtension(const char* path);
bool readFile(const char* path, std::string& data);
bool writeFile(const char* path, const std::string& data);
void removeFile(const char* path);
cgltf_data* parseObj(const char* path, std::vector<Mesh>& meshes, const char** error);
cgltf_data* parseGltf(const char* path, std::vector<Mesh>& meshes, std::vector<Animation>& animations, const char** error);
cgltf_data* parseGlb(const void* buffer, size_t size, std::vector<Mesh>& meshes, std::vector<Animation>& animations, const char** error);
bool areExtrasEqual(const cgltf_extras& lhs, const cgltf_extras& rhs);
void processAnimation(Animation& animation, const Settings& settings);
void processMesh(Mesh& mesh, const Settings& settings);
bool compareMeshTargets(const Mesh& lhs, const Mesh& rhs);
bool compareMeshVariants(const Mesh& lhs, const Mesh& rhs);
bool compareMeshNodes(const Mesh& lhs, const Mesh& rhs);
void hashMesh(Mesh& mesh);
void dedupMeshes(std::vector<Mesh>& meshes, const Settings& settings);
void mergeMeshInstances(Mesh& mesh);
void mergeMeshes(std::vector<Mesh>& meshes, const Settings& settings);
void filterEmptyMeshes(std::vector<Mesh>& meshes);
void filterStreams(Mesh& mesh, const MaterialInfo& mi);
void mergeMeshMaterials(cgltf_data* data, std::vector<Mesh>& meshes, const Settings& settings);
void markNeededMaterials(cgltf_data* data, std::vector<MaterialInfo>& materials, const std::vector<Mesh>& meshes, const Settings& settings);
void mergeTextures(cgltf_data* data, std::vector<TextureInfo>& textures);
bool hasValidTransform(const cgltf_texture_view& view);
void analyzeMaterials(cgltf_data* data, std::vector<MaterialInfo>& materials, std::vector<TextureInfo>& textures, std::vector<ImageInfo>& images);
void optimizeMaterials(cgltf_data* data, std::vector<MaterialInfo>& materials, std::vector<ImageInfo>& images, const char* input_path);
bool readImage(const cgltf_image& image, const char* input_path, std::string& data, std::string& mime_type);
bool hasAlpha(const std::string& data, const char* mime_type);
bool getDimensions(const std::string& data, const char* mime_type, int& width, int& height);
void adjustDimensions(int& width, int& height, float scale, int limit, bool pow2);
const char* mimeExtension(const char* mime_type);
#ifdef WITH_BASISU
void encodeImagesBasis(std::string* encoded, const cgltf_data* data, const std::vector<ImageInfo>& images, const char* input_path, const Settings& settings);
#endif
#ifdef WITH_LIBWEBP
void encodeImagesWebP(std::string* encoded, const cgltf_data* data, const std::vector<ImageInfo>& images, const char* input_path, const Settings& settings);
#endif
void markScenes(cgltf_data* data, std::vector<NodeInfo>& nodes);
void markAnimated(cgltf_data* data, std::vector<NodeInfo>& nodes, const std::vector<Animation>& animations);
void markNeededNodes(cgltf_data* data, std::vector<NodeInfo>& nodes, const std::vector<Mesh>& meshes, const std::vector<Animation>& animations, const Settings& settings);
void remapNodes(cgltf_data* data, std::vector<NodeInfo>& nodes, size_t& node_offset);
void decomposeTransform(float translation[3], float rotation[4], float scale[3], const float* transform);
void computeMeshQuality(std::vector<Mesh>& meshes);
bool hasVertexAlpha(const Mesh& mesh);
bool hasInstanceAlpha(const std::vector<Instance>& instances);
QuantizationPosition prepareQuantizationPosition(const std::vector<Mesh>& meshes, const Settings& settings);
void prepareQuantizationTexture(cgltf_data* data, std::vector<QuantizationTexture>& result, std::vector<size_t>& indices, const std::vector<Mesh>& meshes, const Settings& settings);
void getPositionBounds(float min[3], float max[3], const Stream& stream, const QuantizationPosition& qp, const Settings& settings);
StreamFormat writeVertexStream(std::string& bin, const Stream& stream, const QuantizationPosition& qp, const QuantizationTexture& qt, const Settings& settings, bool filters = true);
StreamFormat writeIndexStream(std::string& bin, const std::vector<unsigned int>& stream);
StreamFormat writeTimeStream(std::string& bin, const std::vector<float>& data);
StreamFormat writeKeyframeStream(std::string& bin, cgltf_animation_path_type type, const std::vector<Attr>& data, const Settings& settings, bool has_tangents = false);
void compressVertexStream(std::string& bin, const std::string& data, size_t count, size_t stride, int level);
void compressIndexStream(std::string& bin, const std::string& data, size_t count, size_t stride);
void compressIndexSequence(std::string& bin, const std::string& data, size_t count, size_t stride);
size_t getBufferView(std::vector<BufferView>& views, BufferView::Kind kind, StreamFormat::Filter filter, BufferView::Compression compression, size_t stride, int variant = 0);
void comma(std::string& s);
void append(std::string& s, size_t v);
void append(std::string& s, float v);
void append(std::string& s, const char* v);
void append(std::string& s, const std::string& v);
void append(std::string& s, const float* data, size_t count);
void appendJson(std::string& s, const char* data);
const char* attributeType(cgltf_attribute_type type);
const char* animationPath(cgltf_animation_path_type type);
void writeMaterial(std::string& json, const cgltf_data* data, const cgltf_material& material, const QuantizationPosition* qp, const QuantizationTexture* qt, std::vector<TextureInfo>& textures);
void writeBufferView(std::string& json, BufferView::Kind kind, StreamFormat::Filter filter, size_t count, size_t stride, size_t bin_offset, size_t bin_size, BufferView::Compression compression, size_t compressed_offset, size_t compressed_size, const char* meshopt_ext);
void writeSampler(std::string& json, const cgltf_sampler& sampler);
void writeImage(std::string& json, std::vector<BufferView>& views, const cgltf_image& image, const ImageInfo& info, const std::string* encoded, size_t index, const char* input_path, const char* output_path, const Settings& settings);
void writeTexture(std::string& json, const cgltf_texture& texture, const ImageInfo* info, cgltf_data* data, const Settings& settings);
void writeMeshAttributes(std::string& json, std::vector<BufferView>& views, std::string& json_accessors, size_t& accr_offset, const Mesh& mesh, int target, const QuantizationPosition& qp, const QuantizationTexture& qt, const Settings& settings);
size_t writeMeshIndices(std::vector<BufferView>& views, std::string& json_accessors, size_t& accr_offset, const std::vector<unsigned int>& indices, cgltf_primitive_type type, const Settings& settings);
void writeMeshGeometry(std::string& json, std::vector<BufferView>& views, std::string& json_accessors, size_t& accr_offset, const Mesh& mesh, const QuantizationPosition& qp, const QuantizationTexture& qt, const Settings& settings);
size_t writeJointBindMatrices(std::vector<BufferView>& views, std::string& json_accessors, size_t& accr_offset, const cgltf_skin& skin, const QuantizationPosition& qp, const Settings& settings);
size_t writeInstances(std::vector<BufferView>& views, std::string& json_accessors, size_t& accr_offset, const std::vector<Instance>& instances, const QuantizationPosition& qp, bool has_color, const Settings& settings);
void writeMeshNode(std::string& json, size_t mesh_offset, cgltf_node* node, cgltf_skin* skin, cgltf_data* data, const QuantizationPosition* qp);
void writeMeshNodeInstanced(std::string& json, size_t mesh_offset, size_t accr_offset, bool has_color);
void writeSkin(std::string& json, const cgltf_skin& skin, size_t matrix_accr, const std::vector<NodeInfo>& nodes, cgltf_data* data);
void writeNode(std::string& json, const cgltf_node& node, const std::vector<NodeInfo>& nodes, cgltf_data* data);
void writeAnimation(std::string& json, std::vector<BufferView>& views, std::string& json_accessors, size_t& accr_offset, const Animation& animation, size_t i, cgltf_data* data, const std::vector<NodeInfo>& nodes, const Settings& settings);
void writeCamera(std::string& json, const cgltf_camera& camera);
void writeLight(std::string& json, const cgltf_light& light);
void writeArray(std::string& json, const char* name, const std::string& contents);
void writeExtensions(std::string& json, const ExtensionInfo* extensions, size_t count);
void writeExtras(std::string& json, const cgltf_extras& extras);
void writeScene(std::string& json, const cgltf_scene& scene, const std::string& roots, const Settings& settings);
/**
* Copyright (c) 2016-2026 Arseny Kapoulkine
*
* 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.
*/
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
gltf/image.cpp | C++ | // This file is part of gltfpack; see gltfpack.h for version/license details
#include "gltfpack.h"
#include <stdlib.h>
#include <string.h>
static const char* kMimeTypes[][2] = {
{"image/jpeg", ".jpg"},
{"image/jpeg", ".jpeg"},
{"image/png", ".png"},
{"image/ktx2", ".ktx2"},
{"image/webp", ".webp"},
};
static const char* inferMimeType(const char* path)
{
std::string ext = getExtension(path);
for (size_t i = 0; i < sizeof(kMimeTypes) / sizeof(kMimeTypes[0]); ++i)
if (ext == kMimeTypes[i][1])
return kMimeTypes[i][0];
return "";
}
static bool parseDataUri(const char* uri, std::string& mime_type, std::string& result)
{
if (strncmp(uri, "data:", 5) == 0)
{
const char* comma = strchr(uri, ',');
if (comma && comma - uri >= 7 && strncmp(comma - 7, ";base64", 7) == 0)
{
const char* base64 = comma + 1;
size_t base64_size = strlen(base64);
size_t size = base64_size - base64_size / 4;
if (base64_size >= 2)
{
size -= base64[base64_size - 2] == '=';
size -= base64[base64_size - 1] == '=';
}
void* data = NULL;
cgltf_options options = {};
cgltf_result res = cgltf_load_buffer_base64(&options, size, base64, &data);
if (res != cgltf_result_success)
return false;
mime_type = std::string(uri + 5, comma - 7);
result = std::string(static_cast<const char*>(data), size);
free(data);
return true;
}
}
return false;
}
static std::string fixupMimeType(const std::string& data, const std::string& mime_type)
{
if (mime_type == "image/jpeg" && data.compare(0, 8, "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a") == 0)
return "image/png";
if (mime_type == "image/png" && data.compare(0, 3, "\xff\xd8\xff") == 0)
return "image/jpeg";
return mime_type;
}
bool readImage(const cgltf_image& image, const char* input_path, std::string& data, std::string& mime_type)
{
if (image.uri && parseDataUri(image.uri, mime_type, data))
{
mime_type = fixupMimeType(data, mime_type);
return true;
}
else if (image.buffer_view && image.buffer_view->buffer->data && image.mime_type)
{
const cgltf_buffer_view* view = image.buffer_view;
data.assign(static_cast<const char*>(view->buffer->data) + view->offset, view->size);
mime_type = image.mime_type;
mime_type = fixupMimeType(data, image.mime_type);
return true;
}
else if (image.uri && *image.uri && input_path)
{
std::string path = image.uri;
cgltf_decode_uri(&path[0]);
path.resize(strlen(&path[0]));
if (!readFile(getFullPath(path.c_str(), input_path).c_str(), data))
return false;
mime_type = image.mime_type ? image.mime_type : inferMimeType(path.c_str());
mime_type = fixupMimeType(data, mime_type);
return true;
}
else
{
return false;
}
}
static int readInt16BE(const std::string& data, size_t offset)
{
return (unsigned char)data[offset] * 256 + (unsigned char)data[offset + 1];
}
static int readInt32BE(const std::string& data, size_t offset)
{
return (unsigned((unsigned char)data[offset]) << 24) |
(unsigned((unsigned char)data[offset + 1]) << 16) |
(unsigned((unsigned char)data[offset + 2]) << 8) |
unsigned((unsigned char)data[offset + 3]);
}
static int readInt32LE(const std::string& data, size_t offset)
{
return unsigned((unsigned char)data[offset]) |
(unsigned((unsigned char)data[offset + 1]) << 8) |
(unsigned((unsigned char)data[offset + 2]) << 16) |
(unsigned((unsigned char)data[offset + 3]) << 24);
}
// https://en.wikipedia.org/wiki/PNG#File_format
static bool getDimensionsPng(const std::string& data, int& width, int& height)
{
if (data.size() < 8 + 8 + 13 + 4)
return false;
const char* signature = "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a";
if (data.compare(0, 8, signature) != 0)
return false;
if (data.compare(12, 4, "IHDR") != 0)
return false;
width = readInt32BE(data, 16);
height = readInt32BE(data, 20);
return true;
}
// https://en.wikipedia.org/wiki/JPEG_File_Interchange_Format#File_format_structure
static bool getDimensionsJpeg(const std::string& data, int& width, int& height)
{
size_t offset = 0;
// note, this can stop parsing before reaching the end but we stop at SOF anyway
while (offset + 4 <= data.size())
{
if (data[offset] != '\xff')
return false;
char marker = data[offset + 1];
if (marker == '\xff')
{
offset++;
continue; // padding
}
// d0..d9 correspond to SOI, RSTn, EOI
if (marker == 0 || unsigned(marker - '\xd0') <= 9)
{
offset += 2;
continue; // no payload
}
// c0..c1 correspond to SOF0, SOF1
if (marker == '\xc0' || marker == '\xc2')
{
if (offset + 10 > data.size())
return false;
width = readInt16BE(data, offset + 7);
height = readInt16BE(data, offset + 5);
return true;
}
offset += 2 + readInt16BE(data, offset + 2);
}
return false;
}
// https://en.wikipedia.org/wiki/PNG#File_format
static bool hasTransparencyPng(const std::string& data)
{
if (data.size() < 8 + 8 + 13 + 4)
return false;
const char* signature = "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a";
if (data.compare(0, 8, signature) != 0)
return false;
if (data.compare(12, 4, "IHDR") != 0)
return false;
int ctype = data[25];
if (ctype != 3)
return ctype == 4 || ctype == 6;
size_t offset = 8; // reparse IHDR chunk for simplicity
while (offset + 12 <= data.size())
{
int length = readInt32BE(data, offset);
if (length < 0)
return false;
if (data.compare(offset + 4, 4, "tRNS") == 0)
return true;
offset += 12 + length;
}
return false;
}
// https://github.khronos.org/KTX-Specification/ktxspec.v2.html
static bool hasTransparencyKtx2(const std::string& data)
{
if (data.size() < 12 + 17 * 4)
return false;
const char* signature = "\xabKTX 20\xbb\r\n\x1a\n";
if (data.compare(0, 12, signature) != 0)
return false;
int dfdOffset = readInt32LE(data, 48);
int dfdLength = readInt32LE(data, 52);
if (dfdLength < 4 + 24 + 16 || unsigned(dfdOffset) > data.size() || unsigned(dfdLength) > data.size() - dfdOffset)
return false;
const int KDF_DF_MODEL_ETC1S = 163;
const int KDF_DF_MODEL_UASTC = 166;
const int KHR_DF_CHANNEL_UASTC_RGBA = 3;
const int KHR_DF_CHANNEL_ETC1S_RGB = 0;
const int KHR_DF_CHANNEL_ETC1S_AAA = 15;
int colorModel = readInt32LE(data, dfdOffset + 12) & 0xff;
int channelType1 = (readInt32LE(data, dfdOffset + 28) >> 24) & 0xf;
int channelType2 = dfdLength >= 4 + 24 + 16 * 2 ? (readInt32LE(data, dfdOffset + 44) >> 24) & 0xf : channelType1;
if (colorModel == KDF_DF_MODEL_ETC1S)
{
return channelType1 == KHR_DF_CHANNEL_ETC1S_RGB && channelType2 == KHR_DF_CHANNEL_ETC1S_AAA;
}
else if (colorModel == KDF_DF_MODEL_UASTC)
{
return channelType1 == KHR_DF_CHANNEL_UASTC_RGBA;
}
return false;
}
// https://developers.google.com/speed/webp/docs/riff_container
static bool hasTransparencyWebP(const std::string& data)
{
if (data.size() < 12 + 4 + 12)
return false;
if (data.compare(0, 4, "RIFF") != 0)
return false;
if (data.compare(8, 4, "WEBP") != 0)
return false;
// WebP data may use VP8L, VP8X or VP8 format, but VP8 does not support transparency
if (data.compare(12, 4, "VP8L") == 0)
{
if (unsigned(data[20]) != 0x2f)
return false;
// width (14) | height (14) | alpha_is_used (1) | version_number(3)
unsigned int header = readInt32LE(data, 21);
return (header & (1 << 28)) != 0;
}
else if (data.compare(12, 4, "VP8X") == 0)
{
// zero (2) | icc (1) | alpha (1) | exif (1) | xmp (1) | animation (1) | zero (1)
unsigned char header = data[20];
return (header & (1 << 4)) != 0;
}
return false;
}
bool hasAlpha(const std::string& data, const char* mime_type)
{
if (strcmp(mime_type, "image/png") == 0)
return hasTransparencyPng(data);
else if (strcmp(mime_type, "image/ktx2") == 0)
return hasTransparencyKtx2(data);
else if (strcmp(mime_type, "image/webp") == 0)
return hasTransparencyWebP(data);
else
return false;
}
bool getDimensions(const std::string& data, const char* mime_type, int& width, int& height)
{
if (strcmp(mime_type, "image/png") == 0)
return getDimensionsPng(data, width, height);
if (strcmp(mime_type, "image/jpeg") == 0)
return getDimensionsJpeg(data, width, height);
return false;
}
static int roundPow2(int value)
{
int result = 1;
while (result < value)
result <<= 1;
// to prevent odd texture sizes from increasing the size too much, we round to nearest power of 2 above a certain size
if (value > 128 && result * 3 / 4 > value)
result >>= 1;
return result;
}
static int roundBlock(int value, bool pow2)
{
if (value == 0)
return 4;
if (pow2 && value > 4)
return roundPow2(value);
return (value + 3) & ~3;
}
void adjustDimensions(int& width, int& height, float scale, int limit, bool pow2)
{
width = int(width * scale);
height = int(height * scale);
if (limit && (width > limit || height > limit))
{
float limit_scale = float(limit) / float(width > height ? width : height);
width = int(width * limit_scale);
height = int(height * limit_scale);
}
width = roundBlock(width, pow2);
height = roundBlock(height, pow2);
}
const char* mimeExtension(const char* mime_type)
{
for (size_t i = 0; i < sizeof(kMimeTypes) / sizeof(kMimeTypes[0]); ++i)
if (strcmp(kMimeTypes[i][0], mime_type) == 0)
return kMimeTypes[i][1];
return ".raw";
}
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
gltf/json.cpp | C++ | // This file is part of gltfpack; see gltfpack.h for version/license details
#include "gltfpack.h"
#include <float.h>
#include <math.h>
#include <stdio.h>
void comma(std::string& s)
{
char ch = s.empty() ? 0 : s[s.size() - 1];
if (ch != 0 && ch != '[' && ch != '{')
s += ",";
}
void append(std::string& s, size_t v)
{
char buf[32];
snprintf(buf, sizeof(buf), "%zu", v);
s += buf;
}
void append(std::string& s, float v)
{
// sanitize +-inf to +-FLT_MAX and NaN to FLT_MAX
// it would be more consistent to use null for NaN but that makes JSON invalid, and 0 makes it hard to distinguish from valid values
float sv = fabsf(v) < FLT_MAX ? v : (v < 0 ? -FLT_MAX : FLT_MAX);
char buf[64];
snprintf(buf, sizeof(buf), "%.9g", sv);
s += buf;
}
void append(std::string& s, const char* v)
{
s += v;
}
void append(std::string& s, const std::string& v)
{
s += v;
}
void append(std::string& s, const float* data, size_t count)
{
s += '[';
for (size_t i = 0; i < count; ++i)
{
if (i != 0)
s += ',';
append(s, data[i]);
}
s += ']';
}
void appendJson(std::string& s, const char* data)
{
enum State
{
None,
Escape,
Quoted
} state = None;
for (const char* it = data; *it; ++it)
{
char ch = *it;
// whitespace outside of quoted strings can be ignored
if (state != None || !isspace(ch))
s += ch;
// the finite automata tracks whether we're inside a quoted string
switch (state)
{
case None:
state = (ch == '"') ? Quoted : None;
break;
case Quoted:
state = (ch == '"') ? None : (ch == '\\' ? Escape : Quoted);
break;
case Escape:
state = Quoted;
break;
default:
assert(!"Unexpected parsing state");
}
}
}
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
gltf/library.js | JavaScript | // This file is part of gltfpack and is distributed under the terms of MIT License.
/**
* Initialize the library with the Wasm module (library.wasm)
*
* @param wasm Promise with contents of library.wasm
*
* Note: this is called automatically in node.js
*/
function init(wasm) {
if (ready) {
throw new Error('init must be called once');
}
ready = Promise.resolve(wasm)
.then(function (buffer) {
return WebAssembly.instantiate(buffer, { wasi_snapshot_preview1: wasi });
})
.then(function (result) {
instance = result.instance;
instance.exports.__wasm_call_ctors();
});
}
/**
* Pack the requested glTF data using the requested command line and access interface.
*
* @param args An array of strings with the input arguments; the paths for input and output files are interpreted by the interface
* @param iface An interface to the system that will be used to service file requests and other system calls
* @return Promise that indicates completion of the operation
*
* iface should contain the following methods:
* read(path): Given a path, return a Uint8Array with the contents of that path
* write(path, data): Write the specified Uint8Array to the provided path
*/
function pack(args, iface) {
if (!ready) {
throw new Error('init must be called before pack');
}
var argv = args.slice();
argv.unshift('gltfpack');
return ready.then(function () {
var buf = uploadArgv(argv);
output.position = 0;
output.size = 0;
fs_interface = iface;
var result = instance.exports.pack(argv.length, buf);
fs_interface = undefined;
instance.exports.free(buf);
var log = getString(output.data.buffer, 0, output.size);
if (result != 0) {
throw new Error(log);
} else {
return log;
}
});
}
// Library implementation (here be dragons)
var WASI_EBADF = 8;
var WASI_EINVAL = 28;
var WASI_EIO = 29;
var WASI_ENOSYS = 52;
var ready;
var instance;
var fs_interface;
var output = { data: new Uint8Array(), position: 0, size: 0 };
var fds = { 1: output, 2: output, 3: { mount: '/', path: '/' }, 4: { mount: '/gltfpack-$pwd', path: '' } };
var wasi = {
proc_exit: function (rval) {},
fd_close: function (fd) {
if (!fds[fd]) {
return WASI_EBADF;
}
try {
if (fds[fd].close) {
fds[fd].close();
}
fds[fd] = undefined;
return 0;
} catch (err) {
fds[fd] = undefined;
return WASI_EIO;
}
},
fd_fdstat_get: function (fd, stat) {
if (!fds[fd]) {
return WASI_EBADF;
}
var heap = getHeap();
heap.setUint8(stat + 0, fds[fd].path !== undefined ? 3 : 4);
heap.setUint16(stat + 2, 0, true);
heap.setUint32(stat + 8, 0, true);
heap.setUint32(stat + 12, 0, true);
heap.setUint32(stat + 16, 0, true);
heap.setUint32(stat + 20, 0, true);
return 0;
},
path_open32: function (parent_fd, dirflags, path, path_len, oflags, fs_rights_base, fs_rights_inheriting, fdflags, opened_fd) {
if (!fds[parent_fd] || fds[parent_fd].path === undefined) {
return WASI_EBADF;
}
var heap = getHeap();
var file = {};
file.name = fds[parent_fd].path + getString(heap.buffer, path, path_len);
file.position = 0;
if (oflags & 1) {
file.data = new Uint8Array(4096);
file.size = 0;
file.close = function () {
fs_interface.write(file.name, new Uint8Array(file.data.buffer, 0, file.size));
};
} else {
try {
file.data = fs_interface.read(file.name);
if (!file.data) {
return WASI_EIO;
}
file.size = file.data.length;
} catch (err) {
return WASI_EIO;
}
}
var fd = nextFd();
fds[fd] = file;
heap.setUint32(opened_fd, fd, true);
return 0;
},
path_filestat_get: function (parent_fd, flags, path, path_len, buf) {
if (!fds[parent_fd] || fds[parent_fd].path === undefined) {
return WASI_EBADF;
}
var heap = getHeap();
var name = getString(heap.buffer, path, path_len);
var heap = getHeap();
for (var i = 0; i < 64; ++i) heap.setUint8(buf + i, 0);
heap.setUint8(buf + 16, name == '.' ? 3 : 4);
return 0;
},
fd_prestat_get: function (fd, buf) {
if (!fds[fd] || fds[fd].path === undefined) {
return WASI_EBADF;
}
var path_buf = stringBuffer(fds[fd].mount);
var heap = getHeap();
heap.setUint8(buf, 0);
heap.setUint32(buf + 4, path_buf.length, true);
return 0;
},
fd_prestat_dir_name: function (fd, path, path_len) {
if (!fds[fd] || fds[fd].path === undefined) {
return WASI_EBADF;
}
var path_buf = stringBuffer(fds[fd].mount);
if (path_len != path_buf.length) {
return WASI_EINVAL;
}
var heap = getHeap();
new Uint8Array(heap.buffer).set(path_buf, path);
return 0;
},
path_remove_directory: function (parent_fd, path, path_len) {
return WASI_EINVAL;
},
fd_fdstat_set_flags: function (fd, flags) {
return WASI_ENOSYS;
},
fd_seek32: function (fd, offset, whence, newoffset) {
if (!fds[fd]) {
return WASI_EBADF;
}
var newposition;
switch (whence) {
case 0:
newposition = offset;
break;
case 1:
newposition = fds[fd].position + offset;
break;
case 2:
newposition = fds[fd].size;
break;
default:
return WASI_EINVAL;
}
if (newposition > fds[fd].size) {
return WASI_EINVAL;
}
fds[fd].position = newposition;
var heap = getHeap();
heap.setUint32(newoffset, newposition, true);
return 0;
},
fd_read: function (fd, iovs, iovs_len, nread) {
if (!fds[fd]) {
return WASI_EBADF;
}
var heap = getHeap();
var read = 0;
for (var i = 0; i < iovs_len; ++i) {
var buf = heap.getUint32(iovs + 8 * i + 0, true);
var buf_len = heap.getUint32(iovs + 8 * i + 4, true);
var readi = Math.min(fds[fd].size - fds[fd].position, buf_len);
new Uint8Array(heap.buffer).set(fds[fd].data.subarray(fds[fd].position, fds[fd].position + readi), buf);
fds[fd].position += readi;
read += readi;
}
heap.setUint32(nread, read, true);
return 0;
},
fd_write: function (fd, iovs, iovs_len, nwritten) {
if (!fds[fd]) {
return WASI_EBADF;
}
var heap = getHeap();
var written = 0;
for (var i = 0; i < iovs_len; ++i) {
var buf = heap.getUint32(iovs + 8 * i + 0, true);
var buf_len = heap.getUint32(iovs + 8 * i + 4, true);
if (fds[fd].position + buf_len > fds[fd].data.length) {
fds[fd].data = growArray(fds[fd].data, fds[fd].position + buf_len);
}
fds[fd].data.set(new Uint8Array(heap.buffer, buf, buf_len), fds[fd].position);
fds[fd].position += buf_len;
fds[fd].size = Math.max(fds[fd].position, fds[fd].size);
written += buf_len;
}
heap.setUint32(nwritten, written, true);
return 0;
},
};
function nextFd() {
for (var i = 1; ; ++i) {
if (fds[i] === undefined) {
return i;
}
}
}
function getHeap() {
return new DataView(instance.exports.memory.buffer);
}
function getString(buffer, offset, length) {
return new TextDecoder().decode(new Uint8Array(buffer, offset, length));
}
function stringBuffer(string) {
return new TextEncoder().encode(string);
}
function growArray(data, len) {
var new_length = Math.max(1, data.length);
while (new_length < len) {
new_length *= 2;
}
var new_data = new Uint8Array(new_length);
new_data.set(data);
return new_data;
}
function uploadArgv(argv) {
var buf_size = argv.length * 4;
for (var i = 0; i < argv.length; ++i) {
buf_size += stringBuffer(argv[i]).length + 1;
}
var buf = instance.exports.malloc(buf_size);
var argp = buf + argv.length * 4;
var heap = getHeap();
for (var i = 0; i < argv.length; ++i) {
var item = stringBuffer(argv[i]);
heap.setUint32(buf + i * 4, argp, true);
new Uint8Array(heap.buffer).set(item, argp);
heap.setUint8(argp + item.length, 0);
argp += item.length + 1;
}
return buf;
}
// Automatic initialization for node.js
if (typeof process !== 'undefined' && process.release && process.release.name === 'node') {
init(
import('node:fs').then(function (fs) {
return fs.readFileSync(new URL('./library.wasm', import.meta.url));
})
);
}
export { init, pack };
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
gltf/material.cpp | C++ | // This file is part of gltfpack; see gltfpack.h for version/license details
#include "gltfpack.h"
#include <string.h>
static bool areTexturesEqual(const cgltf_texture& lhs, const cgltf_texture& rhs)
{
if (lhs.image != rhs.image)
return false;
if (lhs.sampler != rhs.sampler)
return false;
if (lhs.basisu_image != rhs.basisu_image)
return false;
if (lhs.webp_image != rhs.webp_image)
return false;
return true;
}
static bool areTextureViewsEqual(const cgltf_texture_view& lhs, const cgltf_texture_view& rhs)
{
if (lhs.has_transform != rhs.has_transform)
return false;
if (lhs.has_transform)
{
const cgltf_texture_transform& lt = lhs.transform;
const cgltf_texture_transform& rt = rhs.transform;
if (memcmp(lt.offset, rt.offset, sizeof(cgltf_float) * 2) != 0)
return false;
if (lt.rotation != rt.rotation)
return false;
if (memcmp(lt.scale, rt.scale, sizeof(cgltf_float) * 2) != 0)
return false;
if (lt.texcoord != rt.texcoord)
return false;
}
if (lhs.texture != rhs.texture && (!lhs.texture || !rhs.texture || !areTexturesEqual(*lhs.texture, *rhs.texture)))
return false;
if (lhs.texcoord != rhs.texcoord)
return false;
if (lhs.scale != rhs.scale)
return false;
return true;
}
static bool areMaterialComponentsEqual(const cgltf_pbr_metallic_roughness& lhs, const cgltf_pbr_metallic_roughness& rhs)
{
if (!areTextureViewsEqual(lhs.base_color_texture, rhs.base_color_texture))
return false;
if (!areTextureViewsEqual(lhs.metallic_roughness_texture, rhs.metallic_roughness_texture))
return false;
if (memcmp(lhs.base_color_factor, rhs.base_color_factor, sizeof(cgltf_float) * 4) != 0)
return false;
if (lhs.metallic_factor != rhs.metallic_factor)
return false;
if (lhs.roughness_factor != rhs.roughness_factor)
return false;
return true;
}
static bool areMaterialComponentsEqual(const cgltf_pbr_specular_glossiness& lhs, const cgltf_pbr_specular_glossiness& rhs)
{
if (!areTextureViewsEqual(lhs.diffuse_texture, rhs.diffuse_texture))
return false;
if (!areTextureViewsEqual(lhs.specular_glossiness_texture, rhs.specular_glossiness_texture))
return false;
if (memcmp(lhs.diffuse_factor, rhs.diffuse_factor, sizeof(cgltf_float) * 4) != 0)
return false;
if (memcmp(lhs.specular_factor, rhs.specular_factor, sizeof(cgltf_float) * 3) != 0)
return false;
if (lhs.glossiness_factor != rhs.glossiness_factor)
return false;
return true;
}
static bool areMaterialComponentsEqual(const cgltf_clearcoat& lhs, const cgltf_clearcoat& rhs)
{
if (!areTextureViewsEqual(lhs.clearcoat_texture, rhs.clearcoat_texture))
return false;
if (!areTextureViewsEqual(lhs.clearcoat_roughness_texture, rhs.clearcoat_roughness_texture))
return false;
if (!areTextureViewsEqual(lhs.clearcoat_normal_texture, rhs.clearcoat_normal_texture))
return false;
if (lhs.clearcoat_factor != rhs.clearcoat_factor)
return false;
if (lhs.clearcoat_roughness_factor != rhs.clearcoat_roughness_factor)
return false;
return true;
}
static bool areMaterialComponentsEqual(const cgltf_transmission& lhs, const cgltf_transmission& rhs)
{
if (!areTextureViewsEqual(lhs.transmission_texture, rhs.transmission_texture))
return false;
if (lhs.transmission_factor != rhs.transmission_factor)
return false;
return true;
}
static bool areMaterialComponentsEqual(const cgltf_ior& lhs, const cgltf_ior& rhs)
{
if (lhs.ior != rhs.ior)
return false;
return true;
}
static bool areMaterialComponentsEqual(const cgltf_specular& lhs, const cgltf_specular& rhs)
{
if (!areTextureViewsEqual(lhs.specular_texture, rhs.specular_texture))
return false;
if (!areTextureViewsEqual(lhs.specular_color_texture, rhs.specular_color_texture))
return false;
if (lhs.specular_factor != rhs.specular_factor)
return false;
if (memcmp(lhs.specular_color_factor, rhs.specular_color_factor, sizeof(cgltf_float) * 3) != 0)
return false;
return true;
}
static bool areMaterialComponentsEqual(const cgltf_sheen& lhs, const cgltf_sheen& rhs)
{
if (!areTextureViewsEqual(lhs.sheen_color_texture, rhs.sheen_color_texture))
return false;
if (memcmp(lhs.sheen_color_factor, rhs.sheen_color_factor, sizeof(cgltf_float) * 3) != 0)
return false;
if (!areTextureViewsEqual(lhs.sheen_roughness_texture, rhs.sheen_roughness_texture))
return false;
if (lhs.sheen_roughness_factor != rhs.sheen_roughness_factor)
return false;
return true;
}
static bool areMaterialComponentsEqual(const cgltf_volume& lhs, const cgltf_volume& rhs)
{
if (!areTextureViewsEqual(lhs.thickness_texture, rhs.thickness_texture))
return false;
if (lhs.thickness_factor != rhs.thickness_factor)
return false;
if (memcmp(lhs.attenuation_color, rhs.attenuation_color, sizeof(cgltf_float) * 3) != 0)
return false;
if (lhs.attenuation_distance != rhs.attenuation_distance)
return false;
return true;
}
static bool areMaterialComponentsEqual(const cgltf_emissive_strength& lhs, const cgltf_emissive_strength& rhs)
{
if (lhs.emissive_strength != rhs.emissive_strength)
return false;
return true;
}
static bool areMaterialComponentsEqual(const cgltf_iridescence& lhs, const cgltf_iridescence& rhs)
{
if (lhs.iridescence_factor != rhs.iridescence_factor)
return false;
if (!areTextureViewsEqual(lhs.iridescence_texture, rhs.iridescence_texture))
return false;
if (lhs.iridescence_ior != rhs.iridescence_ior)
return false;
if (lhs.iridescence_thickness_min != rhs.iridescence_thickness_min)
return false;
if (lhs.iridescence_thickness_max != rhs.iridescence_thickness_max)
return false;
if (!areTextureViewsEqual(lhs.iridescence_thickness_texture, rhs.iridescence_thickness_texture))
return false;
return true;
}
static bool areMaterialComponentsEqual(const cgltf_anisotropy& lhs, const cgltf_anisotropy& rhs)
{
if (lhs.anisotropy_strength != rhs.anisotropy_strength)
return false;
if (lhs.anisotropy_rotation != rhs.anisotropy_rotation)
return false;
if (!areTextureViewsEqual(lhs.anisotropy_texture, rhs.anisotropy_texture))
return false;
return true;
}
static bool areMaterialComponentsEqual(const cgltf_dispersion& lhs, const cgltf_dispersion& rhs)
{
if (lhs.dispersion != rhs.dispersion)
return false;
return true;
}
static bool areMaterialComponentsEqual(const cgltf_diffuse_transmission& lhs, const cgltf_diffuse_transmission& rhs)
{
if (lhs.diffuse_transmission_factor != rhs.diffuse_transmission_factor)
return false;
if (memcmp(lhs.diffuse_transmission_color_factor, rhs.diffuse_transmission_color_factor, sizeof(cgltf_float) * 3) != 0)
return false;
if (!areTextureViewsEqual(lhs.diffuse_transmission_texture, rhs.diffuse_transmission_texture))
return false;
if (!areTextureViewsEqual(lhs.diffuse_transmission_color_texture, rhs.diffuse_transmission_color_texture))
return false;
return true;
}
static bool areMaterialsEqual(const cgltf_material& lhs, const cgltf_material& rhs, const Settings& settings)
{
if (lhs.has_pbr_metallic_roughness != rhs.has_pbr_metallic_roughness)
return false;
if (lhs.has_pbr_metallic_roughness && !areMaterialComponentsEqual(lhs.pbr_metallic_roughness, rhs.pbr_metallic_roughness))
return false;
if (lhs.has_pbr_specular_glossiness != rhs.has_pbr_specular_glossiness)
return false;
if (lhs.has_pbr_specular_glossiness && !areMaterialComponentsEqual(lhs.pbr_specular_glossiness, rhs.pbr_specular_glossiness))
return false;
if (lhs.has_clearcoat != rhs.has_clearcoat)
return false;
if (lhs.has_clearcoat && !areMaterialComponentsEqual(lhs.clearcoat, rhs.clearcoat))
return false;
if (lhs.has_transmission != rhs.has_transmission)
return false;
if (lhs.has_transmission && !areMaterialComponentsEqual(lhs.transmission, rhs.transmission))
return false;
if (lhs.has_ior != rhs.has_ior)
return false;
if (lhs.has_ior && !areMaterialComponentsEqual(lhs.ior, rhs.ior))
return false;
if (lhs.has_specular != rhs.has_specular)
return false;
if (lhs.has_specular && !areMaterialComponentsEqual(lhs.specular, rhs.specular))
return false;
if (lhs.has_sheen != rhs.has_sheen)
return false;
if (lhs.has_sheen && !areMaterialComponentsEqual(lhs.sheen, rhs.sheen))
return false;
if (lhs.has_volume != rhs.has_volume)
return false;
if (lhs.has_volume && !areMaterialComponentsEqual(lhs.volume, rhs.volume))
return false;
if (lhs.has_emissive_strength != rhs.has_emissive_strength)
return false;
if (lhs.has_emissive_strength && !areMaterialComponentsEqual(lhs.emissive_strength, rhs.emissive_strength))
return false;
if (lhs.has_iridescence != rhs.has_iridescence)
return false;
if (lhs.has_iridescence && !areMaterialComponentsEqual(lhs.iridescence, rhs.iridescence))
return false;
if (lhs.has_anisotropy != rhs.has_anisotropy)
return false;
if (lhs.has_anisotropy && !areMaterialComponentsEqual(lhs.anisotropy, rhs.anisotropy))
return false;
if (lhs.has_dispersion != rhs.has_dispersion)
return false;
if (lhs.has_dispersion && !areMaterialComponentsEqual(lhs.dispersion, rhs.dispersion))
return false;
if (lhs.has_diffuse_transmission != rhs.has_diffuse_transmission)
return false;
if (lhs.has_diffuse_transmission && !areMaterialComponentsEqual(lhs.diffuse_transmission, rhs.diffuse_transmission))
return false;
if (!areTextureViewsEqual(lhs.normal_texture, rhs.normal_texture))
return false;
if (!areTextureViewsEqual(lhs.occlusion_texture, rhs.occlusion_texture))
return false;
if (!areTextureViewsEqual(lhs.emissive_texture, rhs.emissive_texture))
return false;
if (memcmp(lhs.emissive_factor, rhs.emissive_factor, sizeof(cgltf_float) * 3) != 0)
return false;
if (lhs.alpha_mode != rhs.alpha_mode)
return false;
if (lhs.alpha_cutoff != rhs.alpha_cutoff)
return false;
if (lhs.double_sided != rhs.double_sided)
return false;
if (lhs.unlit != rhs.unlit)
return false;
if (settings.keep_extras && !areExtrasEqual(lhs.extras, rhs.extras))
return false;
return true;
}
void mergeMeshMaterials(cgltf_data* data, std::vector<Mesh>& meshes, const Settings& settings)
{
std::vector<cgltf_material*> material_remap(data->materials_count);
for (size_t i = 0; i < data->materials_count; ++i)
{
material_remap[i] = &data->materials[i];
if (settings.keep_materials && data->materials[i].name && *data->materials[i].name)
continue;
assert(areMaterialsEqual(data->materials[i], data->materials[i], settings));
for (size_t j = 0; j < i; ++j)
{
if (settings.keep_materials && data->materials[j].name && *data->materials[j].name)
continue;
if (areMaterialsEqual(data->materials[i], data->materials[j], settings))
{
material_remap[i] = &data->materials[j];
break;
}
}
}
for (size_t i = 0; i < meshes.size(); ++i)
{
Mesh& mesh = meshes[i];
if (mesh.material)
mesh.material = material_remap[mesh.material - data->materials];
for (size_t j = 0; j < mesh.variants.size(); ++j)
mesh.variants[j].material = material_remap[mesh.variants[j].material - data->materials];
}
}
void markNeededMaterials(cgltf_data* data, std::vector<MaterialInfo>& materials, const std::vector<Mesh>& meshes, const Settings& settings)
{
// mark all used materials as kept
for (size_t i = 0; i < meshes.size(); ++i)
{
const Mesh& mesh = meshes[i];
if (mesh.material)
{
MaterialInfo& mi = materials[mesh.material - data->materials];
mi.keep = true;
}
for (size_t j = 0; j < mesh.variants.size(); ++j)
{
MaterialInfo& mi = materials[mesh.variants[j].material - data->materials];
mi.keep = true;
}
}
// mark all named materials as kept if requested
if (settings.keep_materials)
{
for (size_t i = 0; i < data->materials_count; ++i)
{
cgltf_material& material = data->materials[i];
if (material.name && *material.name)
{
materials[i].keep = true;
}
}
}
}
bool hasValidTransform(const cgltf_texture_view& view)
{
if (view.has_transform)
{
if (view.transform.offset[0] != 0.0f || view.transform.offset[1] != 0.0f ||
view.transform.scale[0] != 1.0f || view.transform.scale[1] != 1.0f ||
view.transform.rotation != 0.0f)
return true;
if (view.transform.has_texcoord && view.transform.texcoord != view.texcoord)
return true;
}
return false;
}
static const cgltf_image* getTextureImage(const cgltf_texture* texture)
{
if (texture && texture->image)
return texture->image;
if (texture && texture->basisu_image)
return texture->basisu_image;
if (texture && texture->webp_image)
return texture->webp_image;
return NULL;
}
static void analyzeMaterialTexture(const cgltf_texture_view& view, TextureKind kind, MaterialInfo& mi, cgltf_data* data, std::vector<TextureInfo>& textures, std::vector<ImageInfo>& images)
{
mi.uses_texture_transform |= hasValidTransform(view);
if (view.texture)
{
textures[view.texture - data->textures].keep = true;
mi.texture_set_mask |= 1u << view.texcoord;
mi.needs_tangents |= (kind == TextureKind_Normal);
}
if (const cgltf_image* image = getTextureImage(view.texture))
{
ImageInfo& info = images[image - data->images];
if (info.kind == TextureKind_Generic)
info.kind = kind;
else if (info.kind > kind) // this is useful to keep color textures that have attrib data in alpha tagged as color
info.kind = kind;
info.normal_map |= (kind == TextureKind_Normal);
info.srgb |= (kind == TextureKind_Color);
}
}
static void analyzeMaterial(const cgltf_material& material, MaterialInfo& mi, cgltf_data* data, std::vector<TextureInfo>& textures, std::vector<ImageInfo>& images)
{
if (material.has_pbr_metallic_roughness)
{
analyzeMaterialTexture(material.pbr_metallic_roughness.base_color_texture, TextureKind_Color, mi, data, textures, images);
analyzeMaterialTexture(material.pbr_metallic_roughness.metallic_roughness_texture, TextureKind_Attrib, mi, data, textures, images);
}
if (material.has_pbr_specular_glossiness)
{
analyzeMaterialTexture(material.pbr_specular_glossiness.diffuse_texture, TextureKind_Color, mi, data, textures, images);
analyzeMaterialTexture(material.pbr_specular_glossiness.specular_glossiness_texture, TextureKind_Attrib, mi, data, textures, images);
}
if (material.has_clearcoat)
{
analyzeMaterialTexture(material.clearcoat.clearcoat_texture, TextureKind_Attrib, mi, data, textures, images);
analyzeMaterialTexture(material.clearcoat.clearcoat_roughness_texture, TextureKind_Attrib, mi, data, textures, images);
analyzeMaterialTexture(material.clearcoat.clearcoat_normal_texture, TextureKind_Normal, mi, data, textures, images);
}
if (material.has_transmission)
{
analyzeMaterialTexture(material.transmission.transmission_texture, TextureKind_Attrib, mi, data, textures, images);
}
if (material.has_specular)
{
analyzeMaterialTexture(material.specular.specular_texture, TextureKind_Attrib, mi, data, textures, images);
analyzeMaterialTexture(material.specular.specular_color_texture, TextureKind_Color, mi, data, textures, images);
}
if (material.has_sheen)
{
analyzeMaterialTexture(material.sheen.sheen_color_texture, TextureKind_Color, mi, data, textures, images);
analyzeMaterialTexture(material.sheen.sheen_roughness_texture, TextureKind_Attrib, mi, data, textures, images);
}
if (material.has_volume)
{
analyzeMaterialTexture(material.volume.thickness_texture, TextureKind_Attrib, mi, data, textures, images);
}
if (material.has_iridescence)
{
analyzeMaterialTexture(material.iridescence.iridescence_texture, TextureKind_Attrib, mi, data, textures, images);
analyzeMaterialTexture(material.iridescence.iridescence_thickness_texture, TextureKind_Attrib, mi, data, textures, images);
}
if (material.has_anisotropy)
{
analyzeMaterialTexture(material.anisotropy.anisotropy_texture, TextureKind_Normal, mi, data, textures, images);
}
if (material.has_diffuse_transmission)
{
analyzeMaterialTexture(material.diffuse_transmission.diffuse_transmission_texture, TextureKind_Attrib, mi, data, textures, images);
analyzeMaterialTexture(material.diffuse_transmission.diffuse_transmission_color_texture, TextureKind_Color, mi, data, textures, images);
}
analyzeMaterialTexture(material.normal_texture, TextureKind_Normal, mi, data, textures, images);
analyzeMaterialTexture(material.occlusion_texture, TextureKind_Attrib, mi, data, textures, images);
analyzeMaterialTexture(material.emissive_texture, TextureKind_Color, mi, data, textures, images);
if (material.unlit)
mi.unlit = true;
}
void analyzeMaterials(cgltf_data* data, std::vector<MaterialInfo>& materials, std::vector<TextureInfo>& textures, std::vector<ImageInfo>& images)
{
for (size_t i = 0; i < data->materials_count; ++i)
{
analyzeMaterial(data->materials[i], materials[i], data, textures, images);
}
}
static int getChannels(const cgltf_image& image, ImageInfo& info, const char* input_path)
{
if (info.channels)
return info.channels;
std::string img_data;
std::string mime_type;
if (readImage(image, input_path, img_data, mime_type))
info.channels = hasAlpha(img_data, mime_type.c_str()) ? 4 : 3;
else
info.channels = -1;
return info.channels;
}
static bool shouldKeepAlpha(const cgltf_texture_view& color, float alpha, cgltf_data* data, const char* input_path, std::vector<ImageInfo>& images)
{
if (alpha != 1.f)
return true;
const cgltf_image* image = getTextureImage(color.texture);
return image && getChannels(*image, images[image - data->images], input_path) == 4;
}
void optimizeMaterials(cgltf_data* data, std::vector<MaterialInfo>& materials, std::vector<ImageInfo>& images, const char* input_path)
{
for (size_t i = 0; i < data->materials_count; ++i)
{
// remove BLEND/MASK from materials that don't have alpha information
cgltf_material& material = data->materials[i];
if (material.alpha_mode != cgltf_alpha_mode_opaque && !materials[i].mesh_alpha)
{
if (material.has_pbr_metallic_roughness && shouldKeepAlpha(material.pbr_metallic_roughness.base_color_texture, material.pbr_metallic_roughness.base_color_factor[3], data, input_path, images))
continue;
if (material.has_pbr_specular_glossiness && shouldKeepAlpha(material.pbr_specular_glossiness.diffuse_texture, material.pbr_specular_glossiness.diffuse_factor[3], data, input_path, images))
continue;
material.alpha_mode = cgltf_alpha_mode_opaque;
material.alpha_cutoff = 0.5f; // reset to default to avoid writing it to output
}
}
}
void mergeTextures(cgltf_data* data, std::vector<TextureInfo>& textures)
{
size_t offset = 0;
for (size_t i = 0; i < textures.size(); ++i)
{
TextureInfo& info = textures[i];
if (!info.keep)
continue;
for (size_t j = 0; j < i; ++j)
if (textures[j].keep && areTexturesEqual(data->textures[i], data->textures[j]))
{
info.keep = false;
info.remap = textures[j].remap;
break;
}
if (info.keep)
{
info.remap = int(offset);
offset++;
}
}
}
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
gltf/mesh.cpp | C++ | // This file is part of gltfpack; see gltfpack.h for version/license details
#include "gltfpack.h"
#include <algorithm>
#include <unordered_map>
#include <math.h>
#include <stdint.h>
#include <string.h>
#include "../src/meshoptimizer.h"
static float inverseTranspose(float* result, const float* transform)
{
float m[4][4] = {};
memcpy(m, transform, 16 * sizeof(float));
float det =
m[0][0] * (m[1][1] * m[2][2] - m[2][1] * m[1][2]) -
m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) +
m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]);
float invdet = (det == 0.f) ? 0.f : 1.f / det;
float r[4][4] = {};
r[0][0] = (m[1][1] * m[2][2] - m[2][1] * m[1][2]) * invdet;
r[1][0] = (m[0][2] * m[2][1] - m[0][1] * m[2][2]) * invdet;
r[2][0] = (m[0][1] * m[1][2] - m[0][2] * m[1][1]) * invdet;
r[0][1] = (m[1][2] * m[2][0] - m[1][0] * m[2][2]) * invdet;
r[1][1] = (m[0][0] * m[2][2] - m[0][2] * m[2][0]) * invdet;
r[2][1] = (m[1][0] * m[0][2] - m[0][0] * m[1][2]) * invdet;
r[0][2] = (m[1][0] * m[2][1] - m[2][0] * m[1][1]) * invdet;
r[1][2] = (m[2][0] * m[0][1] - m[0][0] * m[2][1]) * invdet;
r[2][2] = (m[0][0] * m[1][1] - m[1][0] * m[0][1]) * invdet;
r[3][3] = 1.f;
memcpy(result, r, 16 * sizeof(float));
return det;
}
static void transformPosition(float* res, const float* ptr, const float* transform)
{
float x = ptr[0] * transform[0] + ptr[1] * transform[4] + ptr[2] * transform[8] + transform[12];
float y = ptr[0] * transform[1] + ptr[1] * transform[5] + ptr[2] * transform[9] + transform[13];
float z = ptr[0] * transform[2] + ptr[1] * transform[6] + ptr[2] * transform[10] + transform[14];
res[0] = x;
res[1] = y;
res[2] = z;
}
static void transformNormal(float* res, const float* ptr, const float* transform)
{
float x = ptr[0] * transform[0] + ptr[1] * transform[4] + ptr[2] * transform[8];
float y = ptr[0] * transform[1] + ptr[1] * transform[5] + ptr[2] * transform[9];
float z = ptr[0] * transform[2] + ptr[1] * transform[6] + ptr[2] * transform[10];
float l = sqrtf(x * x + y * y + z * z);
float s = (l == 0.f) ? 0.f : 1 / l;
res[0] = x * s;
res[1] = y * s;
res[2] = z * s;
}
static Stream* getStream(Mesh& mesh, cgltf_attribute_type type, int index = 0)
{
for (size_t i = 0; i < mesh.streams.size(); ++i)
if (mesh.streams[i].type == type && mesh.streams[i].index == index)
return &mesh.streams[i];
return NULL;
}
// assumes mesh & target are structurally identical
static void transformMesh(Mesh& target, const Mesh& mesh, const cgltf_node* node)
{
assert(target.streams.size() == mesh.streams.size());
assert(target.indices.size() == mesh.indices.size());
float transform[16];
cgltf_node_transform_world(node, transform);
float transforminvt[16];
float det = inverseTranspose(transforminvt, transform);
for (size_t si = 0; si < mesh.streams.size(); ++si)
{
const Stream& source = mesh.streams[si];
Stream& stream = target.streams[si];
assert(source.type == stream.type);
assert(source.data.size() == stream.data.size());
if (stream.type == cgltf_attribute_type_position)
{
for (size_t i = 0; i < stream.data.size(); ++i)
transformPosition(stream.data[i].f, source.data[i].f, transform);
}
else if (stream.type == cgltf_attribute_type_normal)
{
for (size_t i = 0; i < stream.data.size(); ++i)
transformNormal(stream.data[i].f, source.data[i].f, transforminvt);
}
else if (stream.type == cgltf_attribute_type_tangent)
{
for (size_t i = 0; i < stream.data.size(); ++i)
transformNormal(stream.data[i].f, source.data[i].f, transform);
}
}
// copy indices so that we can modify them below
target.indices = mesh.indices;
if (det < 0 && mesh.type == cgltf_primitive_type_triangles)
{
// negative scale means we need to flip face winding
for (size_t i = 0; i < target.indices.size(); i += 3)
std::swap(target.indices[i + 0], target.indices[i + 1]);
}
}
bool compareMeshTargets(const Mesh& lhs, const Mesh& rhs)
{
if (lhs.targets != rhs.targets)
return false;
if (lhs.target_weights.size() != rhs.target_weights.size())
return false;
for (size_t i = 0; i < lhs.target_weights.size(); ++i)
if (lhs.target_weights[i] != rhs.target_weights[i])
return false;
if (lhs.target_names.size() != rhs.target_names.size())
return false;
for (size_t i = 0; i < lhs.target_names.size(); ++i)
if (strcmp(lhs.target_names[i], rhs.target_names[i]) != 0)
return false;
return true;
}
bool compareMeshVariants(const Mesh& lhs, const Mesh& rhs)
{
if (lhs.variants.size() != rhs.variants.size())
return false;
for (size_t i = 0; i < lhs.variants.size(); ++i)
{
if (lhs.variants[i].variant != rhs.variants[i].variant)
return false;
if (lhs.variants[i].material != rhs.variants[i].material)
return false;
}
return true;
}
bool compareMeshNodes(const Mesh& lhs, const Mesh& rhs)
{
if (lhs.nodes.size() != rhs.nodes.size())
return false;
for (size_t i = 0; i < lhs.nodes.size(); ++i)
if (lhs.nodes[i] != rhs.nodes[i])
return false;
return true;
}
static bool compareInstances(const Instance& lhs, const Instance& rhs)
{
return memcmp(&lhs, &rhs, sizeof(Instance)) == 0;
}
static bool canMergeMeshNodes(cgltf_node* lhs, cgltf_node* rhs, const Settings& settings)
{
if (lhs == rhs)
return true;
if (lhs->parent != rhs->parent)
return false;
bool lhs_transform = lhs->has_translation | lhs->has_rotation | lhs->has_scale | lhs->has_matrix | (!!lhs->weights);
bool rhs_transform = rhs->has_translation | rhs->has_rotation | rhs->has_scale | rhs->has_matrix | (!!rhs->weights);
if (lhs_transform || rhs_transform)
return false;
if (settings.keep_nodes)
{
if (lhs->name && *lhs->name)
return false;
if (rhs->name && *rhs->name)
return false;
}
// we can merge nodes that don't have transforms of their own and have the same parent
// this is helpful when instead of splitting mesh into primitives, DCCs split mesh into mesh nodes
return true;
}
static bool canMergeMeshes(const Mesh& lhs, const Mesh& rhs, const Settings& settings)
{
if (lhs.scene != rhs.scene)
return false;
if (lhs.nodes.size() != rhs.nodes.size())
return false;
for (size_t i = 0; i < lhs.nodes.size(); ++i)
if (!canMergeMeshNodes(lhs.nodes[i], rhs.nodes[i], settings))
return false;
if (lhs.instances.size() != rhs.instances.size())
return false;
for (size_t i = 0; i < lhs.instances.size(); ++i)
if (!compareInstances(lhs.instances[i], rhs.instances[i]))
return false;
if (lhs.material != rhs.material)
return false;
if (lhs.skin != rhs.skin)
return false;
if (lhs.type != rhs.type)
return false;
if (!compareMeshTargets(lhs, rhs))
return false;
if (!compareMeshVariants(lhs, rhs))
return false;
if (lhs.indices.empty() != rhs.indices.empty())
return false;
if (lhs.streams.size() != rhs.streams.size())
return false;
if (settings.keep_extras && !areExtrasEqual(lhs.extras, rhs.extras))
return false;
for (size_t i = 0; i < lhs.streams.size(); ++i)
if (lhs.streams[i].type != rhs.streams[i].type || lhs.streams[i].index != rhs.streams[i].index || lhs.streams[i].target != rhs.streams[i].target)
return false;
return true;
}
static void mergeMeshes(Mesh& target, const Mesh& mesh)
{
assert(target.streams.size() == mesh.streams.size());
size_t vertex_offset = target.streams[0].data.size();
size_t index_offset = target.indices.size();
for (size_t i = 0; i < target.streams.size(); ++i)
target.streams[i].data.insert(target.streams[i].data.end(), mesh.streams[i].data.begin(), mesh.streams[i].data.end());
target.indices.resize(target.indices.size() + mesh.indices.size());
size_t index_count = mesh.indices.size();
for (size_t i = 0; i < index_count; ++i)
target.indices[index_offset + i] = unsigned(vertex_offset + mesh.indices[i]);
}
static void hashUpdate(uint64_t hash[2], const void* data, size_t size)
{
#define ROTL64(x, r) (((x) << (r)) | ((x) >> (64 - (r))))
// MurMurHash3 128-bit
const uint64_t c1 = 0x87c37b91114253d5ull;
const uint64_t c2 = 0x4cf5ad432745937full;
uint64_t h1 = hash[0], h2 = hash[1];
size_t offset = 0;
// body
for (; offset + 16 <= size; offset += 16)
{
uint64_t k1, k2;
memcpy(&k1, static_cast<const char*>(data) + offset + 0, 8);
memcpy(&k2, static_cast<const char*>(data) + offset + 8, 8);
k1 *= c1, k1 = ROTL64(k1, 31), k1 *= c2;
h1 ^= k1, h1 = ROTL64(h1, 27), h1 += h2;
h1 = h1 * 5 + 0x52dce729;
k2 *= c2, k2 = ROTL64(k2, 33), k2 *= c1;
h2 ^= k2, h2 = ROTL64(h2, 31), h2 += h1;
h2 = h2 * 5 + 0x38495ab5;
}
// tail
if (offset < size)
{
uint64_t tail[2] = {};
memcpy(tail, static_cast<const char*>(data) + offset, size - offset);
uint64_t k1 = tail[0], k2 = tail[1];
k1 *= c1, k1 = ROTL64(k1, 31), k1 *= c2;
h1 ^= k1;
k2 *= c2, k2 = ROTL64(k2, 33), k2 *= c1;
h2 ^= k2;
}
h1 ^= size;
h2 ^= size;
hash[0] = h1;
hash[1] = h2;
#undef ROTL64
}
void hashMesh(Mesh& mesh)
{
mesh.geometry_hash[0] = mesh.geometry_hash[1] = 41;
for (size_t i = 0; i < mesh.streams.size(); ++i)
{
const Stream& stream = mesh.streams[i];
int meta[3] = {stream.type, stream.index, stream.target};
hashUpdate(mesh.geometry_hash, meta, sizeof(meta));
if (stream.custom_name)
hashUpdate(mesh.geometry_hash, stream.custom_name, strlen(stream.custom_name));
hashUpdate(mesh.geometry_hash, stream.data.data(), stream.data.size() * sizeof(Attr));
}
if (!mesh.indices.empty())
hashUpdate(mesh.geometry_hash, mesh.indices.data(), mesh.indices.size() * sizeof(unsigned int));
int meta[4] = {int(mesh.streams.size()), mesh.streams.empty() ? 0 : int(mesh.streams[0].data.size()), int(mesh.indices.size()), mesh.type};
hashUpdate(mesh.geometry_hash, meta, sizeof(meta));
}
static bool canDedupMesh(const Mesh& mesh, const Settings& settings)
{
// empty mesh
if (mesh.streams.empty())
return false;
// world-space mesh
if (mesh.nodes.empty() && mesh.instances.empty())
return false;
// has extras
if (settings.keep_extras && mesh.extras.data)
return false;
// to simplify dedup we ignore complex target setups for now
if (!mesh.target_weights.empty() || !mesh.target_names.empty() || !mesh.variants.empty())
return false;
return true;
}
void dedupMeshes(std::vector<Mesh>& meshes, const Settings& settings)
{
std::unordered_map<uint64_t, int> hashes;
for (size_t i = 0; i < meshes.size(); ++i)
{
Mesh& mesh = meshes[i];
hashMesh(mesh);
hashes[mesh.geometry_hash[0] ^ mesh.geometry_hash[1]]++;
}
for (size_t i = 0; i < meshes.size(); ++i)
{
Mesh& target = meshes[i];
if (!canDedupMesh(target, settings))
continue;
if (hashes[target.geometry_hash[0] ^ target.geometry_hash[1]] <= 1)
continue;
for (size_t j = i + 1; j < meshes.size(); ++j)
{
Mesh& mesh = meshes[j];
if (mesh.geometry_hash[0] != target.geometry_hash[0] || mesh.geometry_hash[1] != target.geometry_hash[1])
continue;
if (!canDedupMesh(mesh, settings))
continue;
if (mesh.scene != target.scene || mesh.material != target.material || mesh.skin != target.skin)
{
// mark both meshes as having duplicate geometry; we don't use this in dedupMeshes but it's useful later in the pipeline
target.geometry_duplicate = true;
mesh.geometry_duplicate = true;
continue;
}
// basic sanity test; these should be included in geometry hash
assert(mesh.streams.size() == target.streams.size());
assert(mesh.streams[0].data.size() == target.streams[0].data.size());
assert(mesh.indices.size() == target.indices.size());
target.nodes.insert(target.nodes.end(), mesh.nodes.begin(), mesh.nodes.end());
target.instances.insert(target.instances.end(), mesh.instances.begin(), mesh.instances.end());
mesh.streams.clear();
mesh.indices.clear();
mesh.nodes.clear();
mesh.instances.clear();
}
}
for (size_t i = 0; i < meshes.size(); ++i)
{
Mesh& target = meshes[i];
if (target.nodes.size() <= 1)
continue;
std::sort(target.nodes.begin(), target.nodes.end());
target.nodes.erase(std::unique(target.nodes.begin(), target.nodes.end()), target.nodes.end());
}
}
void mergeMeshInstances(Mesh& mesh)
{
if (mesh.nodes.empty())
return;
// fast-path: for single instance meshes we transform in-place
if (mesh.nodes.size() == 1)
{
transformMesh(mesh, mesh, mesh.nodes[0]);
mesh.nodes.clear();
return;
}
Mesh base = mesh;
Mesh transformed = base;
for (size_t i = 0; i < mesh.streams.size(); ++i)
{
mesh.streams[i].data.clear();
mesh.streams[i].data.reserve(base.streams[i].data.size() * mesh.nodes.size());
}
mesh.indices.clear();
mesh.indices.reserve(base.indices.size() * mesh.nodes.size());
for (size_t i = 0; i < mesh.nodes.size(); ++i)
{
transformMesh(transformed, base, mesh.nodes[i]);
mergeMeshes(mesh, transformed);
}
mesh.nodes.clear();
}
void mergeMeshes(std::vector<Mesh>& meshes, const Settings& settings)
{
for (size_t i = 0; i < meshes.size(); ++i)
{
Mesh& target = meshes[i];
if (target.streams.empty())
continue;
size_t target_vertices = target.streams[0].data.size();
size_t target_indices = target.indices.size();
size_t last_merged = i;
for (size_t j = i + 1; j < meshes.size(); ++j)
{
Mesh& mesh = meshes[j];
if (!mesh.streams.empty() && canMergeMeshes(target, mesh, settings))
{
target_vertices += mesh.streams[0].data.size();
target_indices += mesh.indices.size();
last_merged = j;
}
}
for (size_t j = 0; j < target.streams.size(); ++j)
target.streams[j].data.reserve(target_vertices);
target.indices.reserve(target_indices);
for (size_t j = i + 1; j <= last_merged; ++j)
{
Mesh& mesh = meshes[j];
if (!mesh.streams.empty() && canMergeMeshes(target, mesh, settings))
{
mergeMeshes(target, mesh);
mesh.streams.clear();
mesh.indices.clear();
mesh.nodes.clear();
mesh.instances.clear();
}
}
assert(target.streams[0].data.size() == target_vertices);
assert(target.indices.size() == target_indices);
}
}
void filterEmptyMeshes(std::vector<Mesh>& meshes)
{
size_t write = 0;
for (size_t i = 0; i < meshes.size(); ++i)
{
Mesh& mesh = meshes[i];
if (mesh.streams.empty())
continue;
if (mesh.streams[0].data.empty())
continue;
if (mesh.type != cgltf_primitive_type_points && mesh.indices.empty())
continue;
// the following code is roughly equivalent to meshes[write] = std::move(mesh)
std::vector<Stream> streams;
streams.swap(mesh.streams);
std::vector<unsigned int> indices;
indices.swap(mesh.indices);
meshes[write] = mesh;
meshes[write].streams.swap(streams);
meshes[write].indices.swap(indices);
write++;
}
meshes.resize(write);
}
static bool isConstant(const std::vector<Attr>& data, const Attr& value, float tolerance = 0.01f)
{
for (size_t i = 0; i < data.size(); ++i)
{
const Attr& a = data[i];
if (fabsf(a.f[0] - value.f[0]) > tolerance || fabsf(a.f[1] - value.f[1]) > tolerance || fabsf(a.f[2] - value.f[2]) > tolerance || fabsf(a.f[3] - value.f[3]) > tolerance)
return false;
}
return true;
}
void filterStreams(Mesh& mesh, const MaterialInfo& mi)
{
bool morph_normal = false;
bool morph_tangent = false;
int keep_texture_set = -1;
for (size_t i = 0; i < mesh.streams.size(); ++i)
{
Stream& stream = mesh.streams[i];
if (stream.target)
{
morph_normal = morph_normal || (stream.type == cgltf_attribute_type_normal && !isConstant(stream.data, {0, 0, 0, 0}));
morph_tangent = morph_tangent || (stream.type == cgltf_attribute_type_tangent && !isConstant(stream.data, {0, 0, 0, 0}));
}
if (stream.type == cgltf_attribute_type_texcoord && stream.index < 32 && (mi.texture_set_mask & (1u << stream.index)) != 0)
{
keep_texture_set = std::max(keep_texture_set, stream.index);
}
}
size_t write = 0;
for (size_t i = 0; i < mesh.streams.size(); ++i)
{
Stream& stream = mesh.streams[i];
if (stream.type == cgltf_attribute_type_texcoord && stream.index > keep_texture_set)
continue;
if (stream.type == cgltf_attribute_type_normal && mi.unlit)
continue;
if (stream.type == cgltf_attribute_type_tangent && !mi.needs_tangents)
continue;
if ((stream.type == cgltf_attribute_type_joints || stream.type == cgltf_attribute_type_weights) && !mesh.skin)
continue;
if (stream.type == cgltf_attribute_type_color && isConstant(stream.data, {1, 1, 1, 1}))
continue;
if (stream.target && stream.type == cgltf_attribute_type_normal && !morph_normal)
continue;
if (stream.target && stream.type == cgltf_attribute_type_tangent && !morph_tangent)
continue;
if (mesh.type == cgltf_primitive_type_points && stream.type == cgltf_attribute_type_normal && !stream.data.empty() && isConstant(stream.data, stream.data[0]))
continue;
// the following code is roughly equivalent to streams[write] = std::move(stream)
std::vector<Attr> data;
data.swap(stream.data);
mesh.streams[write] = stream;
mesh.streams[write].data.swap(data);
write++;
}
mesh.streams.resize(write);
}
struct QuantizedTBN
{
int8_t nx, ny, nz, nw;
int8_t tx, ty, tz, tw;
};
static void quantizeTBN(QuantizedTBN* target, size_t offset, const Attr* source, size_t size, int bits)
{
int8_t* target8 = reinterpret_cast<int8_t*>(target) + offset;
for (size_t i = 0; i < size; ++i)
{
target8[i * sizeof(QuantizedTBN) + 0] = int8_t(meshopt_quantizeSnorm(source[i].f[0], bits));
target8[i * sizeof(QuantizedTBN) + 1] = int8_t(meshopt_quantizeSnorm(source[i].f[1], bits));
target8[i * sizeof(QuantizedTBN) + 2] = int8_t(meshopt_quantizeSnorm(source[i].f[2], bits));
target8[i * sizeof(QuantizedTBN) + 3] = int8_t(meshopt_quantizeSnorm(source[i].f[3], bits));
}
}
static void reindexMesh(Mesh& mesh, bool quantize_tbn)
{
size_t total_vertices = mesh.streams[0].data.size();
size_t total_indices = mesh.indices.size();
std::vector<QuantizedTBN> qtbn;
std::vector<meshopt_Stream> streams;
for (size_t i = 0; i < mesh.streams.size(); ++i)
{
const Stream& attr = mesh.streams[i];
if (attr.target)
continue;
assert(attr.data.size() == total_vertices);
if (quantize_tbn && (attr.type == cgltf_attribute_type_normal || attr.type == cgltf_attribute_type_tangent))
{
if (qtbn.empty())
{
qtbn.resize(total_vertices);
meshopt_Stream stream = {&qtbn[0], sizeof(QuantizedTBN), sizeof(QuantizedTBN)};
streams.push_back(stream);
}
size_t offset = attr.type == cgltf_attribute_type_normal ? offsetof(QuantizedTBN, nx) : offsetof(QuantizedTBN, tx);
quantizeTBN(&qtbn[0], offset, &attr.data[0], total_vertices, /* bits= */ 8);
}
else
{
meshopt_Stream stream = {&attr.data[0], sizeof(Attr), sizeof(Attr)};
streams.push_back(stream);
}
}
if (streams.empty())
return;
std::vector<unsigned int> remap(total_vertices);
size_t unique_vertices = meshopt_generateVertexRemapMulti(&remap[0], &mesh.indices[0], total_indices, total_vertices, &streams[0], streams.size());
assert(unique_vertices <= total_vertices);
meshopt_remapIndexBuffer(&mesh.indices[0], &mesh.indices[0], total_indices, &remap[0]);
for (size_t i = 0; i < mesh.streams.size(); ++i)
{
assert(mesh.streams[i].data.size() == total_vertices);
meshopt_remapVertexBuffer(&mesh.streams[i].data[0], &mesh.streams[i].data[0], total_vertices, sizeof(Attr), &remap[0]);
mesh.streams[i].data.resize(unique_vertices);
}
}
static void filterTriangles(Mesh& mesh)
{
assert(mesh.type == cgltf_primitive_type_triangles);
unsigned int* indices = &mesh.indices[0];
size_t total_indices = mesh.indices.size();
size_t write = 0;
for (size_t i = 0; i < total_indices; i += 3)
{
unsigned int a = indices[i + 0], b = indices[i + 1], c = indices[i + 2];
if (a != b && a != c && b != c)
{
indices[write + 0] = a;
indices[write + 1] = b;
indices[write + 2] = c;
write += 3;
}
}
mesh.indices.resize(write);
}
static void simplifyAttributes(std::vector<float>& attrs, float* attrw, size_t stride, Mesh& mesh)
{
assert(stride >= 6); // normal + color
size_t vertex_count = mesh.streams[0].data.size();
attrs.resize(vertex_count * stride);
float* data = attrs.data();
if (const Stream* attr = getStream(mesh, cgltf_attribute_type_normal))
{
const Attr* a = attr->data.data();
for (size_t i = 0; i < vertex_count; ++i)
{
data[i * stride + 0] = a[i].f[0];
data[i * stride + 1] = a[i].f[1];
data[i * stride + 2] = a[i].f[2];
}
attrw[0] = attrw[1] = attrw[2] = 0.5f;
}
if (const Stream* attr = getStream(mesh, cgltf_attribute_type_color))
{
const Attr* a = attr->data.data();
for (size_t i = 0; i < vertex_count; ++i)
{
data[i * stride + 3] = a[i].f[0] * a[i].f[3];
data[i * stride + 4] = a[i].f[1] * a[i].f[3];
data[i * stride + 5] = a[i].f[2] * a[i].f[3];
}
attrw[3] = attrw[4] = attrw[5] = 1.0f;
}
}
static void simplifyProtect(std::vector<unsigned char>& locks, Mesh& mesh, size_t presplit_vertices)
{
const Stream* positions = getStream(mesh, cgltf_attribute_type_position);
assert(positions);
size_t vertex_count = positions->data.size();
locks.resize(vertex_count);
unsigned char* data = locks.data();
std::vector<unsigned int> remap(vertex_count);
meshopt_generatePositionRemap(&remap[0], positions->data[0].f, vertex_count, sizeof(Attr));
// protect UV discontinuities
if (Stream* attr = getStream(mesh, cgltf_attribute_type_texcoord))
{
Attr* a = attr->data.data();
for (size_t i = 0; i < vertex_count; ++i)
{
unsigned int r = remap[i];
if (r != i && (a[i].f[0] != a[r].f[0] || a[i].f[1] != a[r].f[1]))
data[i] |= meshopt_SimplifyVertex_Protect;
}
}
// protect all vertices that were artificially split on the UV mirror edges
for (size_t i = presplit_vertices; i < vertex_count; ++i)
data[i] |= meshopt_SimplifyVertex_Protect;
}
static void simplifyUvSplit(Mesh& mesh, std::vector<unsigned int>& remap)
{
assert(mesh.type == cgltf_primitive_type_triangles);
assert(!mesh.indices.empty());
const Stream* uv = getStream(mesh, cgltf_attribute_type_texcoord);
if (!uv)
return;
size_t vertex_count = uv->data.size();
std::vector<unsigned char> uvsign(mesh.indices.size() / 3);
std::vector<unsigned char> flipseam(vertex_count);
for (size_t i = 0; i < mesh.indices.size(); i += 3)
{
unsigned int a = mesh.indices[i + 0];
unsigned int b = mesh.indices[i + 1];
unsigned int c = mesh.indices[i + 2];
const Attr& va = uv->data[a];
const Attr& vb = uv->data[b];
const Attr& vc = uv->data[c];
float uvarea = (vb.f[0] - va.f[0]) * (vc.f[1] - va.f[1]) - (vc.f[0] - va.f[0]) * (vb.f[1] - va.f[1]);
unsigned char flag = uvarea > 0 ? 1 : (uvarea < 0 ? 2 : 0);
uvsign[i / 3] = flag;
flipseam[a] |= flag;
flipseam[b] |= flag;
flipseam[c] |= flag;
}
std::vector<unsigned int> split(vertex_count);
size_t splits = 0;
remap.resize(vertex_count);
for (size_t i = 0; i < vertex_count; ++i)
{
remap[i] = unsigned(i);
if (flipseam[i] == 3)
{
assert(remap.size() == vertex_count + splits);
remap.push_back(unsigned(i));
split[i] = unsigned(vertex_count + splits);
splits++;
for (size_t k = 0; k < mesh.streams.size(); ++k)
mesh.streams[k].data.push_back(mesh.streams[k].data[i]);
}
}
for (size_t i = 0; i < mesh.indices.size(); i += 3)
{
unsigned int a = mesh.indices[i + 0];
unsigned int b = mesh.indices[i + 1];
unsigned int c = mesh.indices[i + 2];
unsigned char sign = uvsign[i / 3];
if (flipseam[a] == 3 && sign == 2)
mesh.indices[i + 0] = split[a];
if (flipseam[b] == 3 && sign == 2)
mesh.indices[i + 1] = split[b];
if (flipseam[c] == 3 && sign == 2)
mesh.indices[i + 2] = split[c];
}
}
static void simplifyMesh(Mesh& mesh, float threshold, float error, bool attributes, bool aggressive, bool lock_borders, bool permissive)
{
assert(mesh.type == cgltf_primitive_type_triangles);
if (mesh.indices.empty())
return;
const Stream* positions = getStream(mesh, cgltf_attribute_type_position);
if (!positions)
return;
size_t presplit_vertices = positions->data.size();
std::vector<unsigned int> uvremap;
if (attributes)
simplifyUvSplit(mesh, uvremap);
size_t vertex_count = positions->data.size();
size_t target_index_count = size_t(double(size_t(mesh.indices.size() / 3)) * threshold) * 3;
float target_error = error;
float target_error_aggressive = 1e-1f;
unsigned int options = 0;
if (lock_borders)
options |= meshopt_SimplifyLockBorder;
else
options |= meshopt_SimplifyPrune;
if (permissive)
options |= meshopt_SimplifyPermissive;
if (mesh.targets || getStream(mesh, cgltf_attribute_type_weights))
options |= meshopt_SimplifyRegularize;
std::vector<unsigned int> indices(mesh.indices.size());
float attrw[6] = {};
std::vector<float> attrs;
if (attributes)
simplifyAttributes(attrs, attrw, sizeof(attrw) / sizeof(attrw[0]), mesh);
std::vector<unsigned char> locks;
if (attributes && permissive)
simplifyProtect(locks, mesh, presplit_vertices);
if (attributes)
indices.resize(meshopt_simplifyWithAttributes(&indices[0], &mesh.indices[0], mesh.indices.size(), positions->data[0].f, vertex_count, sizeof(Attr),
attrs.data(), sizeof(attrw), attrw, sizeof(attrw) / sizeof(attrw[0]), permissive ? locks.data() : NULL, target_index_count, target_error, options));
else
indices.resize(meshopt_simplify(&indices[0], &mesh.indices[0], mesh.indices.size(), positions->data[0].f, vertex_count, sizeof(Attr), target_index_count, target_error, options));
mesh.indices.swap(indices);
// Note: if the simplifier got stuck, we can try to reindex without normals/tangents and retry
// For now we simply fall back to aggressive simplifier instead
// if the precise simplifier got "stuck", we'll try to simplify using the sloppy simplifier; this is only used when aggressive simplification is enabled as it breaks attribute discontinuities
if (aggressive && mesh.indices.size() > target_index_count)
{
indices.resize(meshopt_simplifySloppy(&indices[0], &mesh.indices[0], mesh.indices.size(), positions->data[0].f, vertex_count, sizeof(Attr), target_index_count, target_error_aggressive));
mesh.indices.swap(indices);
}
if (uvremap.size() && mesh.indices.size())
meshopt_remapIndexBuffer(&mesh.indices[0], &mesh.indices[0], mesh.indices.size(), &uvremap[0]);
}
static void optimizeMesh(Mesh& mesh, bool compressmore)
{
assert(mesh.type == cgltf_primitive_type_triangles);
if (mesh.indices.empty())
return;
size_t vertex_count = mesh.streams[0].data.size();
if (compressmore)
meshopt_optimizeVertexCacheStrip(&mesh.indices[0], &mesh.indices[0], mesh.indices.size(), vertex_count);
else
meshopt_optimizeVertexCache(&mesh.indices[0], &mesh.indices[0], mesh.indices.size(), vertex_count);
std::vector<unsigned int> remap(vertex_count);
size_t unique_vertices = meshopt_optimizeVertexFetchRemap(&remap[0], &mesh.indices[0], mesh.indices.size(), vertex_count);
assert(unique_vertices <= vertex_count);
meshopt_remapIndexBuffer(&mesh.indices[0], &mesh.indices[0], mesh.indices.size(), &remap[0]);
for (size_t i = 0; i < mesh.streams.size(); ++i)
{
assert(mesh.streams[i].data.size() == vertex_count);
meshopt_remapVertexBuffer(&mesh.streams[i].data[0], &mesh.streams[i].data[0], vertex_count, sizeof(Attr), &remap[0]);
mesh.streams[i].data.resize(unique_vertices);
}
}
struct BoneInfluence
{
float i;
float w;
};
struct BoneInfluenceWeightPredicate
{
bool operator()(const BoneInfluence& lhs, const BoneInfluence& rhs) const
{
return lhs.w > rhs.w;
}
};
static void filterBones(Mesh& mesh)
{
const int kMaxGroups = 8;
std::pair<Stream*, Stream*> groups[kMaxGroups];
int group_count = 0;
// gather all joint/weight groups; each group contains 4 bone influences
for (int i = 0; i < kMaxGroups; ++i)
{
Stream* jg = getStream(mesh, cgltf_attribute_type_joints, int(i));
Stream* wg = getStream(mesh, cgltf_attribute_type_weights, int(i));
if (!jg || !wg)
break;
groups[group_count++] = std::make_pair(jg, wg);
}
if (group_count == 0)
return;
// weights below cutoff can't be represented in quantized 8-bit storage
const float weight_cutoff = 0.5f / 255.f;
size_t vertex_count = mesh.streams[0].data.size();
BoneInfluence inf[kMaxGroups * 4] = {};
for (size_t i = 0; i < vertex_count; ++i)
{
int count = 0;
// gather all bone influences for this vertex
for (int j = 0; j < group_count; ++j)
{
const Attr& ja = groups[j].first->data[i];
const Attr& wa = groups[j].second->data[i];
for (int k = 0; k < 4; ++k)
if (wa.f[k] > weight_cutoff)
{
inf[count].i = ja.f[k];
inf[count].w = wa.f[k];
count++;
}
}
// pick top 4 influences; this also sorts resulting influences by weight which helps renderers that use influence subset in shader LODs
std::sort(inf, inf + count, BoneInfluenceWeightPredicate());
// copy the top 4 influences back into stream 0 - we will remove other streams at the end
Attr& ja = groups[0].first->data[i];
Attr& wa = groups[0].second->data[i];
for (int k = 0; k < 4; ++k)
{
if (k < count)
{
ja.f[k] = inf[k].i;
wa.f[k] = inf[k].w;
}
else
{
ja.f[k] = 0.f;
wa.f[k] = 0.f;
}
}
}
// remove redundant weight/joint streams
for (size_t i = 0; i < mesh.streams.size();)
{
Stream& s = mesh.streams[i];
if ((s.type == cgltf_attribute_type_joints || s.type == cgltf_attribute_type_weights) && s.index > 0)
mesh.streams.erase(mesh.streams.begin() + i);
else
++i;
}
}
static void simplifyPointMesh(Mesh& mesh, float threshold)
{
assert(mesh.type == cgltf_primitive_type_points);
if (threshold >= 1)
return;
const Stream* positions = getStream(mesh, cgltf_attribute_type_position);
if (!positions)
return;
const Stream* colors = getStream(mesh, cgltf_attribute_type_color);
size_t vertex_count = mesh.streams[0].data.size();
size_t target_vertex_count = size_t(double(vertex_count) * threshold);
const float color_weight = 1;
std::vector<unsigned int> indices(target_vertex_count);
if (target_vertex_count)
indices.resize(meshopt_simplifyPoints(&indices[0], positions->data[0].f, vertex_count, sizeof(Attr), colors ? colors->data[0].f : NULL, sizeof(Attr), color_weight, target_vertex_count));
std::vector<Attr> scratch(indices.size());
for (size_t i = 0; i < mesh.streams.size(); ++i)
{
std::vector<Attr>& data = mesh.streams[i].data;
assert(data.size() == vertex_count);
for (size_t j = 0; j < indices.size(); ++j)
scratch[j] = data[indices[j]];
data = scratch;
}
}
static void sortPointMesh(Mesh& mesh)
{
assert(mesh.type == cgltf_primitive_type_points);
const Stream* positions = getStream(mesh, cgltf_attribute_type_position);
if (!positions)
return;
// skip spatial sort in presence of custom attributes, since when they refer to mesh features their order is more important to preserve for compression efficiency
if (getStream(mesh, cgltf_attribute_type_custom))
return;
size_t vertex_count = mesh.streams[0].data.size();
std::vector<unsigned int> remap(vertex_count);
meshopt_spatialSortRemap(&remap[0], positions->data[0].f, vertex_count, sizeof(Attr));
for (size_t i = 0; i < mesh.streams.size(); ++i)
{
assert(mesh.streams[i].data.size() == vertex_count);
meshopt_remapVertexBuffer(&mesh.streams[i].data[0], &mesh.streams[i].data[0], vertex_count, sizeof(Attr), &remap[0]);
}
}
void processMesh(Mesh& mesh, const Settings& settings)
{
switch (mesh.type)
{
case cgltf_primitive_type_points:
assert(mesh.indices.empty());
simplifyPointMesh(mesh, settings.simplify_ratio);
sortPointMesh(mesh);
break;
case cgltf_primitive_type_lines:
break;
case cgltf_primitive_type_triangles:
filterBones(mesh);
reindexMesh(mesh, settings.quantize && !settings.nrm_float);
filterTriangles(mesh);
if (settings.simplify_ratio < 1)
{
float error = settings.simplify_scaled ? settings.simplify_error / mesh.quality : settings.simplify_error;
simplifyMesh(mesh, settings.simplify_ratio, error, settings.simplify_attributes, settings.simplify_aggressive, settings.simplify_lock_borders, settings.simplify_permissive);
}
optimizeMesh(mesh, settings.compressmore);
break;
default:
assert(!"Unknown primitive type");
}
}
static float getScale(const float* transform)
{
float translation[3], rotation[4], scale[3];
decomposeTransform(translation, rotation, scale, transform);
float sx = fabsf(scale[0]), sy = fabsf(scale[1]), sz = fabsf(scale[2]);
return std::max(std::max(sx, sy), sz);
}
void computeMeshQuality(std::vector<Mesh>& meshes)
{
std::vector<float> scales(meshes.size(), 1.f);
float maxscale = 0.f;
for (size_t i = 0; i < meshes.size(); ++i)
{
Mesh& mesh = meshes[i];
const Stream* positions = getStream(mesh, cgltf_attribute_type_position);
if (!positions)
continue;
float geometry_scale = meshopt_simplifyScale(positions->data[0].f, positions->data.size(), sizeof(Attr));
float node_maxscale = 0.f;
for (cgltf_node* node : mesh.nodes)
{
float transform[16];
cgltf_node_transform_world(node, transform);
node_maxscale = std::max(node_maxscale, getScale(transform));
}
for (const Instance& xf : mesh.instances)
node_maxscale = std::max(node_maxscale, getScale(xf.transform));
scales[i] = node_maxscale == 0.f ? geometry_scale : node_maxscale * geometry_scale;
maxscale = std::max(maxscale, scales[i]);
}
for (size_t i = 0; i < meshes.size(); ++i)
meshes[i].quality = (scales[i] == 0.f || maxscale == 0.f) ? 1.f : scales[i] / maxscale;
}
bool hasVertexAlpha(const Mesh& mesh)
{
const Stream* color = getStream(const_cast<Mesh&>(mesh), cgltf_attribute_type_color);
if (!color)
return false;
for (size_t i = 0; i < color->data.size(); ++i)
if (color->data[i].f[3] < 1.f)
return true;
return false;
}
bool hasInstanceAlpha(const std::vector<Instance>& instances)
{
for (const Instance& instance : instances)
if (instance.color[3] < 1.f)
return true;
return false;
}
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
gltf/node.cpp | C++ | // This file is part of gltfpack; see gltfpack.h for version/license details
#include "gltfpack.h"
#include <math.h>
#include <string.h>
void markScenes(cgltf_data* data, std::vector<NodeInfo>& nodes)
{
for (size_t i = 0; i < nodes.size(); ++i)
nodes[i].scene = -1;
for (size_t i = 0; i < data->scenes_count; ++i)
for (size_t j = 0; j < data->scenes[i].nodes_count; ++j)
{
NodeInfo& ni = nodes[data->scenes[i].nodes[j] - data->nodes];
if (ni.scene >= 0)
ni.scene = -2; // multiple scenes
else
ni.scene = int(i);
}
for (size_t i = 0; i < data->nodes_count; ++i)
{
cgltf_node* root = &data->nodes[i];
while (root->parent)
root = root->parent;
nodes[i].scene = nodes[root - data->nodes].scene;
}
}
void markAnimated(cgltf_data* data, std::vector<NodeInfo>& nodes, const std::vector<Animation>& animations)
{
for (size_t i = 0; i < animations.size(); ++i)
{
const Animation& animation = animations[i];
for (size_t j = 0; j < animation.tracks.size(); ++j)
{
const Track& track = animation.tracks[j];
// mark nodes that have animation tracks that change their base transform as animated
if (!track.dummy)
{
NodeInfo& ni = nodes[track.node - data->nodes];
ni.animated_path_mask |= (1 << track.path);
}
}
}
for (size_t i = 0; i < data->nodes_count; ++i)
{
NodeInfo& ni = nodes[i];
for (cgltf_node* node = &data->nodes[i]; node; node = node->parent)
ni.animated |= nodes[node - data->nodes].animated_path_mask != 0;
}
}
void markNeededNodes(cgltf_data* data, std::vector<NodeInfo>& nodes, const std::vector<Mesh>& meshes, const std::vector<Animation>& animations, const Settings& settings)
{
// mark all joints as kept
for (size_t i = 0; i < data->skins_count; ++i)
{
const cgltf_skin& skin = data->skins[i];
// for now we keep all joints directly referenced by the skin and the entire ancestry tree; we keep names for joints as well
for (size_t j = 0; j < skin.joints_count; ++j)
{
NodeInfo& ni = nodes[skin.joints[j] - data->nodes];
ni.keep = true;
}
}
// mark all animated nodes as kept
for (size_t i = 0; i < animations.size(); ++i)
{
const Animation& animation = animations[i];
for (size_t j = 0; j < animation.tracks.size(); ++j)
{
const Track& track = animation.tracks[j];
if (settings.anim_const || !track.dummy)
{
NodeInfo& ni = nodes[track.node - data->nodes];
ni.keep = true;
}
}
}
// mark all mesh nodes as kept
for (size_t i = 0; i < meshes.size(); ++i)
{
const Mesh& mesh = meshes[i];
for (size_t j = 0; j < mesh.nodes.size(); ++j)
{
NodeInfo& ni = nodes[mesh.nodes[j] - data->nodes];
ni.keep = true;
}
}
// mark all light/camera nodes as kept
for (size_t i = 0; i < data->nodes_count; ++i)
{
const cgltf_node& node = data->nodes[i];
if (node.light || node.camera)
{
nodes[i].keep = true;
}
}
// mark all named nodes as needed (if -kn is specified)
if (settings.keep_nodes)
{
for (size_t i = 0; i < data->nodes_count; ++i)
{
const cgltf_node& node = data->nodes[i];
if (node.name && *node.name)
{
nodes[i].keep = true;
}
}
}
}
void remapNodes(cgltf_data* data, std::vector<NodeInfo>& nodes, size_t& node_offset)
{
// to keep a node, we currently need to keep the entire ancestry chain
for (size_t i = 0; i < data->nodes_count; ++i)
{
if (!nodes[i].keep)
continue;
for (cgltf_node* node = &data->nodes[i]; node; node = node->parent)
nodes[node - data->nodes].keep = true;
}
// generate sequential indices for all nodes; they aren't sorted topologically
for (size_t i = 0; i < data->nodes_count; ++i)
{
NodeInfo& ni = nodes[i];
if (ni.keep)
{
ni.remap = int(node_offset);
node_offset++;
}
}
}
void decomposeTransform(float translation[3], float rotation[4], float scale[3], const float* transform)
{
float m[4][4] = {};
memcpy(m, transform, 16 * sizeof(float));
// extract translation from last row
translation[0] = m[3][0];
translation[1] = m[3][1];
translation[2] = m[3][2];
// compute determinant to determine handedness
float det =
m[0][0] * (m[1][1] * m[2][2] - m[2][1] * m[1][2]) -
m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) +
m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]);
float sign = (det < 0.f) ? -1.f : 1.f;
// recover scale from axis lengths
scale[0] = sqrtf(m[0][0] * m[0][0] + m[0][1] * m[0][1] + m[0][2] * m[0][2]) * sign;
scale[1] = sqrtf(m[1][0] * m[1][0] + m[1][1] * m[1][1] + m[1][2] * m[1][2]) * sign;
scale[2] = sqrtf(m[2][0] * m[2][0] + m[2][1] * m[2][1] + m[2][2] * m[2][2]) * sign;
// normalize axes to get a pure rotation matrix
float rsx = (scale[0] == 0.f) ? 0.f : 1.f / scale[0];
float rsy = (scale[1] == 0.f) ? 0.f : 1.f / scale[1];
float rsz = (scale[2] == 0.f) ? 0.f : 1.f / scale[2];
float r00 = m[0][0] * rsx, r10 = m[1][0] * rsy, r20 = m[2][0] * rsz;
float r01 = m[0][1] * rsx, r11 = m[1][1] * rsy, r21 = m[2][1] * rsz;
float r02 = m[0][2] * rsx, r12 = m[1][2] * rsy, r22 = m[2][2] * rsz;
// "branchless" version of Mike Day's matrix to quaternion conversion
int qc = r22 < 0 ? (r00 > r11 ? 0 : 1) : (r00 < -r11 ? 2 : 3);
float qs1 = qc & 2 ? -1.f : 1.f;
float qs2 = qc & 1 ? -1.f : 1.f;
float qs3 = (qc - 1) & 2 ? -1.f : 1.f;
float qt = 1.f - qs3 * r00 - qs2 * r11 - qs1 * r22;
float qs = 0.5f / sqrtf(qt);
rotation[qc ^ 0] = qs * qt;
rotation[qc ^ 1] = qs * (r01 + qs1 * r10);
rotation[qc ^ 2] = qs * (r20 + qs2 * r02);
rotation[qc ^ 3] = qs * (r12 + qs3 * r21);
}
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
gltf/parsegltf.cpp | C++ | // This file is part of gltfpack; see gltfpack.h for version/license details
#include "gltfpack.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../src/meshoptimizer.h"
static const size_t kMaxStreams = 16;
static const char* getError(cgltf_result result, cgltf_data* data)
{
switch (result)
{
case cgltf_result_file_not_found:
return data ? "resource not found" : "file not found";
case cgltf_result_io_error:
return "I/O error";
case cgltf_result_invalid_json:
return "invalid JSON";
case cgltf_result_invalid_gltf:
return "invalid GLTF";
case cgltf_result_out_of_memory:
return "out of memory";
case cgltf_result_legacy_gltf:
return "legacy GLTF";
case cgltf_result_data_too_short:
return data ? "buffer too short" : "not a GLTF file";
case cgltf_result_unknown_format:
return data ? "unknown resource format" : "not a GLTF file";
default:
return "unknown error";
}
}
static void readAccessor(std::vector<float>& data, const cgltf_accessor* accessor)
{
assert(accessor->type == cgltf_type_scalar);
data.resize(accessor->count);
cgltf_accessor_unpack_floats(accessor, &data[0], data.size());
}
static void readAccessor(std::vector<Attr>& data, const cgltf_accessor* accessor)
{
size_t components = cgltf_num_components(accessor->type);
std::vector<float> temp(accessor->count * components);
cgltf_accessor_unpack_floats(accessor, &temp[0], temp.size());
data.resize(accessor->count);
for (size_t i = 0; i < accessor->count; ++i)
{
for (size_t k = 0; k < components && k < 4; ++k)
data[i].f[k] = temp[i * components + k];
}
}
static void readAccessor(std::vector<Attr>& data, const cgltf_accessor* accessor, const std::vector<unsigned int>& sparse)
{
data.resize(sparse.size());
for (size_t i = 0; i < sparse.size(); ++i)
cgltf_accessor_read_float(accessor, sparse[i], &data[i].f[0], 4);
}
static void fixupIndices(std::vector<unsigned int>& indices, cgltf_primitive_type& type)
{
if (type == cgltf_primitive_type_line_loop)
{
std::vector<unsigned int> result;
result.reserve(indices.size() * 2 + 2);
for (size_t i = 1; i <= indices.size(); ++i)
{
result.push_back(indices[i - 1]);
result.push_back(indices[i % indices.size()]);
}
indices.swap(result);
type = cgltf_primitive_type_lines;
}
else if (type == cgltf_primitive_type_line_strip)
{
std::vector<unsigned int> result;
result.reserve(indices.size() * 2);
for (size_t i = 1; i < indices.size(); ++i)
{
result.push_back(indices[i - 1]);
result.push_back(indices[i]);
}
indices.swap(result);
type = cgltf_primitive_type_lines;
}
else if (type == cgltf_primitive_type_triangle_strip)
{
std::vector<unsigned int> result;
result.reserve(indices.size() * 3);
for (size_t i = 2; i < indices.size(); ++i)
{
int flip = i & 1;
result.push_back(indices[i - 2 + flip]);
result.push_back(indices[i - 1 - flip]);
result.push_back(indices[i]);
}
indices.swap(result);
type = cgltf_primitive_type_triangles;
}
else if (type == cgltf_primitive_type_triangle_fan)
{
std::vector<unsigned int> result;
result.reserve(indices.size() * 3);
for (size_t i = 2; i < indices.size(); ++i)
{
result.push_back(indices[0]);
result.push_back(indices[i - 1]);
result.push_back(indices[i]);
}
indices.swap(result);
type = cgltf_primitive_type_triangles;
}
else if (type == cgltf_primitive_type_lines)
{
// glTF files don't require that line index count is divisible by 2, but it is obviously critical for scenes to render
indices.resize(indices.size() / 2 * 2);
}
else if (type == cgltf_primitive_type_triangles)
{
// glTF files don't require that triangle index count is divisible by 3, but it is obviously critical for scenes to render
indices.resize(indices.size() / 3 * 3);
}
}
static bool isIdAttribute(const char* name)
{
return strcmp(name, "_ID") == 0 ||
strcmp(name, "_BATCHID") == 0 ||
strncmp(name, "_FEATURE_ID_", 12) == 0;
}
static void parseMeshesGltf(cgltf_data* data, std::vector<Mesh>& meshes, std::vector<std::pair<size_t, size_t> >& mesh_remap)
{
size_t total_primitives = 0;
for (size_t mi = 0; mi < data->meshes_count; ++mi)
total_primitives += data->meshes[mi].primitives_count;
meshes.reserve(total_primitives);
mesh_remap.resize(data->meshes_count);
for (size_t mi = 0; mi < data->meshes_count; ++mi)
{
const cgltf_mesh& mesh = data->meshes[mi];
size_t remap_offset = meshes.size();
for (size_t pi = 0; pi < mesh.primitives_count; ++pi)
{
const cgltf_primitive& primitive = mesh.primitives[pi];
if (primitive.type == cgltf_primitive_type_points && primitive.indices)
{
fprintf(stderr, "Warning: ignoring primitive %d of mesh %d because indexed points are not supported\n", int(pi), int(mi));
continue;
}
meshes.push_back(Mesh());
Mesh& result = meshes.back();
result.scene = -1;
result.material = primitive.material;
result.extras = primitive.extras;
result.type = primitive.type;
result.streams.reserve(primitive.attributes_count);
size_t vertex_count = primitive.attributes_count ? primitive.attributes[0].data->count : 0;
if (primitive.indices)
{
result.indices.resize(primitive.indices->count);
if (!result.indices.empty())
cgltf_accessor_unpack_indices(primitive.indices, &result.indices[0], sizeof(unsigned int), result.indices.size());
for (size_t i = 0; i < result.indices.size(); ++i)
assert(result.indices[i] < vertex_count);
}
else if (primitive.type != cgltf_primitive_type_points)
{
// note, while we could generate a good index buffer here, mesh will be reindexed during processing
result.indices.resize(vertex_count);
for (size_t i = 0; i < vertex_count; ++i)
result.indices[i] = unsigned(i);
}
// convert line loops and line/triangle strips to lists
fixupIndices(result.indices, result.type);
std::vector<unsigned int> sparse;
// if the index data is very sparse, switch to deindexing on the fly to avoid the excessive cost of reading large accessors
if (!result.indices.empty() && result.indices.size() < vertex_count / 2)
{
sparse = result.indices;
// mesh will be reindexed during processing
for (size_t i = 0; i < result.indices.size(); ++i)
result.indices[i] = unsigned(i);
}
for (size_t ai = 0; ai < primitive.attributes_count; ++ai)
{
const cgltf_attribute& attr = primitive.attributes[ai];
if (attr.type == cgltf_attribute_type_invalid || (attr.type == cgltf_attribute_type_custom && !isIdAttribute(attr.name)))
{
fprintf(stderr, "Warning: ignoring %s attribute %s in primitive %d of mesh %d\n", attr.type == cgltf_attribute_type_invalid ? "unknown" : "custom", attr.name, int(pi), int(mi));
continue;
}
if (result.streams.size() == kMaxStreams)
{
fprintf(stderr, "Warning: ignoring attribute %s in primitive %d of mesh %d (limit %d reached)\n", attr.name, int(pi), int(mi), int(kMaxStreams));
continue;
}
result.streams.push_back(Stream());
Stream& s = result.streams.back();
s.type = attr.type;
s.index = attr.index;
if (attr.type == cgltf_attribute_type_custom)
s.custom_name = attr.name;
if (sparse.empty())
readAccessor(s.data, attr.data);
else
readAccessor(s.data, attr.data, sparse);
if (attr.type == cgltf_attribute_type_color && attr.data->type == cgltf_type_vec3)
{
for (size_t i = 0; i < s.data.size(); ++i)
s.data[i].f[3] = 1.0f;
}
}
for (size_t ti = 0; ti < primitive.targets_count; ++ti)
{
const cgltf_morph_target& target = primitive.targets[ti];
for (size_t ai = 0; ai < target.attributes_count; ++ai)
{
const cgltf_attribute& attr = target.attributes[ai];
if (attr.type == cgltf_attribute_type_invalid || attr.type == cgltf_attribute_type_custom)
{
fprintf(stderr, "Warning: ignoring %s attribute %s in morph target %d of primitive %d of mesh %d\n", attr.type == cgltf_attribute_type_invalid ? "unknown" : "custom", attr.name, int(ti), int(pi), int(mi));
continue;
}
result.streams.push_back(Stream());
Stream& s = result.streams.back();
s.type = attr.type;
s.index = attr.index;
s.target = int(ti + 1);
if (sparse.empty())
readAccessor(s.data, attr.data);
else
readAccessor(s.data, attr.data, sparse);
}
}
result.targets = primitive.targets_count;
result.target_weights.assign(mesh.weights, mesh.weights + mesh.weights_count);
result.target_names.assign(mesh.target_names, mesh.target_names + mesh.target_names_count);
result.variants.assign(primitive.mappings, primitive.mappings + primitive.mappings_count);
}
mesh_remap[mi] = std::make_pair(remap_offset, meshes.size());
}
}
static void parseMeshInstancesGltf(std::vector<Instance>& instances, cgltf_node* node, size_t ni)
{
cgltf_accessor* translation = NULL;
cgltf_accessor* rotation = NULL;
cgltf_accessor* scale = NULL;
cgltf_accessor* color = NULL;
for (size_t i = 0; i < node->mesh_gpu_instancing.attributes_count; ++i)
{
const cgltf_attribute& attr = node->mesh_gpu_instancing.attributes[i];
if (strcmp(attr.name, "TRANSLATION") == 0 && attr.data->type == cgltf_type_vec3)
translation = attr.data;
else if (strcmp(attr.name, "ROTATION") == 0 && attr.data->type == cgltf_type_vec4)
rotation = attr.data;
else if (strcmp(attr.name, "SCALE") == 0 && attr.data->type == cgltf_type_vec3)
scale = attr.data;
else if (strcmp(attr.name, "_COLOR_0") == 0 && (attr.data->type == cgltf_type_vec3 || attr.data->type == cgltf_type_vec4))
color = attr.data;
else
fprintf(stderr, "Warning: ignoring %s instance attribute %s in node %d\n", *attr.name == '_' ? "custom" : "unknown", attr.name, int(ni));
}
size_t count = node->mesh_gpu_instancing.attributes[0].data->count;
instances.reserve(instances.size() + count);
cgltf_node instance = {};
instance.parent = node;
instance.has_translation = translation != NULL;
instance.has_rotation = rotation != NULL;
instance.has_scale = scale != NULL;
instance.rotation[3] = 1.f;
instance.scale[0] = 1.f;
instance.scale[1] = 1.f;
instance.scale[2] = 1.f;
for (size_t i = 0; i < count; ++i)
{
if (translation)
cgltf_accessor_read_float(translation, i, instance.translation, 4);
if (rotation)
cgltf_accessor_read_float(rotation, i, instance.rotation, 4);
if (scale)
cgltf_accessor_read_float(scale, i, instance.scale, 4);
Instance obj = {};
cgltf_node_transform_world(&instance, obj.transform);
obj.color[0] = obj.color[1] = obj.color[2] = obj.color[3] = 1.0f;
if (color)
cgltf_accessor_read_float(color, i, obj.color, 4);
instances.push_back(obj);
}
}
static void parseMeshNodesGltf(cgltf_data* data, std::vector<Mesh>& meshes, const std::vector<std::pair<size_t, size_t> >& mesh_remap)
{
for (size_t i = 0; i < data->nodes_count; ++i)
{
cgltf_node& node = data->nodes[i];
if (!node.mesh)
continue;
std::pair<size_t, size_t> range = mesh_remap[node.mesh - data->meshes];
for (size_t mi = range.first; mi < range.second; ++mi)
{
Mesh* mesh = &meshes[mi];
if (mesh->skin != node.skin && (!mesh->nodes.empty() || !mesh->instances.empty()))
{
// this should be extremely rare - if the same mesh is used with different skins, we need to duplicate it
// in this case we don't spend any effort on keeping the number of duplicates to the minimum, because this
// should really never happen.
meshes.push_back(*mesh);
mesh = &meshes.back();
}
if (node.has_mesh_gpu_instancing)
{
mesh->scene = 0; // we need to assign scene index since instances are attached to a scene; for now we assume 0
parseMeshInstancesGltf(mesh->instances, &node, i);
}
else
{
mesh->skin = node.skin;
mesh->nodes.push_back(&node);
}
}
}
for (size_t i = 0; i < meshes.size(); ++i)
{
Mesh& mesh = meshes[i];
// because the rest of gltfpack assumes that empty nodes array = world-space mesh, we need to filter unused meshes
if (mesh.nodes.empty() && mesh.instances.empty())
{
mesh.streams.clear();
mesh.indices.clear();
}
}
}
static void parseAnimationsGltf(cgltf_data* data, std::vector<Animation>& animations)
{
animations.reserve(data->animations_count);
for (size_t i = 0; i < data->animations_count; ++i)
{
const cgltf_animation& animation = data->animations[i];
animations.push_back(Animation());
Animation& result = animations.back();
result.name = animation.name;
result.tracks.reserve(animation.channels_count);
for (size_t j = 0; j < animation.channels_count; ++j)
{
const cgltf_animation_channel& channel = animation.channels[j];
if (!channel.target_node)
{
fprintf(stderr, "Warning: ignoring channel %d of animation %d (%s) because it has no target node\n", int(j), int(i), animation.name ? animation.name : "");
continue;
}
result.tracks.push_back(Track());
Track& track = result.tracks.back();
track.node = channel.target_node;
track.path = channel.target_path;
track.components = (channel.target_path == cgltf_animation_path_type_weights) ? track.node->mesh->primitives[0].targets_count : 1;
track.interpolation = channel.sampler->interpolation;
readAccessor(track.time, channel.sampler->input);
readAccessor(track.data, channel.sampler->output);
}
if (result.tracks.empty())
{
fprintf(stderr, "Warning: ignoring animation %d (%s) because it has no valid tracks\n", int(i), animation.name ? animation.name : "");
animations.pop_back();
}
}
}
static bool requiresExtension(cgltf_data* data, const char* name)
{
for (size_t i = 0; i < data->extensions_required_count; ++i)
if (strcmp(data->extensions_required[i], name) == 0)
return true;
return false;
}
static bool needsDummyBuffers(cgltf_data* data)
{
for (size_t i = 0; i < data->accessors_count; ++i)
{
cgltf_accessor* accessor = &data->accessors[i];
if (accessor->buffer_view && accessor->buffer_view->data == NULL && accessor->buffer_view->buffer->data == NULL)
return true;
if (accessor->is_sparse)
{
cgltf_accessor_sparse* sparse = &accessor->sparse;
if (sparse->indices_buffer_view->buffer->data == NULL)
return true;
if (sparse->values_buffer_view->buffer->data == NULL)
return true;
}
}
for (size_t i = 0; i < data->images_count; ++i)
{
cgltf_image* image = &data->images[i];
if (image->buffer_view && image->buffer_view->buffer->data == NULL)
return true;
}
return false;
}
static void freeFile(cgltf_data* data)
{
data->json = NULL;
data->bin = NULL;
free(data->file_data);
data->file_data = NULL;
}
static bool freeUnusedBuffers(cgltf_data* data)
{
std::vector<char> used(data->buffers_count);
for (size_t i = 0; i < data->skins_count; ++i)
{
const cgltf_skin& skin = data->skins[i];
if (skin.inverse_bind_matrices && skin.inverse_bind_matrices->buffer_view)
{
assert(skin.inverse_bind_matrices->buffer_view->buffer);
used[skin.inverse_bind_matrices->buffer_view->buffer - data->buffers] = 1;
}
}
for (size_t i = 0; i < data->images_count; ++i)
{
const cgltf_image& image = data->images[i];
if (image.buffer_view)
{
assert(image.buffer_view->buffer);
used[image.buffer_view->buffer - data->buffers] = 1;
}
}
bool free_bin = false;
for (size_t i = 0; i < data->buffers_count; ++i)
{
cgltf_buffer& buffer = data->buffers[i];
if (!used[i] && buffer.data)
{
if (buffer.data != data->bin)
free(buffer.data);
else
free_bin = true;
buffer.data = NULL;
}
}
return free_bin;
}
static cgltf_result decompressMeshopt(cgltf_data* data)
{
for (size_t i = 0; i < data->buffer_views_count; ++i)
{
if (!data->buffer_views[i].has_meshopt_compression)
continue;
cgltf_meshopt_compression* mc = &data->buffer_views[i].meshopt_compression;
const unsigned char* source = (const unsigned char*)mc->buffer->data;
if (!source)
return cgltf_result_invalid_gltf;
source += mc->offset;
void* result = malloc(mc->count * mc->stride);
if (!result)
return cgltf_result_out_of_memory;
data->buffer_views[i].data = result;
int rc = -1;
switch (mc->mode)
{
case cgltf_meshopt_compression_mode_attributes:
rc = meshopt_decodeVertexBuffer(result, mc->count, mc->stride, source, mc->size);
break;
case cgltf_meshopt_compression_mode_triangles:
rc = meshopt_decodeIndexBuffer(result, mc->count, mc->stride, source, mc->size);
break;
case cgltf_meshopt_compression_mode_indices:
rc = meshopt_decodeIndexSequence(result, mc->count, mc->stride, source, mc->size);
break;
default:
return cgltf_result_invalid_gltf;
}
if (rc != 0)
return cgltf_result_io_error;
switch (mc->filter)
{
case cgltf_meshopt_compression_filter_octahedral:
meshopt_decodeFilterOct(result, mc->count, mc->stride);
break;
case cgltf_meshopt_compression_filter_quaternion:
meshopt_decodeFilterQuat(result, mc->count, mc->stride);
break;
case cgltf_meshopt_compression_filter_exponential:
meshopt_decodeFilterExp(result, mc->count, mc->stride);
break;
case cgltf_meshopt_compression_filter_color:
meshopt_decodeFilterColor(result, mc->count, mc->stride);
break;
default:
break;
}
}
return cgltf_result_success;
}
static cgltf_data* parseGltf(cgltf_data* data, cgltf_result result, std::vector<Mesh>& meshes, std::vector<Animation>& animations, const char** error)
{
*error = NULL;
if (result != cgltf_result_success)
*error = getError(result, data);
else if (requiresExtension(data, "KHR_draco_mesh_compression"))
*error = "file requires Draco mesh compression support";
else if (needsDummyBuffers(data))
*error = "buffer has no data";
if (*error)
{
cgltf_free(data);
return NULL;
}
if (requiresExtension(data, "KHR_mesh_quantization"))
fprintf(stderr, "Warning: file uses quantized geometry; repacking may result in increased quantization error\n");
if (requiresExtension(data, "EXT_mesh_gpu_instancing") && data->scenes_count > 1)
fprintf(stderr, "Warning: file uses instancing and has more than one scene; results may be incorrect\n");
std::vector<std::pair<size_t, size_t> > mesh_remap;
parseMeshesGltf(data, meshes, mesh_remap);
parseMeshNodesGltf(data, meshes, mesh_remap);
parseAnimationsGltf(data, animations);
bool free_bin = freeUnusedBuffers(data);
if (data->bin && free_bin)
freeFile(data);
return data;
}
cgltf_data* parseGltf(const char* path, std::vector<Mesh>& meshes, std::vector<Animation>& animations, const char** error)
{
cgltf_data* data = NULL;
cgltf_options options = {};
cgltf_result result = cgltf_parse_file(&options, path, &data);
if (result == cgltf_result_success && !data->bin)
freeFile(data);
result = (result == cgltf_result_success) ? cgltf_load_buffers(&options, data, path) : result;
result = (result == cgltf_result_success) ? cgltf_validate(data) : result;
result = (result == cgltf_result_success) ? decompressMeshopt(data) : result;
return parseGltf(data, result, meshes, animations, error);
}
cgltf_data* parseGlb(const void* buffer, size_t size, std::vector<Mesh>& meshes, std::vector<Animation>& animations, const char** error)
{
cgltf_data* data = NULL;
cgltf_options options = {};
options.type = cgltf_file_type_glb;
cgltf_result result = cgltf_parse(&options, buffer, size, &data);
result = (result == cgltf_result_success) ? cgltf_load_buffers(&options, data, NULL) : result;
result = (result == cgltf_result_success) ? cgltf_validate(data) : result;
result = (result == cgltf_result_success) ? decompressMeshopt(data) : result;
return parseGltf(data, result, meshes, animations, error);
}
bool areExtrasEqual(const cgltf_extras& lhs, const cgltf_extras& rhs)
{
if (lhs.data && rhs.data)
return strcmp(lhs.data, rhs.data) == 0;
else
return lhs.data == rhs.data;
}
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
gltf/parselib.cpp | C++ | #ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#define CGLTF_IMPLEMENTATION
#include "../extern/cgltf.h"
#define FAST_OBJ_IMPLEMENTATION
#include "../extern/fast_obj.h"
#undef CGLTF_IMPLEMENTATION
#undef FAST_OBJ_IMPLEMENTATION
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
gltf/parseobj.cpp | C++ | // This file is part of gltfpack; see gltfpack.h for version/license details
#include "gltfpack.h"
#include "../extern/fast_obj.h"
#include "../src/meshoptimizer.h"
#include <stdlib.h>
#include <string.h>
static void defaultFree(void*, void* p)
{
free(p);
}
static int textureIndex(const std::vector<unsigned int>& textures, unsigned int name)
{
for (size_t i = 0; i < textures.size(); ++i)
if (textures[i] == name)
return int(i);
return -1;
}
static void fixupUri(char* uri)
{
// Some .obj paths come with back slashes, that are invalid as URI separators and won't open on macOS/Linux when embedding textures
for (char* s = uri; *s; ++s)
if (*s == '\\')
*s = '/';
}
static void parseMaterialsObj(fastObjMesh* obj, cgltf_data* data)
{
// every texture in obj has a unique id (1+); we convert it to a 0-based index
// this effectively extracts only used textures out of the obj, as we don't remove unused textures later in the processing
std::vector<unsigned int> textures;
for (unsigned int mi = 0; mi < obj->material_count; ++mi)
{
fastObjMaterial& om = obj->materials[mi];
if (om.map_Kd && textureIndex(textures, om.map_Kd) < 0)
textures.push_back(om.map_Kd);
}
data->images = (cgltf_image*)calloc(textures.size(), sizeof(cgltf_image));
data->images_count = textures.size();
for (size_t i = 0; i < textures.size(); ++i)
{
unsigned int id = textures[i];
data->images[i].uri = strdup(obj->textures[id].name);
fixupUri(data->images[i].uri);
}
data->textures = (cgltf_texture*)calloc(textures.size(), sizeof(cgltf_texture));
data->textures_count = textures.size();
for (size_t i = 0; i < textures.size(); ++i)
{
data->textures[i].image = &data->images[i];
}
data->materials = (cgltf_material*)calloc(obj->material_count, sizeof(cgltf_material));
data->materials_count = obj->material_count;
for (unsigned int mi = 0; mi < obj->material_count; ++mi)
{
const fastObjMaterial& om = obj->materials[mi];
cgltf_material& gm = data->materials[mi];
if (om.name)
gm.name = strdup(om.name);
gm.has_pbr_metallic_roughness = true;
gm.pbr_metallic_roughness.base_color_factor[0] = 1.0f;
gm.pbr_metallic_roughness.base_color_factor[1] = 1.0f;
gm.pbr_metallic_roughness.base_color_factor[2] = 1.0f;
gm.pbr_metallic_roughness.base_color_factor[3] = 1.0f;
gm.pbr_metallic_roughness.metallic_factor = 0.0f;
gm.pbr_metallic_roughness.roughness_factor = 1.0f;
gm.alpha_cutoff = 0.5f;
if (om.map_Kd)
{
gm.pbr_metallic_roughness.base_color_texture.texture = &data->textures[textureIndex(textures, om.map_Kd)];
gm.pbr_metallic_roughness.base_color_texture.scale = 1.0f;
gm.alpha_mode = (om.illum == 4 || om.illum == 6 || om.illum == 7 || om.illum == 9) ? cgltf_alpha_mode_mask : cgltf_alpha_mode_opaque;
}
else
{
gm.pbr_metallic_roughness.base_color_factor[0] = om.Kd[0];
gm.pbr_metallic_roughness.base_color_factor[1] = om.Kd[1];
gm.pbr_metallic_roughness.base_color_factor[2] = om.Kd[2];
}
if (om.map_d)
{
if (om.map_Kd && strcmp(obj->textures[om.map_Kd].name, obj->textures[om.map_d].name) != 0)
fprintf(stderr, "Warning: material has different diffuse and alpha textures (Kd: %s, d: %s) and might not render correctly\n", obj->textures[om.map_Kd].name, obj->textures[om.map_d].name);
gm.alpha_mode = cgltf_alpha_mode_blend;
}
else if (om.d < 1.0f)
{
gm.pbr_metallic_roughness.base_color_factor[3] = om.d;
gm.alpha_mode = cgltf_alpha_mode_blend;
}
}
}
static void parseNodesObj(fastObjMesh* obj, cgltf_data* data)
{
data->nodes = (cgltf_node*)calloc(obj->object_count, sizeof(cgltf_node));
data->nodes_count = obj->object_count;
for (unsigned int oi = 0; oi < obj->object_count; ++oi)
{
const fastObjGroup& og = obj->objects[oi];
cgltf_node* node = &data->nodes[oi];
if (og.name)
node->name = strdup(og.name);
node->rotation[3] = 1.0f;
node->scale[0] = 1.0f;
node->scale[1] = 1.0f;
node->scale[2] = 1.0f;
}
data->scenes = (cgltf_scene*)calloc(1, sizeof(cgltf_scene));
data->scenes_count = 1;
data->scene = data->scenes;
data->scenes->nodes = (cgltf_node**)calloc(obj->object_count, sizeof(cgltf_node*));
data->scenes->nodes_count = obj->object_count;
for (unsigned int oi = 0; oi < obj->object_count; ++oi)
data->scenes->nodes[oi] = &data->nodes[oi];
}
static void parseMeshObj(fastObjMesh* obj, unsigned int face_offset, unsigned int face_vertex_offset, unsigned int face_count, unsigned int face_vertex_count, unsigned int index_count, Mesh& mesh)
{
std::vector<unsigned int> remap(face_vertex_count);
size_t unique_vertices = meshopt_generateVertexRemap(remap.data(), NULL, face_vertex_count, &obj->indices[face_vertex_offset], face_vertex_count, sizeof(fastObjIndex));
int pos_stream = 0;
int nrm_stream = obj->normal_count > 1 ? 1 : -1;
int tex_stream = obj->texcoord_count > 1 ? 1 + (nrm_stream >= 0) : -1;
int col_stream = obj->color_count > 1 ? 1 + (nrm_stream >= 0) + (tex_stream >= 0) : -1;
mesh.streams.resize(1 + (nrm_stream >= 0) + (tex_stream >= 0) + (col_stream >= 0));
mesh.streams[pos_stream].type = cgltf_attribute_type_position;
mesh.streams[pos_stream].data.resize(unique_vertices);
if (nrm_stream >= 0)
{
mesh.streams[nrm_stream].type = cgltf_attribute_type_normal;
mesh.streams[nrm_stream].data.resize(unique_vertices);
}
if (tex_stream >= 0)
{
mesh.streams[tex_stream].type = cgltf_attribute_type_texcoord;
mesh.streams[tex_stream].data.resize(unique_vertices);
}
if (col_stream >= 0)
{
mesh.streams[col_stream].type = cgltf_attribute_type_color;
mesh.streams[col_stream].data.resize(unique_vertices);
}
mesh.indices.resize(index_count);
for (unsigned int vi = 0; vi < face_vertex_count; ++vi)
{
unsigned int target = remap[vi];
// TODO: this fills every target vertex multiple times
fastObjIndex ii = obj->indices[face_vertex_offset + vi];
Attr p = {{obj->positions[ii.p * 3 + 0], obj->positions[ii.p * 3 + 1], obj->positions[ii.p * 3 + 2]}};
mesh.streams[pos_stream].data[target] = p;
if (nrm_stream >= 0)
{
Attr n = {{obj->normals[ii.n * 3 + 0], obj->normals[ii.n * 3 + 1], obj->normals[ii.n * 3 + 2]}};
mesh.streams[nrm_stream].data[target] = n;
}
if (tex_stream >= 0)
{
Attr t = {{obj->texcoords[ii.t * 2 + 0], 1.f - obj->texcoords[ii.t * 2 + 1]}};
mesh.streams[tex_stream].data[target] = t;
}
if (col_stream >= 0)
{
Attr c = {{obj->colors[ii.p * 3 + 0], obj->colors[ii.p * 3 + 1], obj->colors[ii.p * 3 + 2]}};
mesh.streams[col_stream].data[target] = c;
}
}
unsigned int vertex_offset = 0;
unsigned int index_offset = 0;
for (unsigned int fi = 0; fi < face_count; ++fi)
{
unsigned int face_vertices = obj->face_vertices[face_offset + fi];
if (mesh.type == cgltf_primitive_type_lines)
{
for (unsigned int vi = 1; vi < face_vertices; ++vi)
{
size_t to = index_offset + (vi - 1) * 2;
mesh.indices[to + 0] = remap[vertex_offset + vi - 1];
mesh.indices[to + 1] = remap[vertex_offset + vi];
}
vertex_offset += face_vertices;
index_offset += (face_vertices - 1) * 2;
}
else
{
for (unsigned int vi = 2; vi < face_vertices; ++vi)
{
size_t to = index_offset + (vi - 2) * 3;
mesh.indices[to + 0] = remap[vertex_offset];
mesh.indices[to + 1] = remap[vertex_offset + vi - 1];
mesh.indices[to + 2] = remap[vertex_offset + vi];
}
vertex_offset += face_vertices;
index_offset += (face_vertices - 2) * 3;
}
}
assert(vertex_offset == face_vertex_count);
assert(index_offset == index_count);
}
static void parseMeshGroupObj(fastObjMesh* obj, const fastObjGroup& og, cgltf_data* data, cgltf_node* node, std::vector<Mesh>& meshes)
{
unsigned int face_vertex_offset = og.index_offset;
unsigned int face_end_offset = og.face_offset + og.face_count;
for (unsigned int face_offset = og.face_offset; face_offset < face_end_offset;)
{
unsigned int mi = obj->face_materials[face_offset];
unsigned char isl = obj->face_lines ? obj->face_lines[face_offset] : 0;
unsigned int face_count = 0;
unsigned int face_vertex_count = 0;
unsigned int index_count = 0;
for (unsigned int fj = face_offset; fj < face_end_offset && obj->face_materials[fj] == mi && (!obj->face_lines || obj->face_lines[fj] == isl); ++fj)
{
face_count += 1;
face_vertex_count += obj->face_vertices[fj];
index_count += isl ? (obj->face_vertices[fj] - 1) * 2 : (obj->face_vertices[fj] - 2) * 3;
}
meshes.push_back(Mesh());
Mesh& mesh = meshes.back();
if (data->materials_count)
{
assert(mi < data->materials_count);
mesh.material = &data->materials[mi];
}
mesh.type = isl ? cgltf_primitive_type_lines : cgltf_primitive_type_triangles;
mesh.targets = 0;
if (node)
mesh.nodes.push_back(node);
parseMeshObj(obj, face_offset, face_vertex_offset, face_count, face_vertex_count, index_count, mesh);
face_offset += face_count;
face_vertex_offset += face_vertex_count;
}
}
cgltf_data* parseObj(const char* path, std::vector<Mesh>& meshes, const char** error)
{
fastObjMesh* obj = fast_obj_read(path);
if (!obj)
{
*error = "file not found";
return NULL;
}
int fallback_materials = 0;
for (unsigned int mi = 0; mi < obj->material_count; ++mi)
fallback_materials += obj->materials[mi].fallback;
if (fallback_materials)
fprintf(stderr, "Warning: %d/%d materials could not be loaded from mtllib\n", fallback_materials, obj->material_count);
cgltf_data* data = (cgltf_data*)calloc(1, sizeof(cgltf_data));
data->memory.free_func = defaultFree;
parseMaterialsObj(obj, data);
parseNodesObj(obj, data);
assert(data->nodes_count == obj->object_count);
for (unsigned int oi = 0; oi < obj->object_count; ++oi)
parseMeshGroupObj(obj, obj->objects[oi], data, &data->nodes[oi], meshes);
fast_obj_destroy(obj);
return data;
}
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
gltf/stream.cpp | C++ | // This file is part of gltfpack; see gltfpack.h for version/license details
#include "gltfpack.h"
#include <algorithm>
#include <float.h>
#include <limits.h>
#include <math.h>
#include <stdint.h>
#include "../src/meshoptimizer.h"
struct Bounds
{
Attr min, max;
Bounds()
{
min.f[0] = min.f[1] = min.f[2] = min.f[3] = +FLT_MAX;
max.f[0] = max.f[1] = max.f[2] = max.f[3] = -FLT_MAX;
}
bool isValid() const
{
return min.f[0] <= max.f[0] && min.f[1] <= max.f[1] && min.f[2] <= max.f[2] && min.f[3] <= max.f[3];
}
float getExtent() const
{
return std::max(max.f[0] - min.f[0], std::max(max.f[1] - min.f[1], max.f[2] - min.f[2]));
}
void merge(const Bounds& other)
{
for (int k = 0; k < 4; ++k)
{
min.f[k] = std::min(min.f[k], other.min.f[k]);
max.f[k] = std::max(max.f[k], other.max.f[k]);
}
}
};
static Bounds computeBounds(const Mesh& mesh, cgltf_attribute_type type)
{
Bounds b;
Attr pad = {};
for (size_t j = 0; j < mesh.streams.size(); ++j)
{
const Stream& s = mesh.streams[j];
if (s.type == type)
{
if (s.target == 0)
{
for (size_t k = 0; k < s.data.size(); ++k)
{
const Attr& a = s.data[k];
b.min.f[0] = std::min(b.min.f[0], a.f[0]);
b.min.f[1] = std::min(b.min.f[1], a.f[1]);
b.min.f[2] = std::min(b.min.f[2], a.f[2]);
b.min.f[3] = std::min(b.min.f[3], a.f[3]);
b.max.f[0] = std::max(b.max.f[0], a.f[0]);
b.max.f[1] = std::max(b.max.f[1], a.f[1]);
b.max.f[2] = std::max(b.max.f[2], a.f[2]);
b.max.f[3] = std::max(b.max.f[3], a.f[3]);
}
}
else
{
for (size_t k = 0; k < s.data.size(); ++k)
{
const Attr& a = s.data[k];
pad.f[0] = std::max(pad.f[0], fabsf(a.f[0]));
pad.f[1] = std::max(pad.f[1], fabsf(a.f[1]));
pad.f[2] = std::max(pad.f[2], fabsf(a.f[2]));
pad.f[3] = std::max(pad.f[3], fabsf(a.f[3]));
}
}
}
}
for (int k = 0; k < 4; ++k)
{
b.min.f[k] -= pad.f[k];
b.max.f[k] += pad.f[k];
}
return b;
}
static float computeUvArea(const Mesh& mesh)
{
if (mesh.indices.empty() || mesh.type != cgltf_primitive_type_triangles)
return 0.f;
float result = 0.f;
for (size_t j = 0; j < mesh.streams.size(); ++j)
{
const Stream& s = mesh.streams[j];
if (s.type != cgltf_attribute_type_texcoord)
continue;
float uvarea = 0.f;
for (size_t i = 0; i < mesh.indices.size(); i += 3)
{
unsigned int a = mesh.indices[i + 0];
unsigned int b = mesh.indices[i + 1];
unsigned int c = mesh.indices[i + 2];
const Attr& va = s.data[a];
const Attr& vb = s.data[b];
const Attr& vc = s.data[c];
uvarea += fabsf((vb.f[0] - va.f[0]) * (vc.f[1] - va.f[1]) - (vc.f[0] - va.f[0]) * (vb.f[1] - va.f[1]));
}
result = std::max(result, uvarea / float(mesh.indices.size() / 3));
}
return result;
}
QuantizationPosition prepareQuantizationPosition(const std::vector<Mesh>& meshes, const Settings& settings)
{
QuantizationPosition result = {};
result.bits = settings.pos_bits;
result.normalized = settings.pos_normalized;
std::vector<Bounds> bounds(meshes.size());
for (size_t i = 0; i < meshes.size(); ++i)
bounds[i] = computeBounds(meshes[i], cgltf_attribute_type_position);
Bounds b;
for (size_t i = 0; i < meshes.size(); ++i)
b.merge(bounds[i]);
if (b.isValid())
{
result.offset[0] = b.min.f[0];
result.offset[1] = b.min.f[1];
result.offset[2] = b.min.f[2];
result.scale = b.getExtent();
}
if (b.isValid() && settings.quantize && !settings.pos_float)
{
float error = result.scale * 0.5f / (1 << (result.bits - 1));
float max_rel_error = 0;
for (size_t i = 0; i < meshes.size(); ++i)
if (bounds[i].isValid() && bounds[i].getExtent() > 1e-2f)
max_rel_error = std::max(max_rel_error, error / bounds[i].getExtent());
if (max_rel_error > 5e-2f)
fprintf(stderr, "Warning: position data has significant error (%.0f%%); consider using floating-point quantization (-vpf) or more bits (-vp N)\n", max_rel_error * 100);
}
result.node_scale = result.scale / float((1 << result.bits) - 1) * (result.normalized ? 65535.f : 1.f);
return result;
}
static size_t follow(std::vector<size_t>& parents, size_t index)
{
while (index != parents[index])
{
size_t parent = parents[index];
parents[index] = parents[parent];
index = parent;
}
return index;
}
void prepareQuantizationTexture(cgltf_data* data, std::vector<QuantizationTexture>& result, std::vector<size_t>& indices, const std::vector<Mesh>& meshes, const Settings& settings)
{
// use union-find to associate each material with a canonical material
// this is necessary because any set of materials that are used on the same mesh must use the same quantization
std::vector<size_t> parents(result.size());
for (size_t i = 0; i < parents.size(); ++i)
parents[i] = i;
for (size_t i = 0; i < meshes.size(); ++i)
{
const Mesh& mesh = meshes[i];
if (!mesh.material && mesh.variants.empty())
continue;
size_t root = follow(parents, (mesh.material ? mesh.material : mesh.variants[0].material) - data->materials);
for (size_t j = 0; j < mesh.variants.size(); ++j)
{
size_t var = follow(parents, mesh.variants[j].material - data->materials);
parents[var] = root;
}
indices[i] = root;
}
// compute canonical material bounds based on meshes that use them
std::vector<Bounds> bounds(result.size());
for (size_t i = 0; i < meshes.size(); ++i)
{
const Mesh& mesh = meshes[i];
if (!mesh.material && mesh.variants.empty())
continue;
indices[i] = follow(parents, indices[i]);
Bounds mb = computeBounds(mesh, cgltf_attribute_type_texcoord);
bounds[indices[i]].merge(mb);
}
// detect potential precision issues and warn about them
if (settings.quantize && !settings.tex_float)
{
float max_rel_error = 0;
for (size_t i = 0; i < meshes.size(); ++i)
{
const Mesh& mesh = meshes[i];
if (!mesh.material && mesh.variants.empty())
continue;
const Bounds& b = bounds[indices[i]];
if (!b.isValid())
continue;
float scale = std::max(b.max.f[0] - b.min.f[0], b.max.f[1] - b.min.f[1]);
float error = scale * 0.5f / (1 << (settings.tex_bits - 1));
if (error < 1e-3f)
continue;
float uvarea = computeUvArea(mesh);
float rel_error = uvarea > 0 ? error / sqrtf(uvarea) : 0.f;
max_rel_error = std::max(max_rel_error, rel_error);
}
if (max_rel_error > 1e-1f)
fprintf(stderr, "Warning: texture coordinate data has significant error (%.0f%%); consider using floating-point quantization (-vtf) or more bits (-vt N)\n", max_rel_error * 100);
}
// update all material data using canonical bounds
for (size_t i = 0; i < result.size(); ++i)
{
QuantizationTexture& qt = result[i];
qt.bits = settings.tex_bits;
qt.normalized = true;
const Bounds& b = bounds[follow(parents, i)];
if (b.isValid())
{
qt.offset[0] = b.min.f[0];
qt.offset[1] = b.min.f[1];
qt.scale[0] = b.max.f[0] - b.min.f[0];
qt.scale[1] = b.max.f[1] - b.min.f[1];
}
}
}
void getPositionBounds(float min[3], float max[3], const Stream& stream, const QuantizationPosition& qp, const Settings& settings)
{
assert(stream.type == cgltf_attribute_type_position);
assert(stream.data.size() > 0);
min[0] = min[1] = min[2] = FLT_MAX;
max[0] = max[1] = max[2] = -FLT_MAX;
for (size_t i = 0; i < stream.data.size(); ++i)
{
const Attr& a = stream.data[i];
for (int k = 0; k < 3; ++k)
{
min[k] = std::min(min[k], a.f[k]);
max[k] = std::max(max[k], a.f[k]);
}
}
if (settings.quantize)
{
if (settings.pos_float)
{
for (int k = 0; k < 3; ++k)
{
min[k] = meshopt_quantizeFloat(min[k], qp.bits);
max[k] = meshopt_quantizeFloat(max[k], qp.bits);
}
}
else
{
float pos_rscale = qp.scale == 0.f ? 0.f : 1.f / qp.scale * (stream.target > 0 && qp.normalized ? 32767.f / 65535.f : 1.f);
for (int k = 0; k < 3; ++k)
{
if (stream.target == 0)
{
min[k] = float(meshopt_quantizeUnorm((min[k] - qp.offset[k]) * pos_rscale, qp.bits));
max[k] = float(meshopt_quantizeUnorm((max[k] - qp.offset[k]) * pos_rscale, qp.bits));
}
else
{
min[k] = (min[k] >= 0.f ? 1.f : -1.f) * float(meshopt_quantizeUnorm(fabsf(min[k]) * pos_rscale, qp.bits));
max[k] = (max[k] >= 0.f ? 1.f : -1.f) * float(meshopt_quantizeUnorm(fabsf(max[k]) * pos_rscale, qp.bits));
}
}
}
}
}
static void renormalizeWeights(uint8_t (&w)[4])
{
int sum = w[0] + w[1] + w[2] + w[3];
if (sum == 255)
return;
// we assume that the total error is limited to 0.5/component = 2
// this means that it's acceptable to adjust the max. component to compensate for the error
int max = 0;
for (int k = 1; k < 4; ++k)
if (w[k] > w[max])
max = k;
w[max] += uint8_t(255 - sum);
}
static void encodeSnorm(void* destination, size_t count, size_t stride, int bits, const float* data)
{
assert(stride == 4 || stride == 8);
assert(bits >= 1 && bits <= 16);
signed char* d8 = static_cast<signed char*>(destination);
short* d16 = static_cast<short*>(destination);
for (size_t i = 0; i < count; ++i)
{
const float* v = &data[i * 4];
int fx = meshopt_quantizeSnorm(v[0], bits);
int fy = meshopt_quantizeSnorm(v[1], bits);
int fz = meshopt_quantizeSnorm(v[2], bits);
int fw = meshopt_quantizeSnorm(v[3], bits);
if (stride == 4)
{
d8[i * 4 + 0] = (signed char)(fx);
d8[i * 4 + 1] = (signed char)(fy);
d8[i * 4 + 2] = (signed char)(fz);
d8[i * 4 + 3] = (signed char)(fw);
}
else
{
d16[i * 4 + 0] = short(fx);
d16[i * 4 + 1] = short(fy);
d16[i * 4 + 2] = short(fz);
d16[i * 4 + 3] = short(fw);
}
}
}
static int quantizeColor(float v, int bytebits, int bits)
{
int result = meshopt_quantizeUnorm(v, bytebits);
// replicate the top bit into the low significant bits
const int mask = (1 << (bytebits - bits)) - 1;
return (result & ~mask) | (mask & -(result >> (bytebits - 1)));
}
static void encodeColor(void* destination, size_t count, size_t stride, int bits, const float* data)
{
assert(stride == 4 || stride == 8);
assert(bits >= 2 && bits <= 16);
unsigned char* d8 = static_cast<unsigned char*>(destination);
unsigned short* d16 = static_cast<unsigned short*>(destination);
for (size_t i = 0; i < count; ++i)
{
const float* c = &data[i * 4];
if (stride == 4)
{
d8[i * 4 + 0] = uint8_t(quantizeColor(c[0], 8, bits));
d8[i * 4 + 1] = uint8_t(quantizeColor(c[1], 8, bits));
d8[i * 4 + 2] = uint8_t(quantizeColor(c[2], 8, bits));
d8[i * 4 + 3] = uint8_t(quantizeColor(c[3], 8, bits));
}
else
{
d16[i * 4 + 0] = uint16_t(quantizeColor(c[0], 16, bits));
d16[i * 4 + 1] = uint16_t(quantizeColor(c[1], 16, bits));
d16[i * 4 + 2] = uint16_t(quantizeColor(c[2], 16, bits));
d16[i * 4 + 3] = uint16_t(quantizeColor(c[3], 16, bits));
}
}
}
static StreamFormat writeVertexStreamRaw(std::string& bin, const Stream& stream, cgltf_type type, size_t components)
{
assert(components >= 1 && components <= 4);
for (size_t i = 0; i < stream.data.size(); ++i)
{
const Attr& a = stream.data[i];
bin.append(reinterpret_cast<const char*>(a.f), sizeof(float) * components);
}
StreamFormat format = {type, cgltf_component_type_r_32f, false, sizeof(float) * components};
return format;
}
static StreamFormat writeVertexStreamFloat(std::string& bin, const Stream& stream, cgltf_type type, int components, bool expf, int bits, meshopt_EncodeExpMode mode)
{
assert(components >= 1 && components <= 4);
StreamFormat::Filter filter = expf ? StreamFormat::Filter_Exp : StreamFormat::Filter_None;
if (filter == StreamFormat::Filter_Exp)
{
size_t offset = bin.size();
size_t stride = sizeof(float) * components;
for (size_t i = 0; i < stream.data.size(); ++i)
bin.append(reinterpret_cast<const char*>(stream.data[i].f), stride);
meshopt_encodeFilterExp(&bin[offset], stream.data.size(), stride, bits + 1, reinterpret_cast<const float*>(&bin[offset]), mode);
}
else
{
for (size_t i = 0; i < stream.data.size(); ++i)
{
const Attr& a = stream.data[i];
float v[4];
for (int k = 0; k < components; ++k)
v[k] = meshopt_quantizeFloat(a.f[k], bits);
bin.append(reinterpret_cast<const char*>(v), sizeof(float) * components);
}
}
StreamFormat format = {type, cgltf_component_type_r_32f, false, sizeof(float) * components, filter};
return format;
}
StreamFormat writeVertexStream(std::string& bin, const Stream& stream, const QuantizationPosition& qp, const QuantizationTexture& qt, const Settings& settings, bool filters)
{
if (stream.type == cgltf_attribute_type_position)
{
if (!settings.quantize)
return writeVertexStreamRaw(bin, stream, cgltf_type_vec3, 3);
if (settings.pos_float)
return writeVertexStreamFloat(bin, stream, cgltf_type_vec3, 3, settings.compress && filters, qp.bits,
settings.compressmore ? meshopt_EncodeExpSharedComponent : meshopt_EncodeExpSeparate);
if (stream.target == 0)
{
float pos_rscale = qp.scale == 0.f ? 0.f : 1.f / qp.scale;
for (size_t i = 0; i < stream.data.size(); ++i)
{
const Attr& a = stream.data[i];
uint16_t v[4] = {
uint16_t(meshopt_quantizeUnorm((a.f[0] - qp.offset[0]) * pos_rscale, qp.bits)),
uint16_t(meshopt_quantizeUnorm((a.f[1] - qp.offset[1]) * pos_rscale, qp.bits)),
uint16_t(meshopt_quantizeUnorm((a.f[2] - qp.offset[2]) * pos_rscale, qp.bits)),
0};
bin.append(reinterpret_cast<const char*>(v), sizeof(v));
}
StreamFormat format = {cgltf_type_vec3, cgltf_component_type_r_16u, qp.normalized, 8};
return format;
}
else
{
float pos_rscale = qp.scale == 0.f ? 0.f : 1.f / qp.scale * (qp.normalized ? 32767.f / 65535.f : 1.f);
int maxv = 0;
for (size_t i = 0; i < stream.data.size(); ++i)
{
const Attr& a = stream.data[i];
maxv = std::max(maxv, meshopt_quantizeUnorm(fabsf(a.f[0]) * pos_rscale, qp.bits));
maxv = std::max(maxv, meshopt_quantizeUnorm(fabsf(a.f[1]) * pos_rscale, qp.bits));
maxv = std::max(maxv, meshopt_quantizeUnorm(fabsf(a.f[2]) * pos_rscale, qp.bits));
}
if (maxv <= 127 && !qp.normalized)
{
for (size_t i = 0; i < stream.data.size(); ++i)
{
const Attr& a = stream.data[i];
int8_t v[4] = {
int8_t((a.f[0] >= 0.f ? 1 : -1) * meshopt_quantizeUnorm(fabsf(a.f[0]) * pos_rscale, qp.bits)),
int8_t((a.f[1] >= 0.f ? 1 : -1) * meshopt_quantizeUnorm(fabsf(a.f[1]) * pos_rscale, qp.bits)),
int8_t((a.f[2] >= 0.f ? 1 : -1) * meshopt_quantizeUnorm(fabsf(a.f[2]) * pos_rscale, qp.bits)),
0};
bin.append(reinterpret_cast<const char*>(v), sizeof(v));
}
StreamFormat format = {cgltf_type_vec3, cgltf_component_type_r_8, false, 4};
return format;
}
else
{
for (size_t i = 0; i < stream.data.size(); ++i)
{
const Attr& a = stream.data[i];
int16_t v[4] = {
int16_t((a.f[0] >= 0.f ? 1 : -1) * meshopt_quantizeUnorm(fabsf(a.f[0]) * pos_rscale, qp.bits)),
int16_t((a.f[1] >= 0.f ? 1 : -1) * meshopt_quantizeUnorm(fabsf(a.f[1]) * pos_rscale, qp.bits)),
int16_t((a.f[2] >= 0.f ? 1 : -1) * meshopt_quantizeUnorm(fabsf(a.f[2]) * pos_rscale, qp.bits)),
0};
bin.append(reinterpret_cast<const char*>(v), sizeof(v));
}
StreamFormat format = {cgltf_type_vec3, cgltf_component_type_r_16, qp.normalized, 8};
return format;
}
}
}
else if (stream.type == cgltf_attribute_type_texcoord)
{
if (!settings.quantize)
return writeVertexStreamRaw(bin, stream, cgltf_type_vec2, 2);
// expand the encoded range to ensure it covers [0..1) interval
// this can slightly reduce precision but we should not need more precision inside 0..1, and this significantly improves compressed size when using encodeExpOne
if (settings.tex_float)
return writeVertexStreamFloat(bin, stream, cgltf_type_vec2, 2, settings.compress && filters, qt.bits, meshopt_EncodeExpClamped);
float uv_rscale[2] = {
qt.scale[0] == 0.f ? 0.f : 1.f / qt.scale[0],
qt.scale[1] == 0.f ? 0.f : 1.f / qt.scale[1],
};
for (size_t i = 0; i < stream.data.size(); ++i)
{
const Attr& a = stream.data[i];
uint16_t v[2] = {
uint16_t(meshopt_quantizeUnorm((a.f[0] - qt.offset[0]) * uv_rscale[0], qt.bits)),
uint16_t(meshopt_quantizeUnorm((a.f[1] - qt.offset[1]) * uv_rscale[1], qt.bits)),
};
bin.append(reinterpret_cast<const char*>(v), sizeof(v));
}
StreamFormat format = {cgltf_type_vec2, cgltf_component_type_r_16u, qt.normalized, 4};
return format;
}
else if (stream.type == cgltf_attribute_type_normal)
{
if (!settings.quantize)
return writeVertexStreamRaw(bin, stream, cgltf_type_vec3, 3);
// expand the encoded range to ensure it covers [0..1) interval
if (settings.nrm_float)
return writeVertexStreamFloat(bin, stream, cgltf_type_vec3, 3, settings.compress && filters, settings.nrm_bits,
(settings.compressmore || stream.target) ? meshopt_EncodeExpSharedComponent : meshopt_EncodeExpClamped);
bool oct = filters && settings.compressmore && stream.target == 0;
int bits = settings.nrm_bits;
StreamFormat::Filter filter = oct ? StreamFormat::Filter_Oct : StreamFormat::Filter_None;
size_t offset = bin.size();
size_t stride = bits > 8 ? 8 : 4;
bin.resize(bin.size() + stream.data.size() * stride);
if (oct)
meshopt_encodeFilterOct(&bin[offset], stream.data.size(), stride, bits, stream.data[0].f);
else
encodeSnorm(&bin[offset], stream.data.size(), stride, bits, stream.data[0].f);
cgltf_component_type component_type = bits > 8 ? cgltf_component_type_r_16 : cgltf_component_type_r_8;
StreamFormat format = {cgltf_type_vec3, component_type, true, stride, filter};
return format;
}
else if (stream.type == cgltf_attribute_type_tangent)
{
if (!settings.quantize)
return writeVertexStreamRaw(bin, stream, cgltf_type_vec4, 4);
bool oct = filters && settings.compressmore && stream.target == 0;
int bits = (settings.nrm_bits > 8) ? 8 : settings.nrm_bits;
StreamFormat::Filter filter = oct ? StreamFormat::Filter_Oct : StreamFormat::Filter_None;
size_t offset = bin.size();
size_t stride = 4;
bin.resize(bin.size() + stream.data.size() * stride);
if (oct)
meshopt_encodeFilterOct(&bin[offset], stream.data.size(), stride, bits, stream.data[0].f);
else
encodeSnorm(&bin[offset], stream.data.size(), stride, bits, stream.data[0].f);
cgltf_type type = (stream.target == 0) ? cgltf_type_vec4 : cgltf_type_vec3;
StreamFormat format = {type, cgltf_component_type_r_8, true, 4, filter};
return format;
}
else if (stream.type == cgltf_attribute_type_color)
{
bool col = filters && settings.compresskhr && settings.compressmore;
int bits = settings.col_bits;
StreamFormat::Filter filter = col ? StreamFormat::Filter_Color : StreamFormat::Filter_None;
size_t offset = bin.size();
size_t stride = bits > 8 ? 8 : 4;
bin.resize(bin.size() + stream.data.size() * stride);
if (col)
meshopt_encodeFilterColor(&bin[offset], stream.data.size(), stride, bits, stream.data[0].f);
else
encodeColor(&bin[offset], stream.data.size(), stride, bits, stream.data[0].f);
if (bits > 8)
{
StreamFormat format = {cgltf_type_vec4, cgltf_component_type_r_16u, true, 8, filter};
return format;
}
else
{
StreamFormat format = {cgltf_type_vec4, cgltf_component_type_r_8u, true, 4, filter};
return format;
}
}
else if (stream.type == cgltf_attribute_type_weights)
{
for (size_t i = 0; i < stream.data.size(); ++i)
{
const Attr& a = stream.data[i];
float ws = a.f[0] + a.f[1] + a.f[2] + a.f[3];
float wsi = (ws == 0.f) ? 0.f : 1.f / ws;
uint8_t v[4] = {
uint8_t(meshopt_quantizeUnorm(a.f[0] * wsi, 8)),
uint8_t(meshopt_quantizeUnorm(a.f[1] * wsi, 8)),
uint8_t(meshopt_quantizeUnorm(a.f[2] * wsi, 8)),
uint8_t(meshopt_quantizeUnorm(a.f[3] * wsi, 8))};
if (wsi != 0.f)
renormalizeWeights(v);
bin.append(reinterpret_cast<const char*>(v), sizeof(v));
}
StreamFormat format = {cgltf_type_vec4, cgltf_component_type_r_8u, true, 4};
return format;
}
else if (stream.type == cgltf_attribute_type_joints)
{
unsigned int maxj = 0;
for (size_t i = 0; i < stream.data.size(); ++i)
maxj = std::max(maxj, unsigned(stream.data[i].f[0]));
assert(maxj <= 65535);
if (maxj <= 255)
{
for (size_t i = 0; i < stream.data.size(); ++i)
{
const Attr& a = stream.data[i];
uint8_t v[4] = {
uint8_t(a.f[0]),
uint8_t(a.f[1]),
uint8_t(a.f[2]),
uint8_t(a.f[3])};
bin.append(reinterpret_cast<const char*>(v), sizeof(v));
}
StreamFormat format = {cgltf_type_vec4, cgltf_component_type_r_8u, false, 4};
return format;
}
else
{
for (size_t i = 0; i < stream.data.size(); ++i)
{
const Attr& a = stream.data[i];
uint16_t v[4] = {
uint16_t(a.f[0]),
uint16_t(a.f[1]),
uint16_t(a.f[2]),
uint16_t(a.f[3])};
bin.append(reinterpret_cast<const char*>(v), sizeof(v));
}
StreamFormat format = {cgltf_type_vec4, cgltf_component_type_r_16u, false, 8};
return format;
}
}
else if (stream.type == cgltf_attribute_type_custom)
{
// note: _custom is equivalent to _ID, as such the data contains scalar integers
if (!settings.compressmore || !filters)
return writeVertexStreamRaw(bin, stream, cgltf_type_scalar, 1);
unsigned int maxv = 0;
for (size_t i = 0; i < stream.data.size(); ++i)
maxv = std::max(maxv, unsigned(stream.data[i].f[0]));
// exp encoding uses a signed mantissa with only 23 significant bits; input glTF encoding may encode indices losslessly up to 2^24
if (maxv >= (1 << 23))
return writeVertexStreamRaw(bin, stream, cgltf_type_scalar, 1);
for (size_t i = 0; i < stream.data.size(); ++i)
{
const Attr& a = stream.data[i];
uint32_t id = uint32_t(a.f[0]);
uint32_t v = id; // exp encoding of integers in [0..2^23-1] range is equivalent to the integer itself
bin.append(reinterpret_cast<const char*>(&v), sizeof(v));
}
StreamFormat format = {cgltf_type_scalar, cgltf_component_type_r_32f, false, 4, StreamFormat::Filter_Exp};
return format;
}
else
{
return writeVertexStreamRaw(bin, stream, cgltf_type_vec4, 4);
}
}
StreamFormat writeIndexStream(std::string& bin, const std::vector<unsigned int>& stream)
{
unsigned int maxi = 0;
for (size_t i = 0; i < stream.size(); ++i)
maxi = std::max(maxi, stream[i]);
// save 16-bit indices if we can; note that we can't use restart index (65535)
if (maxi < 65535)
{
for (size_t i = 0; i < stream.size(); ++i)
{
uint16_t v[1] = {uint16_t(stream[i])};
bin.append(reinterpret_cast<const char*>(v), sizeof(v));
}
StreamFormat format = {cgltf_type_scalar, cgltf_component_type_r_16u, false, 2};
return format;
}
else
{
for (size_t i = 0; i < stream.size(); ++i)
{
uint32_t v[1] = {stream[i]};
bin.append(reinterpret_cast<const char*>(v), sizeof(v));
}
StreamFormat format = {cgltf_type_scalar, cgltf_component_type_r_32u, false, 4};
return format;
}
}
StreamFormat writeTimeStream(std::string& bin, const std::vector<float>& data)
{
for (size_t i = 0; i < data.size(); ++i)
{
float v[1] = {data[i]};
bin.append(reinterpret_cast<const char*>(v), sizeof(v));
}
StreamFormat format = {cgltf_type_scalar, cgltf_component_type_r_32f, false, 4};
return format;
}
StreamFormat writeKeyframeStream(std::string& bin, cgltf_animation_path_type type, const std::vector<Attr>& data, const Settings& settings, bool has_tangents)
{
if (type == cgltf_animation_path_type_rotation)
{
StreamFormat::Filter filter = settings.compressmore && !has_tangents ? StreamFormat::Filter_Quat : StreamFormat::Filter_None;
size_t offset = bin.size();
size_t stride = 8;
bin.resize(bin.size() + data.size() * stride);
if (filter == StreamFormat::Filter_Quat)
meshopt_encodeFilterQuat(&bin[offset], data.size(), stride, settings.rot_bits, data[0].f);
else
encodeSnorm(&bin[offset], data.size(), stride, 16, data[0].f);
StreamFormat format = {cgltf_type_vec4, cgltf_component_type_r_16, true, 8, filter};
return format;
}
else if (type == cgltf_animation_path_type_weights)
{
for (size_t i = 0; i < data.size(); ++i)
{
const Attr& a = data[i];
uint8_t v[1] = {uint8_t(meshopt_quantizeUnorm(a.f[0], 8))};
bin.append(reinterpret_cast<const char*>(v), sizeof(v));
}
StreamFormat format = {cgltf_type_scalar, cgltf_component_type_r_8u, true, 1};
return format;
}
else if (type == cgltf_animation_path_type_translation || type == cgltf_animation_path_type_scale)
{
StreamFormat::Filter filter = settings.compressmore ? StreamFormat::Filter_Exp : StreamFormat::Filter_None;
int bits = (type == cgltf_animation_path_type_translation) ? settings.trn_bits : settings.scl_bits;
size_t offset = bin.size();
for (size_t i = 0; i < data.size(); ++i)
{
const Attr& a = data[i];
float v[3] = {a.f[0], a.f[1], a.f[2]};
bin.append(reinterpret_cast<const char*>(v), sizeof(v));
}
if (filter == StreamFormat::Filter_Exp)
meshopt_encodeFilterExp(&bin[offset], data.size(), 12, bits, reinterpret_cast<const float*>(&bin[offset]), meshopt_EncodeExpSharedVector);
StreamFormat format = {cgltf_type_vec3, cgltf_component_type_r_32f, false, 12, filter};
return format;
}
else
{
for (size_t i = 0; i < data.size(); ++i)
{
const Attr& a = data[i];
float v[4] = {a.f[0], a.f[1], a.f[2], a.f[3]};
bin.append(reinterpret_cast<const char*>(v), sizeof(v));
}
StreamFormat format = {cgltf_type_vec4, cgltf_component_type_r_32f, false, 16};
return format;
}
}
void compressVertexStream(std::string& bin, const std::string& data, size_t count, size_t stride, int level)
{
assert(data.size() == count * stride);
std::vector<unsigned char> compressed(meshopt_encodeVertexBufferBound(count, stride));
size_t size = meshopt_encodeVertexBufferLevel(&compressed[0], compressed.size(), data.c_str(), count, stride, level, level > 0);
bin.append(reinterpret_cast<const char*>(&compressed[0]), size);
}
void compressIndexStream(std::string& bin, const std::string& data, size_t count, size_t stride)
{
assert(stride == 2 || stride == 4);
assert(data.size() == count * stride);
assert(count % 3 == 0);
std::vector<unsigned char> compressed(meshopt_encodeIndexBufferBound(count, count));
size_t size = 0;
if (stride == 2)
size = meshopt_encodeIndexBuffer(&compressed[0], compressed.size(), reinterpret_cast<const uint16_t*>(data.c_str()), count);
else
size = meshopt_encodeIndexBuffer(&compressed[0], compressed.size(), reinterpret_cast<const uint32_t*>(data.c_str()), count);
bin.append(reinterpret_cast<const char*>(&compressed[0]), size);
}
void compressIndexSequence(std::string& bin, const std::string& data, size_t count, size_t stride)
{
assert(stride == 2 || stride == 4);
assert(data.size() == count * stride);
std::vector<unsigned char> compressed(meshopt_encodeIndexSequenceBound(count, count));
size_t size = 0;
if (stride == 2)
size = meshopt_encodeIndexSequence(&compressed[0], compressed.size(), reinterpret_cast<const uint16_t*>(data.c_str()), count);
else
size = meshopt_encodeIndexSequence(&compressed[0], compressed.size(), reinterpret_cast<const uint32_t*>(data.c_str()), count);
bin.append(reinterpret_cast<const char*>(&compressed[0]), size);
}
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
gltf/wasistubs.cpp | C++ | #ifdef __wasi__
#include <stdlib.h>
#include <string.h>
#include <wasi/api.h>
extern "C" void __cxa_throw(void* ptr, void* type, void* destructor)
{
abort();
}
extern "C" void* __cxa_allocate_exception(size_t thrown_size)
{
abort();
}
extern "C" int32_t __wasi_path_open32(int32_t arg0, int32_t arg1, int32_t arg2, int32_t arg3, int32_t arg4, int32_t arg5, int32_t arg6, int32_t arg7, int32_t arg8)
__attribute__((
__import_module__("wasi_snapshot_preview1"),
__import_name__("path_open32"),
__warn_unused_result__));
extern "C" int32_t __imported_wasi_snapshot_preview1_path_open(int32_t arg0, int32_t arg1, int32_t arg2, int32_t arg3, int32_t arg4, int64_t arg5, int64_t arg6, int32_t arg7, int32_t arg8)
{
return __wasi_path_open32(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
}
extern "C" int32_t __wasi_fd_seek32(int32_t arg0, int32_t arg1, int32_t arg2, int32_t arg3)
__attribute__((
__import_module__("wasi_snapshot_preview1"),
__import_name__("fd_seek32"),
__warn_unused_result__));
extern "C" int32_t __imported_wasi_snapshot_preview1_fd_seek(int32_t arg0, int64_t arg1, int32_t arg2, int32_t arg3)
{
*(uint64_t*)arg3 = 0;
return __wasi_fd_seek32(arg0, arg1, arg2, arg3);
}
extern "C" int32_t __imported_wasi_snapshot_preview1_clock_time_get(int32_t arg0, int64_t arg1, int32_t arg2)
{
return __WASI_ERRNO_NOSYS;
}
#endif
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
gltf/write.cpp | C++ | // This file is part of gltfpack; see gltfpack.h for version/license details
#include "gltfpack.h"
#include <float.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static const char* componentType(cgltf_component_type type)
{
switch (type)
{
case cgltf_component_type_r_8:
return "5120";
case cgltf_component_type_r_8u:
return "5121";
case cgltf_component_type_r_16:
return "5122";
case cgltf_component_type_r_16u:
return "5123";
case cgltf_component_type_r_32u:
return "5125";
case cgltf_component_type_r_32f:
return "5126";
default:
return "0";
}
}
static const char* shapeType(cgltf_type type)
{
switch (type)
{
case cgltf_type_scalar:
return "SCALAR";
case cgltf_type_vec2:
return "VEC2";
case cgltf_type_vec3:
return "VEC3";
case cgltf_type_vec4:
return "VEC4";
case cgltf_type_mat2:
return "MAT2";
case cgltf_type_mat3:
return "MAT3";
case cgltf_type_mat4:
return "MAT4";
default:
return "";
}
}
const char* attributeType(cgltf_attribute_type type)
{
switch (type)
{
case cgltf_attribute_type_position:
return "POSITION";
case cgltf_attribute_type_normal:
return "NORMAL";
case cgltf_attribute_type_tangent:
return "TANGENT";
case cgltf_attribute_type_texcoord:
return "TEXCOORD";
case cgltf_attribute_type_color:
return "COLOR";
case cgltf_attribute_type_joints:
return "JOINTS";
case cgltf_attribute_type_weights:
return "WEIGHTS";
case cgltf_attribute_type_custom:
return "CUSTOM";
default:
return "ATTRIBUTE";
}
}
const char* animationPath(cgltf_animation_path_type type)
{
switch (type)
{
case cgltf_animation_path_type_translation:
return "translation";
case cgltf_animation_path_type_rotation:
return "rotation";
case cgltf_animation_path_type_scale:
return "scale";
case cgltf_animation_path_type_weights:
return "weights";
default:
return "";
}
}
static const char* lightType(cgltf_light_type type)
{
switch (type)
{
case cgltf_light_type_directional:
return "directional";
case cgltf_light_type_point:
return "point";
case cgltf_light_type_spot:
return "spot";
default:
return "";
}
}
static const char* alphaMode(cgltf_alpha_mode mode)
{
switch (mode)
{
case cgltf_alpha_mode_opaque:
return "OPAQUE";
case cgltf_alpha_mode_mask:
return "MASK";
case cgltf_alpha_mode_blend:
return "BLEND";
default:
return "";
}
}
static const char* interpolationType(cgltf_interpolation_type type)
{
switch (type)
{
case cgltf_interpolation_type_linear:
return "LINEAR";
case cgltf_interpolation_type_step:
return "STEP";
case cgltf_interpolation_type_cubic_spline:
return "CUBICSPLINE";
default:
return "";
}
}
static const char* compressionMode(BufferView::Compression mode)
{
switch (mode)
{
case BufferView::Compression_Attribute:
return "ATTRIBUTES";
case BufferView::Compression_Index:
return "TRIANGLES";
case BufferView::Compression_IndexSequence:
return "INDICES";
default:
return "";
}
}
static const char* compressionFilter(StreamFormat::Filter filter)
{
switch (filter)
{
case StreamFormat::Filter_None:
return "NONE";
case StreamFormat::Filter_Oct:
return "OCTAHEDRAL";
case StreamFormat::Filter_Quat:
return "QUATERNION";
case StreamFormat::Filter_Exp:
return "EXPONENTIAL";
case StreamFormat::Filter_Color:
return "COLOR";
default:
return "";
}
}
static void writeTextureInfo(std::string& json, const cgltf_data* data, const cgltf_texture_view& view, const QuantizationTexture* qt, std::vector<TextureInfo>& textures, const char* scale = NULL)
{
assert(view.texture);
bool has_transform = false;
cgltf_texture_transform transform = {};
transform.scale[0] = transform.scale[1] = 1.f;
if (hasValidTransform(view))
{
transform = view.transform;
has_transform = true;
}
if (qt)
{
transform.offset[0] += qt->offset[0];
transform.offset[1] += qt->offset[1];
transform.scale[0] *= qt->scale[0] / float((1 << qt->bits) - 1) * (qt->normalized ? 65535.f : 1.f);
transform.scale[1] *= qt->scale[1] / float((1 << qt->bits) - 1) * (qt->normalized ? 65535.f : 1.f);
has_transform = true;
}
append(json, "{\"index\":");
append(json, size_t(textures[view.texture - data->textures].remap));
if (view.texcoord != 0)
{
append(json, ",\"texCoord\":");
append(json, size_t(view.texcoord));
}
if (scale && view.scale != 1)
{
append(json, ",\"");
append(json, scale);
append(json, "\":");
append(json, view.scale);
}
if (has_transform)
{
append(json, ",\"extensions\":{\"KHR_texture_transform\":{");
append(json, "\"offset\":");
append(json, transform.offset, 2);
append(json, ",\"scale\":");
append(json, transform.scale, 2);
if (transform.rotation != 0.f)
{
append(json, ",\"rotation\":");
append(json, transform.rotation);
}
append(json, "}}");
}
append(json, "}");
}
static const float white[4] = {1, 1, 1, 1};
static const float black[4] = {0, 0, 0, 0};
static void writeMaterialComponent(std::string& json, const cgltf_data* data, const cgltf_pbr_metallic_roughness& pbr, const QuantizationTexture* qt, std::vector<TextureInfo>& textures)
{
comma(json);
append(json, "\"pbrMetallicRoughness\":{");
if (memcmp(pbr.base_color_factor, white, 16) != 0)
{
comma(json);
append(json, "\"baseColorFactor\":");
append(json, pbr.base_color_factor, 4);
}
if (pbr.base_color_texture.texture)
{
comma(json);
append(json, "\"baseColorTexture\":");
writeTextureInfo(json, data, pbr.base_color_texture, qt, textures);
}
if (pbr.metallic_factor != 1)
{
comma(json);
append(json, "\"metallicFactor\":");
append(json, pbr.metallic_factor);
}
if (pbr.roughness_factor != 1)
{
comma(json);
append(json, "\"roughnessFactor\":");
append(json, pbr.roughness_factor);
}
if (pbr.metallic_roughness_texture.texture)
{
comma(json);
append(json, "\"metallicRoughnessTexture\":");
writeTextureInfo(json, data, pbr.metallic_roughness_texture, qt, textures);
}
append(json, "}");
}
static void writeMaterialComponent(std::string& json, const cgltf_data* data, const cgltf_pbr_specular_glossiness& pbr, const QuantizationTexture* qt, std::vector<TextureInfo>& textures)
{
comma(json);
append(json, "\"KHR_materials_pbrSpecularGlossiness\":{");
if (pbr.diffuse_texture.texture)
{
comma(json);
append(json, "\"diffuseTexture\":");
writeTextureInfo(json, data, pbr.diffuse_texture, qt, textures);
}
if (pbr.specular_glossiness_texture.texture)
{
comma(json);
append(json, "\"specularGlossinessTexture\":");
writeTextureInfo(json, data, pbr.specular_glossiness_texture, qt, textures);
}
if (memcmp(pbr.diffuse_factor, white, 16) != 0)
{
comma(json);
append(json, "\"diffuseFactor\":");
append(json, pbr.diffuse_factor, 4);
}
if (memcmp(pbr.specular_factor, white, 12) != 0)
{
comma(json);
append(json, "\"specularFactor\":");
append(json, pbr.specular_factor, 3);
}
if (pbr.glossiness_factor != 1)
{
comma(json);
append(json, "\"glossinessFactor\":");
append(json, pbr.glossiness_factor);
}
append(json, "}");
}
static void writeMaterialComponent(std::string& json, const cgltf_data* data, const cgltf_clearcoat& cc, const QuantizationTexture* qt, std::vector<TextureInfo>& textures)
{
comma(json);
append(json, "\"KHR_materials_clearcoat\":{");
if (cc.clearcoat_texture.texture)
{
comma(json);
append(json, "\"clearcoatTexture\":");
writeTextureInfo(json, data, cc.clearcoat_texture, qt, textures);
}
if (cc.clearcoat_roughness_texture.texture)
{
comma(json);
append(json, "\"clearcoatRoughnessTexture\":");
writeTextureInfo(json, data, cc.clearcoat_roughness_texture, qt, textures);
}
if (cc.clearcoat_normal_texture.texture)
{
comma(json);
append(json, "\"clearcoatNormalTexture\":");
writeTextureInfo(json, data, cc.clearcoat_normal_texture, qt, textures, "scale");
}
if (cc.clearcoat_factor != 0)
{
comma(json);
append(json, "\"clearcoatFactor\":");
append(json, cc.clearcoat_factor);
}
if (cc.clearcoat_factor != 0)
{
comma(json);
append(json, "\"clearcoatRoughnessFactor\":");
append(json, cc.clearcoat_roughness_factor);
}
append(json, "}");
}
static void writeMaterialComponent(std::string& json, const cgltf_data* data, const cgltf_transmission& tm, const QuantizationTexture* qt, std::vector<TextureInfo>& textures)
{
comma(json);
append(json, "\"KHR_materials_transmission\":{");
if (tm.transmission_texture.texture)
{
comma(json);
append(json, "\"transmissionTexture\":");
writeTextureInfo(json, data, tm.transmission_texture, qt, textures);
}
if (tm.transmission_factor != 0)
{
comma(json);
append(json, "\"transmissionFactor\":");
append(json, tm.transmission_factor);
}
append(json, "}");
}
static void writeMaterialComponent(std::string& json, const cgltf_data* data, const cgltf_ior& tm)
{
(void)data;
comma(json);
append(json, "\"KHR_materials_ior\":{");
append(json, "\"ior\":");
append(json, tm.ior);
append(json, "}");
}
static void writeMaterialComponent(std::string& json, const cgltf_data* data, const cgltf_specular& tm, const QuantizationTexture* qt, std::vector<TextureInfo>& textures)
{
comma(json);
append(json, "\"KHR_materials_specular\":{");
if (tm.specular_texture.texture)
{
comma(json);
append(json, "\"specularTexture\":");
writeTextureInfo(json, data, tm.specular_texture, qt, textures);
}
if (tm.specular_color_texture.texture)
{
comma(json);
append(json, "\"specularColorTexture\":");
writeTextureInfo(json, data, tm.specular_color_texture, qt, textures);
}
if (tm.specular_factor != 1)
{
comma(json);
append(json, "\"specularFactor\":");
append(json, tm.specular_factor);
}
if (memcmp(tm.specular_color_factor, white, 12) != 0)
{
comma(json);
append(json, "\"specularColorFactor\":");
append(json, tm.specular_color_factor, 3);
}
append(json, "}");
}
static void writeMaterialComponent(std::string& json, const cgltf_data* data, const cgltf_sheen& tm, const QuantizationTexture* qt, std::vector<TextureInfo>& textures)
{
comma(json);
append(json, "\"KHR_materials_sheen\":{");
if (tm.sheen_color_texture.texture)
{
comma(json);
append(json, "\"sheenColorTexture\":");
writeTextureInfo(json, data, tm.sheen_color_texture, qt, textures);
}
if (tm.sheen_roughness_texture.texture)
{
comma(json);
append(json, "\"sheenRoughnessTexture\":");
writeTextureInfo(json, data, tm.sheen_roughness_texture, qt, textures);
}
if (memcmp(tm.sheen_color_factor, black, 12) != 0)
{
comma(json);
append(json, "\"sheenColorFactor\":");
append(json, tm.sheen_color_factor, 3);
}
if (tm.sheen_roughness_factor != 0)
{
comma(json);
append(json, "\"sheenRoughnessFactor\":");
append(json, tm.sheen_roughness_factor);
}
append(json, "}");
}
static void writeMaterialComponent(std::string& json, const cgltf_data* data, const cgltf_volume& tm, const QuantizationPosition* qp, const QuantizationTexture* qt, std::vector<TextureInfo>& textures)
{
comma(json);
append(json, "\"KHR_materials_volume\":{");
if (tm.thickness_texture.texture)
{
comma(json);
append(json, "\"thicknessTexture\":");
writeTextureInfo(json, data, tm.thickness_texture, qt, textures);
}
if (tm.thickness_factor != 0)
{
// thickness is in mesh coordinate space which is rescaled by quantization
comma(json);
append(json, "\"thicknessFactor\":");
append(json, tm.thickness_factor / (qp ? qp->node_scale : 1.f));
}
if (memcmp(tm.attenuation_color, white, 12) != 0)
{
comma(json);
append(json, "\"attenuationColor\":");
append(json, tm.attenuation_color, 3);
}
if (tm.attenuation_distance != FLT_MAX)
{
comma(json);
append(json, "\"attenuationDistance\":");
append(json, tm.attenuation_distance);
}
append(json, "}");
}
static void writeMaterialComponent(std::string& json, const cgltf_data* data, const cgltf_emissive_strength& tm)
{
(void)data;
comma(json);
append(json, "\"KHR_materials_emissive_strength\":{");
if (tm.emissive_strength != 1)
{
comma(json);
append(json, "\"emissiveStrength\":");
append(json, tm.emissive_strength);
}
append(json, "}");
}
static void writeMaterialComponent(std::string& json, const cgltf_data* data, const cgltf_iridescence& tm, const QuantizationTexture* qt, std::vector<TextureInfo>& textures)
{
comma(json);
append(json, "\"KHR_materials_iridescence\":{");
if (tm.iridescence_factor != 0)
{
comma(json);
append(json, "\"iridescenceFactor\":");
append(json, tm.iridescence_factor);
}
if (tm.iridescence_texture.texture)
{
comma(json);
append(json, "\"iridescenceTexture\":");
writeTextureInfo(json, data, tm.iridescence_texture, qt, textures);
}
if (tm.iridescence_ior != 1.3f)
{
comma(json);
append(json, "\"iridescenceIor\":");
append(json, tm.iridescence_ior);
}
if (tm.iridescence_thickness_min != 100.f)
{
comma(json);
append(json, "\"iridescenceThicknessMinimum\":");
append(json, tm.iridescence_thickness_min);
}
if (tm.iridescence_thickness_max != 400.f)
{
comma(json);
append(json, "\"iridescenceThicknessMaximum\":");
append(json, tm.iridescence_thickness_max);
}
if (tm.iridescence_thickness_texture.texture)
{
comma(json);
append(json, "\"iridescenceThicknessTexture\":");
writeTextureInfo(json, data, tm.iridescence_thickness_texture, qt, textures);
}
append(json, "}");
}
static void writeMaterialComponent(std::string& json, const cgltf_data* data, const cgltf_anisotropy& tm, const QuantizationTexture* qt, std::vector<TextureInfo>& textures)
{
comma(json);
append(json, "\"KHR_materials_anisotropy\":{");
if (tm.anisotropy_strength != 0)
{
comma(json);
append(json, "\"anisotropyStrength\":");
append(json, tm.anisotropy_strength);
}
if (tm.anisotropy_rotation != 0)
{
comma(json);
append(json, "\"anisotropyRotation\":");
append(json, tm.anisotropy_rotation);
}
if (tm.anisotropy_texture.texture)
{
comma(json);
append(json, "\"anisotropyTexture\":");
writeTextureInfo(json, data, tm.anisotropy_texture, qt, textures);
}
append(json, "}");
}
static void writeMaterialComponent(std::string& json, const cgltf_data* data, const cgltf_dispersion& tm)
{
(void)data;
comma(json);
append(json, "\"KHR_materials_dispersion\":{");
append(json, "\"dispersion\":");
append(json, tm.dispersion);
append(json, "}");
}
static void writeMaterialComponent(std::string& json, const cgltf_data* data, const cgltf_diffuse_transmission& tm, const QuantizationTexture* qt, std::vector<TextureInfo>& textures)
{
comma(json);
append(json, "\"KHR_materials_diffuse_transmission\":{");
if (tm.diffuse_transmission_factor != 0)
{
comma(json);
append(json, "\"diffuseTransmissionFactor\":");
append(json, tm.diffuse_transmission_factor);
}
if (tm.diffuse_transmission_texture.texture)
{
comma(json);
append(json, "\"diffuseTransmissionTexture\":");
writeTextureInfo(json, data, tm.diffuse_transmission_texture, qt, textures);
}
if (memcmp(tm.diffuse_transmission_color_factor, white, sizeof(float) * 3) != 0)
{
comma(json);
append(json, "\"diffuseTransmissionColorFactor\":");
append(json, tm.diffuse_transmission_color_factor, 3);
}
if (tm.diffuse_transmission_color_texture.texture)
{
comma(json);
append(json, "\"diffuseTransmissionColorTexture\":");
writeTextureInfo(json, data, tm.diffuse_transmission_color_texture, qt, textures);
}
append(json, "}");
}
void writeMaterial(std::string& json, const cgltf_data* data, const cgltf_material& material, const QuantizationPosition* qp, const QuantizationTexture* qt, std::vector<TextureInfo>& textures)
{
if (material.name && *material.name)
{
comma(json);
append(json, "\"name\":\"");
append(json, material.name);
append(json, "\"");
}
if (material.has_pbr_metallic_roughness)
{
writeMaterialComponent(json, data, material.pbr_metallic_roughness, qt, textures);
}
if (material.normal_texture.texture)
{
comma(json);
append(json, "\"normalTexture\":");
writeTextureInfo(json, data, material.normal_texture, qt, textures, "scale");
}
if (material.occlusion_texture.texture)
{
comma(json);
append(json, "\"occlusionTexture\":");
writeTextureInfo(json, data, material.occlusion_texture, qt, textures, "strength");
}
if (material.emissive_texture.texture)
{
comma(json);
append(json, "\"emissiveTexture\":");
writeTextureInfo(json, data, material.emissive_texture, qt, textures);
}
if (memcmp(material.emissive_factor, black, 12) != 0)
{
comma(json);
append(json, "\"emissiveFactor\":");
append(json, material.emissive_factor, 3);
}
if (material.alpha_mode != cgltf_alpha_mode_opaque)
{
comma(json);
append(json, "\"alphaMode\":\"");
append(json, alphaMode(material.alpha_mode));
append(json, "\"");
}
if (material.alpha_cutoff != 0.5f)
{
comma(json);
append(json, "\"alphaCutoff\":");
append(json, material.alpha_cutoff);
}
if (material.double_sided)
{
comma(json);
append(json, "\"doubleSided\":true");
}
if (material.has_pbr_specular_glossiness || material.has_clearcoat || material.has_transmission || material.has_ior || material.has_specular ||
material.has_sheen || material.has_volume || material.has_emissive_strength || material.has_iridescence || material.has_anisotropy ||
material.has_dispersion || material.has_diffuse_transmission || material.unlit)
{
comma(json);
append(json, "\"extensions\":{");
if (material.has_pbr_specular_glossiness)
writeMaterialComponent(json, data, material.pbr_specular_glossiness, qt, textures);
if (material.has_clearcoat)
writeMaterialComponent(json, data, material.clearcoat, qt, textures);
if (material.has_transmission)
writeMaterialComponent(json, data, material.transmission, qt, textures);
if (material.has_ior)
writeMaterialComponent(json, data, material.ior);
if (material.has_specular)
writeMaterialComponent(json, data, material.specular, qt, textures);
if (material.has_sheen)
writeMaterialComponent(json, data, material.sheen, qt, textures);
if (material.has_volume)
writeMaterialComponent(json, data, material.volume, qp, qt, textures);
if (material.has_emissive_strength)
writeMaterialComponent(json, data, material.emissive_strength);
if (material.has_iridescence)
writeMaterialComponent(json, data, material.iridescence, qt, textures);
if (material.has_anisotropy)
writeMaterialComponent(json, data, material.anisotropy, qt, textures);
if (material.has_dispersion)
writeMaterialComponent(json, data, material.dispersion);
if (material.has_diffuse_transmission)
writeMaterialComponent(json, data, material.diffuse_transmission, qt, textures);
if (material.unlit)
{
comma(json);
append(json, "\"KHR_materials_unlit\":{}");
}
append(json, "}");
}
}
size_t getBufferView(std::vector<BufferView>& views, BufferView::Kind kind, StreamFormat::Filter filter, BufferView::Compression compression, size_t stride, int variant)
{
if (variant >= 0)
{
for (size_t i = 0; i < views.size(); ++i)
{
BufferView& v = views[i];
if (v.kind == kind && v.filter == filter && v.compression == compression && v.stride == stride && v.variant == variant)
return i;
}
}
BufferView view = {kind, filter, compression, stride, variant};
views.push_back(view);
return views.size() - 1;
}
void writeBufferView(std::string& json, BufferView::Kind kind, StreamFormat::Filter filter, size_t count, size_t stride, size_t bin_offset, size_t bin_size, BufferView::Compression compression, size_t compressed_offset, size_t compressed_size, const char* meshopt_ext)
{
assert(bin_size == count * stride);
// when compression is enabled, we store uncompressed data in buffer 1 and compressed data in buffer 0
// when compression is disabled, we store uncompressed data in buffer 0
size_t buffer = compression != BufferView::Compression_None ? 1 : 0;
append(json, "{\"buffer\":");
append(json, buffer);
append(json, ",\"byteOffset\":");
append(json, bin_offset);
append(json, ",\"byteLength\":");
append(json, bin_size);
if (kind == BufferView::Kind_Vertex)
{
append(json, ",\"byteStride\":");
append(json, stride);
}
if (kind == BufferView::Kind_Vertex || kind == BufferView::Kind_Index)
{
append(json, ",\"target\":");
append(json, (kind == BufferView::Kind_Vertex) ? "34962" : "34963");
}
if (compression != BufferView::Compression_None)
{
append(json, ",\"extensions\":{");
append(json, "\"");
append(json, meshopt_ext);
append(json, "\":{");
append(json, "\"buffer\":0");
append(json, ",\"byteOffset\":");
append(json, size_t(compressed_offset));
append(json, ",\"byteLength\":");
append(json, size_t(compressed_size));
append(json, ",\"byteStride\":");
append(json, stride);
append(json, ",\"mode\":\"");
append(json, compressionMode(compression));
append(json, "\"");
if (filter != StreamFormat::Filter_None)
{
append(json, ",\"filter\":\"");
append(json, compressionFilter(filter));
append(json, "\"");
}
append(json, ",\"count\":");
append(json, count);
append(json, "}}");
}
append(json, "}");
}
static void writeAccessor(std::string& json, size_t view, size_t offset, cgltf_type type, cgltf_component_type component_type, bool normalized, size_t count, const float* min = NULL, const float* max = NULL, size_t numminmax = 0)
{
append(json, "{\"bufferView\":");
append(json, view);
append(json, ",\"byteOffset\":");
append(json, offset);
append(json, ",\"componentType\":");
append(json, componentType(component_type));
append(json, ",\"count\":");
append(json, count);
append(json, ",\"type\":\"");
append(json, shapeType(type));
append(json, "\"");
if (normalized)
{
append(json, ",\"normalized\":true");
}
if (min && max)
{
assert(numminmax);
append(json, ",\"min\":");
append(json, min, numminmax);
append(json, ",\"max\":");
append(json, max, numminmax);
}
append(json, "}");
}
static void writeEmbeddedImage(std::string& json, std::vector<BufferView>& views, const char* data, size_t size, const char* mime_type, TextureKind kind)
{
size_t view = getBufferView(views, BufferView::Kind_Image, StreamFormat::Filter_None, BufferView::Compression_None, 1, -1 - kind);
assert(views[view].data.empty());
views[view].data.assign(data, size);
append(json, "\"bufferView\":");
append(json, view);
append(json, ",\"mimeType\":\"");
append(json, mime_type);
append(json, "\"");
}
static std::string decodeUri(const char* uri)
{
std::string result = uri;
if (!result.empty())
{
cgltf_decode_uri(&result[0]);
result.resize(strlen(result.c_str()));
}
return result;
}
void writeSampler(std::string& json, const cgltf_sampler& sampler)
{
if (sampler.mag_filter != cgltf_filter_type_undefined)
{
comma(json);
append(json, "\"magFilter\":");
append(json, size_t(sampler.mag_filter));
}
if (sampler.min_filter != cgltf_filter_type_undefined)
{
comma(json);
append(json, "\"minFilter\":");
append(json, size_t(sampler.min_filter));
}
if (sampler.wrap_s != cgltf_wrap_mode_repeat)
{
comma(json);
append(json, "\"wrapS\":");
append(json, size_t(sampler.wrap_s));
}
if (sampler.wrap_t != cgltf_wrap_mode_repeat)
{
comma(json);
append(json, "\"wrapT\":");
append(json, size_t(sampler.wrap_t));
}
}
static void writeImageError(std::string& json, const char* action, size_t index, const char* uri, const char* reason)
{
append(json, "\"uri\":\"");
append(json, "data:image/png;base64,ERR/");
append(json, "\"");
fprintf(stderr, "Warning: unable to %s image %d (%s), skipping%s%s%s\n", action, int(index), uri ? uri : "embedded", reason ? " (" : "", reason ? reason : "", reason ? ")" : "");
}
static void writeImageData(std::string& json, std::vector<BufferView>& views, size_t index, const char* uri, const char* mime_type, const std::string& contents, const char* output_path, TextureKind kind, bool embed)
{
bool dataUri = uri && strncmp(uri, "data:", 5) == 0;
if (!embed && uri && !dataUri && output_path)
{
std::string file_name = getFileName(uri) + mimeExtension(mime_type);
std::string file_path = getFullPath(decodeUri(file_name.c_str()).c_str(), output_path);
if (writeFile(file_path.c_str(), contents))
{
append(json, "\"uri\":\"");
append(json, file_name);
append(json, "\"");
}
else
{
writeImageError(json, "save", int(index), uri, file_path.c_str());
}
}
else
{
writeEmbeddedImage(json, views, contents.c_str(), contents.size(), mime_type, kind);
}
}
void writeImage(std::string& json, std::vector<BufferView>& views, const cgltf_image& image, const ImageInfo& info, const std::string* encoded, size_t index, const char* input_path, const char* output_path, const Settings& settings)
{
if (image.name && *image.name)
{
append(json, "\"name\":\"");
append(json, image.name);
append(json, "\",");
}
if (encoded)
{
const char* mime_type = (settings.texture_mode[info.kind] == TextureMode_WebP) ? "image/webp" : "image/ktx2";
// image was pre-encoded via encodeImages (which might have failed!)
if (encoded->compare(0, 5, "error") == 0)
writeImageError(json, "encode", int(index), image.uri, encoded->c_str());
else
writeImageData(json, views, index, image.uri, mime_type, *encoded, output_path, info.kind, settings.texture_embed);
return;
}
bool dataUri = image.uri && strncmp(image.uri, "data:", 5) == 0;
if (image.uri && !dataUri && settings.texture_ref)
{
// fast-path: we don't need to read the image to memory
append(json, "\"uri\":\"");
append(json, image.uri);
append(json, "\"");
return;
}
std::string img_data;
std::string mime_type;
if (!readImage(image, input_path, img_data, mime_type))
{
writeImageError(json, "read", index, image.uri, NULL);
return;
}
writeImageData(json, views, index, image.uri, mime_type.c_str(), img_data, output_path, info.kind, settings.texture_embed);
}
void writeTexture(std::string& json, const cgltf_texture& texture, const ImageInfo* info, cgltf_data* data, const Settings& settings)
{
if (texture.sampler)
{
append(json, "\"sampler\":");
append(json, size_t(texture.sampler - data->samplers));
}
if (texture.image)
{
if (info && settings.texture_mode[info->kind] != TextureMode_Raw)
{
const char* texture_ext = (settings.texture_mode[info->kind] == TextureMode_WebP) ? "EXT_texture_webp" : "KHR_texture_basisu";
comma(json);
append(json, "\"extensions\":{\"");
append(json, texture_ext);
append(json, "\":{\"source\":");
append(json, size_t(texture.image - data->images));
append(json, "}}");
return; // skip input basisu image if present, as we replace it with the one we encoded
}
else
{
comma(json);
append(json, "\"source\":");
append(json, size_t(texture.image - data->images));
}
}
if (texture.basisu_image)
{
comma(json);
append(json, "\"extensions\":{\"KHR_texture_basisu\":{\"source\":");
append(json, size_t(texture.basisu_image - data->images));
append(json, "}}");
}
else if (texture.webp_image)
{
comma(json);
append(json, "\"extensions\":{\"EXT_texture_webp\":{\"source\":");
append(json, size_t(texture.webp_image - data->images));
append(json, "}}");
}
}
static void writePrimitiveAccessor(std::string& json_accessors, const Stream& stream, size_t view, size_t offset, const StreamFormat& format, const QuantizationPosition& qp, const Settings& settings)
{
comma(json_accessors);
if (stream.type == cgltf_attribute_type_position)
{
float min[3] = {};
float max[3] = {};
getPositionBounds(min, max, stream, qp, settings);
writeAccessor(json_accessors, view, offset, format.type, format.component_type, format.normalized, stream.data.size(), min, max, 3);
}
else
{
writeAccessor(json_accessors, view, offset, format.type, format.component_type, format.normalized, stream.data.size());
}
}
static void writePrimitiveAttribute(std::string& json, const Stream& stream, size_t accessor)
{
comma(json);
append(json, "\"");
if (stream.custom_name)
{
append(json, stream.custom_name);
}
else
{
append(json, attributeType(stream.type));
if (stream.type != cgltf_attribute_type_position && stream.type != cgltf_attribute_type_normal && stream.type != cgltf_attribute_type_tangent)
{
append(json, "_");
append(json, size_t(stream.index));
}
}
append(json, "\":");
append(json, accessor);
}
static void writeMeshAttributesInterleaved(std::string& json, std::vector<BufferView>& views, std::string& json_accessors, size_t& accr_offset, const Mesh& mesh, int target, const QuantizationPosition& qp, const QuantizationTexture& qt, const Settings& settings)
{
struct Attribute
{
const Stream* stream;
StreamFormat format;
std::string data;
};
std::vector<Attribute> attributes;
size_t stride = 0;
for (size_t j = 0; j < mesh.streams.size(); ++j)
{
const Stream& stream = mesh.streams[j];
if (stream.target != target)
continue;
Attribute attr = {&stream};
attr.format = writeVertexStream(attr.data, stream, qp, qt, settings, /* filters= */ false);
assert(attr.format.filter == StreamFormat::Filter_None);
stride += attr.format.stride;
attributes.emplace_back(std::move(attr));
}
BufferView::Compression compression = settings.compress ? BufferView::Compression_Attribute : BufferView::Compression_None;
size_t view = getBufferView(views, BufferView::Kind_Vertex, StreamFormat::Filter_None, compression, stride, 0);
size_t offset = views[view].data.size();
size_t vertex_count = mesh.streams[0].data.size();
views[view].data.resize(views[view].data.size() + stride * vertex_count);
size_t write_offset = offset;
for (size_t i = 0; i < vertex_count; ++i)
for (Attribute& attr : attributes)
{
memcpy(&views[view].data[write_offset], &attr.data[i * attr.format.stride], attr.format.stride);
write_offset += attr.format.stride;
}
for (Attribute& attr : attributes)
{
const Stream& stream = *attr.stream;
const StreamFormat& format = attr.format;
writePrimitiveAccessor(json_accessors, stream, view, offset, format, qp, settings);
size_t vertex_accr = accr_offset++;
writePrimitiveAttribute(json, stream, vertex_accr);
offset += attr.format.stride;
}
}
void writeMeshAttributes(std::string& json, std::vector<BufferView>& views, std::string& json_accessors, size_t& accr_offset, const Mesh& mesh, int target, const QuantizationPosition& qp, const QuantizationTexture& qt, const Settings& settings)
{
if (settings.mesh_interleaved)
return writeMeshAttributesInterleaved(json, views, json_accessors, accr_offset, mesh, target, qp, qt, settings);
std::string scratch;
for (size_t j = 0; j < mesh.streams.size(); ++j)
{
const Stream& stream = mesh.streams[j];
if (stream.target != target)
continue;
scratch.clear();
StreamFormat format = writeVertexStream(scratch, stream, qp, qt, settings);
BufferView::Compression compression = settings.compress ? BufferView::Compression_Attribute : BufferView::Compression_None;
size_t view = getBufferView(views, BufferView::Kind_Vertex, format.filter, compression, format.stride, stream.type);
size_t offset = views[view].data.size();
views[view].data += scratch;
writePrimitiveAccessor(json_accessors, stream, view, offset, format, qp, settings);
size_t vertex_accr = accr_offset++;
writePrimitiveAttribute(json, stream, vertex_accr);
}
}
size_t writeMeshIndices(std::vector<BufferView>& views, std::string& json_accessors, size_t& accr_offset, const std::vector<unsigned int>& indices, cgltf_primitive_type type, const Settings& settings)
{
std::string scratch;
StreamFormat format = writeIndexStream(scratch, indices);
BufferView::Compression compression = settings.compress ? (type == cgltf_primitive_type_triangles ? BufferView::Compression_Index : BufferView::Compression_IndexSequence) : BufferView::Compression_None;
size_t view = getBufferView(views, BufferView::Kind_Index, StreamFormat::Filter_None, compression, format.stride);
size_t offset = views[view].data.size();
views[view].data += scratch;
comma(json_accessors);
writeAccessor(json_accessors, view, offset, format.type, format.component_type, format.normalized, indices.size());
size_t index_accr = accr_offset++;
return index_accr;
}
void writeMeshGeometry(std::string& json, std::vector<BufferView>& views, std::string& json_accessors, size_t& accr_offset, const Mesh& mesh, const QuantizationPosition& qp, const QuantizationTexture& qt, const Settings& settings)
{
append(json, "{\"attributes\":{");
writeMeshAttributes(json, views, json_accessors, accr_offset, mesh, 0, qp, qt, settings);
append(json, "}");
if (mesh.type != cgltf_primitive_type_triangles)
{
append(json, ",\"mode\":");
append(json, size_t(mesh.type - cgltf_primitive_type_points));
}
if (mesh.targets)
{
append(json, ",\"targets\":[");
for (size_t j = 0; j < mesh.targets; ++j)
{
comma(json);
append(json, "{");
writeMeshAttributes(json, views, json_accessors, accr_offset, mesh, int(1 + j), qp, qt, settings);
append(json, "}");
}
append(json, "]");
}
if (!mesh.indices.empty())
{
size_t index_accr = writeMeshIndices(views, json_accessors, accr_offset, mesh.indices, mesh.type, settings);
append(json, ",\"indices\":");
append(json, index_accr);
}
}
static size_t writeAnimationTime(std::vector<BufferView>& views, std::string& json_accessors, size_t& accr_offset, const std::vector<float>& time, const Settings& settings)
{
std::string scratch;
StreamFormat format = writeTimeStream(scratch, time);
BufferView::Compression compression = settings.compress ? BufferView::Compression_Attribute : BufferView::Compression_None;
size_t view = getBufferView(views, BufferView::Kind_Time, StreamFormat::Filter_None, compression, format.stride);
size_t offset = views[view].data.size();
views[view].data += scratch;
comma(json_accessors);
writeAccessor(json_accessors, view, offset, cgltf_type_scalar, format.component_type, format.normalized, time.size(), &time.front(), &time.back(), 1);
size_t time_accr = accr_offset++;
return time_accr;
}
static size_t writeAnimationTime(std::vector<BufferView>& views, std::string& json_accessors, size_t& accr_offset, float mint, int frames, float period, const Settings& settings)
{
std::vector<float> time(frames);
for (int j = 0; j < frames; ++j)
time[j] = mint + float(j) * period;
return writeAnimationTime(views, json_accessors, accr_offset, time, settings);
}
size_t writeJointBindMatrices(std::vector<BufferView>& views, std::string& json_accessors, size_t& accr_offset, const cgltf_skin& skin, const QuantizationPosition& qp, const Settings& settings)
{
std::string scratch;
for (size_t j = 0; j < skin.joints_count; ++j)
{
float transform[16] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
if (skin.inverse_bind_matrices)
{
cgltf_accessor_read_float(skin.inverse_bind_matrices, j, transform, 16);
}
if (settings.quantize && !settings.pos_float)
{
// pos_offset has to be applied first, thus it results in an offset rotated by the bind matrix
transform[12] += qp.offset[0] * transform[0] + qp.offset[1] * transform[4] + qp.offset[2] * transform[8];
transform[13] += qp.offset[0] * transform[1] + qp.offset[1] * transform[5] + qp.offset[2] * transform[9];
transform[14] += qp.offset[0] * transform[2] + qp.offset[1] * transform[6] + qp.offset[2] * transform[10];
// node_scale will be applied before the rotation/scale from transform
for (int k = 0; k < 12; ++k)
transform[k] *= qp.node_scale;
}
scratch.append(reinterpret_cast<const char*>(transform), sizeof(transform));
}
BufferView::Compression compression = settings.compress ? BufferView::Compression_Attribute : BufferView::Compression_None;
size_t view = getBufferView(views, BufferView::Kind_Skin, StreamFormat::Filter_None, compression, 64);
size_t offset = views[view].data.size();
views[view].data += scratch;
comma(json_accessors);
writeAccessor(json_accessors, view, offset, cgltf_type_mat4, cgltf_component_type_r_32f, false, skin.joints_count);
size_t matrix_accr = accr_offset++;
return matrix_accr;
}
static void writeInstanceData(std::vector<BufferView>& views, std::string& json_accessors, cgltf_animation_path_type type, const std::vector<Attr>& data, const Settings& settings)
{
BufferView::Compression compression = settings.compress ? BufferView::Compression_Attribute : BufferView::Compression_None;
std::string scratch;
StreamFormat format = writeKeyframeStream(scratch, type, data, settings);
size_t view = getBufferView(views, BufferView::Kind_Instance, format.filter, compression, format.stride, type);
size_t offset = views[view].data.size();
views[view].data += scratch;
comma(json_accessors);
writeAccessor(json_accessors, view, offset, format.type, format.component_type, format.normalized, data.size());
}
size_t writeInstances(std::vector<BufferView>& views, std::string& json_accessors, size_t& accr_offset, const std::vector<Instance>& instances, const QuantizationPosition& qp, bool has_color, const Settings& settings)
{
std::vector<Attr> position, rotation, scale;
position.resize(instances.size());
rotation.resize(instances.size());
scale.resize(instances.size());
Stream color = {cgltf_attribute_type_color};
if (has_color)
color.data.resize(instances.size());
for (size_t i = 0; i < instances.size(); ++i)
{
decomposeTransform(position[i].f, rotation[i].f, scale[i].f, instances[i].transform);
if (settings.quantize && !settings.pos_float)
{
const float* transform = instances[i].transform;
// pos_offset has to be applied first, thus it results in an offset rotated by the instance matrix
position[i].f[0] += qp.offset[0] * transform[0] + qp.offset[1] * transform[4] + qp.offset[2] * transform[8];
position[i].f[1] += qp.offset[0] * transform[1] + qp.offset[1] * transform[5] + qp.offset[2] * transform[9];
position[i].f[2] += qp.offset[0] * transform[2] + qp.offset[1] * transform[6] + qp.offset[2] * transform[10];
// node_scale will be applied before the rotation/scale from transform
scale[i].f[0] *= qp.node_scale;
scale[i].f[1] *= qp.node_scale;
scale[i].f[2] *= qp.node_scale;
}
if (has_color)
memcpy(color.data[i].f, instances[i].color, sizeof(Attr));
}
writeInstanceData(views, json_accessors, cgltf_animation_path_type_translation, position, settings);
writeInstanceData(views, json_accessors, cgltf_animation_path_type_rotation, rotation, settings);
writeInstanceData(views, json_accessors, cgltf_animation_path_type_scale, scale, settings);
size_t result = accr_offset;
accr_offset += 3;
if (has_color)
{
BufferView::Compression compression = settings.compress ? BufferView::Compression_Attribute : BufferView::Compression_None;
std::string scratch;
StreamFormat format = writeVertexStream(scratch, color, QuantizationPosition(), QuantizationTexture(), settings);
size_t view = getBufferView(views, BufferView::Kind_Instance, format.filter, compression, format.stride, 0);
size_t offset = views[view].data.size();
views[view].data += scratch;
comma(json_accessors);
writeAccessor(json_accessors, view, offset, format.type, format.component_type, format.normalized, instances.size());
accr_offset += 1;
}
return result;
}
void writeMeshNode(std::string& json, size_t mesh_offset, cgltf_node* node, cgltf_skin* skin, cgltf_data* data, const QuantizationPosition* qp)
{
comma(json);
append(json, "{\"mesh\":");
append(json, mesh_offset);
if (skin)
{
append(json, ",\"skin\":");
append(json, size_t(skin - data->skins));
}
if (qp)
{
append(json, ",\"translation\":");
append(json, qp->offset, 3);
append(json, ",\"scale\":[");
append(json, qp->node_scale);
append(json, ",");
append(json, qp->node_scale);
append(json, ",");
append(json, qp->node_scale);
append(json, "]");
}
if (node && node->weights_count)
{
append(json, ",\"weights\":");
append(json, node->weights, node->weights_count);
}
append(json, "}");
}
void writeMeshNodeInstanced(std::string& json, size_t mesh_offset, size_t accr_offset, bool has_color)
{
comma(json);
append(json, "{\"mesh\":");
append(json, mesh_offset);
append(json, ",\"extensions\":{\"EXT_mesh_gpu_instancing\":{\"attributes\":{");
comma(json);
append(json, "\"TRANSLATION\":");
append(json, accr_offset + 0);
comma(json);
append(json, "\"ROTATION\":");
append(json, accr_offset + 1);
comma(json);
append(json, "\"SCALE\":");
append(json, accr_offset + 2);
if (has_color)
{
comma(json);
append(json, "\"_COLOR_0\":");
append(json, accr_offset + 3);
}
append(json, "}}}");
append(json, "}");
}
void writeSkin(std::string& json, const cgltf_skin& skin, size_t matrix_accr, const std::vector<NodeInfo>& nodes, cgltf_data* data)
{
comma(json);
append(json, "{");
if (skin.name && *skin.name)
{
append(json, "\"name\":\"");
append(json, skin.name);
append(json, "\",");
}
append(json, "\"joints\":[");
for (size_t j = 0; j < skin.joints_count; ++j)
{
comma(json);
append(json, size_t(nodes[skin.joints[j] - data->nodes].remap));
}
append(json, "]");
append(json, ",\"inverseBindMatrices\":");
append(json, matrix_accr);
if (skin.skeleton)
{
comma(json);
append(json, "\"skeleton\":");
append(json, size_t(nodes[skin.skeleton - data->nodes].remap));
}
append(json, "}");
}
void writeNode(std::string& json, const cgltf_node& node, const std::vector<NodeInfo>& nodes, cgltf_data* data)
{
const NodeInfo& ni = nodes[&node - data->nodes];
if (node.name && *node.name)
{
comma(json);
append(json, "\"name\":\"");
append(json, node.name);
append(json, "\"");
}
if (node.has_translation)
{
comma(json);
append(json, "\"translation\":");
append(json, node.translation, 3);
}
if (node.has_rotation)
{
comma(json);
append(json, "\"rotation\":");
append(json, node.rotation, 4);
}
if (node.has_scale)
{
comma(json);
append(json, "\"scale\":");
append(json, node.scale, 3);
}
if (node.has_matrix)
{
comma(json);
append(json, "\"matrix\":");
append(json, node.matrix, 16);
}
bool has_children = !ni.mesh_nodes.empty();
for (size_t j = 0; j < node.children_count; ++j)
has_children |= nodes[node.children[j] - data->nodes].keep;
if (has_children)
{
comma(json);
append(json, "\"children\":[");
for (size_t j = 0; j < node.children_count; ++j)
{
const NodeInfo& ci = nodes[node.children[j] - data->nodes];
if (ci.keep)
{
comma(json);
append(json, size_t(ci.remap));
}
}
for (size_t j = 0; j < ni.mesh_nodes.size(); ++j)
{
comma(json);
append(json, ni.mesh_nodes[j]);
}
append(json, "]");
}
if (ni.has_mesh)
{
comma(json);
append(json, "\"mesh\":");
append(json, ni.mesh_index);
if (ni.mesh_skin)
{
append(json, ",\"skin\":");
append(json, size_t(ni.mesh_skin - data->skins));
}
if (node.weights_count)
{
append(json, ",\"weights\":");
append(json, node.weights, node.weights_count);
}
}
if (node.camera)
{
comma(json);
append(json, "\"camera\":");
append(json, size_t(node.camera - data->cameras));
}
if (node.light)
{
comma(json);
append(json, "\"extensions\":{\"KHR_lights_punctual\":{\"light\":");
append(json, size_t(node.light - data->lights));
append(json, "}}");
}
}
void writeAnimation(std::string& json, std::vector<BufferView>& views, std::string& json_accessors, size_t& accr_offset, const Animation& animation, size_t i, cgltf_data* data, const std::vector<NodeInfo>& nodes, const Settings& settings)
{
std::vector<const Track*> tracks;
for (size_t j = 0; j < animation.tracks.size(); ++j)
{
const Track& track = animation.tracks[j];
const NodeInfo& ni = nodes[track.node - data->nodes];
if (!ni.keep)
continue;
if (!settings.anim_const && (ni.animated_path_mask & (1 << track.path)) == 0)
continue;
tracks.push_back(&track);
}
if (tracks.empty())
{
fprintf(stderr, "Warning: ignoring animation %d (%s) because it has no tracks with motion; use -ac to override\n", int(i), animation.name ? animation.name : "");
return;
}
bool needs_time = false;
bool needs_pose = false;
for (size_t j = 0; j < tracks.size(); ++j)
{
const Track& track = *tracks[j];
#ifndef NDEBUG
size_t keyframe_size = (track.interpolation == cgltf_interpolation_type_cubic_spline) ? 3 : 1;
size_t time_size = track.constant ? 1 : (track.time.empty() ? animation.frames : track.time.size());
assert(track.data.size() == keyframe_size * track.components * time_size);
#endif
needs_time = needs_time || (track.time.empty() && !track.constant);
needs_pose = needs_pose || track.constant;
}
bool needs_range = needs_pose && !needs_time && animation.frames > 1;
needs_pose = needs_pose && !(needs_range && tracks.size() == 1);
assert(int(needs_time) + int(needs_pose) + int(needs_range) <= 2);
float animation_period = 1.f / float(settings.anim_freq);
float animation_length = float(animation.frames - 1) * animation_period;
size_t time_accr = needs_time ? writeAnimationTime(views, json_accessors, accr_offset, animation.start, animation.frames, animation_period, settings) : 0;
size_t pose_accr = needs_pose ? writeAnimationTime(views, json_accessors, accr_offset, animation.start, 1, 0.f, settings) : 0;
size_t range_accr = needs_range ? writeAnimationTime(views, json_accessors, accr_offset, animation.start, 2, animation_length, settings) : 0;
std::string json_samplers;
std::string json_channels;
size_t track_offset = 0;
size_t last_track_time_accr = 0;
const Track* last_track_time = NULL;
for (size_t j = 0; j < tracks.size(); ++j)
{
const Track& track = *tracks[j];
bool range = needs_range && j == 0;
int range_size = range ? 2 : 1;
size_t track_time_accr = time_accr;
if (!track.time.empty())
{
// reuse time accessors between consecutive tracks if possible
if (last_track_time && track.time == last_track_time->time)
track_time_accr = last_track_time_accr;
else
{
track_time_accr = writeAnimationTime(views, json_accessors, accr_offset, track.time, settings);
last_track_time_accr = track_time_accr;
last_track_time = &track;
}
}
std::string scratch;
StreamFormat format = writeKeyframeStream(scratch, track.path, track.data, settings, track.interpolation == cgltf_interpolation_type_cubic_spline);
if (range)
{
assert(range_size == 2);
scratch += scratch;
}
BufferView::Compression compression = settings.compress && track.path != cgltf_animation_path_type_weights ? BufferView::Compression_Attribute : BufferView::Compression_None;
size_t view = getBufferView(views, BufferView::Kind_Keyframe, format.filter, compression, format.stride, track.path);
size_t offset = views[view].data.size();
views[view].data += scratch;
comma(json_accessors);
writeAccessor(json_accessors, view, offset, format.type, format.component_type, format.normalized, track.data.size() * range_size);
size_t data_accr = accr_offset++;
comma(json_samplers);
append(json_samplers, "{\"input\":");
append(json_samplers, range ? range_accr : (track.constant ? pose_accr : track_time_accr));
append(json_samplers, ",\"output\":");
append(json_samplers, data_accr);
if (track.interpolation != cgltf_interpolation_type_linear)
{
append(json_samplers, ",\"interpolation\":\"");
append(json_samplers, interpolationType(track.interpolation));
append(json_samplers, "\"");
}
append(json_samplers, "}");
const NodeInfo& tni = nodes[track.node - data->nodes];
size_t target_node = size_t(tni.remap);
// when animating morph weights, quantization may move mesh assignments to a mesh node in which case we need to move the animation output
if (track.path == cgltf_animation_path_type_weights && tni.mesh_nodes.size() == 1)
target_node = tni.mesh_nodes[0];
comma(json_channels);
append(json_channels, "{\"sampler\":");
append(json_channels, track_offset);
append(json_channels, ",\"target\":{\"node\":");
append(json_channels, target_node);
append(json_channels, ",\"path\":\"");
append(json_channels, animationPath(track.path));
append(json_channels, "\"}}");
track_offset++;
}
comma(json);
append(json, "{");
if (animation.name && *animation.name)
{
append(json, "\"name\":\"");
append(json, animation.name);
append(json, "\",");
}
append(json, "\"samplers\":[");
append(json, json_samplers);
append(json, "],\"channels\":[");
append(json, json_channels);
append(json, "]}");
}
void writeCamera(std::string& json, const cgltf_camera& camera)
{
comma(json);
append(json, "{");
switch (camera.type)
{
case cgltf_camera_type_perspective:
append(json, "\"type\":\"perspective\",\"perspective\":{");
append(json, "\"yfov\":");
append(json, camera.data.perspective.yfov);
append(json, ",\"znear\":");
append(json, camera.data.perspective.znear);
if (camera.data.perspective.aspect_ratio != 0.f)
{
append(json, ",\"aspectRatio\":");
append(json, camera.data.perspective.aspect_ratio);
}
if (camera.data.perspective.zfar != 0.f)
{
append(json, ",\"zfar\":");
append(json, camera.data.perspective.zfar);
}
append(json, "}");
break;
case cgltf_camera_type_orthographic:
append(json, "\"type\":\"orthographic\",\"orthographic\":{");
append(json, "\"xmag\":");
append(json, camera.data.orthographic.xmag);
append(json, ",\"ymag\":");
append(json, camera.data.orthographic.ymag);
append(json, ",\"znear\":");
append(json, camera.data.orthographic.znear);
append(json, ",\"zfar\":");
append(json, camera.data.orthographic.zfar);
append(json, "}");
break;
default:
fprintf(stderr, "Warning: skipping camera of unknown type\n");
}
append(json, "}");
}
void writeLight(std::string& json, const cgltf_light& light)
{
comma(json);
append(json, "{\"type\":\"");
append(json, lightType(light.type));
append(json, "\"");
if (memcmp(light.color, white, 12) != 0)
{
comma(json);
append(json, "\"color\":");
append(json, light.color, 3);
}
if (light.intensity != 1.f)
{
comma(json);
append(json, "\"intensity\":");
append(json, light.intensity);
}
if (light.range != 0.f)
{
comma(json);
append(json, "\"range\":");
append(json, light.range);
}
if (light.type == cgltf_light_type_spot)
{
comma(json);
append(json, "\"spot\":{");
append(json, "\"innerConeAngle\":");
append(json, light.spot_inner_cone_angle);
append(json, ",\"outerConeAngle\":");
append(json, light.spot_outer_cone_angle == 0.f ? 0.78539816339f : light.spot_outer_cone_angle);
append(json, "}");
}
append(json, "}");
}
void writeArray(std::string& json, const char* name, const std::string& contents)
{
if (contents.empty())
return;
comma(json);
append(json, "\"");
append(json, name);
append(json, "\":[");
append(json, contents);
append(json, "]");
}
void writeExtensions(std::string& json, const ExtensionInfo* extensions, size_t count)
{
bool used_extensions = false;
bool required_extensions = false;
for (size_t i = 0; i < count; ++i)
{
used_extensions |= extensions[i].used;
required_extensions |= extensions[i].used && extensions[i].required;
}
if (used_extensions)
{
comma(json);
append(json, "\"extensionsUsed\":[");
for (size_t i = 0; i < count; ++i)
if (extensions[i].used)
{
comma(json);
append(json, "\"");
append(json, extensions[i].name);
append(json, "\"");
}
append(json, "]");
}
if (required_extensions)
{
comma(json);
append(json, "\"extensionsRequired\":[");
for (size_t i = 0; i < count; ++i)
if (extensions[i].used && extensions[i].required)
{
comma(json);
append(json, "\"");
append(json, extensions[i].name);
append(json, "\"");
}
append(json, "]");
}
}
void writeExtras(std::string& json, const cgltf_extras& extras)
{
if (!extras.data)
return;
comma(json);
append(json, "\"extras\":");
appendJson(json, extras.data);
}
void writeScene(std::string& json, const cgltf_scene& scene, const std::string& roots, const Settings& settings)
{
comma(json);
append(json, "{");
if (scene.name && *scene.name)
{
append(json, "\"name\":\"");
append(json, scene.name);
append(json, "\"");
}
if (!roots.empty())
{
comma(json);
append(json, "\"nodes\":[");
append(json, roots);
append(json, "]");
}
if (settings.keep_extras)
writeExtras(json, scene.extras);
append(json, "}");
}
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
js/benchmark.js | JavaScript | import { MeshoptEncoder as encoder } from './meshopt_encoder.js';
import { MeshoptDecoder as decoder } from './meshopt_decoder.mjs';
import { performance } from 'perf_hooks';
process.on('unhandledRejection', (error) => {
console.log('unhandledRejection', error);
process.exit(1);
});
function bytes(view) {
return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
}
var tests = {
roundtripVertexBuffer: function () {
var N = 1024 * 1024;
var data = new Uint8Array(N * 16);
var lcg = 1;
for (var i = 0; i < N * 16; ++i) {
// mindstd_rand
lcg = (lcg * 48271) % 2147483647;
var k = i % 16;
if (k <= 8) data[i] = lcg & ((1 << k) - 1);
else data[i] = i & ((1 << (k - 8)) - 1);
}
var decoded = new Uint8Array(N * 16);
var t0 = performance.now();
var encoded = encoder.encodeVertexBuffer(data, N, 16);
var t1 = performance.now();
decoder.decodeVertexBuffer(decoded, N, 16, encoded);
var t2 = performance.now();
return { encodeVertex: t1 - t0, decodeVertex: t2 - t1, bytes: N * 16 };
},
roundtripIndexBuffer: function () {
var N = 1024 * 1024;
var data = new Uint32Array(N * 3);
for (var i = 0; i < N * 3; i += 6) {
var v = i / 6;
data[i + 0] = v;
data[i + 1] = v + 1;
data[i + 2] = v + 2;
data[i + 3] = v + 2;
data[i + 4] = v + 1;
data[i + 5] = v + 3;
}
var decoded = new Uint32Array(data.length);
var t0 = performance.now();
var encoded = encoder.encodeIndexBuffer(bytes(data), data.length, 4);
var t1 = performance.now();
decoder.decodeIndexBuffer(bytes(decoded), data.length, 4, encoded);
var t2 = performance.now();
return { encodeIndex: t1 - t0, decodeIndex: t2 - t1, bytes: N * 12 };
},
decodeGltf: function () {
var N = 1024 * 1024;
var data = new Uint8Array(N * 16);
for (var i = 0; i < N * 16; i += 4) {
data[i + 0] = 0;
data[i + 1] = (i % 16) * 1;
data[i + 2] = (i % 16) * 2;
data[i + 3] = (i % 16) * 8;
}
var decoded = new Uint8Array(N * 16);
var filters = [
{ name: 'none', filter: 'NONE', stride: 16 },
{ name: 'oct8', filter: 'OCTAHEDRAL', stride: 4 },
{ name: 'oct12', filter: 'OCTAHEDRAL', stride: 8 },
{ name: 'quat12', filter: 'QUATERNION', stride: 8 },
{ name: 'col8', filter: 'COLOR', stride: 4 },
{ name: 'col12', filter: 'COLOR', stride: 8 },
{ name: 'exp', filter: 'EXPONENTIAL', stride: 16 },
];
var results = { bytes: N * 16 };
for (var i = 0; i < filters.length; ++i) {
var f = filters[i];
var encoded = encoder.encodeVertexBuffer(data, (N * 16) / f.stride, f.stride);
var t0 = performance.now();
decoder.decodeGltfBuffer(decoded, (N * 16) / f.stride, f.stride, encoded, 'ATTRIBUTES', f.filter);
var t1 = performance.now();
results[f.name] = t1 - t0;
}
return results;
},
};
Promise.all([encoder.ready, decoder.ready]).then(() => {
var reps = 10;
var data = {};
for (var key in tests) {
data[key] = tests[key]();
}
for (var i = 1; i < reps; ++i) {
for (var key in tests) {
var nd = tests[key]();
var od = data[key];
for (var idx in nd) {
od[idx] = Math.min(od[idx], nd[idx]);
}
}
}
for (var key in tests) {
var rep = key;
rep += ':\n';
for (var idx in data[key]) {
if (idx != 'bytes') {
rep += idx;
rep += ' ';
rep += data[key][idx].toFixed(3);
rep += ' ms (';
rep += ((data[key].bytes / 1e9 / data[key][idx]) * 1000).toFixed(3);
rep += ' GB/s)';
if (key == 'decodeGltf' && idx != 'none') {
rep += '; filter ';
rep += ((data[key].bytes / 1e9 / (data[key][idx] - data[key]['none'])) * 1000).toFixed(3);
rep += ' GB/s';
}
rep += '\n';
}
}
console.log(rep);
}
});
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
js/index.d.ts | TypeScript | export * from './meshopt_encoder.js';
export * from './meshopt_decoder.js';
export * from './meshopt_simplifier.js';
export * from './meshopt_clusterizer.js';
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
js/index.js | JavaScript | export * from './meshopt_encoder.js';
export * from './meshopt_decoder.mjs';
export * from './meshopt_simplifier.js';
export * from './meshopt_clusterizer.js';
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
js/meshopt_clusterizer.d.ts | TypeScript | // This file is part of meshoptimizer library and is distributed under the terms of MIT License.
// Copyright (C) 2016-2026, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
export class Bounds {
centerX: number;
centerY: number;
centerZ: number;
radius: number;
coneApexX: number;
coneApexY: number;
coneApexZ: number;
coneAxisX: number;
coneAxisY: number;
coneAxisZ: number;
coneCutoff: number;
}
export class MeshletBuffers {
meshlets: Uint32Array;
vertices: Uint32Array;
triangles: Uint8Array;
meshletCount: number;
}
export class Meshlet {
vertices: Uint32Array;
triangles: Uint8Array;
}
export const MeshoptClusterizer: {
supported: boolean;
ready: Promise<void>;
buildMeshlets: (
indices: Uint32Array,
vertex_positions: Float32Array,
vertex_positions_stride: number,
max_vertices: number,
max_triangles: number,
cone_weight?: number
) => MeshletBuffers;
buildMeshletsFlex: (
indices: Uint32Array,
vertex_positions: Float32Array,
vertex_positions_stride: number,
max_vertices: number,
min_triangles: number,
max_triangles: number,
cone_weight?: number,
split_factor?: number
) => MeshletBuffers;
buildMeshletsSpatial: (
indices: Uint32Array,
vertex_positions: Float32Array,
vertex_positions_stride: number,
max_vertices: number,
min_triangles: number,
max_triangles: number,
fill_weight?: number
) => MeshletBuffers;
extractMeshlet: (buffers: MeshletBuffers, index: number) => Meshlet;
computeClusterBounds: (indices: Uint32Array, vertex_positions: Float32Array, vertex_positions_stride: number) => Bounds;
computeMeshletBounds: (buffers: MeshletBuffers, vertex_positions: Float32Array, vertex_positions_stride: number) => Bounds[];
computeSphereBounds: (positions: Float32Array, positions_stride: number, radii?: Float32Array, radii_stride?: number) => Bounds;
};
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
js/meshopt_clusterizer.js | JavaScript | // This file is part of meshoptimizer library and is distributed under the terms of MIT License.
// Copyright (C) 2016-2026, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
var MeshoptClusterizer = (function () {
// Built with clang version 19.1.5-wasi-sdk
// Built from meshoptimizer 1.0
var wasm =
'b9H79Tebbbe96x9Geueu9Geub9Gbb9Giuuueu9Gmuuuuuuuuuuu9999eu9Gouuuuuueu9Gruuuuuuub9Gxuuuuuuuuuuuueu9Gxuuuuuuuuuuu99eu9GPuuuuuuuuuuuuu99b9Gouuuuuub9GluuuubiCAdilvorwDqooqkbiibeilve9Weiiviebeoweuecj:Pdkr;Zeqo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9I919P29K9nW79O2Wt79c9V919U9KbeY9TW79O9V9Wt9F9I919P29K9nW79O2Wt7S2W94bd39TW79O9V9Wt9F9I919P29K9nW79O2Wt79t9W9Ht9P9H2bo39TW79O9V9Wt9F9J9V9T9W91tWJ2917tWV9c9V919U9K7bw39TW79O9V9Wt9F9J9V9T9W91tW9nW79O2Wt9c9V919U9K7bqE9TW79O9V9Wt9F9J9V9T9W91tW9t9W9OWVW9c9V919U9K7bkL9TW79O9V9Wt9F9V9Wt9P9T9P96W9nW79O2Wtbxl79IV9RbmDwebcekdzHq:Y:beAdbkIbabaec9:fgefcufae9Ugeabci9Uadfcufad9Ugbaeab0Ek;z8JDPue99eux99due99euo99iu8Jjjjjbc:WD9Rgm8KjjjjbdndnalmbcbhPxekamc:Cwfcbc;Kbz:pjjjb8Adndnalcb9imbaoal9nmbamcuaocdtaocFFFFi0Egscbyd;01jjbHjjjjbbgzBd:CwamceBd;8wamascbyd;01jjbHjjjjbbgHBd:GwamcdBd;8wamcualcdtalcFFFFi0Ecbyd;01jjbHjjjjbbgOBd:KwamciBd;8waihsalhAinazasydbcdtfcbBdbasclfhsaAcufgAmbkaihsalhAinazasydbcdtfgCaCydbcefBdbasclfhsaAcufgAmbkaihsalhCcbhXindnazasydbcdtgQfgAydbcb9imbaHaQfaXBdbaAaAydbgQcjjjj94VBdbaQaXfhXkasclfhsaCcufgCmbkalci9UhLdnalci6mbcbhsaihAinaAcwfydbhCaAclfydbhXaHaAydbcdtfgQaQydbgQcefBdbaOaQcdtfasBdbaHaXcdtfgXaXydbgXcefBdbaOaXcdtfasBdbaHaCcdtfgCaCydbgCcefBdbaOaCcdtfasBdbaAcxfhAaLascefgs9hmbkkaihsalhAindnazasydbcdtgCfgXydbgQcu9kmbaXaQcFFFFrGgQBdbaHaCfgCaCydbaQ9RBdbkasclfhsaAcufgAmbxdkkamcuaocdtgsaocFFFFi0EgAcbyd;01jjbHjjjjbbgzBd:CwamceBd;8wamaAcbyd;01jjbHjjjjbbgHBd:GwamcdBd;8wamcualcdtalcFFFFi0Ecbyd;01jjbHjjjjbbgOBd:KwamciBd;8wazcbasz:pjjjbhXalci9UhLaihsalhAinaXasydbcdtfgCaCydbcefBdbasclfhsaAcufgAmbkdnaoTmbcbhsaHhAaXhCaohQinaAasBdbaAclfhAaCydbasfhsaCclfhCaQcufgQmbkkdnalci6mbcbhsaihAinaAcwfydbhCaAclfydbhQaHaAydbcdtfgKaKydbgKcefBdbaOaKcdtfasBdbaHaQcdtfgQaQydbgQcefBdbaOaQcdtfasBdbaHaCcdtfgCaCydbgCcefBdbaOaCcdtfasBdbaAcxfhAaLascefgs9hmbkkaoTmbcbhsaohAinaHasfgCaCydbaXasfydb9RBdbasclfhsaAcufgAmbkkamaLcbyd;01jjbHjjjjbbgsBd:OwamclBd;8wascbaLz:pjjjbhYamcuaLcK2alcjjjjd0Ecbyd;01jjbHjjjjbbg8ABd:SwamcvBd;8wJbbbbhEdnalci6g3mbarcd4hKaihAa8AhsaLhrJbbbbh5inavaAclfydbaK2cdtfgCIdlh8EavaAydbaK2cdtfgXIdlhEavaAcwfydbaK2cdtfgQIdlh8FaCIdwhaaXIdwhhaQIdwhgasaCIdbg8JaXIdbg8KMaQIdbg8LMJbbnn:vUdbasclfaXIdlaCIdlMaQIdlMJbbnn:vUdbaQIdwh8MaCIdwh8NaXIdwhyascxfa8EaE:tg8Eagah:tggNa8FaE:tg8Faaah:tgaN:tgEJbbbbJbbjZa8Ja8K:tg8Ja8FNa8La8K:tg8Ka8EN:tghahNaEaENaaa8KNaga8JN:tgEaENMM:rg8K:va8KJbbbb9BEg8ENUdbasczfaEa8ENUdbascCfaha8ENUdbascwfa8Maya8NMMJbbnn:vUdba5a8KMh5aAcxfhAascKfhsarcufgrmbka5aL:Z:vJbbbZNhEkamcuaLcdtalcFFFF970Ecbyd;01jjbHjjjjbbgCBd:WwamcoBd;8waq:Zhhdna3mbcbhsaChAinaAasBdbaAclfhAaLascefgs9hmbkkaEahNhhamcuaLcltalcFFFFd0Ecbyd;01jjbHjjjjbbg8PBd:0wamcrBd;8wcba8Pa8AaCaLcbz:djjjb8AJFFuuh8MJFFuuh8NJFFuuhydnalci6mbJFFuuhya8AhsaLhAJFFuuh8NJFFuuh8MinascwfIdbgEa8Ma8MaE9EEh8MasclfIdbgEa8Na8NaE9EEh8NasIdbgEayayaE9EEhyascKfhsaAcufgAmbkkah:rhEamaocetgscuaocu9kEcbyd;01jjbHjjjjbbgCBd:4wdndnaoal9nmbaihsalhAinaCasydbcetfcFFi87ebasclfhsaAcufgAmbxdkkaCcFeasz:pjjjb8AkaEJbbbZNh8JcuhIdnalci6mbcbhAJFFuuhEa8AhscuhIinascwfIdba8M:tghahNasIdbay:tghahNasclfIdba8N:tghahNMM:rghaEaIcuSahaE9DVgXEhEaAaIaXEhIascKfhsaLaAcefgA9hmbkkamczfcbcjwz:pjjjb8Aamcwf9cb83ibam9cb83iba8JaxNh8RJbbjZak:th8Lcbh8SJbbbbhRJbbbbh8UJbbbbh8VJbbbbh8WJbbbbh8XJbbbbh8Ycbh8ZcbhPinJbbbbhEdna8STmbJbbjZa8S:Z:vhEkJbbbbhhdna8Ya8YNa8Wa8WNa8Xa8XNMMg8KJbbbb9BmbJbbjZa8K:r:vhhka8VaENh8Ka8UaENh8EaRaENh5aIhLdndndndndna8SaPVTmbamydwg80Tmea8YahNh8Fa8XahNhaa8WahNhgaeamydbcdtfh81cbh3JFFuuhEcvhQcuhLindnaza81a3cdtfydbcdtgsfydbgvTmbaOaHasfydbcdtfhAindndnaCaiaAydbgKcx2fgsclfydbgrcetf8Vebcs4aCasydbgXcetf8Vebcs4faCascwfydbglcetf8Vebcs4fgombcbhsxekcehsazaXcdtfydbgXceSmbcehsazarcdtfydbgrceSmbcehsazalcdtfydbglceSmbdnarcdSaXcdSfalcdSfcd6mbaocefhsxekaocdfhskdnasaQ9kmba8AaKcK2fgXIdwa8K:tghahNaXIdba5:tghahNaXIdla8E:tghahNMM:ra8J:va8LNJbbjZMJ9VO:d86JbbjZaXIdCa8FNaXIdxagNaaaXIdzNMMakN:tghahJ9VO:d869DENghaEasaQ6ahaE9DVgXEhEaKaLaXEhLasaQaXEhQkaAclfhAavcufgvmbkka3cefg3a809hmbkkaLcu9hmekama8KUd:ODama8EUd:KDama5Ud:GDamcuBd:qDamcFFF;7rBdjDa8Pcba8AaYamc:GDfamc:qDfamcjDfz:ejjjbamyd:qDhLdndnaxJbbbb9ETmba8SaD6mbaLcuSmeceh3amIdjDa8R9EmixdkaLcu9hmekdna8STmbabaPcltfgzam8Pib83dbazcwfamcwf8Pib83dbaPcefhPkc3hzinazc98Smvamc:Cwfazfydbcbyd;41jjbH:bjjjbbazc98fhzxbkkcbh3a8Saq9pmbamydwaCaiaLcx2fgsydbcetf8Vebcs4aCascwfydbcetf8Vebcs4faCasclfydbcetf8Vebcs4ffaw9nmekcbhscbhAdna8ZTmbcbhAamczfhXinamczfaAcdtfaXydbgQBdbaXclfhXaAaYaQfRbbTfhAa8Zcufg8ZmbkkamydwhlamydbhXam9cu83i:GDam9cu83i:ODam9cu83i:qDam9cu83i:yDaAc;8eaAclfc:bd6Eh8ZinamcjDfasfcFFF;7rBdbasclfgscz9hmbka8Zcdth80dnalTmbaeaXcdtfhocbhrindnazaoarcdtfydbcdtgsfydbgvTmbaOaHasfydbcdtfhAcuhQcuhsinazaiaAydbgKcx2fgXclfydbcdtfydbazaXydbcdtfydbfazaXcwfydbcdtfydbfgXasaXas6gXEhsaKaQaXEhQaAclfhAavcufgvmbkaQcuSmba8AaQcK2fgAIdwa8M:tgEaENaAIdbay:tgEaENaAIdla8N:tgEaENMM:rhEcbhAindndnasamc:qDfaAfgvydbgX6mbasaX9hmeaEamcjDfaAfIdb9FTmekavasBdbamc:GDfaAfaQBdbamcjDfaAfaEUdbxdkaAclfgAcz9hmbkkarcefgral9hmbkkamczfa80fhQcbhscbhAindnamc:GDfasfydbgXcuSmbaQaAcdtfaXBdbaAcefhAkasclfgscz9hmbkaAa8Zfg8ZTmbJFFuuhhcuhKamczfhsa8ZhvcuhQina8AasydbgXcK2fgAIdwa8M:tgEaENaAIdbay:tgEaENaAIdla8N:tgEaENMM:rhEdndnazaiaXcx2fgAclfydbcdtfydbazaAydbcdtfydbfazaAcwfydbcdtfydbfgAaQ6mbaAaQ9hmeaEah9DTmekaEhhaAhQaXhKkasclfhsavcufgvmbkaKcuSmbaKhLkdnamaiaLcx2fgrydbarclfydbarcwfydbaCabaeadaPawaqa3z:fjjjbTmbaPcefhPJbbbbhRJbbbbh8UJbbbbh8VJbbbbh8WJbbbbh8XJbbbbh8YkcbhXinaOaHaraXcdtfydbcdtgAfydbcdtfgKhsazaAfgvydbgQhAdnaQTmbdninasydbaLSmeasclfhsaAcufgATmdxbkkasaKaQcdtfc98fydbBdbavavydbcufBdbkaXcefgXci9hmbka8AaLcK2fgsIdbhEasIdlhhasIdwh8KasIdxh8EasIdzh5asIdCh8FaYaLfce86bba8Ya8FMh8Ya8Xa5Mh8Xa8Wa8EMh8Wa8Va8KMh8Va8UahMh8UaRaEMhRamydxh8Sxbkkamc:WDf8KjjjjbaPk:joivuv99lu8Jjjjjbca9Rgo8Kjjjjbdndnalcw0mbaiydbhraeabcitfgwalcdtciVBdlawarBdbdnalcd6mbaiclfhralcufhDawcxfhwinarydbhqawcuBdbawc98faqBdbawcwfhwarclfhraDcufgDmbkkalabfhwxekcbhqaoczfcwfcbBdbao9cb83izaocwfcbBdbao9cb83ibJbbjZhkJbbjZhxinadaiaqcdtfydbcK2fhDcbhwinaoczfawfgraDawfIdbgmarIdbgP:tgsaxNaPMgPUdbaoawfgrasamaP:tNarIdbMUdbawclfgwcx9hmbkJbbjZakJbbjZMgk:vhxaqcefgqal9hmbkcbhradcbcecdaoIdlgmaoIdwgP9GEgwaoIdbgsaP9GEawasam9GEgzcdtgwfhHaoczfawfIdbhmaihwalhDinaiarcdtfgqydbhOaqawydbgABdbawaOBdbawclfhwaraHaAcK2fIdbam9DfhraDcufgDmbkdndnarcv6mbavc8X9kmbaralc98f6mekaiydbhraeabcitfgwalcdtciVBdlawarBdbaiclfhralcufhDawcxfhwinarydbhqawcuBdbawc98faqBdbawcwfhwarclfhraDcufgDmbkalabfhwxekaeabcitfgwamUdbawawydlc98GazVBdlabcefaeadaiaravcefgqz:djjjbhDawawydlciGaDabcu7fcdtVBdlaDaeadaiarcdtfalar9Raqz:djjjbhwkaocaf8Kjjjjbawk;yddvue99dninabaecitfgrydlgwcl6mednawciGgDci9hmbabaecitfhbcbhecehqindnaiabydbgDfRbbmbcbhqadaDcK2fgkIdwalIdw:tgxaxNakIdbalIdb:tgxaxNakIdlalIdl:tgxaxNMM:rgxaoIdb9DTmbaoaxUdbavaDBdbarydlhwkabcwfhbaecefgeawcd46mbkaqceGTmdarawciGBdlskdnabcbawcd4gwalaDcdtfIdbarIdb:tgxJbbbb9FEgkaw7aecefgwfgecitfydlabakawfgwcitfydlVci0mbaraDBdlkabawadaialavaoz:ejjjbax:laoIdb9Fmbkkkjlevudnabydwgxaladcetfgm8Vebcs4alaecetfgP8Vebgscs4falaicetfgz8Vebcs4ffaD0abydxaq9pVakVgDce9hmbavawcltfgxab8Pdb83dbaxcwfabcwfgx8Pdb83dbabydbhqdnaxydbgkTmbaoaqcdtfhxakhsinalaxydbcetfcFFi87ebaxclfhxascufgsmbkkabaqakfBdbabydxhxab9cb83dwababydlaxci2fBdlaP8Vebhscbhxkdnascztcz91cu9kmbabaxcefBdwaPax87ebaoabydbcdtfaxcdtfaeBdbkdnam8Uebcu9kmbababydwgxcefBdwamax87ebaoabydbcdtfaxcdtfadBdbkdnaz8Uebcu9kmbababydwgxcefBdwazax87ebaoabydbcdtfaxcdtfaiBdbkarabydlfabydxci2faPRbb86bbarabydlfabydxci2fcefamRbb86bbarabydlfabydxci2fcdfazRbb86bbababydxcefBdxaDk:zPrHue99eue99eue99eu8Jjjjjbc;W;Gb9Rgx8KjjjjbdndnalmbcbhmxekcbhPaxc:m;Gbfcbc;Kbz:pjjjb8Aaxcualci9UgscltascjjjjiGEcbyd;01jjbHjjjjbbgzBd:m9GaxceBd;S9GaxcuascK2gHcKfalcpFFFe0Ecbyd;01jjbHjjjjbbgOBd:q9GaxcdBd;S9Gdnalci6gAmbarcd4hCascdthXaOhQazhLinavaiaPcx2fgrydbaC2cdtfhKavarcwfydbaC2cdtfhYavarclfydbaC2cdtfh8AcbhraLhEinaQarfgmaKarfg3Idbg5a8Aarfg8EIdbg8Fa5a8F9DEg5UdbamaYarfgaIdbg8Fa5a8Fa59DEg8FUdbamcxfgma3Idbg5a8EIdbgha5ah9EEg5UdbamaaIdbgha5aha59EEg5UdbaEa8Fa5MJbbbZNUdbaEaXfhEarclfgrcx9hmbkaQcKfhQaLclfhLaPcefgPas9hmbkkaOaHfgr9cb83dbarczf9cb83dbarcwf9cb83dbaxcuascx2gralc:bjjjl0Ecbyd;01jjbHjjjjbbgCBdN9GaxciBd;S9GascdthgazarfhvaChHazhLcbhPinaxcbcj;Gbz:pjjjbhEaPas2cdthadnaAmbaLhrash3inaEarydbgmc8F91cjjjj94Vam7gmcQ4cx2fg8Ea8EydwcefBdwaEamcd4cFrGcx2fg8Ea8EydbcefBdbaEamcx4cFrGcx2fgmamydlcefBdlarclfhra3cufg3mbkkazaafh8AaCaafhXcbhmcbh3cbh8EcbhainaEamfgrydbhQara3BdbarcwfgKydbhYaKaaBdbarclfgrydbhKara8EBdbaQa3fh3aYaafhaaKa8Efh8Eamcxfgmcj;Gb9hmbkdnaAmbcbhravhminamarBdbamclfhmasarcefgr9hmbkaAmbavhrashminaEa8Aarydbg3cdtfydbg8Ec8F91a8E7cd4cFrGcx2fg8Ea8Eydbg8EcefBdbaXa8Ecdtfa3BdbarclfhramcufgmmbkaHhrashminaEa8Aarydbg3cdtfydbg8Ec8F91a8E7cx4cFrGcx2fg8Ea8Eydlg8EcefBdlava8Ecdtfa3BdbarclfhramcufgmmbkavhrashminaEa8Aarydbg3cdtfydbg8Ec8F91cjjjj94Va8E7cQ4cx2fg8Ea8Eydwg8EcefBdwaXa8Ecdtfa3BdbarclfhramcufgmmbkkaHagfhHaLagfhLaPcefgPci9hmbkaEaocetgrcuaocu9kEcbyd;01jjbHjjjjbbgKBd:y9GaEclBd;S9Gdndnaoal9nmbaihralhminaKarydbcetfcFFi87ebarclfhramcufgmmbxdkkaKcFearz:pjjjb8AkcbhmaEascbyd;01jjbHjjjjbbg8ABd:C9GaOaCaCascdtfaCascitfa8AascbazaKaiawaDaqakz:hjjjbcbh8Ednalci6gambcbh8Ea8Ahrash3ina8EarRbbfh8Earcefhra3cufg3mbkkaEcwf9cb83ibaE9cb83ibalawc9:fgrfcufar9UhrasaDfcufaD9Uh3dnaambara3ara30EhYcbhra8Ehacbhmincbh3dnarTmba8AarfRbbceSh3kamaEaiaCydbcx2fgQydbaQclfydbaQcwfydbaKabaeadamawaqa3a3ce7a8EaY9nVaaamfaY6VGz:fjjjbfhmaCclfhCaaa8AarfRbb9Rhaasarcefgr9hmbkaEydxTmbabamcltfgraE8Pib83dbarcwfaEcwf8Pib83dbamcefhmkczhrinarc98SmeaEc:m;Gbfarfydbcbyd;41jjbH:bjjjbbarc98fhrxbkkaxc;W;Gbf8Kjjjjbamk:YKDQue99lue99iul9:eur99lu8Jjjjjbc;qb9RgP8Kjjjjbaxhsaxhzdndnavax0gHmbdnavTmbcbhOaehzavhAinawaDazydbcx2fgCcwfydbcetfgX8VebhQawaCclfydbcetfgL8VebhKawaCydbcetfgC8VebhYaXce87ebaLce87ebaCce87ebaOaKcs4aYcs4faQcs4ffhOazclfhzaAcufgAmbkaehzavhAinawaDazydbcx2fgCcwfydbcetfcFFi87ebawaCclfydbcetfcFFi87ebawaCydbcetfcFFi87ebazclfhzaAcufgAmbkcehzaqhsaOaq0mekalce86bbalcefcbavcufz:pjjjb8AxekaPaiBdxaPadBdwaPaeBdlavakaqci9Ug8Aaka8Aak6EaHEgK9RhEaxaK9Rh3aKcufh5aKceth8EaKcdtgCc98fh8FavcitgOaC9Rarfc98fhaascufhhavcufhgaraOfh8JJbbjZas:Y:vh8KaravcdtgYfc94fh8LcbazceakaxSEg8Mcdtg8N9RhyJFFuuh8PcuhIcbh8Rcbh8SinaPclfa8ScdtfydbhQaPc8WfcKfcb8Pd:y1jjbgR83ibaPc8Wfczfcb8Pd:q1jjbg8U83ibaPc8Wfcwfcb8Pd11jjbg8V83ibaPcb8Pdj1jjbg8W83i8WaPczfcKfaR83ibaPczfczfa8U83ibaPczfcwfa8V83ibaPa8W83izaQaYfh8XcbhXinabaQaXcdtgLfydbcK2fhAcbhzinaPc8WfazfgCaAazfgOIdbg8YaCIdbg8Za8Ya8Z9DEUdbaCczfgCaOcxfIdbg8YaCIdbg8Za8Ya8Z9EEUdbazclfgzcx9hmbkaPIdnaPId8W:tg80aPId9iaPIdU:tg81NhBaba8XaXcu7cdtfydbcK2fhAcbhzaPId80h83aPId9ehUinaPczfazfgCaAazfgOIdbg8YaCIdbg8Za8Ya8Z9DEUdbaCczfgCaOcxfIdbg8YaCIdbg8Za8Ya8Z9EEUdbazclfgzcx9hmbkaraLfgzaUa83:tg8Ya81Na80a8YNaBMMUdbazaYfaPId8KaPIdC:tg8YaPIdyaPIdK:tg8ZNaPIdaaPIdz:tg80a8YNa80a8ZNMMUdbaXcefgXav9hmbkcbh85dnaHmbcbhAaQhza8JhCavhXinawaDazydbcx2fgOcwfydbcetfgL8Vebh8XawaOclfydbcetfg868Vebh85awaOydbcetfgO8Vebh87aLce87eba86ce87ebaOce87ebaCaAa85cs4a87cs4fa8Xcs4ffgABdbazclfhzaCclfhCaXcufgXmbkavhCinawaDaQydbcx2fgzcwfydbcetfcFFi87ebawazclfydbcetfcFFi87ebawazydbcetfcFFi87ebaQclfhQaCcufgCmbka8Jh85kdndndndndndndndndndna8Eav0mba8Eax0meavaK6mda5aE9pmDcehLaEhXa85Tmlxrka5ag9pmwa8Eax9nmdxlkdnavavaK9UgzaK29Raza320mba5aE9pmwa85Th88ceh86aEhLxvka5ag6mixrka5ag9pmokcbhLaghXa85mikJFFuuh8YcbhQa5hzindnazcefgCaK6mbaLavaC9RgOaK6GmbarazcdtfIdbg8ZaC:YNa8Lavaz9RcdtfIdbg80aO:YNMg81a8Y9Embdndna8KaOahf:YNgB:lJbbb9p9DTmbaB:OhAxekcjjjj94hAka80asaA2aO9R:YNh80dndna8Kazasf:YNgB:lJbbb9p9DTmbaB:OhOxekcjjjj94hOkamasaO2aC9R:Ya8ZNa80MNa81Mg8Za8Ya8Za8Y9DgOEh8YaCaQaOEhQkaza8MfgzaX6mbxlkka85Th88cbh86aghLkJFFuuh8YcbhQaEhCaahAa8FhOaKhzindnazazaK9UgXaK29RaXa320mbdna86TmbaCaCaK9UgXaK29RaXa320mekaraOfIdbg8Zaz:YNaAIdbg80aC:YNMg81a8Y9EmbazhXaCh8Xdna88mba85aOfydbgXh8Xkdndna8Ka8Xahf:YNgB:lJbbb9p9DTmbaB:Oh87xekcjjjj94h87ka80asa872a8X9R:YNh80dndna8KaXahf:YNgB:lJbbb9p9DTmbaB:Oh8Xxekcjjjj94h8Xkamasa8X2aX9R:Ya8ZNa80MNa81Mg8Za8Ya8Za8Y9DgXEh8YazaQaXEhQkaCa8M9RhCaAayfhAaOa8NfhOaza8MfgzcufaL6mbxdkkJFFuuh8YcbhQaEhCaahAa8FhOaKhzindnazaK6mbaLaCaK6GmbaraOfIdbg8Zaz:YNaAIdbg80aC:YNMg81a8Y9Embdndna8Ka85aOfydbg8Xahf:YNgB:lJbbb9p9DTmbaB:Oh86xekcjjjj94h86kamasa862a8X9R:YgBa8ZNa80aBNMNa81Mg8Za8Ya8Za8Y9Dg8XEh8YazaQa8XEhQkaCa8M9RhCaAayfhAaOa8NfhOaza8MfgzcufaX6mbkkaQTmba8Ya8P9DTmba8Yh8PaQh8Ra8ShIka8Scefg8Sci9hmbkdndnaoc8X9kmbaIcb9omeka8Acufh86cbhYindndndnavaY9RaxaYaxfav0Eg8XTmbcbhAaeaYcdtfgzhCa8XhXinawaDaCydbcx2fgOcwfydbcetfgQ8VebhbawaOclfydbcetfgL8VebhrawaOydbcetfgO8VebhKaQce87ebaLce87ebaOce87ebaAarcs4aKcs4fabcs4ffhAaCclfhCaXcufgXmbka8XhOinawaDazydbcx2fgCcwfydbcetfcFFi87ebawaCclfydbcetfcFFi87ebawaCydbcetfcFFi87ebazclfhzaOcufgOmbkaAaq0mekalaYfgzce86bbazcefcba8Xcufz:pjjjb8AxekalaYfgzce86bbazcefcba86z:pjjjb8Aa8Ah8Xka8XaYfgYav9pmdxbkkaravcdtg8XfhLdna8RTmbaPclfaIcdtfydbhza8RhCinaLazydbfcb86bbazclfhzaCcufgCmbkkdnava8R9nmbaPclfaIcdtfydba8Rcdtfhzava8R9RhCinaLazydbfce86bbazclfhzaCcufgCmbkkcbhYindnaYaISmbcbhzaraPclfaYcdtfydbgKa8Xz:ojjjbhCavhXa8RhOinaKaOazaLaCydbgQfRbbgAEcdtfaQBdbaCclfhCaOaAfhOazaA9RcefhzaXcufgXmbkkaYcefgYci9hmbkabaeadaiala8RaocefgCarawaDaqakaxamz:hjjjbabaea8Rcdtgzfadazfaiazfala8Rfava8R9RaCarawaDaqakaxamz:hjjjbkaPc;qbf8Kjjjjbk;Nkovud99euv99eul998Jjjjjbc:W;ae9Rgo8KjjjjbdndnadTmbavcd4hrcbhwcbhDindnaiaeclfydbar2cdtfgvIdbaiaeydbar2cdtfgqIdbgk:tgxaiaecwfydbar2cdtfgmIdlaqIdlgP:tgsNamIdbak:tgzavIdlaP:tgPN:tgkakNaPamIdwaqIdwgH:tgONasavIdwaH:tgHN:tgPaPNaHazNaOaxN:tgxaxNMM:rgsJbbbb9Bmbaoc:W:qefawcx2fgAakas:vUdwaAaxas:vUdlaAaPas:vUdbaoc8Wfawc8K2fgAaq8Pdb83dbaAav8Pdb83dxaAam8Pdb83dKaAcwfaqcwfydbBdbaAcCfavcwfydbBdbaAcafamcwfydbBdbawcefhwkaecxfheaDcifgDad6mbkab9cb83dbabcyf9cb83dbabcaf9cb83dbabcKf9cb83dbabczf9cb83dbabcwf9cb83dbawTmeaocbBd8Sao9cb83iKao9cb83izaoczfaoc8Wfawci2cxaoc8Sfcbcrz:jjjjbaoIdKhCaoIdChXaoIdzhQao9cb83iwao9cb83ibaoaoc:W:qefawcxaoc8Sfcbciz:jjjjbJbbjZhkaoIdwgPJbbbbJbbjZaPaPNaoIdbgPaPNaoIdlgsasNMM:rgx:vaxJbbbb9BEgzNhxasazNhsaPazNhzaoc:W:qefheawhvinaecwfIdbaxNaeIdbazNasaeclfIdbNMMgPakaPak9DEhkaecxfheavcufgvmbkabaCUdwabaXUdlabaQUdbabaoId3UdxdndnakJ;n;m;m899FmbJbbbbhPaoc:W:qefheaoc8WfhvinaCavcwfIdb:taecwfIdbgHNaQavIdb:taeIdbgONaXavclfIdb:taeclfIdbgLNMMaxaHNazaONasaLNMM:vgHaPaHaP9EEhPavc8KfhvaecxfheawcufgwmbkabaxUd8KabasUdaabazUd3abaCaxaPN:tUdKabaXasaPN:tUdCabaQazaPN:tUdzabJbbjZakakN:t:rgkUdydndnaxJbbj:;axJbbj:;9GEgPJbbjZaPJbbjZ9FEJbb;:9cNJbbbZJbbb:;axJbbbb9GEMgP:lJbbb9p9DTmbaP:Ohexekcjjjj94hekabae86b8UdndnasJbbj:;asJbbj:;9GEgPJbbjZaPJbbjZ9FEJbb;:9cNJbbbZJbbb:;asJbbbb9GEMgP:lJbbb9p9DTmbaP:Ohvxekcjjjj94hvkabav86bRdndnazJbbj:;azJbbj:;9GEgPJbbjZaPJbbjZ9FEJbb;:9cNJbbbZJbbb:;azJbbbb9GEMgP:lJbbb9p9DTmbaP:Ohqxekcjjjj94hqkabaq86b8SdndnaecKtcK91:YJbb;:9c:vax:t:lavcKtcK91:YJbb;:9c:vas:t:laqcKtcK91:YJbb;:9c:vaz:t:lakMMMJbb;:9cNJbbjZMgk:lJbbb9p9DTmbak:Ohexekcjjjj94hekaecFbaecFb9iEhexekabcjjj;8iBdycFbhekabae86b8Vxekab9cb83dbabcyf9cb83dbabcaf9cb83dbabcKf9cb83dbabczf9cb83dbabcwf9cb83dbkaoc:W;aef8Kjjjjbk;Iwwvul99iud99eue99eul998Jjjjjbcje9Rgr8Kjjjjbavcd4hwaicd4hDdndnaoTmbarc;abfcbaocdtgvz:pjjjb8Aarc;Gbfcbavz:pjjjb8AarhvarcafhiaohqinavcFFF97BdbaicFFF;7rBdbaiclfhiavclfhvaqcufgqmbkdnadTmbcbhkinaeakaD2cdtfgvIdwhxavIdlhmavIdbhPalakaw2cdtfIdbhsarc;abfhzarhiarc;GbfhHarcafhqc:G1jjbhvaohOinasavcwfIdbaxNavIdbaPNavclfIdbamNMMgAMhCakhXdnaAas:tgAaqIdbgQ9DgLmbaHydbhXkaHaXBdbakhXdnaCaiIdbgK9EmbazydbhXaKhCkazaXBdbaiaCUdbaqaAaQaLEUdbavcxfhvaqclfhqaHclfhHaiclfhiazclfhzaOcufgOmbkakcefgkad9hmbkkadThkJbbbbhCcbhXarc;abfhvarc;Gbfhicbhqinalavydbgzaw2cdtfIdbalaiydbgHaw2cdtfIdbaeazaD2cdtfgzIdwaeaHaD2cdtfgHIdw:tgsasNazIdbaHIdb:tgsasNazIdlaHIdl:tgsasNMM:rMMgsaCasaC9EgzEhCaqaXazEhXaiclfhiavclfhvaoaqcefgq9hmbkaCJbbbZNhKxekadThkcbhXJbbbbhKkJbbbbhCdnaearc;abfaXcdtgifydbgqaD2cdtfgvIdwaearc;GbfaifydbgzaD2cdtfgiIdwgm:tgsasNavIdbaiIdbgY:tgAaANavIdlaiIdlgP:tgQaQNMM:rgxJbbbb9ETmbaxalaqaw2cdtfIdbMalazaw2cdtfIdb:taxaxM:vhCkasaCNamMhmaQaCNaPMhPaAaCNaYMhYdnakmbaDcdthvawcdthiindnalIdbg8AaecwfIdbam:tgCaCNaeIdbaY:tgsasNaeclfIdbaP:tgAaANMM:rgQMgEaK9ETmbJbbbbhxdnaQJbbbb9ETmbaEaK:taQaQM:vhxkaxaCNamMhmaxaANaPMhPaxasNaYMhYa8AaKaQMMJbbbZNhKkaeavfhealaifhladcufgdmbkkabaKUdxabamUdwabaPUdlabaYUdbarcjef8Kjjjjbkjeeiu8Jjjjjbcj8W9Rgr8Kjjjjbaici2hwdnaiTmbawceawce0EhDarhiinaiaeadRbbcdtfydbBdbadcefhdaiclfhiaDcufgDmbkkabarawaladaoz1jjjbarcj8Wf8Kjjjjbk:Reeeu8Jjjjjbca9Rgo8Kjjjjbab9cb83dbabcyf9cb83dbabcaf9cb83dbabcKf9cb83dbabczf9cb83dbabcwf9cb83dbdnadTmbaocbBd3ao9cb83iwao9cb83ibaoaeadaialaoc3falEavcbalEcrz:jjjjbabao8Pib83dbabao8Piw83dwkaocaf8Kjjjjbk:3lequ8JjjjjbcjP9Rgl8Kjjjjbcbhvalcjxfcbaiz:pjjjb8AdndnadTmbcjehoaehrincuhwarhDcuhqavhkdninawakaoalcjxfaDcefRbbfRbb9RcFeGci6aoalcjxfaDRbbfRbb9RcFeGci6faoalcjxfaDcdfRbbfRbb9RcFeGci6fgxaq9mgmEhwdnammbaxce0mdkaxaqaxaq9kEhqaDcifhDadakcefgk9hmbkkaeawci2fgDcdfRbbhqaDcefRbbhxaDRbbhkaeavci2fgDcifaDawav9Rci2zMjjjb8Aakalcjxffaocefgo86bbaxalcjxffao86bbaDcdfaq86bbaDcefax86bbaDak86bbaqalcjxffao86bbarcifhravcefgvad9hmbkalcFeaicetz:pjjjbhoadci2gDceaDce0EhqcbhxindnaoaeRbbgkcetfgw8UebgDcu9kmbawax87ebaocjlfaxcdtfabakcdtfydbBdbaxhDaxcefhxkaeaD86bbaecefheaqcufgqmbkaxcdthDxekcbhDkabalcjlfaDz:ojjjb8AalcjPf8Kjjjjbk9teiucbcbyd;81jjbgeabcifc98GfgbBd;81jjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaik;teeeudndnaeabVciGTmbabhixekdndnadcz9pmbabhixekabhiinaiaeydbBdbaiaeydlBdlaiaeydwBdwaiaeydxBdxaeczfheaiczfhiadc9Wfgdcs0mbkkadcl6mbinaiaeydbBdbaeclfheaiclfhiadc98fgdci0mbkkdnadTmbinaiaeRbb86bbaicefhiaecefheadcufgdmbkkabk:3eedudndnabciGTmbabhixekaecFeGc:b:c:ew2hldndnadcz9pmbabhixekabhiinaialBdxaialBdwaialBdlaialBdbaiczfhiadc9Wfgdcs0mbkkadcl6mbinaialBdbaiclfhiadc98fgdci0mbkkdnadTmbinaiae86bbaicefhiadcufgdmbkkabk9teiucbcbyd;81jjbgeabcrfc94GfgbBd;81jjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaikTeeucbabcbyd;81jjbge9Rcifc98GaefgbBd;81jjbdnabZbcztge9nmbabae9RcFFifcz4nb8Akk:;Deludndndnadch9pmbabaeSmdaeabadfgi9Rcbadcet9R0mekabaead;8qbbxekaeab7ciGhldndndnabae9pmbdnalTmbadhvabhixikdnabciGmbadhvabhixdkadTmiabaeRbb86bbadcufhvdnabcefgiciGmbaecefhexdkavTmiabaeRbe86beadc9:fhvdnabcdfgiciGmbaecdfhexdkavTmiabaeRbd86bdadc99fhvdnabcifgiciGmbaecifhexdkavTmiabaeRbi86biabclfhiaeclfheadc98fhvxekdnalmbdnaiciGTmbadTmlabadcufgifglaeaifRbb86bbdnalciGmbaihdxekaiTmlabadc9:fgifglaeaifRbb86bbdnalciGmbaihdxekaiTmlabadc99fgifglaeaifRbb86bbdnalciGmbaihdxekaiTmlabadc98fgdfaeadfRbb86bbkadcl6mbdnadc98fgocd4cefciGgiTmbaec98fhlabc98fhvinavadfaladfydbBdbadc98fhdaicufgimbkkaocx6mbaec9Wfhvabc9WfhoinaoadfgicxfavadfglcxfydbBdbaicwfalcwfydbBdbaiclfalclfydbBdbaialydbBdbadc9Wfgdci0mbkkadTmdadhidnadciGglTmbaecufhvabcufhoadhiinaoaifavaifRbb86bbaicufhialcufglmbkkadcl6mdaec98fhlabc98fhvinavaifgecifalaifgdcifRbb86bbaecdfadcdfRbb86bbaecefadcefRbb86bbaeadRbb86bbaic98fgimbxikkavcl6mbdnavc98fglcd4cefcrGgdTmbavadcdt9RhvinaiaeydbBdbaeclfheaiclfhiadcufgdmbkkalc36mbinaiaeydbBdbaiaeydlBdlaiaeydwBdwaiaeydxBdxaiaeydzBdzaiaeydCBdCaiaeydKBdKaiaeyd3Bd3aecafheaicafhiavc9Gfgvci0mbkkavTmbdndnavcrGgdmbavhlxekavc94GhlinaiaeRbb86bbaicefhiaecefheadcufgdmbkkavcw6mbinaiaeRbb86bbaiaeRbe86beaiaeRbd86bdaiaeRbi86biaiaeRbl86blaiaeRbv86bvaiaeRbo86boaiaeRbr86braicwfhiaecwfhealc94fglmbkkabkk:nedbcjwktFFuuFFuuFFuubbbbFFuFFFuFFFuFbbbbbbjZbbbbbbbbbbbbbbjZbbbbbbbbbbbbbbjZ86;nAZ86;nAZ86;nAZ86;nA:;86;nAZ86;nAZ86;nAZ86;nA:;86;nAZ86;nAZ86;nAZ86;nA:;bc;0wkxebbbdbbbjNbb'; // embed! wasm
var wasmpack = new Uint8Array([
32, 0, 65, 2, 1, 106, 34, 33, 3, 128, 11, 4, 13, 64, 6, 253, 10, 7, 15, 116, 127, 5, 8, 12, 40, 16, 19, 54, 20, 9, 27, 255, 113, 17, 42, 67,
24, 23, 146, 148, 18, 14, 22, 45, 70, 69, 56, 114, 101, 21, 25, 63, 75, 136, 108, 28, 118, 29, 73, 115,
]);
if (typeof WebAssembly !== 'object') {
return {
supported: false,
};
}
var instance;
var ready = WebAssembly.instantiate(unpack(wasm), {}).then(function (result) {
instance = result.instance;
instance.exports.__wasm_call_ctors();
});
function unpack(data) {
var result = new Uint8Array(data.length);
for (var i = 0; i < data.length; ++i) {
var ch = data.charCodeAt(i);
result[i] = ch > 96 ? ch - 97 : ch > 64 ? ch - 39 : ch + 4;
}
var write = 0;
for (var i = 0; i < data.length; ++i) {
result[write++] = result[i] < 60 ? wasmpack[result[i]] : (result[i] - 60) * 64 + result[++i];
}
return result.buffer.slice(0, write);
}
function assert(cond) {
if (!cond) {
throw new Error('Assertion failed');
}
}
function bytes(view) {
return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
}
var BOUNDS_SIZE = 48;
var MESHLET_SIZE = 16;
function extractMeshlet(buffers, index) {
var vertex_offset = buffers.meshlets[index * 4 + 0];
var triangle_offset = buffers.meshlets[index * 4 + 1];
var vertex_count = buffers.meshlets[index * 4 + 2];
var triangle_count = buffers.meshlets[index * 4 + 3];
return {
vertices: buffers.vertices.subarray(vertex_offset, vertex_offset + vertex_count),
triangles: buffers.triangles.subarray(triangle_offset, triangle_offset + triangle_count * 3),
};
}
function buildMeshlets(
fun,
indices,
vertex_positions,
vertex_count,
vertex_positions_stride,
max_vertices,
min_triangles,
max_triangles,
parama,
paramb
) {
var sbrk = instance.exports.sbrk;
var max_meshlets = instance.exports.meshopt_buildMeshletsBound(indices.length, max_vertices, min_triangles);
// allocate memory
var meshletsp = sbrk(max_meshlets * MESHLET_SIZE);
var meshlet_verticesp = sbrk(indices.length * 4);
var meshlet_trianglesp = sbrk(indices.length);
var indicesp = sbrk(indices.byteLength);
var verticesp = sbrk(vertex_positions.byteLength);
// copy input data to wasm memory
var heap = new Uint8Array(instance.exports.memory.buffer);
heap.set(bytes(indices), indicesp);
heap.set(bytes(vertex_positions), verticesp);
var count = fun(
meshletsp,
meshlet_verticesp,
meshlet_trianglesp,
indicesp,
indices.length,
verticesp,
vertex_count,
vertex_positions_stride,
max_vertices,
min_triangles,
max_triangles,
parama,
paramb
);
// heap might (will?) have grown -> re-acquire
heap = new Uint8Array(instance.exports.memory.buffer);
var meshletBytes = heap.subarray(meshletsp, meshletsp + count * MESHLET_SIZE);
var meshlets = new Uint32Array(meshletBytes.buffer, meshletBytes.byteOffset, meshletBytes.byteLength / 4).slice();
for (var i = 0; i < count; ++i) {
var vertex_offset = meshlets[i * 4 + 0];
var triangle_offset = meshlets[i * 4 + 1];
var vertex_count = meshlets[i * 4 + 2];
var triangle_count = meshlets[i * 4 + 3];
instance.exports.meshopt_optimizeMeshlet(
meshlet_verticesp + vertex_offset * 4,
meshlet_trianglesp + triangle_offset,
triangle_count,
vertex_count
);
}
var last_vertex_offset = meshlets[(count - 1) * 4 + 0];
var last_triangle_offset = meshlets[(count - 1) * 4 + 1];
var last_vertex_count = meshlets[(count - 1) * 4 + 2];
var last_triangle_count = meshlets[(count - 1) * 4 + 3];
var used_vertices = last_vertex_offset + last_vertex_count;
var used_triangles = last_triangle_offset + last_triangle_count * 3;
var result = {
meshlets: meshlets,
vertices: new Uint32Array(heap.buffer, meshlet_verticesp, used_vertices).slice(),
triangles: new Uint8Array(heap.buffer, meshlet_trianglesp, used_triangles * 3).slice(),
meshletCount: count,
};
// reset memory
sbrk(meshletsp - sbrk(0));
return result;
}
function extractBounds(boundsp) {
var bounds_floats = new Float32Array(instance.exports.memory.buffer, boundsp, BOUNDS_SIZE / 4);
// see meshopt_Bounds in meshoptimizer.h for layout
return {
centerX: bounds_floats[0],
centerY: bounds_floats[1],
centerZ: bounds_floats[2],
radius: bounds_floats[3],
coneApexX: bounds_floats[4],
coneApexY: bounds_floats[5],
coneApexZ: bounds_floats[6],
coneAxisX: bounds_floats[7],
coneAxisY: bounds_floats[8],
coneAxisZ: bounds_floats[9],
coneCutoff: bounds_floats[10],
};
}
function computeMeshletBounds(buffers, vertex_positions, vertex_count, vertex_positions_stride) {
var sbrk = instance.exports.sbrk;
var results = [];
// allocate memory that's constant for all meshlets
var verticesp = sbrk(vertex_positions.byteLength);
var meshlet_verticesp = sbrk(buffers.vertices.byteLength);
var meshlet_trianglesp = sbrk(buffers.triangles.byteLength);
var resultp = sbrk(BOUNDS_SIZE);
// copy vertices to wasm memory
var heap = new Uint8Array(instance.exports.memory.buffer);
heap.set(bytes(vertex_positions), verticesp);
heap.set(bytes(buffers.vertices), meshlet_verticesp);
heap.set(bytes(buffers.triangles), meshlet_trianglesp);
for (var i = 0; i < buffers.meshletCount; ++i) {
var vertex_offset = buffers.meshlets[i * 4 + 0];
var triangle_offset = buffers.meshlets[i * 4 + 0 + 1];
var triangle_count = buffers.meshlets[i * 4 + 0 + 3];
instance.exports.meshopt_computeMeshletBounds(
resultp,
meshlet_verticesp + vertex_offset * 4,
meshlet_trianglesp + triangle_offset,
triangle_count,
verticesp,
vertex_count,
vertex_positions_stride
);
results.push(extractBounds(resultp));
}
// reset memory
sbrk(verticesp - sbrk(0));
return results;
}
function computeClusterBounds(indices, vertex_positions, vertex_count, vertex_positions_stride) {
var sbrk = instance.exports.sbrk;
// allocate memory
var resultp = sbrk(BOUNDS_SIZE);
var indicesp = sbrk(indices.byteLength);
var verticesp = sbrk(vertex_positions.byteLength);
// copy input data to wasm memory
var heap = new Uint8Array(instance.exports.memory.buffer);
heap.set(bytes(indices), indicesp);
heap.set(bytes(vertex_positions), verticesp);
instance.exports.meshopt_computeClusterBounds(resultp, indicesp, indices.length, verticesp, vertex_count, vertex_positions_stride);
var result = extractBounds(resultp);
// reset memory
sbrk(resultp - sbrk(0));
return result;
}
function computeSphereBounds(positions, count, positions_stride, radii, radii_stride) {
var sbrk = instance.exports.sbrk;
// allocate memory
var resultp = sbrk(BOUNDS_SIZE);
var positionsp = sbrk(positions.byteLength);
var radiip = radii ? sbrk(radii.byteLength) : 0;
// copy input data to wasm memory
var heap = new Uint8Array(instance.exports.memory.buffer);
heap.set(bytes(positions), positionsp);
if (radii) {
heap.set(bytes(radii), radiip);
}
instance.exports.meshopt_computeSphereBounds(resultp, positionsp, count, positions_stride, radiip, radii ? radii_stride : 0);
var result = extractBounds(resultp);
// reset memory
sbrk(resultp - sbrk(0));
return result;
}
return {
ready: ready,
supported: true,
buildMeshlets: function (indices, vertex_positions, vertex_positions_stride, max_vertices, max_triangles, cone_weight) {
assert(indices.length % 3 == 0);
assert(vertex_positions instanceof Float32Array);
assert(vertex_positions.length % vertex_positions_stride == 0);
assert(vertex_positions_stride >= 3);
assert(max_vertices > 0 && max_vertices <= 256);
assert(max_triangles >= 1 && max_triangles <= 512);
cone_weight = cone_weight || 0.0;
var indices32 = indices.BYTES_PER_ELEMENT == 4 ? indices : new Uint32Array(indices);
return buildMeshlets(
instance.exports.meshopt_buildMeshletsFlex,
indices32,
vertex_positions,
vertex_positions.length / vertex_positions_stride,
vertex_positions_stride * 4,
max_vertices,
max_triangles,
max_triangles,
cone_weight,
0.0
);
},
buildMeshletsFlex: function (
indices,
vertex_positions,
vertex_positions_stride,
max_vertices,
min_triangles,
max_triangles,
cone_weight,
split_factor
) {
assert(indices.length % 3 == 0);
assert(vertex_positions instanceof Float32Array);
assert(vertex_positions.length % vertex_positions_stride == 0);
assert(vertex_positions_stride >= 3);
assert(max_vertices > 0 && max_vertices <= 256);
assert(min_triangles >= 1 && max_triangles <= 512);
assert(min_triangles <= max_triangles);
cone_weight = cone_weight || 0.0;
split_factor = split_factor || 0.0;
var indices32 = indices.BYTES_PER_ELEMENT == 4 ? indices : new Uint32Array(indices);
return buildMeshlets(
instance.exports.meshopt_buildMeshletsFlex,
indices32,
vertex_positions,
vertex_positions.length / vertex_positions_stride,
vertex_positions_stride * 4,
max_vertices,
min_triangles,
max_triangles,
cone_weight,
split_factor
);
},
buildMeshletsSpatial: function (indices, vertex_positions, vertex_positions_stride, max_vertices, min_triangles, max_triangles, fill_weight) {
assert(indices.length % 3 == 0);
assert(vertex_positions instanceof Float32Array);
assert(vertex_positions.length % vertex_positions_stride == 0);
assert(vertex_positions_stride >= 3);
assert(max_vertices > 0 && max_vertices <= 256);
assert(min_triangles >= 1 && max_triangles <= 512);
assert(min_triangles <= max_triangles);
fill_weight = fill_weight || 0.0;
var indices32 = indices.BYTES_PER_ELEMENT == 4 ? indices : new Uint32Array(indices);
return buildMeshlets(
instance.exports.meshopt_buildMeshletsSpatial,
indices32,
vertex_positions,
vertex_positions.length / vertex_positions_stride,
vertex_positions_stride * 4,
max_vertices,
min_triangles,
max_triangles,
fill_weight
);
},
extractMeshlet: function (buffers, index) {
assert(index >= 0 && index < buffers.meshletCount);
return extractMeshlet(buffers, index);
},
computeClusterBounds: function (indices, vertex_positions, vertex_positions_stride) {
assert(indices.length % 3 == 0);
assert(indices.length / 3 <= 512);
assert(vertex_positions instanceof Float32Array);
assert(vertex_positions.length % vertex_positions_stride == 0);
assert(vertex_positions_stride >= 3);
var indices32 = indices.BYTES_PER_ELEMENT == 4 ? indices : new Uint32Array(indices);
return computeClusterBounds(indices32, vertex_positions, vertex_positions.length / vertex_positions_stride, vertex_positions_stride * 4);
},
computeMeshletBounds: function (buffers, vertex_positions, vertex_positions_stride) {
assert(buffers.meshletCount != 0);
assert(vertex_positions instanceof Float32Array);
assert(vertex_positions.length % vertex_positions_stride == 0);
assert(vertex_positions_stride >= 3);
return computeMeshletBounds(buffers, vertex_positions, vertex_positions.length / vertex_positions_stride, vertex_positions_stride * 4);
},
computeSphereBounds: function (positions, positions_stride, radii, radii_stride) {
assert(positions instanceof Float32Array);
assert(positions.length % positions_stride == 0);
assert(positions_stride >= 3);
assert(!radii || radii instanceof Float32Array);
assert(!radii || radii.length % radii_stride == 0);
assert(!radii || radii_stride >= 1);
assert(!radii || positions.length / positions_stride == radii.length / radii_stride);
radii_stride = radii_stride || 0;
return computeSphereBounds(positions, positions.length / positions_stride, positions_stride * 4, radii, radii_stride * 4);
},
};
})();
export { MeshoptClusterizer };
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
js/meshopt_clusterizer.test.js | JavaScript | import assert from 'assert/strict';
import { MeshoptClusterizer as clusterizer } from './meshopt_clusterizer.js';
process.on('unhandledRejection', (error) => {
console.log('unhandledRejection', error);
process.exit(1);
});
const cubeWithNormals = {
vertices: new Float32Array([
// n = (0, 0, 1)
-1.0, -1.0, 1.0, 0.0, 0.0, 1.0, 1.0, -1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, -1.0, 1.0, 1.0, 0.0, 0.0, 1.0,
// n = (0, 0, -1)
-1.0, 1.0, -1.0, 0.0, 0.0, -1.0, 1.0, 1.0, -1.0, 0.0, 0.0, -1.0, 1.0, -1.0, -1.0, 0.0, 0.0, -1.0, -1.0, -1.0, -1.0, 0.0, 0.0, -1.0,
// n = (1, 0, 0)
1.0, -1.0, -1.0, 1.0, 0.0, 0.0, 1.0, 1.0, -1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, -1.0, 1.0, 1.0, 0.0, 0.0,
// n = (-1, 0, 0)
-1.0, -1.0, 1.0, -1.0, 0.0, 0.0, -1.0, 1.0, 1.0, -1.0, 0.0, 0.0, -1.0, 1.0, -1.0, -1.0, 0.0, 0.0, -1.0, -1.0, -1.0, -1.0, 0.0, 0.0,
// n = (0, 1, 0)
1.0, 1.0, -1.0, 0.0, 1.0, 0.0, -1.0, 1.0, -1.0, 0.0, 1.0, 0.0, -1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0,
// n = (0, -1, 0)
1.0, -1.0, 1.0, 0.0, -1.0, 0.0, -1.0, -1.0, 1.0, 0.0, -1.0, 0.0, -1.0, -1.0, -1.0, 0.0, -1.0, 0.0, 1.0, -1.0, -1.0, 0.0, -1.0, 0.0,
]),
indices: new Uint32Array([
// n = (0, 0, 1)
0, 1, 2, 2, 3, 0,
// n = (0, 0, -1)
4, 5, 6, 6, 7, 4,
// n = (1, 0, 0)
8, 9, 10, 10, 11, 8,
// n = (-1, 0, 0)
12, 13, 14, 14, 15, 12,
// n = (0, 1, 0)
16, 17, 18, 18, 19, 16,
// n = (0, -1, 0)
20, 21, 22, 22, 23, 20,
]),
vertexStride: 6, // in floats
};
const tests = {
buildMeshlets: function () {
const maxVertices = 4;
const buffers = clusterizer.buildMeshlets(cubeWithNormals.indices, cubeWithNormals.vertices, cubeWithNormals.vertexStride, maxVertices, 512);
const expectedVertices = [
new Uint32Array([6, 7, 4, 5]),
new Uint32Array([14, 15, 12, 13]),
new Uint32Array([2, 3, 0, 1]),
new Uint32Array([20, 21, 22, 23]),
new Uint32Array([10, 11, 8, 9]),
new Uint32Array([18, 19, 16, 17]),
];
const expectedTriangles = new Uint8Array([0, 1, 2, 2, 3, 0]);
assert.equal(buffers.meshletCount, 6);
for (let i = 0; i < buffers.meshletCount; ++i) {
const m = clusterizer.extractMeshlet(buffers, i);
assert.deepStrictEqual(m.vertices, expectedVertices[i]);
assert.deepStrictEqual(m.triangles, expectedTriangles);
}
},
computeClusterBounds: function () {
for (let i = 0; i < 6; ++i) {
const indexOffset = i * 6;
const normalOffset = i * 4 * cubeWithNormals.vertexStride;
const bounds = clusterizer.computeClusterBounds(
cubeWithNormals.indices.subarray(indexOffset, 6 + indexOffset),
cubeWithNormals.vertices,
cubeWithNormals.vertexStride
);
assert.deepStrictEqual(
new Int32Array([bounds.coneAxisX, bounds.coneAxisY, bounds.coneAxisZ]),
new Int32Array(cubeWithNormals.vertices.subarray(3 + normalOffset, 6 + normalOffset))
);
}
},
computeMeshletBounds: function () {
const maxVertices = 4;
const buffers = clusterizer.buildMeshlets(cubeWithNormals.indices, cubeWithNormals.vertices, cubeWithNormals.vertexStride, maxVertices, 512);
const expectedNormals = [
new Int32Array([0, 0, -1]),
new Int32Array([-1, 0, 0]),
new Int32Array([0, 0, 1]),
new Int32Array([0, -1, 0]),
new Int32Array([1, 0, 0]),
new Int32Array([0, 1, 0]),
];
const bounds = clusterizer.computeMeshletBounds(buffers, cubeWithNormals.vertices, cubeWithNormals.vertexStride);
assert(bounds.length === 6);
assert(bounds.length === buffers.meshletCount);
bounds.forEach((b, i) => {
const normal = new Int32Array([b.coneAxisX, b.coneAxisY, b.coneAxisZ]);
assert.deepStrictEqual(normal, expectedNormals[i]);
});
},
computeSphereBounds: function () {
// positions without per-point radii (tetrahedron)
const positions = new Float32Array([0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1]);
const bp = clusterizer.computeSphereBounds(positions, 3);
assert(Math.abs(bp.centerX - 0.5) < 1e-3);
assert(Math.abs(bp.centerY - 0.5) < 1e-3);
assert(Math.abs(bp.centerZ - 0.5) < 1e-3);
assert(bp.radius < 0.87);
// use 4th float of each element as radius (last point has radius=3 enveloping others)
const radii = new Float32Array([0, 1, 2, 3]);
const br = clusterizer.computeSphereBounds(positions, 3, radii, 1);
assert(Math.abs(br.centerX - 1.0) < 1e-3);
assert(Math.abs(br.centerY - 0.0) < 1e-3);
assert(Math.abs(br.centerZ - 1.0) < 1e-3);
assert(Math.abs(br.radius - 3.0) < 1e-3);
},
};
clusterizer.ready.then(() => {
var count = 0;
for (var key in tests) {
tests[key]();
count++;
}
console.log(count, 'tests passed');
});
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
js/meshopt_decoder.cjs | JavaScript | // This file is part of meshoptimizer library and is distributed under the terms of MIT License.
// Copyright (C) 2016-2026, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
var MeshoptDecoder = (function () {
// Built with clang version 19.1.5-wasi-sdk
// Built from meshoptimizer 1.0
var wasm_base =
'b9H79Tebbbe8Fv9Gbb9Gvuuuuueu9Giuuub9Geueu9Giuuueuixkbeeeddddillviebeoweuec:W:Odkr;Neqo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9KW9J9V9KW9wWVtW949c919M9MWVbeY9TW79O9V9Wt9F9KW9J9V9KW69U9KW949c919M9MWVbdE9TW79O9V9Wt9F9KW9J9V9KW69U9KW949tWG91W9U9JWbiL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9p9JtblK9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9r919HtbvL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVT949WboY9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVJ9V29VVbrl79IV9Rbwq;lZkdbk;jYi5ud9:du8Jjjjjbcj;kb9Rgv8Kjjjjbc9:hodnalTmbcuhoaiRbbgrc;WeGc:Ge9hmbarcsGgwce0mbc9:hoalcufadcd4cbawEgDadfgrcKcaawEgqaraq0Egk6mbaicefhxcj;abad9Uc;WFbGcjdadca0EhmaialfgPar9Rgoadfhsavaoadz:jjjjbgzceVhHcbhOdndninaeaO9nmeaPax9RaD6mdamaeaO9RaOamfgoae6EgAcsfglc9WGhCabaOad2fhXaAcethQaxaDfhiaOaeaoaeao6E9RhLalcl4cifcd4hKazcj;cbfaAfhYcbh8AazcjdfhEaHh3incbhodnawTmbaxa8Acd4fRbbhokaocFeGh5cbh8Eazcj;cbfhqinaih8Fdndndndna5a8Ecet4ciGgoc9:fPdebdkaPa8F9RaA6mrazcj;cbfa8EaA2fa8FaAz:jjjjb8Aa8FaAfhixdkazcj;cbfa8EaA2fcbaAz:kjjjb8Aa8FhixekaPa8F9RaK6mva8FaKfhidnaCTmbaPai9RcK6mbaocdtc:q1jjbfcj1jjbawEhaczhrcbhlinargoc9Wfghaqfhrdndndndndndnaaa8Fahco4fRbbalcoG4ciGcdtfydbPDbedvivvvlvkar9cb83bbarcwf9cb83bbxlkarcbaiRbdai8Xbb9c:c:qj:bw9:9c:q;c1:I1e:d9c:b:c:e1z9:gg9cjjjjjz:dg8J9qE86bbaqaofgrcGfag9c8F1:NghcKtc8F91aicdfa8J9c8N1:Nfg8KRbbG86bbarcVfcba8KahcjeGcr4fghRbbag9cjjjjjl:dg8J9qE86bbarc7fcbaha8J9c8L1:NfghRbbag9cjjjjjd:dg8J9qE86bbarctfcbaha8J9c8K1:NfghRbbag9cjjjjje:dg8J9qE86bbarc91fcbaha8J9c8J1:NfghRbbag9cjjjj;ab:dg8J9qE86bbarc4fcbaha8J9cg1:NfghRbbag9cjjjja:dg8J9qE86bbarc93fcbaha8J9ch1:NfghRbbag9cjjjjz:dgg9qE86bbarc94fcbahag9ca1:NfghRbbai8Xbe9c:c:qj:bw9:9c:q;c1:I1e:d9c:b:c:e1z9:gg9cjjjjjz:dg8J9qE86bbarc95fag9c8F1:NgicKtc8F91aha8J9c8N1:NfghRbbG86bbarc96fcbahaicjeGcr4fgiRbbag9cjjjjjl:dg8J9qE86bbarc97fcbaia8J9c8L1:NfgiRbbag9cjjjjjd:dg8J9qE86bbarc98fcbaia8J9c8K1:NfgiRbbag9cjjjjje:dg8J9qE86bbarc99fcbaia8J9c8J1:NfgiRbbag9cjjjj;ab:dg8J9qE86bbarc9:fcbaia8J9cg1:NfgiRbbag9cjjjja:dg8J9qE86bbarcufcbaia8J9ch1:NfgiRbbag9cjjjjz:dgg9qE86bbaiag9ca1:NfhixikaraiRblaiRbbghco4g8Ka8KciSg8KE86bbaqaofgrcGfaiclfa8Kfg8KRbbahcl4ciGg8La8LciSg8LE86bbarcVfa8Ka8Lfg8KRbbahcd4ciGg8La8LciSg8LE86bbarc7fa8Ka8Lfg8KRbbahciGghahciSghE86bbarctfa8Kahfg8KRbbaiRbeghco4g8La8LciSg8LE86bbarc91fa8Ka8Lfg8KRbbahcl4ciGg8La8LciSg8LE86bbarc4fa8Ka8Lfg8KRbbahcd4ciGg8La8LciSg8LE86bbarc93fa8Ka8Lfg8KRbbahciGghahciSghE86bbarc94fa8Kahfg8KRbbaiRbdghco4g8La8LciSg8LE86bbarc95fa8Ka8Lfg8KRbbahcl4ciGg8La8LciSg8LE86bbarc96fa8Ka8Lfg8KRbbahcd4ciGg8La8LciSg8LE86bbarc97fa8Ka8Lfg8KRbbahciGghahciSghE86bbarc98fa8KahfghRbbaiRbigico4g8Ka8KciSg8KE86bbarc99faha8KfghRbbaicl4ciGg8Ka8KciSg8KE86bbarc9:faha8KfghRbbaicd4ciGg8Ka8KciSg8KE86bbarcufaha8KfgrRbbaiciGgiaiciSgiE86bbaraifhixdkaraiRbwaiRbbghcl4g8Ka8KcsSg8KE86bbaqaofgrcGfaicwfa8Kfg8KRbbahcsGghahcsSghE86bbarcVfa8KahfghRbbaiRbeg8Kcl4g8La8LcsSg8LE86bbarc7faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarctfaha8KfghRbbaiRbdg8Kcl4g8La8LcsSg8LE86bbarc91faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc4faha8KfghRbbaiRbig8Kcl4g8La8LcsSg8LE86bbarc93faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc94faha8KfghRbbaiRblg8Kcl4g8La8LcsSg8LE86bbarc95faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc96faha8KfghRbbaiRbvg8Kcl4g8La8LcsSg8LE86bbarc97faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc98faha8KfghRbbaiRbog8Kcl4g8La8LcsSg8LE86bbarc99faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc9:faha8KfghRbbaiRbrgicl4g8Ka8KcsSg8KE86bbarcufaha8KfgrRbbaicsGgiaicsSgiE86bbaraifhixekarai8Pbb83bbarcwfaicwf8Pbb83bbaiczfhikdnaoaC9pmbalcdfhlaoczfhraPai9RcL0mekkaoaC6moaimexokaCmva8FTmvkaqaAfhqa8Ecefg8Ecl9hmbkdndndndnawTmbasa8Acd4fRbbgociGPlbedrbkaATmdaza8Afh8Fazcj;cbfhhcbh8EaEhaina8FRbbhraahocbhlinaoahalfRbbgqce4cbaqceG9R7arfgr86bbaoadfhoaAalcefgl9hmbkaacefhaa8Fcefh8FahaAfhha8Ecefg8Ecl9hmbxikkaATmeaza8Afhaazcj;cbfhhcbhoceh8EaYh8FinaEaofhlaa8Vbbhrcbhoinala8FaofRbbcwtahaofRbbgqVc;:FiGce4cbaqceG9R7arfgr87bbaladfhlaLaocefgofmbka8FaQfh8FcdhoaacdfhaahaQfhha8EceGhlcbh8EalmbxdkkaATmbcbaocl49Rh8Eaza8AfRbbhqcwhoa3hlinalRbbaotaqVhqalcefhlaocwfgoca9hmbkcbhhaEh8FaYhainazcj;cbfahfRbbhrcwhoaahlinalRbbaotarVhralaAfhlaocwfgoca9hmbkara8E93aq7hqcbhoa8Fhlinalaqao486bbalcefhlaocwfgoca9hmbka8Fadfh8FaacefhaahcefghaA9hmbkkaEclfhEa3clfh3a8Aclfg8Aad6mbkaXazcjdfaAad2z:jjjjb8AazazcjdfaAcufad2fadz:jjjjb8AaAaOfhOaihxaimbkc9:hoxdkcbc99aPax9RakSEhoxekc9:hokavcj;kbf8Kjjjjbaok:XseHu8Jjjjjbc;ae9Rgv8Kjjjjbc9:hodnaeci9UgrcHfal0mbcuhoaiRbbgwc;WeGc;Ge9hmbawcsGgDce0mbavc;abfcFecjez:kjjjb8AavcUf9cu83ibavc8Wf9cu83ibavcyf9cu83ibavcaf9cu83ibavcKf9cu83ibavczf9cu83ibav9cu83iwav9cu83ibaialfc9WfhqaicefgwarfhldnaeTmbcmcsaDceSEhkcbhxcbhmcbhrcbhicbhoindnalaq9nmbc9:hoxikdndnawRbbgDc;Ve0mbavc;abfaoaDcu7gPcl4fcsGcitfgsydlhzasydbhHdndnaDcsGgsak9pmbavaiaPfcsGcdtfydbaxasEhDaxasTgOfhxxekdndnascsSmbcehOasc987asamffcefhDxekalcefhDal8SbbgscFeGhPdndnascu9mmbaDhlxekalcvfhlaPcFbGhPcrhsdninaD8SbbgOcFbGastaPVhPaOcu9kmeaDcefhDascrfgsc8J9hmbxdkkaDcefhlkcehOaPce4cbaPceG9R7amfhDkaDhmkavc;abfaocitfgsaDBdbasazBdlavaicdtfaDBdbavc;abfaocefcsGcitfgsaHBdbasaDBdlaocdfhoaOaifhidnadcd9hmbabarcetfgsaH87ebasclfaD87ebascdfaz87ebxdkabarcdtfgsaHBdbascwfaDBdbasclfazBdbxekdnaDcpe0mbaxcefgOavaiaqaDcsGfRbbgscl49RcsGcdtfydbascz6gPEhDavaias9RcsGcdtfydbaOaPfgzascsGgOEhsaOThOdndnadcd9hmbabarcetfgHax87ebaHclfas87ebaHcdfaD87ebxekabarcdtfgHaxBdbaHcwfasBdbaHclfaDBdbkavaicdtfaxBdbavc;abfaocitfgHaDBdbaHaxBdlavaicefgicsGcdtfaDBdbavc;abfaocefcsGcitfgHasBdbaHaDBdlavaiaPfgicsGcdtfasBdbavc;abfaocdfcsGcitfgDaxBdbaDasBdlaocifhoaiaOfhiazaOfhxxekaxcbalRbbgHEgAaDc;:eSgDfhzaHcsGhCaHcl4hXdndnaHcs0mbazcefhOxekazhOavaiaX9RcsGcdtfydbhzkdndnaCmbaOcefhxxekaOhxavaiaH9RcsGcdtfydbhOkdndnaDTmbalcefhDxekalcdfhDal8SbegPcFeGhsdnaPcu9kmbalcofhAascFbGhscrhldninaD8SbbgPcFbGaltasVhsaPcu9kmeaDcefhDalcrfglc8J9hmbkaAhDxekaDcefhDkasce4cbasceG9R7amfgmhAkdndnaXcsSmbaDhsxekaDcefhsaD8SbbglcFeGhPdnalcu9kmbaDcvfhzaPcFbGhPcrhldninas8SbbgDcFbGaltaPVhPaDcu9kmeascefhsalcrfglc8J9hmbkazhsxekascefhskaPce4cbaPceG9R7amfgmhzkdndnaCcsSmbashlxekascefhlas8SbbgDcFeGhPdnaDcu9kmbascvfhOaPcFbGhPcrhDdninal8SbbgscFbGaDtaPVhPascu9kmealcefhlaDcrfgDc8J9hmbkaOhlxekalcefhlkaPce4cbaPceG9R7amfgmhOkdndnadcd9hmbabarcetfgDaA87ebaDclfaO87ebaDcdfaz87ebxekabarcdtfgDaABdbaDcwfaOBdbaDclfazBdbkavc;abfaocitfgDazBdbaDaABdlavaicdtfaABdbavc;abfaocefcsGcitfgDaOBdbaDazBdlavaicefgicsGcdtfazBdbavc;abfaocdfcsGcitfgDaABdbaDaOBdlavaiaHcz6aXcsSVfgicsGcdtfaOBdbaiaCTaCcsSVfhiaocifhokawcefhwaocsGhoaicsGhiarcifgrae6mbkkcbc99alaqSEhokavc;aef8Kjjjjbaok:clevu8Jjjjjbcz9Rhvdnaecvfal9nmbc9:skdnaiRbbc;:eGc;qeSmbcuskav9cb83iwaicefhoaialfc98fhrdnaeTmbdnadcdSmbcbhwindnaoar6mbc9:skaocefhlao8SbbgicFeGhddndnaicu9mmbalhoxekaocvfhoadcFbGhdcrhidninal8SbbgDcFbGaitadVhdaDcu9kmealcefhlaicrfgic8J9hmbxdkkalcefhokabawcdtfadc8Etc8F91adcd47avcwfadceGcdtVglydbfgiBdbalaiBdbawcefgwae9hmbxdkkcbhwindnaoar6mbc9:skaocefhlao8SbbgicFeGhddndnaicu9mmbalhoxekaocvfhoadcFbGhdcrhidninal8SbbgDcFbGaitadVhdaDcu9kmealcefhlaicrfgic8J9hmbxdkkalcefhokabawcetfadc8Etc8F91adcd47avcwfadceGcdtVglydbfgi87ebalaiBdbawcefgwae9hmbkkcbc99aoarSEk:Lvoeue99dud99eud99dndnadcl9hmbaeTmeindndnabcdfgd8Sbb:Yab8Sbbgi:Ygl:l:tabcefgv8Sbbgo:Ygr:l:tgwJbb;:9cawawNJbbbbawawJbbbb9GgDEgq:mgkaqaicb9iEalMgwawNakaqaocb9iEarMgqaqNMM:r:vglNJbbbZJbbb:;aDEMgr:lJbbb9p9DTmbar:Ohixekcjjjj94hikadai86bbdndnaqalNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkavad86bbdndnawalNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohdxekcjjjj94hdkabad86bbabclfhbaecufgembxdkkaeTmbindndnabclfgd8Ueb:Yab8Uebgi:Ygl:l:tabcdfgv8Uebgo:Ygr:l:tgwJb;:FSawawNJbbbbawawJbbbb9GgDEgq:mgkaqaicb9iEalMgwawNakaqaocb9iEarMgqaqNMM:r:vglNJbbbZJbbb:;aDEMgr:lJbbb9p9DTmbar:Ohixekcjjjj94hikadai87ebdndnaqalNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkavad87ebdndnawalNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohdxekcjjjj94hdkabad87ebabcwfhbaecufgembkkk::ioiue99dud99dud99dnaeTmbcbhiabhlindndnal8Uebgv:YgoJ:ji:1Salcof8UebgrciVgw:Y:vgDNJbbbZJbbb:;avcu9kEMgq:lJbbb9p9DTmbaq:Ohkxekcjjjj94hkkalclf8Uebhvalcdf8UebhxabaiarcefciGfcetfak87ebdndnax:YgqaDNJbbbZJbbb:;axcu9kEMgm:lJbbb9p9DTmbam:Ohxxekcjjjj94hxkabaiarciGfgkcd7cetfax87ebdndnav:YgmaDNJbbbZJbbb:;avcu9kEMgP:lJbbb9p9DTmbaP:Ohvxekcjjjj94hvkabaiarcufciGfcetfav87ebdndnawaw2:ZgPaPMaoaoN:taqaqN:tamamN:tgoJbbbbaoJbbbb9GE:raDNJbbbZMgD:lJbbb9p9DTmbaD:Ohrxekcjjjj94hrkabakcetfar87ebalcwfhlaiclfhiaecufgembkkk9mbdnadcd4ae2gdTmbinababydbgecwtcw91:Yaece91cjjj98Gcjjj;8if::NUdbabclfhbadcufgdmbkkk:Tvirud99eudndnadcl9hmbaeTmeindndnabRbbgiabcefgl8Sbbgvabcdfgo8Sbbgrf9R:YJbbuJabcifgwRbbgdce4adVgDcd4aDVgDcl4aDVgD:Z:vgqNJbbbZMgk:lJbbb9p9DTmbak:Ohxxekcjjjj94hxkaoax86bbdndnaraif:YaqNJbbbZMgk:lJbbb9p9DTmbak:Ohoxekcjjjj94hokalao86bbdndnavaifar9R:YaqNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikabai86bbdndnaDadcetGadceGV:ZaqNJbbbZMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkawad86bbabclfhbaecufgembxdkkaeTmbindndnab8Vebgiabcdfgl8Uebgvabclfgo8Uebgrf9R:YJbFu9habcofgw8Vebgdce4adVgDcd4aDVgDcl4aDVgDcw4aDVgD:Z:vgqNJbbbZMgk:lJbbb9p9DTmbak:Ohxxekcjjjj94hxkaoax87ebdndnaraif:YaqNJbbbZMgk:lJbbb9p9DTmbak:Ohoxekcjjjj94hokalao87ebdndnavaifar9R:YaqNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikabai87ebdndnaDadcetGadceGV:ZaqNJbbbZMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkawad87ebabcwfhbaecufgembkkk9teiucbcbyd:K1jjbgeabcifc98GfgbBd:K1jjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaik;teeeudndnaeabVciGTmbabhixekdndnadcz9pmbabhixekabhiinaiaeydbBdbaiaeydlBdlaiaeydwBdwaiaeydxBdxaeczfheaiczfhiadc9Wfgdcs0mbkkadcl6mbinaiaeydbBdbaeclfheaiclfhiadc98fgdci0mbkkdnadTmbinaiaeRbb86bbaicefhiaecefheadcufgdmbkkabk:3eedudndnabciGTmbabhixekaecFeGc:b:c:ew2hldndnadcz9pmbabhixekabhiinaialBdxaialBdwaialBdlaialBdbaiczfhiadc9Wfgdcs0mbkkadcl6mbinaialBdbaiclfhiadc98fgdci0mbkkdnadTmbinaiae86bbaicefhiadcufgdmbkkabkk81dbcjwk8Kbbbbdbbblbbbwbbbbbbbebbbdbbblbbbwbbbbc:Kwkl8WNbb'; // embed! base
var wasm_simd =
'b9H79TebbbeKl9Gbb9Gvuuuuueu9Giuuub9Geueuixkbbebeeddddilve9Weeeviebeoweuec:q:6dkr;Neqo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9KW9J9V9KW9wWVtW949c919M9MWVbdY9TW79O9V9Wt9F9KW9J9V9KW69U9KW949c919M9MWVblE9TW79O9V9Wt9F9KW9J9V9KW69U9KW949tWG91W9U9JWbvL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9p9JtboK9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9r919HtbrL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVT949WbwY9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVJ9V29VVbDl79IV9Rbqq:Ctklbzik9:evu8Jjjjjbcz9Rhbcbheincbhdcbhiinabcwfadfaicjuaead4ceGglE86bbaialfhiadcefgdcw9hmbkaec:q:yjjbfai86bbaecitc:q1jjbfab8Piw83ibaecefgecjd9hmbkk:183lYud97dur978Jjjjjbcj;kb9Rgv8Kjjjjbc9:hodnalTmbcuhoaiRbbgrc;WeGc:Ge9hmbarcsGgwce0mbc9:hoalcufadcd4cbawEgDadfgrcKcaawEgqaraq0Egk6mbaicefhxavaialfgmar9Rgoad;8qbbcj;abad9Uc;WFbGcjdadca0EhPdndndnadTmbaoadfhscbhzinaeaz9nmdamax9RaD6miabazad2fhHaxaDfhOaPaeaz9RazaPfae6EgAcsfgocl4cifcd4hCavcj;cbfaoc9WGgXcetfhQavcj;cbfaXci2fhLavcj;cbfaXfhKcbhYaoc;ab6h8AincbhodnawTmbaxaYcd4fRbbhokaocFeGhEcbh3avcj;cbfh5indndndndnaEa3cet4ciGgoc9:fPdebdkamaO9RaX6mwavcj;cbfa3aX2faOaX;8qbbaOaAfhOxdkavcj;cbfa3aX2fcbaX;8kbxekamaO9RaC6moaoclVcbawEhraOaCfhocbhidna8Ambamao9Rc;Gb6mbcbhlina5alfhidndndndndndnaOalco4fRbbgqciGarfPDbedibledibkaipxbbbbbbbbbbbbbbbbpklbxlkaiaopbblaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLg8Ecdp:mea8EpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9og8Fpxiiiiiiiiiiiiiiiip8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngacitc:q1jjbfpbibaac:q:yjjbfRbbgapsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Nghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spklbaaaoclffahc:q:yjjbfRbbfhoxikaiaopbbwaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9og8Fpxssssssssssssssssp8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngacitc:q1jjbfpbibaac:q:yjjbfRbbgapsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Nghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spklbaaaocwffahc:q:yjjbfRbbfhoxdkaiaopbbbpklbaoczfhoxekaiaopbbdaoRbbgacitc:q1jjbfpbibaac:q:yjjbfRbbgapsaoRbeghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPpklbaaaocdffahc:q:yjjbfRbbfhokdndndndndndnaqcd4ciGarfPDbedibledibkaiczfpxbbbbbbbbbbbbbbbbpklbxlkaiczfaopbblaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLg8Ecdp:mea8EpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9og8Fpxiiiiiiiiiiiiiiiip8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngacitc:q1jjbfpbibaac:q:yjjbfRbbgapsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Nghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spklbaaaoclffahc:q:yjjbfRbbfhoxikaiczfaopbbwaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9og8Fpxssssssssssssssssp8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngacitc:q1jjbfpbibaac:q:yjjbfRbbgapsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Nghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spklbaaaocwffahc:q:yjjbfRbbfhoxdkaiczfaopbbbpklbaoczfhoxekaiczfaopbbdaoRbbgacitc:q1jjbfpbibaac:q:yjjbfRbbgapsaoRbeghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPpklbaaaocdffahc:q:yjjbfRbbfhokdndndndndndnaqcl4ciGarfPDbedibledibkaicafpxbbbbbbbbbbbbbbbbpklbxlkaicafaopbblaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLg8Ecdp:mea8EpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9og8Fpxiiiiiiiiiiiiiiiip8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngacitc:q1jjbfpbibaac:q:yjjbfRbbgapsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Nghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spklbaaaoclffahc:q:yjjbfRbbfhoxikaicafaopbbwaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9og8Fpxssssssssssssssssp8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngacitc:q1jjbfpbibaac:q:yjjbfRbbgapsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Nghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spklbaaaocwffahc:q:yjjbfRbbfhoxdkaicafaopbbbpklbaoczfhoxekaicafaopbbdaoRbbgacitc:q1jjbfpbibaac:q:yjjbfRbbgapsaoRbeghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPpklbaaaocdffahc:q:yjjbfRbbfhokdndndndndndnaqco4arfPDbedibledibkaic8Wfpxbbbbbbbbbbbbbbbbpklbxlkaic8Wfaopbblaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLg8Ecdp:mea8EpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9og8Fpxiiiiiiiiiiiiiiiip8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngicitc:q1jjbfpbibaic:q:yjjbfRbbgipsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Ngqcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spklbaiaoclffaqc:q:yjjbfRbbfhoxikaic8Wfaopbbwaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9og8Fpxssssssssssssssssp8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngicitc:q1jjbfpbibaic:q:yjjbfRbbgipsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Ngqcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spklbaiaocwffaqc:q:yjjbfRbbfhoxdkaic8Wfaopbbbpklbaoczfhoxekaic8WfaopbbdaoRbbgicitc:q1jjbfpbibaic:q:yjjbfRbbgipsaoRbegqcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPpklbaiaocdffaqc:q:yjjbfRbbfhokalc;abfhialcjefaX0meaihlamao9Rc;Fb0mbkkdnaiaX9pmbaici4hlinamao9RcK6mwa5aifhqdndndndndndnaOaico4fRbbalcoG4ciGarfPDbedibledibkaqpxbbbbbbbbbbbbbbbbpkbbxlkaqaopbblaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLg8Ecdp:mea8EpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9og8Fpxiiiiiiiiiiiiiiiip8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngacitc:q1jjbfpbibaac:q:yjjbfRbbgapsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Nghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spkbbaaaoclffahc:q:yjjbfRbbfhoxikaqaopbbwaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9og8Fpxssssssssssssssssp8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngacitc:q1jjbfpbibaac:q:yjjbfRbbgapsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Nghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spkbbaaaocwffahc:q:yjjbfRbbfhoxdkaqaopbbbpkbbaoczfhoxekaqaopbbdaoRbbgacitc:q1jjbfpbibaac:q:yjjbfRbbgapsaoRbeghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPpkbbaaaocdffahc:q:yjjbfRbbfhokalcdfhlaiczfgiaX6mbkkaohOaoTmoka5aXfh5a3cefg3cl9hmbkdndndndnawTmbasaYcd4fRbbglciGPlbedwbkaXTmdavcjdfaYfhlavaYfpbdbhgcbhoinalavcj;cbfaofpblbg8JaKaofpblbg8KpmbzeHdOiAlCvXoQrLg8LaQaofpblbg8MaLaofpblbg8NpmbzeHdOiAlCvXoQrLgypmbezHdiOAlvCXorQLg8Ecep9Ta8Epxeeeeeeeeeeeeeeeeg8Fp9op9Hp9rg8Eagp9Uggp9Abbbaladfglaga8Ea8Epmlvorlvorlvorlvorp9Uggp9Abbbaladfglaga8Ea8EpmwDqkwDqkwDqkwDqkp9Uggp9Abbbaladfglaga8Ea8EpmxmPsxmPsxmPsxmPsp9Uggp9Abbbaladfglaga8LaypmwDKYqk8AExm35Ps8E8Fg8Ecep9Ta8Ea8Fp9op9Hp9rg8Ep9Uggp9Abbbaladfglaga8Ea8Epmlvorlvorlvorlvorp9Uggp9Abbbaladfglaga8Ea8EpmwDqkwDqkwDqkwDqkp9Uggp9Abbbaladfglaga8Ea8EpmxmPsxmPsxmPsxmPsp9Uggp9Abbbaladfglaga8Ja8KpmwKDYq8AkEx3m5P8Es8Fg8Ja8Ma8NpmwKDYq8AkEx3m5P8Es8Fg8KpmbezHdiOAlvCXorQLg8Ecep9Ta8Ea8Fp9op9Hp9rg8Ep9Uggp9Abbbaladfglaga8Ea8Epmlvorlvorlvorlvorp9Uggp9Abbbaladfglaga8Ea8EpmwDqkwDqkwDqkwDqkp9Uggp9Abbbaladfglaga8Ea8EpmxmPsxmPsxmPsxmPsp9Uggp9Abbbaladfglaga8Ja8KpmwDKYqk8AExm35Ps8E8Fg8Ecep9Ta8Ea8Fp9op9Hp9rg8Ep9Ug8Fp9Abbbaladfgla8Fa8Ea8Epmlvorlvorlvorlvorp9Ug8Fp9Abbbaladfgla8Fa8Ea8EpmwDqkwDqkwDqkwDqkp9Ug8Fp9Abbbaladfgla8Fa8Ea8EpmxmPsxmPsxmPsxmPsp9Uggp9AbbbaladfhlaoczfgoaX6mbxikkaXTmeavcjdfaYfhlavaYfpbdbhgcbhoinalavcj;cbfaofpblbg8JaKaofpblbg8KpmbzeHdOiAlCvXoQrLg8LaQaofpblbg8MaLaofpblbg8NpmbzeHdOiAlCvXoQrLgypmbezHdiOAlvCXorQLg8Ecep:nea8Epxebebebebebebebebg8Fp9op:bep9rg8Eagp:oeggp9Abbbaladfglaga8Ea8Epmlvorlvorlvorlvorp:oeggp9Abbbaladfglaga8Ea8EpmwDqkwDqkwDqkwDqkp:oeggp9Abbbaladfglaga8Ea8EpmxmPsxmPsxmPsxmPsp:oeggp9Abbbaladfglaga8LaypmwDKYqk8AExm35Ps8E8Fg8Ecep:nea8Ea8Fp9op:bep9rg8Ep:oeggp9Abbbaladfglaga8Ea8Epmlvorlvorlvorlvorp:oeggp9Abbbaladfglaga8Ea8EpmwDqkwDqkwDqkwDqkp:oeggp9Abbbaladfglaga8Ea8EpmxmPsxmPsxmPsxmPsp:oeggp9Abbbaladfglaga8Ja8KpmwKDYq8AkEx3m5P8Es8Fg8Ja8Ma8NpmwKDYq8AkEx3m5P8Es8Fg8KpmbezHdiOAlvCXorQLg8Ecep:nea8Ea8Fp9op:bep9rg8Ep:oeggp9Abbbaladfglaga8Ea8Epmlvorlvorlvorlvorp:oeggp9Abbbaladfglaga8Ea8EpmwDqkwDqkwDqkwDqkp:oeggp9Abbbaladfglaga8Ea8EpmxmPsxmPsxmPsxmPsp:oeggp9Abbbaladfglaga8Ja8KpmwDKYqk8AExm35Ps8E8Fg8Ecep:nea8Ea8Fp9op:bep9rg8Ep:oeg8Fp9Abbbaladfgla8Fa8Ea8Epmlvorlvorlvorlvorp:oeg8Fp9Abbbaladfgla8Fa8Ea8EpmwDqkwDqkwDqkwDqkp:oeg8Fp9Abbbaladfgla8Fa8Ea8EpmxmPsxmPsxmPsxmPsp:oeggp9AbbbaladfhlaoczfgoaX6mbxdkkaXTmbcbhocbalcl4gl9Rc8FGhiavcjdfaYfhravaYfpbdbh8Finaravcj;cbfaofpblbggaKaofpblbg8JpmbzeHdOiAlCvXoQrLg8KaQaofpblbg8LaLaofpblbg8MpmbzeHdOiAlCvXoQrLg8NpmbezHdiOAlvCXorQLg8Eaip:Rea8Ealp:Sep9qg8Ea8Fp9rg8Fp9Abbbaradfgra8Fa8Ea8Epmlvorlvorlvorlvorp9rg8Fp9Abbbaradfgra8Fa8Ea8EpmwDqkwDqkwDqkwDqkp9rg8Fp9Abbbaradfgra8Fa8Ea8EpmxmPsxmPsxmPsxmPsp9rg8Fp9Abbbaradfgra8Fa8Ka8NpmwDKYqk8AExm35Ps8E8Fg8Eaip:Rea8Ealp:Sep9qg8Ep9rg8Fp9Abbbaradfgra8Fa8Ea8Epmlvorlvorlvorlvorp9rg8Fp9Abbbaradfgra8Fa8Ea8EpmwDqkwDqkwDqkwDqkp9rg8Fp9Abbbaradfgra8Fa8Ea8EpmxmPsxmPsxmPsxmPsp9rg8Fp9Abbbaradfgra8Faga8JpmwKDYq8AkEx3m5P8Es8Fgga8La8MpmwKDYq8AkEx3m5P8Es8Fg8JpmbezHdiOAlvCXorQLg8Eaip:Rea8Ealp:Sep9qg8Ep9rg8Fp9Abbbaradfgra8Fa8Ea8Epmlvorlvorlvorlvorp9rg8Fp9Abbbaradfgra8Fa8Ea8EpmwDqkwDqkwDqkwDqkp9rg8Fp9Abbbaradfgra8Fa8Ea8EpmxmPsxmPsxmPsxmPsp9rg8Fp9Abbbaradfgra8Faga8JpmwDKYqk8AExm35Ps8E8Fg8Eaip:Rea8Ealp:Sep9qg8Ep9rg8Fp9Abbbaradfgra8Fa8Ea8Epmlvorlvorlvorlvorp9rg8Fp9Abbbaradfgra8Fa8Ea8EpmwDqkwDqkwDqkwDqkp9rg8Fp9Abbbaradfgra8Fa8Ea8EpmxmPsxmPsxmPsxmPsp9rg8Fp9AbbbaradfhraoczfgoaX6mbkkaYclfgYad6mbkaHavcjdfaAad2;8qbbavavcjdfaAcufad2fad;8qbbaAazfhzc9:hoaOhxaOmbxlkkaeTmbaDalfhrcbhocuhlinaralaD9RglfaD6mdaPaeao9RaoaPfae6Eaofgoae6mbkaial9Rhxkcbc99amax9RakSEhoxekc9:hokavcj;kbf8Kjjjjbaokwbz:bjjjbk:TseHu8Jjjjjbc;ae9Rgv8Kjjjjbc9:hodnaeci9UgrcHfal0mbcuhoaiRbbgwc;WeGc;Ge9hmbawcsGgDce0mbavc;abfcFecje;8kbavcUf9cu83ibavc8Wf9cu83ibavcyf9cu83ibavcaf9cu83ibavcKf9cu83ibavczf9cu83ibav9cu83iwav9cu83ibaialfc9WfhqaicefgwarfhldnaeTmbcmcsaDceSEhkcbhxcbhmcbhrcbhicbhoindnalaq9nmbc9:hoxikdndnawRbbgDc;Ve0mbavc;abfaoaDcu7gPcl4fcsGcitfgsydlhzasydbhHdndnaDcsGgsak9pmbavaiaPfcsGcdtfydbaxasEhDaxasTgOfhxxekdndnascsSmbcehOasc987asamffcefhDxekalcefhDal8SbbgscFeGhPdndnascu9mmbaDhlxekalcvfhlaPcFbGhPcrhsdninaD8SbbgOcFbGastaPVhPaOcu9kmeaDcefhDascrfgsc8J9hmbxdkkaDcefhlkcehOaPce4cbaPceG9R7amfhDkaDhmkavc;abfaocitfgsaDBdbasazBdlavaicdtfaDBdbavc;abfaocefcsGcitfgsaHBdbasaDBdlaocdfhoaOaifhidnadcd9hmbabarcetfgsaH87ebasclfaD87ebascdfaz87ebxdkabarcdtfgsaHBdbascwfaDBdbasclfazBdbxekdnaDcpe0mbaxcefgOavaiaqaDcsGfRbbgscl49RcsGcdtfydbascz6gPEhDavaias9RcsGcdtfydbaOaPfgzascsGgOEhsaOThOdndnadcd9hmbabarcetfgHax87ebaHclfas87ebaHcdfaD87ebxekabarcdtfgHaxBdbaHcwfasBdbaHclfaDBdbkavaicdtfaxBdbavc;abfaocitfgHaDBdbaHaxBdlavaicefgicsGcdtfaDBdbavc;abfaocefcsGcitfgHasBdbaHaDBdlavaiaPfgicsGcdtfasBdbavc;abfaocdfcsGcitfgDaxBdbaDasBdlaocifhoaiaOfhiazaOfhxxekaxcbalRbbgHEgAaDc;:eSgDfhzaHcsGhCaHcl4hXdndnaHcs0mbazcefhOxekazhOavaiaX9RcsGcdtfydbhzkdndnaCmbaOcefhxxekaOhxavaiaH9RcsGcdtfydbhOkdndnaDTmbalcefhDxekalcdfhDal8SbegPcFeGhsdnaPcu9kmbalcofhAascFbGhscrhldninaD8SbbgPcFbGaltasVhsaPcu9kmeaDcefhDalcrfglc8J9hmbkaAhDxekaDcefhDkasce4cbasceG9R7amfgmhAkdndnaXcsSmbaDhsxekaDcefhsaD8SbbglcFeGhPdnalcu9kmbaDcvfhzaPcFbGhPcrhldninas8SbbgDcFbGaltaPVhPaDcu9kmeascefhsalcrfglc8J9hmbkazhsxekascefhskaPce4cbaPceG9R7amfgmhzkdndnaCcsSmbashlxekascefhlas8SbbgDcFeGhPdnaDcu9kmbascvfhOaPcFbGhPcrhDdninal8SbbgscFbGaDtaPVhPascu9kmealcefhlaDcrfgDc8J9hmbkaOhlxekalcefhlkaPce4cbaPceG9R7amfgmhOkdndnadcd9hmbabarcetfgDaA87ebaDclfaO87ebaDcdfaz87ebxekabarcdtfgDaABdbaDcwfaOBdbaDclfazBdbkavc;abfaocitfgDazBdbaDaABdlavaicdtfaABdbavc;abfaocefcsGcitfgDaOBdbaDazBdlavaicefgicsGcdtfazBdbavc;abfaocdfcsGcitfgDaABdbaDaOBdlavaiaHcz6aXcsSVfgicsGcdtfaOBdbaiaCTaCcsSVfhiaocifhokawcefhwaocsGhoaicsGhiarcifgrae6mbkkcbc99alaqSEhokavc;aef8Kjjjjbaok:clevu8Jjjjjbcz9Rhvdnaecvfal9nmbc9:skdnaiRbbc;:eGc;qeSmbcuskav9cb83iwaicefhoaialfc98fhrdnaeTmbdnadcdSmbcbhwindnaoar6mbc9:skaocefhlao8SbbgicFeGhddndnaicu9mmbalhoxekaocvfhoadcFbGhdcrhidninal8SbbgDcFbGaitadVhdaDcu9kmealcefhlaicrfgic8J9hmbxdkkalcefhokabawcdtfadc8Etc8F91adcd47avcwfadceGcdtVglydbfgiBdbalaiBdbawcefgwae9hmbxdkkcbhwindnaoar6mbc9:skaocefhlao8SbbgicFeGhddndnaicu9mmbalhoxekaocvfhoadcFbGhdcrhidninal8SbbgDcFbGaitadVhdaDcu9kmealcefhlaicrfgic8J9hmbxdkkalcefhokabawcetfadc8Etc8F91adcd47avcwfadceGcdtVglydbfgi87ebalaiBdbawcefgwae9hmbkkcbc99aoarSEk:2Pliur97eue978Jjjjjbc8W9Rhiaec98Ghldndnadcl9hmbdnalTmbcbhvabhdinadadpbbbgocKp:RecKp:Sep;6egraocwp:RecKp:Sep;6earp;Geaoczp:RecKp:Sep;6egwp;Gep;Kep;LegDpxbbbbbbbbbbbbbbbbp:2egqarpxbbbjbbbjbbbjbbbjgkp9op9rp;Kegrpxbb;:9cbb;:9cbb;:9cbb;:9cararp;MeaDaDp;Meawaqawakp9op9rp;Kegrarp;Mep;Kep;Kep;Jep;Negwp;Mepxbbn0bbn0bbn0bbn0gqp;KepxFbbbFbbbFbbbFbbbp9oaopxbbbFbbbFbbbFbbbFp9op9qarawp;Meaqp;Kecwp:RepxbFbbbFbbbFbbbFbbp9op9qaDawp;Meaqp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qpkbbadczfhdavclfgval6mbkkalaeSmeaipxbbbbbbbbbbbbbbbbgqpklbaiabalcdtfgdaeciGglcdtgv;8qbbdnalTmbaiaipblbgocKp:RecKp:Sep;6egraocwp:RecKp:Sep;6earp;Geaoczp:RecKp:Sep;6egwp;Gep;Kep;LegDaqp:2egqarpxbbbjbbbjbbbjbbbjgkp9op9rp;Kegrpxbb;:9cbb;:9cbb;:9cbb;:9cararp;MeaDaDp;Meawaqawakp9op9rp;Kegrarp;Mep;Kep;Kep;Jep;Negwp;Mepxbbn0bbn0bbn0bbn0gqp;KepxFbbbFbbbFbbbFbbbp9oaopxbbbFbbbFbbbFbbbFp9op9qarawp;Meaqp;Kecwp:RepxbFbbbFbbbFbbbFbbp9op9qaDawp;Meaqp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qpklbkadaiav;8qbbskaipxFubbFubbFubbFubbgxpklbdnalTmbcbhvabhdinadczfgmampbbbgopxbbbbbbFFbbbbbbFFgkp9oadpbbbgDaopmbediwDqkzHOAKY8AEgwczp:Reczp:Sep;6egraipblbaDaopmlvorxmPsCXQL358E8Fp9op;6eawczp:Sep;6egwp;Gearp;Gep;Kep;Legopxbbbbbbbbbbbbbbbbp:2egqarpxbbbjbbbjbbbjbbbjgPp9op9rp;Kegrpxb;:FSb;:FSb;:FSb;:FSararp;Meaoaop;MeawaqawaPp9op9rp;Kegrarp;Mep;Kep;Kep;Jep;Negwp;Mepxbbn0bbn0bbn0bbn0gqp;KepxFFbbFFbbFFbbFFbbp9oaoawp;Meaqp;Keczp:Rep9qgoarawp;Meaqp;KepxFFbbFFbbFFbbFFbbp9ogrpmwDKYqk8AExm35Ps8E8Fp9qpkbbadaDakp9oaoarpmbezHdiOAlvCXorQLp9qpkbbadcafhdavclfgval6mbkkalaeSmbaiczfpxbbbbbbbbbbbbbbbbgopklbaiaopklbaiabalcitfgdaeciGglcitgv;8qbbaiaxpkladnalTmbaiaipblzgopxbbbbbbFFbbbbbbFFgkp9oaipblbgDaopmbediwDqkzHOAKY8AEgwczp:Reczp:Sep;6egraipblaaDaopmlvorxmPsCXQL358E8Fp9op;6eawczp:Sep;6egwp;Gearp;Gep;Kep;Legopxbbbbbbbbbbbbbbbbp:2egqarpxbbbjbbbjbbbjbbbjgPp9op9rp;Kegrpxb;:FSb;:FSb;:FSb;:FSararp;Meaoaop;MeawaqawaPp9op9rp;Kegrarp;Mep;Kep;Kep;Jep;Negwp;Mepxbbn0bbn0bbn0bbn0gqp;KepxFFbbFFbbFFbbFFbbp9oaoawp;Meaqp;Keczp:Rep9qgoarawp;Meaqp;KepxFFbbFFbbFFbbFFbbp9ogrpmwDKYqk8AExm35Ps8E8Fp9qpklzaiaDakp9oaoarpmbezHdiOAlvCXorQLp9qpklbkadaiav;8qbbkk:Iwllue97euo978Jjjjjbca9Rhidnaec98GglTmbcbhvabhoinaocKfpx:ji:1S:ji:1S:ji:1S:ji:1SaopbbbgraoczfgwpbbbgDpmlvorxmPsCXQL358E8Fgqczp:Segkpxibbbibbbibbbibbbp9qgxp;6ep;Negmaxaxp:1ep;7egxaxp;KearaDpmbediwDqkzHOAKY8AEgxczp:Reczp:Sep;6egrarp;Meaxczp:Sep;6egDaDp;Meaqczp:Reczp:Sep;6egqaqp;Mep;Kep;Kep;Lepxbbbbbbbbbbbbbbbbp:4ep;Jep;Mepxbbn0bbn0bbn0bbn0gxp;KepxFFbbFFbbFFbbFFbbgPp9oamaDp;Meaxp;Keczp:Rep9qgDamarp;Meaxp;KeaPp9oamaqp;Meaxp;Keczp:Rep9qgxpmwDKYqk8AExm35Ps8E8Fgrp5eakclp:RegmpEi:T:j83ibawarp5bampEd:T:j83ibaocwfaDaxpmbezHdiOAlvCXorQLgxp5eampEe:T:j83ibaoaxp5bampEb:T:j83ibaocafhoavclfgval6mbkkdnalaeSmbaiczfpxbbbbbbbbbbbbbbbbgmpklbaiampklbaiabalcitfgoaeciGgvcitgw;8qbbdnavTmbaipx:ji:1S:ji:1S:ji:1S:ji:1SaipblbgraipblzgDpmlvorxmPsCXQL358E8Fgqczp:Segkpxibbbibbbibbbibbbp9qgxp;6ep;Negmaxaxp:1ep;7egxaxp;KearaDpmbediwDqkzHOAKY8AEgxczp:Reczp:Sep;6egrarp;Meaxczp:Sep;6egDaDp;Meaqczp:Reczp:Sep;6egqaqp;Mep;Kep;Kep;Lepxbbbbbbbbbbbbbbbbp:4ep;Jep;Mepxbbn0bbn0bbn0bbn0gxp;KepxFFbbFFbbFFbbFFbbgPp9oamaDp;Meaxp;Keczp:Rep9qgDamarp;Meaxp;KeaPp9oamaqp;Meaxp;Keczp:Rep9qgxpmwDKYqk8AExm35Ps8E8Fgrp5eakclp:RegmpEi:T:j83iKaiarp5bampEd:T:j83izaiaDaxpmbezHdiOAlvCXorQLgxp5eampEe:T:j83iwaiaxp5bampEb:T:j83ibkaoaiaw;8qbbkk;uddiue978Jjjjjbc;ab9Rhidnadcd4ae2glc98GgvTmbcbheabhdinadadpbbbgocwp:Recwp:Sep;6eaocep:SepxbbjFbbjFbbjFbbjFp9opxbbjZbbjZbbjZbbjZp:Uep;Mepkbbadczfhdaeclfgeav6mbkkdnavalSmbaic8WfpxbbbbbbbbbbbbbbbbgopklbaicafaopklbaiczfaopklbaiaopklbaiabavcdtfgdalciGgecdtgv;8qbbdnaeTmbaiaipblbgocwp:Recwp:Sep;6eaocep:SepxbbjFbbjFbbjFbbjFp9opxbbjZbbjZbbjZbbjZp:Uep;Mepklbkadaiav;8qbbkk:CPvdue97euw97eu8Jjjjjbc8W9Rhiaec98Ghldndnadcl9hmbaipxbbbbbbbbbbbbbbbbgvpklbdnalTmbcbhoabhdinadpbbbhradpxbbuJbbuJbbuJbbuJaipblbarcKp:Tep9qgwcep:Seawp9qgDcdp:SeaDp9qgDclp:SeaDp9qgqp;6ep;NegDarcwp:RecKp:SegkarpxFbbbFbbbFbbbFbbbgxp9ogmp:Uep;6ep;Mepxbbn0bbn0bbn0bbn0gPp;Kecwp:RepxbFbbbFbbbFbbbFbbp9oaDamakp:Xearczp:RecKp:Segrp:Uep;6ep;MeaPp;Keaxp9op9qaDamakarp:Uep:Xep;6ep;MeaPp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qaDaqawcep:Rep9oawpxebbbebbbebbbebbbp9op9qp;6ep;MeaPp;KecKp:Rep9qpkbbadczfhdaoclfgoal6mbkkalaeSmeaiavpklaaicafabalcdtfgdaeciGglcdtgo;8qbbaiavpklbdnalTmbaipblahraipxbbuJbbuJbbuJbbuJaipblbarcKp:Tep9qgwcep:Seawp9qgDcdp:SeaDp9qgDclp:SeaDp9qgqp;6ep;NegDarcwp:RecKp:SegkarpxFbbbFbbbFbbbFbbbgxp9ogmp:Uep;6ep;Mepxbbn0bbn0bbn0bbn0gPp;Kecwp:RepxbFbbbFbbbFbbbFbbp9oaDamakp:Xearczp:RecKp:Segrp:Uep;6ep;MeaPp;Keaxp9op9qaDamakarp:Uep:Xep;6ep;MeaPp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qaDaqawcep:Rep9oawpxebbbebbbebbbebbbp9op9qp;6ep;MeaPp;KecKp:Rep9qpklakadaicafao;8qbbskaipxbbbbbbbbbbbbbbbbgvpklbdnalTmbcbhoabhdinadczfgspxbFu9hbFu9hbFu9hbFu9hadpbbbgDaspbbbgPpmlvorxmPsCXQL358E8Fgmczp:Teaipblbp9qgrcep:Searp9qgwcdp:Seawp9qgwclp:Seawp9qgwcwp:Seawp9qgqp;6ep;NegwaDaPpmbediwDqkzHOAKY8AEgDpxFFbbFFbbFFbbFFbbgPp9ogkaDczp:Segxp:Ueamczp:Reczp:Segmp:Xep;6ep;Mepxbbn0bbn0bbn0bbn0gDp;KeaPp9oawakaxamp:Uep:Xep;6ep;MeaDp;Keczp:Rep9qgxawaqarcep:Rep9oarpxebbbebbbebbbebbbp9op9qp;6ep;MeaDp;Keczp:Reawamakp:Uep;6ep;MeaDp;KeaPp9op9qgrpmwDKYqk8AExm35Ps8E8FpkbbadaxarpmbezHdiOAlvCXorQLpkbbadcafhdaoclfgoal6mbkkalaeSmbaiczfpxbbbbbbbbbbbbbbbbgrpklbaiarpklbaiabalcitfgdaeciGglcitgo;8qbbaiavpkladnalTmbaipxbFu9hbFu9hbFu9hbFu9haipblbgDaipblzgPpmlvorxmPsCXQL358E8Fgmczp:Teaipblap9qgrcep:Searp9qgwcdp:Seawp9qgwclp:Seawp9qgwcwp:Seawp9qgqp;6ep;NegwaDaPpmbediwDqkzHOAKY8AEgDpxFFbbFFbbFFbbFFbbgPp9ogkaDczp:Segxp:Ueamczp:Reczp:Segmp:Xep;6ep;Mepxbbn0bbn0bbn0bbn0gDp;KeaPp9oawakaxamp:Uep:Xep;6ep;MeaDp;Keczp:Rep9qgxawaqarcep:Rep9oarpxebbbebbbebbbebbbp9op9qp;6ep;MeaDp;Keczp:Reawamakp:Uep;6ep;MeaDp;KeaPp9op9qgrpmwDKYqk8AExm35Ps8E8FpklzaiaxarpmbezHdiOAlvCXorQLpklbkadaiao;8qbbkk9teiucbcbydj1jjbgeabcifc98GfgbBdj1jjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaikkkebcjwklz:Dbb'; // embed! simd
var detector = new Uint8Array([
0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 3, 2, 0, 0, 5, 3, 1, 0, 1, 12, 1, 0, 10, 22, 2, 12, 0, 65, 0, 65, 0, 65, 0, 252, 10, 0, 0,
11, 7, 0, 65, 0, 253, 15, 26, 11,
]);
var wasmpack = new Uint8Array([
32, 0, 65, 2, 1, 106, 34, 33, 3, 128, 11, 4, 13, 64, 6, 253, 10, 7, 15, 116, 127, 5, 8, 12, 40, 16, 19, 54, 20, 9, 27, 255, 113, 17, 42, 67,
24, 23, 146, 148, 18, 14, 22, 45, 70, 69, 56, 114, 101, 21, 25, 63, 75, 136, 108, 28, 118, 29, 73, 115,
]);
if (typeof WebAssembly !== 'object') {
return {
supported: false,
};
}
var wasm = WebAssembly.validate(detector) ? unpack(wasm_simd) : unpack(wasm_base);
var instance;
var ready = WebAssembly.instantiate(wasm, {}).then(function (result) {
instance = result.instance;
instance.exports.__wasm_call_ctors();
});
function unpack(data) {
var result = new Uint8Array(data.length);
for (var i = 0; i < data.length; ++i) {
var ch = data.charCodeAt(i);
result[i] = ch > 96 ? ch - 97 : ch > 64 ? ch - 39 : ch + 4;
}
var write = 0;
for (var i = 0; i < data.length; ++i) {
result[write++] = result[i] < 60 ? wasmpack[result[i]] : (result[i] - 60) * 64 + result[++i];
}
return result.buffer.slice(0, write);
}
function decode(instance, fun, target, count, size, source, filter) {
var sbrk = instance.exports.sbrk;
var count4 = (count + 3) & ~3;
var tp = sbrk(count4 * size);
var sp = sbrk(source.length);
var heap = new Uint8Array(instance.exports.memory.buffer);
heap.set(source, sp);
var res = fun(tp, count, size, sp, source.length);
if (res == 0 && filter) {
filter(tp, count4, size);
}
target.set(heap.subarray(tp, tp + count * size));
sbrk(tp - sbrk(0));
if (res != 0) {
throw new Error('Malformed buffer data: ' + res);
}
}
var filters = {
NONE: '',
OCTAHEDRAL: 'meshopt_decodeFilterOct',
QUATERNION: 'meshopt_decodeFilterQuat',
EXPONENTIAL: 'meshopt_decodeFilterExp',
COLOR: 'meshopt_decodeFilterColor',
};
var decoders = {
ATTRIBUTES: 'meshopt_decodeVertexBuffer',
TRIANGLES: 'meshopt_decodeIndexBuffer',
INDICES: 'meshopt_decodeIndexSequence',
};
var workers = [];
var requestId = 0;
function createWorker(url) {
var worker = {
object: new Worker(url),
pending: 0,
requests: {},
};
worker.object.onmessage = function (event) {
var data = event.data;
worker.pending -= data.count;
worker.requests[data.id][data.action](data.value);
delete worker.requests[data.id];
};
return worker;
}
function initWorkers(count) {
var source =
'self.ready = WebAssembly.instantiate(new Uint8Array([' +
new Uint8Array(wasm) +
']), {})' +
'.then(function(result) { result.instance.exports.__wasm_call_ctors(); return result.instance; });' +
'self.onmessage = ' +
workerProcess.name +
';' +
decode.toString() +
workerProcess.toString();
var blob = new Blob([source], { type: 'text/javascript' });
var url = URL.createObjectURL(blob);
for (var i = workers.length; i < count; ++i) {
workers[i] = createWorker(url);
}
for (var i = count; i < workers.length; ++i) {
workers[i].object.postMessage({});
}
workers.length = count;
URL.revokeObjectURL(url);
}
function decodeWorker(count, size, source, mode, filter) {
var worker = workers[0];
for (var i = 1; i < workers.length; ++i) {
if (workers[i].pending < worker.pending) {
worker = workers[i];
}
}
return new Promise(function (resolve, reject) {
var data = new Uint8Array(source);
var id = ++requestId;
worker.pending += count;
worker.requests[id] = { resolve: resolve, reject: reject };
worker.object.postMessage({ id: id, count: count, size: size, source: data, mode: mode, filter: filter }, [data.buffer]);
});
}
function workerProcess(event) {
var data = event.data;
if (!data.id) {
return self.close();
}
self.ready.then(function (instance) {
try {
var target = new Uint8Array(data.count * data.size);
decode(instance, instance.exports[data.mode], target, data.count, data.size, data.source, instance.exports[data.filter]);
self.postMessage({ id: data.id, count: data.count, action: 'resolve', value: target }, [target.buffer]);
} catch (error) {
self.postMessage({ id: data.id, count: data.count, action: 'reject', value: error });
}
});
}
return {
ready: ready,
supported: true,
useWorkers: function (count) {
initWorkers(count);
},
decodeVertexBuffer: function (target, count, size, source, filter) {
decode(instance, instance.exports.meshopt_decodeVertexBuffer, target, count, size, source, instance.exports[filters[filter]]);
},
decodeIndexBuffer: function (target, count, size, source) {
decode(instance, instance.exports.meshopt_decodeIndexBuffer, target, count, size, source);
},
decodeIndexSequence: function (target, count, size, source) {
decode(instance, instance.exports.meshopt_decodeIndexSequence, target, count, size, source);
},
decodeGltfBuffer: function (target, count, size, source, mode, filter) {
decode(instance, instance.exports[decoders[mode]], target, count, size, source, instance.exports[filters[filter]]);
},
decodeGltfBufferAsync: function (count, size, source, mode, filter) {
if (workers.length > 0) {
return decodeWorker(count, size, source, decoders[mode], filters[filter]);
}
return ready.then(function () {
var target = new Uint8Array(count * size);
decode(instance, instance.exports[decoders[mode]], target, count, size, source, instance.exports[filters[filter]]);
return target;
});
},
};
})();
if (typeof exports === 'object' && typeof module === 'object') module.exports = MeshoptDecoder;
else if (typeof define === 'function' && define['amd']) define([], function () { return MeshoptDecoder; });
else if (typeof exports === 'object') exports['MeshoptDecoder'] = MeshoptDecoder;
else (typeof self !== 'undefined' ? self : this).MeshoptDecoder = MeshoptDecoder;
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
js/meshopt_decoder.d.ts | TypeScript | // This file is part of meshoptimizer library and is distributed under the terms of MIT License.
// Copyright (C) 2016-2026, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
export const MeshoptDecoder: {
supported: boolean;
ready: Promise<void>;
decodeVertexBuffer: (target: Uint8Array, count: number, size: number, source: Uint8Array, filter?: string) => void;
decodeIndexBuffer: (target: Uint8Array, count: number, size: number, source: Uint8Array) => void;
decodeIndexSequence: (target: Uint8Array, count: number, size: number, source: Uint8Array) => void;
decodeGltfBuffer: (target: Uint8Array, count: number, size: number, source: Uint8Array, mode: string, filter?: string) => void;
useWorkers: (count: number) => void;
decodeGltfBufferAsync: (count: number, size: number, source: Uint8Array, mode: string, filter?: string) => Promise<Uint8Array>;
};
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
js/meshopt_decoder.mjs | JavaScript | // This file is part of meshoptimizer library and is distributed under the terms of MIT License.
// Copyright (C) 2016-2026, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
var MeshoptDecoder = (function () {
// Built with clang version 19.1.5-wasi-sdk
// Built from meshoptimizer 1.0
var wasm_base =
'b9H79Tebbbe8Fv9Gbb9Gvuuuuueu9Giuuub9Geueu9Giuuueuixkbeeeddddillviebeoweuec:W:Odkr;Neqo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9KW9J9V9KW9wWVtW949c919M9MWVbeY9TW79O9V9Wt9F9KW9J9V9KW69U9KW949c919M9MWVbdE9TW79O9V9Wt9F9KW9J9V9KW69U9KW949tWG91W9U9JWbiL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9p9JtblK9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9r919HtbvL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVT949WboY9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVJ9V29VVbrl79IV9Rbwq;lZkdbk;jYi5ud9:du8Jjjjjbcj;kb9Rgv8Kjjjjbc9:hodnalTmbcuhoaiRbbgrc;WeGc:Ge9hmbarcsGgwce0mbc9:hoalcufadcd4cbawEgDadfgrcKcaawEgqaraq0Egk6mbaicefhxcj;abad9Uc;WFbGcjdadca0EhmaialfgPar9Rgoadfhsavaoadz:jjjjbgzceVhHcbhOdndninaeaO9nmeaPax9RaD6mdamaeaO9RaOamfgoae6EgAcsfglc9WGhCabaOad2fhXaAcethQaxaDfhiaOaeaoaeao6E9RhLalcl4cifcd4hKazcj;cbfaAfhYcbh8AazcjdfhEaHh3incbhodnawTmbaxa8Acd4fRbbhokaocFeGh5cbh8Eazcj;cbfhqinaih8Fdndndndna5a8Ecet4ciGgoc9:fPdebdkaPa8F9RaA6mrazcj;cbfa8EaA2fa8FaAz:jjjjb8Aa8FaAfhixdkazcj;cbfa8EaA2fcbaAz:kjjjb8Aa8FhixekaPa8F9RaK6mva8FaKfhidnaCTmbaPai9RcK6mbaocdtc:q1jjbfcj1jjbawEhaczhrcbhlinargoc9Wfghaqfhrdndndndndndnaaa8Fahco4fRbbalcoG4ciGcdtfydbPDbedvivvvlvkar9cb83bbarcwf9cb83bbxlkarcbaiRbdai8Xbb9c:c:qj:bw9:9c:q;c1:I1e:d9c:b:c:e1z9:gg9cjjjjjz:dg8J9qE86bbaqaofgrcGfag9c8F1:NghcKtc8F91aicdfa8J9c8N1:Nfg8KRbbG86bbarcVfcba8KahcjeGcr4fghRbbag9cjjjjjl:dg8J9qE86bbarc7fcbaha8J9c8L1:NfghRbbag9cjjjjjd:dg8J9qE86bbarctfcbaha8J9c8K1:NfghRbbag9cjjjjje:dg8J9qE86bbarc91fcbaha8J9c8J1:NfghRbbag9cjjjj;ab:dg8J9qE86bbarc4fcbaha8J9cg1:NfghRbbag9cjjjja:dg8J9qE86bbarc93fcbaha8J9ch1:NfghRbbag9cjjjjz:dgg9qE86bbarc94fcbahag9ca1:NfghRbbai8Xbe9c:c:qj:bw9:9c:q;c1:I1e:d9c:b:c:e1z9:gg9cjjjjjz:dg8J9qE86bbarc95fag9c8F1:NgicKtc8F91aha8J9c8N1:NfghRbbG86bbarc96fcbahaicjeGcr4fgiRbbag9cjjjjjl:dg8J9qE86bbarc97fcbaia8J9c8L1:NfgiRbbag9cjjjjjd:dg8J9qE86bbarc98fcbaia8J9c8K1:NfgiRbbag9cjjjjje:dg8J9qE86bbarc99fcbaia8J9c8J1:NfgiRbbag9cjjjj;ab:dg8J9qE86bbarc9:fcbaia8J9cg1:NfgiRbbag9cjjjja:dg8J9qE86bbarcufcbaia8J9ch1:NfgiRbbag9cjjjjz:dgg9qE86bbaiag9ca1:NfhixikaraiRblaiRbbghco4g8Ka8KciSg8KE86bbaqaofgrcGfaiclfa8Kfg8KRbbahcl4ciGg8La8LciSg8LE86bbarcVfa8Ka8Lfg8KRbbahcd4ciGg8La8LciSg8LE86bbarc7fa8Ka8Lfg8KRbbahciGghahciSghE86bbarctfa8Kahfg8KRbbaiRbeghco4g8La8LciSg8LE86bbarc91fa8Ka8Lfg8KRbbahcl4ciGg8La8LciSg8LE86bbarc4fa8Ka8Lfg8KRbbahcd4ciGg8La8LciSg8LE86bbarc93fa8Ka8Lfg8KRbbahciGghahciSghE86bbarc94fa8Kahfg8KRbbaiRbdghco4g8La8LciSg8LE86bbarc95fa8Ka8Lfg8KRbbahcl4ciGg8La8LciSg8LE86bbarc96fa8Ka8Lfg8KRbbahcd4ciGg8La8LciSg8LE86bbarc97fa8Ka8Lfg8KRbbahciGghahciSghE86bbarc98fa8KahfghRbbaiRbigico4g8Ka8KciSg8KE86bbarc99faha8KfghRbbaicl4ciGg8Ka8KciSg8KE86bbarc9:faha8KfghRbbaicd4ciGg8Ka8KciSg8KE86bbarcufaha8KfgrRbbaiciGgiaiciSgiE86bbaraifhixdkaraiRbwaiRbbghcl4g8Ka8KcsSg8KE86bbaqaofgrcGfaicwfa8Kfg8KRbbahcsGghahcsSghE86bbarcVfa8KahfghRbbaiRbeg8Kcl4g8La8LcsSg8LE86bbarc7faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarctfaha8KfghRbbaiRbdg8Kcl4g8La8LcsSg8LE86bbarc91faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc4faha8KfghRbbaiRbig8Kcl4g8La8LcsSg8LE86bbarc93faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc94faha8KfghRbbaiRblg8Kcl4g8La8LcsSg8LE86bbarc95faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc96faha8KfghRbbaiRbvg8Kcl4g8La8LcsSg8LE86bbarc97faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc98faha8KfghRbbaiRbog8Kcl4g8La8LcsSg8LE86bbarc99faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc9:faha8KfghRbbaiRbrgicl4g8Ka8KcsSg8KE86bbarcufaha8KfgrRbbaicsGgiaicsSgiE86bbaraifhixekarai8Pbb83bbarcwfaicwf8Pbb83bbaiczfhikdnaoaC9pmbalcdfhlaoczfhraPai9RcL0mekkaoaC6moaimexokaCmva8FTmvkaqaAfhqa8Ecefg8Ecl9hmbkdndndndnawTmbasa8Acd4fRbbgociGPlbedrbkaATmdaza8Afh8Fazcj;cbfhhcbh8EaEhaina8FRbbhraahocbhlinaoahalfRbbgqce4cbaqceG9R7arfgr86bbaoadfhoaAalcefgl9hmbkaacefhaa8Fcefh8FahaAfhha8Ecefg8Ecl9hmbxikkaATmeaza8Afhaazcj;cbfhhcbhoceh8EaYh8FinaEaofhlaa8Vbbhrcbhoinala8FaofRbbcwtahaofRbbgqVc;:FiGce4cbaqceG9R7arfgr87bbaladfhlaLaocefgofmbka8FaQfh8FcdhoaacdfhaahaQfhha8EceGhlcbh8EalmbxdkkaATmbcbaocl49Rh8Eaza8AfRbbhqcwhoa3hlinalRbbaotaqVhqalcefhlaocwfgoca9hmbkcbhhaEh8FaYhainazcj;cbfahfRbbhrcwhoaahlinalRbbaotarVhralaAfhlaocwfgoca9hmbkara8E93aq7hqcbhoa8Fhlinalaqao486bbalcefhlaocwfgoca9hmbka8Fadfh8FaacefhaahcefghaA9hmbkkaEclfhEa3clfh3a8Aclfg8Aad6mbkaXazcjdfaAad2z:jjjjb8AazazcjdfaAcufad2fadz:jjjjb8AaAaOfhOaihxaimbkc9:hoxdkcbc99aPax9RakSEhoxekc9:hokavcj;kbf8Kjjjjbaok:XseHu8Jjjjjbc;ae9Rgv8Kjjjjbc9:hodnaeci9UgrcHfal0mbcuhoaiRbbgwc;WeGc;Ge9hmbawcsGgDce0mbavc;abfcFecjez:kjjjb8AavcUf9cu83ibavc8Wf9cu83ibavcyf9cu83ibavcaf9cu83ibavcKf9cu83ibavczf9cu83ibav9cu83iwav9cu83ibaialfc9WfhqaicefgwarfhldnaeTmbcmcsaDceSEhkcbhxcbhmcbhrcbhicbhoindnalaq9nmbc9:hoxikdndnawRbbgDc;Ve0mbavc;abfaoaDcu7gPcl4fcsGcitfgsydlhzasydbhHdndnaDcsGgsak9pmbavaiaPfcsGcdtfydbaxasEhDaxasTgOfhxxekdndnascsSmbcehOasc987asamffcefhDxekalcefhDal8SbbgscFeGhPdndnascu9mmbaDhlxekalcvfhlaPcFbGhPcrhsdninaD8SbbgOcFbGastaPVhPaOcu9kmeaDcefhDascrfgsc8J9hmbxdkkaDcefhlkcehOaPce4cbaPceG9R7amfhDkaDhmkavc;abfaocitfgsaDBdbasazBdlavaicdtfaDBdbavc;abfaocefcsGcitfgsaHBdbasaDBdlaocdfhoaOaifhidnadcd9hmbabarcetfgsaH87ebasclfaD87ebascdfaz87ebxdkabarcdtfgsaHBdbascwfaDBdbasclfazBdbxekdnaDcpe0mbaxcefgOavaiaqaDcsGfRbbgscl49RcsGcdtfydbascz6gPEhDavaias9RcsGcdtfydbaOaPfgzascsGgOEhsaOThOdndnadcd9hmbabarcetfgHax87ebaHclfas87ebaHcdfaD87ebxekabarcdtfgHaxBdbaHcwfasBdbaHclfaDBdbkavaicdtfaxBdbavc;abfaocitfgHaDBdbaHaxBdlavaicefgicsGcdtfaDBdbavc;abfaocefcsGcitfgHasBdbaHaDBdlavaiaPfgicsGcdtfasBdbavc;abfaocdfcsGcitfgDaxBdbaDasBdlaocifhoaiaOfhiazaOfhxxekaxcbalRbbgHEgAaDc;:eSgDfhzaHcsGhCaHcl4hXdndnaHcs0mbazcefhOxekazhOavaiaX9RcsGcdtfydbhzkdndnaCmbaOcefhxxekaOhxavaiaH9RcsGcdtfydbhOkdndnaDTmbalcefhDxekalcdfhDal8SbegPcFeGhsdnaPcu9kmbalcofhAascFbGhscrhldninaD8SbbgPcFbGaltasVhsaPcu9kmeaDcefhDalcrfglc8J9hmbkaAhDxekaDcefhDkasce4cbasceG9R7amfgmhAkdndnaXcsSmbaDhsxekaDcefhsaD8SbbglcFeGhPdnalcu9kmbaDcvfhzaPcFbGhPcrhldninas8SbbgDcFbGaltaPVhPaDcu9kmeascefhsalcrfglc8J9hmbkazhsxekascefhskaPce4cbaPceG9R7amfgmhzkdndnaCcsSmbashlxekascefhlas8SbbgDcFeGhPdnaDcu9kmbascvfhOaPcFbGhPcrhDdninal8SbbgscFbGaDtaPVhPascu9kmealcefhlaDcrfgDc8J9hmbkaOhlxekalcefhlkaPce4cbaPceG9R7amfgmhOkdndnadcd9hmbabarcetfgDaA87ebaDclfaO87ebaDcdfaz87ebxekabarcdtfgDaABdbaDcwfaOBdbaDclfazBdbkavc;abfaocitfgDazBdbaDaABdlavaicdtfaABdbavc;abfaocefcsGcitfgDaOBdbaDazBdlavaicefgicsGcdtfazBdbavc;abfaocdfcsGcitfgDaABdbaDaOBdlavaiaHcz6aXcsSVfgicsGcdtfaOBdbaiaCTaCcsSVfhiaocifhokawcefhwaocsGhoaicsGhiarcifgrae6mbkkcbc99alaqSEhokavc;aef8Kjjjjbaok:clevu8Jjjjjbcz9Rhvdnaecvfal9nmbc9:skdnaiRbbc;:eGc;qeSmbcuskav9cb83iwaicefhoaialfc98fhrdnaeTmbdnadcdSmbcbhwindnaoar6mbc9:skaocefhlao8SbbgicFeGhddndnaicu9mmbalhoxekaocvfhoadcFbGhdcrhidninal8SbbgDcFbGaitadVhdaDcu9kmealcefhlaicrfgic8J9hmbxdkkalcefhokabawcdtfadc8Etc8F91adcd47avcwfadceGcdtVglydbfgiBdbalaiBdbawcefgwae9hmbxdkkcbhwindnaoar6mbc9:skaocefhlao8SbbgicFeGhddndnaicu9mmbalhoxekaocvfhoadcFbGhdcrhidninal8SbbgDcFbGaitadVhdaDcu9kmealcefhlaicrfgic8J9hmbxdkkalcefhokabawcetfadc8Etc8F91adcd47avcwfadceGcdtVglydbfgi87ebalaiBdbawcefgwae9hmbkkcbc99aoarSEk:Lvoeue99dud99eud99dndnadcl9hmbaeTmeindndnabcdfgd8Sbb:Yab8Sbbgi:Ygl:l:tabcefgv8Sbbgo:Ygr:l:tgwJbb;:9cawawNJbbbbawawJbbbb9GgDEgq:mgkaqaicb9iEalMgwawNakaqaocb9iEarMgqaqNMM:r:vglNJbbbZJbbb:;aDEMgr:lJbbb9p9DTmbar:Ohixekcjjjj94hikadai86bbdndnaqalNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkavad86bbdndnawalNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohdxekcjjjj94hdkabad86bbabclfhbaecufgembxdkkaeTmbindndnabclfgd8Ueb:Yab8Uebgi:Ygl:l:tabcdfgv8Uebgo:Ygr:l:tgwJb;:FSawawNJbbbbawawJbbbb9GgDEgq:mgkaqaicb9iEalMgwawNakaqaocb9iEarMgqaqNMM:r:vglNJbbbZJbbb:;aDEMgr:lJbbb9p9DTmbar:Ohixekcjjjj94hikadai87ebdndnaqalNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkavad87ebdndnawalNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohdxekcjjjj94hdkabad87ebabcwfhbaecufgembkkk::ioiue99dud99dud99dnaeTmbcbhiabhlindndnal8Uebgv:YgoJ:ji:1Salcof8UebgrciVgw:Y:vgDNJbbbZJbbb:;avcu9kEMgq:lJbbb9p9DTmbaq:Ohkxekcjjjj94hkkalclf8Uebhvalcdf8UebhxabaiarcefciGfcetfak87ebdndnax:YgqaDNJbbbZJbbb:;axcu9kEMgm:lJbbb9p9DTmbam:Ohxxekcjjjj94hxkabaiarciGfgkcd7cetfax87ebdndnav:YgmaDNJbbbZJbbb:;avcu9kEMgP:lJbbb9p9DTmbaP:Ohvxekcjjjj94hvkabaiarcufciGfcetfav87ebdndnawaw2:ZgPaPMaoaoN:taqaqN:tamamN:tgoJbbbbaoJbbbb9GE:raDNJbbbZMgD:lJbbb9p9DTmbaD:Ohrxekcjjjj94hrkabakcetfar87ebalcwfhlaiclfhiaecufgembkkk9mbdnadcd4ae2gdTmbinababydbgecwtcw91:Yaece91cjjj98Gcjjj;8if::NUdbabclfhbadcufgdmbkkk:Tvirud99eudndnadcl9hmbaeTmeindndnabRbbgiabcefgl8Sbbgvabcdfgo8Sbbgrf9R:YJbbuJabcifgwRbbgdce4adVgDcd4aDVgDcl4aDVgD:Z:vgqNJbbbZMgk:lJbbb9p9DTmbak:Ohxxekcjjjj94hxkaoax86bbdndnaraif:YaqNJbbbZMgk:lJbbb9p9DTmbak:Ohoxekcjjjj94hokalao86bbdndnavaifar9R:YaqNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikabai86bbdndnaDadcetGadceGV:ZaqNJbbbZMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkawad86bbabclfhbaecufgembxdkkaeTmbindndnab8Vebgiabcdfgl8Uebgvabclfgo8Uebgrf9R:YJbFu9habcofgw8Vebgdce4adVgDcd4aDVgDcl4aDVgDcw4aDVgD:Z:vgqNJbbbZMgk:lJbbb9p9DTmbak:Ohxxekcjjjj94hxkaoax87ebdndnaraif:YaqNJbbbZMgk:lJbbb9p9DTmbak:Ohoxekcjjjj94hokalao87ebdndnavaifar9R:YaqNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikabai87ebdndnaDadcetGadceGV:ZaqNJbbbZMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkawad87ebabcwfhbaecufgembkkk9teiucbcbyd:K1jjbgeabcifc98GfgbBd:K1jjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaik;teeeudndnaeabVciGTmbabhixekdndnadcz9pmbabhixekabhiinaiaeydbBdbaiaeydlBdlaiaeydwBdwaiaeydxBdxaeczfheaiczfhiadc9Wfgdcs0mbkkadcl6mbinaiaeydbBdbaeclfheaiclfhiadc98fgdci0mbkkdnadTmbinaiaeRbb86bbaicefhiaecefheadcufgdmbkkabk:3eedudndnabciGTmbabhixekaecFeGc:b:c:ew2hldndnadcz9pmbabhixekabhiinaialBdxaialBdwaialBdlaialBdbaiczfhiadc9Wfgdcs0mbkkadcl6mbinaialBdbaiclfhiadc98fgdci0mbkkdnadTmbinaiae86bbaicefhiadcufgdmbkkabkk81dbcjwk8Kbbbbdbbblbbbwbbbbbbbebbbdbbblbbbwbbbbc:Kwkl8WNbb'; // embed! base
var wasm_simd =
'b9H79TebbbeKl9Gbb9Gvuuuuueu9Giuuub9Geueuixkbbebeeddddilve9Weeeviebeoweuec:q:6dkr;Neqo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9KW9J9V9KW9wWVtW949c919M9MWVbdY9TW79O9V9Wt9F9KW9J9V9KW69U9KW949c919M9MWVblE9TW79O9V9Wt9F9KW9J9V9KW69U9KW949tWG91W9U9JWbvL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9p9JtboK9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9r919HtbrL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVT949WbwY9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVJ9V29VVbDl79IV9Rbqq:Ctklbzik9:evu8Jjjjjbcz9Rhbcbheincbhdcbhiinabcwfadfaicjuaead4ceGglE86bbaialfhiadcefgdcw9hmbkaec:q:yjjbfai86bbaecitc:q1jjbfab8Piw83ibaecefgecjd9hmbkk:183lYud97dur978Jjjjjbcj;kb9Rgv8Kjjjjbc9:hodnalTmbcuhoaiRbbgrc;WeGc:Ge9hmbarcsGgwce0mbc9:hoalcufadcd4cbawEgDadfgrcKcaawEgqaraq0Egk6mbaicefhxavaialfgmar9Rgoad;8qbbcj;abad9Uc;WFbGcjdadca0EhPdndndnadTmbaoadfhscbhzinaeaz9nmdamax9RaD6miabazad2fhHaxaDfhOaPaeaz9RazaPfae6EgAcsfgocl4cifcd4hCavcj;cbfaoc9WGgXcetfhQavcj;cbfaXci2fhLavcj;cbfaXfhKcbhYaoc;ab6h8AincbhodnawTmbaxaYcd4fRbbhokaocFeGhEcbh3avcj;cbfh5indndndndnaEa3cet4ciGgoc9:fPdebdkamaO9RaX6mwavcj;cbfa3aX2faOaX;8qbbaOaAfhOxdkavcj;cbfa3aX2fcbaX;8kbxekamaO9RaC6moaoclVcbawEhraOaCfhocbhidna8Ambamao9Rc;Gb6mbcbhlina5alfhidndndndndndnaOalco4fRbbgqciGarfPDbedibledibkaipxbbbbbbbbbbbbbbbbpklbxlkaiaopbblaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLg8Ecdp:mea8EpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9og8Fpxiiiiiiiiiiiiiiiip8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngacitc:q1jjbfpbibaac:q:yjjbfRbbgapsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Nghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spklbaaaoclffahc:q:yjjbfRbbfhoxikaiaopbbwaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9og8Fpxssssssssssssssssp8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngacitc:q1jjbfpbibaac:q:yjjbfRbbgapsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Nghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spklbaaaocwffahc:q:yjjbfRbbfhoxdkaiaopbbbpklbaoczfhoxekaiaopbbdaoRbbgacitc:q1jjbfpbibaac:q:yjjbfRbbgapsaoRbeghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPpklbaaaocdffahc:q:yjjbfRbbfhokdndndndndndnaqcd4ciGarfPDbedibledibkaiczfpxbbbbbbbbbbbbbbbbpklbxlkaiczfaopbblaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLg8Ecdp:mea8EpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9og8Fpxiiiiiiiiiiiiiiiip8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngacitc:q1jjbfpbibaac:q:yjjbfRbbgapsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Nghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spklbaaaoclffahc:q:yjjbfRbbfhoxikaiczfaopbbwaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9og8Fpxssssssssssssssssp8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngacitc:q1jjbfpbibaac:q:yjjbfRbbgapsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Nghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spklbaaaocwffahc:q:yjjbfRbbfhoxdkaiczfaopbbbpklbaoczfhoxekaiczfaopbbdaoRbbgacitc:q1jjbfpbibaac:q:yjjbfRbbgapsaoRbeghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPpklbaaaocdffahc:q:yjjbfRbbfhokdndndndndndnaqcl4ciGarfPDbedibledibkaicafpxbbbbbbbbbbbbbbbbpklbxlkaicafaopbblaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLg8Ecdp:mea8EpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9og8Fpxiiiiiiiiiiiiiiiip8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngacitc:q1jjbfpbibaac:q:yjjbfRbbgapsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Nghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spklbaaaoclffahc:q:yjjbfRbbfhoxikaicafaopbbwaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9og8Fpxssssssssssssssssp8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngacitc:q1jjbfpbibaac:q:yjjbfRbbgapsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Nghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spklbaaaocwffahc:q:yjjbfRbbfhoxdkaicafaopbbbpklbaoczfhoxekaicafaopbbdaoRbbgacitc:q1jjbfpbibaac:q:yjjbfRbbgapsaoRbeghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPpklbaaaocdffahc:q:yjjbfRbbfhokdndndndndndnaqco4arfPDbedibledibkaic8Wfpxbbbbbbbbbbbbbbbbpklbxlkaic8Wfaopbblaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLg8Ecdp:mea8EpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9og8Fpxiiiiiiiiiiiiiiiip8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngicitc:q1jjbfpbibaic:q:yjjbfRbbgipsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Ngqcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spklbaiaoclffaqc:q:yjjbfRbbfhoxikaic8Wfaopbbwaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9og8Fpxssssssssssssssssp8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngicitc:q1jjbfpbibaic:q:yjjbfRbbgipsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Ngqcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spklbaiaocwffaqc:q:yjjbfRbbfhoxdkaic8Wfaopbbbpklbaoczfhoxekaic8WfaopbbdaoRbbgicitc:q1jjbfpbibaic:q:yjjbfRbbgipsaoRbegqcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPpklbaiaocdffaqc:q:yjjbfRbbfhokalc;abfhialcjefaX0meaihlamao9Rc;Fb0mbkkdnaiaX9pmbaici4hlinamao9RcK6mwa5aifhqdndndndndndnaOaico4fRbbalcoG4ciGarfPDbedibledibkaqpxbbbbbbbbbbbbbbbbpkbbxlkaqaopbblaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLg8Ecdp:mea8EpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9og8Fpxiiiiiiiiiiiiiiiip8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngacitc:q1jjbfpbibaac:q:yjjbfRbbgapsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Nghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spkbbaaaoclffahc:q:yjjbfRbbfhoxikaqaopbbwaopbbbg8Eclp:mea8EpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9og8Fpxssssssssssssssssp8Jg8Ep5b9cjF;8;4;W;G;ab9:9cU1:Ngacitc:q1jjbfpbibaac:q:yjjbfRbbgapsa8Ep5e9cjF;8;4;W;G;ab9:9cU1:Nghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPa8Fa8Ep9spkbbaaaocwffahc:q:yjjbfRbbfhoxdkaqaopbbbpkbbaoczfhoxekaqaopbbdaoRbbgacitc:q1jjbfpbibaac:q:yjjbfRbbgapsaoRbeghcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPpkbbaaaocdffahc:q:yjjbfRbbfhokalcdfhlaiczfgiaX6mbkkaohOaoTmoka5aXfh5a3cefg3cl9hmbkdndndndnawTmbasaYcd4fRbbglciGPlbedwbkaXTmdavcjdfaYfhlavaYfpbdbhgcbhoinalavcj;cbfaofpblbg8JaKaofpblbg8KpmbzeHdOiAlCvXoQrLg8LaQaofpblbg8MaLaofpblbg8NpmbzeHdOiAlCvXoQrLgypmbezHdiOAlvCXorQLg8Ecep9Ta8Epxeeeeeeeeeeeeeeeeg8Fp9op9Hp9rg8Eagp9Uggp9Abbbaladfglaga8Ea8Epmlvorlvorlvorlvorp9Uggp9Abbbaladfglaga8Ea8EpmwDqkwDqkwDqkwDqkp9Uggp9Abbbaladfglaga8Ea8EpmxmPsxmPsxmPsxmPsp9Uggp9Abbbaladfglaga8LaypmwDKYqk8AExm35Ps8E8Fg8Ecep9Ta8Ea8Fp9op9Hp9rg8Ep9Uggp9Abbbaladfglaga8Ea8Epmlvorlvorlvorlvorp9Uggp9Abbbaladfglaga8Ea8EpmwDqkwDqkwDqkwDqkp9Uggp9Abbbaladfglaga8Ea8EpmxmPsxmPsxmPsxmPsp9Uggp9Abbbaladfglaga8Ja8KpmwKDYq8AkEx3m5P8Es8Fg8Ja8Ma8NpmwKDYq8AkEx3m5P8Es8Fg8KpmbezHdiOAlvCXorQLg8Ecep9Ta8Ea8Fp9op9Hp9rg8Ep9Uggp9Abbbaladfglaga8Ea8Epmlvorlvorlvorlvorp9Uggp9Abbbaladfglaga8Ea8EpmwDqkwDqkwDqkwDqkp9Uggp9Abbbaladfglaga8Ea8EpmxmPsxmPsxmPsxmPsp9Uggp9Abbbaladfglaga8Ja8KpmwDKYqk8AExm35Ps8E8Fg8Ecep9Ta8Ea8Fp9op9Hp9rg8Ep9Ug8Fp9Abbbaladfgla8Fa8Ea8Epmlvorlvorlvorlvorp9Ug8Fp9Abbbaladfgla8Fa8Ea8EpmwDqkwDqkwDqkwDqkp9Ug8Fp9Abbbaladfgla8Fa8Ea8EpmxmPsxmPsxmPsxmPsp9Uggp9AbbbaladfhlaoczfgoaX6mbxikkaXTmeavcjdfaYfhlavaYfpbdbhgcbhoinalavcj;cbfaofpblbg8JaKaofpblbg8KpmbzeHdOiAlCvXoQrLg8LaQaofpblbg8MaLaofpblbg8NpmbzeHdOiAlCvXoQrLgypmbezHdiOAlvCXorQLg8Ecep:nea8Epxebebebebebebebebg8Fp9op:bep9rg8Eagp:oeggp9Abbbaladfglaga8Ea8Epmlvorlvorlvorlvorp:oeggp9Abbbaladfglaga8Ea8EpmwDqkwDqkwDqkwDqkp:oeggp9Abbbaladfglaga8Ea8EpmxmPsxmPsxmPsxmPsp:oeggp9Abbbaladfglaga8LaypmwDKYqk8AExm35Ps8E8Fg8Ecep:nea8Ea8Fp9op:bep9rg8Ep:oeggp9Abbbaladfglaga8Ea8Epmlvorlvorlvorlvorp:oeggp9Abbbaladfglaga8Ea8EpmwDqkwDqkwDqkwDqkp:oeggp9Abbbaladfglaga8Ea8EpmxmPsxmPsxmPsxmPsp:oeggp9Abbbaladfglaga8Ja8KpmwKDYq8AkEx3m5P8Es8Fg8Ja8Ma8NpmwKDYq8AkEx3m5P8Es8Fg8KpmbezHdiOAlvCXorQLg8Ecep:nea8Ea8Fp9op:bep9rg8Ep:oeggp9Abbbaladfglaga8Ea8Epmlvorlvorlvorlvorp:oeggp9Abbbaladfglaga8Ea8EpmwDqkwDqkwDqkwDqkp:oeggp9Abbbaladfglaga8Ea8EpmxmPsxmPsxmPsxmPsp:oeggp9Abbbaladfglaga8Ja8KpmwDKYqk8AExm35Ps8E8Fg8Ecep:nea8Ea8Fp9op:bep9rg8Ep:oeg8Fp9Abbbaladfgla8Fa8Ea8Epmlvorlvorlvorlvorp:oeg8Fp9Abbbaladfgla8Fa8Ea8EpmwDqkwDqkwDqkwDqkp:oeg8Fp9Abbbaladfgla8Fa8Ea8EpmxmPsxmPsxmPsxmPsp:oeggp9AbbbaladfhlaoczfgoaX6mbxdkkaXTmbcbhocbalcl4gl9Rc8FGhiavcjdfaYfhravaYfpbdbh8Finaravcj;cbfaofpblbggaKaofpblbg8JpmbzeHdOiAlCvXoQrLg8KaQaofpblbg8LaLaofpblbg8MpmbzeHdOiAlCvXoQrLg8NpmbezHdiOAlvCXorQLg8Eaip:Rea8Ealp:Sep9qg8Ea8Fp9rg8Fp9Abbbaradfgra8Fa8Ea8Epmlvorlvorlvorlvorp9rg8Fp9Abbbaradfgra8Fa8Ea8EpmwDqkwDqkwDqkwDqkp9rg8Fp9Abbbaradfgra8Fa8Ea8EpmxmPsxmPsxmPsxmPsp9rg8Fp9Abbbaradfgra8Fa8Ka8NpmwDKYqk8AExm35Ps8E8Fg8Eaip:Rea8Ealp:Sep9qg8Ep9rg8Fp9Abbbaradfgra8Fa8Ea8Epmlvorlvorlvorlvorp9rg8Fp9Abbbaradfgra8Fa8Ea8EpmwDqkwDqkwDqkwDqkp9rg8Fp9Abbbaradfgra8Fa8Ea8EpmxmPsxmPsxmPsxmPsp9rg8Fp9Abbbaradfgra8Faga8JpmwKDYq8AkEx3m5P8Es8Fgga8La8MpmwKDYq8AkEx3m5P8Es8Fg8JpmbezHdiOAlvCXorQLg8Eaip:Rea8Ealp:Sep9qg8Ep9rg8Fp9Abbbaradfgra8Fa8Ea8Epmlvorlvorlvorlvorp9rg8Fp9Abbbaradfgra8Fa8Ea8EpmwDqkwDqkwDqkwDqkp9rg8Fp9Abbbaradfgra8Fa8Ea8EpmxmPsxmPsxmPsxmPsp9rg8Fp9Abbbaradfgra8Faga8JpmwDKYqk8AExm35Ps8E8Fg8Eaip:Rea8Ealp:Sep9qg8Ep9rg8Fp9Abbbaradfgra8Fa8Ea8Epmlvorlvorlvorlvorp9rg8Fp9Abbbaradfgra8Fa8Ea8EpmwDqkwDqkwDqkwDqkp9rg8Fp9Abbbaradfgra8Fa8Ea8EpmxmPsxmPsxmPsxmPsp9rg8Fp9AbbbaradfhraoczfgoaX6mbkkaYclfgYad6mbkaHavcjdfaAad2;8qbbavavcjdfaAcufad2fad;8qbbaAazfhzc9:hoaOhxaOmbxlkkaeTmbaDalfhrcbhocuhlinaralaD9RglfaD6mdaPaeao9RaoaPfae6Eaofgoae6mbkaial9Rhxkcbc99amax9RakSEhoxekc9:hokavcj;kbf8Kjjjjbaokwbz:bjjjbk:TseHu8Jjjjjbc;ae9Rgv8Kjjjjbc9:hodnaeci9UgrcHfal0mbcuhoaiRbbgwc;WeGc;Ge9hmbawcsGgDce0mbavc;abfcFecje;8kbavcUf9cu83ibavc8Wf9cu83ibavcyf9cu83ibavcaf9cu83ibavcKf9cu83ibavczf9cu83ibav9cu83iwav9cu83ibaialfc9WfhqaicefgwarfhldnaeTmbcmcsaDceSEhkcbhxcbhmcbhrcbhicbhoindnalaq9nmbc9:hoxikdndnawRbbgDc;Ve0mbavc;abfaoaDcu7gPcl4fcsGcitfgsydlhzasydbhHdndnaDcsGgsak9pmbavaiaPfcsGcdtfydbaxasEhDaxasTgOfhxxekdndnascsSmbcehOasc987asamffcefhDxekalcefhDal8SbbgscFeGhPdndnascu9mmbaDhlxekalcvfhlaPcFbGhPcrhsdninaD8SbbgOcFbGastaPVhPaOcu9kmeaDcefhDascrfgsc8J9hmbxdkkaDcefhlkcehOaPce4cbaPceG9R7amfhDkaDhmkavc;abfaocitfgsaDBdbasazBdlavaicdtfaDBdbavc;abfaocefcsGcitfgsaHBdbasaDBdlaocdfhoaOaifhidnadcd9hmbabarcetfgsaH87ebasclfaD87ebascdfaz87ebxdkabarcdtfgsaHBdbascwfaDBdbasclfazBdbxekdnaDcpe0mbaxcefgOavaiaqaDcsGfRbbgscl49RcsGcdtfydbascz6gPEhDavaias9RcsGcdtfydbaOaPfgzascsGgOEhsaOThOdndnadcd9hmbabarcetfgHax87ebaHclfas87ebaHcdfaD87ebxekabarcdtfgHaxBdbaHcwfasBdbaHclfaDBdbkavaicdtfaxBdbavc;abfaocitfgHaDBdbaHaxBdlavaicefgicsGcdtfaDBdbavc;abfaocefcsGcitfgHasBdbaHaDBdlavaiaPfgicsGcdtfasBdbavc;abfaocdfcsGcitfgDaxBdbaDasBdlaocifhoaiaOfhiazaOfhxxekaxcbalRbbgHEgAaDc;:eSgDfhzaHcsGhCaHcl4hXdndnaHcs0mbazcefhOxekazhOavaiaX9RcsGcdtfydbhzkdndnaCmbaOcefhxxekaOhxavaiaH9RcsGcdtfydbhOkdndnaDTmbalcefhDxekalcdfhDal8SbegPcFeGhsdnaPcu9kmbalcofhAascFbGhscrhldninaD8SbbgPcFbGaltasVhsaPcu9kmeaDcefhDalcrfglc8J9hmbkaAhDxekaDcefhDkasce4cbasceG9R7amfgmhAkdndnaXcsSmbaDhsxekaDcefhsaD8SbbglcFeGhPdnalcu9kmbaDcvfhzaPcFbGhPcrhldninas8SbbgDcFbGaltaPVhPaDcu9kmeascefhsalcrfglc8J9hmbkazhsxekascefhskaPce4cbaPceG9R7amfgmhzkdndnaCcsSmbashlxekascefhlas8SbbgDcFeGhPdnaDcu9kmbascvfhOaPcFbGhPcrhDdninal8SbbgscFbGaDtaPVhPascu9kmealcefhlaDcrfgDc8J9hmbkaOhlxekalcefhlkaPce4cbaPceG9R7amfgmhOkdndnadcd9hmbabarcetfgDaA87ebaDclfaO87ebaDcdfaz87ebxekabarcdtfgDaABdbaDcwfaOBdbaDclfazBdbkavc;abfaocitfgDazBdbaDaABdlavaicdtfaABdbavc;abfaocefcsGcitfgDaOBdbaDazBdlavaicefgicsGcdtfazBdbavc;abfaocdfcsGcitfgDaABdbaDaOBdlavaiaHcz6aXcsSVfgicsGcdtfaOBdbaiaCTaCcsSVfhiaocifhokawcefhwaocsGhoaicsGhiarcifgrae6mbkkcbc99alaqSEhokavc;aef8Kjjjjbaok:clevu8Jjjjjbcz9Rhvdnaecvfal9nmbc9:skdnaiRbbc;:eGc;qeSmbcuskav9cb83iwaicefhoaialfc98fhrdnaeTmbdnadcdSmbcbhwindnaoar6mbc9:skaocefhlao8SbbgicFeGhddndnaicu9mmbalhoxekaocvfhoadcFbGhdcrhidninal8SbbgDcFbGaitadVhdaDcu9kmealcefhlaicrfgic8J9hmbxdkkalcefhokabawcdtfadc8Etc8F91adcd47avcwfadceGcdtVglydbfgiBdbalaiBdbawcefgwae9hmbxdkkcbhwindnaoar6mbc9:skaocefhlao8SbbgicFeGhddndnaicu9mmbalhoxekaocvfhoadcFbGhdcrhidninal8SbbgDcFbGaitadVhdaDcu9kmealcefhlaicrfgic8J9hmbxdkkalcefhokabawcetfadc8Etc8F91adcd47avcwfadceGcdtVglydbfgi87ebalaiBdbawcefgwae9hmbkkcbc99aoarSEk:2Pliur97eue978Jjjjjbc8W9Rhiaec98Ghldndnadcl9hmbdnalTmbcbhvabhdinadadpbbbgocKp:RecKp:Sep;6egraocwp:RecKp:Sep;6earp;Geaoczp:RecKp:Sep;6egwp;Gep;Kep;LegDpxbbbbbbbbbbbbbbbbp:2egqarpxbbbjbbbjbbbjbbbjgkp9op9rp;Kegrpxbb;:9cbb;:9cbb;:9cbb;:9cararp;MeaDaDp;Meawaqawakp9op9rp;Kegrarp;Mep;Kep;Kep;Jep;Negwp;Mepxbbn0bbn0bbn0bbn0gqp;KepxFbbbFbbbFbbbFbbbp9oaopxbbbFbbbFbbbFbbbFp9op9qarawp;Meaqp;Kecwp:RepxbFbbbFbbbFbbbFbbp9op9qaDawp;Meaqp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qpkbbadczfhdavclfgval6mbkkalaeSmeaipxbbbbbbbbbbbbbbbbgqpklbaiabalcdtfgdaeciGglcdtgv;8qbbdnalTmbaiaipblbgocKp:RecKp:Sep;6egraocwp:RecKp:Sep;6earp;Geaoczp:RecKp:Sep;6egwp;Gep;Kep;LegDaqp:2egqarpxbbbjbbbjbbbjbbbjgkp9op9rp;Kegrpxbb;:9cbb;:9cbb;:9cbb;:9cararp;MeaDaDp;Meawaqawakp9op9rp;Kegrarp;Mep;Kep;Kep;Jep;Negwp;Mepxbbn0bbn0bbn0bbn0gqp;KepxFbbbFbbbFbbbFbbbp9oaopxbbbFbbbFbbbFbbbFp9op9qarawp;Meaqp;Kecwp:RepxbFbbbFbbbFbbbFbbp9op9qaDawp;Meaqp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qpklbkadaiav;8qbbskaipxFubbFubbFubbFubbgxpklbdnalTmbcbhvabhdinadczfgmampbbbgopxbbbbbbFFbbbbbbFFgkp9oadpbbbgDaopmbediwDqkzHOAKY8AEgwczp:Reczp:Sep;6egraipblbaDaopmlvorxmPsCXQL358E8Fp9op;6eawczp:Sep;6egwp;Gearp;Gep;Kep;Legopxbbbbbbbbbbbbbbbbp:2egqarpxbbbjbbbjbbbjbbbjgPp9op9rp;Kegrpxb;:FSb;:FSb;:FSb;:FSararp;Meaoaop;MeawaqawaPp9op9rp;Kegrarp;Mep;Kep;Kep;Jep;Negwp;Mepxbbn0bbn0bbn0bbn0gqp;KepxFFbbFFbbFFbbFFbbp9oaoawp;Meaqp;Keczp:Rep9qgoarawp;Meaqp;KepxFFbbFFbbFFbbFFbbp9ogrpmwDKYqk8AExm35Ps8E8Fp9qpkbbadaDakp9oaoarpmbezHdiOAlvCXorQLp9qpkbbadcafhdavclfgval6mbkkalaeSmbaiczfpxbbbbbbbbbbbbbbbbgopklbaiaopklbaiabalcitfgdaeciGglcitgv;8qbbaiaxpkladnalTmbaiaipblzgopxbbbbbbFFbbbbbbFFgkp9oaipblbgDaopmbediwDqkzHOAKY8AEgwczp:Reczp:Sep;6egraipblaaDaopmlvorxmPsCXQL358E8Fp9op;6eawczp:Sep;6egwp;Gearp;Gep;Kep;Legopxbbbbbbbbbbbbbbbbp:2egqarpxbbbjbbbjbbbjbbbjgPp9op9rp;Kegrpxb;:FSb;:FSb;:FSb;:FSararp;Meaoaop;MeawaqawaPp9op9rp;Kegrarp;Mep;Kep;Kep;Jep;Negwp;Mepxbbn0bbn0bbn0bbn0gqp;KepxFFbbFFbbFFbbFFbbp9oaoawp;Meaqp;Keczp:Rep9qgoarawp;Meaqp;KepxFFbbFFbbFFbbFFbbp9ogrpmwDKYqk8AExm35Ps8E8Fp9qpklzaiaDakp9oaoarpmbezHdiOAlvCXorQLp9qpklbkadaiav;8qbbkk:Iwllue97euo978Jjjjjbca9Rhidnaec98GglTmbcbhvabhoinaocKfpx:ji:1S:ji:1S:ji:1S:ji:1SaopbbbgraoczfgwpbbbgDpmlvorxmPsCXQL358E8Fgqczp:Segkpxibbbibbbibbbibbbp9qgxp;6ep;Negmaxaxp:1ep;7egxaxp;KearaDpmbediwDqkzHOAKY8AEgxczp:Reczp:Sep;6egrarp;Meaxczp:Sep;6egDaDp;Meaqczp:Reczp:Sep;6egqaqp;Mep;Kep;Kep;Lepxbbbbbbbbbbbbbbbbp:4ep;Jep;Mepxbbn0bbn0bbn0bbn0gxp;KepxFFbbFFbbFFbbFFbbgPp9oamaDp;Meaxp;Keczp:Rep9qgDamarp;Meaxp;KeaPp9oamaqp;Meaxp;Keczp:Rep9qgxpmwDKYqk8AExm35Ps8E8Fgrp5eakclp:RegmpEi:T:j83ibawarp5bampEd:T:j83ibaocwfaDaxpmbezHdiOAlvCXorQLgxp5eampEe:T:j83ibaoaxp5bampEb:T:j83ibaocafhoavclfgval6mbkkdnalaeSmbaiczfpxbbbbbbbbbbbbbbbbgmpklbaiampklbaiabalcitfgoaeciGgvcitgw;8qbbdnavTmbaipx:ji:1S:ji:1S:ji:1S:ji:1SaipblbgraipblzgDpmlvorxmPsCXQL358E8Fgqczp:Segkpxibbbibbbibbbibbbp9qgxp;6ep;Negmaxaxp:1ep;7egxaxp;KearaDpmbediwDqkzHOAKY8AEgxczp:Reczp:Sep;6egrarp;Meaxczp:Sep;6egDaDp;Meaqczp:Reczp:Sep;6egqaqp;Mep;Kep;Kep;Lepxbbbbbbbbbbbbbbbbp:4ep;Jep;Mepxbbn0bbn0bbn0bbn0gxp;KepxFFbbFFbbFFbbFFbbgPp9oamaDp;Meaxp;Keczp:Rep9qgDamarp;Meaxp;KeaPp9oamaqp;Meaxp;Keczp:Rep9qgxpmwDKYqk8AExm35Ps8E8Fgrp5eakclp:RegmpEi:T:j83iKaiarp5bampEd:T:j83izaiaDaxpmbezHdiOAlvCXorQLgxp5eampEe:T:j83iwaiaxp5bampEb:T:j83ibkaoaiaw;8qbbkk;uddiue978Jjjjjbc;ab9Rhidnadcd4ae2glc98GgvTmbcbheabhdinadadpbbbgocwp:Recwp:Sep;6eaocep:SepxbbjFbbjFbbjFbbjFp9opxbbjZbbjZbbjZbbjZp:Uep;Mepkbbadczfhdaeclfgeav6mbkkdnavalSmbaic8WfpxbbbbbbbbbbbbbbbbgopklbaicafaopklbaiczfaopklbaiaopklbaiabavcdtfgdalciGgecdtgv;8qbbdnaeTmbaiaipblbgocwp:Recwp:Sep;6eaocep:SepxbbjFbbjFbbjFbbjFp9opxbbjZbbjZbbjZbbjZp:Uep;Mepklbkadaiav;8qbbkk:CPvdue97euw97eu8Jjjjjbc8W9Rhiaec98Ghldndnadcl9hmbaipxbbbbbbbbbbbbbbbbgvpklbdnalTmbcbhoabhdinadpbbbhradpxbbuJbbuJbbuJbbuJaipblbarcKp:Tep9qgwcep:Seawp9qgDcdp:SeaDp9qgDclp:SeaDp9qgqp;6ep;NegDarcwp:RecKp:SegkarpxFbbbFbbbFbbbFbbbgxp9ogmp:Uep;6ep;Mepxbbn0bbn0bbn0bbn0gPp;Kecwp:RepxbFbbbFbbbFbbbFbbp9oaDamakp:Xearczp:RecKp:Segrp:Uep;6ep;MeaPp;Keaxp9op9qaDamakarp:Uep:Xep;6ep;MeaPp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qaDaqawcep:Rep9oawpxebbbebbbebbbebbbp9op9qp;6ep;MeaPp;KecKp:Rep9qpkbbadczfhdaoclfgoal6mbkkalaeSmeaiavpklaaicafabalcdtfgdaeciGglcdtgo;8qbbaiavpklbdnalTmbaipblahraipxbbuJbbuJbbuJbbuJaipblbarcKp:Tep9qgwcep:Seawp9qgDcdp:SeaDp9qgDclp:SeaDp9qgqp;6ep;NegDarcwp:RecKp:SegkarpxFbbbFbbbFbbbFbbbgxp9ogmp:Uep;6ep;Mepxbbn0bbn0bbn0bbn0gPp;Kecwp:RepxbFbbbFbbbFbbbFbbp9oaDamakp:Xearczp:RecKp:Segrp:Uep;6ep;MeaPp;Keaxp9op9qaDamakarp:Uep:Xep;6ep;MeaPp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qaDaqawcep:Rep9oawpxebbbebbbebbbebbbp9op9qp;6ep;MeaPp;KecKp:Rep9qpklakadaicafao;8qbbskaipxbbbbbbbbbbbbbbbbgvpklbdnalTmbcbhoabhdinadczfgspxbFu9hbFu9hbFu9hbFu9hadpbbbgDaspbbbgPpmlvorxmPsCXQL358E8Fgmczp:Teaipblbp9qgrcep:Searp9qgwcdp:Seawp9qgwclp:Seawp9qgwcwp:Seawp9qgqp;6ep;NegwaDaPpmbediwDqkzHOAKY8AEgDpxFFbbFFbbFFbbFFbbgPp9ogkaDczp:Segxp:Ueamczp:Reczp:Segmp:Xep;6ep;Mepxbbn0bbn0bbn0bbn0gDp;KeaPp9oawakaxamp:Uep:Xep;6ep;MeaDp;Keczp:Rep9qgxawaqarcep:Rep9oarpxebbbebbbebbbebbbp9op9qp;6ep;MeaDp;Keczp:Reawamakp:Uep;6ep;MeaDp;KeaPp9op9qgrpmwDKYqk8AExm35Ps8E8FpkbbadaxarpmbezHdiOAlvCXorQLpkbbadcafhdaoclfgoal6mbkkalaeSmbaiczfpxbbbbbbbbbbbbbbbbgrpklbaiarpklbaiabalcitfgdaeciGglcitgo;8qbbaiavpkladnalTmbaipxbFu9hbFu9hbFu9hbFu9haipblbgDaipblzgPpmlvorxmPsCXQL358E8Fgmczp:Teaipblap9qgrcep:Searp9qgwcdp:Seawp9qgwclp:Seawp9qgwcwp:Seawp9qgqp;6ep;NegwaDaPpmbediwDqkzHOAKY8AEgDpxFFbbFFbbFFbbFFbbgPp9ogkaDczp:Segxp:Ueamczp:Reczp:Segmp:Xep;6ep;Mepxbbn0bbn0bbn0bbn0gDp;KeaPp9oawakaxamp:Uep:Xep;6ep;MeaDp;Keczp:Rep9qgxawaqarcep:Rep9oarpxebbbebbbebbbebbbp9op9qp;6ep;MeaDp;Keczp:Reawamakp:Uep;6ep;MeaDp;KeaPp9op9qgrpmwDKYqk8AExm35Ps8E8FpklzaiaxarpmbezHdiOAlvCXorQLpklbkadaiao;8qbbkk9teiucbcbydj1jjbgeabcifc98GfgbBdj1jjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaikkkebcjwklz:Dbb'; // embed! simd
var detector = new Uint8Array([
0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 3, 2, 0, 0, 5, 3, 1, 0, 1, 12, 1, 0, 10, 22, 2, 12, 0, 65, 0, 65, 0, 65, 0, 252, 10, 0, 0,
11, 7, 0, 65, 0, 253, 15, 26, 11,
]);
var wasmpack = new Uint8Array([
32, 0, 65, 2, 1, 106, 34, 33, 3, 128, 11, 4, 13, 64, 6, 253, 10, 7, 15, 116, 127, 5, 8, 12, 40, 16, 19, 54, 20, 9, 27, 255, 113, 17, 42, 67,
24, 23, 146, 148, 18, 14, 22, 45, 70, 69, 56, 114, 101, 21, 25, 63, 75, 136, 108, 28, 118, 29, 73, 115,
]);
if (typeof WebAssembly !== 'object') {
return {
supported: false,
};
}
var wasm = WebAssembly.validate(detector) ? unpack(wasm_simd) : unpack(wasm_base);
var instance;
var ready = WebAssembly.instantiate(wasm, {}).then(function (result) {
instance = result.instance;
instance.exports.__wasm_call_ctors();
});
function unpack(data) {
var result = new Uint8Array(data.length);
for (var i = 0; i < data.length; ++i) {
var ch = data.charCodeAt(i);
result[i] = ch > 96 ? ch - 97 : ch > 64 ? ch - 39 : ch + 4;
}
var write = 0;
for (var i = 0; i < data.length; ++i) {
result[write++] = result[i] < 60 ? wasmpack[result[i]] : (result[i] - 60) * 64 + result[++i];
}
return result.buffer.slice(0, write);
}
function decode(instance, fun, target, count, size, source, filter) {
var sbrk = instance.exports.sbrk;
var count4 = (count + 3) & ~3;
var tp = sbrk(count4 * size);
var sp = sbrk(source.length);
var heap = new Uint8Array(instance.exports.memory.buffer);
heap.set(source, sp);
var res = fun(tp, count, size, sp, source.length);
if (res == 0 && filter) {
filter(tp, count4, size);
}
target.set(heap.subarray(tp, tp + count * size));
sbrk(tp - sbrk(0));
if (res != 0) {
throw new Error('Malformed buffer data: ' + res);
}
}
var filters = {
NONE: '',
OCTAHEDRAL: 'meshopt_decodeFilterOct',
QUATERNION: 'meshopt_decodeFilterQuat',
EXPONENTIAL: 'meshopt_decodeFilterExp',
COLOR: 'meshopt_decodeFilterColor',
};
var decoders = {
ATTRIBUTES: 'meshopt_decodeVertexBuffer',
TRIANGLES: 'meshopt_decodeIndexBuffer',
INDICES: 'meshopt_decodeIndexSequence',
};
var workers = [];
var requestId = 0;
function createWorker(url) {
var worker = {
object: new Worker(url),
pending: 0,
requests: {},
};
worker.object.onmessage = function (event) {
var data = event.data;
worker.pending -= data.count;
worker.requests[data.id][data.action](data.value);
delete worker.requests[data.id];
};
return worker;
}
function initWorkers(count) {
var source =
'self.ready = WebAssembly.instantiate(new Uint8Array([' +
new Uint8Array(wasm) +
']), {})' +
'.then(function(result) { result.instance.exports.__wasm_call_ctors(); return result.instance; });' +
'self.onmessage = ' +
workerProcess.name +
';' +
decode.toString() +
workerProcess.toString();
var blob = new Blob([source], { type: 'text/javascript' });
var url = URL.createObjectURL(blob);
for (var i = workers.length; i < count; ++i) {
workers[i] = createWorker(url);
}
for (var i = count; i < workers.length; ++i) {
workers[i].object.postMessage({});
}
workers.length = count;
URL.revokeObjectURL(url);
}
function decodeWorker(count, size, source, mode, filter) {
var worker = workers[0];
for (var i = 1; i < workers.length; ++i) {
if (workers[i].pending < worker.pending) {
worker = workers[i];
}
}
return new Promise(function (resolve, reject) {
var data = new Uint8Array(source);
var id = ++requestId;
worker.pending += count;
worker.requests[id] = { resolve: resolve, reject: reject };
worker.object.postMessage({ id: id, count: count, size: size, source: data, mode: mode, filter: filter }, [data.buffer]);
});
}
function workerProcess(event) {
var data = event.data;
if (!data.id) {
return self.close();
}
self.ready.then(function (instance) {
try {
var target = new Uint8Array(data.count * data.size);
decode(instance, instance.exports[data.mode], target, data.count, data.size, data.source, instance.exports[data.filter]);
self.postMessage({ id: data.id, count: data.count, action: 'resolve', value: target }, [target.buffer]);
} catch (error) {
self.postMessage({ id: data.id, count: data.count, action: 'reject', value: error });
}
});
}
return {
ready: ready,
supported: true,
useWorkers: function (count) {
initWorkers(count);
},
decodeVertexBuffer: function (target, count, size, source, filter) {
decode(instance, instance.exports.meshopt_decodeVertexBuffer, target, count, size, source, instance.exports[filters[filter]]);
},
decodeIndexBuffer: function (target, count, size, source) {
decode(instance, instance.exports.meshopt_decodeIndexBuffer, target, count, size, source);
},
decodeIndexSequence: function (target, count, size, source) {
decode(instance, instance.exports.meshopt_decodeIndexSequence, target, count, size, source);
},
decodeGltfBuffer: function (target, count, size, source, mode, filter) {
decode(instance, instance.exports[decoders[mode]], target, count, size, source, instance.exports[filters[filter]]);
},
decodeGltfBufferAsync: function (count, size, source, mode, filter) {
if (workers.length > 0) {
return decodeWorker(count, size, source, decoders[mode], filters[filter]);
}
return ready.then(function () {
var target = new Uint8Array(count * size);
decode(instance, instance.exports[decoders[mode]], target, count, size, source, instance.exports[filters[filter]]);
return target;
});
},
};
})();
export { MeshoptDecoder };
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
js/meshopt_decoder.test.js | JavaScript | import assert from 'assert/strict';
import { MeshoptDecoder as decoder } from './meshopt_decoder.mjs';
process.on('unhandledRejection', (error) => {
console.log('unhandledRejection', error);
process.exit(1);
});
var tests = {
decodeVertexBuffer: function () {
var encoded = new Uint8Array([
0xa0, 0x01, 0x3f, 0x00, 0x00, 0x00, 0x58, 0x57, 0x58, 0x01, 0x26, 0x00, 0x00, 0x00, 0x01, 0x0c, 0x00, 0x00, 0x00, 0x58, 0x01, 0x08, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x3f, 0x00, 0x00, 0x00, 0x17, 0x18, 0x17, 0x01, 0x26, 0x00, 0x00, 0x00, 0x01, 0x0c, 0x00, 0x00,
0x00, 0x17, 0x01, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
]);
var expected = new Uint8Array([
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 44, 1, 0, 0, 0, 0, 0, 0, 244, 1, 0, 0, 0, 0, 44, 1, 0, 0, 0, 0, 0, 0, 244, 1, 44, 1, 44, 1, 0, 0, 0,
0, 244, 1, 244, 1,
]);
var result = new Uint8Array(expected.length);
decoder.decodeVertexBuffer(result, 4, 12, encoded);
assert.deepStrictEqual(result, expected);
},
decodeVertexBuffer_More: function () {
var encoded = new Uint8Array([
0xa0, 0x00, 0x01, 0x2a, 0xaa, 0xaa, 0xaa, 0x02, 0x04, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x03, 0x00, 0x10, 0x10, 0x10, 0x10, 0x10,
0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
]);
var expected = new Uint8Array([
0, 0, 0, 0, 0, 1, 2, 8, 0, 2, 4, 16, 0, 3, 6, 24, 0, 4, 8, 32, 0, 5, 10, 40, 0, 6, 12, 48, 0, 7, 14, 56, 0, 8, 16, 64, 0, 9, 18, 72, 0,
10, 20, 80, 0, 11, 22, 88, 0, 12, 24, 96, 0, 13, 26, 104, 0, 14, 28, 112, 0, 15, 30, 120,
]);
var result = new Uint8Array(expected.length);
decoder.decodeVertexBuffer(result, 16, 4, encoded);
assert.deepStrictEqual(result, expected);
},
decodeVertexBuffer_Mode2: function () {
var encoded = new Uint8Array([
0xa0, 0x02, 0x08, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x02, 0x0a, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x02, 0x0c, 0xcc, 0xcc,
0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x02, 0x0e, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
]);
var expected = new Uint8Array([
0, 0, 0, 0, 4, 5, 6, 7, 8, 10, 12, 14, 12, 15, 18, 21, 16, 20, 24, 28, 20, 25, 30, 35, 24, 30, 36, 42, 28, 35, 42, 49, 32, 40, 48, 56, 36,
45, 54, 63, 40, 50, 60, 70, 44, 55, 66, 77, 48, 60, 72, 84, 52, 65, 78, 91, 56, 70, 84, 98, 60, 75, 90, 105,
]);
var result = new Uint8Array(expected.length);
decoder.decodeVertexBuffer(result, 16, 4, encoded);
assert.deepStrictEqual(result, expected);
},
decodeVertexBufferV1: function () {
var encoded = new Uint8Array([
0xa1, 0xee, 0xaa, 0xee, 0x00, 0x4b, 0x4b, 0x4b, 0x00, 0x00, 0x4b, 0x00, 0x00, 0x7d, 0x7d, 0x7d, 0x00, 0x00, 0x7d, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x00, 0x62,
]);
var expected = new Uint8Array([
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 44, 1, 0, 0, 0, 0, 0, 0, 244, 1, 0, 0, 0, 0, 44, 1, 0, 0, 0, 0, 0, 0, 244, 1, 44, 1, 44, 1, 0, 0, 0,
0, 244, 1, 244, 1,
]);
var result = new Uint8Array(expected.length);
decoder.decodeVertexBuffer(result, 4, 12, encoded);
assert.deepStrictEqual(result, expected);
},
decodeVertexBufferV1_Custom: function () {
var encoded = new Uint8Array([
0xa1, 0xd4, 0x94, 0xd4, 0x01, 0x0e, 0x00, 0x58, 0x57, 0x58, 0x02, 0x02, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x58,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x7d, 0x7d,
0x7d, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x62,
]);
var expected = new Uint8Array([
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 44, 1, 0, 0, 0, 0, 0, 0, 244, 1, 0, 0, 0, 0, 44, 1, 0, 0, 0, 0, 0, 0, 244, 1, 44, 1, 44, 1, 0, 0, 0,
0, 244, 1, 244, 1,
]);
var result = new Uint8Array(expected.length);
decoder.decodeVertexBuffer(result, 4, 12, encoded);
assert.deepStrictEqual(result, expected);
},
decodeVertexBufferV1_Deltas: function () {
var encoded = new Uint8Array([
0xa1, 0x99, 0x99, 0x01, 0x2a, 0xaa, 0xaa, 0xaa, 0x02, 0x04, 0x44, 0x44, 0x44, 0x43, 0x33, 0x33, 0x33, 0x02, 0x06, 0x66, 0x66, 0x66, 0x66,
0x66, 0x66, 0x66, 0x02, 0x08, 0x88, 0x88, 0x88, 0x87, 0x77, 0x77, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xf8, 0x00, 0xf8, 0x00, 0xf0, 0x00, 0xf0, 0x00, 0x01, 0x01,
]);
var expected = new Uint16Array([
248, 248, 240, 240, 249, 250, 243, 244, 250, 252, 246, 248, 251, 254, 249, 252, 252, 256, 252, 256, 253, 258, 255, 260, 254, 260, 258,
264, 255, 262, 261, 268, 256, 264, 264, 272, 257, 262, 267, 268, 258, 260, 270, 264, 259, 258, 273, 260, 260, 256, 276, 256, 261, 254,
279, 252, 262, 252, 282, 248, 263, 250, 285, 244,
]);
var result = new Uint16Array(expected.length);
decoder.decodeVertexBuffer(new Uint8Array(result.buffer), 16, 8, encoded);
assert.deepStrictEqual(result, expected);
},
decodeIndexBuffer16: function () {
var encoded = new Uint8Array([
0xe0, 0xf0, 0x10, 0xfe, 0xff, 0xf0, 0x0c, 0xff, 0x02, 0x02, 0x02, 0x00, 0x76, 0x87, 0x56, 0x67, 0x78, 0xa9, 0x86, 0x65, 0x89, 0x68, 0x98,
0x01, 0x69, 0x00, 0x00,
]);
var expected = new Uint16Array([0, 1, 2, 2, 1, 3, 4, 6, 5, 7, 8, 9]);
var result = new Uint16Array(expected.length);
decoder.decodeIndexBuffer(new Uint8Array(result.buffer), 12, 2, encoded);
assert.deepEqual(result, expected);
},
decodeIndexBuffer32: function () {
var encoded = new Uint8Array([
0xe0, 0xf0, 0x10, 0xfe, 0xff, 0xf0, 0x0c, 0xff, 0x02, 0x02, 0x02, 0x00, 0x76, 0x87, 0x56, 0x67, 0x78, 0xa9, 0x86, 0x65, 0x89, 0x68, 0x98,
0x01, 0x69, 0x00, 0x00,
]);
var expected = new Uint32Array([0, 1, 2, 2, 1, 3, 4, 6, 5, 7, 8, 9]);
var result = new Uint32Array(expected.length);
decoder.decodeIndexBuffer(new Uint8Array(result.buffer), 12, 4, encoded);
assert.deepStrictEqual(result, expected);
},
decodeIndexBufferV1: function () {
var encoded = new Uint8Array([
0xe1, 0xf0, 0x10, 0xfe, 0x1f, 0x3d, 0x00, 0x0a, 0x00, 0x76, 0x87, 0x56, 0x67, 0x78, 0xa9, 0x86, 0x65, 0x89, 0x68, 0x98, 0x01, 0x69, 0x00,
0x00,
]);
var expected = new Uint32Array([0, 1, 2, 2, 1, 3, 0, 1, 2, 2, 1, 5, 2, 1, 4]);
var result = new Uint32Array(expected.length);
decoder.decodeIndexBuffer(new Uint8Array(result.buffer), 15, 4, encoded);
assert.deepStrictEqual(result, expected);
},
decodeIndexBufferV1_More: function () {
var encoded = new Uint8Array([
0xe1, 0xf0, 0x10, 0xfe, 0xff, 0xf0, 0x0c, 0xff, 0x02, 0x02, 0x02, 0x00, 0x76, 0x87, 0x56, 0x67, 0x78, 0xa9, 0x86, 0x65, 0x89, 0x68, 0x98,
0x01, 0x69, 0x00, 0x00,
]);
var expected = new Uint32Array([0, 1, 2, 2, 1, 3, 4, 6, 5, 7, 8, 9]);
var result = new Uint32Array(expected.length);
decoder.decodeIndexBuffer(new Uint8Array(result.buffer), 12, 4, encoded);
assert.deepStrictEqual(result, expected);
},
decodeIndexBufferV1_3Edges: function () {
var encoded = new Uint8Array([
0xe1, 0xf0, 0x20, 0x30, 0x40, 0x00, 0x76, 0x87, 0x56, 0x67, 0x78, 0xa9, 0x86, 0x65, 0x89, 0x68, 0x98, 0x01, 0x69, 0x00, 0x00,
]);
var expected = new Uint32Array([0, 1, 2, 1, 0, 3, 2, 1, 4, 0, 2, 5]);
var result = new Uint32Array(expected.length);
decoder.decodeIndexBuffer(new Uint8Array(result.buffer), 12, 4, encoded);
assert.deepStrictEqual(result, expected);
},
decodeIndexSequence: function () {
var encoded = new Uint8Array([0xd1, 0x00, 0x04, 0xcd, 0x01, 0x04, 0x07, 0x98, 0x1f, 0x00, 0x00, 0x00, 0x00]);
var expected = new Uint32Array([0, 1, 51, 2, 49, 1000]);
var result = new Uint32Array(expected.length);
decoder.decodeIndexSequence(new Uint8Array(result.buffer), 6, 4, encoded);
assert.deepStrictEqual(result, expected);
},
decodeFilterOct8: function () {
var encoded = new Uint8Array([
0xa0, 0x01, 0x07, 0x00, 0x00, 0x00, 0x1e, 0x01, 0x3f, 0x00, 0x00, 0x00, 0x8b, 0x8c, 0xfd, 0x00, 0x01, 0x26, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x01, 0x7f, 0x00,
]);
var expected = new Uint8Array([0, 1, 127, 0, 0, 159, 82, 1, 255, 1, 127, 0, 1, 130, 241, 1]);
var result = new Uint8Array(expected.length);
decoder.decodeVertexBuffer(new Uint8Array(result.buffer), 4, 4, encoded, /* filter= */ 'OCTAHEDRAL');
assert.deepStrictEqual(result, expected);
},
decodeFilterOct12: function () {
var encoded = new Uint8Array([
0xa0, 0x01, 0x0f, 0x00, 0x00, 0x00, 0x3d, 0x5a, 0x01, 0x0f, 0x00, 0x00, 0x00, 0x0e, 0x0d, 0x01, 0x3f, 0x00, 0x00, 0x00, 0x9a, 0x99, 0x26,
0x01, 0x3f, 0x00, 0x00, 0x00, 0x0e, 0x0d, 0x0a, 0x00, 0x00, 0x01, 0x26, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0xff, 0x07,
0x00, 0x00,
]);
var expected = new Uint16Array([0, 16, 32767, 0, 0, 32621, 3088, 1, 32764, 16, 471, 0, 307, 28541, 16093, 1]);
var result = new Uint16Array(expected.length);
decoder.decodeVertexBuffer(new Uint8Array(result.buffer), 4, 8, encoded, /* filter= */ 'OCTAHEDRAL');
assert.deepStrictEqual(result, expected);
},
decodeFilterQuat12: function () {
var encoded = new Uint8Array([
0xa0, 0x01, 0x0f, 0x00, 0x00, 0x00, 0x3d, 0x5a, 0x01, 0x0f, 0x00, 0x00, 0x00, 0x0e, 0x0d, 0x01, 0x3f, 0x00, 0x00, 0x00, 0x9a, 0x99, 0x26,
0x01, 0x3f, 0x00, 0x00, 0x00, 0x0e, 0x0d, 0x0a, 0x00, 0x00, 0x01, 0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0xfc, 0x07,
]);
var expected = new Uint16Array([32767, 0, 11, 0, 0, 25013, 0, 21166, 11, 0, 23504, 22830, 158, 14715, 0, 29277]);
var result = new Uint16Array(expected.length);
decoder.decodeVertexBuffer(new Uint8Array(result.buffer), 4, 8, encoded, /* filter= */ 'QUATERNION');
assert.deepStrictEqual(result, expected);
},
decodeFilterExp: function () {
var encoded = new Uint8Array([
0xa0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0xff, 0xf7, 0xff, 0xff, 0x02, 0xff,
0xff, 0x7f, 0xfe,
]);
var expected = new Uint32Array([0, 0x3fc00000, 0xc2100000, 0x49fffffe]);
var result = new Uint32Array(expected.length);
decoder.decodeVertexBuffer(new Uint8Array(result.buffer), 1, 16, encoded, /* filter= */ 'EXPONENTIAL');
assert.deepStrictEqual(result, expected);
},
decodeFilterColor8: function () {
var encoded = new Uint8Array([
0xa0, 0x01, 0x3f, 0x00, 0x00, 0x00, 0x7e, 0x7d, 0x4c, 0x01, 0x3f, 0x00, 0x00, 0x00, 0xfd, 0xfd, 0xfe, 0x01, 0x3f, 0x00, 0x00, 0x00, 0x83,
0x82, 0x80, 0x01, 0x3f, 0x00, 0x00, 0x00, 0x7d, 0x3f, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x7f, 0xc1, 0xff,
]);
var expected = new Uint8Array([254, 1, 0, 255, 0, 254, 0, 128, 1, 0, 255, 64, 102, 102, 102, 191]);
var result = new Uint8Array(expected.length);
decoder.decodeVertexBuffer(new Uint8Array(result.buffer), 4, 4, encoded, /* filter= */ 'COLOR');
assert.deepStrictEqual(result, expected);
},
decodeFilterColor12: function () {
var encoded = new Uint8Array([
0xa0, 0x01, 0x1b, 0x00, 0x00, 0x00, 0xcc, 0x01, 0x3f, 0x00, 0x00, 0x00, 0x06, 0x05, 0x04, 0x01, 0x29, 0x00, 0x00, 0x00, 0x01, 0x3f, 0x00,
0x00, 0x00, 0x0d, 0x0f, 0x10, 0x01, 0x38, 0x00, 0x00, 0x00, 0x03, 0x01, 0x3f, 0x00, 0x00, 0x00, 0x16, 0x15, 0x08, 0x01, 0x21, 0x00, 0x00,
0x00, 0x01, 0x3f, 0x00, 0x00, 0x00, 0x05, 0x03, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0xff, 0x07, 0x01, 0xfc, 0xff, 0x0f,
]);
var expected = new Uint16Array([65519, 16, 0, 65535, 0, 65519, 0, 32776, 16, 0, 65535, 16388, 26214, 26214, 26214, 49147]);
var result = new Uint16Array(expected.length);
decoder.decodeVertexBuffer(new Uint8Array(result.buffer), 4, 8, encoded, /* filter= */ 'COLOR');
assert.deepStrictEqual(result, expected);
},
decodeGltfBuffer: function () {
var encoded = new Uint8Array([
0xa0, 0x01, 0x3f, 0x00, 0x00, 0x00, 0x58, 0x57, 0x58, 0x01, 0x26, 0x00, 0x00, 0x00, 0x01, 0x0c, 0x00, 0x00, 0x00, 0x58, 0x01, 0x08, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x3f, 0x00, 0x00, 0x00, 0x17, 0x18, 0x17, 0x01, 0x26, 0x00, 0x00, 0x00, 0x01, 0x0c, 0x00, 0x00,
0x00, 0x17, 0x01, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
]);
var expected = new Uint8Array([
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 44, 1, 0, 0, 0, 0, 0, 0, 244, 1, 0, 0, 0, 0, 44, 1, 0, 0, 0, 0, 0, 0, 244, 1, 44, 1, 44, 1, 0, 0, 0,
0, 244, 1, 244, 1,
]);
var result = new Uint8Array(expected.length);
decoder.decodeGltfBuffer(result, 4, 12, encoded, /* mode= */ 'ATTRIBUTES');
assert.deepStrictEqual(result, expected);
},
decodeGltfBufferAsync: function () {
var encoded = new Uint8Array([
0xa0, 0x01, 0x3f, 0x00, 0x00, 0x00, 0x58, 0x57, 0x58, 0x01, 0x26, 0x00, 0x00, 0x00, 0x01, 0x0c, 0x00, 0x00, 0x00, 0x58, 0x01, 0x08, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x3f, 0x00, 0x00, 0x00, 0x17, 0x18, 0x17, 0x01, 0x26, 0x00, 0x00, 0x00, 0x01, 0x0c, 0x00, 0x00,
0x00, 0x17, 0x01, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
]);
var expected = new Uint8Array([
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 44, 1, 0, 0, 0, 0, 0, 0, 244, 1, 0, 0, 0, 0, 44, 1, 0, 0, 0, 0, 0, 0, 244, 1, 44, 1, 44, 1, 0, 0, 0,
0, 244, 1, 244, 1,
]);
decoder.decodeGltfBufferAsync(4, 12, encoded, /* mode= */ 'ATTRIBUTES').then(function (result) {
assert.deepStrictEqual(result, expected);
});
},
};
decoder.ready.then(() => {
var count = 0;
for (var key in tests) {
tests[key]();
count++;
}
console.log(count, 'tests passed');
});
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
js/meshopt_decoder_reference.js | JavaScript | // This file is part of meshoptimizer library and is distributed under the terms of MIT License.
// Copyright (C) 2016-2026, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
// This is the reference decoder implementation by Jasper St. Pierre.
// It follows the decoder interface and should be a drop-in replacement for the actual decoder from meshopt_decoder module
// It is provided for educational value and is not recommended for use in production because it's not performance-optimized.
const MeshoptDecoder = {};
MeshoptDecoder.supported = true;
MeshoptDecoder.ready = Promise.resolve();
function assert(cond) {
if (!cond) {
throw new Error('Assertion failed');
}
}
function dezig(v) {
return (v & 1) !== 0 ? ~(v >>> 1) : v >>> 1;
}
MeshoptDecoder.decodeVertexBuffer = (target, elementCount, byteStride, source, filter) => {
assert(source[0] === 0xa0 || source[0] === 0xa1);
const version = source[0] & 0x0f;
const maxBlockElements = Math.min((0x2000 / byteStride) & ~0x000f, 0x100);
const deltas = new Uint8Array(maxBlockElements * byteStride);
const tailSize = version === 0 ? byteStride : byteStride + byteStride / 4;
const tailDataOffs = source.length - tailSize;
// What deltas are stored relative to
const tempData = source.slice(tailDataOffs, tailDataOffs + byteStride);
// Channel modes for v1
const channels = version === 0 ? null : source.slice(tailDataOffs + byteStride, tailDataOffs + tailSize);
let srcOffs = 1; // Skip header byte
const headerModes = [
[0, 2, 4, 8], // v0
[0, 1, 2, 4], // v1, when control is 0
[1, 2, 4, 8], // v1, when control is 1
];
// Attribute blocks
for (let dstElemBase = 0; dstElemBase < elementCount; dstElemBase += maxBlockElements) {
const attrBlockElementCount = Math.min(elementCount - dstElemBase, maxBlockElements);
const groupCount = ((attrBlockElementCount + 0x0f) & ~0x0f) >>> 4;
const headerByteCount = ((groupCount + 0x03) & ~0x03) >>> 2;
// Control modes for v1
const controlBitsOffs = srcOffs;
srcOffs += version === 0 ? 0 : byteStride / 4;
// Zero out deltas to simplify logic
deltas.fill(0x00);
// Data blocks
for (let byte = 0; byte < byteStride; byte++) {
const deltaBase = byte * attrBlockElementCount;
// Control mode for current byte for v1
const controlMode = version === 0 ? 0 : (source[controlBitsOffs + (byte >>> 2)] >>> ((byte & 0x03) << 1)) & 0x03;
if (controlMode === 2) {
// All byte deltas are 0; no data is stored for this byte
continue;
} else if (controlMode === 3) {
// Byte deltas are stored uncompressed with no header bits
deltas.set(source.subarray(srcOffs, srcOffs + attrBlockElementCount), deltaBase);
srcOffs += attrBlockElementCount;
continue;
}
// Header bits are omitted for v1 when using control modes 2/3
const headerBitsOffs = srcOffs;
srcOffs += headerByteCount;
for (let group = 0; group < groupCount; group++) {
const mode = (source[headerBitsOffs + (group >>> 2)] >>> ((group & 0x03) << 1)) & 0x03;
const modeBits = headerModes[version === 0 ? 0 : controlMode + 1][mode];
const deltaOffs = deltaBase + (group << 4);
if (modeBits === 0) {
// All 16 byte deltas are 0; the size of the encoded block is 0 bytes
} else if (modeBits === 1) {
// Deltas are using 1-bit sentinel encoding; the size of the encoded block is [2..18] bytes
const srcBase = srcOffs;
srcOffs += 0x02;
for (let m = 0; m < 0x10; m++) {
// Bits are stored from least significant to most significant for 1-bit encoding
const shift = m & 0x07;
let delta = (source[srcBase + (m >>> 3)] >>> shift) & 0x01;
if (delta === 1) delta = source[srcOffs++];
deltas[deltaOffs + m] = delta;
}
} else if (modeBits === 2) {
// Deltas are using 2-bit sentinel encoding; the size of the encoded block is [4..20] bytes
const srcBase = srcOffs;
srcOffs += 0x04;
for (let m = 0; m < 0x10; m++) {
// 0 = >>> 6, 1 = >>> 4, 2 = >>> 2, 3 = >>> 0
const shift = 6 - ((m & 0x03) << 1);
let delta = (source[srcBase + (m >>> 2)] >>> shift) & 0x03;
if (delta === 3) delta = source[srcOffs++];
deltas[deltaOffs + m] = delta;
}
} else if (modeBits === 4) {
// Deltas are using 4-bit sentinel encoding; the size of the encoded block is [8..24] bytes
const srcBase = srcOffs;
srcOffs += 0x08;
for (let m = 0; m < 0x10; m++) {
// 0 = >>> 6, 1 = >>> 4, 2 = >>> 2, 3 = >>> 0
const shift = 4 - ((m & 0x01) << 2);
let delta = (source[srcBase + (m >>> 1)] >>> shift) & 0x0f;
if (delta === 0xf) delta = source[srcOffs++];
deltas[deltaOffs + m] = delta;
}
} else {
// All 16 byte deltas are stored verbatim; the size of the encoded block is 16 bytes
deltas.set(source.subarray(srcOffs, srcOffs + 0x10), deltaOffs);
srcOffs += 0x10;
}
}
}
// Go through and apply deltas to data
for (let elem = 0; elem < attrBlockElementCount; elem++) {
const dstElem = dstElemBase + elem;
for (let byteGroup = 0; byteGroup < byteStride; byteGroup += 4) {
let channelMode = version === 0 ? 0 : channels[byteGroup >>> 2] & 0x03;
assert(channelMode !== 0x03);
if (channelMode === 0) {
// Channel 0 (byte deltas): Byte deltas are stored as zigzag-encoded differences between the byte values of the element and the byte values of the previous element in the same position.
for (let byte = byteGroup; byte < byteGroup + 4; byte++) {
const delta = dezig(deltas[byte * attrBlockElementCount + elem]);
const temp = (tempData[byte] + delta) & 0xff; // wrap around
const dstOffs = dstElem * byteStride + byte;
target[dstOffs] = tempData[byte] = temp;
}
} else if (channelMode === 1) {
// Channel 1 (2-byte deltas): 2-byte deltas are computed as zigzag-encoded differences between 16-bit values of the element and the previous element in the same position.
for (let byte = byteGroup; byte < byteGroup + 4; byte += 2) {
const delta = dezig(deltas[byte * attrBlockElementCount + elem] + (deltas[(byte + 1) * attrBlockElementCount + elem] << 8));
let temp = tempData[byte] + (tempData[byte + 1] << 8);
temp = (temp + delta) & 0xffff; // wrap around
const dstOffs = dstElem * byteStride + byte;
target[dstOffs] = tempData[byte] = temp & 0xff;
target[dstOffs + 1] = tempData[byte + 1] = temp >>> 8;
}
} else if (channelMode === 2) {
// Channel 2 (4-byte XOR deltas): 4-byte deltas are computed as XOR between 32-bit values of the element and the previous element in the same position, with an additional rotation applied based on the high 4 bits of the channel mode byte.
const byte = byteGroup;
const delta =
deltas[byte * attrBlockElementCount + elem] +
(deltas[(byte + 1) * attrBlockElementCount + elem] << 8) +
(deltas[(byte + 2) * attrBlockElementCount + elem] << 16) +
(deltas[(byte + 3) * attrBlockElementCount + elem] << 24);
let temp = tempData[byte] + (tempData[byte + 1] << 8) + (tempData[byte + 2] << 16) + (tempData[byte + 3] << 24);
const rot = channels[byteGroup >>> 2] >>> 4;
temp = temp ^ ((delta >>> rot) | (delta << (32 - rot))); // rotate and XOR
const dstOffs = dstElem * byteStride + byte;
target[dstOffs] = tempData[byte] = temp & 0xff;
target[dstOffs + 1] = tempData[byte + 1] = (temp >>> 8) & 0xff;
target[dstOffs + 2] = tempData[byte + 2] = (temp >>> 16) & 0xff;
target[dstOffs + 3] = tempData[byte + 3] = temp >>> 24;
}
}
}
}
const tailSizePadded = Math.max(tailSize, version === 0 ? 32 : 24);
assert(srcOffs == source.length - tailSizePadded);
// Filters - only applied if filter isn't undefined or NONE
if (filter === 'OCTAHEDRAL') {
assert(byteStride === 4 || byteStride === 8);
const dst = byteStride === 4 ? new Int8Array(target.buffer) : new Int16Array(target.buffer);
const maxInt = byteStride === 4 ? 127 : 32767;
for (let i = 0; i < 4 * elementCount; i += 4) {
let x = dst[i + 0],
y = dst[i + 1],
one = dst[i + 2];
x /= one;
y /= one;
const z = 1.0 - Math.abs(x) - Math.abs(y);
const t = Math.max(-z, 0.0);
x -= x >= 0 ? t : -t;
y -= y >= 0 ? t : -t;
const h = maxInt / Math.hypot(x, y, z);
dst[i + 0] = Math.round(x * h);
dst[i + 1] = Math.round(y * h);
dst[i + 2] = Math.round(z * h);
// keep dst[i + 3] as is
}
} else if (filter === 'QUATERNION') {
assert(byteStride === 8);
const dst = new Int16Array(target.buffer);
for (let i = 0; i < 4 * elementCount; i += 4) {
const inputW = dst[i + 3];
const maxComponent = inputW & 0x03;
const s = Math.SQRT1_2 / (inputW | 0x03);
let x = dst[i + 0] * s;
let y = dst[i + 1] * s;
let z = dst[i + 2] * s;
let w = Math.sqrt(Math.max(0.0, 1.0 - x ** 2 - y ** 2 - z ** 2));
dst[i + ((maxComponent + 1) % 4)] = Math.round(x * 32767);
dst[i + ((maxComponent + 2) % 4)] = Math.round(y * 32767);
dst[i + ((maxComponent + 3) % 4)] = Math.round(z * 32767);
dst[i + ((maxComponent + 0) % 4)] = Math.round(w * 32767);
}
} else if (filter === 'EXPONENTIAL') {
assert((byteStride & 0x03) === 0x00);
const src = new Int32Array(target.buffer);
const dst = new Float32Array(target.buffer);
for (let i = 0; i < (byteStride * elementCount) / 4; i++) {
const v = src[i],
exp = v >> 24,
mantissa = (v << 8) >> 8;
dst[i] = 2.0 ** exp * mantissa;
}
} else if (filter === 'COLOR') {
assert(byteStride === 4 || byteStride === 8);
const maxInt = (1 << (byteStride * 2)) - 1;
const data = byteStride === 4 ? new Uint8Array(target.buffer) : new Uint16Array(target.buffer, 0, elementCount * 4);
const dataSigned = byteStride === 4 ? new Int8Array(target.buffer) : new Int16Array(target.buffer, 0, elementCount * 4);
for (let i = 0; i < elementCount * 4; i += 4) {
const y = data[i + 0];
const co = dataSigned[i + 1];
const cg = dataSigned[i + 2];
const alphaInput = data[i + 3];
// Recover scale from alpha high bit - find highest bit set
const alphaBit = 31 - Math.clz32(alphaInput);
const as = (1 << (alphaBit + 1)) - 1;
// YCoCg to RGB conversion
const r = y + co - cg;
const g = y + cg;
const b = y - co - cg;
// Expand alpha by one bit, replicating last bit
let a = alphaInput & (as >> 1);
a = (a << 1) | (a & 1);
// Scale to full range
const ss = maxInt / as;
// Store result
data[i + 0] = Math.round(r * ss);
data[i + 1] = Math.round(g * ss);
data[i + 2] = Math.round(b * ss);
data[i + 3] = Math.round(a * ss);
}
}
};
function pushfifo(fifo, n) {
for (let i = fifo.length - 1; i > 0; i--) fifo[i] = fifo[i - 1];
fifo[0] = n;
}
MeshoptDecoder.decodeIndexBuffer = (target, count, byteStride, source) => {
assert(source[0] === 0xe1);
assert(count % 3 === 0);
assert(byteStride === 2 || byteStride === 4);
let dst;
if (byteStride === 2) dst = new Uint16Array(target.buffer);
else dst = new Uint32Array(target.buffer);
const triCount = count / 3;
let codeOffs = 0x01;
let dataOffs = codeOffs + triCount;
let codeauxOffs = source.length - 0x10;
function readLEB128() {
let n = 0;
for (let i = 0; ; i += 7) {
const b = source[dataOffs++];
n |= (b & 0x7f) << i;
if (b < 0x80) return n;
}
}
let next = 0,
last = 0;
const edgefifo = new Uint32Array(32);
const vertexfifo = new Uint32Array(16);
function decodeIndex(v) {
return (last += dezig(v));
}
let dstOffs = 0;
for (let i = 0; i < triCount; i++) {
const code = source[codeOffs++];
const b0 = code >>> 4,
b1 = code & 0x0f;
if (b0 < 0x0f) {
const a = edgefifo[(b0 << 1) + 0],
b = edgefifo[(b0 << 1) + 1];
let c = -1;
if (b1 === 0x00) {
c = next++;
pushfifo(vertexfifo, c);
} else if (b1 < 0x0d) {
c = vertexfifo[b1];
} else if (b1 === 0x0d) {
c = --last;
pushfifo(vertexfifo, c);
} else if (b1 === 0x0e) {
c = ++last;
pushfifo(vertexfifo, c);
} else if (b1 === 0x0f) {
const v = readLEB128();
c = decodeIndex(v);
pushfifo(vertexfifo, c);
}
// fifo pushes happen backwards
pushfifo(edgefifo, b);
pushfifo(edgefifo, c);
pushfifo(edgefifo, c);
pushfifo(edgefifo, a);
dst[dstOffs++] = a;
dst[dstOffs++] = b;
dst[dstOffs++] = c;
} else {
// b0 === 0x0F
let a = -1,
b = -1,
c = -1;
if (b1 < 0x0e) {
const e = source[codeauxOffs + b1];
const z = e >>> 4,
w = e & 0x0f;
a = next++;
if (z === 0x00) b = next++;
else b = vertexfifo[z - 1];
if (w === 0x00) c = next++;
else c = vertexfifo[w - 1];
pushfifo(vertexfifo, a);
if (z === 0x00) pushfifo(vertexfifo, b);
if (w === 0x00) pushfifo(vertexfifo, c);
} else {
const e = source[dataOffs++];
if (e === 0x00) next = 0;
const z = e >>> 4,
w = e & 0x0f;
if (b1 === 0x0e) a = next++;
else a = decodeIndex(readLEB128());
if (z === 0x00) b = next++;
else if (z === 0x0f) b = decodeIndex(readLEB128());
else b = vertexfifo[z - 1];
if (w === 0x00) c = next++;
else if (w === 0x0f) c = decodeIndex(readLEB128());
else c = vertexfifo[w - 1];
pushfifo(vertexfifo, a);
if (z === 0x00 || z === 0x0f) pushfifo(vertexfifo, b);
if (w === 0x00 || w === 0x0f) pushfifo(vertexfifo, c);
}
pushfifo(edgefifo, a);
pushfifo(edgefifo, b);
pushfifo(edgefifo, b);
pushfifo(edgefifo, c);
pushfifo(edgefifo, c);
pushfifo(edgefifo, a);
dst[dstOffs++] = a;
dst[dstOffs++] = b;
dst[dstOffs++] = c;
}
}
};
MeshoptDecoder.decodeIndexSequence = (target, count, byteStride, source) => {
assert(source[0] === 0xd1);
assert(byteStride === 2 || byteStride === 4);
let dst;
if (byteStride === 2) dst = new Uint16Array(target.buffer);
else dst = new Uint32Array(target.buffer);
let dataOffs = 0x01;
function readLEB128() {
let n = 0;
for (let i = 0; ; i += 7) {
const b = source[dataOffs++];
n |= (b & 0x7f) << i;
if (b < 0x80) return n;
}
}
const last = new Uint32Array(2);
for (let i = 0; i < count; i++) {
const v = readLEB128();
const b = v & 0x01;
const delta = dezig(v >>> 1);
dst[i] = last[b] += delta;
}
};
MeshoptDecoder.decodeGltfBuffer = (target, count, size, source, mode, filter) => {
const table = {
ATTRIBUTES: MeshoptDecoder.decodeVertexBuffer,
TRIANGLES: MeshoptDecoder.decodeIndexBuffer,
INDICES: MeshoptDecoder.decodeIndexSequence,
};
assert(table[mode] !== undefined);
table[mode](target, count, size, source, filter);
};
MeshoptDecoder.decodeGltfBufferAsync = (count, size, source, mode, filter) => {
const target = new Uint8Array(count * size);
MeshoptDecoder.decodeGltfBuffer(target, count, size, source, mode, filter);
return Promise.resolve(target);
};
// node.js interface:
// for (let k in MeshoptDecoder) exports[k] = MeshoptDecoder[k];
export { MeshoptDecoder };
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine | |
js/meshopt_encoder.d.ts | TypeScript | // This file is part of meshoptimizer library and is distributed under the terms of MIT License.
// Copyright (C) 2016-2026, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
export type ExpMode = 'Separate' | 'SharedVector' | 'SharedComponent' | 'Clamped';
export const MeshoptEncoder: {
supported: boolean;
ready: Promise<void>;
reorderMesh: (indices: Uint32Array, triangles: boolean, optsize: boolean) => [Uint32Array, number];
reorderPoints: (positions: Float32Array, positions_stride: number) => Uint32Array;
encodeVertexBuffer: (source: Uint8Array, count: number, size: number) => Uint8Array;
encodeVertexBufferLevel: (source: Uint8Array, count: number, size: number, level: number, version?: number) => Uint8Array;
encodeIndexBuffer: (source: Uint8Array, count: number, size: number) => Uint8Array;
encodeIndexSequence: (source: Uint8Array, count: number, size: number) => Uint8Array;
encodeGltfBuffer: (source: Uint8Array, count: number, size: number, mode: string, version?: number) => Uint8Array;
encodeFilterOct: (source: Float32Array, count: number, stride: number, bits: number) => Uint8Array;
encodeFilterQuat: (source: Float32Array, count: number, stride: number, bits: number) => Uint8Array;
encodeFilterExp: (source: Float32Array, count: number, stride: number, bits: number, mode?: ExpMode) => Uint8Array;
encodeFilterColor: (source: Float32Array, count: number, stride: number, bits: number) => Uint8Array;
};
| zeux/meshoptimizer | 7,278 | Mesh optimization library that makes meshes smaller and faster to render | C++ | zeux | Arseny Kapoulkine |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.