mirror of
https://github.com/3b1b/manim.git
synced 2025-04-13 09:47:07 +00:00
Added Docs & Agent frameworks
This commit is contained in:
parent
f4737828f6
commit
3bb8ce9433
16 changed files with 2117 additions and 0 deletions
82
animation-agent/README.md
Normal file
82
animation-agent/README.md
Normal file
|
@ -0,0 +1,82 @@
|
|||
# Animation Agent
|
||||
|
||||
An AI-powered system for creating mathematical animations using the Manim library.
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
animation-agent/
|
||||
├── knowledge_base.py # Contains animation capabilities and patterns
|
||||
├── agents.py # Core agent implementations
|
||||
├── main.py # Main orchestration logic
|
||||
└── requirements.txt # Project dependencies
|
||||
```
|
||||
|
||||
## Components
|
||||
|
||||
1. **Knowledge Base**
|
||||
- Animation capabilities
|
||||
- Mathematical visualization patterns
|
||||
- Object properties and uses
|
||||
- Common narrative structures
|
||||
|
||||
2. **Agents**
|
||||
- ContentPlanningAgent: Plans the educational content
|
||||
- NarrativeDesignAgent: Designs the story flow
|
||||
- VisualPlanningAgent: Plans the visual elements
|
||||
|
||||
3. **Main System**
|
||||
- Orchestrates agent interactions
|
||||
- Manages the animation creation process
|
||||
- Provides the main interface
|
||||
|
||||
## Setup
|
||||
|
||||
1. Create a virtual environment:
|
||||
```bash
|
||||
python -m venv venv
|
||||
source venv/bin/activate # On Windows: venv\Scripts\activate
|
||||
```
|
||||
|
||||
2. Install dependencies:
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
3. Set up environment variables:
|
||||
```bash
|
||||
# Create .env file with:
|
||||
OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
Run the main script:
|
||||
```bash
|
||||
python main.py
|
||||
```
|
||||
|
||||
Example code:
|
||||
```python
|
||||
from main import AnimationSystem
|
||||
|
||||
system = AnimationSystem()
|
||||
animation_plan = system.create_animation(
|
||||
concept="derivative_introduction",
|
||||
audience_level="high_school"
|
||||
)
|
||||
```
|
||||
|
||||
## Development
|
||||
|
||||
- The system uses a modular design for easy extension
|
||||
- Each agent can be enhanced independently
|
||||
- Knowledge base can be expanded with new patterns
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
1. Add more mathematical patterns
|
||||
2. Implement feedback loops
|
||||
3. Add quality checking
|
||||
4. Integrate voice-over generation
|
||||
5. Add more animation templates
|
173
animation-agent/agents.py
Normal file
173
animation-agent/agents.py
Normal file
|
@ -0,0 +1,173 @@
|
|||
"""
|
||||
Core agents for the animation system.
|
||||
Each agent uses LLMs for intelligent decision making.
|
||||
"""
|
||||
|
||||
from typing import List, Dict, Any, Optional
|
||||
from pydantic import BaseModel, Field
|
||||
from .llm_providers import BaseLLMProvider, create_llm_provider
|
||||
|
||||
class ContentPlan(BaseModel):
|
||||
concept: str = Field(description="The mathematical concept being explained")
|
||||
audience_level: str = Field(description="Target audience level")
|
||||
prerequisites: List[str] = Field(description="List of prerequisite concepts")
|
||||
learning_objectives: List[str] = Field(description="List of learning objectives")
|
||||
|
||||
class NarrativePlan(BaseModel):
|
||||
story_flow: List[str] = Field(description="Sequence of narrative elements")
|
||||
examples: List[str] = Field(description="List of examples to use")
|
||||
timing: Dict[str, float] = Field(description="Timing for each story element")
|
||||
|
||||
class VisualPlan(BaseModel):
|
||||
scenes: List[Dict[str, Any]] = Field(description="List of scenes with their configurations")
|
||||
transitions: List[str] = Field(description="List of transitions between scenes")
|
||||
objects: List[Dict[str, Any]] = Field(description="List of required objects")
|
||||
timing: Dict[str, float] = Field(description="Timing for visual elements")
|
||||
|
||||
class BaseAgent:
|
||||
def __init__(
|
||||
self,
|
||||
knowledge_base,
|
||||
llm_provider: str = "openai",
|
||||
model_name: Optional[str] = None,
|
||||
temperature: float = 0.7,
|
||||
device: str = "auto"
|
||||
):
|
||||
self.knowledge_base = knowledge_base
|
||||
self.llm = create_llm_provider(
|
||||
provider=llm_provider,
|
||||
model_name=model_name,
|
||||
temperature=temperature,
|
||||
device=device
|
||||
)
|
||||
|
||||
class ContentPlanningAgent(BaseAgent):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.system_prompt = """You are an expert mathematics educator. Your task is to create a
|
||||
content plan for teaching a mathematical concept. Consider the audience level
|
||||
and create appropriate learning objectives.
|
||||
|
||||
Available Manim capabilities:
|
||||
{capabilities}
|
||||
"""
|
||||
|
||||
self.human_prompt = """Create a content plan for teaching {concept} to {audience_level} students.
|
||||
The plan should include:
|
||||
1. Prerequisites needed for understanding the concept
|
||||
2. Clear learning objectives
|
||||
3. Key points to cover
|
||||
|
||||
Format your response as a JSON object with these fields:
|
||||
{
|
||||
"concept": "the concept name",
|
||||
"audience_level": "the target audience level",
|
||||
"prerequisites": ["list", "of", "prerequisites"],
|
||||
"learning_objectives": ["list", "of", "objectives"]
|
||||
}
|
||||
"""
|
||||
|
||||
def plan(self, concept: str, audience_level: str) -> ContentPlan:
|
||||
"""Create a content plan using LLM."""
|
||||
capabilities = self.knowledge_base.get_all_capabilities()
|
||||
|
||||
# Construct full prompt
|
||||
prompt = self.system_prompt.format(capabilities=capabilities) + "\n" + \
|
||||
self.human_prompt.format(concept=concept, audience_level=audience_level)
|
||||
|
||||
# Get LLM response
|
||||
response = self.llm.generate(prompt)
|
||||
|
||||
# Parse response into ContentPlan
|
||||
# Note: You might need to add error handling here
|
||||
import json
|
||||
plan_dict = json.loads(response)
|
||||
return ContentPlan(**plan_dict)
|
||||
|
||||
class NarrativeDesignAgent(BaseAgent):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.system_prompt = """You are an expert in creating educational narratives. Your task is
|
||||
to design a narrative flow for teaching a mathematical concept. Consider the
|
||||
content plan and available visualization capabilities.
|
||||
|
||||
Available Manim capabilities:
|
||||
{capabilities}
|
||||
"""
|
||||
|
||||
self.human_prompt = """Design a narrative for the following content plan:
|
||||
{content_plan}
|
||||
|
||||
Create a narrative that:
|
||||
1. Follows a logical progression
|
||||
2. Includes relevant examples
|
||||
3. Has appropriate timing for each section
|
||||
|
||||
Format your response as a JSON object with these fields:
|
||||
{
|
||||
"story_flow": ["list", "of", "narrative", "elements"],
|
||||
"examples": ["list", "of", "examples"],
|
||||
"timing": {"element": seconds_duration}
|
||||
}
|
||||
"""
|
||||
|
||||
def design(self, content_plan: ContentPlan) -> NarrativePlan:
|
||||
"""Create a narrative plan using LLM."""
|
||||
capabilities = self.knowledge_base.get_all_capabilities()
|
||||
|
||||
# Construct full prompt
|
||||
prompt = self.system_prompt.format(capabilities=capabilities) + "\n" + \
|
||||
self.human_prompt.format(content_plan=content_plan.model_dump())
|
||||
|
||||
# Get LLM response
|
||||
response = self.llm.generate(prompt)
|
||||
|
||||
# Parse response into NarrativePlan
|
||||
import json
|
||||
plan_dict = json.loads(response)
|
||||
return NarrativePlan(**plan_dict)
|
||||
|
||||
class VisualPlanningAgent(BaseAgent):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.system_prompt = """You are an expert in creating mathematical visualizations. Your task
|
||||
is to plan the visual elements and animations for teaching a mathematical concept.
|
||||
Consider the narrative plan and available Manim capabilities.
|
||||
|
||||
Available Manim capabilities:
|
||||
{capabilities}
|
||||
"""
|
||||
|
||||
self.human_prompt = """Create a visual plan for the following narrative:
|
||||
{narrative_plan}
|
||||
|
||||
Plan the visuals including:
|
||||
1. Required scenes and their configurations
|
||||
2. Transitions between scenes
|
||||
3. Objects needed for each scene
|
||||
4. Timing for visual elements
|
||||
|
||||
Format your response as a JSON object with these fields:
|
||||
{
|
||||
"scenes": [{"name": "scene_name", "config": {}}],
|
||||
"transitions": ["list", "of", "transitions"],
|
||||
"objects": [{"type": "object_type", "properties": {}}],
|
||||
"timing": {"element": seconds_duration}
|
||||
}
|
||||
"""
|
||||
|
||||
def plan(self, narrative_plan: NarrativePlan) -> VisualPlan:
|
||||
"""Create a visual plan using LLM."""
|
||||
capabilities = self.knowledge_base.get_all_capabilities()
|
||||
|
||||
# Construct full prompt
|
||||
prompt = self.system_prompt.format(capabilities=capabilities) + "\n" + \
|
||||
self.human_prompt.format(narrative_plan=narrative_plan.model_dump())
|
||||
|
||||
# Get LLM response
|
||||
response = self.llm.generate(prompt)
|
||||
|
||||
# Parse response into VisualPlan
|
||||
import json
|
||||
plan_dict = json.loads(response)
|
||||
return VisualPlan(**plan_dict)
|
126
animation-agent/code_generator.py
Normal file
126
animation-agent/code_generator.py
Normal file
|
@ -0,0 +1,126 @@
|
|||
"""
|
||||
Code generator for converting visual plans into Manim animations using LLM.
|
||||
"""
|
||||
|
||||
from typing import Dict, Any, List, Optional
|
||||
from dataclasses import dataclass
|
||||
from .llm_providers import create_llm_provider
|
||||
|
||||
@dataclass
|
||||
class ManimCode:
|
||||
imports: List[str]
|
||||
scene_class: str
|
||||
construct_method: str
|
||||
|
||||
class ManimCodeGenerator:
|
||||
def __init__(
|
||||
self,
|
||||
llm_provider: str = "huggingface", # Default to HuggingFace for code generation
|
||||
model_name: Optional[str] = "bigcode/starcoder", # Default to a code-specialized model
|
||||
temperature: float = 0.3, # Lower temperature for more precise code generation
|
||||
device: str = "auto"
|
||||
):
|
||||
self.llm = create_llm_provider(
|
||||
provider=llm_provider,
|
||||
model_name=model_name,
|
||||
temperature=temperature,
|
||||
device=device
|
||||
)
|
||||
|
||||
self.system_prompt = """You are an expert in creating animations using the Manim library.
|
||||
Your task is to generate Manim code based on a visual plan. The code should be
|
||||
well-structured and follow Manim best practices.
|
||||
|
||||
Available Manim capabilities:
|
||||
{capabilities}
|
||||
"""
|
||||
|
||||
self.human_prompt = """Generate Manim code for the following visual plan:
|
||||
{visual_plan}
|
||||
|
||||
The code should create a scene named {scene_name} that implements the
|
||||
specified animations and transitions. Use the exact object types and
|
||||
properties from the visual plan.
|
||||
|
||||
Return the code in three parts, each prefixed with PART n: where n is 1, 2, or 3:
|
||||
|
||||
PART 1: Import statements
|
||||
- Include all necessary imports from manim
|
||||
- Add any other required imports (numpy, etc.)
|
||||
|
||||
PART 2: Scene class definition
|
||||
- Define the scene class that inherits from Scene
|
||||
- Add any necessary class-level attributes
|
||||
|
||||
PART 3: Construct method implementation
|
||||
- Implement the construct method
|
||||
- Create and configure all objects
|
||||
- Add all animations in the correct sequence
|
||||
- Handle timing and transitions
|
||||
"""
|
||||
|
||||
def generate_code(self, visual_plan: Dict[str, Any], concept_name: str) -> ManimCode:
|
||||
"""Generate Manim code using LLM."""
|
||||
# Format scene name
|
||||
scene_name = f"{concept_name.title().replace('_', '')}Scene"
|
||||
|
||||
# Construct full prompt
|
||||
prompt = self.system_prompt.format(
|
||||
capabilities=visual_plan.get("capabilities", {})
|
||||
) + "\n" + self.human_prompt.format(
|
||||
visual_plan=visual_plan,
|
||||
scene_name=scene_name
|
||||
)
|
||||
|
||||
# Get LLM response
|
||||
response = self.llm.generate(prompt)
|
||||
|
||||
# Parse response into code parts
|
||||
parts = self._parse_code_parts(response)
|
||||
|
||||
return ManimCode(
|
||||
imports=self._clean_imports(parts.get("PART 1", "")),
|
||||
scene_class=parts.get("PART 2", ""),
|
||||
construct_method=parts.get("PART 3", "")
|
||||
)
|
||||
|
||||
def _parse_code_parts(self, response: str) -> Dict[str, str]:
|
||||
"""Parse the LLM response into code parts."""
|
||||
parts = {}
|
||||
current_part = None
|
||||
current_content = []
|
||||
|
||||
for line in response.split("\n"):
|
||||
if line.startswith("PART"):
|
||||
if current_part:
|
||||
parts[current_part] = "\n".join(current_content).strip()
|
||||
current_part = line.split(":")[0]
|
||||
current_content = []
|
||||
elif current_part:
|
||||
current_content.append(line)
|
||||
|
||||
if current_part:
|
||||
parts[current_part] = "\n".join(current_content).strip()
|
||||
|
||||
return parts
|
||||
|
||||
def _clean_imports(self, imports_str: str) -> List[str]:
|
||||
"""Clean and validate import statements."""
|
||||
imports = []
|
||||
for line in imports_str.split("\n"):
|
||||
line = line.strip()
|
||||
if line and not line.startswith("#"):
|
||||
imports.append(line)
|
||||
return imports
|
||||
|
||||
def save_to_file(self, code: ManimCode, filename: str):
|
||||
"""Save generated code to a file."""
|
||||
with open(filename, 'w') as f:
|
||||
# Write imports
|
||||
for imp in code.imports:
|
||||
f.write(f"{imp}\n")
|
||||
f.write("\n\n")
|
||||
|
||||
# Write scene class
|
||||
f.write(f"{code.scene_class}\n")
|
||||
f.write(f"{code.construct_method}\n")
|
84
animation-agent/knowledge_base.py
Normal file
84
animation-agent/knowledge_base.py
Normal file
|
@ -0,0 +1,84 @@
|
|||
"""
|
||||
Knowledge base for the animation system.
|
||||
Contains information about available animations and objects.
|
||||
"""
|
||||
|
||||
from typing import List, Dict, Any, Optional
|
||||
|
||||
class ManimKnowledgeBase:
|
||||
def __init__(self):
|
||||
self.animation_capabilities = {
|
||||
"transitions": {
|
||||
"FadeIn": {
|
||||
"description": "Gradually makes object visible",
|
||||
"parameters": ["mobject", "duration"],
|
||||
"suitable_for": ["introducing_new_elements", "emphasis"]
|
||||
},
|
||||
"Transform": {
|
||||
"description": "Morphs one object into another",
|
||||
"parameters": ["source", "target", "duration"],
|
||||
"suitable_for": ["showing_changes", "concept_evolution"]
|
||||
},
|
||||
"Write": {
|
||||
"description": "Simulates writing/drawing of an object",
|
||||
"parameters": ["mobject", "duration"],
|
||||
"suitable_for": ["equations", "step_by_step_construction"]
|
||||
},
|
||||
"GrowFromCenter": {
|
||||
"description": "Object grows from its center",
|
||||
"parameters": ["mobject", "duration"],
|
||||
"suitable_for": ["emphasis", "geometric_construction"]
|
||||
}
|
||||
},
|
||||
"objects": {
|
||||
"geometric": {
|
||||
"Circle": {
|
||||
"description": "A circle shape",
|
||||
"properties": ["radius", "color", "fill_opacity"],
|
||||
"common_uses": ["points", "sets", "cycles"]
|
||||
},
|
||||
"Square": {
|
||||
"description": "A square shape",
|
||||
"properties": ["side_length", "color", "fill_opacity"],
|
||||
"common_uses": ["areas", "grids", "boundaries"]
|
||||
},
|
||||
"Arrow": {
|
||||
"description": "An arrow shape",
|
||||
"properties": ["start", "end", "color", "tip_length"],
|
||||
"common_uses": ["vectors", "directions", "transformations"]
|
||||
},
|
||||
"Axes": {
|
||||
"description": "Coordinate axes",
|
||||
"properties": ["x_range", "y_range", "axis_config"],
|
||||
"common_uses": ["coordinate_systems", "graphs", "plots"]
|
||||
}
|
||||
},
|
||||
"text": {
|
||||
"Text": {
|
||||
"description": "Regular text",
|
||||
"properties": ["content", "font_size", "color"],
|
||||
"common_uses": ["labels", "explanations", "titles"]
|
||||
},
|
||||
"MathTex": {
|
||||
"description": "LaTeX formatted mathematical text",
|
||||
"properties": ["tex_string", "font_size", "color"],
|
||||
"common_uses": ["equations", "formulas", "mathematical_expressions"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
def get_all_capabilities(self) -> Dict[str, Any]:
|
||||
"""Get all available animation capabilities."""
|
||||
return self.animation_capabilities
|
||||
|
||||
def get_object_info(self, obj_type: str) -> Dict[str, Any]:
|
||||
"""Get information about a specific object type."""
|
||||
for category in self.animation_capabilities["objects"].values():
|
||||
if obj_type in category:
|
||||
return category[obj_type]
|
||||
return {}
|
||||
|
||||
def get_transition_info(self, transition_type: str) -> Dict[str, Any]:
|
||||
"""Get information about a specific transition type."""
|
||||
return self.animation_capabilities["transitions"].get(transition_type, {})
|
105
animation-agent/llm_providers.py
Normal file
105
animation-agent/llm_providers.py
Normal file
|
@ -0,0 +1,105 @@
|
|||
"""
|
||||
LLM providers for the animation system.
|
||||
Supports both OpenAI and open-source models.
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, Optional
|
||||
from abc import ABC, abstractmethod
|
||||
from langchain.llms import HuggingFacePipeline
|
||||
from langchain.chat_models import ChatOpenAI
|
||||
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
||||
import torch
|
||||
|
||||
class BaseLLMProvider(ABC):
|
||||
@abstractmethod
|
||||
def generate(self, prompt: str) -> str:
|
||||
"""Generate text from prompt."""
|
||||
pass
|
||||
|
||||
class OpenAIProvider(BaseLLMProvider):
|
||||
def __init__(self, model_name: str = "gpt-3.5-turbo", temperature: float = 0.7):
|
||||
self.llm = ChatOpenAI(
|
||||
model_name=model_name,
|
||||
temperature=temperature
|
||||
)
|
||||
|
||||
def generate(self, prompt: str) -> str:
|
||||
"""Generate text using OpenAI's API."""
|
||||
response = self.llm.invoke(prompt)
|
||||
return response.content
|
||||
|
||||
class HuggingFaceProvider(BaseLLMProvider):
|
||||
def __init__(
|
||||
self,
|
||||
model_name: str = "tiiuae/falcon-7b-instruct",
|
||||
temperature: float = 0.7,
|
||||
device: str = "auto",
|
||||
max_length: int = 2048
|
||||
):
|
||||
# Determine device
|
||||
if device == "auto":
|
||||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
||||
|
||||
# Load model and tokenizer
|
||||
print(f"Loading model {model_name} on {device}...")
|
||||
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
|
||||
self.model = AutoModelForCausalLM.from_pretrained(
|
||||
model_name,
|
||||
torch_dtype=torch.bfloat16 if device == "cuda" else torch.float32,
|
||||
device_map=device,
|
||||
trust_remote_code=True
|
||||
)
|
||||
|
||||
# Create pipeline
|
||||
pipe = pipeline(
|
||||
"text-generation",
|
||||
model=self.model,
|
||||
tokenizer=self.tokenizer,
|
||||
max_length=max_length,
|
||||
temperature=temperature,
|
||||
device=device
|
||||
)
|
||||
|
||||
# Create LangChain wrapper
|
||||
self.llm = HuggingFacePipeline(pipeline=pipe)
|
||||
|
||||
def generate(self, prompt: str) -> str:
|
||||
"""Generate text using Hugging Face model."""
|
||||
response = self.llm.invoke(prompt)
|
||||
return response
|
||||
|
||||
def create_llm_provider(
|
||||
provider: str = "openai",
|
||||
model_name: Optional[str] = None,
|
||||
temperature: float = 0.7,
|
||||
device: str = "auto"
|
||||
) -> BaseLLMProvider:
|
||||
"""Factory function to create LLM provider."""
|
||||
if provider == "openai":
|
||||
return OpenAIProvider(
|
||||
model_name=model_name or "gpt-3.5-turbo",
|
||||
temperature=temperature
|
||||
)
|
||||
elif provider == "huggingface":
|
||||
return HuggingFaceProvider(
|
||||
model_name=model_name or "tiiuae/falcon-7b-instruct",
|
||||
temperature=temperature,
|
||||
device=device
|
||||
)
|
||||
else:
|
||||
raise ValueError(f"Unknown provider: {provider}")
|
||||
|
||||
# Example open-source models that work well for this use case
|
||||
RECOMMENDED_MODELS = {
|
||||
"instruction_following": [
|
||||
"tiiuae/falcon-7b-instruct", # Good balance of size and quality
|
||||
"google/flan-t5-large", # Smaller, faster, good for structured output
|
||||
"databricks/dolly-v2-3b", # Good for instruction following
|
||||
"stabilityai/stablelm-tuned-alpha-7b" # Good for code generation
|
||||
],
|
||||
"code_generation": [
|
||||
"bigcode/starcoder", # Specialized for code generation
|
||||
"codellama/codellama-7b-instruct", # Good for Python code
|
||||
"stabilityai/stablelm-code-7b" # Another good code option
|
||||
]
|
||||
}
|
87
animation-agent/main.py
Normal file
87
animation-agent/main.py
Normal file
|
@ -0,0 +1,87 @@
|
|||
"""
|
||||
Main entry point for the animation system.
|
||||
Orchestrates the interaction between different agents.
|
||||
"""
|
||||
|
||||
from typing import Dict, Any, Optional
|
||||
from knowledge_base import ManimKnowledgeBase
|
||||
from agents import ContentPlanningAgent, NarrativeDesignAgent, VisualPlanningAgent
|
||||
from code_generator import ManimCodeGenerator
|
||||
|
||||
class AnimationSystem:
|
||||
def __init__(self):
|
||||
self.knowledge_base = ManimKnowledgeBase()
|
||||
self.content_agent = ContentPlanningAgent(self.knowledge_base)
|
||||
self.narrative_agent = NarrativeDesignAgent(self.knowledge_base)
|
||||
self.visual_agent = VisualPlanningAgent(self.knowledge_base)
|
||||
self.code_generator = ManimCodeGenerator()
|
||||
|
||||
def create_animation(
|
||||
self,
|
||||
concept: str,
|
||||
audience_level: str,
|
||||
output_file: Optional[str] = None
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Create an animation for a given concept.
|
||||
|
||||
Args:
|
||||
concept: The mathematical concept to explain
|
||||
audience_level: Target audience level (e.g., "high_school", "college")
|
||||
output_file: Optional path to save the generated Manim code
|
||||
|
||||
Returns:
|
||||
Dictionary containing the complete animation plan and generated code
|
||||
"""
|
||||
# Content Planning Phase
|
||||
print("Planning content...")
|
||||
content_plan = self.content_agent.plan(concept, audience_level)
|
||||
|
||||
# Narrative Design Phase
|
||||
print("Designing narrative...")
|
||||
narrative_plan = self.narrative_agent.design(content_plan)
|
||||
|
||||
# Visual Planning Phase
|
||||
print("Planning visuals...")
|
||||
visual_plan = self.visual_agent.plan(narrative_plan)
|
||||
|
||||
# Code Generation Phase
|
||||
print("Generating Manim code...")
|
||||
manim_code = self.code_generator.generate_code(visual_plan, concept)
|
||||
|
||||
# Save code if output file specified
|
||||
if output_file:
|
||||
self.code_generator.save_to_file(manim_code, output_file)
|
||||
print(f"Manim code saved to {output_file}")
|
||||
|
||||
# Combine all plans into final output
|
||||
return {
|
||||
"content": content_plan,
|
||||
"narrative": narrative_plan,
|
||||
"visual": visual_plan,
|
||||
"code": manim_code
|
||||
}
|
||||
|
||||
def main():
|
||||
# Example usage
|
||||
system = AnimationSystem()
|
||||
|
||||
# Create an animation for explaining derivatives to high school students
|
||||
animation_plan = system.create_animation(
|
||||
concept="derivative_introduction",
|
||||
audience_level="high_school",
|
||||
output_file="derivative_animation.py"
|
||||
)
|
||||
|
||||
# Print the generated plan
|
||||
print("\nAnimation Plan Generated:")
|
||||
print(f"Content Plan: {animation_plan['content']}")
|
||||
print(f"Narrative Plan: {animation_plan['narrative']}")
|
||||
print(f"Visual Plan: {animation_plan['visual']}")
|
||||
|
||||
# Print example of how to run the animation
|
||||
print("\nTo render the animation, run:")
|
||||
print("manim derivative_animation.py DerivativeIntroductionScene -pql")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
1
animation-agent/manim_animation_agent.ipynb
Normal file
1
animation-agent/manim_animation_agent.ipynb
Normal file
|
@ -0,0 +1 @@
|
|||
|
5
animation-agent/requirements.txt
Normal file
5
animation-agent/requirements.txt
Normal file
|
@ -0,0 +1,5 @@
|
|||
langchain==0.1.0
|
||||
openai==1.3.0
|
||||
manim==0.17.3
|
||||
python-dotenv==1.0.0
|
||||
typing-extensions==4.8.0
|
211
manim_docs/README.md
Normal file
211
manim_docs/README.md
Normal file
|
@ -0,0 +1,211 @@
|
|||
# Manim Library Documentation
|
||||
|
||||
## Overview
|
||||
Manim is a powerful mathematical animation library that enables the creation of precise, programmatic animations for mathematical concepts. This documentation provides a comprehensive guide to the library's architecture and capabilities.
|
||||
|
||||
## Core Architecture
|
||||
|
||||
### Module Structure
|
||||
The library is organized into several core modules, each handling specific aspects of the animation system:
|
||||
|
||||
1. **Animation Module** (`animation/`)
|
||||
- Handles animation creation and management
|
||||
- Controls timing and transitions
|
||||
- Manages animation sequences
|
||||
|
||||
2. **Camera Module** (`camera/`)
|
||||
- Manages viewport and rendering
|
||||
- Handles 3D perspective
|
||||
- Controls scene framing
|
||||
|
||||
3. **Event Handler Module** (`event_handler/`)
|
||||
- Manages user interactions
|
||||
- Handles input events
|
||||
- Controls interactive elements
|
||||
|
||||
4. **Mobject Module** (`mobject/`)
|
||||
- Core visual elements
|
||||
- Mathematical objects
|
||||
- Text and LaTeX rendering
|
||||
|
||||
5. **Scene Module** (`scene/`)
|
||||
- Scene management
|
||||
- Animation playback
|
||||
- Output generation
|
||||
|
||||
6. **Shaders Module** (`shaders/`)
|
||||
- OpenGL shader system
|
||||
- Custom visual effects
|
||||
- Advanced rendering
|
||||
|
||||
7. **Utils Module** (`utils/`)
|
||||
- Utility functions
|
||||
- Mathematical operations
|
||||
- System integration
|
||||
|
||||
## Module Interactions
|
||||
|
||||
### Core Workflow
|
||||
1. **Scene Creation**
|
||||
- Scene module initializes the environment
|
||||
- Camera module sets up the viewport
|
||||
- Event handler module prepares for interaction
|
||||
|
||||
2. **Mobject Management**
|
||||
- Mobjects are created and modified
|
||||
- Shaders are applied for rendering
|
||||
- Utils provide supporting functions
|
||||
|
||||
3. **Animation Execution**
|
||||
- Animations are created and scheduled
|
||||
- Camera captures the scene
|
||||
- Event handler manages interactions
|
||||
|
||||
4. **Output Generation**
|
||||
- Scene module coordinates rendering
|
||||
- Camera module finalizes frames
|
||||
- Utils handle file operations
|
||||
|
||||
## Key Features
|
||||
|
||||
### 1. Mathematical Visualization
|
||||
- Precise geometric transformations
|
||||
- Complex mathematical concepts
|
||||
- Interactive demonstrations
|
||||
|
||||
### 2. Animation System
|
||||
- Smooth transitions
|
||||
- Complex sequences
|
||||
- Custom timing
|
||||
|
||||
### 3. Rendering Capabilities
|
||||
- High-quality output
|
||||
- Custom shader effects
|
||||
- 3D support
|
||||
|
||||
### 4. Interactive Features
|
||||
- User input handling
|
||||
- Real-time updates
|
||||
- Custom interactions
|
||||
|
||||
## Module Dependencies
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
Scene[Scene Module] --> Animation[Animation Module]
|
||||
Scene --> Camera[Camera Module]
|
||||
Scene --> Mobject[Mobject Module]
|
||||
Scene --> EventHandler[Event Handler Module]
|
||||
Mobject --> Shaders[Shaders Module]
|
||||
Animation --> Utils[Utils Module]
|
||||
Camera --> Shaders
|
||||
EventHandler --> Utils
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Scene Organization
|
||||
- Clear structure
|
||||
- Logical flow
|
||||
- Proper timing
|
||||
|
||||
### 2. Animation Design
|
||||
- Smooth transitions
|
||||
- Appropriate pacing
|
||||
- Clear sequences
|
||||
|
||||
### 3. Performance Optimization
|
||||
- Efficient rendering
|
||||
- Resource management
|
||||
- Cache utilization
|
||||
|
||||
### 4. Code Organization
|
||||
- Modular design
|
||||
- Clear interfaces
|
||||
- Proper documentation
|
||||
|
||||
## Example Workflow
|
||||
|
||||
```python
|
||||
from manim import *
|
||||
|
||||
class ExampleScene(Scene):
|
||||
def construct(self):
|
||||
# Create mobjects
|
||||
circle = Circle()
|
||||
square = Square()
|
||||
|
||||
# Set up animation
|
||||
self.play(ShowCreation(circle))
|
||||
self.wait()
|
||||
|
||||
# Transform
|
||||
self.play(Transform(circle, square))
|
||||
self.wait()
|
||||
|
||||
# Clean up
|
||||
self.play(FadeOut(square))
|
||||
```
|
||||
|
||||
## Module Documentation
|
||||
|
||||
For detailed information about each module, refer to their respective documentation:
|
||||
|
||||
1. [Animation Module](modules/animation.md)
|
||||
2. [Camera Module](modules/camera.md)
|
||||
3. [Event Handler Module](modules/event_handler.md)
|
||||
4. [Mobject Module](modules/mobject.md)
|
||||
5. [Scene Module](modules/scene.md)
|
||||
6. [Shaders Module](modules/shaders.md)
|
||||
7. [Utils Module](modules/utils.md)
|
||||
|
||||
## Development Guidelines
|
||||
|
||||
### 1. Code Style
|
||||
- Follow PEP 8
|
||||
- Use type hints
|
||||
- Document thoroughly
|
||||
|
||||
### 2. Testing
|
||||
- Unit tests
|
||||
- Integration tests
|
||||
- Performance benchmarks
|
||||
|
||||
### 3. Documentation
|
||||
- Clear examples
|
||||
- API references
|
||||
- Usage guides
|
||||
|
||||
### 4. Version Control
|
||||
- Semantic versioning
|
||||
- Changelog maintenance
|
||||
- Branch management
|
||||
|
||||
## Getting Started
|
||||
|
||||
1. **Installation**
|
||||
```bash
|
||||
pip install manim
|
||||
```
|
||||
|
||||
2. **Basic Usage**
|
||||
```python
|
||||
from manim import *
|
||||
|
||||
class MyScene(Scene):
|
||||
def construct(self):
|
||||
# Your animation code here
|
||||
pass
|
||||
```
|
||||
|
||||
3. **Running**
|
||||
```bash
|
||||
manim -pql scene.py MyScene
|
||||
```
|
||||
|
||||
## Resources
|
||||
|
||||
- [Official Documentation](https://docs.manim.community)
|
||||
- [GitHub Repository](https://github.com/ManimCommunity/manim)
|
||||
- [Community Forum](https://community.manim.community)
|
||||
- [Example Gallery](https://docs.manim.community/en/stable/examples.html)
|
173
manim_docs/modules/animation.md
Normal file
173
manim_docs/modules/animation.md
Normal file
|
@ -0,0 +1,173 @@
|
|||
# Animation Module README
|
||||
|
||||
## Overview
|
||||
The animation module is the core of Manim's animation system. It provides classes and utilities for creating and managing animations of mobjects (mathematical objects).
|
||||
|
||||
## Key Components
|
||||
|
||||
### 1. Base Animation Class (`animation.py`)
|
||||
- **Purpose**: Base class for all animations in Manim
|
||||
- **Key Features**:
|
||||
- Manages animation timing and interpolation
|
||||
- Handles mobject updates during animation
|
||||
- Provides core animation functionality
|
||||
- **Usage**:
|
||||
```python
|
||||
class CustomAnimation(Animation):
|
||||
def interpolate(self, alpha):
|
||||
# Custom interpolation logic
|
||||
pass
|
||||
```
|
||||
|
||||
### 2. Transform Animations (`transform.py`)
|
||||
- **Purpose**: Handles transformations between mobjects
|
||||
- **Key Classes**:
|
||||
- `Transform`: Base transformation class
|
||||
- `ReplacementTransform`: Replaces one mobject with another
|
||||
- `TransformFromCopy`: Creates a copy for transformation
|
||||
- `MoveToTarget`: Moves mobject to its target position
|
||||
- **Usage**:
|
||||
```python
|
||||
scene.play(Transform(circle, square))
|
||||
scene.play(ReplacementTransform(text1, text2))
|
||||
```
|
||||
|
||||
### 3. Creation Animations (`creation.py`)
|
||||
- **Purpose**: Animates the creation of mobjects
|
||||
- **Key Classes**:
|
||||
- `ShowCreation`: Draws mobject from start to end
|
||||
- `Write`: Writes text or equations
|
||||
- `DrawBorderThenFill`: Draws border then fills
|
||||
- **Usage**:
|
||||
```python
|
||||
scene.play(ShowCreation(circle))
|
||||
scene.play(Write(text))
|
||||
```
|
||||
|
||||
### 4. Fading Animations (`fading.py`)
|
||||
- **Purpose**: Handles fade in/out animations
|
||||
- **Key Classes**:
|
||||
- `FadeIn`: Fades in a mobject
|
||||
- `FadeOut`: Fades out a mobject
|
||||
- `FadeInFrom`: Fades in from a specific direction
|
||||
- **Usage**:
|
||||
```python
|
||||
scene.play(FadeIn(circle))
|
||||
scene.play(FadeOut(text))
|
||||
```
|
||||
|
||||
### 5. Movement Animations (`movement.py`)
|
||||
- **Purpose**: Handles movement and rotation animations
|
||||
- **Key Classes**:
|
||||
- `MoveAlongPath`: Moves along a path
|
||||
- `Rotate`: Rotates mobject
|
||||
- `ApplyMethod`: Applies a method with animation
|
||||
- **Usage**:
|
||||
```python
|
||||
scene.play(MoveAlongPath(dot, path))
|
||||
scene.play(Rotate(circle, PI/2))
|
||||
```
|
||||
|
||||
### 6. Composition Animations (`composition.py`)
|
||||
- **Purpose**: Combines multiple animations
|
||||
- **Key Classes**:
|
||||
- `AnimationGroup`: Plays animations simultaneously
|
||||
- `Succession`: Plays animations in sequence
|
||||
- `LaggedStart`: Starts animations with delay
|
||||
- **Usage**:
|
||||
```python
|
||||
scene.play(AnimationGroup(
|
||||
FadeIn(circle),
|
||||
Write(text),
|
||||
lag_ratio=0.5
|
||||
))
|
||||
```
|
||||
|
||||
### 7. Indication Animations (`indication.py`)
|
||||
- **Purpose**: Highlights and draws attention to mobjects
|
||||
- **Key Classes**:
|
||||
- `Flash`: Creates a flash effect
|
||||
- `Indicate`: Highlights a mobject
|
||||
- `ShowPassingFlash`: Shows a passing flash
|
||||
- **Usage**:
|
||||
```python
|
||||
scene.play(Flash(circle))
|
||||
scene.play(Indicate(text))
|
||||
```
|
||||
|
||||
### 8. Update Animations (`update.py`)
|
||||
- **Purpose**: Updates mobjects based on functions
|
||||
- **Key Classes**:
|
||||
- `UpdateFromFunc`: Updates based on function
|
||||
- `UpdateFromAlphaFunc`: Updates based on alpha
|
||||
- **Usage**:
|
||||
```python
|
||||
def update_func(mob):
|
||||
mob.rotate(0.1)
|
||||
scene.play(UpdateFromFunc(circle, update_func))
|
||||
```
|
||||
|
||||
## Interaction with Other Modules
|
||||
|
||||
1. **Mobject Module**:
|
||||
- Animations operate on mobjects
|
||||
- Uses mobject properties and methods for transformations
|
||||
- Interacts with mobject families and groups
|
||||
|
||||
2. **Scene Module**:
|
||||
- Scenes play and manage animations
|
||||
- Handles timing and synchronization
|
||||
- Manages animation queues and playback
|
||||
|
||||
3. **Camera Module**:
|
||||
- Animations can affect camera position
|
||||
- Camera movements are handled as animations
|
||||
- 3D animations interact with camera orientation
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Animation Timing**:
|
||||
- Use appropriate `run_time` for smooth animations
|
||||
- Consider `lag_ratio` for sequential animations
|
||||
- Use `rate_func` for custom timing curves
|
||||
|
||||
2. **Performance**:
|
||||
- Group similar animations together
|
||||
- Use `AnimationGroup` for parallel animations
|
||||
- Consider using `LaggedStart` for complex sequences
|
||||
|
||||
3. **Code Organization**:
|
||||
- Create custom animations for reusable effects
|
||||
- Use composition for complex animations
|
||||
- Keep animations focused and modular
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
class ComplexAnimation(Scene):
|
||||
def construct(self):
|
||||
# Create mobjects
|
||||
circle = Circle()
|
||||
square = Square()
|
||||
text = Text("Example")
|
||||
|
||||
# Basic animations
|
||||
self.play(ShowCreation(circle))
|
||||
self.wait()
|
||||
|
||||
# Transform animation
|
||||
self.play(Transform(circle, square))
|
||||
self.wait()
|
||||
|
||||
# Composition of animations
|
||||
self.play(AnimationGroup(
|
||||
FadeIn(text),
|
||||
Indicate(square),
|
||||
lag_ratio=0.5
|
||||
))
|
||||
|
||||
# Custom animation
|
||||
def update_func(mob, alpha):
|
||||
mob.rotate(alpha * TAU)
|
||||
self.play(UpdateFromAlphaFunc(square, update_func))
|
||||
```
|
126
manim_docs/modules/camera.md
Normal file
126
manim_docs/modules/camera.md
Normal file
|
@ -0,0 +1,126 @@
|
|||
# Camera Module README
|
||||
|
||||
## Overview
|
||||
The camera module handles all aspects of viewing and rendering in Manim. It manages the virtual camera that captures the scene, handles perspective, and controls the final output.
|
||||
|
||||
## Key Components
|
||||
|
||||
### 1. Camera Class (`camera.py`)
|
||||
- **Purpose**: Main camera class that handles rendering and viewport management
|
||||
- **Key Features**:
|
||||
- Manages OpenGL context and rendering
|
||||
- Handles frame buffering and composition
|
||||
- Controls resolution and quality settings
|
||||
- **Properties**:
|
||||
- `frame_width`, `frame_height`: Viewport dimensions
|
||||
- `frame_rate`: Frames per second
|
||||
- `background_color`: Scene background color
|
||||
- `samples`: Anti-aliasing samples
|
||||
- **Usage**:
|
||||
```python
|
||||
camera = Camera(
|
||||
frame_width=16,
|
||||
frame_height=9,
|
||||
frame_rate=30,
|
||||
samples=4
|
||||
)
|
||||
```
|
||||
|
||||
### 2. CameraFrame Class (`camera_frame.py`)
|
||||
- **Purpose**: Manages the camera's frame and orientation
|
||||
- **Key Features**:
|
||||
- Controls camera position and orientation
|
||||
- Handles 3D transformations
|
||||
- Manages field of view and perspective
|
||||
- **Methods**:
|
||||
- `reorient`: Changes camera orientation
|
||||
- `set_euler_angles`: Sets Euler angles
|
||||
- `make_orientation_default`: Resets orientation
|
||||
- **Usage**:
|
||||
```python
|
||||
camera_frame = CameraFrame()
|
||||
camera_frame.reorient(30, 70, 0) # Set orientation
|
||||
```
|
||||
|
||||
## Camera Features
|
||||
|
||||
### 1. Viewport Management
|
||||
- Controls what portion of the scene is visible
|
||||
- Handles aspect ratio and scaling
|
||||
- Manages zoom levels and focus
|
||||
|
||||
### 2. 3D Support
|
||||
- Handles perspective projection
|
||||
- Manages depth testing
|
||||
- Supports 3D transformations
|
||||
|
||||
### 3. Rendering Options
|
||||
- Anti-aliasing
|
||||
- Background color
|
||||
- Frame rate control
|
||||
- Resolution settings
|
||||
|
||||
## Interaction with Other Modules
|
||||
|
||||
1. **Scene Module**:
|
||||
- Scenes create and manage camera instances
|
||||
- Camera renders the scene's mobjects
|
||||
- Scene controls camera movement and transitions
|
||||
|
||||
2. **Mobject Module**:
|
||||
- Mobjects are rendered through the camera
|
||||
- Camera transforms affect mobject appearance
|
||||
- 3D mobjects interact with camera perspective
|
||||
|
||||
3. **Animation Module**:
|
||||
- Camera movements are handled as animations
|
||||
- Animations can affect camera properties
|
||||
- Camera transitions are animated
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Camera Setup**:
|
||||
- Set appropriate frame dimensions
|
||||
- Configure quality settings based on needs
|
||||
- Consider performance impact of high samples
|
||||
|
||||
2. **3D Scenes**:
|
||||
- Use appropriate camera angles
|
||||
- Consider depth and perspective
|
||||
- Plan camera movements carefully
|
||||
|
||||
3. **Performance**:
|
||||
- Balance quality and performance
|
||||
- Use appropriate frame rates
|
||||
- Consider rendering time for high-quality output
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
class CameraExample(ThreeDScene):
|
||||
def construct(self):
|
||||
# Set up camera
|
||||
self.camera.frame.set_euler_angles(
|
||||
theta=-30 * DEGREES,
|
||||
phi=70 * DEGREES
|
||||
)
|
||||
|
||||
# Create 3D objects
|
||||
cube = Cube()
|
||||
sphere = Sphere()
|
||||
|
||||
# Animate camera movement
|
||||
self.play(
|
||||
self.camera.frame.animate.set_euler_angles(
|
||||
theta=60 * DEGREES,
|
||||
phi=30 * DEGREES
|
||||
),
|
||||
run_time=2
|
||||
)
|
||||
|
||||
# Add objects with proper depth
|
||||
self.play(
|
||||
ShowCreation(cube),
|
||||
ShowCreation(sphere)
|
||||
)
|
||||
```
|
116
manim_docs/modules/event_handler.md
Normal file
116
manim_docs/modules/event_handler.md
Normal file
|
@ -0,0 +1,116 @@
|
|||
# Event Handler Module README
|
||||
|
||||
## Overview
|
||||
The event handler module manages user interactions and events in Manim. It provides a system for handling keyboard and mouse events, allowing for interactive animations and user input.
|
||||
|
||||
## Key Components
|
||||
|
||||
### 1. Event Dispatcher (`event_dispatcher.py`)
|
||||
- **Purpose**: Central event management system
|
||||
- **Key Features**:
|
||||
- Registers and manages event listeners
|
||||
- Dispatches events to appropriate handlers
|
||||
- Handles event propagation
|
||||
- **Usage**:
|
||||
```python
|
||||
dispatcher = EventDispatcher()
|
||||
dispatcher.add_listener(event_type, handler)
|
||||
```
|
||||
|
||||
### 2. Event Listener (`event_listner.py`)
|
||||
- **Purpose**: Handles individual event subscriptions
|
||||
- **Key Features**:
|
||||
- Manages event callbacks
|
||||
- Handles event priority
|
||||
- Controls event propagation
|
||||
- **Usage**:
|
||||
```python
|
||||
listener = EventListener(handler, priority=0)
|
||||
```
|
||||
|
||||
### 3. Event Types (`event_type.py`)
|
||||
- **Purpose**: Defines different types of events
|
||||
- **Key Features**:
|
||||
- Keyboard events
|
||||
- Mouse events
|
||||
- Custom event types
|
||||
- **Usage**:
|
||||
```python
|
||||
class CustomEvent(EventType):
|
||||
pass
|
||||
```
|
||||
|
||||
## Event Types
|
||||
|
||||
### 1. Keyboard Events
|
||||
- Key press events
|
||||
- Key release events
|
||||
- Special key combinations
|
||||
|
||||
### 2. Mouse Events
|
||||
- Mouse movement
|
||||
- Mouse clicks
|
||||
- Mouse drag
|
||||
- Mouse wheel
|
||||
|
||||
### 3. Custom Events
|
||||
- Scene-specific events
|
||||
- Animation events
|
||||
- State change events
|
||||
|
||||
## Interaction with Other Modules
|
||||
|
||||
1. **Scene Module**:
|
||||
- Scenes register event handlers
|
||||
- Events can trigger scene changes
|
||||
- Interactive scenes use event system
|
||||
|
||||
2. **Animation Module**:
|
||||
- Events can control animations
|
||||
- Animation state changes trigger events
|
||||
- Interactive animations use event system
|
||||
|
||||
3. **Mobject Module**:
|
||||
- Mobjects can respond to events
|
||||
- Events can modify mobject properties
|
||||
- Interactive mobjects use event system
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Event Handling**:
|
||||
- Keep handlers focused and simple
|
||||
- Use appropriate event priorities
|
||||
- Handle event propagation carefully
|
||||
|
||||
2. **Performance**:
|
||||
- Minimize event handler complexity
|
||||
- Use event filtering when possible
|
||||
- Consider event frequency
|
||||
|
||||
3. **Code Organization**:
|
||||
- Group related event handlers
|
||||
- Use event types appropriately
|
||||
- Document event dependencies
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
class InteractiveExample(Scene):
|
||||
def construct(self):
|
||||
# Create interactive mobject
|
||||
circle = Circle()
|
||||
self.add(circle)
|
||||
|
||||
# Define event handlers
|
||||
def on_key_press(event):
|
||||
if event.key == "LEFT":
|
||||
circle.shift(LEFT)
|
||||
elif event.key == "RIGHT":
|
||||
circle.shift(RIGHT)
|
||||
|
||||
# Register event handler
|
||||
self.add_key_press_handler(on_key_press)
|
||||
|
||||
# Interactive loop
|
||||
self.wait()
|
||||
```
|
183
manim_docs/modules/mobject.md
Normal file
183
manim_docs/modules/mobject.md
Normal file
|
@ -0,0 +1,183 @@
|
|||
# Mobject Module README
|
||||
|
||||
## Overview
|
||||
The mobject (Mathematical Object) module is the core of Manim's visual system. It provides the base classes and implementations for all visual elements that can be displayed and animated in Manim.
|
||||
|
||||
## Key Components
|
||||
|
||||
### 1. Base Mobject Class (`mobject.py`)
|
||||
- **Purpose**: Base class for all visual objects
|
||||
- **Key Features**:
|
||||
- Manages object properties and state
|
||||
- Handles transformations and updates
|
||||
- Provides core functionality for all mobjects
|
||||
- **Properties**:
|
||||
- `color`, `opacity`, `shading`
|
||||
- `position`, `scale`, `rotation`
|
||||
- `submobjects`: Child mobjects
|
||||
- **Usage**:
|
||||
```python
|
||||
class CustomMobject(Mobject):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.init_points()
|
||||
```
|
||||
|
||||
### 2. Geometry Mobjects (`geometry.py`)
|
||||
- **Purpose**: Basic geometric shapes
|
||||
- **Key Classes**:
|
||||
- `Circle`, `Square`, `Rectangle`
|
||||
- `Line`, `Arrow`, `Polygon`
|
||||
- `Arc`, `CurvedArrow`
|
||||
- **Usage**:
|
||||
```python
|
||||
circle = Circle(radius=2)
|
||||
square = Square(side_length=3)
|
||||
line = Line(start=LEFT, end=RIGHT)
|
||||
```
|
||||
|
||||
### 3. Text and LaTeX Mobjects (`text.py`)
|
||||
- **Purpose**: Text and mathematical notation
|
||||
- **Key Classes**:
|
||||
- `Text`: Regular text
|
||||
- `Tex`: LaTeX math
|
||||
- `MathTex`: Mathematical expressions
|
||||
- **Usage**:
|
||||
```python
|
||||
text = Text("Hello World")
|
||||
equation = Tex(r"\frac{d}{dx}f(x) = \lim_{h \to 0} \frac{f(x+h)-f(x)}{h}")
|
||||
```
|
||||
|
||||
### 4. Coordinate Systems (`coordinate_systems.py`)
|
||||
- **Purpose**: Mathematical coordinate systems
|
||||
- **Key Classes**:
|
||||
- `NumberLine`: One-dimensional number line
|
||||
- `Axes`: 2D coordinate system
|
||||
- `ThreeDAxes`: 3D coordinate system
|
||||
- **Usage**:
|
||||
```python
|
||||
axes = Axes(
|
||||
x_range=[-3, 3],
|
||||
y_range=[-3, 3]
|
||||
)
|
||||
```
|
||||
|
||||
### 5. Vectorized Mobjects (`types/vectorized_mobject.py`)
|
||||
- **Purpose**: Efficient rendering of complex shapes
|
||||
- **Key Classes**:
|
||||
- `VMobject`: Vector-based mobject
|
||||
- `VGroup`: Group of vectorized mobjects
|
||||
- `DashedVMobject`: Dashed line version
|
||||
- **Usage**:
|
||||
```python
|
||||
vgroup = VGroup(circle, square, line)
|
||||
dashed_line = DashedVMobject(line)
|
||||
```
|
||||
|
||||
### 6. 3D Mobjects (`three_dimensions.py`)
|
||||
- **Purpose**: Three-dimensional objects
|
||||
- **Key Classes**:
|
||||
- `Sphere`, `Cube`, `Cylinder`
|
||||
- `Surface`: Parametric surfaces
|
||||
- `ThreeDScene`: 3D scene support
|
||||
- **Usage**:
|
||||
```python
|
||||
sphere = Sphere(radius=2)
|
||||
cube = Cube(side_length=3)
|
||||
```
|
||||
|
||||
### 7. Interactive Mobjects (`interactive.py`)
|
||||
- **Purpose**: User-interactive elements
|
||||
- **Key Classes**:
|
||||
- `ValueTracker`: Tracks numerical values
|
||||
- `Button`: Clickable buttons
|
||||
- `Slider`: Value sliders
|
||||
- **Usage**:
|
||||
```python
|
||||
tracker = ValueTracker(0)
|
||||
slider = Slider(min_value=0, max_value=10)
|
||||
```
|
||||
|
||||
## Mobject Features
|
||||
|
||||
### 1. Transformations
|
||||
- Position changes
|
||||
- Scaling and rotation
|
||||
- Color and opacity changes
|
||||
- Complex transformations
|
||||
|
||||
### 2. Grouping
|
||||
- Parent-child relationships
|
||||
- Group transformations
|
||||
- Layering and z-index
|
||||
|
||||
### 3. Animation Support
|
||||
- Property interpolation
|
||||
- Path following
|
||||
- Complex animations
|
||||
|
||||
## Interaction with Other Modules
|
||||
|
||||
1. **Animation Module**:
|
||||
- Mobjects are animated
|
||||
- Properties can be interpolated
|
||||
- Supports complex transformations
|
||||
|
||||
2. **Scene Module**:
|
||||
- Mobjects are added to scenes
|
||||
- Scene manages mobject updates
|
||||
- Handles mobject rendering
|
||||
|
||||
3. **Camera Module**:
|
||||
- Mobjects are rendered through camera
|
||||
- 3D mobjects use camera perspective
|
||||
- Camera affects mobject appearance
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Mobject Creation**:
|
||||
- Use appropriate mobject types
|
||||
- Consider performance implications
|
||||
- Plan for animation needs
|
||||
|
||||
2. **Organization**:
|
||||
- Group related mobjects
|
||||
- Use appropriate layering
|
||||
- Manage z-index carefully
|
||||
|
||||
3. **Performance**:
|
||||
- Minimize complex mobjects
|
||||
- Use vectorized mobjects when possible
|
||||
- Consider rendering complexity
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
class MobjectExample(Scene):
|
||||
def construct(self):
|
||||
# Create basic shapes
|
||||
circle = Circle(radius=2, color=BLUE)
|
||||
square = Square(side_length=3, color=RED)
|
||||
|
||||
# Create text
|
||||
text = Text("Example", font_size=24)
|
||||
|
||||
# Create coordinate system
|
||||
axes = Axes(
|
||||
x_range=[-3, 3],
|
||||
y_range=[-3, 3]
|
||||
)
|
||||
|
||||
# Group mobjects
|
||||
group = VGroup(circle, square, text)
|
||||
|
||||
# Transform and animate
|
||||
self.play(
|
||||
ShowCreation(axes),
|
||||
FadeIn(group)
|
||||
)
|
||||
self.play(
|
||||
group.animate.shift(UP),
|
||||
group.animate.scale(1.5)
|
||||
)
|
||||
```
|
144
manim_docs/modules/scene.md
Normal file
144
manim_docs/modules/scene.md
Normal file
|
@ -0,0 +1,144 @@
|
|||
# Scene Module README
|
||||
|
||||
## Overview
|
||||
The scene module provides the framework for creating and managing animations in Manim. It handles the organization, timing, and rendering of animations and mobjects.
|
||||
|
||||
## Key Components
|
||||
|
||||
### 1. Base Scene Class (`scene.py`)
|
||||
- **Purpose**: Base class for all scenes
|
||||
- **Key Features**:
|
||||
- Manages animation playback
|
||||
- Handles mobject organization
|
||||
- Controls scene timing
|
||||
- **Methods**:
|
||||
- `play`: Plays animations
|
||||
- `wait`: Pauses scene
|
||||
- `add`: Adds mobjects
|
||||
- `remove`: Removes mobjects
|
||||
- **Usage**:
|
||||
```python
|
||||
class CustomScene(Scene):
|
||||
def construct(self):
|
||||
# Scene implementation
|
||||
pass
|
||||
```
|
||||
|
||||
### 2. Interactive Scene (`interactive_scene.py`)
|
||||
- **Purpose**: Handles user interaction
|
||||
- **Key Features**:
|
||||
- User input handling
|
||||
- Real-time updates
|
||||
- Interactive controls
|
||||
- **Usage**:
|
||||
```python
|
||||
class InteractiveExample(InteractiveScene):
|
||||
def construct(self):
|
||||
# Interactive implementation
|
||||
pass
|
||||
```
|
||||
|
||||
### 3. Scene File Writer (`scene_file_writer.py`)
|
||||
- **Purpose**: Handles scene output
|
||||
- **Key Features**:
|
||||
- Video file generation
|
||||
- Frame rendering
|
||||
- Progress tracking
|
||||
- **Usage**:
|
||||
```python
|
||||
writer = SceneFileWriter(scene)
|
||||
writer.begin()
|
||||
# Scene rendering
|
||||
writer.finish()
|
||||
```
|
||||
|
||||
### 4. Scene Embed (`scene_embed.py`)
|
||||
- **Purpose**: Embeds scenes in other contexts
|
||||
- **Key Features**:
|
||||
- Jupyter notebook support
|
||||
- Web embedding
|
||||
- Interactive previews
|
||||
- **Usage**:
|
||||
```python
|
||||
embed = SceneEmbed(scene)
|
||||
embed.display()
|
||||
```
|
||||
|
||||
## Scene Features
|
||||
|
||||
### 1. Animation Management
|
||||
- Sequence control
|
||||
- Timing management
|
||||
- Animation grouping
|
||||
|
||||
### 2. Mobject Management
|
||||
- Organization
|
||||
- Layering
|
||||
- State tracking
|
||||
|
||||
### 3. Output Control
|
||||
- Video generation
|
||||
- Frame rendering
|
||||
- Quality settings
|
||||
|
||||
## Interaction with Other Modules
|
||||
|
||||
1. **Mobject Module**:
|
||||
- Scenes contain and manage mobjects
|
||||
- Controls mobject updates
|
||||
- Handles mobject rendering
|
||||
|
||||
2. **Animation Module**:
|
||||
- Scenes play animations
|
||||
- Manages animation timing
|
||||
- Controls animation sequence
|
||||
|
||||
3. **Camera Module**:
|
||||
- Scenes control camera
|
||||
- Manages camera movements
|
||||
- Handles rendering
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Scene Organization**:
|
||||
- Clear structure
|
||||
- Logical flow
|
||||
- Proper timing
|
||||
|
||||
2. **Animation Management**:
|
||||
- Smooth transitions
|
||||
- Appropriate timing
|
||||
- Clear sequences
|
||||
|
||||
3. **Performance**:
|
||||
- Efficient rendering
|
||||
- Proper cleanup
|
||||
- Resource management
|
||||
|
||||
## Example Usage
|
||||
|
||||
```python
|
||||
class ExampleScene(Scene):
|
||||
def construct(self):
|
||||
# Create mobjects
|
||||
circle = Circle()
|
||||
square = Square()
|
||||
text = Text("Example")
|
||||
|
||||
# Organize scene
|
||||
self.add(circle)
|
||||
self.wait()
|
||||
|
||||
# Animate
|
||||
self.play(
|
||||
Transform(circle, square),
|
||||
Write(text)
|
||||
)
|
||||
self.wait()
|
||||
|
||||
# Clean up
|
||||
self.play(
|
||||
FadeOut(square),
|
||||
FadeOut(text)
|
||||
)
|
||||
```
|
206
manim_docs/modules/shaders.md
Normal file
206
manim_docs/modules/shaders.md
Normal file
|
@ -0,0 +1,206 @@
|
|||
# Shaders in Manim
|
||||
|
||||
The shader system in Manim is a sophisticated component that enables high-performance rendering of various visual elements. This document provides a comprehensive overview of the shader system, its components, and how they interact with other parts of Manim.
|
||||
|
||||
## Overview
|
||||
|
||||
The shader system is implemented using OpenGL (GLSL) and is organized into several specialized components:
|
||||
|
||||
1. Core Shaders
|
||||
2. Special Effects
|
||||
3. Utility Components
|
||||
4. Common Functions
|
||||
|
||||
## Directory Structure
|
||||
|
||||
```
|
||||
manimlib/shaders/
|
||||
├── image/ # Image rendering shaders
|
||||
├── inserts/ # Shared shader code components
|
||||
├── mandelbrot_fractal/ # Mandelbrot set visualization
|
||||
├── newton_fractal/ # Newton fractal visualization
|
||||
├── quadratic_bezier/ # Curve rendering
|
||||
├── surface/ # Surface rendering
|
||||
├── textured_surface/ # Textured surface handling
|
||||
├── true_dot/ # Point/dot rendering
|
||||
└── simple_vert.glsl # Basic vertex shader
|
||||
```
|
||||
|
||||
## Core Components
|
||||
|
||||
### 1. Basic Rendering (simple_vert.glsl)
|
||||
- Provides fundamental vertex transformation
|
||||
- Used as a base for more complex shaders
|
||||
- Handles basic position calculations
|
||||
|
||||
### 2. Image Processing (image/)
|
||||
- Handles texture mapping and image rendering
|
||||
- Components:
|
||||
- `vert.glsl`: Vertex shader for image coordinates
|
||||
- `frag.glsl`: Fragment shader for texture sampling
|
||||
|
||||
### 3. Surface Rendering (surface/)
|
||||
- Manages 3D surface visualization
|
||||
- Features:
|
||||
- Normal calculation
|
||||
- Color interpolation
|
||||
- Lighting effects
|
||||
|
||||
### 4. Curve System (quadratic_bezier/)
|
||||
- Implements sophisticated curve rendering
|
||||
- Subcomponents:
|
||||
- `stroke/`: Handles curve outlines
|
||||
- `fill/`: Manages curve filling
|
||||
- `depth/`: Handles depth-based rendering
|
||||
|
||||
## Special Effects
|
||||
|
||||
### 1. Fractal Renderers
|
||||
- **Mandelbrot Fractal**
|
||||
- Real-time Mandelbrot set visualization
|
||||
- Customizable coloring and iterations
|
||||
- Interactive zooming capabilities
|
||||
|
||||
- **Newton Fractal**
|
||||
- Complex polynomial root visualization
|
||||
- Color-coded root basins
|
||||
- Parameter space exploration
|
||||
|
||||
### 2. Textured Surfaces
|
||||
- Supports multiple texture layers
|
||||
- Light/dark texture blending
|
||||
- Normal-based shading
|
||||
|
||||
### 3. True Dots
|
||||
- High-quality point rendering
|
||||
- Anti-aliasing support
|
||||
- Size and glow effects
|
||||
|
||||
## Utility Components (inserts/)
|
||||
|
||||
### 1. Common Functions
|
||||
- `complex_functions.glsl`: Complex number operations
|
||||
- `finalize_color.glsl`: Color processing and lighting
|
||||
- `get_xyz_to_uv.glsl`: Coordinate transformations
|
||||
- `emit_gl_Position.glsl`: Position calculation
|
||||
|
||||
### 2. Shared Features
|
||||
- Lighting calculations
|
||||
- Matrix transformations
|
||||
- Anti-aliasing utilities
|
||||
- Color interpolation
|
||||
|
||||
## Key Features
|
||||
|
||||
### 1. Lighting System
|
||||
- Phong lighting model
|
||||
- Customizable parameters:
|
||||
- Reflectiveness
|
||||
- Gloss
|
||||
- Shadow intensity
|
||||
|
||||
### 2. Coordinate Systems
|
||||
- Multiple coordinate space handling
|
||||
- Smooth transitions between spaces
|
||||
- Perspective and orthographic projections
|
||||
|
||||
### 3. Anti-aliasing
|
||||
- Edge smoothing
|
||||
- Adaptive width calculation
|
||||
- Resolution-independent rendering
|
||||
|
||||
## Integration with Other Modules
|
||||
|
||||
### 1. Scene Interaction
|
||||
- Works with the scene module for rendering
|
||||
- Handles camera transformations
|
||||
- Supports animation transitions
|
||||
|
||||
### 2. Mobject Integration
|
||||
- Provides shading for mobjects
|
||||
- Handles complex geometries
|
||||
- Supports custom effects
|
||||
|
||||
### 3. Animation Support
|
||||
- Real-time shader parameter updates
|
||||
- Smooth transitions
|
||||
- Effect interpolation
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### 1. Basic Surface
|
||||
```glsl
|
||||
// Example of using surface shader
|
||||
void main() {
|
||||
emit_gl_Position(point);
|
||||
vec3 unit_normal = normalize(d_normal_point - point);
|
||||
v_color = finalize_color(rgba, point, unit_normal);
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Complex Effects
|
||||
```glsl
|
||||
// Example of fractal rendering
|
||||
vec2 z = xyz_coords.xy;
|
||||
for(int n = 0; n < int(n_steps); n++) {
|
||||
z = complex_mult(z, z) + c;
|
||||
}
|
||||
```
|
||||
|
||||
## Performance Considerations
|
||||
|
||||
1. **Optimization Techniques**
|
||||
- Efficient matrix operations
|
||||
- Minimal texture lookups
|
||||
- Smart branching
|
||||
|
||||
2. **Memory Management**
|
||||
- Vertex attribute optimization
|
||||
- Uniform buffer usage
|
||||
- Texture memory handling
|
||||
|
||||
3. **Rendering Pipeline**
|
||||
- Efficient draw calls
|
||||
- Batch processing
|
||||
- State management
|
||||
|
||||
## Development Guidelines
|
||||
|
||||
1. **Shader Creation**
|
||||
- Follow GLSL 330 standards
|
||||
- Use shared components via #INSERT
|
||||
- Maintain backward compatibility
|
||||
|
||||
2. **Best Practices**
|
||||
- Document uniform variables
|
||||
- Use consistent naming
|
||||
- Handle edge cases
|
||||
|
||||
3. **Testing**
|
||||
- Verify visual output
|
||||
- Check performance impact
|
||||
- Test cross-platform compatibility
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
1. **Common Issues**
|
||||
- Shader compilation errors
|
||||
- Uniform binding problems
|
||||
- Version compatibility
|
||||
|
||||
2. **Debug Techniques**
|
||||
- Use debug uniforms
|
||||
- Check shader logs
|
||||
- Validate inputs
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
1. **Planned Features**
|
||||
- Additional effect shaders
|
||||
- Performance optimizations
|
||||
- New visualization techniques
|
||||
|
||||
2. **Compatibility**
|
||||
- WebGL support
|
||||
- Mobile optimization
|
||||
- Modern GPU features
|
295
manim_docs/modules/utils.md
Normal file
295
manim_docs/modules/utils.md
Normal file
|
@ -0,0 +1,295 @@
|
|||
# Utils Module Documentation
|
||||
|
||||
## Overview
|
||||
The utils module provides essential utility functions and classes that support the core functionality of Manim. It includes mathematical operations, color management, file handling, caching mechanisms, and system utilities.
|
||||
|
||||
## Directory Structure
|
||||
|
||||
```
|
||||
manimlib/utils/
|
||||
├── bezier.py # Bezier curve operations
|
||||
├── cache.py # Caching mechanisms
|
||||
├── color.py # Color manipulation
|
||||
├── config_ops.py # Configuration management
|
||||
├── customization.py # User customization
|
||||
├── debug.py # Debugging utilities
|
||||
├── dict_ops.py # Dictionary operations
|
||||
├── directories.py # Directory management
|
||||
├── family_ops.py # Mobject family operations
|
||||
├── file_ops.py # File operations
|
||||
├── images.py # Image handling
|
||||
├── iterables.py # Iterable utilities
|
||||
├── paths.py # Path manipulation
|
||||
├── rate_functions.py # Animation rate functions
|
||||
├── shaders.py # Shader utilities
|
||||
├── simple_functions.py # Basic utility functions
|
||||
├── sounds.py # Sound handling
|
||||
├── space_ops.py # Spatial operations
|
||||
├── strings.py # String utilities
|
||||
├── tex.py # TeX utilities
|
||||
├── tex_file_writing.py # TeX file generation
|
||||
└── tex_to_symbol_count.py # TeX symbol counting
|
||||
```
|
||||
|
||||
## Core Components
|
||||
|
||||
### 1. Mathematical Utilities
|
||||
|
||||
#### Bezier Operations (`bezier.py`)
|
||||
- **Purpose**: Handle Bezier curve calculations
|
||||
- **Key Functions**:
|
||||
- `interpolate_bezier`: Interpolate points along curve
|
||||
- `get_bezier_points`: Generate curve points
|
||||
- `partial_bezier_points`: Get partial curve
|
||||
- `get_quadratic_approximation`: Approximate curves
|
||||
- **Usage**:
|
||||
```python
|
||||
points = get_bezier_points(start, control1, control2, end)
|
||||
```
|
||||
|
||||
#### Space Operations (`space_ops.py`)
|
||||
- **Purpose**: Handle spatial transformations and vector operations
|
||||
- **Key Functions**:
|
||||
- `rotation_matrix`: Generate rotation matrices
|
||||
- `angle_between_vectors`: Calculate angles
|
||||
- `get_norm`: Vector normalization
|
||||
- `cross`: Cross product calculation
|
||||
- `find_intersection`: Line intersection
|
||||
- `get_closest_point_on_line`: Point-line distance
|
||||
- **Usage**:
|
||||
```python
|
||||
angle = angle_between_vectors(vector1, vector2)
|
||||
intersection = find_intersection(p0, v0, p1, v1)
|
||||
```
|
||||
|
||||
#### Rate Functions (`rate_functions.py`)
|
||||
- **Purpose**: Animation timing functions
|
||||
- **Key Functions**:
|
||||
- `linear`: Linear interpolation
|
||||
- `smooth`: Smooth interpolation
|
||||
- `there_and_back`: Reversing motion
|
||||
- `double_smooth`: Double smooth transition
|
||||
- `exponential_decay`: Exponential decay
|
||||
- `lingering`: Lingering effect
|
||||
- **Usage**:
|
||||
```python
|
||||
progress = smooth(alpha)
|
||||
decay = exponential_decay(t, half_life=0.1)
|
||||
```
|
||||
|
||||
### 2. Color Management (`color.py`)
|
||||
- **Purpose**: Color operations and conversions
|
||||
- **Key Features**:
|
||||
- Color space conversions (RGB, hex)
|
||||
- Color interpolation
|
||||
- Gradient generation
|
||||
- Color map creation
|
||||
- Average color calculation
|
||||
- **Usage**:
|
||||
```python
|
||||
rgb = color_to_rgb(hex_color)
|
||||
interpolated = interpolate_color(color1, color2, alpha)
|
||||
avg_color = average_color(*colors)
|
||||
colormap = get_colormap_from_colors(colors)
|
||||
```
|
||||
|
||||
### 3. File and Resource Management
|
||||
|
||||
#### File Operations (`file_ops.py`)
|
||||
- **Purpose**: File system operations
|
||||
- **Key Functions**:
|
||||
- `find_file`: Locate files with extensions
|
||||
- `guarantee_existence`: Directory creation
|
||||
- `download_url`: URL resource downloading
|
||||
- **Usage**:
|
||||
```python
|
||||
file_path = find_file(name, directories, extensions)
|
||||
dir_path = guarantee_existence(path)
|
||||
```
|
||||
|
||||
#### Directory Management (`directories.py`)
|
||||
- **Purpose**: Directory structure handling
|
||||
- **Key Functions**:
|
||||
- `get_cache_dir`: Cache directory access
|
||||
- `get_downloads_dir`: Downloads location
|
||||
- `get_shader_dir`: Shader file location
|
||||
- `get_sound_dir`: Sound file location
|
||||
- **Usage**:
|
||||
```python
|
||||
cache_dir = get_cache_dir()
|
||||
shader_dir = get_shader_dir()
|
||||
```
|
||||
|
||||
#### Image Operations (`images.py`)
|
||||
- **Purpose**: Image processing and management
|
||||
- **Key Features**:
|
||||
- Image loading and path resolution
|
||||
- Format conversion
|
||||
- Image inversion
|
||||
- Raster and vector image handling
|
||||
- **Usage**:
|
||||
```python
|
||||
image_path = get_full_raster_image_path(filename)
|
||||
inverted = invert_image(image)
|
||||
```
|
||||
|
||||
#### Sound Operations (`sounds.py`)
|
||||
- **Purpose**: Sound file handling
|
||||
- **Key Features**:
|
||||
- Sound file path resolution
|
||||
- Audio format support (.wav, .mp3)
|
||||
- Platform-specific playback
|
||||
- **Usage**:
|
||||
```python
|
||||
sound_path = get_full_sound_file_path(filename)
|
||||
```
|
||||
|
||||
### 4. TeX and Mathematical Typesetting
|
||||
|
||||
#### TeX System (`tex.py`, `tex_file_writing.py`, `tex_to_symbol_count.py`)
|
||||
- **Purpose**: LaTeX integration and processing
|
||||
- **Key Features**:
|
||||
- TeX template management
|
||||
- SVG conversion
|
||||
- Symbol counting
|
||||
- Template configuration
|
||||
- Error handling
|
||||
- **Usage**:
|
||||
```python
|
||||
svg = latex_to_svg(latex_expression)
|
||||
symbol_count = num_tex_symbols(tex_string)
|
||||
```
|
||||
|
||||
### 5. Performance and Optimization
|
||||
|
||||
#### Caching System (`cache.py`)
|
||||
- **Purpose**: Performance optimization through caching
|
||||
- **Key Features**:
|
||||
- Disk-based caching
|
||||
- Function result caching
|
||||
- Cache size management
|
||||
- Cache invalidation
|
||||
- **Usage**:
|
||||
```python
|
||||
@cache_on_disk
|
||||
def expensive_operation():
|
||||
# Function implementation
|
||||
```
|
||||
|
||||
#### Shader Management (`shaders.py`)
|
||||
- **Purpose**: GPU shader handling
|
||||
- **Key Features**:
|
||||
- Shader code loading
|
||||
- Texture management
|
||||
- Uniform handling
|
||||
- Program compilation
|
||||
- **Usage**:
|
||||
```python
|
||||
shader_code = get_shader_code_from_file(filename)
|
||||
texture = image_path_to_texture(path, ctx)
|
||||
```
|
||||
|
||||
### 6. Utility Functions
|
||||
|
||||
#### Simple Functions (`simple_functions.py`)
|
||||
- **Purpose**: Basic utility operations
|
||||
- **Key Functions**:
|
||||
- `sigmoid`: Sigmoid function
|
||||
- `clip`: Value clamping
|
||||
- `fdiv`: Safe division
|
||||
- `get_parameters`: Function parameter inspection
|
||||
- **Usage**:
|
||||
```python
|
||||
result = sigmoid(x)
|
||||
clipped = clip(value, min_val, max_val)
|
||||
```
|
||||
|
||||
#### Dictionary Operations (`dict_ops.py`)
|
||||
- **Purpose**: Dictionary manipulation utilities
|
||||
- **Key Features**:
|
||||
- Deep dictionary updates
|
||||
- Nested access
|
||||
- Dictionary merging
|
||||
- **Usage**:
|
||||
```python
|
||||
merged = merge_dicts(dict1, dict2)
|
||||
```
|
||||
|
||||
#### Family Operations (`family_ops.py`)
|
||||
- **Purpose**: Mobject family relationship handling
|
||||
- **Key Features**:
|
||||
- Family member tracking
|
||||
- Relationship management
|
||||
- Hierarchy operations
|
||||
- **Usage**:
|
||||
```python
|
||||
family = extract_mobject_family_members(mobject)
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Mathematical Operations
|
||||
- Use vectorized operations when possible
|
||||
- Cache complex calculations
|
||||
- Handle edge cases and numerical stability
|
||||
- Maintain precision in transformations
|
||||
|
||||
### 2. Resource Management
|
||||
- Use context managers for file operations
|
||||
- Handle permissions and file existence
|
||||
- Clean up resources properly
|
||||
- Use appropriate caching strategies
|
||||
|
||||
### 3. Performance Optimization
|
||||
- Profile critical paths
|
||||
- Cache frequent operations
|
||||
- Optimize memory usage
|
||||
- Use appropriate data structures
|
||||
- Leverage GPU acceleration when possible
|
||||
|
||||
## Integration Examples
|
||||
|
||||
### 1. Complex Animation
|
||||
```python
|
||||
from manimlib.utils.rate_functions import smooth
|
||||
from manimlib.utils.space_ops import rotation_matrix
|
||||
from manimlib.utils.bezier import interpolate_bezier
|
||||
|
||||
class ComplexAnimation(Scene):
|
||||
def construct(self):
|
||||
# Create a smooth path with bezier curves
|
||||
points = get_bezier_points(start, control1, control2, end)
|
||||
|
||||
# Apply rotation with smooth timing
|
||||
matrix = rotation_matrix(PI, axis=OUT)
|
||||
self.play(
|
||||
MoveAlongPath(object, points),
|
||||
ApplyMatrix(matrix, object),
|
||||
rate_func=smooth
|
||||
)
|
||||
```
|
||||
|
||||
### 2. Resource Management
|
||||
```python
|
||||
from manimlib.utils.file_ops import find_file
|
||||
from manimlib.utils.images import get_full_raster_image_path
|
||||
from manimlib.utils.sounds import get_full_sound_file_path
|
||||
|
||||
class ResourceExample(Scene):
|
||||
def construct(self):
|
||||
# Load and display an image
|
||||
image_path = get_full_raster_image_path("example.png")
|
||||
image = ImageMobject(image_path)
|
||||
|
||||
# Add sound
|
||||
sound_path = get_full_sound_file_path("effect.wav")
|
||||
self.add_sound(sound_path)
|
||||
```
|
||||
|
||||
## Resources
|
||||
|
||||
- [NumPy Documentation](https://numpy.org/doc/)
|
||||
- [Python Path Operations](https://docs.python.org/3/library/pathlib.html)
|
||||
- [OpenGL Shader Language](https://www.khronos.org/opengl/wiki/Core_Language_(GLSL))
|
||||
- [Color Theory Guide](https://www.w3.org/TR/css-color-4/)
|
||||
- [Bezier Curve Reference](https://pomax.github.io/bezierinfo/)
|
Loading…
Add table
Reference in a new issue