Para corrigir seu código referente às coordenadas de textura, é essencial garantir que as coordenadas de textura (u e v) estejam normalizadas no intervalo de [0, 1]. Além disso, a coordenação v geralmente precisa ser invertida para corresponder corretamente à direção vertical das texturas.
No seu código atual, você está multiplicando as coordenadas de textura (t.dx e t.dy) pelas dimensões da textura (texture.width e texture.height). Isso pode causar discrepâncias porque o ImageShader do Flutter espera coordenadas de textura normalizadas, não coordenadas em pixels.
Passos para corrigir o código:
-
Normalizar as coordenadas de textura:
u (coordenada horizontal): Deve permanecer no intervalo [0, 1], portanto, não é necessário multiplicar por texture.width.
v (coordenada vertical): Deve ser invertido e mantido no intervalo [0, 1]. A inversão é feita subtraindo t.dy de 1.0.
-
Remover a multiplicação por texture.width e texture.height:
- Isso garante que as coordenadas de textura permaneçam normalizadas.
-
Atualizar a conversão das coordenadas de textura dentro do loop:
- Utilize as coordenadas normalizadas sem escala adicional.
Aqui está o código corrigido com base nas alterações mencionadas:
Código Corrigido
// Dentro do método paint do SpherePainter
void paint(Canvas canvas, Size size) {
canvas.translate(size.width / 2, size.height / 2);
rotation.setValues(0, angle, angle);
updateTransform();
final Float32List positions = Float32List(vertices.length * 2);
final Float32List renderTexcoords = Float32List(texcoords.length * 2);
// Assumindo que `renderTexcoords` já está inicializado e tem tamanho suficiente
final int texcoordCount = texcoords.length;
if (texcoords.length == texcoordCount) {
for (int i = 0; i < texcoordCount; i++) {
final Offset t = texcoords[i];
// **Correção: Usar coordenadas normalizadas e inverter V**
double u = t.dx; // Coordenada U normalizada [0,1]
double v = 1.0 - t.dy; // Coordenada V invertida e normalizada [0,1]
// Calcula os índices para renderizar as coordenadas de textura
final int xIndex = i * 2; // U
final int yIndex = xIndex + 1; // V
renderTexcoords[xIndex] = u; // Aplica U normalizado
renderTexcoords[yIndex] = v; // Aplica V normalizado e invertido
}
} else {
// Se as coordenadas de textura não forem válidas, zere-as
for (int i = 0; i < texcoordCount; i++) {
final int xIndex = i * 2;
final int yIndex = xIndex + 1;
renderTexcoords[xIndex] = 0; // Zera U
renderTexcoords[yIndex] = 0; // Zera V
}
}
final Uint16List indexBuffer = Uint16List(indices.length * 3);
int indexCount = 0;
for (var triangle in indices) {
indexBuffer[indexCount++] = triangle[0];
indexBuffer[indexCount++] = triangle[1];
indexBuffer[indexCount++] = triangle[2];
}
final verticesData = Vertices.raw(
VertexMode.triangles,
positions,
textureCoordinates: renderTexcoords,
indices: indexBuffer,
);
final Float64List matrix4 = Matrix4.identity().storage;
final paint = Paint()
..shader = ImageShader(
texture,
TileMode.clamp,
TileMode.clamp,
matrix4,
);
canvas.drawVertices(verticesData, BlendMode.srcOver, paint);
}
Explicações Detalhadas
-
Normalização das Coordenadas de Textura:
- As coordenadas de textura
u e v devem estar no intervalo de [0, 1]. Isso garante que a textura seja mapeada corretamente sobre o modelo 3D.
u = t.dx;: Mantém a coordenada horizontal no intervalo normalizado.
v = 1.0 - t.dy;: Inverte a coordenada vertical e a mantém no intervalo normalizado, já que muitas vezes as texturas têm a origem no canto inferior esquerdo ou superior esquerdo, dependendo da convenção.
-
Remoção da Multiplicação por Largura e Altura:
- Antes:
double u = t.dx * texture.width;
- Depois:
double u = t.dx;
- Antes:
double v = t.dy * texture.height;
- Depois:
double v = 1.0 - t.dy;
- Multiplicar por
texture.width e texture.height não é necessário porque o ImageShader espera coordenadas de textura normalizadas.
-
Atualização do Shader:
- O
ImageShader está configurado com uma matriz identidade (Matrix4.identity().storage), o que significa que não há transformação adicional nas coordenadas de textura.
- Garantir que as coordenadas de textura estejam normalizadas permite que o
ImageShader mapeie corretamente a textura sobre o objeto.
-
Verificação de Texcoords Válidos:
- O código verifica se
texcoords.length == texcoordCount para garantir que as coordenadas de textura sejam válidas antes de aplicá-las. Caso contrário, ele define todas as coordenadas de textura como zero, evitando possíveis erros de renderização.
Considerações Adicionais
-
Performance:
- Se o número de segmentos da esfera (
latSegments e lonSegments) for alto, isso pode impactar a performance. Certifique-se de ajustar esses valores conforme necessário para o seu caso de uso.
-
Texturas Subdivididas:
- Se você estiver usando apenas uma parte da textura (sub-regiões), será necessário ajustar
u e v de acordo com as coordenadas da sub-região.
-
Debugging Visual:
- Para garantir que as texturas estejam sendo mapeadas corretamente, você pode aplicar texturas de teste com padrões visíveis para verificar a orientação e mapeamento das coordenadas.
Código Completo Com Correções Aplicadas
Aqui está o seu código completo com as correções aplicadas nas coordenadas de textura:
import 'dart:async';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:vector_math/vector_math_64.dart' hide Colors;
import 'dart:math' as math;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('3D Sphere with Fixed Texture')),
body: Center(child: SphereWidget()),
backgroundColor: const Color.fromARGB(255, 52, 13, 245),
),
);
}
}
class SphereWidget extends StatefulWidget {
@override
_SphereWidgetState createState() => _SphereWidgetState();
}
class _SphereWidgetState extends State<SphereWidget> {
double angle = 0;
ui.Image? texture;
@override
void initState() {
super.initState();
loadImageFromAsset('assets/nova.png');
rotate();
}
void rotate() {
Timer.periodic(Duration(milliseconds: 16), (timer) {
setState(() {
angle += 0.5;
});
});
}
Future<void> loadImageFromAsset(String path) async {
final completer = Completer<ui.Image>();
final image = AssetImage(path);
image.resolve(ImageConfiguration()).addListener(
ImageStreamListener((info, _) {
completer.complete(info.image);
}),
);
texture = await completer.future;
setState(() {});
}
@override
Widget build(BuildContext context) {
if (texture == null) {
return Container();
}
return CustomPaint(
size: const Size(200, 200), // Ajuste o tamanho da esfera conforme necessário
painter: SpherePainter(texture!, angle),
);
}
}
class SpherePainter extends CustomPainter {
final ui.Image texture;
final double angle;
final Matrix4 transform = Matrix4.identity();
final Vector3 position = Vector3.zero();
final Vector3 rotation = Vector3.zero();
final Vector3 scale = Vector3(1, 1, 1);
final double radius = 100;
final int latSegments = 100;
final int lonSegments = 100;
late List<Vector3> vertices;
late List<Offset> texcoords;
late List<List<int>> indices;
SpherePainter(this.texture, this.angle) {
vertices = List<Vector3>.filled(
(latSegments + 1) * (lonSegments + 1), Vector3.zero());
texcoords =
List<Offset>.filled((latSegments + 1) * (lonSegments + 1), Offset.zero);
indices = [];
_generateSphere(); // Inicializa a geometria da esfera apenas uma vez
}
void _generateSphere() {
int i = 0;
for (int y = 0; y <= latSegments; ++y) {
final double v = y / latSegments;
final double sv = math.sin(v * math.pi);
final double cv = math.cos(v * math.pi);
for (int x = 0; x <= lonSegments; ++x) {
final double u = x / lonSegments;
vertices[i] = Vector3(
radius * math.cos(u * math.pi * 2.0) * sv, // X
radius * cv, // Y
radius * math.sin(u * math.pi * 2.0) * sv, // Z
);
texcoords[i] = Offset(u, v); // Coordenadas UV normalizadas
i++;
}
}
// Popula os índices dos triângulos
for (int y = 0; y < latSegments; y++) {
final int base1 = (lonSegments + 1) * y;
final int base2 = (lonSegments + 1) * (y + 1);
for (int x = 0; x < lonSegments; x++) {
final int current = base1 + x;
final int next = base1 + x + 1;
final int below = base2 + x;
final int belowNext = base2 + x + 1;
indices.add([current, below, next]); // Triângulo inferior esquerdo
indices.add([next, below, belowNext]); // Triângulo superior direito
}
}
}
void updateTransform() {
final Matrix4 m = Matrix4.compose(
position,
Quaternion.euler(
radians(rotation.x), radians(rotation.y), radians(rotation.z)),
scale);
transform.setFrom(m);
}
@override
void paint(Canvas canvas, Size size) {
canvas.translate(size.width / 2, size.height / 2);
rotation.setValues(0, angle, angle);
updateTransform();
final Float32List positions = Float32List(vertices.length * 2);
final Float32List renderTexcoords = Float32List(texcoords.length * 2);
// Atualização das coordenadas de textura corrigidas
final int texcoordCount = texcoords.length;
if (texcoords.length == texcoordCount) {
for (int i = 0; i < texcoordCount; i++) {
final Offset t = texcoords[i];
// **Correção Aplicada Aqui**
double u = t.dx; // Coordenada U normalizada [0,1]
double v = 1.0 - t.dy; // Coordenada V invertida e normalizada [0,1]
final int xIndex = i * 2; // U
final int yIndex = xIndex + 1; // V
renderTexcoords[xIndex] = u; // Aplica U normalizado
renderTexcoords[yIndex] = v; // Aplica V normalizado e invertido
}
} else {
for (int i = 0; i < texcoordCount; i++) {
final int xIndex = i * 2;
final int yIndex = xIndex + 1;
renderTexcoords[xIndex] = 0; // Zera U
renderTexcoords[yIndex] = 0; // Zera V
}
}
final Uint16List indexBuffer = Uint16List(indices.length * 3);
int indexCount = 0;
for (var triangle in indices) {
indexBuffer[indexCount++] = triangle[0];
indexBuffer[indexCount++] = triangle[1];
indexBuffer[indexCount++] = triangle[2];
}
final verticesData = Vertices.raw(
VertexMode.triangles,
positions,
textureCoordinates: renderTexcoords,
indices: indexBuffer,
);
final Float64List matrix4 = Matrix4.identity().storage;
final paint = Paint()
..shader = ImageShader(
texture,
TileMode.clamp,
TileMode.clamp,
matrix4,
);
canvas.drawVertices(verticesData, BlendMode.srcOver, paint);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return true;
}
}
Resumo
- Normalização das Coordenadas: Mantenha
u e v no intervalo [0, 1] para garantir que o ImageShader funcione conforme esperado.
- Inversão da Coordenada V: Inverta
v para alinhar corretamente a textura com a esfera.
- Remoção de Escalas Desnecessárias: Evite multiplicar as coordenadas de textura por
texture.width e texture.height, pois isso pode causar distorções.
- Verificação de Validade das Coordenadas: Assegure-se de que as coordenadas de textura sejam válidas antes de aplicá-las.
Com essas correções, sua esfera texturizada deve renderizar corretamente com a textura aplicada de forma apropriada.