Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.
Kotlin alternativeandroidandroid-applicationclientglassmorphisminnertubelibrespotliquid-glassspotifyspotify-connectspotifyapiyoutube-musicyoutube-playerytdlnis
Draw the glass with liquid_glass_widgets' material
Lelonio5cf2e2e002ce
diff --git a/app/src/main/java/dev/lelonio/square/ui/glass/GlassEffect.kt b/app/src/main/java/dev/lelonio/square/ui/glass/GlassEffect.ktindex f98aada..d0d9a8f 100644--- a/app/src/main/java/dev/lelonio/square/ui/glass/GlassEffect.kt+++ b/app/src/main/java/dev/lelonio/square/ui/glass/GlassEffect.kt@@ -5,6 +5,7 @@package dev.lelonio.square.ui.glass+import dev.lelonio.square.ui.glass.morph.liquidGlassMaterialimport android.app.ActivityManagerimport android.os.Buildimport androidx.compose.foundation.shape.CornerBasedShape@@ -446,9 +447,21 @@ fun Modifier.liquidGlass(// glass IS, which is the part that now has one answer.layerBlock: (GraphicsLayerScope.() -> Unit)? = null,onDrawTint: (DrawScope.() -> Unit)? = null,+ /**+ * Where a finger is on this surface and how far it is pressed, for+ * upstream's touch glint: the rim nearest the finger lights up. Read+ * while the frame is drawn; null for a surface nobody presses.+ */+ touch: (() -> GlassTouch?)? = null,): Modifier {val density = LocalDensity.current- val resolutionScale = backdropScale.coerceIn(0.05f, 1f)+ // Upstream's material draws its edge, its lighting and its anti-aliasing+ // in the shader, at the layer's own resolution: recorded at a fraction+ // and stretched back up, the rim came out soft and doubled. It is drawn+ // at full resolution, as upstream draws it.+ val upstreamCapable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&+ config.style != GlassStyle.BLUR && applyEdgeEffects+ val resolutionScale = if (upstreamCapable) 1f else backdropScale.coerceIn(0.05f, 1f)// A surface that names its own condition (the tab bar, mid-fold) still// obeys the app-wide one: either reason to hold the last capture is enough.val appFrozen = LocalGlassFrozen.current@@ -591,6 +604,22 @@ fun Modifier.liquidGlass(// expensive link in the effect chain.val plainBlur = config.style == GlassStyle.BLUR+ // liquid_glass_widgets' material, where the phone can run it: its+ // refraction, tint, saturation and lit edge, in its own shader, from the+ // listener's settings (see toLiquidGlassSettings). The film the bar has+ // always worn is its glass colour, so a pane still follows what is behind+ // it. Below Android 13 the chain below is the app's own, as before.+ val upstream = upstreamCapable+ val upstreamSettings = config.toLiquidGlassSettings().copy(+ blur = blurRadiusDp,+ glassColor = surfaceTintColor.copy(alpha = config.surfaceOpacity.coerceIn(0f, 1f)),+ )+ // Upstream's blur is a sigma in logical pixels; Android's takes a radius.+ val upstreamBlurPx = dev.lelonio.square.ui.glass.morph.blurRadiusForSigma(+ with(density) { blurRadiusDp.dp.toPx() },+ ) * resolutionScale+ val lightPage = dev.lelonio.square.ui.theme.LocalLightTheme.current+val effectsBlock: BackdropEffectScope.() -> Unit = remember(saturation,blurPx,@@ -600,7 +629,18 @@ fun Modifier.liquidGlass(lensAmountPx,config.depthEffect,config.chromaticAberration,+ upstream,+ upstreamSettings,+ upstreamBlurPx,+ touch,) {+ if (upstream) {+ {+ if (upstreamBlurPx > 0f) blur(upstreamBlurPx)+ val pressed = touch?.invoke()+ liquidGlassMaterial(upstreamSettings, pressed?.position, pressed?.intensity ?: 0f)+ }+ } else {{if (saturation != 1f) {colorControls(saturation = saturation)@@ -648,6 +688,7 @@ fun Modifier.liquidGlass()}}+ }}// The rim's own colour, independent of the surface tint: on a tinted pill a@@ -662,8 +703,9 @@ fun Modifier.liquidGlass(// per-component tuning and the preference still mean something.val rimAlpha = (highlightAlpha * (config.highlightOpacity / EdgeHighlightAlpha)).coerceIn(0f, 1f)- val highlightBlock: (() -> Highlight?)? = remember(applyEdgeEffects, plainBlur, rimColor, rimAlpha, animatedHighlightAngle) {- if (applyEdgeEffects && !plainBlur) {+ val highlightBlock: (() -> Highlight?)? = remember(applyEdgeEffects, plainBlur, rimColor, rimAlpha, animatedHighlightAngle, upstream) {+ // Upstream's shader lights its own edge.+ if (applyEdgeEffects && !plainBlur && !upstream) {{Highlight(width = EdgeHighlightWidth,@@ -678,15 +720,32 @@ fun Modifier.liquidGlass(}}- val shadowBlock: (() -> Shadow?)? = remember(applyEdgeEffects) {- if (applyEdgeEffects) ({ Shadow.Default }) else null+ val shadowBlock: (() -> Shadow?)? = remember(applyEdgeEffects, upstream, lightPage) {+ when {+ !applyEdgeEffects -> null+ // Upstream's GlassShadow.elevation, on light pages only, as+ // upstream draws it: 0x0F black, an 8 px blur, 2 px down.+ upstream -> if (lightPage) {+ {+ Shadow(+ radius = 8.dp,+ offset = androidx.compose.ui.unit.DpOffset(0.dp, 2.dp),+ color = Color.Black.copy(alpha = 15f / 255f),+ )+ }+ } else {+ null+ }+ else -> ({ Shadow.Default })+ }}// RenderEffect is guaranteed supported past this point — the unsupported// case already returned the translucent-tint fallback above.- val surfaceBlock: DrawScope.() -> Unit = remember(surfaceTintColor, config.surfaceOpacity, onDrawTint) {+ val surfaceBlock: DrawScope.() -> Unit = remember(surfaceTintColor, config.surfaceOpacity, onDrawTint, upstream) {{- if (config.surfaceOpacity > 0f) {+ // Upstream's shader tints the glass itself.+ if (config.surfaceOpacity > 0f && !upstream) {drawRect(color = surfaceTintColor.copy(alpha = config.surfaceOpacity),size = size,@@ -754,3 +813,53 @@ private fun tintedRim(base: Color, config: GlassEffectConfig): Color {/** How coloured the film and the rim go at full strength. */private const val TINT_SATURATION = 0.55fprivate const val TINT_RIM_SATURATION = 0.85f++/**+ * The listener's glass, as liquid_glass_widgets' material takes it.+ *+ * Through upstream's own translation of designer parameters+ * (`LiquidGlassSettings.figma`): the bend, as a percentage, sets the+ * refractive index at `1 + bend × 0.2`; the edge depth is the bevel's+ * thickness; colour splitting is a dispersion; the frost is the blur's sigma;+ * the rim light is the light's intensity. Saturation is this app's vibrancy,+ * the film is the one the bar wears, and the depth switch is upstream's edge+ * absorption at the strength of its iOS 27 material. The optics — how these+ * bend, tint and light the glass — are upstream's, in its shader.+ *+ * [blurScale] thickens the frost for the surfaces that need more than a pill,+ * and [minBlur] is the least they may have, in logical pixels.+ */+@Composable+fun GlassEffectConfig.toLiquidGlassSettings(+ blurScale: Float = 1f,+ minBlur: Float = 0f,+): dev.lelonio.square.ui.glass.morph.LiquidGlassSettings {+ val light = dev.lelonio.square.ui.theme.LocalLightTheme.current+ val film = tinted(+ when {+ surfaceTintColor.isSpecified -> surfaceTintColor+ light -> Color(0xFFFAFAFA)+ else -> Color(0xFF23232A)+ },+ this,+ ).copy(alpha = surfaceOpacity.coerceIn(0f, 1f))+ val liquid = style != GlassStyle.BLUR+ return dev.lelonio.square.ui.glass.morph.LiquidGlassSettings(+ refractiveIndex = if (liquid) 1f + lensAmount.coerceIn(0f, 1f) * 0.2f else 1f,+ thickness = if (liquid) (lensHeight * LENS_MAX_DP).coerceAtLeast(1f) else 1f,+ chromaticAberration = if (liquid && chromaticAberration) 4f * DISPERSION_SHARE else 0f,+ lightIntensity = if (liquid) highlightOpacity.coerceIn(0f, 1f) else 0f,+ blur = (blurRadius * blurScale).coerceAtLeast(minBlur),+ ambientStrength = 0.1f,+ saturation = glassSaturation(vibrancy),+ glassColor = film,+ edgeAbsorption = if (depthEffect) 0.035f else 0f,+ )+}++/** The dispersion colour splitting stands for, as a share of upstream's 0–100 %. */+private const val DISPERSION_SHARE = 0.10f++/** A finger on a glass surface: where, in its own pixels, and how far pressed (0..1). */+data class GlassTouch(val position: androidx.compose.ui.geometry.Offset, val intensity: Float)diff --git a/app/src/main/java/dev/lelonio/square/ui/glass/InteractiveHighlight.kt b/app/src/main/java/dev/lelonio/square/ui/glass/InteractiveHighlight.ktindex 2492fea..64224e6 100644--- a/app/src/main/java/dev/lelonio/square/ui/glass/InteractiveHighlight.kt+++ b/app/src/main/java/dev/lelonio/square/ui/glass/InteractiveHighlight.kt@@ -48,6 +48,10 @@ class InteractiveHighlight(val pressProgress: Float get() = pressProgressAnimation.valueval offset: Offset get() = positionAnimation.value - startPosition+ // LOCAL CHANGE: where the finger is, in the control's own pixels, for+ // liquid_glass_widgets' touch glint (see liquidGlassMaterial).+ val touchPosition: Offset get() = positionAnimation.value+private val shader =if (isRuntimeShaderSupported()) {RuntimeShader(diff --git a/app/src/main/java/dev/lelonio/square/ui/glass/LiquidBottomTabs.kt b/app/src/main/java/dev/lelonio/square/ui/glass/LiquidBottomTabs.ktindex f611938..e8f5221 100644--- a/app/src/main/java/dev/lelonio/square/ui/glass/LiquidBottomTabs.kt+++ b/app/src/main/java/dev/lelonio/square/ui/glass/LiquidBottomTabs.kt@@ -10,6 +10,7 @@package dev.lelonio.square.ui.glass+import dev.lelonio.square.ui.glass.morph.liquidGlassIndicatorimport androidx.compose.animation.core.Animatableimport androidx.compose.animation.core.EaseOutimport androidx.compose.animation.core.spring@@ -388,12 +389,25 @@ fun LiquidBottomTabs(backdrop = pressedBackdrop,shape = { ContinuousCapsule() },effects = {+ // At rest the slot is frosted like the bar under it:+ // upstream's resting pill sits on the bar's glass and+ // lets it show through, where this slot draws the+ // page itself, and drawn clear it let the page+ // straight through the bar. The frost lifts as it is+ // pressed, down to upstream's clear lens.vibrancy()blur(8f.dp.toPx() * (1f - dampedDragAnimation.pressProgress.coerceIn(0f, 1f)))- slotLens()+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {+ // LOCAL CHANGE: liquid_glass_widgets' indicator+ // glass, coming in with the press.+ liquidGlassIndicator(dampedDragAnimation.pressProgress)+ } else {+ slotLens()+ }},highlight = {val progress = dampedDragAnimation.pressProgress+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) return@drawBackdrop nullHighlight.Default.copy(alpha = progress)},shadow = {@@ -402,6 +416,7 @@ fun LiquidBottomTabs(},innerShadow = {val progress = dampedDragAnimation.pressProgress+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) return@drawBackdrop nullInnerShadow(radius = 8f.dp * progress,alpha = progress@@ -409,11 +424,18 @@ fun LiquidBottomTabs(},onDrawSurface = {val progress = dampedDragAnimation.pressProgress- drawRect(containerColor, alpha = 1f - progress)+ // Upstream's resting pill fades over the first 0.15+ // of the press, as its glass comes in.+ val resting = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {+ dev.lelonio.square.ui.glass.morph.indicatorRestingAlpha(progress)+ } else {+ 1f - progress+ }+ drawRect(containerColor, alpha = resting)drawRect(indicatorColor ?: if (isLightTheme) Color.Black.copy(0.1f)else Color.White.copy(0.1f),- alpha = 1f - progress+ alpha = resting)drawRect(Color.Black.copy(alpha = 0.03f * progress))}diff --git a/app/src/main/java/dev/lelonio/square/ui/glass/LiquidButton.kt b/app/src/main/java/dev/lelonio/square/ui/glass/LiquidButton.ktindex b5dd5a8..1b874fa 100644--- a/app/src/main/java/dev/lelonio/square/ui/glass/LiquidButton.kt+++ b/app/src/main/java/dev/lelonio/square/ui/glass/LiquidButton.kt@@ -128,6 +128,19 @@ fun LiquidButton(// The bar's rim, so a button beside it is cut from the same pane.highlightAlpha = dev.lelonio.square.ui.player.BarHighlightAlpha,ownBackdrop = backdrop,+ // Upstream's touch glint, on the rim nearest the finger.+ touch = if (isInteractive) {+ remember(interactiveHighlight) {+ {+ GlassTouch(+ interactiveHighlight.touchPosition,+ interactiveHighlight.pressProgress,+ )+ }+ }+ } else {+ null+ },layerBlock = if (isInteractive) {{val width = size.widthdiff --git a/app/src/main/java/dev/lelonio/square/ui/glass/LiquidSlider.kt b/app/src/main/java/dev/lelonio/square/ui/glass/LiquidSlider.ktindex 3100d7e..14ce45b 100644--- a/app/src/main/java/dev/lelonio/square/ui/glass/LiquidSlider.kt+++ b/app/src/main/java/dev/lelonio/square/ui/glass/LiquidSlider.kt@@ -10,6 +10,7 @@package dev.lelonio.square.ui.glass+import dev.lelonio.square.ui.glass.morph.liquidGlassIndicatorimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.gestures.awaitEachGestureimport androidx.compose.foundation.gestures.awaitFirstDown@@ -279,6 +280,12 @@ fun LiquidSlider(shape = { ContinuousCapsule() },effects = {val progress = dampedDragAnimation.pressProgress+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {+ // LOCAL CHANGE: liquid_glass_widgets' indicator+ // glass, coming in with the press; see+ // liquidGlassIndicator.+ liquidGlassIndicator(progress)+ } else {blur(8f.dp.toPx() * (1f - progress))lens(10f.dp.toPx() * progress,@@ -287,9 +294,12 @@ fun LiquidSlider(// switch, as every other pane does (#147).chromaticAberration = dispersion)+ }},highlight = {val progress = dampedDragAnimation.pressProgress+ // Upstream's glass lights its own edge.+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) return@drawBackdrop nullHighlight.Ambient.copy(width = Highlight.Ambient.width / 1.5f,blurRadius = Highlight.Ambient.blurRadius / 1.5f,@@ -304,6 +314,7 @@ fun LiquidSlider(},innerShadow = {val progress = dampedDragAnimation.pressProgress+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) return@drawBackdrop nullInnerShadow(radius = 4f.dp * progress,alpha = progress@@ -318,7 +329,14 @@ fun LiquidSlider(},onDrawSurface = {val progress = dampedDragAnimation.pressProgress- drawRect(Color.White.copy(alpha = 1f - progress))+ // Upstream's resting thumb fades over the first 0.15+ // of the press, as its glass comes in.+ val resting = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {+ dev.lelonio.square.ui.glass.morph.indicatorRestingAlpha(progress)+ } else {+ 1f - progress+ }+ drawRect(Color.White.copy(alpha = resting))})// Required rather than asked for: a thumb taller than thediff --git a/app/src/main/java/dev/lelonio/square/ui/glass/LiquidToggle.kt b/app/src/main/java/dev/lelonio/square/ui/glass/LiquidToggle.ktindex d7000d9..8611a71 100644--- a/app/src/main/java/dev/lelonio/square/ui/glass/LiquidToggle.kt+++ b/app/src/main/java/dev/lelonio/square/ui/glass/LiquidToggle.kt@@ -10,6 +10,7 @@package dev.lelonio.square.ui.glass+import dev.lelonio.square.ui.glass.morph.liquidGlassIndicatorimport androidx.compose.foundation.isSystemInDarkThemeimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.size@@ -177,6 +178,12 @@ fun LiquidToggle(shape = { ContinuousCapsule() },effects = {val progress = dampedDragAnimation.pressProgress+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {+ // LOCAL CHANGE: liquid_glass_widgets' indicator+ // glass, coming in with the press; see+ // liquidGlassIndicator.+ liquidGlassIndicator(progress)+ } else {blur(8f.dp.toPx() * (1f - progress))lens(5f.dp.toPx() * progress,@@ -185,9 +192,12 @@ fun LiquidToggle(// switch, as every other pane does (#147).chromaticAberration = dispersion)+ }},highlight = {val progress = dampedDragAnimation.pressProgress+ // Upstream's glass lights its own edge.+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) return@drawBackdrop nullHighlight.Ambient.copy(width = Highlight.Ambient.width / 1.5f,blurRadius = Highlight.Ambient.blurRadius / 1.5f,@@ -202,6 +212,7 @@ fun LiquidToggle(},innerShadow = {val progress = dampedDragAnimation.pressProgress+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) return@drawBackdrop nullInnerShadow(radius = 4f.dp * progress,alpha = progress@@ -216,7 +227,14 @@ fun LiquidToggle(},onDrawSurface = {val progress = dampedDragAnimation.pressProgress- drawRect(Color.White.copy(alpha = 1f - progress))+ // Upstream's resting thumb fades over the first 0.15+ // of the press, as its glass comes in.+ val resting = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {+ dev.lelonio.square.ui.glass.morph.indicatorRestingAlpha(progress)+ } else {+ 1f - progress+ }+ drawRect(Color.White.copy(alpha = resting))}).size(40f.dp, 24f.dp)diff --git a/app/src/main/java/dev/lelonio/square/ui/glass/morph/LICENSE-liquid-glass.txt b/app/src/main/java/dev/lelonio/square/ui/glass/morph/LICENSE-liquid-glass.txtnew file mode 100644index 0000000..b46ee71--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/ui/glass/morph/LICENSE-liquid-glass.txt@@ -0,0 +1,35 @@+The morph physics (LiquidMorphPhysics.kt) and the SDF scene in the morph+shader (MorphGlass.kt) are ported from liquid_glass_widgets:++ https://github.com/sdegenaar/liquid_glass_widgets++whose rendering engine is derived from liquid_glass_renderer:++ https://github.com/whynotmake-it/flutter_liquid_glass/tree/main/packages/liquid_glass_renderer++Both are released under the MIT License.++--------------------------------------------------------------------------------++MIT License++Copyright (c) 2024–2026 Sebastian Degenaar (liquid_glass_widgets)+Copyright 2025 Tim Lehmann for whynotmake.it (liquid_glass_renderer)++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/app/src/main/java/dev/lelonio/square/ui/glass/morph/LiquidGlassEffect.kt b/app/src/main/java/dev/lelonio/square/ui/glass/morph/LiquidGlassEffect.ktnew file mode 100644index 0000000..43ab929--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/ui/glass/morph/LiquidGlassEffect.kt@@ -0,0 +1,181 @@+// liquid_glass_widgets' render pass (see LiquidGlassShader.kt) as a link in the+// backdrop effect chain, for every surface that is drawn over a live page.+// MIT; see LICENSE-liquid-glass.txt beside this file.++package dev.lelonio.square.ui.glass.morph++import androidx.compose.foundation.shape.CornerBasedShape+import androidx.compose.ui.util.fastCoerceAtMost+import dev.lelonio.square.ui.glass.backdrop.BackdropEffectScope+import dev.lelonio.square.ui.glass.backdrop.effects.effect+import dev.lelonio.square.ui.glass.backdrop.internal.RuntimeShaderEffect+import dev.lelonio.square.ui.glass.backdrop.isRuntimeShaderSupported+import kotlin.math.cos+import kotlin.math.sin++/**+ * Upstream's glass over the backdrop recorded so far, which arrives already+ * blurred: one shape, the surface's own rounded rectangle, with nothing to+ * blend it with.+ *+ * Its shadow is not drawn here: a RenderEffect cannot draw outside the layer+ * it runs on, and the surface's own shadow already does that part.+ */+fun BackdropEffectScope.liquidGlassMaterial(+ settings: LiquidGlassSettings,+ /** The finger, in the surface's own pixels at full resolution; null when untouched. */+ touchPosition: androidx.compose.ui.geometry.Offset? = null,+ /** Upstream's touch intensity: 0 at rest, 1 pressed. */+ touchIntensity: Float = 0f,+) {+ if (!isRuntimeShaderSupported()) return+ if (size.width <= 0f || size.height <= 0f) return++ // The recorded layer's pixels per logical pixel.+ val dpr = density * contentScale+ val scale = dpr / 3f+ // A shape with no corner of its own (a capsule) is upstream's+ // borderRadius 9999, which the shader clamps to half the short side.+ val radius = (shape as? CornerBasedShape)+ ?.topStart?.toPx(size, this)+ ?.times(contentScale)+ ?.fastCoerceAtMost(size.minDimension / 2f)+ ?: (size.minDimension / 2f)++ val shader = obtainRuntimeShader("LiquidGlassSingle", LiquidGlassShader.SOURCE_SINGLE)++ // The surface, as it sits in the recorded layer: inset by the padding+ // the blur asked for.+ val left = padding+ val top = padding+ val width = size.width+ val height = size.height+ val shapeData = FloatArray(LiquidGlassShader.MAX_SHAPES * LiquidGlassShader.SHAPE_STRIDE)+ shapeData[0] = LiquidShapeType.RoundedRectangle.shaderIndex+ shapeData[1] = left + width / 2f+ shapeData[2] = top + height / 2f+ shapeData[3] = width+ shapeData[4] = height+ shapeData[5] = radius+ shapeData[6] = radius+ // Upstream's matte, inflated for the anti-aliasing band (no blend here).+ val inflate = 3f+ val glass = settings.effectiveGlassColor++ shader.setFloatUniform("uSize", width + 2f * padding, height + 2f * padding)+ shader.setFloatUniform("uGeometryOffset", left - inflate, top - inflate)+ shader.setFloatUniform("uGeometrySize", width + 2f * inflate, height + 2f * inflate)+ shader.setFloatUniform("uGlassColor", glass.red, glass.green, glass.blue, glass.alpha)+ shader.setFloatUniform(+ "uOpticalProps",+ settings.effectiveRefractiveIndex,+ settings.effectiveChromaticAberration,+ settings.effectiveThickness * scale,+ 1f,+ )+ shader.setFloatUniform(+ "uLightConfig",+ settings.effectiveLightIntensity,+ settings.effectiveAmbientStrength,+ settings.effectiveSaturation,+ )+ shader.setFloatUniform("uLightDirection", cos(settings.lightAngle), -sin(settings.lightAngle))+ shader.setFloatUniform("uWhiten", settings.effectiveWhitenStrength)+ shader.setFloatUniform("uWhitenGated", if (settings.whitenGated) 1f else 0f)+ shader.setFloatUniform("uPinchStrength", settings.pinchStrength)+ shader.setFloatUniform(+ "uEdgeConfig",+ settings.effectiveAmbientRim * scale,+ settings.effectiveFresnelStrength,+ scale,+ settings.effectiveEdgeAbsorption,+ )+ shader.setFloatUniform("uBodyMode", if (settings.bodyMode == GlassBodyMode.Clear) 1f else 0f)+ // Upstream's touch glint: the rim nearest the finger catches the light.+ // In the recorded layer's pixels, as the shader's coordinates are.+ if (touchPosition != null && touchIntensity > 0f) {+ shader.setFloatUniform(+ "uTouchPosition",+ left + touchPosition.x * contentScale,+ top + touchPosition.y * contentScale,+ )+ shader.setFloatUniform("uTouchIntensity", touchIntensity.coerceIn(0f, 1f))+ } else {+ shader.setFloatUniform("uTouchPosition", 0f, 0f)+ shader.setFloatUniform("uTouchIntensity", 0f)+ }+ shader.setFloatUniform(+ "uRimConfig",+ settings.effectiveRimShade,+ settings.effectiveRimLight,+ settings.rimShadeEnds,+ )+ shader.setFloatUniform("uLensModel", if (settings.lensModel == GlassLensModel.Paraxial) 1f else 0f)+ shader.setFloatUniform("uBodyShade", settings.effectiveBodyShade.coerceIn(0f, 1f))+ shader.setFloatUniform("uNumShapes", 1f)+ shader.setFloatUniform("uDpr", dpr)+ shader.setFloatUniform("uBlend", 0f)+ shader.setFloatUniform("uNativeEdge", if (settings.rimShade > 0f) 1f else 0f)+ shader.setFloatUniform("uShapeData", shapeData)+ shader.setFloatUniform("uOpacity", 1f)+ shader.setFloatUniform("uShadowA", 0f, 0f, 0f, 0f)+ shader.setFloatUniform("uShadowB", 0f, 0f, 0f, 0f)++ effect(RuntimeShaderEffect(shader, "content"))+}++/**+ * Upstream's blur pass takes a Gaussian sigma; Android's takes a radius it+ * turns into one as `0.57735 × radius + 0.5`. The radius that gives [sigmaPx].+ */+fun blurRadiusForSigma(sigmaPx: Float): Float =+ if (sigmaPx <= 0.5f) 0f else (sigmaPx - 0.5f) / 0.57735f++/**+ * Upstream's `AnimatedGlassIndicator.baseIndicatorSettings`: a clear lens,+ * no blur and no tint, a shallow curve, and no colour splitting.+ */+val IndicatorBaseSettings = LiquidGlassSettings(+ glassColor = androidx.compose.ui.graphics.Color(1f, 1f, 1f, 0f),+ thickness = 20f,+ refractiveIndex = 1.10f,+ lightIntensity = 2.0f,+ chromaticAberration = 0f,+ lightAngle = LiquidGlassSettings.DEFAULT_LIGHT_ANGLE,+ blur = 0f,+)++/**+ * An indicator's glass, as upstream's AnimatedGlassIndicator draws it on its+ * premium path: [progress] is the press, 0 at rest and 1 held; the glass comes+ * in with it (`visibility`), and the pinch through its lens follows the press+ * eased as `1 − (1 − p)²`, which steadies it while the spring settles.+ */+fun BackdropEffectScope.liquidGlassIndicator(+ progress: Float,+ settings: LiquidGlassSettings = IndicatorBaseSettings,+ pinchStrength: Float = 1f,+) {+ val fade = progress.coerceIn(0f, 1f)+ if (fade <= 0f) return+ val stablePinch = 1f - (1f - fade) * (1f - fade)+ liquidGlassMaterial(settings.copy(visibility = fade, pinchStrength = stablePinch * pinchStrength))+}++/**+ * How much of the resting indicator — the plain filled pill — still shows at+ * [progress]: upstream fades it out over the first 0.15 of the press.+ */+fun indicatorRestingAlpha(progress: Float): Float = (1f - progress / 0.15f).coerceIn(0f, 1f)++/**+ * Upstream's press springs for an indicator: `GlassSpring.snappy(150 ms)` in+ * and `GlassSpring.smooth(300 ms)` out. A spring given by duration and bounce+ * is stiffness (2π / duration)² and damping ratio 1 − bounce.+ */+fun <T> indicatorPressSpring(pressing: Boolean): androidx.compose.animation.core.SpringSpec<T> =+ if (pressing) {+ androidx.compose.animation.core.spring(dampingRatio = 0.85f, stiffness = 1754.6f)+ } else {+ androidx.compose.animation.core.spring(dampingRatio = 1f, stiffness = 438.6f)+ }diff --git a/app/src/main/java/dev/lelonio/square/ui/glass/morph/LiquidGlassShader.kt b/app/src/main/java/dev/lelonio/square/ui/glass/morph/LiquidGlassShader.ktnew file mode 100644index 0000000..c754729--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/ui/glass/morph/LiquidGlassShader.kt@@ -0,0 +1,624 @@+// Ported line for line from liquid_glass_widgets' shaders, MIT:+//+// shaders/sdf.glsl+// shaders/displacement_encoding.glsl+// shaders/render.glsl+// shaders/liquid_glass_geometry_blended.frag+// shaders/liquid_glass_render.frag+// https://github.com/sdegenaar/liquid_glass_widgets (commit 59118973)+//+// Copyright 2025, Tim Lehmann for whynotmake.it+// Copyright 2026, Sebastian Degenaar for pixel-innovations.com (liquid_glass_widgets)+//+// See LICENSE-liquid-glass.txt beside this file.+//+// What differs from upstream, and why:+//+// - GLSL to AGSL: `vec` is `float`, `texture()` is a child shader's `eval()`+// at pixel coordinates, uniforms carry no layout slots.+// - The geometry pass runs inline. Upstream renders it into a texture the+// render pass reads at the same pixel; here the render pass evaluates it at+// that pixel itself. The numbers are the same, without the texture's 8 bits+// per channel.+// - sceneSDF's unrolled folds are loops: the same left folds, forwards and+// backwards, averaged. Upstream unrolled them for glslang on Windows only.+// - The backdrop is two pictures, sharp and blurred, combined where the blur+// pass would have been clipped: upstream blurs the backdrop inside the+// union of the shapes' paths before this shader reads it.+// - Not carried over: the frost passes and the platform-view modes, which the+// settings this app uses leave off (frost 0, fallback colour off).++package dev.lelonio.square.ui.glass.morph++internal object LiquidGlassShader {++ const val MAX_SHAPES = 4+ const val SHAPE_STRIDE = 7++ /**+ * The same shader for a surface whose backdrop arrives already blurred,+ * as the one input of a RenderEffect: the bar, the mini player, a button.+ * Upstream's blur pass is clipped to the shape; here the whole recorded+ * layer is the surface and its edge, so the blurred backdrop stands for+ * both sides of the outline.+ */+ val SOURCE_SINGLE: String by lazy {+ SOURCE+ .replace(+ "uniform shader sharpBackdrop;\nuniform shader blurredBackdrop;",+ "uniform shader content;",+ )+ .replace(+ Regex("float4 backdropWithClip\\(float2 p, float clip\\) \\{[^}]*\\}"),+ "float4 backdropWithClip(float2 p, float clip) { return float4(content.eval(p)); }",+ )+ .replace("float centre = clipSDF(p0 + 1.0);", "float centre = -3.0;")+ }++ const val SOURCE = """+uniform shader sharpBackdrop;+uniform shader blurredBackdrop;++uniform float2 uSize;+uniform float2 uGeometryOffset;+uniform float2 uGeometrySize;+uniform float4 uGlassColor;+uniform float4 uOpticalProps;+uniform float3 uLightConfig;+uniform float2 uLightDirection;+uniform float uWhiten;+uniform float uWhitenGated;+uniform float uPinchStrength;+uniform float4 uEdgeConfig;+uniform float uBodyMode;+uniform float2 uTouchPosition;+uniform float uTouchIntensity;+uniform float3 uRimConfig;+uniform float uLensModel;+uniform float uBodyShade;++uniform float uNumShapes;+uniform float uDpr;+uniform float uBlend;+uniform float uNativeEdge;+uniform float uShapeData[28];++uniform float uOpacity;+// Light-mode shadows (upstream: GlassShadow.defaults, drawn from the matte).+// x: alpha, y: sigma (px), z: offset x (px), w: offset y (px).+uniform float4 uShadowA;+uniform float4 uShadowB;++const float3 LUMA_WEIGHTS = float3(0.2126, 0.7152, 0.0722);++// ── sdf.glsl ────────────────────────────────────────────────────────────────++float sdfRRect(float2 p, float2 b, float r) {+ float shortest = min(b.x, b.y);+ r = min(r, shortest);+ float2 q = abs(p) - b + r;+ return min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - r;+}++float sstep(float e0, float e1, float x) {+ float t = clamp((x - e0) / (e1 - e0), 0.0, 1.0);+ return t * t * (3.0 - 2.0 * t);+}++float sdfRRectAsym(float2 p, float2 b, float rTop, float rBottom) {+ // Equal radii give dT == dB, and mix() returns it: evaluated once.+ if (rTop == rBottom) return sdfRRect(p, b, rTop);+ float dT = sdfRRect(p, b, rTop);+ float dB = sdfRRect(p, b, rBottom);+ float t = sstep(-2.0, 2.0, p.y);+ return mix(dT, dB, t);+}++float fastPow(float x, float n) {+ return exp2(n * log2(max(x, 1e-4)));+}++float squircleShape(float2 p, float2 b, float zone, float n) {+ float2 q = abs(p) - b + zone;+ float2 m = max(q, 0.0);+ float M = max(m.x, m.y);+ float corner = 0.0;+ if (M > 1e-4) {+ float2 mNorm = m / M;+ corner = M * fastPow(fastPow(mNorm.x, n) + fastPow(mNorm.y, n), 1.0 / n);+ }+ return min(max(q.x, q.y), 0.0) + corner - zone;+}++float sdfSquircle(float2 p, float2 b, float r) {+ float boxShort = min(b.x, b.y);+ r = min(r, boxShort);+ float zone = min(r * 1.528, boxShort);+ float base = 1.0 - 0.29289322 * (r / max(zone, 1e-4));+ float n = -1.0 / log2(clamp(base, 0.5, 0.9999));+ return squircleShape(p, b, zone, n);+}++float sdfSquircleAsym(float2 p, float2 b, float rTop, float rBottom) {+ if (rTop == rBottom) {+ return sdfSquircle(p, b, rTop);+ }+ float boxShort = min(b.x, b.y);+ rTop = min(rTop, boxShort);+ rBottom = min(rBottom, boxShort);++ float zoneT = min(rTop * 1.528, boxShort);+ float baseT = 1.0 - 0.29289322 * (rTop / max(zoneT, 1e-4));+ float nT = -1.0 / log2(clamp(baseT, 0.5, 0.9999));+ float dT = squircleShape(p, b, zoneT, nT);++ float zoneB = min(rBottom * 1.528, boxShort);+ float baseB = 1.0 - 0.29289322 * (rBottom / max(zoneB, 1e-4));+ float nB = -1.0 / log2(clamp(baseB, 0.5, 0.9999));+ float dB = squircleShape(p, b, zoneB, nB);++ float t = sstep(-2.0, 2.0, p.y);+ return mix(dT, dB, t);+}++float sdfEllipse(float2 p, float2 r) {+ r = max(r, 1e-4);+ float2 invR = 1.0 / r;+ float2 invR2 = invR * invR;+ float2 pInvR = p * invR;+ float k1 = length(pInvR);+ float2 pInvR2 = p * invR2;+ float k2 = length(pInvR2);+ return (k1 * (k1 - 1.0)) / max(k2, 1e-4);+}++float smoothUnion(float d1, float d2, float k) {+ float e = max(k - abs(d1 - d2), 0.0);+ return min(d1, d2) - e * e * 0.25 / max(k, 1e-5);+}++float getShapeSDF(float type, float2 p, float2 center, float2 size, float rTop, float rBottom) {+ if (type == 1.0) return sdfSquircleAsym(p - center, size / 2.0, rTop, rBottom);+ else if (type == 2.0) return sdfEllipse(p - center, size / 2.0);+ else if (type == 3.0) return sdfRRectAsym(p - center, size / 2.0, rTop, rBottom);+ return 0.0;+}++// Upstream's sceneSDF, unrolled as upstream unrolls it (literal indices+// only), up to the four shapes this app ever groups: forward and backward+// left folds of smoothUnion, averaged.+float sdf0(float2 p) { return getShapeSDF(uShapeData[0], p, float2(uShapeData[1], uShapeData[2]), float2(uShapeData[3], uShapeData[4]), uShapeData[5], uShapeData[6]); }+float sdf1(float2 p) { return getShapeSDF(uShapeData[7], p, float2(uShapeData[8], uShapeData[9]), float2(uShapeData[10], uShapeData[11]), uShapeData[12], uShapeData[13]); }+float sdf2(float2 p) { return getShapeSDF(uShapeData[14], p, float2(uShapeData[15], uShapeData[16]), float2(uShapeData[17], uShapeData[18]), uShapeData[19], uShapeData[20]); }+float sdf3(float2 p) { return getShapeSDF(uShapeData[21], p, float2(uShapeData[22], uShapeData[23]), float2(uShapeData[24], uShapeData[25]), uShapeData[26], uShapeData[27]); }++float sceneSDF(float2 p, float k) {+ if (uNumShapes < 0.5) return 1e9;+ float s0 = sdf0(p);+ if (uNumShapes < 1.5) return s0;+ float s1 = sdf1(p);+ float fwd = smoothUnion(s0, s1, k);+ float bwd = smoothUnion(s1, s0, k);+ if (uNumShapes < 2.5) return mix(fwd, bwd, 0.5);+ float s2 = sdf2(p);+ fwd = smoothUnion(fwd, s2, k);+ float b3a = smoothUnion(s2, s1, k);+ bwd = smoothUnion(b3a, s0, k);+ if (uNumShapes < 3.5) return mix(fwd, bwd, 0.5);+ float s3 = sdf3(p);+ fwd = smoothUnion(fwd, s3, k);+ float b4a = smoothUnion(s3, s2, k);+ float b4b = smoothUnion(b4a, s1, k);+ bwd = smoothUnion(b4b, s0, k);+ return mix(fwd, bwd, 0.5);+}++// The union of the shapes' own outlines, without the blend: the path the+// upstream blur pass is clipped to.+float clipSDF(float2 p) {+ float d = 1e9;+ if (uNumShapes > 0.5) d = sdf0(p);+ if (uNumShapes > 1.5) d = min(d, sdf1(p));+ if (uNumShapes > 2.5) d = min(d, sdf2(p));+ if (uNumShapes > 3.5) d = min(d, sdf3(p));+ return d;+}++// A Gaussian of the given sigma, run over the shape's coverage, at signed+// distance d: the same as upstream's blurred matte, in closed form. Exact+// along a straight edge; at these sigmas, which are a few pixels against+// corners tens of pixels round, the corners agree too.+float erfcApprox(float x) {+ float z = abs(x);+ float t = 1.0 / (1.0 + 0.5 * z);+ float r = t * exp(-z * z - 1.26551223 + t * (1.00002368 + t * (0.37409196 + t * (0.09678418+ + t * (-0.18628806 + t * (0.27886807 + t * (-1.13520398 + t * (1.48851587+ + t * (-0.82215223 + t * 0.17087277)))))))));+ return x >= 0.0 ? r : 2.0 - r;+}++float shadowAt(float2 p, float4 shadow) {+ if (shadow.x <= 0.0) return 0.0;+ float d = sceneSDF(p - shadow.zw, uBlend);+ float coverage = 0.5 * erfcApprox(d / (max(shadow.y, 0.001) * 1.41421356));+ return shadow.x * coverage;+}++// ── render.glsl ─────────────────────────────────────────────────────────────++float3 getHighlightColor(float3 backgroundColor, float targetBrightness) {+ float luminance = dot(backgroundColor, LUMA_WEIGHTS);+ float maxComponent = max(max(backgroundColor.r, backgroundColor.g), backgroundColor.b);+ float lum = luminance * 2.5;+ float lumFactor = lum / (1.0 + lum);+ float sat = maxComponent * 2.5;+ float satFactor = sat / (1.0 + sat);+ float colorInfluence = lumFactor * satFactor;+ float3 tinted = (backgroundColor / max(luminance, 0.001)) * targetBrightness;+ return mix(float3(targetBrightness), tinted, colorInfluence);+}++float3 applySaturation(float3 color, float saturation) {+ float luminance = dot(color, LUMA_WEIGHTS);+ float3 saturatedColor = mix(float3(luminance), color, saturation);+ return clamp(saturatedColor, 0.0, 1.0);+}++float4 applyGlassColor(float4 liquidColor, float4 glassColor, float bodyMode) {+ float3 directMix = mix(liquidColor.rgb, glassColor.rgb, glassColor.a);+ if (bodyMode > 0.5) {+ return float4(directMix, liquidColor.a);+ }+ float backdropLuminance = dot(liquidColor.rgb, LUMA_WEIGHTS);+ float glassLuminance = dot(glassColor.rgb, LUMA_WEIGHTS);+ float3 tinted = clamp(glassColor.rgb + (backdropLuminance - glassLuminance), 0.0, 1.0);+ float chroma = max(max(glassColor.r, glassColor.g), glassColor.b)+ - min(min(glassColor.r, glassColor.g), glassColor.b);+ float chromaWeight = clamp(chroma * 8.0, 0.0, 1.0);+ float3 luminosityMix = mix(liquidColor.rgb, tinted, glassColor.a);+ return float4(mix(directMix, luminosityMix, chromaWeight), liquidColor.a);+}++// ── liquid_glass_render.frag ────────────────────────────────────────────────++// The backdrop as the render pass sees it: blurred inside the shapes'+// outlines, where the blur pass drew, and sharp outside them.+float4 backdropWithClip(float2 p, float clip) {+ if (clip >= 1.0) return float4(blurredBackdrop.eval(p));+ float4 sharp = float4(sharpBackdrop.eval(p));+ if (clip <= 0.0) return sharp;+ return mix(sharp, float4(blurredBackdrop.eval(p)), clip);+}++float4 backdropAt(float2 p) {+ return backdropWithClip(p, clamp(0.5 - clipSDF(p), 0.0, 1.0));+}++float4 textureBilinear(float2 uv, float2 size, float2 invSize) {+ float2 px = uv * size - 0.5;+ float2 f = fract(px);+ float2 p0 = floor(px);+ float2 p1 = p0 + float2(1.0, 0.0);+ float2 p2 = p0 + float2(0.0, 1.0);+ float2 p3 = p0 + float2(1.0, 1.0);++ // The four texels lie within 1.5 px of the footprint's centre and a+ // distance field changes by no more than the distance moved: where the+ // centre is 2 px inside the outline all four are wholly inside, and 2 px+ // outside all four wholly outside. Only near the outline is each texel's+ // own coverage needed.+ float centre = clipSDF(p0 + 1.0);+ float4 c0;+ float4 c1;+ float4 c2;+ float4 c3;+ if (centre < -2.0 || centre > 2.0) {+ float clip = centre < -2.0 ? 1.0 : 0.0;+ c0 = backdropWithClip(p0 + 0.5, clip);+ c1 = backdropWithClip(p1 + 0.5, clip);+ c2 = backdropWithClip(p2 + 0.5, clip);+ c3 = backdropWithClip(p3 + 0.5, clip);+ } else {+ c0 = backdropAt(p0 + 0.5);+ c1 = backdropAt(p1 + 0.5);+ c2 = backdropAt(p2 + 0.5);+ c3 = backdropAt(p3 + 0.5);+ }++ float4 cTop = mix(c0, c1, f.x);+ float4 cBot = mix(c2, c3, f.x);+ return mix(cTop, cBot, f.y);+}++half4 main(float2 fragCoord) {+ float uRefractiveIndex = uOpticalProps.x;+ float uChromaticAberration = uOpticalProps.y;+ float uThickness = uOpticalProps.z;+ float uLightIntensity = uLightConfig.x;+ float uAmbientStrength = uLightConfig.y;+ float uSaturation = uLightConfig.z;++ // ── Shadows, under the glass (upstream: _drawShadows) ──+ // Where the glass is opaque the shadow is cut away (dstOut), so it is+ // only worked out where some of it can show.+ float sd = sceneSDF(fragCoord, uBlend);+ float shadowAlpha = 0.0;+ // And not where it rounds to nothing: past 2 sigma beyond the offset+ // edge the elevation shadow (0.0588 at most) is under half a level out+ // of 255, and the contact shadow, smaller and fainter, long before.+ float shadowEnd = 2.0 * uShadowA.y + abs(uShadowA.w);+ if ((uShadowA.x > 0.0 || uShadowB.x > 0.0) && sd > -3.0 * max(1.0, uDpr) && sd < shadowEnd) {+ shadowAlpha = shadowAt(fragCoord, uShadowA) + shadowAt(fragCoord, uShadowB);+ }++ // ── Geometry pass (liquid_glass_geometry_blended.frag), at this pixel ──+ float2 geometryUV = (fragCoord - uGeometryOffset) / uGeometrySize;+ if (geometryUV.x < 0.0 || geometryUV.y < 0.0 || geometryUV.x > 1.0 || geometryUV.y > 1.0) {+ return half4(0.0, 0.0, 0.0, half(shadowAlpha * uOpacity));+ }++ float gdx = 0.0;+ float gdy = 0.0;+ float sdN = sd;+ // Deep in the flat face — further in than the bevel and the+ // anti-aliasing reach — the normal is straight up whatever the gradient+ // is, and the field only grows when normalised (its gradient is at most+ // 1), so sdN is past both thresholds either way: the four taps below+ // change nothing there and are skipped.+ float faceDepth = max(uThickness, 1.5 * max(1.0, uDpr)) + 1.0;+ if (sd > -faceDepth) {+ float stepDist = uDpr / 3.0;+ float sdPX = sceneSDF(fragCoord + float2(stepDist, 0.0), uBlend);+ float sdMX = sceneSDF(fragCoord - float2(stepDist, 0.0), uBlend);+ float sdPY = sceneSDF(fragCoord + float2(0.0, stepDist), uBlend);+ float sdMY = sceneSDF(fragCoord - float2(0.0, stepDist), uBlend);+ gdx = (sdPX - sdMX) / (2.0 * stepDist);+ gdy = (sdPY - sdMY) / (2.0 * stepDist);+ float gradMag = sqrt(gdx * gdx + gdy * gdy);+ sdN = (gradMag > 0.1) ? sd / gradMag : sd;+ }++ float smoothing = 1.5 * max(1.0, uDpr);+ if (uNativeEdge > 0.5) {+ smoothing = max(1.0, 0.5 * uDpr);+ sdN -= max(1.0, uDpr / 3.0);+ }+ float foregroundAlpha = sstep(smoothing * 0.5, -smoothing * 0.5, sdN);+ // The shadow is cut out where the matte is (upstream: dstOut).+ shadowAlpha *= 1.0 - foregroundAlpha;+ if (foregroundAlpha < 0.01) {+ return half4(0.0, 0.0, 0.0, half(shadowAlpha * uOpacity));+ }+ if (uThickness <= 0.0) {+ return half4(0.0, 0.0, 0.0, half(shadowAlpha * uOpacity));+ }++ float n_cos = max(uThickness + sdN, 0.0) / uThickness;+ float n_sin = sqrt(max(0.0, 1.0 - n_cos * n_cos));+ float3 gNormal = normalize(float3(gdx * n_cos, gdy * n_cos, n_sin));++ float2 storedNormal;+ float storedHeight;+ if (sdN >= 0.0) {+ storedNormal = length(gNormal.xy) > 1e-4 ? gNormal.xy : float2(0.0);+ storedHeight = 0.0;+ } else {+ float x = uThickness + sdN;+ float sqrtTerm = sqrt(max(0.0, uThickness * uThickness - x * x));+ storedHeight = mix(sqrtTerm, uThickness, (sdN < -uThickness) ? 1.0 : 0.0);+ storedNormal = gNormal.xy;+ }+ // encodeGeometryData / decode, without the texture in between.+ float4 geometryData = float4(+ clamp(storedNormal * 0.5 + 0.5, 0.0, 1.0),+ uThickness > 0.0 ? clamp(storedHeight / uThickness, 0.0, 1.0) : 0.0,+ foregroundAlpha);++ // ── Render pass ──+ float2 physTexSize = uSize;+ float2 invTexSize = 1.0 / physTexSize;+ float2 screenUV = fragCoord * invTexSize;++ if (geometryData.a < 0.01) {+ return half4(0.0);+ }++ float2 normalXY = geometryData.rg * 2.0 - 1.0;+ float normalZSq = max(0.0, 1.0 - dot(normalXY, normalXY));+ float normalZ = sqrt(normalZSq);+ float3 normal = float3(normalXY, normalZ);++ float height = geometryData.b * uThickness;+ float baseHeight = uThickness * 8.0;+ float2 displacement;+ if (uLensModel > 0.5) {+ displacement = -normalXY * length(normalXY) * baseHeight * (uRefractiveIndex - 1.0);+ } else {+ float3 incident = float3(0.0, 0.0, -1.0);+ float invN = 1.0 / max(uRefractiveIndex, 0.001);+ float3 baseRefract = refract(incident, normal, invN);+ float refractLen = (height + baseHeight) / max(0.001, abs(baseRefract.z));+ displacement = baseRefract.xy * refractLen;+ }+ displacement *= uOpticalProps.w;++ float maxReach = 0.5 * min(uGeometrySize.x, uGeometrySize.y);+ float reach = length(displacement);+ if (reach > maxReach) {+ displacement *= maxReach / reach;+ }++ float normalizedHeight = geometryData.b;+ float cosTerm = sqrt(max(0.0, 1.0 - normalizedHeight * normalizedHeight));+ float rimDist = uThickness * (1.0 - cosTerm);+ float dprScale = max(0.1, uEdgeConfig.z);++ float hairline = 0.0;+ if (uRimConfig.x > 0.001) {+ hairline = 1.0 - sstep(0.75 * dprScale, 2.0 * dprScale, rimDist);+ hairline *= 1.0 - step(0.999, normalizedHeight);+ float2 outward = normalXY / max(length(normalXY), 1e-4) * (2.5 * dprScale);+ displacement = mix(displacement, outward, hairline);+ }++ if (uPinchStrength > 0.001) {+ float2 centered = clamp(geometryUV, 0.0, 1.0) - float2(0.5);+ float2 absCentered = abs(centered) * 2.0;+ float x2 = absCentered.x * absCentered.x;+ float ax4 = x2 * x2;+ float y2 = absCentered.y * absCentered.y;+ float ay4 = y2 * y2;+ float s = ax4 + ay4;+ float squircleDist = sqrt(sqrt(s));+ float pinchRamp = sstep(0.0, 1.0, squircleDist);+ float2 pinchShift = centered * pinchRamp * uPinchStrength * 0.025;+ pinchShift *= geometryData.a;+ screenUV += pinchShift;+ screenUV = clamp(screenUV, float2(0.001), float2(0.999));+ }++ float4 refractColor;+ if (dot(normalXY, normalXY) < 1e-4) {+ refractColor = textureBilinear(screenUV, physTexSize, invTexSize);+ } else if (uChromaticAberration < 0.01) {+ float2 refractedUV = screenUV + displacement * invTexSize;+ refractColor = textureBilinear(refractedUV, physTexSize, invTexSize);+ if (hairline > 0.0) {+ float2 tangent = float2(-normalXY.y, normalXY.x)+ / max(length(normalXY), 1e-4)+ * (1.5 * dprScale) * invTexSize;+ float4 side = textureBilinear(refractedUV + tangent, physTexSize, invTexSize)+ + textureBilinear(refractedUV - tangent, physTexSize, invTexSize);+ refractColor = mix(refractColor, (refractColor + side) / 3.0, hairline);+ }+ } else {+ float dispersionStrength = uChromaticAberration * 0.5;+ float2 redOffset = displacement * (1.0 + dispersionStrength);+ float2 blueOffset = displacement * (1.0 - dispersionStrength);+ float2 redUV = screenUV + redOffset * invTexSize;+ float2 greenUV = screenUV + displacement * invTexSize;+ float2 blueUV = screenUV + blueOffset * invTexSize;+ float red = textureBilinear(redUV, physTexSize, invTexSize).r;+ float4 greenSample = textureBilinear(greenUV, physTexSize, invTexSize);+ float blue = textureBilinear(blueUV, physTexSize, invTexSize).b;+ refractColor = float4(red, greenSample.g, blue, greenSample.a);+ }++ if (refractColor.a > 0.001) {+ refractColor.rgb /= refractColor.a;+ }++ float4 bodyGlassColor = uGlassColor;+ bodyGlassColor.a *= 1.0 - hairline;+ float4 finalColor = applyGlassColor(refractColor, bodyGlassColor, uBodyMode);++ float backdropLuma = dot(refractColor.rgb, LUMA_WEIGHTS);+ float adaptiveStrength = mix(1.2, 0.8, backdropLuma);++ finalColor.rgb = applySaturation(+ finalColor.rgb, mix(uSaturation * adaptiveStrength, 1.0, hairline));++ finalColor.rgb = mix(finalColor.rgb,+ uGlassColor.rgb,+ uGlassColor.a * 0.12 * (adaptiveStrength - 1.0) * (1.0 - uBodyMode)+ * (1.0 - hairline));++ const float WHITEN_LO = 0.40;+ const float WHITEN_HI = 0.80;+ float whitenLuma = dot(finalColor.rgb, LUMA_WEIGHTS);+ float whitenGate = mix(1.0, sstep(WHITEN_LO, WHITEN_HI, whitenLuma), uWhitenGated);+ finalColor.rgb = mix(finalColor.rgb, float3(1.0),+ clamp(uWhiten, 0.0, 1.0) * whitenGate * (1.0 - hairline));+ if (uBodyShade > 0.0) {+ float shadeLuma = dot(finalColor.rgb, LUMA_WEIGHTS);+ finalColor.rgb *= 1.0 - uBodyShade * shadeLuma * shadeLuma;+ }++ float baseScale = 40.0 * max(0.1, uEdgeConfig.z);+ float thicknessScale = clamp(baseScale / max(uThickness, 1.0), 1.0, 4.0);+ float edgeThreshold = mix(0.8, 0.5, 1.0 / thicknessScale);+ float edgeFactor = uThickness < 0.01 ? 0.0 : 1.0 - sstep(0.0, edgeThreshold, normalizedHeight);++ float r_rim = clamp(1.0 - normalizedHeight, 0.0, 1.0);+ float lensThickness = uThickness < 0.01 ? 0.0 : sqrt(max(0.0, 1.0 - r_rim * r_rim));+ float rimThickness = 1.0 - lensThickness;++ float len2D = max(length(normalXY), 1e-4);+ float2 rimN = normalXY / len2D;+ float litness = dot(rimN, uLightDirection);+ float dirScale = mix(1.4, 0.6, litness * 0.5 + 0.5);++ float absorption = 1.0 - sqrt(rimThickness) * uEdgeConfig.w * dirScale;+ finalColor.rgb *= max(0.0, absorption);++ if (edgeFactor > 0.01 && (uLightIntensity > 0.0 || uAmbientStrength > 0.0)) {+ float len = max(length(normalXY), 1e-4);+ float2 anisoN = normalXY / len;++ float mainLight = max(0.0, dot(anisoN, uLightDirection));+ float oppositeLight = max(0.0, dot(anisoN, -uLightDirection));+ float totalInfluence = mainLight + oppositeLight * 0.8;++ float directional = totalInfluence * sqrt(totalInfluence) * uLightIntensity * 3.0;+ float ambient = uAmbientStrength * 0.5;++ float brightnessRaw = (directional + ambient) * edgeFactor * thicknessScale * 0.8;+ float brightness = brightnessRaw / (1.0 + brightnessRaw);++ float3 highlightColor = getHighlightColor(refractColor.rgb, 1.0);+ finalColor.rgb = mix(finalColor.rgb, highlightColor, brightness);++ if (uTouchIntensity > 0.001) {+ float2 toFragPx = fragCoord - uTouchPosition;+ float touchDist = length(toFragPx);+ float dpr = max(1.0, uEdgeConfig.z * 3.0);+ float touchRadius = max(70.0 * dpr, uSize.y * 1.5);+ float distFactor = sstep(touchRadius, 0.0, touchDist);+ if (distFactor > 0.001 && touchDist > 1.0) {+ float2 touchDir = toFragPx / touchDist;+ float rimTouchDot = max(0.0, dot(anisoN, touchDir));+ float rtd2 = rimTouchDot * rimTouchDot;+ float tSpec = rtd2 * rtd2 * rtd2 * distFactor;+ float tBrightnessRaw = tSpec * uTouchIntensity * uLightIntensity * 2.5;+ float tBrightness = tBrightnessRaw / (1.0 + tBrightnessRaw);+ finalColor.rgb = mix(finalColor.rgb, highlightColor, tBrightness * edgeFactor);+ }+ }+ }++ float rimBase = (1.0 - normalZ) * edgeFactor;+ float ringWindow = 0.75 * max(0.1, uEdgeConfig.z);+ float ring = (1.0 - sstep(uEdgeConfig.x - ringWindow, uEdgeConfig.x + ringWindow, rimDist))+ * step(0.001, uEdgeConfig.x);+ float fresnel = rimBase * 0.12 * uEdgeConfig.y + ring * 0.45;+ finalColor.rgb = clamp(finalColor.rgb + float3(fresnel), 0.0, 1.0);++ if (uRimConfig.y > 0.001 && rimDist < 30.0 * dprScale) {+ float along = dot(rimN, uLightDirection);+ float lit = max(along, 0.0);+ float opp = max(-along, 0.0);+ float lobe = lit * lit * lit + 0.85 * opp * opp * opp;+ float inset = max(0.0, rimDist - 2.25 * dprScale) / dprScale;+ float core = exp(-inset / 1.5);+ float tail = exp(-inset / 8.0);+ float bodyLuma = clamp(dot(finalColor.rgb, LUMA_WEIGHTS), 0.0, 1.0);+ float ease = pow(1.0 - bodyLuma, 0.3);+ float rimLight = uRimConfig.y * lobe * ease+ * (0.175 * core + 0.035 * tail) * (1.0 - hairline);+ finalColor.rgb = clamp(finalColor.rgb + float3(rimLight), 0.0, 1.0);+ }++ if (hairline > 0.0) {+ float across = 1.0 - dot(rimN, uLightDirection) * dot(rimN, uLightDirection);+ across = pow(max(across, 0.0), 1.75);+ float shade = uRimConfig.x * 0.314 * mix(uRimConfig.z, 1.0, across);+ finalColor.rgb = max(finalColor.rgb - float3(shade * hairline), 0.0);+ }++ float alpha = geometryData.a;+ // Glass over its shadow.+ float outA = alpha + shadowAlpha * (1.0 - alpha);+ return half4(half3(finalColor.rgb * alpha * uOpacity), half(outA * uOpacity));+}+"""+}diff --git a/app/src/main/java/dev/lelonio/square/ui/glass/morph/LiquidMorphPhysics.kt b/app/src/main/java/dev/lelonio/square/ui/glass/morph/LiquidMorphPhysics.ktnew file mode 100644index 0000000..fe4cea0--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/ui/glass/morph/LiquidMorphPhysics.kt@@ -0,0 +1,287 @@+// Ported line for line from liquid_glass_widgets, MIT:+//+// lib/utils/liquid_morph_physics.dart+// lib/utils/glass_morph_controller.dart+// https://github.com/sdegenaar/liquid_glass_widgets (commit 59118973)+//+// Copyright (c) 2024–2026 Sebastian Degenaar; engine derived from+// liquid_glass_renderer, Copyright 2025 Tim Lehmann for whynotmake.it+//+// See LICENSE-liquid-glass.txt beside this file. Constants, curves and the+// order of every step are upstream's; only the language changed. Where a+// Flutter curve is named, its exact cubic is reproduced below.++package dev.lelonio.square.ui.glass.morph++import androidx.compose.animation.core.Animatable+import androidx.compose.animation.core.spring+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.Stable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.runtime.snapshotFlow+import kotlin.math.abs+import kotlin.math.pow+import kotlin.math.sqrt++/** Upstream's `MorphPhase`. */+enum class MorphPhase { Idle, Detaching, Travelling, Arriving, Settled }++/** Upstream's `LiquidMorphState`: everything one frame of a morph needs. */+data class LiquidMorphState(+ val pathT: Float,+ val sizeT: Float,+ val currentDx: Float,+ val currentDy: Float,+ val pushDx: Float,+ val pushDy: Float,+ val anchorScale: Float,+ val blend: Float,+ val containerScale: Float,+ val phase: MorphPhase,+)++/** A spring as upstream describes it: mass, stiffness, damping. */+data class SpringDescription(val mass: Float, val stiffness: Float, val damping: Float) {+ /** Compose's parameters for the same spring. */+ val dampingRatio: Float get() = damping / (2f * sqrt(stiffness * mass))+}++object LiquidMorphPhysics {++ val openSpring = SpringDescription(mass = 1f, stiffness = 120f, damping = 16f)+ val closeSpring = SpringDescription(mass = 1f, stiffness = 200f, damping = 21f)+ const val closeVelocityHint = -3.2f++ private const val backOutAmplitude = 2.5f+ private const val minBackOutAmplitude = 0.7f+ private const val adaptiveThresholdDy = 100f+ private const val anchorEaseDuration = 0.4f+ private const val blendMultiplier = 150f+ private const val maxBlend = 28f+ private const val closeProximityThreshold = 0.6f+ private const val maxPushTravelPx = 80f++ fun computeScaleDelta(sourceW: Float, sourceH: Float, targetW: Float, targetH: Float): Float {+ val sourceArea = sourceW * sourceH+ val targetArea = targetW * targetH+ if (sourceArea <= 0f) return 1f+ return sqrt(targetArea / sourceArea)+ }++ fun computeAdaptiveBackOutAmplitude(finalDy: Float, baseAmplitude: Float = backOutAmplitude): Float {+ val absDy = abs(finalDy)+ if (absDy <= adaptiveThresholdDy) return baseAmplitude+ return (baseAmplitude * adaptiveThresholdDy / absDy).coerceIn(minBackOutAmplitude, baseAmplitude)+ }++ fun computeBlendAttenuation(scaleDelta: Float): Float {+ if (scaleDelta <= 3f) return 1f+ return (3f / scaleDelta).coerceIn(0.2f, 1f)+ }++ fun compute(+ rawValue: Float,+ finalDx: Float,+ finalDy: Float,+ horizontalOffset: Float = 0f,+ verticalOffset: Float = 0f,+ scaleDelta: Float = 1f,+ adaptiveDamping: Boolean? = null,+ isClosing: Boolean = false,+ ): LiquidMorphState {+ val clampedValue = rawValue.coerceIn(0f, 1f)+ val closeUndershoot = if (rawValue < 0f) rawValue else 0f+ val adaptive = adaptiveDamping ?: (scaleDelta > 1.5f)+ val amplitude = if (adaptive) computeAdaptiveBackOutAmplitude(finalDy) else backOutAmplitude++ val pathT = if (isClosing) {+ clampedValue + closeUndershoot+ } else {+ backOut(amplitude, clampedValue) + closeUndershoot+ }++ val rawSizeT = when {+ isClosing -> clampedValue.pow(1.4f)+ adaptive && scaleDelta > 3f -> smootherStep(clampedValue)+ else -> FlutterCurves.linearToEaseOut(clampedValue)+ }+ val sizeT = rawSizeT + closeUndershoot++ val pushFactor = if (adaptive) {+ val travelDx = abs(finalDx + horizontalOffset)+ val travelDy = abs(finalDy + verticalOffset)+ val travelMag = sqrt(travelDx * travelDx + travelDy * travelDy)+ if (travelMag > 0f) (maxPushTravelPx / travelMag).coerceIn(0f, 1f) else 1f+ } else {+ 1f+ }+ val pushDx = if (rawValue < 0f) (finalDx + horizontalOffset) * rawValue * pushFactor else 0f+ val pushDy = if (rawValue < 0f) (finalDy + verticalOffset) * rawValue * pushFactor else 0f++ val currentDx = finalDx * pathT+ val currentDy = finalDy * pathT++ val anchorScale = if (isClosing) {+ (1f - (clampedValue - 0.45f) / 0.40f).coerceIn(0f, 1f)+ } else {+ (1f - (clampedValue / anchorEaseDuration)).coerceIn(0f, 1f)+ }++ val blendAttenuation = computeBlendAttenuation(scaleDelta)+ val blend = if (isClosing) {+ val proximityT = (1f - clampedValue / closeProximityThreshold).coerceIn(0f, 1f)+ val eased = FlutterCurves.easeOut(proximityT)+ (eased * maxBlend * blendAttenuation).coerceIn(0f, maxBlend)+ } else {+ val separation = abs(pathT - sizeT)+ (separation * blendMultiplier * blendAttenuation).coerceIn(0f, maxBlend)+ }++ val containerScale = when {+ rawValue > 1f -> 1f + (rawValue - 1f) * 0.10f+ rawValue < 0f -> 1f + rawValue * 0.55f+ else -> 1f+ }++ return LiquidMorphState(+ pathT = pathT,+ sizeT = sizeT,+ currentDx = currentDx,+ currentDy = currentDy,+ pushDx = pushDx,+ pushDy = pushDy,+ anchorScale = anchorScale,+ blend = blend,+ containerScale = containerScale,+ phase = derivePhase(rawValue, clampedValue),+ )+ }++ private fun derivePhase(rawValue: Float, clampedValue: Float): MorphPhase = when {+ rawValue < 0f -> MorphPhase.Detaching+ clampedValue < 0.001f -> MorphPhase.Idle+ clampedValue < 0.4f -> MorphPhase.Detaching+ clampedValue < 0.8f -> MorphPhase.Travelling+ clampedValue < 0.999f -> MorphPhase.Arriving+ else -> MorphPhase.Settled+ }++ private fun smootherStep(t: Float): Float {+ val tc = t.coerceIn(0f, 1f)+ return tc * tc * tc * (tc * (tc * 6f - 15f) + 10f)+ }++ /** Upstream's `_BackOutCurve.transformInternal`. */+ private fun backOut(amplitude: Float, t0: Float): Float {+ val t = t0 - 1f+ return t * t * ((amplitude + 1f) * t + amplitude) + 1f+ }+}++/**+ * Flutter's curves, as Flutter defines them.+ *+ * A [Cubic] in Flutter is a CSS-style Bézier through (0,0) and (1,1), solved+ * for x by bisection to within 0.001 — reproduced here with the same+ * tolerance, so the values agree with Flutter's.+ */+object FlutterCurves {+ fun linearToEaseOut(t: Float) = cubic(0.35f, 0.91f, 0.33f, 0.97f, t)+ fun easeOut(t: Float) = cubic(0.0f, 0.0f, 0.58f, 1.0f, t)+ fun easeInExpo(t: Float) = cubic(0.95f, 0.05f, 0.795f, 0.035f, t)++ private fun evaluate(a: Float, b: Float, m: Float): Float =+ 3f * a * (1f - m) * (1f - m) * m + 3f * b * (1f - m) * m * m + m * m * m++ private fun cubic(a: Float, b: Float, c: Float, d: Float, t: Float): Float {+ if (t == 0f || t == 1f) return t+ var start = 0f+ var end = 1f+ while (true) {+ val midpoint = (start + end) / 2f+ val estimate = evaluate(a, c, midpoint)+ if (abs(t - estimate) < 0.001f) return evaluate(b, d, midpoint)+ if (estimate < t) start = midpoint else end = midpoint+ }+ }+}++/**+ * Upstream's `GlassMorphController`, on a Compose [Animatable].+ *+ * The spring is the same spring: Compose takes it as a damping ratio and a+ * stiffness, and with a mass of 1 those are exactly upstream's damping and+ * stiffness. Opening starts from rest, closing with upstream's push, each from+ * wherever the value is, as upstream's `animateWith` does.+ */+@Stable+class GlassMorphController internal constructor() {+ internal val spring = Animatable(0f)++ var isClosing by mutableStateOf(false)+ internal set+ var hasHandedOff by mutableStateOf(false)+ internal set+ internal var settled by mutableStateOf(true)++ val value: Float get() = spring.value+ val velocity: Float get() = spring.velocity++ /** Upstream's `isShowing`: until the closing spring has come to rest. */+ val isShowing: Boolean get() = spring.value > 0.001f || (isClosing && !settled)++ fun computeState(+ finalDx: Float,+ finalDy: Float,+ horizontalOffset: Float = 0f,+ verticalOffset: Float = 0f,+ scaleDelta: Float = 1f,+ adaptiveDamping: Boolean? = null,+ ): LiquidMorphState = LiquidMorphPhysics.compute(+ rawValue = spring.value,+ finalDx = finalDx,+ finalDy = finalDy,+ horizontalOffset = horizontalOffset,+ verticalOffset = verticalOffset,+ scaleDelta = scaleDelta,+ adaptiveDamping = adaptiveDamping,+ isClosing = isClosing,+ )+}++@Composable+fun rememberGlassMorphController(open: Boolean, disableAnimations: Boolean = false): GlassMorphController {+ val morph = remember { GlassMorphController() }+ LaunchedEffect(open) {+ val description = when {+ disableAnimations -> SpringDescription(mass = 1f, stiffness = 500f, damping = 32.4f)+ open -> LiquidMorphPhysics.openSpring+ else -> LiquidMorphPhysics.closeSpring+ }+ if (open) {+ morph.isClosing = false+ morph.hasHandedOff = false+ } else {+ if (morph.spring.value <= 0.001f && morph.settled) return@LaunchedEffect+ morph.isClosing = true+ }+ morph.settled = false+ morph.spring.animateTo(+ targetValue = if (open) 1f else 0f,+ animationSpec = spring(+ dampingRatio = description.dampingRatio,+ stiffness = description.stiffness,+ visibilityThreshold = 0.001f,+ ),+ initialVelocity = if (open) 0f else LiquidMorphPhysics.closeVelocityHint,+ ) {+ if (morph.isClosing && value <= 0f && !morph.hasHandedOff) morph.hasHandedOff = true+ }+ morph.settled = true+ }+ return morph+}diff --git a/app/src/main/java/dev/lelonio/square/ui/glass/morph/MorphGlass.kt b/app/src/main/java/dev/lelonio/square/ui/glass/morph/MorphGlass.ktnew file mode 100644index 0000000..e0a40e4--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/ui/glass/morph/MorphGlass.kt@@ -0,0 +1,436 @@+// The settings and the uniforms they become are ported from liquid_glass_widgets,+// MIT (lib/src/engine/liquid_glass_settings.dart,+// lib/src/engine/rendering/liquid_glass_render_object.dart,+// lib/src/engine/liquid_glass_blend_group.dart, lib/constants/glass_shadow.dart;+// https://github.com/sdegenaar/liquid_glass_widgets, commit 59118973).+// Copyright (c) 2024–2026 Sebastian Degenaar; engine derived from+// liquid_glass_renderer, Copyright 2025 Tim Lehmann for whynotmake.it.+// See LICENSE-liquid-glass.txt beside this file.++package dev.lelonio.square.ui.glass.morph++import android.os.Build+import androidx.compose.runtime.Composable+import androidx.compose.runtime.Immutable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.Stable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.runtime.snapshotFlow+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.drawBehind+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.ImageBitmap+import androidx.compose.ui.graphics.asAndroidBitmap+import androidx.compose.ui.graphics.asComposeRenderEffect+import androidx.compose.ui.graphics.drawscope.drawIntoCanvas+import androidx.compose.ui.graphics.layer.GraphicsLayer+import androidx.compose.ui.graphics.layer.drawLayer+import androidx.compose.ui.graphics.nativeCanvas+import androidx.compose.ui.graphics.rememberGraphicsLayer+import androidx.compose.ui.layout.LayoutCoordinates+import androidx.compose.ui.layout.onGloballyPositioned+import androidx.compose.ui.unit.IntSize+import dev.lelonio.square.ui.glass.backdrop.Backdrop+import kotlin.math.cos+import kotlin.math.sin++/** Upstream's `GlassLensModel`. */+enum class GlassLensModel { Spherical, Paraxial }++/** Upstream's `GlassBodyMode`. */+enum class GlassBodyMode { Adaptive, Clear }++/**+ * Upstream's `LiquidGlassSettings`, the fields its render pass reads, with+ * upstream's defaults and its `effective*` getters.+ */+@Immutable+data class LiquidGlassSettings(+ val visibility: Float = 1f,+ val glassColor: Color = Color(255, 255, 255, 0),+ val thickness: Float = 20f,+ val blur: Float = 5f,+ val chromaticAberration: Float = 0.01f,+ val lightAngle: Float = DEFAULT_LIGHT_ANGLE,+ val lightIntensity: Float = 0.5f,+ val ambientStrength: Float = 0f,+ val ambientRim: Float = 0f,+ val fresnelStrength: Float = 1f,+ val refractiveIndex: Float = 1.2f,+ val saturation: Float = 1.5f,+ val shadowElevation: Float = 1f,+ val whitenStrength: Float = 0f,+ val whitenGated: Boolean = true,+ val edgeAbsorption: Float = 0f,+ val rimShade: Float = 0f,+ val rimShadeEnds: Float = 0.2f,+ val rimLight: Float = 0f,+ val bodyShade: Float = 0f,+ val lensModel: GlassLensModel = GlassLensModel.Spherical,+ val bodyMode: GlassBodyMode = GlassBodyMode.Adaptive,+ val pinchStrength: Float = 0f,+) {+ val effectiveGlassColor: Color get() = glassColor.copy(alpha = glassColor.alpha * visibility)+ val effectiveThickness: Float get() = thickness * visibility+ val effectiveBlur: Float get() = blur * visibility+ val effectiveChromaticAberration: Float get() = chromaticAberration * visibility+ val effectiveLightIntensity: Float get() = lightIntensity * visibility+ val effectiveFresnelStrength: Float get() = fresnelStrength * visibility+ val effectiveAmbientRim: Float get() = ambientRim * visibility+ val effectiveAmbientStrength: Float get() = ambientStrength * visibility+ val effectiveShadowElevation: Float get() = shadowElevation * visibility+ val effectiveWhitenStrength: Float get() = whitenStrength * visibility+ val effectiveEdgeAbsorption: Float get() = edgeAbsorption * visibility+ val effectiveRimShade: Float get() = rimShade * visibility+ val effectiveRimLight: Float get() = rimLight * visibility+ val effectiveBodyShade: Float get() = bodyShade * visibility+ val effectiveSaturation: Float get() = 1f + (saturation - 1f) * visibility+ val effectiveRefractiveIndex: Float get() = 1f + (refractiveIndex - 1f) * visibility++ companion object {+ /** Upstream's `GlassDefaults.lightAngle`: 0.75π. */+ const val DEFAULT_LIGHT_ANGLE = (0.75 * 3.14159265358979).toFloat()++ /**+ * What upstream's GlassMenu falls back to with no theme above it: the+ * menu's own glass.+ */+ val Menu = LiquidGlassSettings(+ blur = 10f,+ thickness = 10f,+ glassColor = Color(255, 255, 255, (0.12f * 255).toInt()),+ lightAngle = DEFAULT_LIGHT_ANGLE,+ lightIntensity = 0.7f,+ ambientStrength = 0.4f,+ saturation = 1.2f,+ refractiveIndex = 0.7f,+ chromaticAberration = 0f,+ )+ }+}++/** Upstream's `LiquidRoundedRectangle`, `LiquidRoundedSuperellipse` and `LiquidOval` as shader types. */+enum class LiquidShapeType(val shaderIndex: Float) { Squircle(1f), Oval(2f), RoundedRectangle(3f) }++/** One shape of a blend group, in the surface's own logical pixels. */+@Immutable+data class LiquidShape(+ val type: LiquidShapeType,+ val bounds: Rect,+ val cornerRadius: Float,+ val bottomCornerRadius: Float = cornerRadius,+)++/** One frame of a blend group: its shapes, their blend, and the group's opacity. */+@Immutable+data class LiquidGlassFrame(+ val shapes: List<LiquidShape>,+ /** Upstream's `LiquidGlassBlendGroup.blend`, in logical pixels. */+ val blend: Float,+ /** Upstream wraps the whole layer in an `Opacity`; this is that. */+ val opacity: Float = 1f,+)++/**+ * The page under a blend group, captured once: sharp, and blurred the way the+ * upstream blur pass blurs it.+ *+ * Upstream reads a live backdrop every frame; here the page is read when the+ * group appears, since nothing under a modal menu moves while it is open, and+ * every frame after that only moves the shapes.+ */+@Stable+class LiquidGlassCapture internal constructor(+ internal val page: GraphicsLayer,+ internal val blurred: GraphicsLayer,+) {+ internal var coordinates: LayoutCoordinates? = null+ internal var recordedSize: IntSize? = null+ internal var recordedBlur: Float = -1f+ internal var generation by mutableIntStateOf(0)+ internal var sharpBitmap by mutableStateOf<ImageBitmap?>(null)+ internal var blurredBitmap by mutableStateOf<ImageBitmap?>(null)+ internal var bitmapsFor by mutableIntStateOf(-1)+ internal var sharpShader: android.graphics.Shader? = null+ internal var blurredShader: android.graphics.Shader? = null++ internal val shader: android.graphics.RuntimeShader? =+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ android.graphics.RuntimeShader(LiquidGlassShader.SOURCE)+ } else {+ null+ }+ internal val paint = android.graphics.Paint()+ internal val shapeData = FloatArray(LiquidGlassShader.MAX_SHAPES * LiquidGlassShader.SHAPE_STRIDE)++ /** Whether the page has been read and the shader can draw from it. */+ val ready: Boolean+ get() = sharpBitmap != null && blurredBitmap != null && bitmapsFor == generation++ /** Forgets the page, so the next appearance reads it again. */+ fun reset() {+ recordedSize = null+ sharpBitmap = null+ blurredBitmap = null+ sharpShader = null+ blurredShader = null+ bitmapsFor = -1+ }+}++@Composable+fun rememberLiquidGlassCapture(): LiquidGlassCapture {+ val page = rememberGraphicsLayer()+ val blurred = rememberGraphicsLayer()+ val capture = remember(page, blurred) { LiquidGlassCapture(page, blurred) }+ // The pictures the shader reads, taken once the layers have been drawn.+ LaunchedEffect(capture) {+ snapshotFlow { capture.generation }.collect { generation ->+ if (generation == 0) return@collect+ val sharp = runCatching { capture.page.toImageBitmap() }+ .onFailure { android.util.Log.w("SquareGlass", "sharp failed", it) }.getOrNull()+ val blurredImage = runCatching { capture.blurred.toImageBitmap() }+ .onFailure { android.util.Log.w("SquareGlass", "blurred failed", it) }.getOrNull()+ if (generation == capture.generation && sharp != null && blurredImage != null) {+ // Made into shaders once, here, rather than on every frame.+ capture.sharpShader = nearest(sharp)+ capture.blurredShader = nearest(blurredImage)+ capture.sharpBitmap = sharp+ capture.blurredBitmap = blurredImage+ capture.bitmapsFor = generation+ }+ }+ }+ return capture+}++/**+ * A blend group of liquid glass shapes, drawn over [backdrop] with upstream's+ * render pass.+ *+ * Covers the whole surface it is put on and draws only where [frame]'s shapes+ * (and their shadows) are. Light-mode shadows follow upstream: none on a dark+ * page. Below Android 13 there is no runtime shader, and nothing is drawn.+ */+fun Modifier.liquidGlassGroup(+ backdrop: Backdrop,+ capture: LiquidGlassCapture,+ settings: LiquidGlassSettings,+ darkPage: Boolean,+ frame: () -> LiquidGlassFrame,+): Modifier = this+ .onGloballyPositioned { capture.coordinates = it }+ .drawBehind {+ val shader = capture.shader ?: return@drawBehind+ val pixels = IntSize(size.width.toInt(), size.height.toInt())+ if (pixels.width <= 0 || pixels.height <= 0) return@drawBehind+ val dpr = density++ // The page, read once for this size and this blur.+ if (capture.recordedSize != pixels || capture.recordedBlur != settings.effectiveBlur) {+ capture.page.record(pixels) {+ with(backdrop) {+ drawBackdrop(density = this@record, coordinates = capture.coordinates)+ }+ }+ capture.blurred.renderEffect = blurEffect(settings.effectiveBlur * dpr)+ capture.blurred.record(pixels) {+ with(backdrop) {+ drawBackdrop(density = this@record, coordinates = capture.coordinates)+ }+ }+ capture.recordedSize = pixels+ capture.recordedBlur = settings.effectiveBlur+ capture.generation += 1+ }+ if (!capture.ready) return@drawBehind+ val sharp = capture.sharpShader ?: return@drawBehind+ val blurred = capture.blurredShader ?: return@drawBehind++ val current = frame()+ if (current.opacity <= 0f || current.shapes.isEmpty()) return@drawBehind++ val bounds = writeUniforms(shader, capture, settings, darkPage, current, dpr, size.width, size.height)+ shader.setInputShader("sharpBackdrop", sharp)+ shader.setInputShader("blurredBackdrop", blurred)+ capture.paint.shader = shader+ // Only where the glass or its shadow can be: everywhere else the+ // shader would only work out that it draws nothing.+ drawIntoCanvas {+ it.nativeCanvas.drawRect(+ bounds.left.coerceAtLeast(0f),+ bounds.top.coerceAtLeast(0f),+ bounds.right.coerceAtMost(size.width),+ bounds.bottom.coerceAtMost(size.height),+ capture.paint,+ )+ }+ }++/**+ * Upstream's blur pass: `ImageFilter.blur(sigma, mirror)`, where [sigmaPx] is+ * the blur in physical pixels. Android's blur takes a radius and turns it into+ * a sigma as `0.57735 * radius + 0.5`; this undoes that, so the sigma is the+ * same.+ */+private fun blurEffect(sigmaPx: Float): androidx.compose.ui.graphics.RenderEffect? {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S || sigmaPx <= 0.5f) return null+ val radius = (sigmaPx - 0.5f) / 0.57735f+ return android.graphics.RenderEffect+ .createBlurEffect(radius, radius, android.graphics.Shader.TileMode.MIRROR)+ .asComposeRenderEffect()+}++/** A picture as a child shader, sampled texel by texel: the shader filters it itself. */+private fun nearest(image: ImageBitmap): android.graphics.Shader {+ val shader = android.graphics.BitmapShader(+ image.asAndroidBitmap().let {+ if (it.config == android.graphics.Bitmap.Config.HARDWARE) {+ it.copy(android.graphics.Bitmap.Config.ARGB_8888, false)+ } else {+ it+ }+ },+ android.graphics.Shader.TileMode.CLAMP,+ android.graphics.Shader.TileMode.CLAMP,+ )+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ shader.filterMode = android.graphics.BitmapShader.FILTER_MODE_NEAREST+ }+ return shader+}++/** Upstream's uniforms, from `LiquidGlassRenderObject` and `LiquidGlassBlendGroup`. */+private fun writeUniforms(+ shader: android.graphics.RuntimeShader,+ capture: LiquidGlassCapture,+ settings: LiquidGlassSettings,+ darkPage: Boolean,+ frame: LiquidGlassFrame,+ dpr: Float,+ width: Float,+ height: Float,+): Rect {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return Rect.Zero+ // The visual thickness was tuned at 3x; scale keeps it the same logical width.+ val scale = dpr / 3f+ val lightDirX = cos(settings.lightAngle)+ val lightDirY = -sin(settings.lightAngle)++ shader.setFloatUniform("uSize", width, height)++ // Upstream's matte: the shapes' union, inflated for the anti-aliasing band.+ var left = Float.POSITIVE_INFINITY+ var top = Float.POSITIVE_INFINITY+ var right = Float.NEGATIVE_INFINITY+ var bottom = Float.NEGATIVE_INFINITY+ val shapes = frame.shapes.take(LiquidGlassShader.MAX_SHAPES)+ shapes.forEachIndexed { index, shape ->+ left = minOf(left, shape.bounds.left)+ top = minOf(top, shape.bounds.top)+ right = maxOf(right, shape.bounds.right)+ bottom = maxOf(bottom, shape.bounds.bottom)+ val base = index * LiquidGlassShader.SHAPE_STRIDE+ capture.shapeData[base] = shape.type.shaderIndex+ capture.shapeData[base + 1] = shape.bounds.center.x * dpr+ capture.shapeData[base + 2] = shape.bounds.center.y * dpr+ capture.shapeData[base + 3] = shape.bounds.width * dpr+ capture.shapeData[base + 4] = shape.bounds.height * dpr+ capture.shapeData[base + 5] = shape.cornerRadius * dpr+ capture.shapeData[base + 6] = shape.bottomCornerRadius * dpr+ }+ val inflate = frame.blend * 0.25f + 3f / dpr+ shader.setFloatUniform("uGeometryOffset", (left - inflate) * dpr, (top - inflate) * dpr)+ shader.setFloatUniform(+ "uGeometrySize",+ (right - left + 2 * inflate) * dpr,+ (bottom - top + 2 * inflate) * dpr,+ )++ val glass = settings.effectiveGlassColor+ shader.setFloatUniform("uGlassColor", glass.red, glass.green, glass.blue, glass.alpha)+ shader.setFloatUniform(+ "uOpticalProps",+ settings.effectiveRefractiveIndex,+ settings.effectiveChromaticAberration,+ settings.effectiveThickness * scale,+ 1f,+ )+ shader.setFloatUniform(+ "uLightConfig",+ settings.effectiveLightIntensity,+ settings.effectiveAmbientStrength,+ settings.effectiveSaturation,+ )+ shader.setFloatUniform("uLightDirection", lightDirX, lightDirY)+ shader.setFloatUniform("uWhiten", settings.effectiveWhitenStrength)+ shader.setFloatUniform("uWhitenGated", if (settings.whitenGated) 1f else 0f)+ shader.setFloatUniform("uPinchStrength", settings.pinchStrength)+ shader.setFloatUniform(+ "uEdgeConfig",+ settings.effectiveAmbientRim * scale,+ settings.effectiveFresnelStrength,+ scale,+ settings.effectiveEdgeAbsorption,+ )+ shader.setFloatUniform("uBodyMode", if (settings.bodyMode == GlassBodyMode.Clear) 1f else 0f)+ shader.setFloatUniform("uTouchPosition", 0f, 0f)+ shader.setFloatUniform("uTouchIntensity", 0f)+ shader.setFloatUniform(+ "uRimConfig",+ settings.effectiveRimShade,+ settings.effectiveRimLight,+ settings.rimShadeEnds,+ )+ shader.setFloatUniform("uLensModel", if (settings.lensModel == GlassLensModel.Paraxial) 1f else 0f)+ shader.setFloatUniform("uBodyShade", settings.effectiveBodyShade.coerceIn(0f, 1f))++ shader.setFloatUniform("uNumShapes", shapes.size.toFloat())+ shader.setFloatUniform("uDpr", dpr)+ shader.setFloatUniform("uBlend", frame.blend * dpr)+ shader.setFloatUniform("uNativeEdge", if (settings.rimShade > 0f) 1f else 0f)+ shader.setFloatUniform("uShapeData", capture.shapeData)++ shader.setFloatUniform("uOpacity", frame.opacity.coerceIn(0f, 1f))++ // GlassShadow.scaled(elevation): an elevation and a contact shadow, light+ // pages only. A BoxShadow's sigma is 0.57735 × its blur radius + 0.5.+ val elevation = settings.effectiveShadowElevation+ if (darkPage || elevation <= 0f) {+ shader.setFloatUniform("uShadowA", 0f, 0f, 0f, 0f)+ shader.setFloatUniform("uShadowB", 0f, 0f, 0f, 0f)+ } else {+ fun sigma(blurRadius: Float) = (blurRadius * 0.57735f + 0.5f) * dpr+ // At 1, GlassShadow.defaults itself: 0x0F and 0x05 black.+ val elevationAlpha = if (elevation == 1f) 15f / 255f else (0.06f * elevation).coerceIn(0f, 1f)+ val contactAlpha = if (elevation == 1f) 5f / 255f else (0.02f * elevation).coerceIn(0f, 1f)+ shader.setFloatUniform(+ "uShadowA",+ elevationAlpha, sigma(8f * elevation), 0f, 2f * elevation * dpr,+ )+ shader.setFloatUniform(+ "uShadowB",+ contactAlpha, sigma(2f * elevation), 0f, 1f * elevation * dpr,+ )+ }++ // What the draw has to cover: the matte, and the elevation shadow's reach+ // (two sigmas past its offset; see the shader's shadowEnd).+ val shadowReach = if (darkPage || elevation <= 0f) 0f else+ ((8f * elevation * 0.57735f + 0.5f) * 2f + 2f * elevation)+ return Rect(+ (left - inflate - shadowReach) * dpr,+ (top - inflate - shadowReach) * dpr,+ (right + inflate + shadowReach) * dpr,+ (bottom + inflate + shadowReach) * dpr,+ )+}++/** Upstream's `lerpDouble`. */+internal fun lerp(a: Float, b: Float, t: Float): Float = a + (b - a) * t+