File size: 3,170 Bytes
fdb3169
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
"""
SDF Renderer Module
Visualization utilities for SDF fields and zero-level sets.
"""

import torch
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from typing import Tuple, Optional


class SDFRenderer:
    """
    Renderer for SDF fields and zero-level sets.
    Creates visualization grids and renders SDF values.
    """
    
    def __init__(self, resolution: int = 512, 
                 xlim: Tuple[float, float] = (-5, 5),
                 ylim: Tuple[float, float] = (-5, 5)):
        self.resolution = resolution
        self.xlim = xlim
        self.ylim = ylim
        
        # Create evaluation grid
        x = torch.linspace(xlim[0], xlim[1], resolution)
        y = torch.linspace(ylim[0], ylim[1], resolution)
        self.xx, self.yy = torch.meshgrid(x, y, indexing='xy')
        self.grid = torch.stack([self.xx, self.yy], dim=-1)
        
        # Custom colormap for SDF visualization
        self.sdf_cmap = LinearSegmentedColormap.from_list(
            'sdf', ['#2E86AB', '#FFFFFF', '#E74C3C'], N=256
        )
    
    def render_sdf_field(self, sdf, ax: plt.Axes, 
                        show_field: bool = True,
                        field_alpha: float = 0.3) -> np.ndarray:
        """
        Render SDF field and zero-level set.
        
        Args:
            sdf: SDF primitive to render
            ax: Matplotlib axes
            show_field: Show background SDF field
            field_alpha: Alpha for background field
            
        Returns:
            SDF values as numpy array
        """
        with torch.no_grad():
            # Evaluate SDF on grid
            grid_flat = self.grid.reshape(-1, 2)
            distances = sdf(grid_flat).reshape(self.resolution, self.resolution)
            distances_np = distances.cpu().numpy()
        
        # Show SDF field as background
        if show_field:
            max_val = min(np.abs(distances_np).max(), 10)
            ax.contourf(self.xx.numpy(), self.yy.numpy(), distances_np,
                       levels=50, cmap=self.sdf_cmap, alpha=field_alpha,
                       vmin=-max_val, vmax=max_val)
        
        # Draw zero-level set (the curve)
        ax.contour(self.xx.numpy(), self.yy.numpy(), distances_np,
                  levels=[0], colors=['#2E86AB'], linewidths=2.5)
        
        return distances_np
    
    def render_multiple(self, sdfs: list, ax: plt.Axes,
                       colors: Optional[list] = None) -> None:
        """Render multiple SDFs on the same axes."""
        if colors is None:
            colors = ['#2E86AB', '#E74C3C', '#27AE60', '#9B59B6', '#F39C12']
        
        with torch.no_grad():
            grid_flat = self.grid.reshape(-1, 2)
            
            for i, sdf in enumerate(sdfs):
                distances = sdf(grid_flat).reshape(self.resolution, self.resolution)
                distances_np = distances.cpu().numpy()
                
                color = colors[i % len(colors)]
                ax.contour(self.xx.numpy(), self.yy.numpy(), distances_np,
                          levels=[0], colors=[color], linewidths=2.5)