Pelo que você descreveu, o problema parece estar relacionado à forma como as coordenadas de textura estão sendo mapeadas ou possivelmente à maneira como a rotação está sendo aplicada e acumulada. Vou abordar ambos os pontos para ajudá-lo a resolver o problema.
1. Mapeamento das Coordenadas de Textura
No seu código, você está mapeando as coordenadas UV multiplicando u e v pelas dimensões da textura:
double u = t.dx * texture.width; // Map U coordinate by texture width
double v = t.dy * texture.height; // Map V coordinate by texture height
Problema: O ImageShader do Flutter espera que as coordenadas de textura (u e v) estejam normalizadas entre 0.0 e 1.0. Multiplicar u e v pelas dimensões da textura (texture.width e texture.height) envia valores muito maiores que 1.0, o que pode causar comportamento inesperado com o TileMode.clamp, resultando em corte indesejado da textura e possivelmente afetando a rotação percebida.
Solução: Mantenha as coordenadas UV normalizadas entre 0.0 e 1.0 e ajuste a matriz de transformação do shader conforme necessário. Isso garante que a textura seja aplicada corretamente sem distorções ou cortes inesperados.
Alterações no Código:
// Remova a multiplicação pelas dimensões da textura
double u = t.dx; // Coordenada U normalizada
double v = t.dy; // Coordenada V normalizada
renderTexcoords[i * 2] = u; // U
renderTexcoords[i * 2 + 1] = v; // V
Além disso, ajuste a matriz do shader se necessário (por exemplo, para aplicar escalonamento ou rotação à textura). No entanto, para um mapeamento básico, você pode usar a matriz identidade:
final Float64List matrix4 = Matrix4.identity().storage;
final paint = Paint()
..shader = ImageShader(
texture,
TileMode.clamp,
TileMode.clamp,
matrix4,
);
2. Gestão da Rotação
Outra possível causa do problema está na forma como o ângulo de rotação está sendo tratado. Incrementar continuamente o ângulo sem limitar pode levar a problemas de precisão em ângulos muito grandes.
Problema: O ângulo está sendo incrementado indefinidamente, o que pode levar a comportamentos inesperados após múltiplas rotações completas (por exemplo, após 360 graus ou 2π radianos).
Solução: Utilize o operador módulo para manter o ângulo dentro de um intervalo específico (por exemplo, 0 a 2π radianos). Além disso, certifique-se de que está lidando com unidades de medida consistentes (radianos vs. graus).
Alterações no Código:
No método rotate, ajuste o incremento do ângulo para mantê-lo dentro de 0 a 2π radianos:
void rotate() {
Timer.periodic(Duration(milliseconds: 16), (timer) {
setState(() {
angle += 0.5; // Supondo que este valor esteja em graus
if (angle >= 360.0) {
angle -= 360.0;
}
});
});
}
Ou, se você preferir trabalhar diretamente com radianos:
void rotate() {
Timer.periodic(Duration(milliseconds: 16), (timer) {
setState(() {
angle += 0.0087; // Aproximadamente 0.5 graus em radianos
angle %= 2 * math.pi; // Mantém o ângulo entre 0 e 2π
});
});
}
Nota Importante: Certifique-se de que a função radians está corretamente convertendo de graus para radianos. Se estiver usando o pacote vector_math, a função correta é degrees para converter radianos para graus e vice-versa. Confira se o incremento de angle está de acordo com a unidade esperada.
3. Otimização na Geração da Esfera
Atualmente, a geometria da esfera está sendo gerada toda vez que o SpherePainter é construído, o que é ineficiente e pode levar a problemas de desempenho. Além disso, reter globalmente os dados da esfera evita recomputações desnecessárias.
Solução: Gere a geometria da esfera uma vez e reutilize-a. Você pode armazenar os dados da esfera fora do CustomPainter ou usar mecanismos de caching.
Exemplo de Implementação:
class SpherePainter extends CustomPainter {
final ui.Image texture;
final double angle;
static List<Vector3>? cachedVertices;
static List<Offset>? cachedTexcoords;
static List<List<int>>? cachedIndices;
final Matrix4 transform = Matrix4.identity();
final Vector3 position = Vector3.zero();
final Vector3 rotation = Vector3.zero();
final Vector3 scale = Vector3(1, 1, 1);
static const double radius = 100;
static const int latSegments = 100;
static const int lonSegments = 100;
SpherePainter(this.texture, this.angle) {
if (cachedVertices == null || cachedTexcoords == null || cachedIndices == null) {
_generateSphere();
}
}
void _generateSphere() {
cachedVertices = List<Vector3>.filled(
(latSegments + 1) * (lonSegments + 1), Vector3.zero());
cachedTexcoords =
List<Offset>.filled((latSegments + 1) * (lonSegments + 1), Offset.zero);
cachedIndices = [];
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;
cachedVertices![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
);
cachedTexcoords![i] = Offset(u, v); // Normalized UV coordinates
i++;
}
}
// Populate triangle indices
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;
cachedIndices!.add([current, below, next]); // Lower left triangle
cachedIndices!.add([next, below, belowNext]); // Upper right triangle
}
}
}
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(cachedVertices!.length * 2);
final Float32List renderTexcoords = Float32List(cachedTexcoords!.length * 2);
for (int i = 0; i < cachedVertices!.length; i++) {
final Vector4 transformedVertex = transform.transformed(
Vector4(cachedVertices![i].x, cachedVertices![i].y, cachedVertices![i].z, 1.0));
positions[i * 2] = transformedVertex.x / transformedVertex.w; // X
positions[i * 2 + 1] = transformedVertex.y / transformedVertex.w; // Y
Offset t = cachedTexcoords![i];
// Utilize coordenadas UV normalizadas
double u = t.dx; // Coordenada U normalizada
double v = t.dy; // Coordenada V normalizada
renderTexcoords[i * 2] = u; // U
renderTexcoords[i * 2 + 1] = v; // V
}
final Uint16List indexBuffer = Uint16List(cachedIndices!.length * 3);
int indexCount = 0;
for (var triangle in cachedIndices!) {
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;
}
}
4. Considerações Adicionais
-
Uso de Quaternions vs. Ângulos Euler: O uso de ângulos Euler pode levar a gimbal lock e outros problemas de interpolação de rotação. Considere usar quaternions para representar e acumular rotações de forma mais robusta.
-
Precisão de Ponto Flutuante: Se o ângulo estiver crescendo indefinidamente, pode eventualmente levar a erros de precisão. Manter o ângulo dentro de um intervalo específico ajuda a mitigar isso.
-
Performance: Embora a otimização acima ajude, renderizar uma esfera com alta resolução (100 segmentos latitudinais e longitudinais) pode ser computacionalmente intensivo no Flutter. Considere reduzir a quantidade de segmentos ou usar técnicas de otimização como Level of Detail (LOD) se necessário.
5. Exemplo Completo com Ajustes
Aqui está uma versão ajustada do seu código incorporando as sugestões mencionadas:
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;
Timer? timer;
@override
void initState() {
super.initState();
loadImageFromAsset('assets/1.jpg');
rotate();
}
@override
void dispose() {
timer?.cancel();
super.dispose();
}
void rotate() {
timer = Timer.periodic(Duration(milliseconds: 16), (timer) {
setState(() {
angle += 0.5;
if (angle >= 360.0) {
angle -= 360.0;
}
});
});
}
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(300, 300), // Aumentei o tamanho para melhor visualização
painter: SpherePainter(texture!, angle),
);
}
}
class SpherePainter extends CustomPainter {
final ui.Image texture;
final double angle;
static List<Vector3>? cachedVertices;
static List<Offset>? cachedTexcoords;
static List<List<int>>? cachedIndices;
final Matrix4 transform = Matrix4.identity();
final Vector3 position = Vector3.zero();
final Vector3 rotation = Vector3.zero();
final Vector3 scale = Vector3(1, 1, 1);
static const double radius = 100;
static const int latSegments = 40; // Reduzi para melhorar a performance
static const int lonSegments = 40;
SpherePainter(this.texture, this.angle) {
if (cachedVertices == null || cachedTexcoords == null || cachedIndices == null) {
_generateSphere();
}
}
void _generateSphere() {
cachedVertices = List<Vector3>.filled(
(latSegments + 1) * (lonSegments + 1), Vector3.zero());
cachedTexcoords =
List<Offset>.filled((latSegments + 1) * (lonSegments + 1), Offset.zero);
cachedIndices = [];
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;
cachedVertices![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
);
cachedTexcoords![i] = Offset(u, v); // Normalized UV coordinates
i++;
}
}
// Populate triangle indices
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;
cachedIndices!.add([current, below, next]); // Lower left triangle
cachedIndices!.add([next, below, belowNext]); // Upper right triangle
}
}
}
void updateTransform() {
// Converte o ângulo para radianos
final double rad = radians(angle);
final Matrix4 m = Matrix4.identity()
..rotateX(rad)
..rotateY(rad);
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(cachedVertices!.length * 2);
final Float32List renderTexcoords = Float32List(cachedTexcoords!.length * 2);
for (int i = 0; i < cachedVertices!.length; i++) {
final Vector4 transformedVertex = transform.transformed(
Vector4(cachedVertices![i].x, cachedVertices![i].y, cachedVertices![i].z, 1.0));
positions[i * 2] = transformedVertex.x / transformedVertex.w; // X
positions[i * 2 + 1] = transformedVertex.y / transformedVertex.w; // Y
Offset t = cachedTexcoords![i];
// Coordenadas UV normalizadas
double u = t.dx;
double v = t.dy;
renderTexcoords[i * 2] = u; // U
renderTexcoords[i * 2 + 1] = v; // V
}
final Uint16List indexBuffer = Uint16List(cachedIndices!.length * 3);
int indexCount = 0;
for (var triangle in cachedIndices!) {
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;
}
}
6. Resumo das Alterações Realizadas
-
Mapeamento de Textura Normalizado: Removido o escalonamento das coordenadas UV pelas dimensões da textura para manter u e v entre 0.0 e 1.0.
-
Gestão do Ângulo de Rotação: Implementado um controle que mantém o angle dentro de 0 a 360 graus para evitar incrementos infinitos que podem causar erros de precisão.
-
Cache da Geometria da Esfera: A geometria da esfera (vertices, texcoords, indices) é gerada uma única vez e reutilizada nas renderizações subsequentes para melhorar a performance.
-
Redução dos Segmentos da Esfera: Reduzido o número de segmentos latitudinais e longitudinais para 40 cada para melhorar a performance sem comprometer significativamente a qualidade visual.
-
Tratamento Consistente de Radianos: Garantida a conversão correta dos ângulos de graus para radianos antes de aplicar as rotações no Matrix4.
7. Conclusão
Essas mudanças devem resolver o problema de inversão de rotação que você estava enfrentando e também otimizar a performance da sua aplicação. Certifique-se de testar cada alteração de forma incremental para verificar se o comportamento desejado está sendo alcançado.
Se o problema persistir mesmo após essas alterações, recomendo depurar os valores de angle e as transformações aplicadas para identificar onde exatamente a inversão está ocorrendo. Além disso, considere utilizar ferramentas de depuração gráfica para visualizar melhor como os vértices estão sendo transformados.
Se tiver mais dúvidas ou precisar de assistência adicional, sinta-se à vontade para perguntar!