### Configure VTK IO Crate with Features
Source: https://github.com/elrnv/vtkio/blob/master/README.md
Example of how to configure the vtkio dependency in Cargo.toml to enable specific features like XML support while disabling default features.
```toml
[dependencies]
vtkio = { version = "0.7", default-features = false, features = ["xml"] }
```
--------------------------------
### Disable All Additional Features for VTK IO Crate
Source: https://github.com/elrnv/vtkio/blob/master/README.md
Example of how to configure the vtkio dependency in Cargo.toml to disable all additional features, relying only on the core functionality.
```toml
[dependencies]
vtkio = { version = "0.7", default-features = false }
```
--------------------------------
### Parse XML VTK Files
Source: https://context7.com/elrnv/vtkio/llms.txt
Demonstrates parsing an XML VTK structure from a byte slice using a BufReader.
```rust
use vtkio::model::*;
use std::io::BufReader;
fn main() {
// Parse XML VTK from a byte slice
let input: &[u8] = b"\
\
\
\
\
\
AAAAAAAAAAQAAAAAAAAAAAAAAAA/gAAAAAAAAAAAAAAAAAAAAAAAAL+AAAA=\
\
\
\
\
AAAAAAAAAAgAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAI=\
\
\
AAAAAAAAAAgAAAAAAAAAAw==\
\
\
\
\
";
let vtk = Vtk::parse_xml(BufReader::new(input)).expect("Failed to parse XML VTK");
assert_eq!(vtk.version, Version::new_xml(2, 0));
assert_eq!(vtk.byte_order, ByteOrder::BigEndian);
}
```
--------------------------------
### Create VTK with Field Data Attributes
Source: https://context7.com/elrnv/vtkio/llms.txt
Demonstrates creating a VTK file with both point and cell field data attributes. Use `Attribute::field` to create attributes and `add_field_data` or `with_field_data` to add `FieldArray`s.
```rust
use vtkio::model::*;
fn main() {
let vtk = Vtk {
version: Version::new_legacy(4, 2),
title: String::from("vtk output"),
byte_order: ByteOrder::BigEndian,
file_path: None,
data: DataSet::inline(UnstructuredGridPiece {
points: vec![
0.0f64, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0,
].into(),
cells: Cells {
cell_verts: VertexNumbers::Legacy {
num_cells: 1,
vertices: vec![4, 0, 1, 2, 3],
},
types: vec![CellType::Tetra],
},
data: Attributes {
point: vec![
Attribute::field("PointFieldData")
.add_field_data(FieldArray::new("Zeros", 1).with_data(vec![0.0f32; 4]))
.add_field_data(FieldArray::new("Indices", 1).with_data(vec![0, 1, 2, 3i32])),
],
cell: vec![
Attribute::field("CellFieldData")
.add_field_data(FieldArray::new("CellValue", 1).with_data(vec![42.0f32]))
.add_field_data(FieldArray::new("CellId", 1).with_data(vec![0i32])),
],
},
}),
};
// Alternative: using with_field_data for batch field arrays
let field_arrays = vec![
FieldArray::new("A", 1).with_data(vec![1.0f32, 2.0, 3.0]),
FieldArray::new("B", 2).with_data(vec![1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0]),
];
let field = Attribute::field("Data").with_field_data(field_arrays);
}
```
--------------------------------
### Import and export VTK files
Source: https://github.com/elrnv/vtkio/blob/master/README.md
Load a VTK file, modify its version, and save it back in Legacy ASCII format.
```rust
use vtkio::model::*; // import model definition of a VTK file
fn main() {
use std::path::PathBuf;
let file_path = PathBuf::from("assets/tet.vtk");
let mut vtk_file = Vtk::import(&file_path)
.expect(&format!("Failed to load file: {:?}", file_path));
vtk_file.version = Version::new((4,2)); // arbitrary change
vtk_file.export_ascii(&file_path)
.expect(&format!("Failed to save file: {:?}", file_path));
}
```
--------------------------------
### Import VTK Files
Source: https://context7.com/elrnv/vtkio/llms.txt
Use the `import` function to automatically detect and parse VTK files based on their extension. This function returns a unified `Vtk` data structure. Ensure the file path is correctly specified.
```rust
use vtkio::Vtk;
use std::path::PathBuf;
fn main() {
// Import a Legacy VTK file
let file_path = PathBuf::from("assets/tet.vtk");
let mut vtk_file = Vtk::import(&file_path)
.expect(&format!("Failed to load file: {:?}", file_path));
println!("VTK Version: {:?}", vtk_file.version);
println!("Title: {}", vtk_file.title);
println!("Byte Order: {:?}", vtk_file.byte_order);
// Import an XML VTU (UnstructuredGrid) file
let vtu_path = PathBuf::from("assets/box.vtu");
let vtu_file = Vtk::import(&vtu_path)
.expect("Failed to load VTU file");
// Import parallel XML files and load all pieces
let pvtu_path = PathBuf::from("assets/hexahedron_parallel.pvtu");
let mut parallel_vtk = Vtk::import(&pvtu_path).unwrap();
parallel_vtk.load_all_pieces().expect("Failed to load pieces");
}
```
--------------------------------
### Create Unstructured Grid Meshes
Source: https://context7.com/elrnv/vtkio/llms.txt
Illustrates building a mesh with mixed cell types and accessing cell metadata programmatically.
```rust
use vtkio::model::*;
fn main() {
// Create a mesh with mixed cell types
let vtk = Vtk {
version: Version::new_legacy(4, 2),
title: String::from("Mixed elements"),
byte_order: ByteOrder::BigEndian,
file_path: None,
data: DataSet::inline(UnstructuredGridPiece {
points: IOBuffer::F64(vec![
// Triangle vertices
-1.0, -1.0, 0.0,
1.0, -1.0, 0.0,
1.0, 1.0, 0.0,
// Quad vertices
-1.0, 1.0, 0.0,
2.0, -1.0, 0.2,
2.0, 1.0, 0.2,
]),
cells: Cells {
cell_verts: VertexNumbers::XML {
connectivity: vec![
0, 1, 2, // Triangle
1, 4, 5, 2, // Quadrilateral
],
offsets: vec![3, 7],
},
types: vec![CellType::Triangle, CellType::Quad],
},
data: Attributes::new(),
}),
};
// Access cell information
if let DataSet::UnstructuredGrid { pieces, .. } = &vtk.data {
if let Piece::Inline(piece) = &pieces[0] {
println!("Number of points: {}", piece.num_points());
println!("Number of cells: {}", piece.cells.num_cells());
}
}
}
```
--------------------------------
### Write VTK Data to Buffers and Strings
Source: https://context7.com/elrnv/vtkio/llms.txt
Shows how to serialize VTK models into ASCII strings, binary vectors, or XML format without file system interaction.
```rust
use vtkio::model::*;
fn main() {
let vtk = Vtk {
version: Version::new_legacy(2, 0),
byte_order: ByteOrder::BigEndian,
title: String::from("Triangle example"),
file_path: None,
data: DataSet::inline(PolyDataPiece {
points: vec![0.0f32, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, -1.0].into(),
polys: Some(VertexNumbers::Legacy {
num_cells: 1,
vertices: vec![3, 0, 1, 2],
}),
data: Attributes::new(),
..Default::default()
}),
};
// Write to a String (ASCII format)
let mut vtk_string = String::new();
vtk.clone().write_legacy_ascii(&mut vtk_string).expect("Failed to write");
println!("ASCII output:\n{}", vtk_string);
// Write to a Vec (binary format)
let mut vtk_bytes = Vec::::new();
vtk.clone().write_legacy(&mut vtk_bytes).expect("Failed to write binary");
// Write to XML format
let mut xml_bytes = Vec::::new();
vtk.write_xml(&mut xml_bytes).expect("Failed to write XML");
println!("XML output:\n{}", String::from_utf8_lossy(&xml_bytes));
}
```
--------------------------------
### Access VTK Data Structure
Source: https://context7.com/elrnv/vtkio/llms.txt
Demonstrates how to load a VTK file and access its components, including points, coordinates, and cell types. This is useful for inspecting the structure of loaded VTK data.
```rust
use vtkio::model::*;
use vtkio::Vtk;
fn main() {
let vtk = Vtk::import("assets/para_tet.vtk").unwrap();
// Access the DataSet directly
if let DataSet::UnstructuredGrid { pieces, .. } = &vtk.data {
if let Piece::Inline(piece) = &pieces[0] {
// Access points
println!("Number of points: {}", piece.num_points());
// Access point coordinates
if let Some(coords) = piece.points.iter::() {
for (i, &coord) in coords.enumerate() {
if i % 3 == 0 { print!("Point {}: ", i / 3); }
print!("{:.2} ", coord);
if i % 3 == 2 { println!(); }
}
}
// Iterate over cell types
for (i, cell_type) in piece.cells.types.iter().enumerate() {
println!("Cell {}: {:?}", i, cell_type);
}
}
}
}
```
--------------------------------
### Add vtkio dependency
Source: https://github.com/elrnv/vtkio/blob/master/README.md
Include the vtkio crate in your Cargo.toml file to use the library.
```toml
[dependencies]
vtkio = "0.7"
```
--------------------------------
### Convert Vertex Numbers Format in Rust
Source: https://context7.com/elrnv/vtkio/llms.txt
Demonstrates bidirectional conversion between Legacy (cell-prefixed) and XML (connectivity/offsets) vertex numbering formats. Includes methods for querying cell and vertex counts.
```rust
use vtkio::model::*;
fn main() {
// Legacy format: each cell prefixed with vertex count
let legacy = VertexNumbers::Legacy {
num_cells: 2,
vertices: vec![
3, 0, 1, 2, // Triangle: 3 vertices [0, 1, 2]
4, 1, 2, 3, 4, // Quad: 4 vertices [1, 2, 3, 4]
],
};
// Convert to XML format
let (connectivity, offsets) = legacy.clone().into_xml();
println!("Connectivity: {:?}", connectivity); // [0, 1, 2, 1, 2, 3, 4]
println!("Offsets: {:?}", offsets); // [3, 7]
// XML format: separate connectivity and offsets arrays
let xml = VertexNumbers::XML {
connectivity: vec![0, 1, 2, 1, 2, 3, 4],
offsets: vec![3, 7],
};
// Convert to Legacy format
let (num_cells, vertices) = xml.clone().into_legacy();
println!("Num cells: {}", num_cells); // 2
println!("Vertices: {:?}", vertices); // [3, 0, 1, 2, 4, 1, 2, 3, 4]
// Query vertex numbers
println!("Total vertices: {}", xml.num_verts()); // 7
println!("Number of cells: {}", xml.num_cells()); // 2
}
```
--------------------------------
### Create PolyData Meshes in Rust
Source: https://context7.com/elrnv/vtkio/llms.txt
Constructs a cube surface mesh using polygons and a point cloud using standalone vertices.
```rust
use vtkio::model::*;
fn main() {
// Create a cube surface mesh with polygons
let vtk = Vtk {
version: Version::new_legacy(2, 0),
title: String::from("Cube surface"),
byte_order: ByteOrder::BigEndian,
file_path: None,
data: DataSet::inline(PolyDataPiece {
points: vec![
0.0f32, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0,
].into(),
polys: Some(VertexNumbers::Legacy {
num_cells: 6,
vertices: vec![
4, 0, 1, 2, 3, // front face
4, 4, 5, 6, 7, // back face
4, 0, 1, 5, 4, // bottom face
4, 2, 3, 7, 6, // top face
4, 0, 4, 7, 3, // left face
4, 1, 2, 6, 5, // right face
],
}),
verts: None,
lines: None,
strips: None,
data: Attributes::new(),
}),
};
// Create a point cloud with standalone vertices
let point_cloud = Vtk {
version: Version::new_legacy(2, 0),
title: String::from("Point cloud"),
byte_order: ByteOrder::BigEndian,
file_path: None,
data: DataSet::inline(PolyDataPiece {
points: vec![0.0f32, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, -1.0].into(),
verts: Some(VertexNumbers::Legacy {
num_cells: 3,
vertices: vec![1, 0, 1, 1, 1, 2],
}),
..Default::default()
}),
};
}
```
--------------------------------
### Create Image Data (Structured Points) in Rust
Source: https://context7.com/elrnv/vtkio/llms.txt
Defines a 3D volume using origin, spacing, and extent parameters. Requires the vtkio::model module and exports the result to an ASCII VTK file.
```rust
use vtkio::model::*;
fn main() {
// Create a 3x4x6 volume with scalar data
let vtk = Vtk {
version: Version::new_legacy(2, 0),
title: String::from("Volume example"),
byte_order: ByteOrder::BigEndian,
file_path: None,
data: DataSet::ImageData {
extent: Extent::Dims([3, 4, 6]),
origin: [0.0, 0.0, 0.0], // Starting corner
spacing: [1.0, 1.0, 1.0], // Voxel size
meta: None,
pieces: vec![Piece::Inline(Box::new(ImageDataPiece {
extent: Extent::Dims([3, 4, 6]),
data: Attributes {
point: vec![
Attribute::scalars("volume_scalars", 1)
.with_data(vec![
// 72 values for 3*4*6 = 72 points
0i8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 5, 10, 15, 20, 25, 25, 20, 15, 10, 5, 0,
0, 10, 20, 30, 40, 50, 50, 40, 30, 20, 10, 0,
0, 10, 20, 30, 40, 50, 50, 40, 30, 20, 10, 0,
0, 5, 10, 15, 20, 25, 25, 20, 15, 10, 5, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
]),
],
cell: vec![],
},
}))],
},
};
vtk.export_ascii("volume.vtk").unwrap();
}
```
--------------------------------
### Create a mesh with mixed cell types
Source: https://github.com/elrnv/vtkio/blob/master/README.md
Construct a Vtk instance containing both a triangle and a quadrilateral in an unstructured grid.
```rust
fn make_mixed_flat_elements() -> Vtk {
Vtk {
version: Version { major: 4, minor: 2 },
title: String::new(),
byte_order: ByteOrder::BigEndian,
file_path: None,
data: DataSet::inline(UnstructuredGridPiece {
points: IOBuffer::F64(vec![
-1.0, -1.0, 0.0,
1.0, -1.0, 0.0,
1.0, 1.0, 0.0,
-1.0, 1.0, 0.0,
2.0, -1.0, 0.2,
2.0, 1.0, 0.2,
]),
cells: Cells {
cell_verts: VertexNumbers::XML {
connectivity: vec![
// nodes of triangle
0, 1, 2,
// nodes of quadrilateral
1, 4, 5, 2,
],
offsets: vec![
// number of nodes cell 1
3,
// number of nodes cell 1 + number of nodes of cell 2
// 3 + 4 = 7
7
],
},
types: vec![
CellType::Triangle,
CellType::Quad
],
},
data: Attributes {
..Default::default()
},
}),
}
}
```
--------------------------------
### Create Structured Grid Data
Source: https://context7.com/elrnv/vtkio/llms.txt
Define a structured grid using extent-based organization and explicit point coordinates.
```rust
use vtkio::model::*;
fn main() {
// Create a 2x2x2 structured grid
let vtk = Vtk {
version: Version::new_legacy(3, 0),
title: String::from("Structured grid example"),
byte_order: ByteOrder::BigEndian,
file_path: None,
data: DataSet::inline(StructuredGridPiece {
extent: Extent::Dims([2, 2, 2]), // 2x2x2 grid = 8 points
points: vec![
// Layer z=0
0.0f32, 0.0, 0.0, 0.1, 0.0, 0.0,
0.0, 0.1, 0.0, 0.1, 0.1, 0.0,
// Layer z=1
0.0, 0.0, 0.1, 0.1, 0.0, 0.1,
0.0, 0.1, 0.1, 0.1, 0.1, 0.1,
].into(),
data: Attributes {
point: vec![
Attribute::scalars("point_values", 1)
.with_data(vec![0.0f32, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]),
Attribute::vectors("point_vectors")
.with_data(vec![1.0f32; 24]), // 8 points * 3 components
],
cell: vec![
Attribute::scalars("cell_value", 1)
.with_data(vec![100.0f32]), // 1 cell in 2x2x2 grid
],
},
}),
};
// Check extent information
if let DataSet::StructuredGrid { extent, pieces, .. } = &vtk.data {
println!("Number of points: {}", extent.num_points());
println!("Number of cells: {}", extent.num_cells());
println!("Dimensions: {:?}", extent.clone().into_dims());
}
}
```
--------------------------------
### Create DataArray and Attributes in Rust
Source: https://context7.com/elrnv/vtkio/llms.txt
Uses the builder pattern to define various attribute types and data arrays. Ensure the vtkio crate is included in your project dependencies.
```rust
use vtkio::model::*;
fn main() {
// Create various attribute types using builder pattern
let scalars = DataArray::scalars("temperature", 1)
.with_data(vec![20.0f32, 25.0, 30.0, 35.0]);
let scalars_with_lookup = DataArray::scalars_with_lookup("pressure", 1, "color_table")
.with_data(vec![100.0f32, 200.0, 300.0]);
let vectors = DataArray::vectors("velocity")
.with_data(vec![1.0f32, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]);
let normals = DataArray::normals("surface_normals")
.with_data(vec![0.0f32, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0]);
let tensors = DataArray::tensors("stress")
.with_data(vec![
1.0f64, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, // 3x3 identity
]);
let tcoords = DataArray::tcoords("uv_coords", 2)
.with_data(vec![0.0f32, 0.0, 1.0, 0.0, 0.5, 1.0]);
let generic = DataArray::new("custom_data", 4) // 4 components per element
.with_data(vec![1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]);
let lookup_table = DataArray::lookup_table("color_table")
.with_data(vec![
0.0f32, 0.0, 1.0, 1.0, // Blue
0.0, 1.0, 0.0, 1.0, // Green
1.0, 0.0, 0.0, 1.0, // Red
]);
let color_scalars = DataArray::color_scalars("vertex_colors", 3)
.with_data(vec![255u8, 0, 0, 0, 255, 0, 0, 0, 255]);
// Check data array properties
println!("Scalar type: {:?}", scalars.scalar_type());
println!("Number of components: {}", scalars.num_comp());
println!("Number of elements: {}", scalars.num_elem());
}
```
--------------------------------
### Create a simple triangular cell
Source: https://github.com/elrnv/vtkio/blob/master/README.md
Construct a Vtk instance containing a single triangle as an unstructured grid cell.
```rust
fn make_triangle() -> Vtk {
Vtk {
version: Version { major: 4, minor: 2 },
title: String::new(),
byte_order: ByteOrder::BigEndian,
file_path: None,
data: DataSet::inline(UnstructuredGridPiece {
points: IOBuffer::F64(vec![
// coordinates of node 0
-1.0, -1.0, 0.0,
// coordinates of node 1
1.0, -1.0, 0.0,
// coordinates of node 2
1.0, 1.0, 0.0,
]),
cells: Cells {
cell_verts: VertexNumbers::XML {
// connect node 0, 1, 2 (in this order)
connectivity: vec![0, 1, 2],
// only one group of size 3
offsets: vec![3],
},
// only one cell of type triangle
types: vec![CellType::Triangle; 1],
},
data: Attributes {
..Default::default()
},
}),
}
}
```
--------------------------------
### Extract Field Data from VTK File
Source: https://context7.com/elrnv/vtkio/llms.txt
Shows how to load a VTK file and extract specific field data arrays from cell attributes. Ensure the field array name and desired data type match.
```rust
use vtkio::model::*;
use vtkio::Vtk;
fn extract_field_data(vtk: Vtk) -> Option> {
// Get pieces from UnstructuredGrid
let pieces = if let DataSet::UnstructuredGrid { pieces, .. } = vtk.data {
pieces
} else {
return None;
};
// Load piece data (handles inline, loaded, and source pieces)
let piece = pieces[0].load_piece_data(None).ok()?;
// Find a specific field attribute in cell data
for attribute in &piece.data.cell {
if let Attribute::Field { data_array, .. } = attribute {
for array in data_array {
if array.name == "FloatValue" {
// Cast the data to f64
return array.data.cast_into::();
}
}
}
}
None
}
```
--------------------------------
### Export VTK Files
Source: https://context7.com/elrnv/vtkio/llms.txt
Export `Vtk` data to files using the `export` function, which determines the format by file extension. Binary and ASCII output modes are supported. Specific endianness can be enforced using `export_le` and `export_be`.
```rust
use vtkio::model::*;
use std::path::PathBuf;
fn main() {
// Create a tetrahedron mesh
let vtk = Vtk {
version: Version::new_legacy(4, 1),
byte_order: ByteOrder::BigEndian,
title: String::from("Tetrahedron"),
file_path: Some(PathBuf::from("./output.vtk")),
data: DataSet::inline(UnstructuredGridPiece {
points: vec![
0.0f32, 0.0, 0.0,
1.0, 0.0, 0.0,
0.0, 0.0, -1.0,
0.0, 1.0, 0.0
].into(),
cells: Cells {
cell_verts: VertexNumbers::Legacy {
num_cells: 1,
vertices: vec![4, 0, 1, 2, 3],
},
types: vec![CellType::Tetra],
},
data: Attributes::new(),
}),
};
// Export as binary Legacy VTK file
vtk.clone().export("output.vtk").expect("Failed to export");
// Export as ASCII Legacy VTK file
vtk.clone().export_ascii("output_ascii.vtk").expect("Failed to export ASCII");
// Export with specific endianness
vtk.clone().export_le("output_le.vtk").expect("Failed to export little endian");
vtk.clone().export_be("output_be.vtk").expect("Failed to export big endian");
// Export as XML VTU file (determined by extension)
vtk.export("output.vtu").expect("Failed to export VTU");
}
```
--------------------------------
### Parse Legacy VTK from Byte Buffers
Source: https://context7.com/elrnv/vtkio/llms.txt
Parse Legacy VTK files directly from byte slices or readers using `parse_legacy_be` or `parse_legacy_le` for big or little endian respectively. `parse_legacy_buf_be` can be used with a buffer for efficiency.
```rust
use vtkio::model::*;
fn main() {
// Parse Legacy ASCII VTK from a byte slice
let vtk_ascii: &[u8] = b"
# vtk DataFile Version 2.0
Triangle example
ASCII
DATASET POLYDATA
POINTS 3 float
0.0 0.0 0.0
1.0 0.0 0.0
0.0 0.0 -1.0
POLYGONS 1 4
3 0 1 2
";
// Parse assuming big endian (standard for VTK files)
let vtk = Vtk::parse_legacy_be(vtk_ascii).expect("Failed to parse VTK");
assert_eq!(vtk.version, Version::new_legacy(2, 0));
assert_eq!(vtk.title, "Triangle example");
// Parse with little endian byte order
let vtk_le = Vtk::parse_legacy_le(vtk_ascii).expect("Failed to parse VTK");
assert_eq!(vtk_le.byte_order, ByteOrder::LittleEndian);
// Reuse buffer for parsing multiple files efficiently
let mut buffer = Vec::new();
let vtk_buffered = Vtk::parse_legacy_buf_be(vtk_ascii, &mut buffer)
.expect("Failed to parse with buffer");
}
```
--------------------------------
### Handle Typed Numeric Data with IOBuffer
Source: https://context7.com/elrnv/vtkio/llms.txt
Use IOBuffer to manage typed numeric arrays, perform type casting, and compute ranges. The match_buf! macro is useful for type-agnostic operations.
```rust
use vtkio::model::*;
fn main() {
// Create buffers from various numeric types
let f32_buf: IOBuffer = vec![1.0f32, 2.0, 3.0].into();
let f64_buf: IOBuffer = vec![1.0f64, 2.0, 3.0].into();
let i32_buf: IOBuffer = vec![1i32, 2, 3].into();
let u8_buf: IOBuffer = vec![255u8, 128, 0].into();
// Check buffer properties
println!("Scalar type: {:?}", f32_buf.scalar_type()); // ScalarType::F32
println!("Length: {}", f32_buf.len()); // 3
println!("Bytes: {}", f32_buf.num_bytes()); // 12
// Convert to typed vector (returns None if types don't match)
let vec_f32: Option> = f32_buf.clone().into_vec::();
let vec_wrong: Option> = f32_buf.clone().into_vec::(); // None
// Cast buffer to different type (with conversion)
let as_f64: Option> = f32_buf.cast_into::();
// Iterate over buffer elements
if let Some(iter) = f32_buf.iter::() {
for value in iter {
println!("Value: {}", value);
}
}
// Compute value range
if let Some((min, max)) = f32_buf.compute_range() {
println!("Range: {} to {}", min, max);
}
// Use match_buf macro for type-agnostic operations
match_buf!(&f32_buf, v => println!("Buffer length: {}", v.len()));
}
```
--------------------------------
### Create Rectilinear Grid Data
Source: https://context7.com/elrnv/vtkio/llms.txt
Define a rectilinear grid where axis coordinates are specified independently, suitable for non-uniform spacing.
```rust
use vtkio::model::*;
fn main() {
// Create a rectilinear grid with non-uniform spacing
let vtk = Vtk {
version: Version::new_legacy(3, 0),
title: String::from("Rectilinear grid"),
byte_order: ByteOrder::BigEndian,
file_path: None,
data: DataSet::inline(RectilinearGridPiece {
extent: Extent::Dims([3, 4, 1]), // 3x4x1 = 12 points, 2x3x0 = 6 cells
coords: Coordinates {
x: vec![0.0f32, 2.0, 4.0].into(), // 3 x-coordinates
y: vec![1.0f32, 2.0, 3.0, 4.0].into(), // 4 y-coordinates
z: vec![0.0f32].into(), // 1 z-coordinate (2D grid)
},
data: Attributes {
point: vec![],
cell: vec![
Attribute::field("FieldData")
.add_field_data(
FieldArray::new("cell_scalars", 1)
.with_data(vec![1.1f32, 7.5, 1.2, 1.5, 2.6, 8.1])
),
],
},
}),
};
vtk.export_ascii("rectilinear.vtk").unwrap();
}
```
--------------------------------
### Add Point and Cell Attributes in Rust
Source: https://context7.com/elrnv/vtkio/llms.txt
Attaches various data attributes such as scalars, vectors, normals, and texture coordinates to an unstructured grid.
```rust
use vtkio::model::*;
fn main() {
let vtk = Vtk {
version: Version::new_legacy(4, 2),
title: String::from("Mesh with attributes"),
byte_order: ByteOrder::BigEndian,
file_path: None,
data: DataSet::inline(UnstructuredGridPiece {
points: vec![
0.0f32, 0.0, 0.0, 1.0, 0.0, 0.0,
0.0, 1.0, 0.0, 1.0, 1.0, 0.0,
].into(),
cells: Cells {
cell_verts: VertexNumbers::Legacy {
num_cells: 1,
vertices: vec![4, 0, 1, 3, 2],
},
types: vec![CellType::Quad],
},
data: Attributes {
point: vec![
// Scalar attribute (e.g., temperature)
Attribute::scalars("temperature", 1)
.with_data(vec![0.0f32, 1.0, 2.0, 3.0]),
// Vector attribute (e.g., velocity)
Attribute::vectors("velocity")
.with_data(vec![1.0f32, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0]),
// Normal vectors
Attribute::normals("normals")
.with_data(vec![0.0f32, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0]),
// Texture coordinates (2D)
Attribute::tcoords("uv", 2)
.with_data(vec![0.0f32, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0]),
],
cell: vec![
// Cell scalar (e.g., material ID)
Attribute::scalars("material_id", 1)
.with_data(vec![1i32]),
// Cell normals
Attribute::normals("face_normal")
.with_data(vec![0.0f32, 0.0, 1.0]),
],
},
}),
};
vtk.export_ascii("mesh_with_attributes.vtk").unwrap();
}
```
--------------------------------
### Extract 'id' Field Data from Vtk Struct
Source: https://github.com/elrnv/vtkio/blob/master/README.md
Extracts an 'id' field from the point data of a Vtk unstructured grid. Assumes the 'id' field exists and is of type i32. Panics if the Vtk data type is incorrect or the field is not found.
```rust
fn extract_id_field(vtk: Vtk) -> Vec {
let pieces = if let DataSet::UnstructuredGrid { pieces, .. } = vtk.data {
pieces
} else {
panic!("Wrong vtk data type");
};
// If piece is already inline, this just returns a piece data clone.
let piece = pieces[0].load_piece_data(None).expect("Failed to load piece data");
let attribute = &piece.data.point[0];
if let Attribute::Field { data_array, .. } = attribute {
data_array
.iter()
.find(|&DataArrayBase { name, .. }| name == "id")
.expect("Failed to find id field")
.data
.cast_into::()
.expect("Failed cast")
} else {
panic!("No field attribute found");
}
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.