# Text Texture Generator - Blender Addon

A modern Blender addon that generates image textures from text with extensive customization options and advanced features.

## Features

- **Text Input & Processing**:

  - Enter any text to convert into a texture (up to 1024 characters)
  - Prepend and append text support with customizable margins
  - Horizontal and vertical text layout options
  - Text fitting system with automatic font size adjustment

- **Advanced Positioning System**:

  - 9-point anchor positioning system (top-left, center, bottom-right, etc.)
  - Manual coordinate positioning with percentage or pixel units
  - Fine-tuning offsets for precise placement
  - Canvas constraint options

- **Font System**:

  - System font detection and selection
  - Custom font file support (.ttf, .otf)
  - Font validation with mixed-case support testing
  - Adjustable font size (8-500px)
  - Text alignment (left, center, right)

- **Image Overlay System**:

  - Multiple image overlays with individual controls
  - Three positioning modes: Absolute, Prepend, Append
  - Per-overlay scaling, rotation, and z-index control
  - Image spacing and sequencing for complex layouts
  - Enable/disable individual overlays
  - SVG overlays automatically rasterized to preserve sharpness across texture sizes

- **Color & Transparency**:

  - RGBA text color picker with full alpha support
  - RGBA background color picker
  - Transparent background option
  - Preview background options (transparent, solid color, gradient)

- **Normal Map Generation**:

  - Automatic normal map creation from text alpha channel
  - Adjustable strength, blur radius, and invert options
  - Proper colorspace handling for normal maps

- **Advanced Shader Generation**:

  - Complete material shader creation
  - Multiple shader types: Principled BSDF, Emission, Transparent
  - Light path control: disable shadows, reflections, backfacing
  - Auto-assignment to selected objects
  - Normal map integration in shaders

- **Preset Management System**:

  - Simplified two-tier storage: Persistent File (default) + Blend File (optional)
  - Unified preset list with clear storage indicators (🏠/📄)
  - Presets travel with .blend files when "Save with .blend file" is checked
  - Import/export functionality for backup and sharing
  - Automatic migration from legacy three-tier system
  - Conflict resolution with blend file presets taking priority

- **Preview System**:

  - Full-resolution live preview generation
  - Zoomable preview window with Image Editor integration
  - Multiple preview background options
  - Real-time updates on property changes

- **Blender Integration**:
  - Works in Shader Editor, 3D Viewport, and Properties panel
  - Automatic texture node creation with proper connections
  - Generated textures are packed into the .blend file
  - Menu integration across multiple editors

## Installation

### Method 1: Modern Blender 4.0+ (Recommended)

1. Download the addon files (`blender_manifest.toml` and `__init__.py`)
2. Create a folder named `text_texture_generator`
3. Place both files in this folder
4. In Blender, go to `Edit > Preferences > Add-ons`
5. Click `Install from Disk` and select the folder
6. Enable the "Text Texture Generator" addon

### Method 2: Traditional Installation

1. Download the `__init__.py` file
2. In Blender, go to `Edit > Preferences > Add-ons`
3. Click `Install from Disk` and select the `__init__.py` file
4. Enable the "Text Texture Generator" addon

## Usage

### In Shader Editor:

1. Select a material with nodes enabled
2. Open the Shader Editor
3. Press `N` to open the side panel
4. Navigate to the "Text Texture" tab
5. Configure your text and settings
6. Click "Generate Texture"
7. The texture node will be automatically added to your material

### In 3D Viewport:

1. Press `N` to open the side panel
2. Navigate to the "Text Texture" tab
3. Configure your text and settings
4. Click "Generate Texture"
5. Find your texture in the Image Editor or use it in materials

## Settings Reference

### Text Settings

- **Main Text**: Primary text to render (up to 1024 characters)
- **Prepend Text**: Text to add before main text (up to 512 characters)
- **Append Text**: Text to add after main text (up to 512 characters)
- **Layout**: Horizontal or vertical arrangement of text elements
- **Margins**: Percentage-based spacing between text elements

