Loading...
Loading...
Advanced Compose visuals - Material 3 Expressive motion physics, AGSL shaders (Android 13+), Canvas/DrawScope generative, graphicsLayer effects.
npx skill4agent add athevon/genjutsu compose-graphicsAdvanced Compose visuals: M3 Expressive motion physics, AGSL shaders (Android 13+), Canvas / DrawScope, graphicsLayer effects. Loaded for advanced thesis (shader, expressive, M3 Expressive, AGSL, Canvas, holographic). Foundation:covers basics. Concise rules here. Deep-dive in../compose-motion/SKILL.md.references/
| Need | API |
|---|---|
| Spring physics with bounce / overshoot | |
| Pixel-level shader | |
| Generative drawing (paths, particles, fractals) | |
| GPU effects (blur, shadows, color filters) | |
| Adaptive system materials (Material You glassmorphism) | |
| Liquid glass on Android | AGSL shader recipe (no native API like iOS yet) |
androidx.graphics.shapesMotionScheme| Scheme | Personality | Use For |
|---|---|---|
| Calmer, less overshoot | Default for chrome, lists, navigation |
| More overshoot, longer settle | Hero reveals, FABs, primary CTAs |
MaterialTheme(motionScheme = MotionScheme.expressive()) {
// children read tokens via MaterialTheme.motionScheme.*
}| Token | Domain | Speed |
|---|---|---|
| Position / size | < 200ms |
| Position / size | ~ 350ms |
| Position / size | ~ 600ms |
| Opacity / color | < 150ms |
| Opacity / color | ~ 250ms |
| Opacity / color | ~ 400ms |
Spatial vs Effects: spatial = anything physical (height, offset, scale). Effects = visual properties without inertia (alpha, color, elevation). Springs feel natural for spatial; tweens feel right for effects. The tokens encode this for you.
@Composable
fun ExpressiveHero() {
var expanded by remember { mutableStateOf(false) }
MaterialTheme(motionScheme = MotionScheme.expressive()) {
val transition = updateTransition(targetState = expanded, label = "expand")
val height by transition.animateDp(
transitionSpec = { MaterialTheme.motionScheme.slowSpatialSpec() },
label = "height"
) { if (it) 400.dp else 100.dp }
val alpha by transition.animateFloat(
transitionSpec = { MaterialTheme.motionScheme.defaultEffectsSpec() },
label = "alpha"
) { if (it) 1f else 0f }
Card(
modifier = Modifier
.fillMaxWidth()
.height(height)
.clickable { expanded = !expanded }
) {
Box(modifier = Modifier.alpha(alpha)) {
Text("Detail content", modifier = Modifier.padding(24.dp))
}
}
}
}| Mood | Spec |
|---|---|
| Hero reveal | |
| Snappy expressive | |
| Calm spatial | |
| Critical (no overshoot) | |
androidx.graphics.shapesMaterialShapes.CirclePentagonCookie4SidedSunnyHeartMorph(start, end)val morph = remember { Morph(MaterialShapes.Circle, MaterialShapes.Cookie4Sided) }
val progress by animateFloatAsState(
targetValue = if (active) 1f else 0f,
animationSpec = MaterialTheme.motionScheme.slowSpatialSpec(),
label = "morph"
)
Box(
modifier = Modifier
.size(96.dp)
.clip(GenericShape { size, _ ->
addPath(
morph.toPath(progress).asAndroidPath().asComposePath()
)
})
.background(MaterialTheme.colorScheme.primary)
)half4vec4RuntimeShaderModifier.graphicsLayer { renderEffect = ... }@Composable
fun ShaderEffect(content: @Composable () -> Unit) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
// Android 12 and below: skip the shader, render content as-is.
content()
return
}
val shader = remember { RuntimeShader(AGSL_SOURCE) }
val time by produceState(0f) {
while (true) {
withFrameMillis { ms ->
value = ms / 1000f
}
}
}
Box(
modifier = Modifier
.onSizeChanged {
shader.setFloatUniform("resolution", it.width.toFloat(), it.height.toFloat())
}
.graphicsLayer {
shader.setFloatUniform("time", time)
renderEffect = RenderEffect
.createRuntimeShaderEffect(shader, "image")
.asComposeRenderEffect()
}
) { content() }
}Always gate on. Pre-Android 13 fallback: render the content unmodified, or useBuild.VERSION.SDK_INT >= 33/ a static gradient overlay.Modifier.blur()
// ripple.agsl
uniform float2 resolution;
uniform float2 origin;
uniform float time;
uniform shader image;
half4 main(float2 fragCoord) {
float2 toOrigin = fragCoord - origin;
float dist = length(toOrigin);
float wave = sin(dist * 0.05 - time * 8.0) * 0.05;
float falloff = 1.0 / max(dist * 0.01, 1.0);
float2 dir = toOrigin / max(dist, 0.0001);
float2 displaced = fragCoord + dir * wave * falloff * 50.0;
return image.eval(displaced);
}timeLaunchedEffect@Composable
fun RippleSurface(content: @Composable BoxScope.() -> Unit) {
if (Build.VERSION.SDK_INT < 33) { Box { content() }; return }
val shader = remember { RuntimeShader(RIPPLE_AGSL) }
var origin by remember { mutableStateOf(Offset.Zero) }
var startMs by remember { mutableStateOf<Long?>(null) }
val time by produceState(0f, startMs) {
if (startMs == null) { value = 0f; return@produceState }
val begin = startMs!!
while (true) {
withFrameMillis { now ->
value = (now - begin) / 1000f
}
}
}
Box(
modifier = Modifier
.onSizeChanged {
shader.setFloatUniform("resolution", it.width.toFloat(), it.height.toFloat())
}
.pointerInput(Unit) {
detectTapGestures { tap ->
origin = tap
startMs = System.currentTimeMillis()
}
}
.graphicsLayer {
shader.setFloatUniform("origin", origin.x, origin.y)
shader.setFloatUniform("time", time)
renderEffect = RenderEffect
.createRuntimeShaderEffect(shader, "image")
.asComposeRenderEffect()
},
content = content
)
}uniform float time;
uniform shader image;
half4 main(float2 fragCoord) {
half4 color = image.eval(fragCoord);
float n = fragCoord.x * 0.01 + fragCoord.y * 0.005 + time * 0.3;
half3 rainbow = half3(
sin(n * 2.0) * 0.5 + 0.5,
sin(n * 2.0 + 2.094) * 0.5 + 0.5,
sin(n * 2.0 + 4.188) * 0.5 + 0.5
);
half luma = dot(color.rgb, half3(0.299, 0.587, 0.114));
return half4(mix(color.rgb, rainbow * luma * 2.0, 0.5), color.a);
}timeglassEffectuniform float2 resolution;
uniform shader image;
half4 main(float2 fragCoord) {
float2 uv = fragCoord / resolution;
// Chromatic aberration: sample R, G, B at slightly different offsets
float2 ca = (uv - 0.5) * 0.004;
half r = image.eval(fragCoord + ca * resolution).r;
half g = image.eval(fragCoord).g;
half b = image.eval(fragCoord - ca * resolution).b;
half4 base = half4(r, g, b, 1.0);
// Soft edge tint: brighten near borders for that frosted look
float edge = smoothstep(0.45, 0.5, max(abs(uv.x - 0.5), abs(uv.y - 0.5)));
half3 tinted = base.rgb + half3(edge * 0.08);
return half4(tinted, 0.85);
}Modifier.blur(20.dp, BlurredEdgeTreatment.Unbounded)RuntimeShaderimage.eval(coord)Canvas(modifier = Modifier.size(200.dp)) {
// 'this' is DrawScope - size, drawCircle, drawPath, drawRect...
drawCircle(Color.Blue, radius = size.minDimension / 2)
drawPath(myPath, color = Color.White, style = Stroke(width = 4.dp.toPx()))
}| DrawScope method | Use |
|---|---|
| Filled or stroked circles |
| Rectangles, optionally with gradient brush |
| Arbitrary path with |
| Slice of an oval - useful for progress arcs |
| Straight segment between two |
| Text via |
| Escape hatch - access raw |
@Composable
fun AnimatedWave() {
val infinite = rememberInfiniteTransition(label = "wave")
val phase by infinite.animateFloat(
initialValue = 0f,
targetValue = 2 * PI.toFloat(),
animationSpec = infiniteRepeatable(
animation = tween(3000, easing = LinearEasing)
),
label = "phase"
)
Canvas(modifier = Modifier.fillMaxWidth().height(80.dp)) {
val path = Path()
var x = 0
while (x <= size.width.toInt()) {
val y = size.height / 2 + sin(x * 0.05f + phase) * 20f
if (x == 0) path.moveTo(x.toFloat(), y) else path.lineTo(x.toFloat(), y)
x += 2
}
drawPath(path, color = Color.Blue, style = Stroke(width = 2.dp.toPx()))
}
}data class Particle(var x: Float, var y: Float, var vx: Float, var vy: Float, var life: Float)
@Composable
fun ParticleField() {
val particles = remember {
mutableStateListOf<Particle>().apply {
repeat(50) {
add(Particle(
x = Random.nextFloat() * 1000f,
y = Random.nextFloat() * 1000f,
vx = (Random.nextFloat() - 0.5f) * 4f,
vy = (Random.nextFloat() - 0.5f) * 4f,
life = 1f
))
}
}
}
LaunchedEffect(Unit) {
while (true) {
withFrameMillis { /* tick */ }
particles.forEachIndexed { i, p ->
p.x += p.vx
p.y += p.vy
p.life -= 0.01f
if (p.life <= 0f) {
p.x = Random.nextFloat() * 1000f
p.y = Random.nextFloat() * 1000f
p.life = 1f
}
}
}
}
Canvas(modifier = Modifier.fillMaxSize()) {
particles.forEach { p ->
drawCircle(
color = Color.White.copy(alpha = p.life),
radius = 2.dp.toPx(),
center = Offset(p.x, p.y)
)
}
}
}references/canvas-generative.mdderivedStateOfLaunchedEffect(Unit) { while(true) { withFrameMillis { ... } } }delay(16)remembertranslate { drawPath(...) }// BAD - every interaction overshoots, UI feels like a bouncy castle
MaterialTheme(motionScheme = MotionScheme.expressive()) {
AppRoot()
}
// GOOD - Standard for chrome, scope Expressive to hero moments
MaterialTheme(motionScheme = MotionScheme.standard()) {
NavigationScaffold {
// Hero detail screen overrides locally
MaterialTheme(motionScheme = MotionScheme.expressive()) {
HeroDetail()
}
}
}// BAD - crashes on Android 12 and below
val shader = remember { RuntimeShader(AGSL_SOURCE) }
// GOOD - gate on SDK level, provide fallback
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
ShaderEffect { content() }
} else {
Box(modifier = Modifier.background(fallbackGradient)) { content() }
}// BAD - any state change in the parent triggers a recompose of the Canvas
Canvas(modifier = Modifier.fillMaxSize()) {
drawCircle(color = if (viewModel.isActive) Color.Red else Color.Blue, radius = 50f)
}
// GOOD - hoist the reads, derive a stable value
val color by remember { derivedStateOf { if (viewModel.isActive) Color.Red else Color.Blue } }
Canvas(modifier = Modifier.fillMaxSize()) {
drawCircle(color = color, radius = 50f)
}// BAD - 4 render passes per frame, GPU melts on mid-range devices
.graphicsLayer { renderEffect = blurEffect }
.graphicsLayer { renderEffect = chromaticEffect }
.graphicsLayer { renderEffect = noiseEffect }
.graphicsLayer { renderEffect = vignetteEffect }
// GOOD - one shader doing all the math in a single pass
.graphicsLayer { renderEffect = combinedGlassEffect }// BAD - new Path every frame, GC stutter
Canvas(modifier = Modifier.fillMaxSize()) {
val path = Path()
points.forEach { path.lineTo(it.x, it.y) }
drawPath(path, color = Color.Black)
}
// GOOD - reuse a remembered Path, rewind each frame
val path = remember { Path() }
Canvas(modifier = Modifier.fillMaxSize()) {
path.rewind()
points.forEach { path.lineTo(it.x, it.y) }
drawPath(path, color = Color.Black)
}| Need | Load |
|---|---|
| AGSL recipes (7 working shaders with binding code) | |
| M3 Expressive choreography deep-dive | |
| Generative drawing patterns (flow fields, L-systems, particles) | |
| Base animations (animateAsState, AnimatedVisibility, Transition) | |
| CMP patterns (shared UI iOS / Android / Desktop) | |