magic-glyphs 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +1 -1
- package/README.md +126 -89
- package/cli/index.js +32 -13
- package/cli/video.js +36 -0
- package/data/icons/apple.json +1 -0
- package/data/icons/arrow-down.json +1 -0
- package/data/icons/arrow-left.json +1 -0
- package/data/icons/arrow-right.json +1 -0
- package/data/icons/arrow-up.json +1 -0
- package/data/icons/bag.json +1 -0
- package/data/icons/battery.json +1 -0
- package/data/icons/bell.json +1 -0
- package/data/icons/bike.json +1 -0
- package/data/icons/bird.json +1 -0
- package/data/icons/bolt.json +1 -0
- package/data/icons/book.json +1 -0
- package/data/icons/bookmark.json +1 -0
- package/data/icons/briefcase.json +1 -0
- package/data/icons/bug.json +1 -0
- package/data/icons/bus.json +1 -0
- package/data/icons/cake.json +1 -0
- package/data/icons/calendar.json +1 -0
- package/data/icons/camera.json +1 -0
- package/data/icons/car.json +1 -0
- package/data/icons/card.json +1 -0
- package/data/icons/cart.json +1 -0
- package/data/icons/cat.json +1 -0
- package/data/icons/chat.json +1 -0
- package/data/icons/check.json +1 -0
- package/data/icons/chevron-down.json +1 -0
- package/data/icons/chevron-left.json +1 -0
- package/data/icons/chevron-right.json +1 -0
- package/data/icons/chevron-up.json +1 -0
- package/data/icons/circle-alert.json +1 -0
- package/data/icons/circle-check.json +1 -0
- package/data/icons/circle-minus.json +1 -0
- package/data/icons/circle-plus.json +1 -0
- package/data/icons/circle-x.json +1 -0
- package/data/icons/clipboard.json +1 -0
- package/data/icons/clock.json +1 -0
- package/data/icons/cloud.json +1 -0
- package/data/icons/code.json +1 -0
- package/data/icons/coffee.json +1 -0
- package/data/icons/coin.json +1 -0
- package/data/icons/copy.json +1 -0
- package/data/icons/database.json +1 -0
- package/data/icons/dog.json +1 -0
- package/data/icons/download.json +1 -0
- package/data/icons/drop.json +1 -0
- package/data/icons/edit.json +1 -0
- package/data/icons/external-link.json +1 -0
- package/data/icons/eye-off.json +1 -0
- package/data/icons/eye.json +1 -0
- package/data/icons/file.json +1 -0
- package/data/icons/filter.json +1 -0
- package/data/icons/fish.json +1 -0
- package/data/icons/flag.json +1 -0
- package/data/icons/flame.json +1 -0
- package/data/icons/folder.json +1 -0
- package/data/icons/frown.json +1 -0
- package/data/icons/gift.json +1 -0
- package/data/icons/globe.json +1 -0
- package/data/icons/hand.json +1 -0
- package/data/icons/heart.json +1 -0
- package/data/icons/help.json +1 -0
- package/data/icons/home.json +1 -0
- package/data/icons/image.json +1 -0
- package/data/icons/info.json +1 -0
- package/data/icons/key.json +1 -0
- package/data/icons/laptop.json +1 -0
- package/data/icons/laugh.json +1 -0
- package/data/icons/leaf.json +1 -0
- package/data/icons/link.json +1 -0
- package/data/icons/lock.json +1 -0
- package/data/icons/mail.json +1 -0
- package/data/icons/map.json +1 -0
- package/data/icons/menu.json +1 -0
- package/data/icons/mic.json +1 -0
- package/data/icons/minus.json +1 -0
- package/data/icons/monitor.json +1 -0
- package/data/icons/moon.json +1 -0
- package/data/icons/music.json +1 -0
- package/data/icons/package.json +1 -0
- package/data/icons/pause.json +1 -0
- package/data/icons/pencil.json +1 -0
- package/data/icons/phone.json +1 -0
- package/data/icons/pin.json +1 -0
- package/data/icons/pizza.json +1 -0
- package/data/icons/plane.json +1 -0
- package/data/icons/play.json +1 -0
- package/data/icons/plus.json +1 -0
- package/data/icons/printer.json +1 -0
- package/data/icons/receipt.json +1 -0
- package/data/icons/refresh.json +1 -0
- package/data/icons/rocket.json +1 -0
- package/data/icons/save.json +1 -0
- package/data/icons/search.json +1 -0
- package/data/icons/server.json +1 -0
- package/data/icons/settings.json +1 -0
- package/data/icons/share.json +1 -0
- package/data/icons/shield.json +1 -0
- package/data/icons/smile.json +1 -0
- package/data/icons/star.json +1 -0
- package/data/icons/stop.json +1 -0
- package/data/icons/store.json +1 -0
- package/data/icons/sun.json +1 -0
- package/data/icons/tablet.json +1 -0
- package/data/icons/tag.json +1 -0
- package/data/icons/terminal.json +1 -0
- package/data/icons/thumbs-down.json +1 -0
- package/data/icons/thumbs-up.json +1 -0
- package/data/icons/train.json +1 -0
- package/data/icons/trash.json +1 -0
- package/data/icons/tree.json +1 -0
- package/data/icons/truck.json +1 -0
- package/data/icons/upload.json +1 -0
- package/data/icons/user.json +1 -0
- package/data/icons/users.json +1 -0
- package/data/icons/video.json +1 -0
- package/data/icons/volume.json +1 -0
- package/data/icons/wallet.json +1 -0
- package/data/icons/wave.json +1 -0
- package/data/icons/wifi.json +1 -0
- package/data/icons/wink.json +1 -0
- package/data/index.json +1 -1
- package/docs/avalonia.md +15 -0
- package/docs/cli.md +1 -1
- package/docs/figma.md +12 -0
- package/docs/flutter.md +18 -0
- package/docs/godot.md +13 -0
- package/docs/images-video.md +42 -0
- package/docs/jetpack-compose.md +39 -0
- package/docs/maker.md +64 -0
- package/docs/maui.md +17 -0
- package/docs/more-frameworks.md +49 -0
- package/docs/native-lottie.md +5 -0
- package/docs/qt.md +26 -0
- package/docs/react-native.md +34 -0
- package/docs/react-vue.md +12 -1
- package/docs/rust.md +43 -0
- package/docs/site-builders.md +27 -0
- package/docs/sound.md +2 -2
- package/docs/swiftui.md +22 -0
- package/docs/tauri-rust.md +15 -0
- package/docs/unity.md +15 -0
- package/docs/windows.md +23 -0
- package/lib.js +9 -1
- package/mcp/server.js +1 -1
- package/package.json +48 -11
- package/shopify/magic-glyph.liquid +8 -6
- package/tools/apng.js +36 -0
- package/tools/baked.js +30 -0
- package/tools/gif.js +60 -0
- package/tools/motion.js +31 -0
- package/tools/native.js +208 -0
- package/tools/native2.js +432 -0
- package/tools/raster.js +139 -0
- package/web/magic-glyphs.all.js +4 -3
- package/web/runtime.js +4 -3
- package/wordpress/magic-glyphs/magic-glyphs.all.js +4 -3
- package/wordpress/magic-glyphs/magic-glyphs.php +19 -6
package/tools/native2.js
ADDED
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
// More native targets. Most draw the icon's own vectors and play the motion baked by tools/baked.js,
|
|
2
|
+
// so they need no animation library: Qt Quick (QML), Avalonia, Godot, Rust. .NET MAUI and Compose Multiplatform use
|
|
3
|
+
// their usual Lottie players; Unity (and any game engine) gets a sprite sheet.
|
|
4
|
+
const B=require('./baked.js');
|
|
5
|
+
const pascal=(n)=>n.split(/[^a-z0-9]+/i).filter(Boolean).map((w)=>w[0].toUpperCase()+w.slice(1)).join('').replace(/^(\d)/,'Glyph$1');
|
|
6
|
+
const snake=(n)=>n.replace(/[^a-z0-9]+/gi,'_').toLowerCase().replace(/^(\d)/,'glyph_$1');
|
|
7
|
+
const num=(v)=>(Math.round(v*1000)/1000).toString();
|
|
8
|
+
const fl=(v)=>{const t=num(v);return /[.e]/.test(t)?t:t+'.0'};
|
|
9
|
+
const rot=(r)=>{if(!r)return null;const t=r[0]*Math.PI/180,c=Math.cos(t),s=Math.sin(t);return[c,s,-s,c,r[1]-c*r[1]+s*r[2],r[2]-s*r[1]-c*r[2]].map(num)};
|
|
10
|
+
const colours=(o)=>({fg:o.color||'#000000',bg:o.background||'#ffffff',sec:o.secondary||o.color||'#000000'});
|
|
11
|
+
|
|
12
|
+
// ---------- Qt Quick (Qt 6.6+) ----------
|
|
13
|
+
function qml(ic,o){
|
|
14
|
+
const b=B.bake(o.MG,ic,{style:o.style,fps:30}),P=pascal(ic.n),c=colours(o);
|
|
15
|
+
const role=(r)=>r==='fg'?'root.color':r==='bg'?'root.background':'root.secondary';
|
|
16
|
+
const M='['+b.layers.map(l=>l.m?'['+l.m.flat().map(num).join(',')+']':'null').join(',\n ')+']';
|
|
17
|
+
const shapes=b.layers.map((l,i)=>` Item {
|
|
18
|
+
width: 24; height: 24
|
|
19
|
+
transform: Matrix4x4 { matrix: root.mat(${i}) }
|
|
20
|
+
${l.paths.map(p=>{const r=rot(p.r);return ` Shape {
|
|
21
|
+
width: 24; height: 24; preferredRendererType: Shape.CurveRenderer${r?`
|
|
22
|
+
transform: Matrix4x4 { matrix: Qt.matrix4x4(${r[0]}, ${r[2]}, 0, ${r[4]}, ${r[1]}, ${r[3]}, 0, ${r[5]}, 0, 0, 1, 0, 0, 0, 0, 1) }`:''}
|
|
23
|
+
ShapePath {
|
|
24
|
+
strokeColor: ${l.paint.stroke?role(l.paint.stroke):'"transparent"'}; strokeWidth: ${l.paint.stroke?1.75:0}
|
|
25
|
+
capStyle: ShapePath.RoundCap; joinStyle: ShapePath.RoundJoin
|
|
26
|
+
fillColor: ${p.fill?JSON.stringify(p.fill):l.paint.fill?(l.paint.fillOpacity?`Qt.rgba(${role(l.paint.fill)}.r, ${role(l.paint.fill)}.g, ${role(l.paint.fill)}.b, ${l.paint.fillOpacity})`:role(l.paint.fill)):'"transparent"'}
|
|
27
|
+
PathSvg { path: ${JSON.stringify(p.d)} }
|
|
28
|
+
}
|
|
29
|
+
}`}).join('\n')}
|
|
30
|
+
}`).join('\n');
|
|
31
|
+
return{file:P+'Glyph.qml',text:`// Animated "${ic.n}" icon from Magic Glyphs for Qt Quick (Qt 6.6 or newer). No plugins or Lottie needed:
|
|
32
|
+
// it draws the icon's own vectors and plays its spring motion, pre-computed at ${b.fps} frames per second.
|
|
33
|
+
// Use: ${P}Glyph { size: 32; color: "#2747f5" } Sound, optional: put ${ic.n}.wav next to this file and set sound: true (uses Qt Multimedia).
|
|
34
|
+
import QtQuick
|
|
35
|
+
import QtQuick.Shapes
|
|
36
|
+
|
|
37
|
+
Item {
|
|
38
|
+
id: root
|
|
39
|
+
property real size: 24
|
|
40
|
+
property color color: ${JSON.stringify(c.fg)}
|
|
41
|
+
property color background: ${JSON.stringify(c.bg)} // knocked-out details in the solid style
|
|
42
|
+
property color secondary: ${o.secondary?JSON.stringify(o.secondary):'color'}
|
|
43
|
+
property string trigger: "hover" // hover | click | none (call play() yourself)
|
|
44
|
+
property bool sound: false
|
|
45
|
+
property real frame: ${b.frames-1}
|
|
46
|
+
readonly property int frames: ${b.frames}
|
|
47
|
+
readonly property var motion: ${M}
|
|
48
|
+
width: size; height: size
|
|
49
|
+
|
|
50
|
+
property var fx: null
|
|
51
|
+
// Qt Multimedia is only loaded when sound is on, so apps without it still work
|
|
52
|
+
function play() {
|
|
53
|
+
anim.restart();
|
|
54
|
+
if (!sound) return;
|
|
55
|
+
if (!fx) fx = Qt.createQmlObject('import QtMultimedia; SoundEffect { source: "' + Qt.resolvedUrl("${ic.n}.wav") + '" }', root);
|
|
56
|
+
fx.play();
|
|
57
|
+
}
|
|
58
|
+
function mat(i) {
|
|
59
|
+
var a = motion[i], t = frame;
|
|
60
|
+
if (!a) return Qt.matrix4x4();
|
|
61
|
+
var k = Math.floor(t), f = t - k, j = Math.min(k + 1, frames - 1);
|
|
62
|
+
function v(n) { return a[k * 6 + n] + (a[j * 6 + n] - a[k * 6 + n]) * f }
|
|
63
|
+
return Qt.matrix4x4(v(0), v(2), 0, v(4), v(1), v(3), 0, v(5), 0, 0, 1, 0, 0, 0, 0, 1);
|
|
64
|
+
}
|
|
65
|
+
NumberAnimation { id: anim; target: root; property: "frame"; from: 0; to: root.frames - 1; duration: ${Math.round((b.frames-1)/b.fps*1000)} }
|
|
66
|
+
HoverHandler { onHoveredChanged: if (hovered && root.trigger === "hover") root.play() }
|
|
67
|
+
TapHandler { onTapped: if (root.trigger !== "none") root.play() }
|
|
68
|
+
|
|
69
|
+
Item {
|
|
70
|
+
width: 24; height: 24
|
|
71
|
+
transform: Scale { xScale: root.size / 24; yScale: root.size / 24 }
|
|
72
|
+
${shapes}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
`};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// ---------- Avalonia 11 ----------
|
|
79
|
+
function avalonia(ic,o){
|
|
80
|
+
const b=B.bake(o.MG,ic,{style:o.style,fps:30}),P=pascal(ic.n),c=colours(o);
|
|
81
|
+
const brush=(r,op)=>r?(op?`WithOpacity(${r==='fg'?'fg':r==='bg'?'bg':'sec'}, ${op})`:(r==='fg'?'fg':r==='bg'?'bg':'sec')):'null';
|
|
82
|
+
const M=b.layers.map(l=>l.m?'new double[] { '+l.m.flat().map(num).join(', ')+' }':'null').join(',\n ');
|
|
83
|
+
const build=b.layers.map((l,i)=>` _layers[${i}] = Layer(root${l.paths.map(p=>{const r=rot(p.r);return `,
|
|
84
|
+
Shape(${JSON.stringify(p.d)}, ${p.fill?`Brush.Parse(${JSON.stringify(p.fill)})`:brush(l.paint.fill,l.paint.fillOpacity)}, ${brush(l.paint.stroke)}${r?`, new Matrix(${r.join(', ')})`:''})`}).join('')});`).join('\n');
|
|
85
|
+
return{file:P+'Glyph.Avalonia.cs',text:`// Animated "${ic.n}" icon from Magic Glyphs for Avalonia 11. No extra packages:
|
|
86
|
+
// it draws the icon's own vectors and plays its spring motion, pre-computed at ${b.fps} frames per second.
|
|
87
|
+
// Use: new ${P}Glyph(size: 32, color: "#2747f5") It plays on hover and click; call Play() yourself for other triggers.
|
|
88
|
+
// Sound: Avalonia has no built-in audio, so handle the Played event with the audio library you use and ${ic.n}.wav.
|
|
89
|
+
using System;
|
|
90
|
+
using System.Diagnostics;
|
|
91
|
+
using Avalonia;
|
|
92
|
+
using Avalonia.Controls;
|
|
93
|
+
using Avalonia.Controls.Shapes;
|
|
94
|
+
using Avalonia.Media;
|
|
95
|
+
using Avalonia.Threading;
|
|
96
|
+
|
|
97
|
+
namespace MagicGlyphs;
|
|
98
|
+
|
|
99
|
+
public sealed class ${P}Glyph : Viewbox
|
|
100
|
+
{
|
|
101
|
+
private static readonly double[]?[] Motion =
|
|
102
|
+
{
|
|
103
|
+
${M}
|
|
104
|
+
};
|
|
105
|
+
private const int Frames = ${b.frames};
|
|
106
|
+
private const double Fps = ${b.fps};
|
|
107
|
+
private readonly Canvas[] _layers = new Canvas[${b.layers.length}];
|
|
108
|
+
private readonly DispatcherTimer _timer;
|
|
109
|
+
private readonly Stopwatch _clock = new();
|
|
110
|
+
public event EventHandler? Played;
|
|
111
|
+
|
|
112
|
+
public ${P}Glyph(double size = 24, string color = ${JSON.stringify(c.fg)}, string background = ${JSON.stringify(c.bg)}, string? secondary = null)
|
|
113
|
+
{
|
|
114
|
+
Width = Height = size;
|
|
115
|
+
IBrush fg = Brush.Parse(color), bg = Brush.Parse(background), sec = Brush.Parse(secondary ?? color);
|
|
116
|
+
var root = new Canvas { Width = 24, Height = 24 };
|
|
117
|
+
Child = root;
|
|
118
|
+
${build}
|
|
119
|
+
_timer = new DispatcherTimer(TimeSpan.FromMilliseconds(15), DispatcherPriority.Render, (_, _) => Tick());
|
|
120
|
+
PointerEntered += (_, _) => Play();
|
|
121
|
+
PointerPressed += (_, _) => Play();
|
|
122
|
+
Apply(Frames - 1);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
public void Play() { _clock.Restart(); _timer.Start(); Played?.Invoke(this, EventArgs.Empty); }
|
|
126
|
+
|
|
127
|
+
private void Tick()
|
|
128
|
+
{
|
|
129
|
+
var t = _clock.Elapsed.TotalSeconds * Fps;
|
|
130
|
+
if (t >= Frames - 1) { t = Frames - 1; _timer.Stop(); }
|
|
131
|
+
Apply(t);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
private void Apply(double t)
|
|
135
|
+
{
|
|
136
|
+
int k = (int)t, j = Math.Min(k + 1, Frames - 1);
|
|
137
|
+
double f = t - k;
|
|
138
|
+
for (var i = 0; i < _layers.Length; i++)
|
|
139
|
+
{
|
|
140
|
+
var a = Motion[i];
|
|
141
|
+
if (a == null) continue;
|
|
142
|
+
double V(int n) => a[k * 6 + n] + (a[j * 6 + n] - a[k * 6 + n]) * f;
|
|
143
|
+
_layers[i].RenderTransform = new MatrixTransform(new Matrix(V(0), V(1), V(2), V(3), V(4), V(5)));
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
private static Canvas Layer(Canvas root, params Path[] paths)
|
|
148
|
+
{
|
|
149
|
+
var c = new Canvas { Width = 24, Height = 24, RenderTransformOrigin = new RelativePoint(0, 0, RelativeUnit.Absolute) };
|
|
150
|
+
foreach (var p in paths) c.Children.Add(p);
|
|
151
|
+
root.Children.Add(c);
|
|
152
|
+
return c;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
private static Path Shape(string d, IBrush? fill, IBrush? stroke, Matrix? turn = null) => new()
|
|
156
|
+
{
|
|
157
|
+
Data = Geometry.Parse(d), Fill = fill, Stroke = stroke, StrokeThickness = stroke == null ? 0 : 1.75,
|
|
158
|
+
StrokeLineCap = PenLineCap.Round, StrokeJoin = PenLineJoin.Round,
|
|
159
|
+
RenderTransformOrigin = new RelativePoint(0, 0, RelativeUnit.Absolute),
|
|
160
|
+
RenderTransform = turn is { } m ? new MatrixTransform(m) : null,
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
private static IBrush WithOpacity(IBrush b, double o) => b is ISolidColorBrush s ? new SolidColorBrush(s.Color, o) : b;
|
|
164
|
+
}
|
|
165
|
+
`};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// ---------- .NET MAUI (SkiaSharp Lottie) ----------
|
|
169
|
+
function maui(ic,o){
|
|
170
|
+
const P=pascal(ic.n),j=require('./native.js').lottieJson(ic,Object.assign({},o,{style:o.style})).replace(/"/g,'""');
|
|
171
|
+
return{file:P+'Glyph.Maui.cs',text:`// Animated "${ic.n}" icon from Magic Glyphs for .NET MAUI (Android, iOS, macOS, Windows).
|
|
172
|
+
// Needs: dotnet add package SkiaSharp.Extended.UI.Maui and in MauiProgram.cs: builder.UseSkiaSharp();
|
|
173
|
+
// Sound, optional: dotnet add package Plugin.Maui.Audio, add ${ic.n}.wav under Resources/Raw, then pass an IAudioManager.
|
|
174
|
+
using System.IO;
|
|
175
|
+
using System.Text;
|
|
176
|
+
using System.Threading.Tasks;
|
|
177
|
+
using Microsoft.Maui.Controls;
|
|
178
|
+
using SkiaSharp.Extended.UI.Controls;
|
|
179
|
+
|
|
180
|
+
namespace MagicGlyphs;
|
|
181
|
+
|
|
182
|
+
public sealed class ${P}Glyph : ContentView
|
|
183
|
+
{
|
|
184
|
+
private const string Json = @"${j}";
|
|
185
|
+
private readonly SKLottieView _view;
|
|
186
|
+
public Func<Task>? PlaySound { get; set; }
|
|
187
|
+
|
|
188
|
+
public ${P}Glyph(double size = 24)
|
|
189
|
+
{
|
|
190
|
+
WidthRequest = HeightRequest = size;
|
|
191
|
+
_view = new SKLottieView
|
|
192
|
+
{
|
|
193
|
+
Source = new SKStreamLottieImageSource { Stream = _ => Task.FromResult<Stream?>(new MemoryStream(Encoding.UTF8.GetBytes(Json))) },
|
|
194
|
+
RepeatCount = 0,
|
|
195
|
+
IsAnimationEnabled = false,
|
|
196
|
+
};
|
|
197
|
+
Content = _view;
|
|
198
|
+
var tap = new TapGestureRecognizer();
|
|
199
|
+
tap.Tapped += (_, _) => Play();
|
|
200
|
+
GestureRecognizers.Add(tap);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
public void Play()
|
|
204
|
+
{
|
|
205
|
+
_view.Progress = TimeSpan.Zero;
|
|
206
|
+
_view.IsAnimationEnabled = true;
|
|
207
|
+
PlaySound?.Invoke();
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
`};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// ---------- Compose Multiplatform (Compottie) ----------
|
|
214
|
+
function composeMp(ic,o){
|
|
215
|
+
const P=pascal(ic.n),j=require('./native.js').lottieJson(ic,o).replace(/\$/g,'${"$"}');
|
|
216
|
+
return{file:P+'Glyph.kt',text:`// Animated "${ic.n}" icon from Magic Glyphs for Compose Multiplatform (Android, iOS, desktop, web).
|
|
217
|
+
// Needs: implementation("io.github.alexzhirkevich:compottie:2.0.0") (any 2.x)
|
|
218
|
+
// Sound: play ${ic.n}.wav with your platform's audio API from onPlay.
|
|
219
|
+
package magicglyphs
|
|
220
|
+
|
|
221
|
+
import androidx.compose.foundation.clickable
|
|
222
|
+
import androidx.compose.foundation.layout.size
|
|
223
|
+
import androidx.compose.runtime.*
|
|
224
|
+
import androidx.compose.ui.Modifier
|
|
225
|
+
import androidx.compose.ui.unit.Dp
|
|
226
|
+
import androidx.compose.ui.unit.dp
|
|
227
|
+
import io.github.alexzhirkevich.compottie.*
|
|
228
|
+
|
|
229
|
+
private const val ${P.toUpperCase()}_JSON = """${j}"""
|
|
230
|
+
|
|
231
|
+
@Composable
|
|
232
|
+
fun ${P}Glyph(modifier: Modifier = Modifier, size: Dp = 24.dp, onPlay: () -> Unit = {}) {
|
|
233
|
+
val composition by rememberLottieComposition { LottieCompositionSpec.JsonString(${P.toUpperCase()}_JSON) }
|
|
234
|
+
var plays by remember { mutableStateOf(0) }
|
|
235
|
+
val progress by animateLottieCompositionAsState(composition, isPlaying = plays > 0, restartOnPlay = true, iterations = 1)
|
|
236
|
+
androidx.compose.foundation.Image(
|
|
237
|
+
painter = rememberLottiePainter(composition, progress = { if (plays == 0) 1f else progress }),
|
|
238
|
+
contentDescription = null,
|
|
239
|
+
modifier = modifier.size(size).clickable { plays++; onPlay() },
|
|
240
|
+
)
|
|
241
|
+
}
|
|
242
|
+
`};
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// ---------- Godot 4 ----------
|
|
246
|
+
function godot(ic,o){
|
|
247
|
+
const b=B.bake(o.MG,ic,{style:o.style,fps:30,polys:true}),c=colours(o);
|
|
248
|
+
const col=(r,op)=>r?`Color(${r==='fg'?'color':r==='bg'?'background':'secondary'}, ${op||1})`:'null';
|
|
249
|
+
const layers=b.layers.map(l=>`\t{"m": ${l.m?'PackedFloat32Array(['+l.m.flat().map(num).join(', ')+'])':'null'}, "shapes": [${l.paths.map(p=>`{"polys": [${p.polys.map(q=>`[PackedVector2Array([${q.pts.reduce((a,v,i)=>i%2?a:a.concat(`Vector2(${num(q.pts[i])}, ${num(q.pts[i+1])})`),[]).join(', ')}]), ${q.closed}]`).join(', ')}], "fill": ${p.fill?`Color(${JSON.stringify(p.fill)})`:`"${l.paint.fill||''}"`}, "fill_opacity": ${l.paint.fillOpacity||1}, "stroke": "${l.paint.stroke||''}"}`).join(', ')}]}`).join(',\n');
|
|
250
|
+
return{file:snake(ic.n)+'_glyph.gd',text:`# Animated "${ic.n}" icon from Magic Glyphs for Godot 4. No plugins:
|
|
251
|
+
# it draws the icon's own vectors and plays its spring motion, pre-computed at ${b.fps} frames per second.
|
|
252
|
+
# Use: add a Control node, attach this script, set its size. Plays on hover and click; call play() for other triggers.
|
|
253
|
+
# Sound, optional: put ${ic.n}.wav in res://, set sound_stream to it.
|
|
254
|
+
extends Control
|
|
255
|
+
|
|
256
|
+
@export var color := Color(${JSON.stringify(c.fg)})
|
|
257
|
+
@export var background := Color(${JSON.stringify(c.bg)})
|
|
258
|
+
@export var secondary := Color(${JSON.stringify(c.sec)})
|
|
259
|
+
@export var sound_stream: AudioStream
|
|
260
|
+
@export var play_on_hover := true
|
|
261
|
+
|
|
262
|
+
const FRAMES := ${b.frames}
|
|
263
|
+
const FPS := ${b.fps}.0
|
|
264
|
+
var LAYERS := [
|
|
265
|
+
${layers}
|
|
266
|
+
]
|
|
267
|
+
var _t := float(FRAMES - 1)
|
|
268
|
+
var _playing := false
|
|
269
|
+
var _audio: AudioStreamPlayer
|
|
270
|
+
|
|
271
|
+
func _ready() -> void:
|
|
272
|
+
\tmouse_entered.connect(func(): if play_on_hover: play())
|
|
273
|
+
\tif custom_minimum_size == Vector2.ZERO:
|
|
274
|
+
\t\tcustom_minimum_size = Vector2(24, 24)
|
|
275
|
+
|
|
276
|
+
func _gui_input(event: InputEvent) -> void:
|
|
277
|
+
\tif event is InputEventMouseButton and event.pressed:
|
|
278
|
+
\t\tplay()
|
|
279
|
+
|
|
280
|
+
func play() -> void:
|
|
281
|
+
\t_t = 0.0
|
|
282
|
+
\t_playing = true
|
|
283
|
+
\tif sound_stream:
|
|
284
|
+
\t\tif _audio == null:
|
|
285
|
+
\t\t\t_audio = AudioStreamPlayer.new()
|
|
286
|
+
\t\t\tadd_child(_audio)
|
|
287
|
+
\t\t_audio.stream = sound_stream
|
|
288
|
+
\t\t_audio.play()
|
|
289
|
+
|
|
290
|
+
func _process(delta: float) -> void:
|
|
291
|
+
\tif not _playing:
|
|
292
|
+
\t\treturn
|
|
293
|
+
\t_t = min(_t + delta * FPS, FRAMES - 1)
|
|
294
|
+
\tif _t >= FRAMES - 1:
|
|
295
|
+
\t\t_playing = false
|
|
296
|
+
\tqueue_redraw()
|
|
297
|
+
|
|
298
|
+
func _matrix(a) -> Transform2D:
|
|
299
|
+
\tif a == null:
|
|
300
|
+
\t\treturn Transform2D.IDENTITY
|
|
301
|
+
\tvar k := int(_t)
|
|
302
|
+
\tvar j := mini(k + 1, FRAMES - 1)
|
|
303
|
+
\tvar f := _t - k
|
|
304
|
+
\tvar v := func(n): return lerpf(a[k * 6 + n], a[j * 6 + n], f)
|
|
305
|
+
\treturn Transform2D(Vector2(v.call(0), v.call(1)), Vector2(v.call(2), v.call(3)), Vector2(v.call(4), v.call(5)))
|
|
306
|
+
|
|
307
|
+
func _paint(role: String) -> Color:
|
|
308
|
+
\treturn color if role == "fg" else background if role == "bg" else secondary
|
|
309
|
+
|
|
310
|
+
func _draw() -> void:
|
|
311
|
+
\tvar k := minf(size.x, size.y) / 24.0
|
|
312
|
+
\tvar w := 1.75 * k
|
|
313
|
+
\tfor layer in LAYERS:
|
|
314
|
+
\t\tvar m := Transform2D().scaled(Vector2(k, k)) * _matrix(layer["m"])
|
|
315
|
+
\t\tfor shape in layer["shapes"]:
|
|
316
|
+
\t\t\tfor poly in shape["polys"]:
|
|
317
|
+
\t\t\t\tvar pts: PackedVector2Array = m * poly[0]
|
|
318
|
+
\t\t\t\tvar fill = shape["fill"]
|
|
319
|
+
\t\t\t\tif fill is Color or fill != "":
|
|
320
|
+
\t\t\t\t\tvar fc: Color = fill if fill is Color else _paint(fill)
|
|
321
|
+
\t\t\t\t\tfc.a *= shape["fill_opacity"]
|
|
322
|
+
\t\t\t\t\tif pts.size() >= 3:
|
|
323
|
+
\t\t\t\t\t\tdraw_colored_polygon(pts, fc)
|
|
324
|
+
\t\t\t\tif shape["stroke"] != "":
|
|
325
|
+
\t\t\t\t\tvar sc := _paint(shape["stroke"])
|
|
326
|
+
\t\t\t\t\tif poly[1]:
|
|
327
|
+
\t\t\t\t\t\tpts.append(pts[0])
|
|
328
|
+
\t\t\t\t\tdraw_polyline(pts, sc, w, true)
|
|
329
|
+
\t\t\t\t\tfor p in pts:
|
|
330
|
+
\t\t\t\t\t\tdraw_circle(p, w / 2.0, sc)
|
|
331
|
+
`};
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// ---------- Rust (the magic-glyphs crate) ----------
|
|
335
|
+
function rust(ic,o){
|
|
336
|
+
const b=B.bake(o.MG,ic,{style:'outline',fps:30}),k={c:'Main',o:'Line',i:'Detail',d:'Dot',f:'Fill'};
|
|
337
|
+
const layers=ic.L.map((l,i)=>` Layer { kind: Kind::${k[l.k]}, paths: &[${l.p.map(p=>`Path { d: ${JSON.stringify(p.d)}, turn: ${p.r?`Some([${p.r.map(fl).join(', ')}])`:'None'}, fill: ${p.f?`Some(${JSON.stringify(p.f)})`:'None'} }`).join(', ')}], motion: ${b.layers[i].m?'Some(&['+b.layers[i].m.flat().map(fl).join(', ')+'])':'None'} },`).join('\n');
|
|
338
|
+
return{file:snake(ic.n)+'.rs',text:`// Animated "${ic.n}" icon from Magic Glyphs, for the magic-glyphs crate (cargo add magic-glyphs).
|
|
339
|
+
// Use: mod ${snake(ic.n)}; let icon = ${snake(ic.n)}::ICON; then icon.svg_at(t, &style) or the egui widget.
|
|
340
|
+
use magic_glyphs::{Icon, Kind, Layer, Path};
|
|
341
|
+
|
|
342
|
+
pub const ICON: Icon = Icon {
|
|
343
|
+
name: ${JSON.stringify(ic.n)},
|
|
344
|
+
sound: ${ic.s?`Some(${JSON.stringify(ic.s)})`:'None'},
|
|
345
|
+
fps: ${b.fps},
|
|
346
|
+
frames: ${b.frames},
|
|
347
|
+
layers: &[
|
|
348
|
+
${layers}
|
|
349
|
+
],
|
|
350
|
+
};
|
|
351
|
+
`};
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// ---------- sprite sheet: one PNG with every frame in a grid, plus frame data (Unity, game engines, CSS) ----------
|
|
355
|
+
function spritesheet(ic,o){
|
|
356
|
+
const R=require('./raster.js'),z=require('zlib'),size=o.size||128,fps=o.fps||30;
|
|
357
|
+
const r=R.render(o.MG,ic,{size,style:o.style,color:o.color||'#000000',secondary:o.secondary,background:o.background||'transparent',fps,lead:0,hold:0});
|
|
358
|
+
const n=r.frames.length,cols=Math.ceil(Math.sqrt(n)),rows=Math.ceil(n/cols),W=cols*size,H=rows*size,img=new Uint8Array(W*H*4);
|
|
359
|
+
r.frames.forEach((f,i)=>{const x0=(i%cols)*size,y0=Math.floor(i/cols)*size;for(let y=0;y<size;y++)img.set(f.subarray(y*size*4,(y+1)*size*4),((y0+y)*W+x0)*4)});
|
|
360
|
+
const png=pngFile(W,H,img,z),meta={name:ic.n,frameWidth:size,frameHeight:size,columns:cols,rows,frames:n,fps,durations:r.delays.map(d=>Math.round(d*1000)),sound:ic.s?ic.n+'.wav':null};
|
|
361
|
+
return{png,meta};
|
|
362
|
+
}
|
|
363
|
+
function pngFile(W,H,rgba,z){
|
|
364
|
+
const CRC=new Uint32Array(256);for(let n=0;n<256;n++){let c=n;for(let k=0;k<8;k++)c=c&1?0xEDB88320^(c>>>1):c>>>1;CRC[n]=c>>>0}
|
|
365
|
+
const crc=b=>{let c=0xFFFFFFFF;for(let i=0;i<b.length;i++)c=CRC[(c^b[i])&255]^(c>>>8);return(c^0xFFFFFFFF)>>>0};
|
|
366
|
+
const chunk=(t,d)=>{const b=Buffer.alloc(12+d.length);b.writeUInt32BE(d.length,0);b.write(t,4);Buffer.from(d).copy(b,8);b.writeUInt32BE(crc(b.subarray(4,8+d.length)),8+d.length);return b};
|
|
367
|
+
const raw=Buffer.alloc(H*(W*4+1));for(let y=0;y<H;y++){raw[y*(W*4+1)]=0;Buffer.from(rgba.buffer,rgba.byteOffset+y*W*4,W*4).copy(raw,y*(W*4+1)+1)}
|
|
368
|
+
const ih=Buffer.alloc(13);ih.writeUInt32BE(W,0);ih.writeUInt32BE(H,4);ih[8]=8;ih[9]=6;
|
|
369
|
+
return Buffer.concat([Buffer.from([137,80,78,71,13,10,26,10]),chunk('IHDR',ih),chunk('IDAT',z.deflateSync(raw,{level:9})),chunk('IEND',Buffer.alloc(0))]);
|
|
370
|
+
}
|
|
371
|
+
// ---------- Unity: a component that plays the sprite sheet (written next to it) ----------
|
|
372
|
+
function unity(ic,o){
|
|
373
|
+
const s=spritesheet(ic,Object.assign({},o,{size:o.size||128})),P=pascal(ic.n);
|
|
374
|
+
return{file:P+'Glyph.cs',extra:[{file:ic.n+'.sheet.png',data:s.png}],text:`// Animated "${ic.n}" icon from Magic Glyphs for Unity (UI Image or SpriteRenderer).
|
|
375
|
+
// Import ${ic.n}.sheet.png as a Texture (Read/Write not needed), assign it to Sheet, and add this to a GameObject
|
|
376
|
+
// that has an Image (UI) or a SpriteRenderer. Sound, optional: assign ${ic.n}.wav to Sound.
|
|
377
|
+
using System.Collections;
|
|
378
|
+
using UnityEngine;
|
|
379
|
+
using UnityEngine.EventSystems;
|
|
380
|
+
using UnityEngine.UI;
|
|
381
|
+
|
|
382
|
+
public class ${P}Glyph : MonoBehaviour, IPointerEnterHandler, IPointerClickHandler
|
|
383
|
+
{
|
|
384
|
+
public Texture2D Sheet;
|
|
385
|
+
public AudioClip Sound;
|
|
386
|
+
public bool PlayOnHover = true;
|
|
387
|
+
const int FrameSize = ${s.meta.frameWidth}, Columns = ${s.meta.columns}, Frames = ${s.meta.frames};
|
|
388
|
+
static readonly int[] DurationsMs = { ${s.meta.durations.join(', ')} };
|
|
389
|
+
Sprite[] _sprites;
|
|
390
|
+
Image _image;
|
|
391
|
+
SpriteRenderer _renderer;
|
|
392
|
+
AudioSource _audio;
|
|
393
|
+
Coroutine _run;
|
|
394
|
+
|
|
395
|
+
void Awake()
|
|
396
|
+
{
|
|
397
|
+
_image = GetComponent<Image>();
|
|
398
|
+
_renderer = GetComponent<SpriteRenderer>();
|
|
399
|
+
_sprites = new Sprite[Frames];
|
|
400
|
+
var rows = Mathf.CeilToInt(Frames / (float)Columns);
|
|
401
|
+
for (var i = 0; i < Frames; i++)
|
|
402
|
+
{
|
|
403
|
+
int x = i % Columns, y = rows - 1 - i / Columns; // textures start at the bottom row
|
|
404
|
+
_sprites[i] = Sprite.Create(Sheet, new Rect(x * FrameSize, y * FrameSize, FrameSize, FrameSize), new Vector2(0.5f, 0.5f), FrameSize);
|
|
405
|
+
}
|
|
406
|
+
Show(Frames - 1);
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
public void Play()
|
|
410
|
+
{
|
|
411
|
+
if (_run != null) StopCoroutine(_run);
|
|
412
|
+
_run = StartCoroutine(Run());
|
|
413
|
+
if (Sound)
|
|
414
|
+
{
|
|
415
|
+
if (!_audio) _audio = gameObject.AddComponent<AudioSource>();
|
|
416
|
+
_audio.PlayOneShot(Sound);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
IEnumerator Run()
|
|
421
|
+
{
|
|
422
|
+
for (var i = 0; i < Frames; i++) { Show(i); yield return new WaitForSeconds(DurationsMs[i] / 1000f); }
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
void Show(int i) { if (_image) _image.sprite = _sprites[i]; if (_renderer) _renderer.sprite = _sprites[i]; }
|
|
426
|
+
public void OnPointerEnter(PointerEventData e) { if (PlayOnHover) Play(); }
|
|
427
|
+
public void OnPointerClick(PointerEventData e) => Play();
|
|
428
|
+
void OnMouseDown() => Play();
|
|
429
|
+
}
|
|
430
|
+
`};
|
|
431
|
+
}
|
|
432
|
+
module.exports={qml,avalonia,maui,'compose-multiplatform':composeMp,godot,rust,unity,spritesheet,pngFile};
|
package/tools/raster.js
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// Draws an icon's animation into pixel frames, with no native modules: GIF, APNG, WebM and MP4 export start here.
|
|
2
|
+
// Geometry is flattened once; each frame applies the spring transforms (the same engine the browser uses), then
|
|
3
|
+
// fills are scanline-filled (non-zero rule, 4 sub-rows with exact horizontal coverage) and strokes are drawn as
|
|
4
|
+
// round-capped capsules (distance to each segment), which is exactly what stroke-linecap/linejoin="round" draws.
|
|
5
|
+
const svgpath=require('svgpath');
|
|
6
|
+
const STROKE_W=1.75;
|
|
7
|
+
|
|
8
|
+
function hex(c,fb){if(c==='transparent'||c==='none')return null;const m=/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(c||'');if(!m)return fb===undefined?[0,0,0]:fb;let h=m[1];if(h.length===3)h=h.split('').map(x=>x+x).join('');return[0,2,4].map(i=>parseInt(h.slice(i,i+2),16)/255)}
|
|
9
|
+
|
|
10
|
+
// path data -> polylines in icon units: [{pts:[x,y,...], closed}]
|
|
11
|
+
function flatten(d,rot,tol){
|
|
12
|
+
let p=svgpath(d);if(rot)p=p.rotate(rot[0],rot[1],rot[2]);
|
|
13
|
+
const out=[];let cur=null,x=0,y=0;
|
|
14
|
+
const start=(px,py)=>{cur={pts:[px,py],closed:false};out.push(cur);x=px;y=py};
|
|
15
|
+
const line=(ex,ey)=>{if(!cur)start(x,y);cur.pts.push(ex,ey);x=ex;y=ey};
|
|
16
|
+
const cubic=(x1,y1,x2,y2,ex,ey)=>{if(!cur)start(x,y);
|
|
17
|
+
const len=Math.hypot(x1-x,y1-y)+Math.hypot(x2-x1,y2-y1)+Math.hypot(ex-x2,ey-y2),n=Math.max(2,Math.min(64,Math.ceil(Math.sqrt(len/tol))));
|
|
18
|
+
for(let i=1;i<=n;i++){const t=i/n,u=1-t;cur.pts.push(u*u*u*x+3*u*u*t*x1+3*u*t*t*x2+t*t*t*ex,u*u*u*y+3*u*u*t*y1+3*u*t*t*y2+t*t*t*ey)}x=ex;y=ey};
|
|
19
|
+
p.abs().unarc().unshort().iterate(s=>{const c=s[0];
|
|
20
|
+
if(c==='M')start(s[1],s[2]);
|
|
21
|
+
else if(c==='L')line(s[1],s[2]);else if(c==='H')line(s[1],y);else if(c==='V')line(x,s[1]);
|
|
22
|
+
else if(c==='C')cubic(s[1],s[2],s[3],s[4],s[5],s[6]);
|
|
23
|
+
else if(c==='Q')cubic(x+2/3*(s[1]-x),y+2/3*(s[2]-y),s[3]+2/3*(s[1]-s[3]),s[4]+2/3*(s[2]-s[4]),s[3],s[4]);
|
|
24
|
+
else if(c==='Z'||c==='z'){if(cur){cur.closed=true;x=cur.pts[0];y=cur.pts[1];cur=null}}});
|
|
25
|
+
return out.filter(q=>q.pts.length>=2);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// what each layer kind paints in each style (mirrors paint() in web/runtime.js)
|
|
29
|
+
function paints(style,kind,o){
|
|
30
|
+
const col=o.color,bg=o.bg||[1,1,1],sec=o.secondary||col,so=o.secondaryOpacity===undefined?.18:o.secondaryOpacity;
|
|
31
|
+
const F=(c,a)=>({t:'fill',c,a:a===undefined?1:a}),S=(c,a)=>({t:'stroke',c,a:a===undefined?1:a});
|
|
32
|
+
if(kind==='f')return[F(col)];
|
|
33
|
+
if(kind==='d')return[F(style==='solid'?bg:col)];
|
|
34
|
+
if(kind==='o')return[S(col)];
|
|
35
|
+
if(kind==='i')return[S(style==='solid'?bg:col)];
|
|
36
|
+
if(style==='solid')return[F(col),S(col)];
|
|
37
|
+
if(style==='duotone')return[F(sec,so),S(col)];
|
|
38
|
+
if(style==='glass')return[{t:'fill',c:sec,a:1,glass:true},S(col,.6)];
|
|
39
|
+
return[S(col)];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// icon -> drawing list, bottom first: {layer, t:'fill'|'stroke', c, a, glass, polys}
|
|
43
|
+
function geometry(ic,style,o){
|
|
44
|
+
const list=[];
|
|
45
|
+
for(const l of ic.L){const ps=paints(style,l.k,o);
|
|
46
|
+
for(const p of l.p){const polys=flatten(p.d,p.r,.02);
|
|
47
|
+
for(const pt of ps)list.push({layer:l.i,t:pt.t,c:pt.t==='fill'&&p.f?hex(p.f):pt.c,a:pt.a,glass:pt.glass,polys})}}
|
|
48
|
+
return list;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// spring transforms sampled at fps: [{layerId:{tx,ty,r,s,sx,sy}}], first frame is the pose before the motion starts
|
|
52
|
+
function sample(MG,ic,fps,maxSec){
|
|
53
|
+
if(!ic.A||!ic.A.length)return[{}];
|
|
54
|
+
const st=MG.state(ic);st.start();const start={};
|
|
55
|
+
ic.A.forEach(a=>{if(a.from!==undefined)a.l.split(' ').forEach(id=>{(start[id]=start[id]||{tx:0,ty:0,r:0,s:0,sx:0,sy:0})[a.p]+=a.from})});
|
|
56
|
+
const frames=[start],sub=Math.max(1,Math.ceil(240/fps)),dt=1/(fps*sub);
|
|
57
|
+
for(let f=1;f<=fps*(maxSec||6);f++){let acc=null,done=false;for(let k=0;k<sub;k++){acc=st.step(dt);if(!acc){done=true;break}}if(done||!acc)break;frames.push(acc)}
|
|
58
|
+
frames.push({});return frames;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// a 2D affine matrix [a,b,c,d,e,f] for one layer's transform (same order as transform() in the runtime)
|
|
62
|
+
function matrix(v,oR,oS){
|
|
63
|
+
if(!v)return null;const r=v.r*Math.PI/180,cs=Math.cos(r),sn=Math.sin(r),kx=1+v.s+v.sx,ky=1+v.s+v.sy;
|
|
64
|
+
// p' = T(t) · R(about oR) · S(about oS) · p
|
|
65
|
+
const sx=x=>oS[0]+(x-oS[0])*kx,sy=y=>oS[1]+(y-oS[1])*ky;
|
|
66
|
+
return(x,y)=>{const X=sx(x),Y=sy(y),dx=X-oR[0],dy=Y-oR[1];return[oR[0]+dx*cs-dy*sn+v.tx,oR[1]+dx*sn+dy*cs+v.ty]};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
class Canvas{
|
|
70
|
+
constructor(w,h,bg){this.w=w;this.h=h;this.px=new Float32Array(w*h*4);this.cov=new Float32Array(w*h);this.bg=bg;this.clear()}
|
|
71
|
+
clear(){const p=this.px;if(this.bg){for(let i=0;i<p.length;i+=4){p[i]=this.bg[0];p[i+1]=this.bg[1];p[i+2]=this.bg[2];p[i+3]=1}}else p.fill(0)}
|
|
72
|
+
// composite the coverage buffer in colour c with opacity a (premultiplied "over"), alphaAt for gradients
|
|
73
|
+
paint(c,a,box,alphaAt){const{w,px,cov}=this;
|
|
74
|
+
for(let y=box[1];y<box[3];y++)for(let x=box[0];x<box[2];x++){const i=y*w+x,k=cov[i];if(!k)continue;cov[i]=0;
|
|
75
|
+
const al=Math.min(1,k)*a*(alphaAt?alphaAt(x+.5,y+.5):1),j=i*4,q=1-al;
|
|
76
|
+
px[j]=c[0]*al+px[j]*q;px[j+1]=c[1]*al+px[j+1]*q;px[j+2]=c[2]*al+px[j+2]*q;px[j+3]=al+px[j+3]*q}}
|
|
77
|
+
fill(polys){const{w,h,cov}=this,edges=[];let x0=w,x1=0,y0=h,y1=0;
|
|
78
|
+
for(const q of polys){const p=q.pts,n=p.length/2;for(let i=0;i<n;i++){const j=(i+1)%n;if(j===0&&n<3)break;
|
|
79
|
+
const ax=p[i*2],ay=p[i*2+1],bx=p[j*2],by=p[j*2+1];x0=Math.min(x0,ax);x1=Math.max(x1,ax);y0=Math.min(y0,ay);y1=Math.max(y1,ay);
|
|
80
|
+
if(ay!==by)edges.push(ay<by?[ax,ay,bx,by,1]:[bx,by,ax,ay,-1])}}
|
|
81
|
+
if(!edges.length)return null;
|
|
82
|
+
const box=[Math.max(0,Math.floor(x0)),Math.max(0,Math.floor(y0)),Math.min(w,Math.ceil(x1)+1),Math.min(h,Math.ceil(y1)+1)];
|
|
83
|
+
const SUB=4,xs=[];
|
|
84
|
+
for(let y=box[1];y<box[3];y++)for(let s=0;s<SUB;s++){const sy=y+(s+.5)/SUB;xs.length=0;
|
|
85
|
+
for(const e of edges)if(sy>=e[1]&&sy<e[3])xs.push([e[0]+(sy-e[1])/(e[3]-e[1])*(e[2]-e[0]),e[4]]);
|
|
86
|
+
if(xs.length<2)continue;xs.sort((a,b)=>a[0]-b[0]);let wn=0;
|
|
87
|
+
for(let i=0;i<xs.length-1;i++){wn+=xs[i][1];if(!wn)continue;
|
|
88
|
+
let a=Math.max(0,xs[i][0]),b=Math.min(w,xs[i+1][0]);if(b<=a)continue;
|
|
89
|
+
const ia=Math.floor(a),ib=Math.floor(b),row=y*w;
|
|
90
|
+
if(ia===ib){cov[row+ia]+=(b-a)/SUB;continue}
|
|
91
|
+
cov[row+ia]+=(ia+1-a)/SUB;for(let x=ia+1;x<ib;x++)cov[row+x]+=1/SUB;if(ib<w)cov[row+ib]+=(b-ib)/SUB}}
|
|
92
|
+
return box}
|
|
93
|
+
stroke(polys,width){const{w,h,cov}=this,r=width/2;let box=null;
|
|
94
|
+
// coverage is the max over segments, so joins and overlaps never darken twice (like a real stroke)
|
|
95
|
+
const seg=(ax,ay,bx,by)=>{const x0=Math.max(0,Math.floor(Math.min(ax,bx)-r-1)),x1=Math.min(w,Math.ceil(Math.max(ax,bx)+r+1)),y0=Math.max(0,Math.floor(Math.min(ay,by)-r-1)),y1=Math.min(h,Math.ceil(Math.max(ay,by)+r+1));
|
|
96
|
+
if(x0>=x1||y0>=y1)return;box=box?[Math.min(box[0],x0),Math.min(box[1],y0),Math.max(box[2],x1),Math.max(box[3],y1)]:[x0,y0,x1,y1];
|
|
97
|
+
const dx=bx-ax,dy=by-ay,L=dx*dx+dy*dy;
|
|
98
|
+
for(let y=y0;y<y1;y++){const py=y+.5;for(let x=x0;x<x1;x++){const px=x+.5;let t=L?((px-ax)*dx+(py-ay)*dy)/L:0;t=t<0?0:t>1?1:t;
|
|
99
|
+
const d=Math.hypot(px-ax-t*dx,py-ay-t*dy),k=r-d+.5;if(k<=0)continue;const i=y*w+x,v=k>1?1:k;if(v>cov[i])cov[i]=v}}};
|
|
100
|
+
for(const q of polys){const p=q.pts,n=p.length/2;if(n===1){seg(p[0],p[1],p[0],p[1]);continue}
|
|
101
|
+
for(let i=0;i<n-1;i++)seg(p[i*2],p[i*2+1],p[i*2+2],p[i*2+3]);if(q.closed)seg(p[n*2-2],p[n*2-1],p[0],p[1])}
|
|
102
|
+
return box}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// render(MG, icon, opts) -> {width, height, fps, frames:[Uint8ClampedArray RGBA], delays:[seconds]}
|
|
106
|
+
// opts: size (px, default 256), style, color, secondary, background ('transparent' default), pad (icon units, default 2.5),
|
|
107
|
+
// fps (default 50), hold (seconds shown still after the motion, default .6), lead (still before, default .15), loop (play count, informational)
|
|
108
|
+
function render(MG,ic,o){
|
|
109
|
+
o=o||{};const style=o.style||'outline',size=Math.max(16,Math.min(2048,o.size||256)),pad=o.pad===undefined?2.5:o.pad,fps=o.fps||50;
|
|
110
|
+
const bg=hex(o.background||'transparent',null),col=hex(o.color||'#000000'),sec=o.secondary?hex(o.secondary):null;
|
|
111
|
+
const geo=geometry(ic,style,{color:col,secondary:sec,bg:bg||[1,1,1],secondaryOpacity:o.secondaryOpacity});
|
|
112
|
+
const org=MG.origins(ic),k=size/(24+pad*2),Z=null;
|
|
113
|
+
const samples=sample(MG,ic,fps,o.maxSeconds);
|
|
114
|
+
const cv=new Canvas(size,size,bg),frames=[];
|
|
115
|
+
const toPx=(x,y)=>[(x+pad)*k,(y+pad)*k];
|
|
116
|
+
for(const f of samples){cv.clear();
|
|
117
|
+
for(const g of geo){const v=f[g.layer]||Z,oR=org[g.layer+'|r']||org[g.layer+'|s']||[12,12],oS=org[g.layer+'|s']||org[g.layer+'|r']||[12,12],M=matrix(v,oR,oS);
|
|
118
|
+
const polys=g.polys.map(q=>{const p=q.pts,out=new Array(p.length);for(let i=0;i<p.length;i+=2){const t=M?M(p[i],p[i+1]):[p[i],p[i+1]],r=toPx(t[0],t[1]);out[i]=r[0];out[i+1]=r[1]}return{pts:out,closed:q.closed}});
|
|
119
|
+
const sw=STROKE_W*k*(v?Math.sqrt(Math.abs((1+v.s+v.sx)*(1+v.s+v.sy))):1);
|
|
120
|
+
const box=g.t==='fill'?cv.fill(polys):cv.stroke(polys,sw);if(!box)continue;
|
|
121
|
+
let alphaAt=null;
|
|
122
|
+
// glass: the runtime's gradient runs corner to corner of each shape, from .8 to .12 opacity
|
|
123
|
+
if(g.glass){let a=1/0,b=1/0,c=-1/0,d=-1/0;for(const q of polys)for(let i=0;i<q.pts.length;i+=2){a=Math.min(a,q.pts[i]);c=Math.max(c,q.pts[i]);b=Math.min(b,q.pts[i+1]);d=Math.max(d,q.pts[i+1])}
|
|
124
|
+
alphaAt=(x,y)=>{const u=c>a?(x-a)/(c-a):0,w=d>b?(y-b)/(d-b):0,t=Math.max(0,Math.min(1,(u+w)/2));return .8+(.12-.8)*t}}
|
|
125
|
+
cv.paint(g.c,g.a,box,alphaAt)}
|
|
126
|
+
const out=new Uint8ClampedArray(size*size*4),p=cv.px;
|
|
127
|
+
// un-premultiply for the encoders
|
|
128
|
+
for(let i=0;i<p.length;i+=4){const a=p[i+3];if(a<=0){out[i+3]=0;continue}out[i]=p[i]/a*255+.5;out[i+1]=p[i+1]/a*255+.5;out[i+2]=p[i+2]/a*255+.5;out[i+3]=a*255+.5}
|
|
129
|
+
frames.push(out)}
|
|
130
|
+
// timing: a short still lead-in, the motion, then a hold on the final pose
|
|
131
|
+
const lead=o.lead===undefined?.15:o.lead,hold=o.hold===undefined?.6:o.hold,delays=frames.map(()=>1/fps);
|
|
132
|
+
delays[0]+=lead;
|
|
133
|
+
// the springs settle long after the eye stops seeing movement: frames that look the same as the final pose become the hold
|
|
134
|
+
const last=frames[frames.length-1],near=f=>{for(let i=0;i<f.length;i++)if(Math.abs(f[i]-last[i])>3)return false;return true};
|
|
135
|
+
while(frames.length>2&&near(frames[frames.length-2])){frames.splice(frames.length-2,1);delays.splice(delays.length-2,1)}
|
|
136
|
+
delays[delays.length-1]+=hold;
|
|
137
|
+
return{width:size,height:size,fps,frames,delays,lead};
|
|
138
|
+
}
|
|
139
|
+
module.exports={render,geometry,sample,flatten,hex};
|
package/web/magic-glyphs.all.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/*! Magic Glyphs runtime — renders and animates icons from the canonical icon data. No dependencies. */
|
|
2
|
-
(function(root,factory){if(typeof module==='object'&&module.exports)module.exports=factory();else root.MagicGlyphs=factory()})(typeof self!=='undefined'?self:this,function(){
|
|
2
|
+
(function(root,factory){if(typeof module==='object'&&module.exports)module.exports=factory();else root.MagicGlyphs=root.MagicGlyphs&&root.MagicGlyphs.register?root.MagicGlyphs:factory()})(typeof self!=='undefined'?self:this,function(){
|
|
3
3
|
'use strict';
|
|
4
4
|
var REG={},uid=0;
|
|
5
5
|
var STROKE='stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"';
|
|
6
|
-
function register(data){(data.icons||data).forEach(function(ic){REG[ic.n]=ic});
|
|
6
|
+
function register(data){(data.icons||(Array.isArray(data)?data:[data])).forEach(function(ic){REG[ic.n]=ic}); // a set, a list, or one icon
|
|
7
7
|
// elements already on the page were upgraded before their data arrived: draw them now
|
|
8
8
|
if(typeof document!=='undefined')Array.prototype.forEach.call(document.querySelectorAll('magic-glyph'),function(e){if(e._render)e._render()});
|
|
9
9
|
return api}
|
|
@@ -155,7 +155,8 @@
|
|
|
155
155
|
else if(o.tone>0){var hs=c.createBiquadFilter();hs.type='highshelf';hs.frequency.value=2500;hs.gain.value=o.tone*9;g.connect(hs);node=hs}
|
|
156
156
|
if(c.createStereoPanner&&pan){var p=c.createStereoPanner();p.pan.setValueAtTime(Math.max(-1,Math.min(1,pan)),c.currentTime);node.connect(p);p.connect(dest)}else node.connect(dest);
|
|
157
157
|
cur={C:c,pm:Math.pow(2,o.pitch/12),sp:o.speed,t0:c.currentTime+o.delay/1000};try{fn(g)}finally{cur=null}return true}
|
|
158
|
-
|
|
158
|
+
// sound="off" on an element always wins, so decorative or autoplaying icons stay silent even when sound is on for the page
|
|
159
|
+
function wantsSound(el){if(el&&el.getAttribute&&el.getAttribute('sound')==='off')return false;return soundAll||!!(el&&el.hasAttribute&&el.hasAttribute('sound'))}
|
|
159
160
|
function playFor(ic,el,extra){if(muted||!unlocked||!ensureAudio())return false;var o=settings(ic,el,extra);if(!o.sound||!o.volume)return false;
|
|
160
161
|
var pan=0;if(o.pan&&el&&el.getBoundingClientRect&&typeof innerWidth==='number'&&innerWidth>0){var r=el.getBoundingClientRect();pan=((r.left+r.width/2)/innerWidth*2-1)*.85*o.pan}
|
|
161
162
|
try{return render(ctx,master,o,pan)}catch(e){return false}}
|
package/web/runtime.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/*! Magic Glyphs runtime — renders and animates icons from the canonical icon data. No dependencies. */
|
|
2
|
-
(function(root,factory){if(typeof module==='object'&&module.exports)module.exports=factory();else root.MagicGlyphs=factory()})(typeof self!=='undefined'?self:this,function(){
|
|
2
|
+
(function(root,factory){if(typeof module==='object'&&module.exports)module.exports=factory();else root.MagicGlyphs=root.MagicGlyphs&&root.MagicGlyphs.register?root.MagicGlyphs:factory()})(typeof self!=='undefined'?self:this,function(){
|
|
3
3
|
'use strict';
|
|
4
4
|
var REG={},uid=0;
|
|
5
5
|
var STROKE='stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"';
|
|
6
|
-
function register(data){(data.icons||data).forEach(function(ic){REG[ic.n]=ic});
|
|
6
|
+
function register(data){(data.icons||(Array.isArray(data)?data:[data])).forEach(function(ic){REG[ic.n]=ic}); // a set, a list, or one icon
|
|
7
7
|
// elements already on the page were upgraded before their data arrived: draw them now
|
|
8
8
|
if(typeof document!=='undefined')Array.prototype.forEach.call(document.querySelectorAll('magic-glyph'),function(e){if(e._render)e._render()});
|
|
9
9
|
return api}
|
|
@@ -155,7 +155,8 @@
|
|
|
155
155
|
else if(o.tone>0){var hs=c.createBiquadFilter();hs.type='highshelf';hs.frequency.value=2500;hs.gain.value=o.tone*9;g.connect(hs);node=hs}
|
|
156
156
|
if(c.createStereoPanner&&pan){var p=c.createStereoPanner();p.pan.setValueAtTime(Math.max(-1,Math.min(1,pan)),c.currentTime);node.connect(p);p.connect(dest)}else node.connect(dest);
|
|
157
157
|
cur={C:c,pm:Math.pow(2,o.pitch/12),sp:o.speed,t0:c.currentTime+o.delay/1000};try{fn(g)}finally{cur=null}return true}
|
|
158
|
-
|
|
158
|
+
// sound="off" on an element always wins, so decorative or autoplaying icons stay silent even when sound is on for the page
|
|
159
|
+
function wantsSound(el){if(el&&el.getAttribute&&el.getAttribute('sound')==='off')return false;return soundAll||!!(el&&el.hasAttribute&&el.hasAttribute('sound'))}
|
|
159
160
|
function playFor(ic,el,extra){if(muted||!unlocked||!ensureAudio())return false;var o=settings(ic,el,extra);if(!o.sound||!o.volume)return false;
|
|
160
161
|
var pan=0;if(o.pan&&el&&el.getBoundingClientRect&&typeof innerWidth==='number'&&innerWidth>0){var r=el.getBoundingClientRect();pan=((r.left+r.width/2)/innerWidth*2-1)*.85*o.pan}
|
|
161
162
|
try{return render(ctx,master,o,pan)}catch(e){return false}}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/*! Magic Glyphs runtime — renders and animates icons from the canonical icon data. No dependencies. */
|
|
2
|
-
(function(root,factory){if(typeof module==='object'&&module.exports)module.exports=factory();else root.MagicGlyphs=factory()})(typeof self!=='undefined'?self:this,function(){
|
|
2
|
+
(function(root,factory){if(typeof module==='object'&&module.exports)module.exports=factory();else root.MagicGlyphs=root.MagicGlyphs&&root.MagicGlyphs.register?root.MagicGlyphs:factory()})(typeof self!=='undefined'?self:this,function(){
|
|
3
3
|
'use strict';
|
|
4
4
|
var REG={},uid=0;
|
|
5
5
|
var STROKE='stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"';
|
|
6
|
-
function register(data){(data.icons||data).forEach(function(ic){REG[ic.n]=ic});
|
|
6
|
+
function register(data){(data.icons||(Array.isArray(data)?data:[data])).forEach(function(ic){REG[ic.n]=ic}); // a set, a list, or one icon
|
|
7
7
|
// elements already on the page were upgraded before their data arrived: draw them now
|
|
8
8
|
if(typeof document!=='undefined')Array.prototype.forEach.call(document.querySelectorAll('magic-glyph'),function(e){if(e._render)e._render()});
|
|
9
9
|
return api}
|
|
@@ -155,7 +155,8 @@
|
|
|
155
155
|
else if(o.tone>0){var hs=c.createBiquadFilter();hs.type='highshelf';hs.frequency.value=2500;hs.gain.value=o.tone*9;g.connect(hs);node=hs}
|
|
156
156
|
if(c.createStereoPanner&&pan){var p=c.createStereoPanner();p.pan.setValueAtTime(Math.max(-1,Math.min(1,pan)),c.currentTime);node.connect(p);p.connect(dest)}else node.connect(dest);
|
|
157
157
|
cur={C:c,pm:Math.pow(2,o.pitch/12),sp:o.speed,t0:c.currentTime+o.delay/1000};try{fn(g)}finally{cur=null}return true}
|
|
158
|
-
|
|
158
|
+
// sound="off" on an element always wins, so decorative or autoplaying icons stay silent even when sound is on for the page
|
|
159
|
+
function wantsSound(el){if(el&&el.getAttribute&&el.getAttribute('sound')==='off')return false;return soundAll||!!(el&&el.hasAttribute&&el.hasAttribute('sound'))}
|
|
159
160
|
function playFor(ic,el,extra){if(muted||!unlocked||!ensureAudio())return false;var o=settings(ic,el,extra);if(!o.sound||!o.volume)return false;
|
|
160
161
|
var pan=0;if(o.pan&&el&&el.getBoundingClientRect&&typeof innerWidth==='number'&&innerWidth>0){var r=el.getBoundingClientRect();pan=((r.left+r.width/2)/innerWidth*2-1)*.85*o.pan}
|
|
161
162
|
try{return render(ctx,master,o,pan)}catch(e){return false}}
|