### Font Settings

- **System Fonts**: Auto-detected system fonts with validation
- **Custom Font**: Load external .ttf/.otf font files
- **Font Size**: Size in pixels (8-500px)
- **Text Alignment**: Left, center, right alignment options

### Positioning & Layout

- **Position Mode**: Preset anchor points or manual coordinates
- **Anchor Points**: 9-point positioning grid (top-left to bottom-right)
- **Margins**: Percentage-based margins from canvas edges (0-50%)
- **Offsets**: Pixel-perfect fine-tuning (-200 to +200px)
- **Manual Positioning**: Direct X,Y coordinates in percentage or pixels
- **Canvas Constraints**: Keep text within canvas bounds

### Text Fitting

- **Auto-Sizing**: Automatically adjust font size to fit canvas
- **Fitting Modes**: Fit width, height, both, or contain within bounds
- **Size Limits**: Minimum and maximum font size constraints
- **Fitting Margin**: Percentage margin for auto-fitting calculations

### Texture Settings

- **Dimensions**: Canvas size in pixels (64x64 and up; practical limit is your Blender setup)
- **Text Color**: RGBA color picker with full alpha support
- **Background**: Transparent or solid color with RGBA control

### Image Overlays

- **Multiple Images**: Add unlimited image overlays
- **Positioning Modes**: Absolute coordinates, prepend, or append to text
- **Transform Controls**: Scale (0.1-5.0x), rotation (360°), z-index layering
- **Spacing Controls**: Configurable spacing between images and text
- **Sequence Control**: Order overlays in prepend/append modes
- **SVG Support**: Vector overlays (.svg) are rasterized on demand and cached for reuse

Cached raster images are stored under Blender's user config directory in `text_texture_generator/overlay_cache`.

### Normal Maps

- **Auto-Generation**: Create normal maps from text alpha channel
- **Strength Control**: Adjust normal map intensity (0.1-5.0)
- **Blur Radius**: Smooth normal map edges (0-10px)
- **Invert Option**: Switch between emboss and deboss effects

### Shader Generation

- **Shader Types**: Principled BSDF, Emission, Transparent materials
- **Texture Connections**: Base color, emission, or alpha channels
- **Light Path Controls**: Disable shadows, reflections, or backfacing
- **Auto-Assignment**: Automatically apply materials to selected objects
- **Normal Map Integration**: Automatic normal map nodes and connections

### Preview Options

- **Live Preview**: Real-time texture generation and display
- **Preview Size**: Adjustable preview resolution (128-2048px)
- **Background Display**: Transparent, solid color, or gradient options
- **Zoom Controls**: Open preview in zoomable Image Editor window

## System Requirements

- Blender 4.0.0 or newer
- Python 3.10+ (included with Blender)
- Pillow library (>=10.0.0, automatically installed via pip)

## Font Support

The addon features intelligent font detection and validation:

### System Font Detection

- Automatically scans system font directories
- Supports .ttf, .ttc, .otf, and .dfont files
- Mixed-case rendering validation for quality assurance
- Platform-specific fallback fonts with guaranteed compatibility

### Windows Fallback Fonts

- Arial, Calibri, Segoe UI, Verdana, Tahoma, Times, Trebuchet MS

### macOS Fallback Fonts

- Helvetica, Arial, Times, Avenir, Geneva, Palatino

### Linux Fallback Fonts

- Liberation Sans, DejaVu Sans, Ubuntu, Noto Sans, Lato, Open Sans

### Custom Fonts

- Load any .ttf or .otf font file
- Automatic validation for mixed-case support
- Error handling and fallback for unsupported fonts

## Dependencies

The addon bundles and automatically installs its dependencies when needed:

- **Pillow** (>=10.0.0): Image generation and text rendering.
- **CairoSVG** (>=2.7.0): Rasterizes SVG overlays using the bundled wheel set for macOS and Linux (installs on first SVG use).

