deve-se seguir exatamente o modo de transformação e texturização do código alvo(claro que, esse código renderiza uma cena, queremos renderizar apenas um objeto, que é a esfera, então algumas partes não são tão necessárias assim:
código alvo para ser replicado:
void render(Canvas canvas, Size size) {
// check if texture needs to update
if (_needsUpdateTexture) {
_needsUpdateTexture = false;
_updateTexture();
}
code
// create render mesh from objects
final renderMesh = _makeRenderMesh();
_renderObject(renderMesh, world, Matrix4.identity(), camera.lookAtMatrix, camera.projectionMatrix);
// remove the culled faces and recreate list.
final List<Polygon> renderIndices = <Polygon>[];
final List<Polygon?> rawIndices = renderMesh.indices;
for (int i = 0; i < rawIndices.length; i++) {
final Polygon? p = rawIndices[i];
if (p != null) renderIndices.add(p);
}
if (renderIndices.length == 0) return;
// sort the faces by z
renderIndices.sort((Polygon a, Polygon b) {
// return b.sumOfZ.compareTo(a.sumOfZ);
final double az = a.sumOfZ;
final double bz = b.sumOfZ;
if (bz > az) return 1;
if (bz < az) return -1;
return 0;
});
// convert Polygon list to Uint16List
final int indexCount = renderIndices.length;
final Uint16List indices = Uint16List(indexCount * 3);
for (int i = 0; i < indexCount; i++) {
final int index0 = i * 3;
final int index1 = index0 + 1;
final int index2 = index0 + 2;
final Polygon polygon = renderIndices[i];
indices[index0] = polygon.vertex0;
indices[index1] = polygon.vertex1;
indices[index2] = polygon.vertex2;
}
final vertices = Vertices.raw(
VertexMode.triangles,
renderMesh.positions,
textureCoordinates: renderMesh.texture == null ? null : renderMesh.texcoords,
colors: renderMesh.colors,
indices: indices,
);
final paint = Paint();
if (renderMesh.texture != null) {
Float64List matrix4 = new Matrix4.identity().storage;
final shader = ImageShader(renderMesh.texture!, TileMode.mirror, TileMode.mirror, matrix4);
paint.shader = shader;
}
paint.blendMode = blendMode;
canvas.drawVertices(vertices, textureBlendMode, paint);
Assistant
}
void _renderObject(RenderMesh renderMesh, Object o, Matrix4 model, Matrix4 view, Matrix4 projection) {
if (!o.visiable) return;
model *= o.transform;
final Matrix4 transform = projection * view * model;
code
// apply transform and add vertices to renderMesh
final double viewportWidth = camera.viewportWidth;
final double viewportHeight = camera.viewportHeight;
final Float32List positions = renderMesh.positions;
final Float32List positionsZ = renderMesh.positionsZ;
final List<Vector3> vertices = o.mesh.vertices;
final int vertexOffset = renderMesh.vertexCount;
final int vertexCount = vertices.length;
final Vector4 v = Vector4.identity();
for (int i = 0; i < vertexCount; i++) {
// Conver Vector3 to Vector4
final Float64List storage3 = vertices[i].storage;
v.setValues(storage3[0], storage3[1], storage3[2], 1.0);
// apply "model => world => camera => perspective" transform
v.applyMatrix4(transform);
// transform from homonegenous coordinates to the normalized device coordinates,
final int xIndex = (vertexOffset + i) * 2;
final int yIndex = xIndex + 1;
final Float64List storage4 = v.storage;
final double w = storage4[3]; //v.w;
positions[xIndex] = storage4[0] / w; //v.x;
positions[yIndex] = storage4[1] / w; //v.y;
positionsZ[vertexOffset + i] = storage4[2] / w; //v.z;
}
renderMesh.vertexCount += vertexCount;
for (int i = 0; i < vertexCount; i++) {
final int x = (vertexOffset + i) * 2;
final int y = x + 1;
// remaps coordinates from [-1, 1] to the [0, viewport] space.
positions[x] = (1.0 + positions[x]) * viewportWidth / 2;
positions[y] = (1.0 - positions[y]) * viewportHeight / 2;
}
// add texture coordinates to renderMesh
final int texcoordCount = o.mesh.vertices.length;
final Float32List renderTexcoords = renderMesh.texcoords;
if (o.mesh.texture != null && o.mesh.texcoords.length == texcoordCount) {
final int imageWidth = o.mesh.textureRect.width.toInt();
final int imageHeight = o.mesh.textureRect.height.toInt();
final double imageLeft = o.mesh.textureRect.left;
final double imageTop = o.mesh.textureRect.top;
final List<Offset> texcoords = o.mesh.texcoords;
for (int i = 0; i < texcoordCount; i++) {
final Offset t = texcoords[i];
final double x = t.dx * imageWidth + imageLeft;
final double y = (1.0 - t.dy) * imageHeight + imageTop;
final int xIndex = (vertexOffset + i) * 2;
final int yIndex = xIndex + 1;
renderTexcoords[xIndex] = x;
renderTexcoords[yIndex] = y;
}
} else {
for (int i = 0; i < texcoordCount; i++) {
final int xIndex = (vertexOffset + i) * 2;
final int yIndex = xIndex + 1;
renderTexcoords[xIndex] = 0;
renderTexcoords[yIndex] = 0;
}
}
List children = o.children;
for (int i = 0; i < children.length; i++) {
_renderObject(renderMesh, children[i], model, view, projection);
}
meu código:
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;
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 = 12;
final int lonSegments = 12;
late List vertices;
late List texcoords;
late List<List> indices;
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++;
}
}
code
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
indices.add([next, below, belowNext]); // Triângulo superior
}
}
}
void updateTransform() {
final Matrix4 model = Matrix4.identity()
..translate(position.x, position.y, position.z)
..rotateX(rotation.x)
..rotateY(rotation.y)
..rotateZ(rotation.z)
..scale(scale.x, scale.y, scale.z);
code
final Matrix4 view = Matrix4.identity(); // Visualização
final Matrix4 projection = Matrix4.identity(); // Projeção
transform.setFrom(projection * view * model);
Para replicar o modo de transformação e texturização do código alvo no seu próprio código, vamos seguir uma abordagem passo a passo que organiza o processo de renderização de forma semelhante. Focaremos apenas na renderização da esfera, eliminando partes desnecessárias. O objetivo é estruturar o seu SpherePainter para alinhar-se mais com o fluxo do código alvo.
Estrutura Geral
Gerenciamento de Textura: Verifique se a textura precisa ser atualizada.
Criação da Malha de Renderização: Gere a malha da esfera.
Transformações: Aplique as transformações de modelo, visualização e projeção.
Culling e Ordenação: Remova faces não visíveis e ordene as faces por profundidade.
Preparação dos Dados para Renderização: Converta posições, texturas e índices em formatos adequados.
Renderização Final: Utilize canvas.drawVertices para desenhar a esfera com a textura aplicada.
Passo a Passo
Vamos ajustar o seu código para seguir esses passos:
dart
import 'dart:async';
import 'dart:typed_data';
import 'dart:ui' as 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.01;
});
});
}
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;
SpherePainter(this.texture, this.angle);
// Parâmetros da esfera
final double radius = 100;
final int latSegments = 24; // Aumentei a resolução
final int lonSegments = 24;
// Estruturas para armazenar dados da malha
late List<Vector3> vertices;
late List<Offset> texcoords;
late List<List<int>> indices;
// Flags para atualização de textura
bool _needsUpdateTexture = true;
// Matrizes de transformação
final Matrix4 model = Matrix4.identity();
final Matrix4 view = Matrix4.identity(); // Para simplificação, uso identidade
final Matrix4 projection = Matrix4.identity(); // Projeção ortográfica
// Malha de renderização
late RenderMesh renderMesh;
void _updateTexture() {
// Função para atualizar textura se necessário
// No caso, a textura é fixa, então podemos deixar vazio ou implementar caso necessário
}
// Função para criar a malha de renderização
void _makeRenderMesh() {
renderMesh = RenderMesh();
_generateSphere();
}
// Função para renderizar o objeto (esfera)
void _renderObject(RenderMesh renderMesh, Object3D o, Matrix4 modelTransform, Matrix4 viewTransform, Matrix4 projectionTransform) {
if (!o.visible) return;
Matrix4 currentModel = Matrix4.identity()..multiply(modelTransform)..multiply(o.transform);
Matrix4 transform = projectionTransform.multiplied(viewTransform).multiplied(currentModel);
// Aplicar transformações e adicionar vértices à malha
List<Vector3> vertices = o.mesh.vertices;
for (var vertex in vertices) {
Vector4 v = Vector4(vertex.x, vertex.y, vertex.z, 1.0);
v = transform.transform(v);
v /= v.w;
// Mapeamento para coordenadas de tela
double x = v.x;
double y = v.y;
renderMesh.positions.add(Vector2(x, y));
renderMesh.positionsZ.add(v.z);
}
renderMesh.vertexCount += vertices.length;
// Adicionar coordenadas de textura
List<Offset> texcoords = o.mesh.texcoords;
renderMesh.texcoords.addAll(texcoords);
}
// Função para geração da esfera
void _generateSphere() {
vertices = List<Vector3>.filled((latSegments + 1) * (lonSegments + 1), Vector3.zero());
texcoords = List<Offset>.filled((latSegments + 1) * (lonSegments + 1), Offset.zero);
indices = [];
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 * 2 * math.pi) * sv, // X
radius * cv, // Y
radius * math.sin(u * 2 * math.pi) * sv // Z
);
texcoords[i] = Offset(u, v);
i++;
}
}
// Índices para desenhar 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
indices.add([next, below, belowNext]); // Triângulo superior
}
}
}
@override
void paint(Canvas canvas, Size size) {
// Passo 1: Verificar se a textura precisa ser atualizada
if (_needsUpdateTexture) {
_needsUpdateTexture = false;
_updateTexture();
}
// Passo 2: Criar a malha de renderização
_makeRenderMesh();
// Passo 3: Configurar transformação
Matrix4 rotation = Matrix4.identity()
..rotateX(angle)
..rotateY(angle);
// Renderizar o objeto
Object3D sphere = Object3D(
visible: true,
transform: rotation,
mesh: Mesh(vertices, texcoords),
children: [],
);
_renderObject(renderMesh, sphere, model, view, projection);
// Passo 4: Culling e ordenação
List<Polygon> renderIndices = [];
for (int i = 0; i < indices.length; i++) {
List<int> triangle = indices[i];
// Aqui você pode implementar o culling de back-face se necessário
// Para simplicidade, vamos adicionar todas as faces
renderIndices.add(Polygon(vertex0: triangle[0], vertex1: triangle[1], vertex2: triangle[2]));
}
if (renderIndices.isEmpty) return;
// Ordenar as faces por profundidade (sumOfZ)
renderIndices.sort((a, b) {
double az = a.sumOfZ;
double bz = b.sumOfZ;
if (bz > az) return 1;
if (bz < az) return -1;
return 0;
});
// Passo 5: Preparar os dados para renderização
final int indexCount = renderIndices.length * 3;
final Uint16List indicesBuffer = Uint16List(indexCount);
for (int i = 0; i < renderIndices.length; i++) {
indicesBuffer[i * 3] = renderIndices[i].vertex0;
indicesBuffer[i * 3 + 1] = renderIndices[i].vertex1;
indicesBuffer[i * 3 + 2] = renderIndices[i].vertex2;
}
final Float32List positions = Float32List(renderMesh.vertexCount * 2);
final Float32List renderTexcoords = Float32List(renderMesh.vertexCount * 2);
for (int i = 0; i < renderMesh.positions.length; i++) {
positions[i * 2] = renderMesh.positions[i].x;
positions[i * 2 + 1] = renderMesh.positions[i].y;
renderTexcoords[i * 2] = (renderMesh.texcoords[i].dx * texture.width).toDouble();
renderTexcoords[i * 2 + 1] = ((1.0 - renderMesh.texcoords[i].dy) * texture.height).toDouble();
}
// Passo 6: Criar Vertices e Pintar
final verticesData = Vertices.raw(
VertexMode.triangles,
positions,
textureCoordinates: renderTexcoords,
indices: indicesBuffer,
);
final Float64List identityMatrix = Matrix4.identity().storage;
final Paint paint = Paint()
..shader = ImageShader(
texture,
TileMode.clamp,
TileMode.clamp,
identityMatrix,
)
..blendMode = BlendMode.srcOver;
canvas.drawVertices(verticesData, BlendMode.srcOver, paint);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return true;
}
}
// Classes auxiliares para estruturar a malha e objetos 3D
class RenderMesh {
List<Vector2> positions = [];
List<double> positionsZ = [];
List<Offset> texcoords = [];
int vertexCount = 0;
}
class Object3D {
bool visible;
Matrix4 transform;
Mesh mesh;
List<Object3D> children;
Object3D({
required this.visible,
required this.transform,
required this.mesh,
required this.children,
});
}
class Mesh {
List<Vector3> vertices;
List<Offset> texcoords;
Mesh(this.vertices, this.texcoords);
}
class Polygon {
int vertex0;
int vertex1;
int vertex2;
Polygon({
required this.vertex0,
required this.vertex1,
required this.vertex2,
});
double get sumOfZ {
// Implementar cálculo da profundidade média das faces
// Para simplicidade, retornar 0
return 0.0;
}
}
Explicações Detalhadas
Gerenciamento de Textura:
Flag _needsUpdateTexture: Utiliza uma flag para verificar se a textura precisa ser atualizada. No caso da esfera estática, essa flag pode permanecer como está.
Método _updateTexture: Implementado para atualizações futuras caso necessário.
Criação da Malha de Renderização:
Classe RenderMesh: Armazena posições, coordenadas de textura e profundidade (Z) dos vértices.
Método _makeRenderMesh: Cria a malha da esfera chamando _generateSphere.
Transformações:
Matrizes de Transformação: model, view e projection são inicialmente identidades. Pode-se personalizá-las para ajustes de câmera e projeção.
Classe Object3D: Representa um objeto 3D com visibilidade, transformação e malha.
Culling e Ordenação:
Classe Polygon: Representa uma face triangular da malha. Implementa um método sumOfZ para ordenar as faces, facilitando o renderização correta considerando a profundidade.
Culling: Para simplificar, todas as faces são adicionadas. Se desejar implementar o culling de faces traseiras, pode-se adicionar lógica para verificar a orientação das faces.
Preparação dos Dados para Renderização:
Positions e Texcoords: Convertidos para Float32List que é compatível com Vertices.raw.
Indices: Convertidos para Uint16List, referenciando os vértices que formam cada triângulo.
Renderização Final:
Vertices.raw: Cria a geometria a ser desenhada.
Paint com Shader: Aplica a textura utilizando ImageShader.
canvas.drawVertices: Renderiza os vértices na tela com a textura aplicada.
Considerações Finais
Otimização: Este exemplo foi ajustado para refletir a estrutura do código alvo. Para otimização adicional, considere implementar culling de faces traseiras e outras técnicas de otimização de renderização.
Transformações de Projeção: Atualmente, a projeção está definida como identidade. Para uma projeção mais realista, ajuste a matriz de projeção conforme necessário (por exemplo, perspectiva).
Interatividade: Você pode expandir este exemplo para incluir interações do usuário, como rotação manual da esfera com gestos.