ProCraft for Android: An Android native painting app written in Rust
Rust
feat(animation): settings, onion skin colours and page backgrounds
Josh0612169db4ba
diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasViewModel.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasViewModel.ktindex cd853a8..887e21d 100644--- a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasViewModel.kt+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/canvas/CanvasViewModel.kt@@ -71,6 +71,8 @@ import androidx.compose.ui.unit.DpSizeimport androidx.compose.ui.unit.dpimport androidx.compose.ui.text.input.TextFieldValueimport kotlinx.coroutines.launch+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLockimport kotlinx.coroutines.withContextimport java.io.Fileimport java.nio.ByteBuffer@@ -3592,13 +3594,19 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {return Bitmap.createBitmap(argb, w, h, Bitmap.Config.ARGB_8888)}+ /** The artwork's name, or the name an unnamed one shows. */+ fun artworkTitle(): String = session?.name()?.trim()?.takeIf { it.isNotEmpty() } ?: "Untitled Artwork"++ /** One animation export at a time: they write the same file. */+ private val animationExports = Mutex()+/*** The animation written as [format] into the cache, to share: Web Ready fits 480 pixels, else* the canvas size (a video as large as the encoder takes, up to 4096).*/suspend fun exportAnimation(format: Animated, webReady: Boolean, dither: Boolean, transparent: Boolean): File? {val s = session ?: return null- return withContext(Dispatchers.IO) {+ return animationExports.withLock { withContext(Dispatchers.IO) {val dir = File(getApplication<Application>().cacheDir, "exports").apply { mkdirs() }val base = s.name().filter { it.isLetterOrDigit() || it in " _-" }.trim().ifEmpty { "Untitled Artwork" }val file = File(dir, "$base.${format.extension}")@@ -3635,7 +3643,7 @@ class CanvasViewModel(app: Application) : AndroidViewModel(app) {Log.e(TAG, "exporting an animation", e)null}- }+ } }}suspend fun exportImage(jpeg: Boolean): File? {diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AnimatedExportUi.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AnimatedExportUi.ktindex 4eb2110..7d978d7 100644--- a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AnimatedExportUi.kt+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AnimatedExportUi.kt@@ -9,9 +9,11 @@ import androidx.compose.foundation.clickableimport androidx.compose.foundation.gestures.awaitEachGestureimport androidx.compose.foundation.gestures.awaitFirstDownimport androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.BoxWithConstraintsimport androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.ColumnScopeimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.Spacerimport androidx.compose.foundation.layout.fillMaxHeight@@ -66,101 +68,225 @@ private val CapsuleEdge = Color(0xFF373737)private val DoneBlue = Color(0xFF0190FF)/**- * Sharing the layers as an animation: the frames playing in a square, Export Settings (the size,- * and per format dithering and a transparent background) in a panel on the left, Cancel, and- * the round Done that exports and shares.+ * Sharing the layers as an animation: the frames playing, the settings (the size, and per format+ * dithering and a transparent background), Cancel, and the round Done that exports and shares.+ * The file is made as the settings change, to show its size.*/@Composablefun AnimatedExport(vm: CanvasViewModel, format: CanvasViewModel.Animated) {val context = LocalContext.currentval scope = rememberCoroutineScope()- var settingsOpen by remember { mutableStateOf(false) }var webReady by remember { mutableStateOf(false) }var dither by remember { mutableStateOf(true) }var transparent by remember { mutableStateOf(false) }var exporting by remember { mutableStateOf(false) }- fun cancel() {- if (settingsOpen) settingsOpen = false else vm.endAnimatedExport()+ val canTransparent = format == CanvasViewModel.Animated.GIF || format == CanvasViewModel.Animated.PNG+ // the file as the settings make it, for its size+ var bytes by remember { mutableStateOf<Long?>(null) }+ LaunchedEffect(webReady, dither, transparent) {+ bytes = null+ bytes = vm.exportAnimation(format, webReady, dither, transparent)?.length()}- BackHandler { cancel() }- BoxWithConstraints(Modifier.fillMaxSize().background(ScreenFill).pointerInput(Unit) { detectTapGestures { } }) {- val box = maxWidth - 48.dp- val side = with(LocalDensity.current) { box.roundToPx() }- // the frames, fitted to the square, played over and over- var frames by remember { mutableStateOf<List<Bitmap>>(emptyList()) }- var shown by remember { mutableIntStateOf(0) }- val canTransparent = format == CanvasViewModel.Animated.GIF || format == CanvasViewModel.Animated.PNG- LaunchedEffect(transparent && canTransparent, side) {- val loaded = withContext(Dispatchers.IO) { List(vm.animationFrameCount()) { vm.animationFrame(it, side, transparent && canTransparent) }.filterNotNull() }- frames = loaded- shown = 0- }- LaunchedEffect(frames) {- while (frames.size > 1) {- delay(1000L / CanvasViewModel.ANIMATION_FPS)- shown = (shown + 1) % frames.size+ ExportScreen(+ title = format.title,+ name = vm.artworkTitle(),+ size = bytes?.let(::fileSize),+ exporting = exporting,+ onCancel = { vm.endAnimatedExport() },+ onDone = {+ exporting = true+ scope.launch {+ val file = vm.exportAnimation(format, webReady, dither, transparent)+ exporting = false+ if (file != null) {+ vm.endAnimatedExport()+ shareFile(context, file, format.mime)+ } else {+ vm.message = "The animation could not be exported."+ }+ }+ },+ preview = { side ->+ // the frames, fitted to the box, played over and over+ var frames by remember { mutableStateOf<List<Bitmap>>(emptyList()) }+ var shown by remember { mutableIntStateOf(0) }+ LaunchedEffect(transparent && canTransparent, side) {+ val loaded = withContext(Dispatchers.IO) { List(vm.animationFrameCount()) { vm.animationFrame(it, side, transparent && canTransparent) }.filterNotNull() }+ frames = loaded+ shown = 0+ }+ LaunchedEffect(frames) {+ while (frames.size > 1) {+ delay(1000L / CanvasViewModel.ANIMATION_FPS)+ shown = (shown + 1) % frames.size+ }}- }- Box(Modifier.offset(x = 24.dp, y = 96.dp).size(box), contentAlignment = Alignment.Center) {frames.getOrNull(shown)?.let { Image(it.asImageBitmap(), contentDescription = "Preview", contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize()) }- }- // the header: Export Settings on the left, Cancel and Done on the right- Row(Modifier.offset(x = 14.dp, y = 20.dp).height(44.dp).clickable { settingsOpen = !settingsOpen }.padding(end = 12.dp), verticalAlignment = Alignment.CenterVertically) {- Box(Modifier.width(60.dp), contentAlignment = Alignment.Center) {- Icon(PcIcons.ChevronLeft, contentDescription = null, tint = TitleInk, modifier = Modifier.size(28.dp))+ },+ ) {+ Segments(listOf("Max Resolution", "Web Ready"), if (webReady) 1 else 0) { webReady = it == 1 }+ Spacer(Modifier.height(6.5.dp))+ if (format == CanvasViewModel.Animated.GIF) SettingRow("Dithering", dither) { dither = it }+ if (canTransparent) SettingRow("Transparent background", transparent) { transparent = it }+ }+}++/** A file's size as the export screen shows it: "1.3 MB", "850 KB". */+private fun fileSize(bytes: Long): String =+ if (bytes >= 1_000_000) "%.1f MB".format(bytes / 1_000_000.0) else "${(bytes / 1000).coerceAtLeast(1)} KB"++/**+ * An export screen. Wide, the settings stay in a 400-wide panel on the left, and the artwork's+ * name and the file's [size] sit over the preview, which fills the rest (41 in at the sides,+ * 110 down). Upright, "Export Settings" opens the panel over a square preview (24 in), a tap+ * beside it closing it again. Cancel and the round Done are at the top right.+ */+@Composable+private fun ExportScreen(+ title: String,+ name: String,+ size: String?,+ exporting: Boolean,+ onCancel: () -> Unit,+ onDone: () -> Unit,+ preview: @Composable (side: Int) -> Unit,+ panel: @Composable ColumnScope.() -> Unit,+) {+ var settingsOpen by remember { mutableStateOf(false) }+ BoxWithConstraints(Modifier.fillMaxSize().background(ScreenFill).pointerInput(Unit) { detectTapGestures { } }) {+ val wide = maxWidth > maxHeight+ BackHandler { if (settingsOpen && !wide) settingsOpen = false else onCancel() }+ val left = if (wide) PanelWidth + 10.dp else 0.dp+ val inset = if (wide) 41.dp else 24.dp+ val boxWidth = maxWidth - left - inset * 2+ val boxHeight = if (wide) minOf(boxWidth, maxHeight - 104.dp) else boxWidth+ val side = with(LocalDensity.current) { minOf(boxWidth, boxHeight).roundToPx() }+ Box(Modifier.offset(x = left + inset, y = 110.dp).size(boxWidth, boxHeight), contentAlignment = Alignment.Center) { preview(side) }+ if (wide) {+ // the name and size centred between the panel and the buttons+ Column(+ Modifier.offset(x = left + 24.dp, y = 23.dp).width(maxWidth - left - 24.dp - 224.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ Text(name, color = TitleInk, fontSize = 20.sp, fontWeight = FontWeight.Bold, maxLines = 1, modifier = Modifier.height(30.dp))+ Text(size ?: "", color = SizeInk, fontSize = 13.sp, maxLines = 1, modifier = Modifier.height(20.dp))+ }+ } else {+ Row(Modifier.offset(x = 14.dp, y = 20.dp).clickable { settingsOpen = !settingsOpen }.padding(end = 12.dp), verticalAlignment = Alignment.CenterVertically) {+ Box(Modifier.width(60.dp), contentAlignment = Alignment.Center) {+ Icon(PcIcons.ChevronLeft, contentDescription = null, tint = TitleInk, modifier = Modifier.size(28.dp))+ }+ // on two lines, as there+ Text("Export\nSettings", color = TitleInk, fontSize = 24.sp, fontWeight = FontWeight.Bold, lineHeight = 29.sp)}- Text("Export Settings", color = TitleInk, fontSize = 24.sp, fontWeight = FontWeight.Bold, maxLines = 1)}Row(Modifier.align(Alignment.TopEnd).padding(top = 16.dp, end = 16.dp), verticalAlignment = Alignment.CenterVertically) {Box(- Modifier.height(43.dp).clip(CircleShape).background(CapsuleFill).border(1.dp, CapsuleEdge, CircleShape).clickable { cancel() }.padding(horizontal = 13.dp),+ Modifier.height(43.dp).clip(CircleShape).background(CapsuleFill).border(1.dp, CapsuleEdge, CircleShape).clickable(onClick = onCancel).padding(horizontal = 13.dp),contentAlignment = Alignment.Center,) {Text("Cancel", color = Color(0xFFA5A5A5), fontSize = 17.sp)}Spacer(Modifier.width(13.dp))Box(- Modifier.size(44.dp, 45.dp).clip(CircleShape).background(DoneBlue).clickable(enabled = !exporting) {- exporting = true- scope.launch {- val file = vm.exportAnimation(format, webReady, dither, transparent)- exporting = false- if (file != null) {- vm.endAnimatedExport()- shareFile(context, file, format.mime)- } else {- vm.message = "The animation could not be exported."- }- }- },+ Modifier.size(44.dp, 45.dp).clip(CircleShape).background(DoneBlue).clickable(enabled = !exporting, onClick = onDone),contentAlignment = Alignment.Center,) {if (exporting) CircularProgressIndicator(color = Color.White, strokeWidth = 2.dp, modifier = Modifier.size(24.dp))else Icon(PcIcons.DoneTick, contentDescription = "Export", tint = Color.White, modifier = Modifier.requiredSize(40.dp))}}- if (settingsOpen) {- // a tap outside the panel closes it- Box(Modifier.fillMaxSize().pointerInput(Unit) { detectTapGestures { settingsOpen = false } })+ if (wide || settingsOpen) {+ // upright, a tap outside the panel closes it+ if (!wide) Box(Modifier.fillMaxSize().pointerInput(Unit) { detectTapGestures { settingsOpen = false } })Column(- Modifier.padding(10.dp).width(400.dp).fillMaxHeight().clip(RoundedCornerShape(20.dp)).background(PanelFill).border(1.dp, PanelEdge, RoundedCornerShape(20.dp))+ Modifier.padding(10.dp).width(PanelWidth).fillMaxHeight().clip(RoundedCornerShape(20.dp)).background(PanelFill).border(1.dp, PanelEdge, RoundedCornerShape(20.dp)).pointerInput(Unit) { detectTapGestures { } },) {- Text(format.title, color = TitleInk, fontSize = 24.sp, fontWeight = FontWeight.Bold, maxLines = 1, modifier = Modifier.padding(start = 24.dp, top = 15.dp).height(36.dp))- Spacer(Modifier.height(8.dp))- Segments(listOf("Max Resolution", "Web Ready"), if (webReady) 1 else 0) { webReady = it == 1 }- Spacer(Modifier.height(15.dp))- if (format == CanvasViewModel.Animated.GIF) SettingRow("Dithering", dither) { dither = it }- if (canTransparent) SettingRow("Transparent background", transparent) { transparent = it }+ Text(title, color = TitleInk, fontSize = 24.sp, fontWeight = FontWeight.Bold, maxLines = 1, modifier = Modifier.padding(start = 24.dp, top = 19.dp).height(36.dp))+ Spacer(Modifier.height(11.5.dp))+ panel()}}}}-/** Two or more choices side by side in a grey track, the chosen one blue. */+private val PanelWidth = 400.dp+private val SizeInk = Color(0xFF8E8E8E)++/**+ * Sharing a model on a turntable: it turning as it will, the settings (the size, once round or+ * swinging, how long a turn takes, how far the camera pulls back, the easing, and whether the+ * environment shows), Cancel, and the round Done that exports and shares.+ */+@Composable+fun ModelAnimatedExport(vm: CanvasViewModel, format: CanvasViewModel.Animated) {+ val context = LocalContext.current+ val scope = rememberCoroutineScope()+ var exporting by remember { mutableStateOf(false) }+ ExportScreen(+ title = format.title,+ name = vm.artworkTitle(),+ size = null,+ exporting = exporting,+ onCancel = { vm.modelAnimatedExport = null },+ onDone = {+ exporting = true+ scope.launch {+ val file = vm.exportModelAnimation(format)+ exporting = false+ if (file != null) {+ vm.modelAnimatedExport = null+ shareFile(context, file, format.mime)+ } else {+ vm.message = "The animation could not be exported."+ }+ }+ },+ preview = { side ->+ // the turntable's frames, made again whenever its settings change, played over and over+ var frames by remember { mutableStateOf<List<Bitmap>>(emptyList()) }+ var shown by remember { mutableIntStateOf(0) }+ LaunchedEffect(vm.turntable, side) {+ frames = vm.turntablePreview(side / 2, PREVIEW_FPS)+ shown = 0+ }+ LaunchedEffect(frames) {+ while (frames.size > 1) {+ delay(1000L / PREVIEW_FPS)+ shown = (shown + 1) % frames.size+ }+ }+ frames.getOrNull(shown)?.let { Image(it.asImageBitmap(), contentDescription = "Preview", contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize()) }+ },+ ) {+ val t = vm.turntable+ Segments(listOf("720p", "1080p", "4K", "Square"), vm.turntableSize) { vm.turntableSize = it }+ Spacer(Modifier.height(14.5.dp))+ Column(Modifier.padding(horizontal = 16.dp).clip(RoundedCornerShape(14.dp)).background(ChoiceFill)) {+ ChoiceRow("Animated rotate", !t.swing) { vm.turntable = t.copy(swing = false) }+ ChoiceRow("Animated swing", t.swing) { vm.turntable = t.copy(swing = true) }+ }+ Spacer(Modifier.height(26.dp))+ val seconds = if (t.seconds < 1f) "%.1f".format(t.seconds) else "${t.seconds.roundToInt()}"+ TurntableSlider("Animation duration", seconds, (t.seconds - 0.5f) / 4.5f) { vm.turntable = vm.turntable.copy(seconds = 0.5f + it * 4.5f) }+ TurntableSlider("Zoom distance", "${(t.zoom * 100).roundToInt()}%", t.zoom) { vm.turntable = vm.turntable.copy(zoom = it) }+ TurntableSlider("Ease", "${(t.ease * 100).roundToInt()}%", t.ease) { vm.turntable = vm.turntable.copy(ease = it) }+ Spacer(Modifier.height(10.dp))+ SettingRow("Show environment", t.environment) { vm.turntable = vm.turntable.copy(environment = it) }+ }+}++/** The turntable preview's frame rate. */+private const val PREVIEW_FPS = 15++/** Two or more choices side by side in a grey track 384 wide, 12 apart, the chosen one blue. */@Composableprivate fun Segments(labels: List<String>, chosen: Int, onChoose: (Int) -> Unit) {- Row(Modifier.padding(start = 9.dp).width(382.dp).height(33.dp).clip(CircleShape).background(SegmentTrack).padding(1.5.dp)) {+ Row(+ Modifier.padding(start = 7.5.dp).width(384.dp).height(34.dp).clip(CircleShape).background(SegmentTrack).padding(2.dp),+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ ) {labels.forEachIndexed { i, label ->Box(Modifier.weight(1f).fillMaxHeight().clip(CircleShape).background(if (i == chosen) Pc.Accent else Color.Transparent).clickable { onChoose(i) },@@ -184,104 +310,6 @@ private fun SettingRow(label: String, on: Boolean, onChange: (Boolean) -> Unit)private val ChoiceFill = Color(0xFF2E2E2E)private val SliderTrack = Color(0xFF3E3E3E)-/**- * Sharing a model on a turntable: it turning in a square as it will, Export Settings (the size,- * once round or swinging, how long a turn takes, how far the camera pulls back, the easing, and- * whether the environment shows) in a panel on the left, Cancel, and the round Done that exports- * and shares.- */-@Composable-fun ModelAnimatedExport(vm: CanvasViewModel, format: CanvasViewModel.Animated) {- val context = LocalContext.current- val scope = rememberCoroutineScope()- var settingsOpen by remember { mutableStateOf(false) }- var exporting by remember { mutableStateOf(false) }- fun cancel() {- if (settingsOpen) settingsOpen = false else vm.modelAnimatedExport = null- }- BackHandler { cancel() }- BoxWithConstraints(Modifier.fillMaxSize().background(ScreenFill).pointerInput(Unit) { detectTapGestures { } }) {- val box = minOf(maxWidth - 48.dp, maxHeight - 120.dp)- val side = with(LocalDensity.current) { box.roundToPx() }- // the turntable's frames, made again whenever its settings change, played over and over- var frames by remember { mutableStateOf<List<Bitmap>>(emptyList()) }- var shown by remember { mutableIntStateOf(0) }- LaunchedEffect(vm.turntable, side) {- frames = vm.turntablePreview(side / 2, PREVIEW_FPS)- shown = 0- }- LaunchedEffect(frames) {- while (frames.size > 1) {- delay(1000L / PREVIEW_FPS)- shown = (shown + 1) % frames.size- }- }- Box(Modifier.align(Alignment.TopCenter).offset(y = 96.dp).size(box), contentAlignment = Alignment.Center) {- frames.getOrNull(shown)?.let { Image(it.asImageBitmap(), contentDescription = "Preview", contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize()) }- }- Row(Modifier.offset(x = 14.dp, y = 20.dp).height(44.dp).clickable { settingsOpen = !settingsOpen }.padding(end = 12.dp), verticalAlignment = Alignment.CenterVertically) {- Box(Modifier.width(60.dp), contentAlignment = Alignment.Center) {- Icon(PcIcons.ChevronLeft, contentDescription = null, tint = TitleInk, modifier = Modifier.size(28.dp))- }- Text("Export Settings", color = TitleInk, fontSize = 24.sp, fontWeight = FontWeight.Bold, maxLines = 1)- }- Row(Modifier.align(Alignment.TopEnd).padding(top = 16.dp, end = 16.dp), verticalAlignment = Alignment.CenterVertically) {- Box(- Modifier.height(43.dp).clip(CircleShape).background(CapsuleFill).border(1.dp, CapsuleEdge, CircleShape).clickable { cancel() }.padding(horizontal = 13.dp),- contentAlignment = Alignment.Center,- ) {- Text("Cancel", color = Color(0xFFA5A5A5), fontSize = 17.sp)- }- Spacer(Modifier.width(13.dp))- Box(- Modifier.size(44.dp, 45.dp).clip(CircleShape).background(DoneBlue).clickable(enabled = !exporting) {- exporting = true- scope.launch {- val file = vm.exportModelAnimation(format)- exporting = false- if (file != null) {- vm.modelAnimatedExport = null- shareFile(context, file, format.mime)- } else {- vm.message = "The animation could not be exported."- }- }- },- contentAlignment = Alignment.Center,- ) {- if (exporting) CircularProgressIndicator(color = Color.White, strokeWidth = 2.dp, modifier = Modifier.size(24.dp))- else Icon(PcIcons.DoneTick, contentDescription = "Export", tint = Color.White, modifier = Modifier.requiredSize(40.dp))- }- }- if (settingsOpen) {- Box(Modifier.fillMaxSize().pointerInput(Unit) { detectTapGestures { settingsOpen = false } })- val t = vm.turntable- Column(- Modifier.padding(10.dp).width(400.dp).fillMaxHeight().clip(RoundedCornerShape(20.dp)).background(PanelFill).border(1.dp, PanelEdge, RoundedCornerShape(20.dp))- .pointerInput(Unit) { detectTapGestures { } },- ) {- Text(format.title, color = TitleInk, fontSize = 24.sp, fontWeight = FontWeight.Bold, maxLines = 1, modifier = Modifier.padding(start = 24.dp, top = 15.dp).height(36.dp))- Spacer(Modifier.height(8.dp))- Segments(listOf("720p", "1080p", "4K", "Square"), vm.turntableSize) { vm.turntableSize = it }- Spacer(Modifier.height(23.dp))- Column(Modifier.padding(horizontal = 16.dp).clip(RoundedCornerShape(14.dp)).background(ChoiceFill)) {- ChoiceRow("Animated rotate", !t.swing) { vm.turntable = t.copy(swing = false) }- ChoiceRow("Animated swing", t.swing) { vm.turntable = t.copy(swing = true) }- }- Spacer(Modifier.height(26.dp))- val seconds = if (t.seconds < 1f) "%.1f".format(t.seconds) else "${t.seconds.roundToInt()}"- TurntableSlider("Animation duration", seconds, (t.seconds - 0.5f) / 4.5f) { vm.turntable = vm.turntable.copy(seconds = 0.5f + it * 4.5f) }- TurntableSlider("Zoom distance", "${(t.zoom * 100).roundToInt()}%", t.zoom) { vm.turntable = vm.turntable.copy(zoom = it) }- TurntableSlider("Ease", "${(t.ease * 100).roundToInt()}%", t.ease) { vm.turntable = vm.turntable.copy(ease = it) }- Spacer(Modifier.height(10.dp))- SettingRow("Show environment", t.environment) { vm.turntable = vm.turntable.copy(environment = it) }- }- }- }-}--/** The turntable preview's frame rate. */-private const val PREVIEW_FPS = 15/** One of two choices in a group, 40 tall: the chosen one blue with a tick. */@Composablediff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AnimationUi.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AnimationUi.ktindex b31e827..182d3ad 100644--- a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AnimationUi.kt+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/AnimationUi.kt@@ -6,6 +6,7 @@ import androidx.compose.foundation.borderimport androidx.compose.foundation.clickableimport androidx.compose.foundation.gestures.detectHorizontalDragGesturesimport androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.BoxScopeimport androidx.compose.foundation.layout.Column@@ -17,6 +18,7 @@ import androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.heightimport androidx.compose.foundation.layout.offsetimport androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.requiredSizeimport androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.layout.widthimport androidx.compose.foundation.shape.RoundedCornerShape@@ -40,6 +42,7 @@ import androidx.compose.ui.graphics.Colorimport androidx.compose.ui.graphics.Pathimport androidx.compose.ui.input.pointer.pointerInputimport androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.layout.layoutimport androidx.compose.ui.layout.onGloballyPositionedimport androidx.compose.ui.layout.positionInParentimport androidx.compose.ui.platform.LocalDensity@@ -63,6 +66,9 @@ private val TrackEdge get() = if (Pc.light) Color(0xFFBDBDBD) else Color(0xFF5C5private val BarInk get() = if (Pc.light) Color(0xFF393939) else Color(0xFFC5C5C5)private const val MAX_ONION = 12+/** Play's and Add Frame's inset from the bar's ends. */+private val BarInset = 26.dp+/*** Animation Assist's bar at the bottom: Play, Settings and Add Frame over the timeline of frames,* the current one in the middle; with its settings or the current frame's options above it.@@ -77,14 +83,19 @@ fun BoxScope.AnimationBar(vm: CanvasViewModel) {var settingsAt by remember { mutableStateOf(281.5.dp) }val density = LocalDensity.currentColumn(Modifier.align(Alignment.BottomCenter)) {+ // Onion skin colors opens a page in the settings' place; closed, they open on settings again+ var colorsPage by remember { mutableStateOf(false) }+ if (!vm.animationSettingsOpen) colorsPage = falseif (vm.animationSettingsOpen) {- DownPopover(290.dp, 145.dp, Modifier.offset(x = (settingsAt - 145.dp).coerceIn(0.dp, barWidth - 290.dp))) { AnimationSettingsPage(vm) }+ DownPopover(290.dp, 145.dp, Modifier.offset(x = (settingsAt - 145.dp).coerceIn(0.dp, barWidth - 290.dp))) {+ if (colorsPage) OnionColorsPage(vm) { colorsPage = false } else AnimationSettingsPage(vm) { colorsPage = true }+ }} else if (vm.frameOptionsOpen) {- DownPopover(268.dp, 134.dp, Modifier.offset(x = barWidth / 2 - 134.dp)) { FrameOptionsPage(vm) }+ DownPopover(260.dp, 130.dp, Modifier.offset(x = barWidth / 2 - 130.dp)) { FrameOptionsPage(vm) }}Box(Modifier.padding(bottom = BarGap).size(barWidth, BarHeight).clip(RoundedCornerShape(30.dp)).background(BarFill)) {val pages = vm.animation?.pages == true- Row(Modifier.fillMaxWidth().padding(start = 26.dp, end = 26.dp, top = 8.dp).height(30.dp), verticalAlignment = Alignment.CenterVertically) {+ Row(Modifier.fillMaxWidth().padding(start = BarInset, end = BarInset, top = 8.dp).height(30.dp), verticalAlignment = Alignment.CenterVertically) {Text(if (pages) "Page Assist" else if (vm.playingFrame != null) "Pause" else "Play", color = BarInk, fontSize = 17.sp, fontWeight = FontWeight.Bold,modifier = if (pages) Modifier else Modifier.clickable { vm.togglePlaying() },@@ -92,7 +103,8 @@ fun BoxScope.AnimationBar(vm: CanvasViewModel) {Spacer(Modifier.weight(1f))if (!pages) BarText("Settings",- Modifier.onGloballyPositioned { c -> settingsAt = with(density) { (c.positionInParent().x + c.size.width / 2f).toDp() } },+ // measured inside the row's padding+ Modifier.onGloballyPositioned { c -> settingsAt = BarInset + with(density) { (c.positionInParent().x + c.size.width / 2f).toDp() } },) {vm.animationSettingsOpen = !vm.animationSettingsOpenvm.frameOptionsOpen = false@@ -165,12 +177,14 @@ private fun DownPopover(width: Dp, arrowX: Dp, modifier: Modifier, content: @Com/** Animation Assist's settings: playback, frames a second, onion skins, the primary frame. */@Composable-private fun ColumnScope.AnimationSettingsPage(vm: CanvasViewModel) {+private fun ColumnScope.AnimationSettingsPage(vm: CanvasViewModel, onColors: () -> Unit) {val a = vm.animation ?: return- Text("Settings", color = Pc.PanelTitle, fontSize = 22.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(start = 14.dp, top = 2.dp, bottom = 12.dp))+ Text("Settings", color = Pc.PanelTitle, fontSize = 23.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(start = 14.dp, top = 11.dp, bottom = 21.dp))Group {- for ((mode, label) in listOf(AnimationPlayback.LOOP to "Loop", AnimationPlayback.PING_PONG to "Ping-Pong", AnimationPlayback.ONE_SHOT to "One Shot")) {+ for ((i, pair) in listOf(AnimationPlayback.LOOP to "Loop", AnimationPlayback.PING_PONG to "Ping-Pong", AnimationPlayback.ONE_SHOT to "One Shot").withIndex()) {+ val (mode, label) = pairval chosen = a.playback == mode+ if (i > 0) RowLine()Row(Modifier.fillMaxWidth().height(40.dp).background(if (chosen) Pc.Accent else Color.Transparent).clickable { vm.changeAnimation { it.copy(playback = mode) } }.padding(horizontal = 16.dp),verticalAlignment = Alignment.CenterVertically,@@ -181,7 +195,7 @@ private fun ColumnScope.AnimationSettingsPage(vm: CanvasViewModel) {}}Spacer(Modifier.height(10.dp))- Group {+ SliderGroup {ValueSlider("Frames Per Second", "${a.fps}", (a.fps.toFloat() - 1f) / 59f) { v -> vm.changeAnimation { it.copy(fps = (1 + (v * 59f).roundToInt()).toUInt()) } }val onion = a.onionFrames.toInt()ValueSlider("Onion skin frames", when (onion) { 0 -> "None"; MAX_ONION -> "Max"; else -> "$onion" }, onion / MAX_ONION.toFloat()) { v ->@@ -189,20 +203,80 @@ private fun ColumnScope.AnimationSettingsPage(vm: CanvasViewModel) {}ValueSlider("Onion skin opacity", "${(a.onionOpacity * 100).roundToInt()} %", a.onionOpacity) { v -> vm.changeAnimation { it.copy(onionOpacity = v) } }}- Spacer(Modifier.height(10.dp))+ Spacer(Modifier.height(9.dp))Group {- Row(Modifier.fillMaxWidth().height(45.dp).clickable { vm.changeAnimation { it.copy(blendPrimary = !it.blendPrimary) } }.padding(start = 16.dp, end = 6.dp), verticalAlignment = Alignment.CenterVertically) {- Text("Blend primary frame", color = Pc.PanelTitle, fontSize = 17.sp, modifier = Modifier.weight(1f))- Switch(a.blendPrimary, enabled = true)+ ToggleRow("Blend primary frame", a.blendPrimary, 44.5.dp) { vm.changeAnimation { it.copy(blendPrimary = !it.blendPrimary) } }+ RowLine()+ Box(Modifier.fillMaxWidth().height(44.5.dp).clickable(onClick = onColors).padding(start = 16.dp), contentAlignment = Alignment.CenterStart) {+ Text("Onion skin colors", color = Pc.PanelTitle, fontSize = 17.sp)+ }+ }+}++/**+ * The onion skins' colours: back to the settings, "Colors" and Reset over two swatches (the frames+ * before the current one, then those after; a tap picks which the picker below edits) and the+ * compact picker with its mode tabs. Black leaves the skins as they are.+ */+@Composable+private fun ColumnScope.OnionColorsPage(vm: CanvasViewModel, onBack: () -> Unit) {+ val a = vm.animation ?: return+ var after by remember { mutableStateOf(false) }+ var mode by remember { mutableStateOf(io.github.artcraftandroid.procraft.canvas.ColorMode.DISC) }+ val rgbOf = { v: List<Float> -> v.take(3).fold(0) { acc, x -> (acc shl 8) or (x.coerceIn(0f, 1f) * 255f).roundToInt() } }+ val unit = { rgb: Int -> listOf((rgb shr 16) and 0xFF, (rgb shr 8) and 0xFF, rgb and 0xFF).map { it / 255f } }+ val c = remember(after) {+ HeldColor(rgbOf(if (after) a.after else a.before), greyHue = 0f) { rgb -> vm.changeAnimation { if (after) it.copy(after = unit(rgb)) else it.copy(before = unit(rgb)) } }+ }+ // the back button at the panel's very edge+ Row(Modifier.offset(x = (-8).dp).fillMaxWidth().height(34.dp), verticalAlignment = Alignment.CenterVertically) {+ Box(Modifier.size(44.dp, 34.dp).clickable(onClick = onBack), contentAlignment = Alignment.Center) {+ Icon(PcIcons.ChevronLeft, contentDescription = "Back", tint = Pc.SlideValue, modifier = Modifier.requiredSize(34.dp))}- Box(Modifier.fillMaxWidth().height(1.dp).background(Pc.ActionsSeparator))- Box(Modifier.fillMaxWidth().height(45.dp).padding(start = 16.dp), contentAlignment = Alignment.CenterStart) {- Text("Onion skin colors", color = Pc.ActionsDisabled, fontSize = 17.sp)+ Text("Colors", color = Pc.PanelTitle, fontSize = 23.sp, fontWeight = FontWeight.Bold, modifier = Modifier.weight(1f))+ Text(+ "Reset", color = Pc.SlideValue, fontSize = 17.sp,+ modifier = Modifier.clickable {+ vm.changeAnimation { it.copy(before = listOf(0f, 0f, 0f), after = listOf(0f, 0f, 0f)) }+ c.setRgb(0)+ }.padding(start = 12.dp, end = 0.dp),+ )+ }+ Row(Modifier.padding(start = 13.dp, top = 7.dp), horizontalArrangement = Arrangement.spacedBy(5.dp)) {+ for ((i, v) in listOf(a.before, a.after).withIndex()) {+ Box(+ Modifier.size(44.dp, 26.dp).clip(RoundedCornerShape(7.dp)).background(SwatchRim).padding(1.dp)+ .clip(RoundedCornerShape(6.dp)).background(Color(0xFF000000.toInt() or rgbOf(v))).clickable { after = i == 1 },+ )}}+ // the 260-wide compact picker drawn 282 wide, in a body of fixed height over the tabs+ Box(Modifier.offset(x = (-4).dp).padding(top = 11.dp).size(282.dp, 365.dp)) {+ Box(Modifier.scaledFrom(260.dp, 282.dp)) { CompactBody(vm, c, mode) }+ }+ Box(Modifier.offset(x = (-4).dp).width(282.dp)) { CompactTabs(mode) { mode = it } }}-/** The current frame's options: how long it is held, Duplicate, Delete, and Background or Foreground. */+private val SwatchRim = Color(0xFF969696)++/** Lays out its content [from] wide and shows it scaled up to [to] wide, touches and all. */+private fun Modifier.scaledFrom(from: Dp, to: Dp): Modifier = layout { measurable, _ ->+ val k = to / from+ val p = measurable.measure(androidx.compose.ui.unit.Constraints.fixedWidth(from.roundToPx()))+ layout((p.width * k).roundToInt(), (p.height * k).roundToInt()) {+ p.placeWithLayer(0, 0) {+ scaleX = k+ scaleY = k+ transformOrigin = androidx.compose.ui.graphics.TransformOrigin(0f, 0f)+ }+ }+}++/**+ * The current frame's options: how long it is held, Duplicate, Delete, and Foreground for the last+ * frame and Background for the first (both for a lone frame). Pages: Duplicate, Delete, and+ * Background for the first.+ */@Composableprivate fun ColumnScope.FrameOptionsPage(vm: CanvasViewModel) {val a = vm.animation ?: return@@ -210,9 +284,9 @@ private fun ColumnScope.FrameOptionsPage(vm: CanvasViewModel) {val last = vm.animationFrames.size - 1// re-read when the hold changesval hold = vm.holdVersion.let { vm.frameHold() }- Text(if (a.pages) "Page options" else "Frame options", color = Pc.PanelTitle, fontSize = 22.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(start = 14.dp, top = 2.dp, bottom = 12.dp))+ Text(if (a.pages) "Page options" else "Frame options", color = Pc.PanelTitle, fontSize = 23.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(start = 14.dp, top = 11.dp, bottom = 15.dp))if (!a.pages) {- Group {+ SliderGroup(top = 4.dp) {ValueSlider("Hold duration", if (hold == 0) "None" else "$hold", hold / CanvasViewModel.MAX_HOLD.toFloat()) { v ->vm.changeFrameHold((v * CanvasViewModel.MAX_HOLD).roundToInt())}@@ -220,41 +294,63 @@ private fun ColumnScope.FrameOptionsPage(vm: CanvasViewModel) {Spacer(Modifier.height(10.dp))}Group {- Row(Modifier.fillMaxWidth().height(45.dp).clickable { vm.duplicateFrame() }.padding(start = 16.dp), verticalAlignment = Alignment.CenterVertically) {+ Row(Modifier.fillMaxWidth().height(44.dp).clickable { vm.duplicateFrame() }.padding(start = 16.dp), verticalAlignment = Alignment.CenterVertically) {Text("Duplicate", color = Pc.PanelTitle, fontSize = 17.sp)}- Box(Modifier.fillMaxWidth().height(1.dp).background(Pc.ActionsSeparator))- Row(Modifier.fillMaxWidth().height(45.dp).clickable { vm.deleteFrame() }.padding(start = 16.dp), verticalAlignment = Alignment.CenterVertically) {+ RowLine()+ Row(Modifier.fillMaxWidth().height(44.dp).clickable { vm.deleteFrame() }.padding(start = 16.dp), verticalAlignment = Alignment.CenterVertically) {Text("Delete", color = Pc.PanelTitle, fontSize = 17.sp)}}- if (!a.pages && (index == 0 || (index == last && last > 0))) {+ val foreground = !a.pages && index == last+ val background = index == 0+ if (foreground || background) {Spacer(Modifier.height(10.dp))- val background = index == 0- val on = if (background) a.background else a.foregroundGroup {- Row(- Modifier.fillMaxWidth().height(45.dp).clickable { vm.changeAnimation { if (background) it.copy(background = !on) else it.copy(foreground = !on) } }.padding(start = 16.dp, end = 6.dp),- verticalAlignment = Alignment.CenterVertically,- ) {- Text(if (background) "Background" else "Foreground", color = Pc.PanelTitle, fontSize = 17.sp, modifier = Modifier.weight(1f))- Switch(on, enabled = true)- }+ if (foreground) ToggleRow("Foreground", a.foreground, 44.dp) { vm.changeAnimation { it.copy(foreground = !it.foreground) } }+ if (foreground && background) RowLine()+ if (background) ToggleRow("Background", a.background, 44.dp) { vm.changeAnimation { it.copy(background = !it.background) } }}}}+@Composable+private fun ToggleRow(label: String, on: Boolean, height: Dp, onClick: () -> Unit) {+ Row(Modifier.fillMaxWidth().height(height).clickable(onClick = onClick).padding(start = 16.dp, end = 6.dp), verticalAlignment = Alignment.CenterVertically) {+ Text(label, color = Pc.PanelTitle, fontSize = 17.sp, modifier = Modifier.weight(1f))+ Switch(on, enabled = true)+ }+}++/** The faint 2 pt line between a group's rows. */+@Composable+private fun RowLine() {+ Box(Modifier.fillMaxWidth().height(2.dp).background(RowLineFill))+}+@Composableprivate fun Group(content: @Composable ColumnScope.() -> Unit) {Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(18.dp)).background(Pc.ActionsGroup), content = content)}+/** A group of sliders: [top] above the first, 11.5 between. */+@Composable+private fun SliderGroup(top: Dp = 8.dp, content: @Composable ColumnScope.() -> Unit) {+ Column(+ Modifier.fillMaxWidth().clip(RoundedCornerShape(18.dp)).background(Pc.ActionsGroup).padding(top = top),+ verticalArrangement = Arrangement.spacedBy(11.5.dp),+ content = content,+ )+}++private val RowLineFill = Color(0x09FFFFFF)+/** A setting's name and value over a bar dragged or tapped along. */@Composableprivate fun ValueSlider(label: String, value: String, fraction: Float, onChange: (Float) -> Unit) {val change by rememberUpdatedState(onChange)- Column(Modifier.fillMaxWidth().height(62.dp).padding(horizontal = 16.dp)) {- Row(Modifier.fillMaxWidth().padding(top = 12.dp)) {+ Column(Modifier.fillMaxWidth().height(55.dp).padding(horizontal = 16.dp)) {+ Row(Modifier.fillMaxWidth().padding(top = 6.5.dp)) {Text(label, color = Pc.SlideLabel, fontSize = 17.sp, modifier = Modifier.weight(1f), maxLines = 1)Text(value, color = Pc.SlideValue, fontSize = 17.sp, maxLines = 1)}diff --git a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ColorPanel.kt b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ColorPanel.ktindex 31717ef..ceaa8b9 100644--- a/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ColorPanel.kt+++ b/apps/procraft-android/android/app/src/main/java/io/github/artcraftandroid/procraft/ui/ColorPanel.kt@@ -160,10 +160,12 @@ private class BrushColor(private val vm: CanvasViewModel) : ColorPick {override fun setRgb(rgb: Int) = vm.setRgb(rgb)}-/** A colour of its own, starting at [rgb]; [onChange] hears every change. Greys keep their hue. */-class HeldColor(rgb: Int, private val onChange: (Int) -> Unit) : ColorPick {- // a grey has no hue of its own: it opens at 180 degrees, as measured- override var hue by mutableFloatStateOf(0.5f)+/**+ * A colour of its own, starting at [rgb]; [onChange] hears every change. Greys keep their hue, and+ * a grey opens at [greyHue] (180 degrees, as measured; some pickers open at 0).+ */+class HeldColor(rgb: Int, greyHue: Float = 0.5f, private val onChange: (Int) -> Unit) : ColorPick {+ override var hue by mutableFloatStateOf(greyHue)private setoverride var saturation by mutableFloatStateOf(0f)private set@@ -275,19 +277,31 @@ fun CompactColors(vm: CanvasViewModel, c: ColorPick, arrowX: Dp, modifier: Modifvar mode by remember { mutableStateOf(ColorMode.DISC) }Popover(CompactWidth, arrowX, modifier, fill = CompactFill, side = side) {Text("Colors", color = Pc.PanelTitle, fontSize = 24.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(start = 18.dp, top = 9.dp, bottom = 5.dp))- when (mode) {- ColorMode.DISC -> Disc(c, compact = true)- ColorMode.VALUE -> Value(c, compact = true)- ColorMode.HARMONY -> Harmony(vm, c, compact = true)- ColorMode.PALETTES -> CompactPalettes(vm, c)- else -> Classic(c, compact = true)- }- Row(Modifier.fillMaxWidth().height(52.dp)) {- for ((m, icon, label) in Modes) {- Box(Modifier.weight(1f).fillMaxSize().clickable { mode = m }, contentAlignment = Alignment.Center) {- // the tabs' 36-unit glyphs, a little smaller here- Icon(icon, contentDescription = label, tint = if (m == mode) Pc.Accent else Pc.PanelTitle, modifier = Modifier.requiredSize(33.dp))- }+ CompactBody(vm, c, mode)+ CompactTabs(mode) { mode = it }+ }+}++/** The compact picker for [mode], 260 wide: the disc, the square, harmony, values or the palettes. */+@Composable+internal fun CompactBody(vm: CanvasViewModel, c: ColorPick, mode: ColorMode) {+ when (mode) {+ ColorMode.DISC -> Disc(c, compact = true)+ ColorMode.VALUE -> Value(c, compact = true)+ ColorMode.HARMONY -> Harmony(vm, c, compact = true)+ ColorMode.PALETTES -> CompactPalettes(vm, c)+ else -> Classic(c, compact = true)+ }+}++/** The compact picker's modes as a row of icons, the chosen one blue. */+@Composable+internal fun CompactTabs(mode: ColorMode, onMode: (ColorMode) -> Unit) {+ Row(Modifier.fillMaxWidth().height(52.dp)) {+ for ((m, icon, label) in Modes) {+ Box(Modifier.weight(1f).fillMaxSize().clickable { onMode(m) }, contentAlignment = Alignment.Center) {+ // the tabs' 36-unit glyphs, a little smaller here+ Icon(icon, contentDescription = label, tint = if (m == mode) Pc.Accent else Pc.PanelTitle, modifier = Modifier.requiredSize(33.dp))}}}diff --git a/crates/engine/src/animation.rs b/crates/engine/src/animation.rsindex 4e024cf..23106c7 100644--- a/crates/engine/src/animation.rs+++ b/crates/engine/src/animation.rs@@ -31,7 +31,8 @@ pub struct Animation {pub playback: Playback,/// The current frame shows blended with the onion skins instead of over them.pub blend_primary: bool,- /// The colours onion skin frames take: before the current frame and after it (sRGB 0..1).+ /// The colours onion skin frames are screened with, before the current frame and after it+ /// (sRGB 0..1); black leaves them as they are.pub before: [f32; 3],pub after: [f32; 3],/// The first frame always shows, behind every other.@@ -52,8 +53,8 @@ impl Default for Animation {onion_opacity: 0.6,playback: Playback::Loop,blend_primary: false,- before: [0.9, 0.12, 0.12],- after: [0.12, 0.7, 0.2],+ before: [0.0; 3],+ after: [0.0; 3],background: false,foreground: false,holds: Vec::new(),@@ -92,7 +93,7 @@ impl Animation {#[derive(Clone, Copy, Debug, PartialEq)]pub enum FrameLook {Shown,- /// An onion skin: tinted towards `color` and at `opacity`.+ /// An onion skin: screened with `color` (black: unchanged) and at `opacity`.Onion {color: [f32; 3],opacity: f32,@@ -122,7 +123,8 @@ pub fn current_frame(doc: &Document) -> Option<usize> {/// one played: no onion skins then).pub fn look(a: &Animation, index: usize, count: usize, current: usize, playing: bool) -> FrameLook {if a.pages {- return if index == current { FrameLook::Shown } else { FrameLook::Hidden };+ // a background page shows behind every page+ return if index == current || (a.background && index == 0) { FrameLook::Shown } else { FrameLook::Hidden };}let last = count.saturating_sub(1);if index == current || (a.background && index == 0) || (a.foreground && index == last && count > 1) {@@ -136,10 +138,10 @@ pub fn look(a: &Animation, index: usize, count: usize, current: usize, playing:if distance == 0 || distance > n {return FrameLook::Hidden;}- // the nearest at the set opacity, fading to nothing past the furthest+ // the nearest at the set opacity squared (60% shows at 36%), fading to nothing past the furthestlet fade = 1.0 - (distance - 1) as f32 / n as f32;let color = if index < current { a.before } else { a.after };- FrameLook::Onion { color, opacity: a.onion_opacity * fade }+ FrameLook::Onion { color, opacity: a.onion_opacity * a.onion_opacity * fade }}#[cfg(test)]@@ -152,21 +154,24 @@ mod tests {assert_eq!(look(&a, 3, 6, 3, false), FrameLook::Shown);let FrameLook::Onion { color, opacity } = look(&a, 2, 6, 3, false) else { panic!() };assert_eq!(color, a.before);- assert!((opacity - 0.6).abs() < 1e-6);+ assert!((opacity - 0.36).abs() < 1e-6);let FrameLook::Onion { color, opacity } = look(&a, 5, 6, 3, false) else { panic!() };assert_eq!(color, a.after);- assert!((opacity - 0.3).abs() < 1e-6);+ assert!((opacity - 0.18).abs() < 1e-6);assert_eq!(look(&a, 0, 6, 3, false), FrameLook::Hidden);// playing, only the played frame (and a background) showsassert_eq!(look(&a, 2, 6, 3, true), FrameLook::Hidden);- let b = Animation { background: true, foreground: true, ..a };+ let b = Animation { background: true, foreground: true, ..a.clone() };assert_eq!(look(&b, 0, 6, 3, true), FrameLook::Shown);assert_eq!(look(&b, 5, 6, 3, true), FrameLook::Shown);- // pages: only the current one- let p = Animation { pages: true, ..b };+ // pages: only the current one, and a background page behind it+ let p = Animation { pages: true, ..a };assert_eq!(look(&p, 3, 6, 3, false), FrameLook::Shown);assert_eq!(look(&p, 0, 6, 3, false), FrameLook::Hidden);assert_eq!(look(&p, 2, 6, 3, false), FrameLook::Hidden);+ let p = Animation { pages: true, ..b };+ assert_eq!(look(&p, 0, 6, 3, false), FrameLook::Shown);+ assert_eq!(look(&p, 5, 6, 3, false), FrameLook::Hidden);}#[test]diff --git a/crates/engine/src/native.rs b/crates/engine/src/native.rsindex fe43ecc..fa9ef62 100644--- a/crates/engine/src/native.rs+++ b/crates/engine/src/native.rs@@ -420,16 +420,23 @@ pub fn write(e: &Export<'_>) -> Vec<u8> {&["ValkyrieColorProfile", "NSObject"],vec![("SiColorProfileArchiveICCNameKey", icc_name), ("SiColorProfileArchiveICCDataKey", Value::Data(icc_data))],);+ // the canvas's settings; whether Animation Assist is on isn't written (its number unknown yet)+ let a = doc.animation.clone().unwrap_or_default();+ let playback = match a.playback {+ crate::animation::Playback::OneShot => 0,+ crate::animation::Playback::Loop => 1,+ crate::animation::Playback::PingPong => 2,+ };let animation = b.object(&["ValkyrieDocumentAnimation", "NSObject"],vec![("animationMode", Value::Int(0)),- ("frameRate", Value::Int(15)),- ("onionSkinCount", Value::Int(12)),- ("onionSkinOpacity", Value::Real(0.6)),+ ("frameRate", Value::Int(i64::from(a.fps))),+ ("onionSkinCount", Value::Int(i64::from(a.onion_frames))),+ ("onionSkinOpacity", Value::Real(f64::from(a.onion_opacity))),("playbackDirection", Value::Int(0)),- ("playbackMode", Value::Int(1)),- ("primaryMixed", Value::Bool(false)),+ ("playbackMode", Value::Int(playback)),+ ("primaryMixed", Value::Bool(a.blend_primary)),],);let size = b.string(&format!("{{{w}, {h}}}"));@@ -516,7 +523,7 @@ fn write_item(return b.object(&["SilicaGroup", "ValkyrieGroup", "NSObject"],vec![- ("animationHeldLength", Value::Int(0)),+ ("animationHeldLength", Value::Int(held(doc, id))),("children", children),("document", doc_ref.clone()),("isClipped", Value::Bool(l.clipped)),@@ -552,6 +559,7 @@ fn write_item(clipped: false,alpha_lock: false,private: false,+ held: 0,};Some(layer_record(b, doc_ref, &mask_uuid, None, rec, w, h))});@@ -566,6 +574,7 @@ fn write_item(clipped: l.clipped,alpha_lock: l.alpha_lock,private: l.private,+ held: held(doc, id),};let r = layer_record(b, doc_ref, &uuid, mask, rec, w, h);if id == doc.current() {@@ -590,6 +599,13 @@ struct LayerRecord<'a> {alpha_lock: bool,/// Left out of the file's preview.private: bool,+ /// Animation Assist: how many more frames this frame is held for.+ held: i64,+}++/// How many more frames Animation Assist holds layer `id` for (0 without a hold).+fn held(doc: &Document, id: LayerId) -> i64 {+ doc.animation.as_ref().map_or(0, |a| i64::from(a.hold(id)))}impl LayerRecord<'_> {@@ -605,6 +621,7 @@ impl LayerRecord<'_> {clipped: false,alpha_lock: false,private: false,+ held: 0,}}}@@ -640,7 +657,7 @@ fn layer_record(&["SilicaLayer", "ValkyrieLayer", "NSObject"],vec![("UUID", uuid),- ("animationHeldLength", Value::Int(0)),+ ("animationHeldLength", Value::Int(r.held)),("blend", Value::Int(older_blends(r.blend).0)),("bundledImagePath", Builder::null()),("bundledMaskPath", Builder::null()),@@ -958,6 +975,44 @@ mod tests {assert_eq!(shape(d), shape(&doc));}+ #[test]+ fn animation_settings_are_the_canvases_own() {+ let mut doc = Document::new(16, 16);+ let id = doc.current();+ let mut a = crate::animation::Animation {+ fps: 24,+ onion_frames: 3,+ onion_opacity: 0.25,+ playback: crate::animation::Playback::PingPong,+ blend_primary: true,+ ..Default::default()+ };+ a.set_hold(id, 2);+ doc.animation = Some(a);+ let pixels = HashMap::from([(id, vec![0u8; 16 * 16 * 4])]);+ let bytes = write(&Export {+ document: &doc,+ pixels: &pixels,+ composite: &[0; 16 * 16 * 4],+ thumbnail_png: &[],+ name: "",+ author: "",+ strokes: 0,+ tracked_seconds: 0.0,+ seed: 1,+ });+ let zip = ZipReader::new(&bytes).unwrap();+ let archive = Archive::read(&zip.read("Document.archive").unwrap()).unwrap();+ let root = archive.root().unwrap();+ let anim = root.object("animation").unwrap();+ assert_eq!(anim.int("frameRate"), Some(24));+ assert_eq!(anim.int("onionSkinCount"), Some(3));+ assert_eq!(anim.real("onionSkinOpacity"), Some(0.25));+ assert_eq!(anim.int("playbackMode"), Some(2));+ assert_eq!(anim.bool("primaryMixed"), Some(true));+ assert_eq!(root.object("selectedLayer").unwrap().int("animationHeldLength"), Some(2));+ }+#[test]fn turned_canvases_are_shown_upright() {// 3 × 2, values = index; a quarter turn clockwise makes it 2 × 3diff --git a/crates/gpu/src/canvas.rs b/crates/gpu/src/canvas.rsindex acd1db0..6e8710b 100644--- a/crates/gpu/src/canvas.rs+++ b/crates/gpu/src/canvas.rs@@ -511,7 +511,7 @@ struct LayerUniform {stroke_on_mask: f32,/// How the stroke blends into the layer (a blend mode's number).stroke_blend: u32,- /// An onion skin's colour and how far towards it the layer goes (none at 0).+ /// An onion skin's colour, screened over the layer, and how much (none at 0).tint: [f32; 4],/// The stroke's texturized grain turned, radians, and how it and the burnt edges combine/// with the stroke (blend modes' numbers).diff --git a/crates/gpu/src/shaders/composite.wgsl b/crates/gpu/src/shaders/composite.wgslindex 4334e57..aa72704 100644--- a/crates/gpu/src/shaders/composite.wgsl+++ b/crates/gpu/src/shaders/composite.wgsl@@ -29,7 +29,7 @@ struct LayerUniform {stroke_on_mask: f32,// how the stroke blends into the layer: a blend mode's number (0: normal)stroke_blend: u32,- // an onion skin's colour (rgb) and how far towards it the layer goes (a)+ // an onion skin's colour (rgb), screened over the layer, and how much (a)tint: vec4<f32>,// the stroke's texturized grain turned, radians, and how it and the burnt edges combine with// the stroke (blend modes' numbers)@@ -176,7 +176,8 @@ fn layer_color(p: vec2<i32>) -> vec4<f32> {c = c * textureLoad(clip_tex, p, 0).a;}if (lu.tint.a > 0.0) {- c = vec4<f32>(mix(c.rgb, lu.tint.rgb * c.a, lu.tint.a), c.a);+ // screen, premultiplied: black leaves the layer as it is+ c = vec4<f32>(mix(c.rgb, c.rgb + lu.tint.rgb * (vec3<f32>(c.a) - c.rgb), lu.tint.a), c.a);}return c * lu.opacity;}