## Troubleshooting

### Common Issues

1. **"Failed to generate texture" error**:

   - Ensure Pillow is installed (addon does this automatically)
   - Check that your text isn't empty
   - Verify texture dimensions are within limits

2. **Font not displaying correctly**:

   - Try using "Default" font option
   - Some system fonts may not be available
   - Custom font paths vary by system

3. **Texture appears in wrong location**:
   - In Shader Editor: Ensure you have a material selected
   - Check the generated image in the Image Editor
   - Look for the texture in `bpy.data.images`

### Performance Notes

- Large textures (2048x2048+) may take longer to generate
- Very long text strings may affect performance
- Generated textures are stored in memory and packed with the .blend file

## Preset System

The addon features a streamlined two-tier preset system designed for simplicity and reliability:

### Storage Locations (Priority Order)

1. **Blend File Storage** (Higher Priority)

   - Presets stored in scene custom properties
   - Travel with your .blend file automatically
   - Perfect for project-specific presets
   - Display with 📄 indicator in UI

2. **Persistent File Storage** (Default Storage)

   - Survives addon updates and Blender upgrades
   - Stored in Blender's user config directory (`~/.config/blender/text_texture_generator/presets/`)
   - Shared across all blend files
   - Display with 🏠 indicator in UI

### Key Features

- **Simplified UI**: Single unified preset list with clear storage indicators
- **Easy Storage Selection**: Simple "Save with .blend file" checkbox controls destination
- **Priority System**: Blend file presets automatically override persistent ones with same name
- **Auto-Migration**: Seamlessly migrates old three-tier presets to new system
- **Import/Export**: Backup and share presets across installations
- **User-Friendly Messages**: Clear, non-technical confirmation messages

### How to Use

- **Default Behavior**: Presets save to persistent storage (🏠) - survives addon updates
- **Project-Specific**: Check "Save with .blend file" to save with your project (📄)
- **Loading**: All presets appear in one list, blend file presets take priority
- **Migration**: Old presets are automatically migrated on first use

## Build System

### File Exclusion Strategy

The addon uses a sophisticated build-time file exclusion system instead of runtime feature flags, creating genuinely different versions:

#### Configuration Files:

- [`build/file_exclusions.json`](build/file_exclusions.json) - Defines which files are excluded from free builds
- [`scripts/build_addon.py`](scripts/build_addon.py) - Enhanced build script with intelligent exclusion logic
- [`build/sync_version.py`](build/sync_version.py) - Version synchronization without feature flag injection

#### Build Commands:

```bash
# Build free version
python3 scripts/build_addon.py --type free --version 1.0.0

# Build full version
python3 scripts/build_addon.py --type full --version 1.0.0

# Build both versions
python3 scripts/build_addon.py --type all --version 1.0.0
```

#### Exclusion Logic:

- **Free Version**: Physically excludes premium modules during build
- **Full Version**: Includes all source code modules
- **Smart Patterns**: Handles directory exclusions and glob patterns
- **Build Verification**: Shows excluded/included file counts and sizes

#### Benefits:

- **Security**: Users cannot access premium source code
- **Clean Separation**: No runtime feature checking complexity
- **Genuine Differences**: 37% smaller free version package
- **Maintainability**: Single codebase with build-time differentiation

## Development

### File Structure

