### Add Audio to Movie (Java) Source: https://context7.com/svga/svga-format/llms.txt Example code demonstrating how to add `AudioEntity` objects to a `MovieEntity` builder in Java. This shows how to embed background music and sound effects with their respective timing and frame information. ```java // Example: Adding background music that plays from frame 0 to 100 AudioEntity bgMusic = AudioEntity.newBuilder() .setAudioKey("background.mp3") .setStartFrame(0) .setEndFrame(100) .setStartTime(0) .setTotalTime(5000) // 5 seconds .build(); // Example: Sound effect that plays at frame 30 AudioEntity soundEffect = AudioEntity.newBuilder() .setAudioKey("explosion.mp3") .setStartFrame(30) .setEndFrame(35) .setStartTime(0) .setTotalTime(250) // 250ms .build(); MovieEntity.Builder movie = MovieEntity.newBuilder(); movie.addAudios(bgMusic); movie.addAudios(soundEffect); ``` -------------------------------- ### Define Audio Synchronization (Protobuf) Source: https://context7.com/svga/svga-format/llms.txt Defines `AudioEntity` for synchronizing audio files with animation frames. It specifies the audio file key, start and end frames for playback, and timing offsets in milliseconds. This is essential for audio-visual synchronization. ```protobuf message AudioEntity { string audioKey = 1; // Audio filename (e.g., "sound.mp3") int32 startFrame = 2; // Animation frame to start playback int32 endFrame = 3; // Animation frame to stop playback int32 startTime = 4; // Audio offset in milliseconds int32 totalTime = 5; // Total audio duration in milliseconds } ``` -------------------------------- ### Create Rectangle Shape (Java) Source: https://context7.com/svga/svga-format/llms.txt Example code demonstrating how to construct a `ShapeEntity` for a rectangle using Java. It specifies the rectangle's dimensions, corner radius, fill color, stroke color, and line cap style. ```java // Example: Drawing a red rectangle with blue stroke ShapeEntity rectangle = ShapeEntity.newBuilder() .setType(ShapeEntity.ShapeType.RECT) .setRect(ShapeEntity.RectArgs.newBuilder() .setX(10.0f).setY(10.0f) .setWidth(80.0f).setHeight(60.0f) .setCornerRadius(5.0f)) .setStyles(ShapeEntity.ShapeStyle.newBuilder() .setFill(ShapeEntity.ShapeStyle.RGBAColor.newBuilder() .setR(1.0f).setG(0.0f).setB(0.0f).setA(1.0f)) .setStroke(ShapeEntity.ShapeStyle.RGBAColor.newBuilder() .setR(0.0f).setG(0.0f).setB(1.0f).setA(1.0f)) .setStrokeWidth(2.0f) .setLineCap(ShapeEntity.ShapeStyle.LineCap.LineCap_ROUND)) .setTransform(Transform.newBuilder() // Assuming Transform is defined elsewhere .setA(1.0f).setD(1.0f) .setTx(0.0f).setTy(0.0f)) .build(); ``` -------------------------------- ### Define MovieEntity Structure with Protocol Buffers Source: https://context7.com/svga/svga-format/llms.txt Defines the root MovieEntity message for SVGA animations using Protocol Buffers. It includes version, canvas parameters, images, sprites, and audios. This structure is serialized into the binary .svga file. Example usage in Java demonstrates building and serializing a MovieEntity. ```protobuf syntax = "proto3"; package com.opensource.svga; message MovieEntity { string version = 1; // SVGA format version (e.g., "2.0.0") MovieParams params = 2; // Canvas size, FPS, frame count map images = 3; // Image key -> PNG binary data or filename repeated SpriteEntity sprites = 4; // Sprite/layer definitions repeated AudioEntity audios = 5; // Audio tracks with timing info } message MovieParams { float viewBoxWidth = 1; // Canvas width in points float viewBoxHeight = 2; // Canvas height in points int32 fps = 3; // Frame rate: [1,2,3,5,6,10,12,15,20,30,60] int32 frames = 4; // Total frame count } ``` ```java // Example usage in Java MovieEntity.Builder builder = MovieEntity.newBuilder(); builder.setVersion("2.0.0"); MovieParams params = MovieParams.newBuilder() .setViewBoxWidth(300.0f) .setViewBoxHeight(300.0f) .setFps(20) .setFrames(144) .build(); builder.setParams(params); // Add image data byte[] imageData = Files.readAllBytes(Paths.get("sprite.png")); builder.putImages("sprite_key", ByteString.copyFrom(imageData)); MovieEntity movie = builder.build(); byte[] serialized = movie.toByteArray(); // Serialize to binary ``` -------------------------------- ### Create SVG Path Shape (Java) Source: https://context7.com/svga/svga-format/llms.txt Example code demonstrating how to construct a `ShapeEntity` for an SVG path using Java. This allows for complex vector shapes defined by SVG path data strings, with specified fill color. ```java // Example: Drawing an SVG path (triangle) ShapeEntity triangle = ShapeEntity.newBuilder() .setType(ShapeEntity.ShapeType.SHAPE) .setShape(ShapeEntity.ShapeArgs.newBuilder() .setD("M 50 0 L 100 100 L 0 100 Z")) .setStyles(ShapeEntity.ShapeStyle.newBuilder() .setFill(ShapeEntity.ShapeStyle.RGBAColor.newBuilder() .setR(0.0f).setG(1.0f).setB(0.0f).setA(0.8f))) .build(); ``` -------------------------------- ### Compile Protocol Buffer Definitions for SVGA Source: https://context7.com/svga/svga-format/llms.txt Demonstrates compiling the `svga.proto` definition file into various programming language bindings using `protoc`. This enables cross-platform compatibility for SVGA animations. It also includes generating a JSON schema for documentation. ```bash #!/bin/bash # Generate Objective-C bindings protoc --objc_out="./" svga.proto # Generate Java bindings protoc --java_out="./" svga.proto # Generate JavaScript bindings (CommonJS) protoc --js_out=import_style=commonjs,binary:. svga.proto # Generate JSON schema for documentation pbjs -t json svga.proto > svga.json # Generate Java bindings using Wire library (alternative) java -jar wire-compiler-2.2.0-jar-with-dependencies.jar \ --proto_path=./ \ --java_out=wire220 \ svga.proto # Usage example - compile all bindings chmod +x svga.pb.sh ./svga.pb.sh # For Python bindings (not in default script) protoc --python_out=./ svga.proto # For Go bindings protoc --go_out=./ svga.proto # For C# bindings protoc --csharp_out=./ svga.proto ``` -------------------------------- ### Create and Serialize SVGA Animation in Java Source: https://context7.com/svga/svga-format/llms.txt This Java code demonstrates the complete process of creating an SVGA animation programmatically. It includes defining movie parameters, loading image data, constructing sprite entities with frame-by-frame transformations, and finally serializing and compressing the animation into an SVGA file. Dependencies include the SVGA protobuf definitions and standard Java I/O libraries. ```java import com.opensource.svgaplayer.proto.Svga.*; import com.google.protobuf.ByteString; import java.io.*; import java.util.zip.Deflater; import java.nio.file.Files; import java.nio.file.Paths; public class SVGACreator { public static void createAnimation() throws IOException { // Create movie parameters MovieParams params = MovieParams.newBuilder() .setViewBoxWidth(400.0f) .setViewBoxHeight(400.0f) .setFps(30) .setFrames(90) // 3 seconds at 30fps .build(); // Load image data byte[] spriteImage = Files.readAllBytes(Paths.get("assets/sprite.png")); // Create sprite with animation SpriteEntity.Builder sprite = SpriteEntity.newBuilder() .setImageKey("sprite.png"); // Generate 90 frames of rotation animation for (int i = 0; i < 90; i++) { double angle = (i / 90.0) * 2 * Math.PI; float cosA = (float) Math.cos(angle); float sinA = (float) Math.sin(angle); // Create rotation transform matrix Transform transform = Transform.newBuilder() .setA(cosA) // cos(θ) .setB(sinA) // sin(θ) .setC(-sinA) // -sin(θ) .setD(cosA) // cos(θ) .setTx(200.0f) // Center X .setTy(200.0f) // Center Y .build(); FrameEntity frame = FrameEntity.newBuilder() .setAlpha(1.0f) .setLayout(Layout.newBuilder() .setX(0).setY(0) .setWidth(100).setHeight(100)) .setTransform(transform) .build(); sprite.addFrames(frame); } // Build complete movie entity MovieEntity movie = MovieEntity.newBuilder() .setVersion("2.0.0") .setParams(params) .putImages("sprite.png", ByteString.copyFrom(spriteImage)) .addSprites(sprite) .build(); // Serialize and compress byte[] serialized = movie.toByteArray(); byte[] compressed = compress(serialized); // Write to file Files.write(Paths.get("output.svga"), compressed); System.out.println("SVGA file created: output.svga"); } private static byte[] compress(byte[] data) throws IOException { Deflater deflater = new Deflater(); deflater.setInput(data); deflater.finish(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length); byte[] buffer = new byte[1024]; while (!deflater.finished()) { int count = deflater.deflate(buffer); outputStream.write(buffer, 0, count); } outputStream.close(); return outputStream.toByteArray(); } public static void main(String[] args) { try { createAnimation(); } catch (IOException e) { e.printStackTrace(); } } } ``` -------------------------------- ### Load and Parse SVGA File in JavaScript Source: https://context7.com/svga/svga-format/llms.txt This snippet shows how to load a compressed SVGA file, decompress it using zlib, and deserialize the Protocol Buffer data into a MovieEntity object. It then accesses and logs animation parameters, sprite details, and image data. Dependencies include 'fs', 'zlib', and the generated SVGA proto file. ```javascript const svga = require('./proto/js/svga_pb.js'); const fs = require('fs'); const zlib = require('zlib'); // Load and decompress SVGA file async function loadSVGA(filePath) { try { // Read compressed binary file const compressedData = fs.readFileSync(filePath); // Decompress using zlib const decompressed = zlib.inflateSync(compressedData); // Deserialize protocol buffer const movieEntity = svga.com.opensource.svga.MovieEntity.deserializeBinary(decompressed); // Access animation properties const params = movieEntity.getParams(); console.log(`Canvas: ${params.getViewboxwidth()}x${params.getViewboxheight()}`); console.log(`FPS: ${params.getFps()}, Frames: ${params.getFrames()}`); // Iterate through sprites const sprites = movieEntity.getSpritesList(); sprites.forEach((sprite, index) => { console.log(`Sprite ${index}: ${sprite.getImagekey()}`); console.log(` Frame count: ${sprite.getFramesList().length}`); // Access first frame properties const frame = sprite.getFramesList()[0]; if (frame) { console.log(` Alpha: ${frame.getAlpha()}`); const transform = frame.getTransform(); console.log(` Position: (${transform.getTx()}, ${transform.getTy()})`); } }); // Extract image data const images = movieEntity.getImagesMap(); images.forEach((imageData, key) => { console.log(`Image: ${key}, Size: ${imageData.length} bytes`); // imageData is Uint8Array of PNG binary fs.writeFileSync(`extracted_${key}`, Buffer.from(imageData)); }); return movieEntity; } catch (error) { console.error('Failed to load SVGA:', error); throw error; } } // Usage loadSVGA('animation.svga').then(movie => { console.log('Successfully loaded SVGA animation'); }); ``` -------------------------------- ### Create Bouncing Ball Animation in Java Source: https://context7.com/svga/svga-format/llms.txt Demonstrates the creation of a complete SVGA animation with physics-based movement. This code generates a bouncing ball using vector graphics and simulates its motion over a specified number of frames. It utilizes the SVGA protobuf definitions for constructing the animation data. ```java import com.opensource.svgaplayer.proto.Svga.*; import com.google.protobuf.ByteString; import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; public class BouncingBallAnimation { public static MovieEntity createBouncingBall() throws IOException { int totalFrames = 60; int fps = 30; float canvasWidth = 400.0f; float canvasHeight = 400.0f; float ballRadius = 20.0f; // Animation parameters MovieParams params = MovieParams.newBuilder() .setViewBoxWidth(canvasWidth) .setViewBoxHeight(canvasHeight) .setFps(fps) .setFrames(totalFrames) .build(); // Create vector ball sprite SpriteEntity.Builder ballSprite = SpriteEntity.newBuilder() .setImageKey("ball.vector"); // Physics simulation parameters float gravity = 0.5f; float velocity = 0.0f; float posY = 50.0f; float posX = canvasWidth / 2; float bounce = 0.8f; // Generate frames with physics for (int frame = 0; frame < totalFrames; frame++) { // Apply gravity velocity += gravity; posY += velocity; // Bounce off ground if (posY > canvasHeight - ballRadius) { posY = canvasHeight - ballRadius; velocity *= -bounce; } // Create circle shape ShapeEntity circle = ShapeEntity.newBuilder() .setType(ShapeEntity.ShapeType.ELLIPSE) .setEllipse(ShapeEntity.EllipseArgs.newBuilder() .setX(0.0f) .setY(0.0f) .setRadiusX(ballRadius) .setRadiusY(ballRadius)) .setStyles(ShapeEntity.ShapeStyle.newBuilder() .setFill(ShapeEntity.ShapeStyle.RGBAColor.newBuilder() .setR(1.0f).setG(0.3f).setB(0.0f).setA(1.0f)) .setStroke(ShapeEntity.ShapeStyle.RGBAColor.newBuilder() .setR(0.5f).setG(0.15f).setB(0.0f).setA(1.0f)) .setStrokeWidth(2.0f)) .setTransform(Transform.newBuilder() .setA(1.0f).setD(1.0f) .setTx(0.0f).setTy(0.0f)) .build(); // Create frame FrameEntity frameEntity = FrameEntity.newBuilder() .setAlpha(1.0f) .setLayout(Layout.newBuilder() .setX(0).setY(0) .setWidth(ballRadius * 2) .setHeight(ballRadius * 2)) .setTransform(Transform.newBuilder() .setA(1.0f).setD(1.0f) .setTx(posX).setTy(posY)) .addShapes(circle) .build(); ballSprite.addFrames(frameEntity); } // Build and return movie return MovieEntity.newBuilder() .setVersion("2.0.0") .setParams(params) .addSprites(ballSprite) .build(); } public static void saveToFile(MovieEntity movie, String filename) throws IOException { byte[] data = movie.toByteArray(); // Compress with zlib java.util.zip.Deflater deflater = new java.util.zip.Deflater(); deflater.setInput(data); deflater.finish(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while (!deflater.finished()) { int count = deflater.deflate(buffer); baos.write(buffer, 0, count); } Files.write(Paths.get(filename), baos.toByteArray()); System.out.println("Saved: " + filename); } public static void main(String[] args) throws IOException { MovieEntity animation = createBouncingBall(); saveToFile(animation, "bouncing_ball.svga"); } } ``` -------------------------------- ### Define Sprite and Frame Entities for Animation Source: https://context7.com/svga/svga-format/llms.txt Defines the structure for `SpriteEntity` and `FrameEntity` within the SVGA format using Protocol Buffers. `SpriteEntity` references an image and contains per-frame definitions, while `FrameEntity` specifies properties like alpha, layout, transform, clipping paths, and shapes for each frame. This enables detailed animation control. ```protobuf message SpriteEntity { string imageKey = 1; // Reference to images map key repeated FrameEntity frames = 2; // Per-frame property definitions string matteKey = 3; // Matte layer key for masking } message FrameEntity { float alpha = 1; // Opacity [0.0 - 1.0] Layout layout = 2; // Bounding box constraint Transform transform = 3; // 2D affine transformation matrix string clipPath = 4; // SVG path for clipping mask repeated ShapeEntity shapes = 5; // Vector shapes for .vector sprites } message Layout { float x = 1; float y = 2; float width = 3; float height = 4; } message Transform { float a = 1; // Scale X & skew float b = 2; // Skew float c = 3; // Skew float d = 4; // Scale Y & skew float tx = 5; // Translate X float ty = 6; // Translate Y } ``` ```protobuf // Example: Creating an animated sprite SpriteEntity.Builder sprite = SpriteEntity.newBuilder();sprite.setImageKey("character.png"); // Frame 0: Initial position FrameEntity frame0 = FrameEntity.newBuilder() .setAlpha(1.0f) .setLayout(Layout.newBuilder() .setX(0).setY(0) .setWidth(100).setHeight(100)) .setTransform(Transform.newBuilder() .setA(1.0f).setD(1.0f) // Identity scale .setTx(50.0f).setTy(50.0f)) // Position .build(); // Frame 1: Moved and scaled FrameEntity frame1 = FrameEntity.newBuilder() .setAlpha(0.8f) .setLayout(Layout.newBuilder() .setX(0).setY(0) .setWidth(100).setHeight(100)) .setTransform(Transform.newBuilder() .setA(1.5f).setD(1.5f) // 150% scale .setTx(100.0f).setTy(50.0f)) // New position .build(); sprite.addFrames(frame0).addFrames(frame1); ``` -------------------------------- ### Define Vector Shapes (Protobuf) Source: https://context7.com/svga/svga-format/llms.txt Defines `ShapeEntity` for rendering vector graphics like SVG paths, rectangles with rounded corners, and ellipses. It includes detailed styling options for fills, strokes, and line patterns. This definition is crucial for vector-based animation playback. ```protobuf message ShapeEntity { enum ShapeType { SHAPE = 0; // SVG path RECT = 1; // Rectangle ELLIPSE = 2; // Ellipse/circle KEEP = 3; // Reuse previous frame's shape } message ShapeArgs { string d = 1; // SVG path data (e.g., "M 0 0 L 100 100") } message RectArgs { float x = 1; float y = 2; float width = 3; float height = 4; float cornerRadius = 5; // Rounded corners } message EllipseArgs { float x = 1; // Center X float y = 2; // Center Y float radiusX = 3; // Horizontal radius float radiusY = 4; // Vertical radius } message ShapeStyle { message RGBAColor { float r = 1; // [0.0 - 1.0] float g = 2; float b = 3; float a = 4; // Alpha } enum LineCap { LineCap_BUTT = 0; LineCap_ROUND = 1; LineCap_SQUARE = 2; } enum LineJoin { LineJoin_MITER = 0; LineJoin_ROUND = 1; LineJoin_BEVEL = 2; } RGBAColor fill = 1; // Fill color RGBAColor stroke = 2; // Stroke color float strokeWidth = 3; // Stroke width in points LineCap lineCap = 4; LineJoin lineJoin = 5; float miterLimit = 6; float lineDashI = 7; // Dash length float lineDashII = 8; // Gap length float lineDashIII = 9; // Dash offset } ShapeType type = 1; oneof args { ShapeArgs shape = 2; RectArgs rect = 3; EllipseArgs ellipse = 4; } ShapeStyle styles = 10; Transform transform = 11; } ``` -------------------------------- ### SVGA 1.x Legacy JSON Format Specification Source: https://context7.com/svga/svga-format/llms.txt Defines the structure of a legacy SVGA animation file using JSON. This format is deprecated but supported for backward compatibility. It specifies movie properties, image assets, and sprite definitions, including layout and transformations. ```json { "ver": "1.1.0", "movie": { "viewBox": { "width": 300.0, "height": 300.0 }, "fps": 20, "frames": 144 }, "images": { "character_idle": "character_idle.png", "background": "bg.png" }, "sprites": [ { "imageKey": "background", "frames": [ { "alpha": 1.0, "layout": { "x": 0, "y": 0, "width": 300, "height": 300 }, "transform": { "a": 1.0, "b": 0.0, "c": 0.0, "d": 1.0, "tx": 0.0, "ty": 0.0 } } ] }, { "imageKey": "character_idle.vector", "frames": [ { "alpha": 1.0, "layout": {"x": 0, "y": 0, "width": 100, "height": 100}, "transform": {"a": 1.0, "b": 0.0, "c": 0.0, "d": 1.0, "tx": 100.0, "ty": 150.0}, "clipPath": "M 0 0 L 100 0 L 100 100 L 0 100 Z", "shapes": [ { "type": "rect", "args": { "x": 10.0, "y": 10.0, "width": 80.0, "height": 80.0, "cornerRadius": 5.0 }, "styles": { "fill": [1.0, 0.5, 0.0, 1.0], "stroke": [0.0, 0.0, 0.0, 1.0], "strokeWidth": 2.0, "lineCap": "round", "lineJoin": "miter", "miterLimit": 4.0, "lineDash": [0.0, 0.0, 0.0] }, "transform": {"a": 1.0, "b": 0.0, "c": 0.0, "d": 1.0, "tx": 0.0, "ty": 0.0} } ] } ] } ] } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.