```
text_texture_generator/
├── build/                          # Build system
│   ├── build_addon.py             # Main build script with file exclusion
│   ├── file_exclusions.json       # File exclusion configuration
│   ├── sync_version.py            # Version synchronization
│   └── templates/                 # Build templates
├── src/                           # Source code
│   ├── blender_manifest.toml      # Blender 4.0+ manifest
│   ├── __init__.py               # Main addon code (~5000 lines)
│   ├── core/                     # Core functionality
│   │   ├── generation_engine.py  # Text rendering engine
│   │   ├── normal_maps.py        # Normal map generation (Premium)
│   │   ├── text_fitting.py       # Text fitting algorithms
│   │   └── text_processor.py     # Text processing utilities
│   ├── operators/                # Blender operators
│   │   ├── generation_ops.py     # Core generation operations
│   │   ├── preset_ops.py         # Preset operations (Premium)
│   │   └── utility_ops.py        # Utility operations (Premium)
│   ├── ui/                       # User interface
│   │   ├── panels.py             # UI panels
│   │   └── preview.py            # Live preview system
│   ├── properties/               # Property definitions
│   ├── presets/                  # Preset management (Premium)
│   └── utils/                    # Utility functions
├── marketing/                     # Marketing materials
└── README.md                     # Documentation
```

### Code Organization

- **Utility Functions**: Font detection, validation, system compatibility
- **Preview Generation**: Real-time texture creation and display
- **Normal Map Generation**: Height-based normal map algorithms
- **Positioning System**: 9-point anchors, manual coordinates, constraints
- **Preset Management**: Three-tier storage with migration system
- **UI Components**: Collapsible sections, shared drawing functions
- **Operators**: 20+ operators for all addon functionality
- **Property Groups**: Comprehensive property system with validation

### Contributing

The addon is designed with modularity and extensibility in mind. Key areas for contribution:

- Additional shader types and material presets
- Extended image overlay positioning modes
- Font rendering improvements and compatibility
- UI/UX enhancements and workflow optimization
- Platform-specific font detection improvements

## License

GPL-3.0-or-later

## Author

Marc Mintel <marc@mintel.me>

## Changelog

### Version 2.3.2 (Current Code Version)

- Advanced positioning system with 9-point anchors and manual coordinates
- Text fitting with automatic font size adjustment and multiple modes
- Comprehensive image overlay system with absolute, prepend, and append positioning
- Normal map generation from text alpha channels with strength/blur controls
- Advanced shader generation with Principled BSDF, Emission, and Transparent types
- Light path controls for shadows, reflections, and backfacing geometry
- Simplified two-tier preset system (persistent + blend file) with priority handling
- Live preview with zoomable Image Editor integration and multiple backgrounds
- Prepend/append text support with horizontal/vertical layouts
- Custom font support with mixed-case validation and fallback systems
- Import/export functionality for preset backup and cross-installation sharing
- Enhanced error handling and user feedback throughout the interface

### Version 1.1.0

- Added a pro-only Create Plane button that generates a plane matching the texture aspect ratio, applies the new material automatically, and configures a Simple subdivision modifier by default.

### Version 1.0.0 (Current Release)

**New Build Strategy**: Redesigned version distribution from runtime feature flags to build-time file exclusion for better security and genuine feature separation.

#### Free Version Features:

- Core text texture generation with full quality output (up to 1024×1024 resolution)
- Basic UI and generation engine
- Font system with system font detection and custom font support
- Standard positioning and text fitting capabilities
- Essential properties and operators
- **File Count**: 17 files (37.9 KB package size)

#### Full Version Features (Additional):

- Normal map generation from text alpha channels
- Complete preset management system with simplified two-tier storage
- Advanced utility operations and batch processing
- Extended UI components and advanced styling options
- **File Count**: 23 files (60.1 KB package size)

#### Technical Implementation:

- **Physical File Exclusion**: Free version physically lacks premium modules rather than using runtime restrictions
- **Build-Time Separation**: Different source code in each version ensures users cannot access premium features
- **37% Size Difference**: Meaningful package size reduction demonstrates genuine feature separation
- **Clean Architecture**: No complex feature flag systems, cleaner codebase maintenance

**Excluded from Free Version**:

- `core/normal_maps.py` - Normal map generation algorithms
- `operators/preset_ops.py` - Preset management operations
- `operators/utility_ops.py` - Batch processing and utility functions
- `presets/` - Entire simplified preset storage and migration system

This approach ensures the free version provides genuine value while the full version offers substantially more capabilities through additional source code modules.
