repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
sjb3d/caldera
https://github.com/sjb3d/caldera/blob/42fc4b496cce21e907eca7112e6d6334d35fc41a/caldera/src/render_cache.rs
caldera/src/render_cache.rs
use crate::prelude::*; use arrayvec::ArrayVec; use spark::{vk, Builder, Device}; use std::{collections::HashMap, iter, slice}; use tinyvec::ArrayVec as TinyVec; pub trait FormatExt { fn bits_per_element(&self) -> usize; } impl FormatExt for vk::Format { fn bits_per_element(&self) -> usize { match *self { vk::Format::BC1_RGB_SRGB_BLOCK => 4, vk::Format::R8G8B8A8_UNORM | vk::Format::R8G8B8A8_SRGB | vk::Format::R16G16_UNORM | vk::Format::R16G16_UINT | vk::Format::R32_SFLOAT => 32, vk::Format::R16G16B16A16_SFLOAT | vk::Format::R32G32_SFLOAT | vk::Format::R32G32_UINT => 64, vk::Format::R32G32B32A32_SFLOAT | vk::Format::R32G32B32A32_UINT => 128, _ => unimplemented!(), } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct BufferDesc { pub size: usize, } impl BufferDesc { pub fn new(size: usize) -> Self { BufferDesc { size } } } #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub struct BufferInfo { pub mem_req: vk::MemoryRequirements, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct ImageDesc { pub width: u32, pub height_or_zero: u32, pub layer_count_or_zero: u32, pub mip_count: u32, pub formats: TinyVec<[vk::Format; 2]>, pub aspect_mask: vk::ImageAspectFlags, pub samples: vk::SampleCountFlags, } impl ImageDesc { pub fn new_1d(width: u32, format: vk::Format, aspect_mask: vk::ImageAspectFlags) -> Self { ImageDesc { width, height_or_zero: 0, layer_count_or_zero: 0, mip_count: 1, formats: iter::once(format).collect(), aspect_mask, samples: vk::SampleCountFlags::N1, } } pub fn new_2d(size: UVec2, format: vk::Format, aspect_mask: vk::ImageAspectFlags) -> Self { ImageDesc { width: size.x, height_or_zero: size.y, layer_count_or_zero: 0, mip_count: 1, formats: iter::once(format).collect(), aspect_mask, samples: vk::SampleCountFlags::N1, } } pub fn with_additional_format(mut self, format: vk::Format) -> Self { self.formats.push(format); self } pub fn with_layer_count(mut self, layer_count: u32) -> Self { self.layer_count_or_zero = layer_count; self } pub fn with_mip_count(mut self, mip_count: u32) -> Self { self.mip_count = mip_count; self } pub fn with_samples(mut self, samples: vk::SampleCountFlags) -> Self { self.samples = samples; self } pub fn first_format(&self) -> vk::Format { *self.formats.first().unwrap() } pub fn size(&self) -> UVec2 { UVec2::new(self.width, self.height_or_zero.max(1)) } pub fn extent_2d(&self) -> vk::Extent2D { vk::Extent2D { width: self.width, height: self.height_or_zero.max(1), } } pub fn is_array(&self) -> bool { self.layer_count_or_zero != 1 } pub(crate) fn image_type(&self) -> vk::ImageType { if self.height_or_zero == 0 { vk::ImageType::N1D } else { vk::ImageType::N2D } } pub(crate) fn image_view_type(&self) -> vk::ImageViewType { if self.height_or_zero == 0 { if self.layer_count_or_zero == 0 { vk::ImageViewType::N1D } else { vk::ImageViewType::N1D_ARRAY } } else { if self.layer_count_or_zero == 0 { vk::ImageViewType::N2D } else { vk::ImageViewType::N2D_ARRAY } } } pub(crate) fn staging_size(&self) -> usize { assert_eq!(self.samples, vk::SampleCountFlags::N1); let bits_per_element = self.first_format().bits_per_element(); let layer_count = self.layer_count_or_zero.max(1) as usize; let mut mip_width = self.width as usize; let mut mip_height = self.height_or_zero.max(1) as usize; let mut mip_offset = 0; for _ in 0..self.mip_count { let mip_layer_size = (mip_width * mip_height * bits_per_element) / 8; mip_offset += mip_layer_size * layer_count; mip_width /= 2; mip_height /= 2; } mip_offset } } #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)] pub struct ImageViewDesc { pub format: Option<vk::Format>, } impl ImageViewDesc { pub fn with_format(mut self, format: vk::Format) -> Self { self.format = Some(format); self } } #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub struct ImageInfo { pub mem_req: vk::MemoryRequirements, } trait DeviceGraphExt { fn create_buffer_from_desc( &self, desc: &BufferDesc, usage_flags: vk::BufferUsageFlags, ) -> spark::Result<vk::Buffer>; fn create_image_from_desc(&self, desc: &ImageDesc, usage_flags: vk::ImageUsageFlags) -> spark::Result<vk::Image>; } impl DeviceGraphExt for Device { fn create_buffer_from_desc( &self, desc: &BufferDesc, usage_flags: vk::BufferUsageFlags, ) -> spark::Result<vk::Buffer> { let buffer_create_info = vk::BufferCreateInfo { size: desc.size as vk::DeviceSize, usage: usage_flags, ..Default::default() }; unsafe { self.create_buffer(&buffer_create_info, None) } } fn create_image_from_desc(&self, desc: &ImageDesc, usage_flags: vk::ImageUsageFlags) -> spark::Result<vk::Image> { let mut format_list = vk::ImageFormatListCreateInfo::builder().p_view_formats(&desc.formats); let image_create_info = vk::ImageCreateInfo::builder() .flags(if desc.formats.len() > 1 { vk::ImageCreateFlags::MUTABLE_FORMAT } else { vk::ImageCreateFlags::empty() }) .image_type(desc.image_type()) .format(desc.first_format()) .extent(vk::Extent3D { width: desc.width, height: desc.height_or_zero.max(1), depth: 1, }) .mip_levels(desc.mip_count) .array_layers(desc.layer_count_or_zero.max(1)) .samples(desc.samples) .tiling(vk::ImageTiling::OPTIMAL) .usage(usage_flags) .initial_layout(vk::ImageLayout::UNDEFINED) .insert_next(&mut format_list); unsafe { self.create_image(&image_create_info, None) } } } #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub(crate) struct RenderPassDepth { pub(crate) format: vk::Format, pub(crate) load_op: AttachmentLoadOp, pub(crate) store_op: AttachmentStoreOp, } #[derive(Clone, Copy, PartialEq, Eq, Hash)] struct RenderPassKey { color_format: Option<vk::Format>, depth: Option<RenderPassDepth>, samples: vk::SampleCountFlags, } #[derive(Clone, Copy, PartialEq, Eq, Hash)] struct BufferInfoKey { desc: BufferDesc, all_usage_flags: vk::BufferUsageFlags, } #[derive(Clone, Copy, PartialEq, Eq, Hash)] struct BufferKey { desc: BufferDesc, all_usage_flags: vk::BufferUsageFlags, alloc: Alloc, } #[derive(Clone, Copy, PartialEq, Eq, Hash)] enum BufferAccelLevel { Bottom, Top, } #[derive(Clone, Copy, PartialEq, Eq, Hash)] struct BufferAccelKey { buffer: UniqueBuffer, level: BufferAccelLevel, } #[derive(Clone, Copy, PartialEq, Eq, Hash)] struct ImageInfoKey { desc: ImageDesc, all_usage_flags: vk::ImageUsageFlags, } #[derive(Clone, Copy, PartialEq, Eq, Hash)] struct ImageKey { desc: ImageDesc, all_usage_flags: vk::ImageUsageFlags, alloc: Alloc, } #[derive(Clone, Copy, PartialEq, Eq, Hash)] struct ImageViewKey { image: UniqueImage, view_desc: ImageViewDesc, } #[derive(Clone, Copy, PartialEq, Eq, Hash)] struct FramebufferKey { render_pass: UniqueRenderPass, size: UVec2, color_output_image_view: Option<UniqueImageView>, color_temp_image_view: Option<UniqueImageView>, depth_image_view: Option<UniqueImageView>, } pub(crate) struct ResourceCache { context: SharedContext, buffer_info: HashMap<BufferInfoKey, BufferInfo>, buffer: HashMap<BufferKey, UniqueBuffer>, buffer_accel: HashMap<BufferAccelKey, vk::AccelerationStructureKHR>, image_info: HashMap<ImageInfoKey, ImageInfo>, image: HashMap<ImageKey, UniqueImage>, image_view: HashMap<ImageViewKey, UniqueImageView>, } pub(crate) struct RenderCache { context: SharedContext, render_pass: HashMap<RenderPassKey, UniqueRenderPass>, framebuffer: HashMap<FramebufferKey, UniqueFramebuffer>, } impl ResourceCache { pub fn new(context: &SharedContext) -> Self { Self { context: SharedContext::clone(context), buffer_info: HashMap::new(), buffer: HashMap::new(), buffer_accel: HashMap::new(), image_info: HashMap::new(), image: HashMap::new(), image_view: HashMap::new(), } } pub fn ui_stats_table_rows(&self, ui: &mut egui::Ui, name: &str) { ui.label(format!("{} buffer cache", name)); ui.label(format!("{},{}", self.buffer_info.len(), self.buffer.len())); ui.end_row(); ui.label(format!("{} image cache", name)); ui.label(format!( "{},{},{}", self.image_info.len(), self.image.len(), self.image_view.len() )); ui.end_row(); } pub fn get_buffer_info(&mut self, desc: &BufferDesc, all_usage_flags: vk::BufferUsageFlags) -> BufferInfo { let context = &self.context; *self .buffer_info .entry(BufferInfoKey { desc: *desc, all_usage_flags, }) .or_insert_with(|| { let buffer = context.device.create_buffer_from_desc(desc, all_usage_flags).unwrap(); let mem_req = unsafe { context.device.get_buffer_memory_requirements(buffer) }; unsafe { context.device.destroy_buffer(buffer, None) }; BufferInfo { mem_req } }) } pub fn get_buffer( &mut self, desc: &BufferDesc, info: &BufferInfo, alloc: &Alloc, all_usage_flags: vk::BufferUsageFlags, ) -> UniqueBuffer { let context = &self.context; *self .buffer .entry(BufferKey { desc: *desc, all_usage_flags, alloc: *alloc, }) .or_insert_with(|| { let buffer = context.device.create_buffer_from_desc(desc, all_usage_flags).unwrap(); let mem_req_check = unsafe { context.device.get_buffer_memory_requirements(buffer) }; assert_eq!(info.mem_req, mem_req_check); unsafe { context.device.bind_buffer_memory(buffer, alloc.mem, alloc.offset) }.unwrap(); Unique::new(buffer, context.allocate_handle_uid()) }) } pub fn get_buffer_accel( &mut self, desc: &BufferDesc, buffer: UniqueBuffer, all_usage: BufferUsage, ) -> Option<vk::AccelerationStructureKHR> { let level = if all_usage.contains(BufferUsage::BOTTOM_LEVEL_ACCELERATION_STRUCTURE_WRITE) { Some(BufferAccelLevel::Bottom) } else if all_usage.contains(BufferUsage::TOP_LEVEL_ACCELERATION_STRUCTURE_WRITE) { Some(BufferAccelLevel::Top) } else { None }; let key = BufferAccelKey { buffer, level: level? }; let context = &self.context; Some(*self.buffer_accel.entry(key).or_insert_with(|| { let create_info = vk::AccelerationStructureCreateInfoKHR { buffer: buffer.0, size: desc.size as vk::DeviceSize, ty: match key.level { BufferAccelLevel::Bottom => vk::AccelerationStructureTypeKHR::BOTTOM_LEVEL, BufferAccelLevel::Top => vk::AccelerationStructureTypeKHR::TOP_LEVEL, }, ..Default::default() }; unsafe { context.device.create_acceleration_structure_khr(&create_info, None) }.unwrap() })) } pub fn get_image_info(&mut self, desc: &ImageDesc, all_usage_flags: vk::ImageUsageFlags) -> ImageInfo { let context = &self.context; *self .image_info .entry(ImageInfoKey { desc: *desc, all_usage_flags, }) .or_insert_with(|| { let image = context.device.create_image_from_desc(desc, all_usage_flags).unwrap(); let mem_req = unsafe { context.device.get_image_memory_requirements(image) }; unsafe { context.device.destroy_image(image, None) }; ImageInfo { mem_req } }) } pub fn get_image( &mut self, desc: &ImageDesc, info: &ImageInfo, alloc: &Alloc, all_usage_flags: vk::ImageUsageFlags, ) -> UniqueImage { let context = &self.context; *self .image .entry(ImageKey { desc: *desc, all_usage_flags, alloc: *alloc, }) .or_insert_with(|| { let image = context.device.create_image_from_desc(desc, all_usage_flags).unwrap(); let mem_req_check = unsafe { context.device.get_image_memory_requirements(image) }; assert_eq!(info.mem_req, mem_req_check); unsafe { context.device.bind_image_memory(image, alloc.mem, alloc.offset) }.unwrap(); Unique::new(image, context.allocate_handle_uid()) }) } pub fn get_image_view( &mut self, desc: &ImageDesc, image: UniqueImage, view_desc: ImageViewDesc, ) -> UniqueImageView { let context = &self.context; *self .image_view .entry(ImageViewKey { image, view_desc }) .or_insert_with(|| { let image_view_create_info = vk::ImageViewCreateInfo { image: image.0, view_type: desc.image_view_type(), format: view_desc.format.unwrap_or(desc.first_format()), subresource_range: vk::ImageSubresourceRange { aspect_mask: desc.aspect_mask, base_mip_level: 0, level_count: vk::REMAINING_MIP_LEVELS, base_array_layer: 0, layer_count: vk::REMAINING_ARRAY_LAYERS, }, ..Default::default() }; let image_view = unsafe { context.device.create_image_view(&image_view_create_info, None) }.unwrap(); Unique::new(image_view, context.allocate_handle_uid()) }) } } impl RenderCache { pub const MAX_ATTACHMENTS: usize = 3; pub fn new(context: &SharedContext) -> Self { Self { context: SharedContext::clone(context), render_pass: HashMap::new(), framebuffer: HashMap::new(), } } pub fn ui_stats_table_rows(&self, ui: &mut egui::Ui) { for &(name, len) in &[ ("render pass", self.render_pass.len()), ("framebuffer", self.framebuffer.len()), ] { ui.label(name); ui.label(format!("{}", len)); ui.end_row(); } } pub fn get_render_pass( &mut self, color_format: Option<vk::Format>, depth: Option<RenderPassDepth>, samples: vk::SampleCountFlags, ) -> UniqueRenderPass { let context = &self.context; *self .render_pass .entry(RenderPassKey { color_format, depth, samples, }) .or_insert_with(|| { let render_pass = { let is_msaa = samples != vk::SampleCountFlags::N1; let mut attachments = ArrayVec::<_, { Self::MAX_ATTACHMENTS }>::new(); let subpass_color_attachment = color_format.map(|color_format| { let index = attachments.len() as u32; attachments.push(vk::AttachmentDescription { flags: vk::AttachmentDescriptionFlags::empty(), format: color_format, samples, load_op: vk::AttachmentLoadOp::CLEAR, store_op: if is_msaa { vk::AttachmentStoreOp::DONT_CARE } else { vk::AttachmentStoreOp::STORE }, stencil_load_op: vk::AttachmentLoadOp::DONT_CARE, stencil_store_op: vk::AttachmentStoreOp::DONT_CARE, initial_layout: vk::ImageLayout::UNDEFINED, final_layout: vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL, }); vk::AttachmentReference { attachment: index, layout: vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL, } }); let subpass_resolve_attachment = color_format.filter(|_| is_msaa).map(|color_format| { let index = attachments.len() as u32; attachments.push(vk::AttachmentDescription { flags: vk::AttachmentDescriptionFlags::empty(), format: color_format, samples: vk::SampleCountFlags::N1, load_op: vk::AttachmentLoadOp::DONT_CARE, store_op: vk::AttachmentStoreOp::STORE, stencil_load_op: vk::AttachmentLoadOp::DONT_CARE, stencil_store_op: vk::AttachmentStoreOp::DONT_CARE, initial_layout: vk::ImageLayout::UNDEFINED, final_layout: vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL, }); vk::AttachmentReference { attachment: index, layout: vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL, } }); let subpass_depth_attachment = depth.as_ref().map(|depth| { let index = attachments.len() as u32; attachments.push(vk::AttachmentDescription { flags: vk::AttachmentDescriptionFlags::empty(), format: depth.format, samples, load_op: match depth.load_op { AttachmentLoadOp::Load => vk::AttachmentLoadOp::LOAD, AttachmentLoadOp::Clear => vk::AttachmentLoadOp::CLEAR, }, store_op: match depth.store_op { AttachmentStoreOp::Store => vk::AttachmentStoreOp::STORE, AttachmentStoreOp::None => vk::AttachmentStoreOp::DONT_CARE, }, stencil_load_op: vk::AttachmentLoadOp::DONT_CARE, stencil_store_op: vk::AttachmentStoreOp::DONT_CARE, initial_layout: match depth.load_op { AttachmentLoadOp::Load => vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL, AttachmentLoadOp::Clear => vk::ImageLayout::UNDEFINED, }, final_layout: vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL, }); vk::AttachmentReference { attachment: index, layout: vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL, } }); let subpass_description = vk::SubpassDescription::builder() .pipeline_bind_point(vk::PipelineBindPoint::GRAPHICS) .p_color_attachments( subpass_color_attachment.as_ref().map(slice::from_ref).unwrap_or(&[]), subpass_resolve_attachment.as_ref().map(slice::from_ref), ) .p_depth_stencil_attachment(subpass_depth_attachment.as_ref()); let render_pass_create_info = vk::RenderPassCreateInfo::builder() .p_attachments(&attachments) .p_subpasses(slice::from_ref(&subpass_description)); unsafe { context.device.create_render_pass(&render_pass_create_info, None) }.unwrap() }; Unique::new(render_pass, context.allocate_handle_uid()) }) } pub fn get_framebuffer( &mut self, render_pass: UniqueRenderPass, size: UVec2, color_output_image_view: Option<UniqueImageView>, color_temp_image_view: Option<UniqueImageView>, depth_image_view: Option<UniqueImageView>, ) -> UniqueFramebuffer { let context = &self.context; *self .framebuffer .entry(FramebufferKey { render_pass, size, color_output_image_view, color_temp_image_view, depth_image_view, }) .or_insert_with(|| { let mut attachments = ArrayVec::<_, { Self::MAX_ATTACHMENTS }>::new(); if let Some(image_view) = color_temp_image_view { attachments.push(image_view.0); } if let Some(image_view) = color_output_image_view { attachments.push(image_view.0); } if let Some(image_view) = depth_image_view { attachments.push(image_view.0); } let framebuffer_create_info = vk::FramebufferCreateInfo::builder() .render_pass(render_pass.0) .p_attachments(&attachments) .width(size.x) .height(size.y) .layers(1); let framebuffer = unsafe { context.device.create_framebuffer(&framebuffer_create_info, None) }.unwrap(); Unique::new(framebuffer, context.allocate_handle_uid()) }) } } impl Drop for RenderCache { fn drop(&mut self) { for (_, framebuffer) in self.framebuffer.drain() { unsafe { self.context.device.destroy_framebuffer(framebuffer.0, None); } } for (_, render_pass) in self.render_pass.drain() { unsafe { self.context.device.destroy_render_pass(render_pass.0, None); } } } } impl Drop for ResourceCache { fn drop(&mut self) { for (_, image_view) in self.image_view.drain() { unsafe { self.context.device.destroy_image_view(image_view.0, None); } } for (_, image) in self.image.drain() { unsafe { self.context.device.destroy_image(image.0, None); } } for (_, accel) in self.buffer_accel.drain() { unsafe { self.context.device.destroy_acceleration_structure_khr(accel, None); } } for (_, buffer) in self.buffer.drain() { unsafe { self.context.device.destroy_buffer(buffer.0, None); } } } }
rust
MIT
42fc4b496cce21e907eca7112e6d6334d35fc41a
2026-01-04T20:23:56.526296Z
false
sjb3d/caldera
https://github.com/sjb3d/caldera/blob/42fc4b496cce21e907eca7112e6d6334d35fc41a/caldera/src/maths.rs
caldera/src/maths.rs
use bytemuck::{Pod, Zeroable}; use std::ops::{Add, Mul}; pub use std::f32::consts::PI; pub use ultraviolet::*; pub trait AsSigned { type Output; fn as_signed(&self) -> Self::Output; } impl AsSigned for UVec2 { type Output = IVec2; fn as_signed(&self) -> Self::Output { IVec2::new(self.x as i32, self.y as i32) } } pub trait AsUnsigned { type Output; fn as_unsigned(&self) -> Self::Output; } impl AsUnsigned for IVec3 { type Output = UVec3; fn as_unsigned(&self) -> Self::Output { UVec3::new(self.x as u32, self.y as u32, self.z as u32) } } pub trait AsFloat { type Output; fn as_float(&self) -> Self::Output; } impl AsFloat for UVec2 { type Output = Vec2; fn as_float(&self) -> Self::Output { Vec2::new(self.x as f32, self.y as f32) } } pub trait MapMut { type Component; fn map_mut<F>(&self, f: F) -> Self where F: FnMut(Self::Component) -> Self::Component; } impl MapMut for UVec3 { type Component = u32; fn map_mut<F>(&self, mut f: F) -> Self where F: FnMut(Self::Component) -> Self::Component, { UVec3::new(f(self.x), f(self.y), f(self.z)) } } pub trait IsNan { fn is_nan(&self) -> bool; } impl IsNan for Vec3 { fn is_nan(&self) -> bool { self.x.is_nan() || self.y.is_nan() || self.z.is_nan() } } pub trait Saturated { fn saturated(&self) -> Self; } impl Saturated for Vec3 { fn saturated(&self) -> Self { self.clamped(Vec3::zero(), Vec3::one()) } } pub trait DivRoundUp { fn div_round_up(&self, divisor: u32) -> Self; } impl DivRoundUp for u32 { fn div_round_up(&self, divisor: u32) -> Self { (*self + (divisor - 1)) / divisor } } impl DivRoundUp for UVec2 { fn div_round_up(&self, divisor: u32) -> Self { (*self + Self::broadcast(divisor - 1)) / divisor } } pub trait TransformVec3 { fn transform_vec3(&self, vec: Vec3) -> Vec3; } impl TransformVec3 for Isometry3 { fn transform_vec3(&self, vec: Vec3) -> Vec3 { self.rotation * vec } } impl TransformVec3 for Similarity3 { fn transform_vec3(&self, vec: Vec3) -> Vec3 { self.rotation * (self.scale * vec) } } #[repr(C)] #[derive(Debug, Clone, Copy, Zeroable, Pod)] pub struct Transform3 { pub cols: [Vec3; 4], } impl Transform3 { pub fn identity() -> Self { Transform3::new(Vec3::unit_x(), Vec3::unit_y(), Vec3::unit_z(), Vec3::zero()) } pub fn new(col0: Vec3, col1: Vec3, col2: Vec3, col3: Vec3) -> Self { Self { cols: [col0, col1, col2, col3], } } pub fn extract_rotation(&self) -> Rotor3 { self.into_similarity().rotation } pub fn extract_translation(&self) -> Vec3 { self.cols[3] } pub fn into_similarity(self) -> Similarity3 { let scale = self.cols[0].cross(self.cols[1]).dot(self.cols[2]).powf(1.0 / 3.0); let rotation = Mat3::new(self.cols[0] / scale, self.cols[1] / scale, self.cols[2] / scale).into_rotor3(); let translation = self.cols[3]; Similarity3::new(translation, rotation, scale) } pub fn transposed(&self) -> TransposedTransform3 { TransposedTransform3::new( Vec4::new(self.cols[0].x, self.cols[1].x, self.cols[2].x, self.cols[3].x), Vec4::new(self.cols[0].y, self.cols[1].y, self.cols[2].y, self.cols[3].y), Vec4::new(self.cols[0].z, self.cols[1].z, self.cols[2].z, self.cols[3].z), ) } } impl Default for Transform3 { fn default() -> Self { Transform3::identity() } } impl Mul for Transform3 { type Output = Transform3; fn mul(self, rhs: Transform3) -> Self::Output { Transform3::new( self.transform_vec3(rhs.cols[0]), self.transform_vec3(rhs.cols[1]), self.transform_vec3(rhs.cols[2]), self * rhs.cols[3], ) } } impl Mul<Vec3> for Transform3 { type Output = Vec3; fn mul(self, rhs: Vec3) -> Self::Output { self.cols[0] * rhs.x + self.cols[1] * rhs.y + self.cols[2] * rhs.z + self.cols[3] } } impl TransformVec3 for Transform3 { fn transform_vec3(&self, vec: Vec3) -> Vec3 { self.cols[0] * vec.x + self.cols[1] * vec.y + self.cols[2] * vec.z } } pub trait IntoTransform { fn into_transform(self) -> Transform3; } impl IntoTransform for Mat4 { fn into_transform(self) -> Transform3 { Transform3::new( self.cols[0].truncated(), self.cols[1].truncated(), self.cols[2].truncated(), self.cols[3].truncated(), ) } } impl IntoTransform for Isometry3 { fn into_transform(self) -> Transform3 { self.into_homogeneous_matrix().into_transform() } } impl IntoTransform for Similarity3 { fn into_transform(self) -> Transform3 { self.into_homogeneous_matrix().into_transform() } } #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod)] pub struct TransposedTransform3 { pub cols: [Vec4; 3], } impl TransposedTransform3 { fn new(col0: Vec4, col1: Vec4, col2: Vec4) -> Self { Self { cols: [col0, col1, col2], } } } pub trait FromPackedUnorm<T> { fn from_packed_unorm(p: T) -> Self; } impl FromPackedUnorm<u32> for Vec4 { fn from_packed_unorm(p: u32) -> Self { let x = ((p & 0xff) as f32) / 255.0; let y = (((p >> 8) & 0xff) as f32) / 255.0; let z = (((p >> 16) & 0xff) as f32) / 255.0; let w = (((p >> 24) & 0xff) as f32) / 255.0; Vec4::new(x, y, z, w) } } pub trait IntoPackedUnorm<T> { fn into_packed_unorm(self) -> T; } impl IntoPackedUnorm<u16> for Vec2 { fn into_packed_unorm(self) -> u16 { let x = (self.x.max(0.0).min(1.0) * 255.0).round() as u8 as u16; let y = (self.y.max(0.0).min(1.0) * 255.0).round() as u8 as u16; x | (y << 8) } } impl IntoPackedUnorm<u32> for Vec2 { fn into_packed_unorm(self) -> u32 { let x = (self.x.max(0.0).min(1.0) * 65535.0).round() as u16 as u32; let y = (self.y.max(0.0).min(1.0) * 65535.0).round() as u16 as u32; x | (y << 16) } } impl IntoPackedUnorm<u32> for Vec3 { fn into_packed_unorm(self) -> u32 { let x = (self.x.max(0.0).min(1.0) * 255.0).round() as u8 as u32; let y = (self.y.max(0.0).min(1.0) * 255.0).round() as u8 as u32; let z = (self.z.max(0.0).min(1.0) * 255.0).round() as u8 as u32; x | (y << 8) | (z << 16) } } impl IntoPackedUnorm<u32> for Vec4 { fn into_packed_unorm(self) -> u32 { let x = (self.x.max(0.0).min(1.0) * 255.0).round() as u8 as u32; let y = (self.y.max(0.0).min(1.0) * 255.0).round() as u8 as u32; let z = (self.z.max(0.0).min(1.0) * 255.0).round() as u8 as u32; let w = (self.w.max(0.0).min(1.0) * 255.0).round() as u8 as u32; x | (y << 8) | (z << 16) | (w << 24) } } pub trait IntoPackedSnorm<T> { fn into_packed_snorm(self) -> T; } impl IntoPackedSnorm<u32> for Vec2 { fn into_packed_snorm(self) -> u32 { let x = (self.x.max(-1.0).min(1.0) * 32767.0).round() as i16 as u16 as u32; let y = (self.y.max(-1.0).min(1.0) * 32767.0).round() as i16 as u16 as u32; x | (y << 16) } } pub trait SumElements { type Output; fn sum_elements(&self) -> Self::Output; } impl SumElements for Vec3 { type Output = f32; fn sum_elements(&self) -> Self::Output { self.x + self.y + self.z } } pub trait CopySign { fn copysign(&self, other: Self) -> Self; } impl CopySign for Vec2 { fn copysign(&self, other: Self) -> Self { Self::new(self.x.copysign(other.x), self.y.copysign(other.y)) } } pub trait VecToOct { fn into_oct(self) -> Vec2; } impl VecToOct for Vec3 { fn into_oct(self) -> Vec2 { let p = self.xy() / self.abs().sum_elements(); if self.z > 0.0 { p } else { (Vec2::broadcast(1.0) - Vec2::new(p.y, p.x).abs()).copysign(p) } } } #[repr(C)] #[derive(Debug, Clone, Copy, Pod, Zeroable)] pub struct Scale2Offset2 { pub scale: Vec2, pub offset: Vec2, } impl Scale2Offset2 { pub fn new(scale: Vec2, offset: Vec2) -> Self { Self { scale, offset } } pub fn into_homogeneous_matrix(self) -> Mat3 { Mat3::new( Vec3::new(self.scale.x, 0.0, 0.0), Vec3::new(0.0, self.scale.y, 0.0), self.offset.into_homogeneous_point(), ) } pub fn inversed(&self) -> Self { // y = a*x + b => x = (y - b)/a let scale_rcp = Vec2::broadcast(1.0) / self.scale; Scale2Offset2 { scale: scale_rcp, offset: -self.offset * scale_rcp, } } } impl Mul for Scale2Offset2 { type Output = Self; #[allow(clippy::suspicious_arithmetic_impl)] fn mul(self, rhs: Scale2Offset2) -> Self::Output { // a(b(v)) = a.s*(b.s*v + b.o) + a.o Scale2Offset2 { scale: self.scale * rhs.scale, offset: self.scale.mul_add(rhs.offset, self.offset), } } } impl Mul<Vec2> for Scale2Offset2 { type Output = Vec2; #[allow(clippy::suspicious_arithmetic_impl)] fn mul(self, rhs: Vec2) -> Self::Output { self.scale.mul_add(rhs, self.offset) } } #[derive(Debug, Clone, Copy)] pub struct FieldOfView { pub tan_min: Vec2, pub tan_max: Vec2, } impl FieldOfView { pub fn new_symmetric(vertical_fov: f32, aspect_ratio: f32) -> Self { let tan_fov_y = (0.5 * vertical_fov).tan(); let tan_fov_x = aspect_ratio * tan_fov_y; Self { tan_min: Vec2::new(-tan_fov_x, -tan_fov_y), tan_max: Vec2::new(tan_fov_x, tan_fov_y), } } pub fn size(&self) -> Vec2 { self.tan_max - self.tan_min } pub fn view_xy_from_uv(&self) -> Scale2Offset2 { Scale2Offset2::new(self.size(), self.tan_min) * Scale2Offset2::new(Vec2::new(-1.0, 1.0), Vec2::new(1.0, 0.0)) } pub fn perspective_reversed_infinite_z(&self, z_near: f32) -> Mat4 { let tan_from_clip = Scale2Offset2::new(self.size(), self.tan_min) * Scale2Offset2::new(Vec2::new(0.5, -0.5), Vec2::broadcast(0.5)); let clip_from_tan = tan_from_clip.inversed(); Mat4::new( Vec4::new(clip_from_tan.scale.x, 0.0, 0.0, 0.0), Vec4::new(0.0, clip_from_tan.scale.y, 0.0, 0.0), Vec4::new(clip_from_tan.offset.x, clip_from_tan.offset.y, 0.0, -1.0), Vec4::new(0.0, 0.0, z_near, 0.0), ) } } impl Add<Vec2> for FieldOfView { type Output = Self; fn add(self, rhs: Vec2) -> Self::Output { Self { tan_min: self.tan_min + rhs, tan_max: self.tan_max + rhs, } } }
rust
MIT
42fc4b496cce21e907eca7112e6d6334d35fc41a
2026-01-04T20:23:56.526296Z
false
sjb3d/caldera
https://github.com/sjb3d/caldera/blob/42fc4b496cce21e907eca7112e6d6334d35fc41a/caldera/src/command_buffer.rs
caldera/src/command_buffer.rs
use crate::context::*; use spark::{vk, Builder}; use std::slice; struct CommandBufferSemaphores { image_available: vk::Semaphore, rendering_finished: vk::Semaphore, } struct CommandBufferSet { pool: vk::CommandPool, pre_swapchain_cmd: vk::CommandBuffer, post_swapchain_cmd: vk::CommandBuffer, fence: vk::Fence, semaphores: Option<CommandBufferSemaphores>, } pub struct CommandBufferAcquireResult { pub pre_swapchain_cmd: vk::CommandBuffer, pub post_swapchain_cmd: vk::CommandBuffer, pub image_available_semaphore: Option<vk::Semaphore>, } impl CommandBufferSet { fn new(context: &Context) -> Self { let device = &context.device; let pool = { let command_pool_create_info = vk::CommandPoolCreateInfo { queue_family_index: context.queue_family_index, ..Default::default() }; unsafe { device.create_command_pool(&command_pool_create_info, None) }.unwrap() }; let (pre_swapchain_cmd, post_swapchain_cmd) = { let command_buffer_allocate_info = vk::CommandBufferAllocateInfo { command_pool: pool, level: vk::CommandBufferLevel::PRIMARY, command_buffer_count: 2, ..Default::default() }; let mut command_buffers = [vk::CommandBuffer::null(); 2]; unsafe { device.allocate_command_buffers(&command_buffer_allocate_info, &mut command_buffers) }.unwrap(); (command_buffers[0], command_buffers[1]) }; let fence = { let fence_create_info = vk::FenceCreateInfo { flags: vk::FenceCreateFlags::SIGNALED, ..Default::default() }; unsafe { device.create_fence(&fence_create_info, None) }.unwrap() }; let semaphores = if context.surface.is_null() { None } else { Some(CommandBufferSemaphores { image_available: unsafe { device.create_semaphore(&Default::default(), None) }.unwrap(), rendering_finished: unsafe { device.create_semaphore(&Default::default(), None) }.unwrap(), }) }; Self { pool, pre_swapchain_cmd, post_swapchain_cmd, fence, semaphores, } } fn wait_for_fence(&self, context: &Context) { let timeout_ns = 1000 * 1000 * 1000; loop { let res = unsafe { context .device .wait_for_fences(slice::from_ref(&self.fence), true, timeout_ns) }; match res { Ok(_) => break, Err(vk::Result::TIMEOUT) => {} Err(err_code) => panic!("failed to wait for fence {}", err_code), } } } } pub struct CommandBufferPool { context: SharedContext, sets: [CommandBufferSet; Self::COUNT], index: usize, } impl CommandBufferPool { pub const COUNT: usize = 2; pub fn new(context: &SharedContext) -> Self { Self { context: SharedContext::clone(context), sets: [CommandBufferSet::new(context), CommandBufferSet::new(context)], index: 0, } } pub fn acquire(&mut self) -> CommandBufferAcquireResult { self.index = (self.index + 1) % Self::COUNT; let set = &self.sets[self.index]; set.wait_for_fence(&self.context); unsafe { self.context.device.reset_fences(slice::from_ref(&set.fence)) }.unwrap(); unsafe { self.context .device .reset_command_pool(set.pool, vk::CommandPoolResetFlags::empty()) } .unwrap(); let command_buffer_begin_info = vk::CommandBufferBeginInfo { flags: vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT, ..Default::default() }; unsafe { self.context .device .begin_command_buffer(set.pre_swapchain_cmd, &command_buffer_begin_info) } .unwrap(); unsafe { self.context .device .begin_command_buffer(set.post_swapchain_cmd, &command_buffer_begin_info) } .unwrap(); CommandBufferAcquireResult { pre_swapchain_cmd: set.pre_swapchain_cmd, image_available_semaphore: set.semaphores.as_ref().map(|s| s.image_available), post_swapchain_cmd: set.post_swapchain_cmd, } } pub fn submit(&self) -> Option<vk::Semaphore> { let set = &self.sets[self.index]; unsafe { self.context.device.end_command_buffer(set.pre_swapchain_cmd) }.unwrap(); unsafe { self.context.device.end_command_buffer(set.post_swapchain_cmd) }.unwrap(); let submit_info = [ *vk::SubmitInfo::builder().p_command_buffers(slice::from_ref(&set.pre_swapchain_cmd)), if let Some(semaphores) = set.semaphores.as_ref() { *vk::SubmitInfo::builder() .p_wait_semaphores( slice::from_ref(&semaphores.image_available), slice::from_ref(&vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT), ) .p_command_buffers(slice::from_ref(&set.post_swapchain_cmd)) .p_signal_semaphores(slice::from_ref(&semaphores.rendering_finished)) } else { *vk::SubmitInfo::builder().p_command_buffers(slice::from_ref(&set.post_swapchain_cmd)) }, ]; unsafe { self.context .device .queue_submit(self.context.queue, &submit_info, set.fence) } .unwrap(); set.semaphores.as_ref().map(|s| s.rendering_finished) } pub fn wait_after_submit(&self) { let set = &self.sets[self.index]; set.wait_for_fence(&self.context); } } impl Drop for CommandBufferPool { fn drop(&mut self) { let device = &self.context.device; for set in self.sets.iter() { unsafe { if let Some(semaphores) = set.semaphores.as_ref() { device.destroy_semaphore(semaphores.rendering_finished, None); device.destroy_semaphore(semaphores.image_available, None); } device.destroy_fence(set.fence, None); device.free_command_buffers(set.pool, &[set.pre_swapchain_cmd, set.post_swapchain_cmd]); device.destroy_command_pool(set.pool, None); } } } }
rust
MIT
42fc4b496cce21e907eca7112e6d6334d35fc41a
2026-01-04T20:23:56.526296Z
false
sjb3d/caldera
https://github.com/sjb3d/caldera/blob/42fc4b496cce21e907eca7112e6d6334d35fc41a/caldera/src/barrier.rs
caldera/src/barrier.rs
use bytemuck::Contiguous; use spark::{vk, Device}; use std::{ fmt, ops::{BitOr, BitOrAssign}, slice, }; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct AccessCategory(u32); impl AccessCategory { pub const READ: AccessCategory = AccessCategory(0x1); pub const WRITE: AccessCategory = AccessCategory(0x2); pub const ATOMIC: AccessCategory = AccessCategory(0x4); pub fn empty() -> Self { Self(0) } pub fn supports_overlap(&self) -> bool { self.0.count_ones() < 2 } } impl BitOr for AccessCategory { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl BitOrAssign for AccessCategory { fn bitor_assign(&mut self, rhs: Self) { self.0 |= rhs.0; } } macro_rules! base_usage_impl { ($usage:ident, $usage_bit:ident, $usage_bit_iter:ident) => { #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct $usage(u32); impl $usage { pub fn empty() -> Self { Self(0) } pub fn is_empty(self) -> bool { self.0 == 0 } pub fn contains(self, other: Self) -> bool { (self.0 & other.0) == other.0 } pub fn intersects(self, other: Self) -> bool { (self.0 & other.0) != 0 } fn iter_set_bits(self) -> $usage_bit_iter { $usage_bit_iter(self.0) } } impl BitOr for $usage { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl BitOrAssign for $usage { fn bitor_assign(&mut self, rhs: Self) { self.0 |= rhs.0; } } struct $usage_bit_iter(u32); impl Iterator for $usage_bit_iter { type Item = $usage_bit; fn next(&mut self) -> Option<Self::Item> { let pos = self.0.trailing_zeros(); if pos < 32 { let bit = 1 << pos; self.0 &= !bit; Some($usage_bit::from_integer(pos).unwrap()) } else { None } } } }; } macro_rules! buffer_usage_impl { ($(($name:ident, $usage_mask:expr, $stage_mask:expr, $access_mask:expr, $access_category:expr)),+ $(,)?) => { #[repr(u32)] #[derive(Clone, Copy, Contiguous)] #[allow(non_camel_case_types)] enum BufferUsageBit { $($name),+ } base_usage_impl!(BufferUsage, BufferUsageBit, BufferUsageBitIterator); impl fmt::Display for BufferUsage { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut has_output = false; for bit in self.iter_set_bits() { if has_output { f.write_str(" | ")?; } f.write_str(match bit { $(BufferUsageBit::$name => stringify!($name)),+ })?; has_output = true; } if !has_output { f.write_str("0")?; } Ok(()) } } impl BufferUsage { $(pub const $name: BufferUsage = BufferUsage(1 << (BufferUsageBit::$name as u32));)+ pub fn as_flags(self) -> vk::BufferUsageFlags { self.iter_set_bits() .map(|bit| match bit { $(BufferUsageBit::$name => $usage_mask),+ }) .fold(vk::BufferUsageFlags::empty(), |m, u| m | u) } pub fn as_stage_mask(self) -> vk::PipelineStageFlags { self.iter_set_bits() .map(|bit| match bit { $(BufferUsageBit::$name => $stage_mask),+ }) .fold(vk::PipelineStageFlags::empty(), |m, u| m | u) } pub fn as_access_mask(self) -> vk::AccessFlags { self.iter_set_bits() .map(|bit| match bit { $(BufferUsageBit::$name => $access_mask),+ }) .fold(vk::AccessFlags::empty(), |m, u| m | u) } pub fn as_access_category(self) -> AccessCategory { self.iter_set_bits() .map(|bit| match bit { $(BufferUsageBit::$name => $access_category),+ }) .fold(AccessCategory::empty(), |m, u| m | u) } } } } buffer_usage_impl! { ( TRANSFER_READ, vk::BufferUsageFlags::TRANSFER_SRC, vk::PipelineStageFlags::TRANSFER, vk::AccessFlags::TRANSFER_READ, AccessCategory::READ ), ( TRANSFER_WRITE, vk::BufferUsageFlags::TRANSFER_DST, vk::PipelineStageFlags::TRANSFER, vk::AccessFlags::TRANSFER_WRITE, AccessCategory::WRITE ), ( COMPUTE_STORAGE_READ, vk::BufferUsageFlags::STORAGE_BUFFER, vk::PipelineStageFlags::COMPUTE_SHADER, vk::AccessFlags::SHADER_READ, AccessCategory::READ ), ( COMPUTE_STORAGE_WRITE, vk::BufferUsageFlags::STORAGE_BUFFER, vk::PipelineStageFlags::COMPUTE_SHADER, vk::AccessFlags::SHADER_WRITE, AccessCategory::WRITE ), ( COMPUTE_STORAGE_ATOMIC, vk::BufferUsageFlags::STORAGE_BUFFER, vk::PipelineStageFlags::COMPUTE_SHADER, vk::AccessFlags::SHADER_READ | vk::AccessFlags::SHADER_WRITE, AccessCategory::ATOMIC ), ( VERTEX_BUFFER, vk::BufferUsageFlags::VERTEX_BUFFER, vk::PipelineStageFlags::VERTEX_INPUT, vk::AccessFlags::VERTEX_ATTRIBUTE_READ, AccessCategory::READ ), ( VERTEX_STORAGE_READ, vk::BufferUsageFlags::STORAGE_BUFFER, vk::PipelineStageFlags::VERTEX_SHADER, vk::AccessFlags::SHADER_READ, AccessCategory::READ ), ( INDEX_BUFFER, vk::BufferUsageFlags::INDEX_BUFFER, vk::PipelineStageFlags::VERTEX_INPUT, vk::AccessFlags::INDEX_READ, AccessCategory::READ ), ( FRAGMENT_STORAGE_READ, vk::BufferUsageFlags::STORAGE_BUFFER, vk::PipelineStageFlags::FRAGMENT_SHADER, vk::AccessFlags::SHADER_READ, AccessCategory::READ ), ( FRAGMENT_ACCELERATION_STRUCTURE, vk::BufferUsageFlags::SHADER_DEVICE_ADDRESS_KHR | vk::BufferUsageFlags::ACCELERATION_STRUCTURE_STORAGE_KHR, vk::PipelineStageFlags::FRAGMENT_SHADER, vk::AccessFlags::ACCELERATION_STRUCTURE_READ_KHR, AccessCategory::READ ), ( ACCELERATION_STRUCTURE_BUILD_INPUT, vk::BufferUsageFlags::SHADER_DEVICE_ADDRESS_KHR | vk::BufferUsageFlags::ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_KHR, vk::PipelineStageFlags::ACCELERATION_STRUCTURE_BUILD_KHR, vk::AccessFlags::SHADER_READ, AccessCategory::READ ), ( ACCELERATION_STRUCTURE_BUILD_SCRATCH, vk::BufferUsageFlags::SHADER_DEVICE_ADDRESS_KHR | vk::BufferUsageFlags::STORAGE_BUFFER, vk::PipelineStageFlags::ACCELERATION_STRUCTURE_BUILD_KHR, vk::AccessFlags::ACCELERATION_STRUCTURE_READ_KHR | vk::AccessFlags::ACCELERATION_STRUCTURE_WRITE_KHR, AccessCategory::READ | AccessCategory::WRITE ), ( BOTTOM_LEVEL_ACCELERATION_STRUCTURE_READ, vk::BufferUsageFlags::SHADER_DEVICE_ADDRESS_KHR | vk::BufferUsageFlags::ACCELERATION_STRUCTURE_STORAGE_KHR, vk::PipelineStageFlags::ACCELERATION_STRUCTURE_BUILD_KHR, vk::AccessFlags::ACCELERATION_STRUCTURE_READ_KHR, AccessCategory::READ ), ( BOTTOM_LEVEL_ACCELERATION_STRUCTURE_WRITE, vk::BufferUsageFlags::SHADER_DEVICE_ADDRESS_KHR | vk::BufferUsageFlags::ACCELERATION_STRUCTURE_STORAGE_KHR, vk::PipelineStageFlags::ACCELERATION_STRUCTURE_BUILD_KHR, vk::AccessFlags::ACCELERATION_STRUCTURE_WRITE_KHR, AccessCategory::WRITE ), ( TOP_LEVEL_ACCELERATION_STRUCTURE_WRITE, vk::BufferUsageFlags::SHADER_DEVICE_ADDRESS_KHR | vk::BufferUsageFlags::ACCELERATION_STRUCTURE_STORAGE_KHR, vk::PipelineStageFlags::ACCELERATION_STRUCTURE_BUILD_KHR, vk::AccessFlags::ACCELERATION_STRUCTURE_WRITE_KHR, AccessCategory::WRITE ), ( RAY_TRACING_ACCELERATION_STRUCTURE, vk::BufferUsageFlags::SHADER_DEVICE_ADDRESS_KHR | vk::BufferUsageFlags::ACCELERATION_STRUCTURE_STORAGE_KHR, vk::PipelineStageFlags::RAY_TRACING_SHADER_KHR, vk::AccessFlags::ACCELERATION_STRUCTURE_READ_KHR, AccessCategory::READ ), ( RAY_TRACING_SHADER_BINDING_TABLE, vk::BufferUsageFlags::SHADER_DEVICE_ADDRESS_KHR | vk::BufferUsageFlags::SHADER_BINDING_TABLE_KHR, vk::PipelineStageFlags::RAY_TRACING_SHADER_KHR, vk::AccessFlags::SHADER_READ, AccessCategory::READ ), ( RAY_TRACING_STORAGE_READ, vk::BufferUsageFlags::SHADER_DEVICE_ADDRESS_KHR | vk::BufferUsageFlags::STORAGE_BUFFER, vk::PipelineStageFlags::RAY_TRACING_SHADER_KHR, vk::AccessFlags::SHADER_READ, AccessCategory::READ ), ( TASK_STORAGE_READ, vk::BufferUsageFlags::STORAGE_BUFFER, vk::PipelineStageFlags::TASK_SHADER_NV, vk::AccessFlags::SHADER_READ, AccessCategory::READ ), ( MESH_STORAGE_READ, vk::BufferUsageFlags::STORAGE_BUFFER, vk::PipelineStageFlags::MESH_SHADER_NV, vk::AccessFlags::SHADER_READ, AccessCategory::READ ) } pub fn emit_buffer_barrier( old_usage: BufferUsage, new_usage: BufferUsage, buffer: vk::Buffer, device: &Device, cmd: vk::CommandBuffer, ) { let buffer_memory_barrier = vk::BufferMemoryBarrier { src_access_mask: old_usage.as_access_mask(), dst_access_mask: new_usage.as_access_mask(), src_queue_family_index: vk::QUEUE_FAMILY_IGNORED, dst_queue_family_index: vk::QUEUE_FAMILY_IGNORED, buffer, offset: 0, size: vk::WHOLE_SIZE, ..Default::default() }; let old_stage_mask = old_usage.as_stage_mask(); let new_stage_mask = new_usage.as_stage_mask(); unsafe { device.cmd_pipeline_barrier( cmd, if old_stage_mask.is_empty() { vk::PipelineStageFlags::BOTTOM_OF_PIPE } else { old_stage_mask }, if new_stage_mask.is_empty() { vk::PipelineStageFlags::TOP_OF_PIPE } else { new_stage_mask }, vk::DependencyFlags::empty(), &[], slice::from_ref(&buffer_memory_barrier), &[], ) } } macro_rules! image_usage_impl { ($(($name:ident, $usage_mask:expr, $stage_mask:expr, $access_mask:expr, $image_layout:expr, $access_category:expr)),+ $(,)?) => { #[repr(u32)] #[derive(Clone, Copy, Contiguous)] #[allow(non_camel_case_types)] enum ImageUsageBit { $($name),+ } base_usage_impl!(ImageUsage, ImageUsageBit, ImageUsageBitIterator); impl fmt::Display for ImageUsage { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut has_output = false; for bit in self.iter_set_bits() { if has_output { f.write_str(" | ")?; } f.write_str(match bit { $(ImageUsageBit::$name => stringify!($name)),+ })?; has_output = true; } if !has_output { f.write_str("0")?; } Ok(()) } } impl ImageUsage { $(pub const $name: ImageUsage = ImageUsage(1 << (ImageUsageBit::$name as u32));)+ pub fn as_flags(self) -> vk::ImageUsageFlags { self.iter_set_bits() .map(|bit| match bit { $(ImageUsageBit::$name => $usage_mask),+ }) .fold(vk::ImageUsageFlags::empty(), |m, u| m | u) } pub fn as_stage_mask(self) -> vk::PipelineStageFlags { self.iter_set_bits() .map(|bit| match bit { $(ImageUsageBit::$name => $stage_mask),+ }) .fold(vk::PipelineStageFlags::empty(), |m, u| m | u) } pub fn as_access_mask(self) -> vk::AccessFlags { self.iter_set_bits() .map(|bit| match bit { $(ImageUsageBit::$name => $access_mask),+ }) .fold(vk::AccessFlags::empty(), |m, u| m | u) } pub fn as_image_layout(self) -> vk::ImageLayout { self.iter_set_bits() .map(|bit| match bit { $(ImageUsageBit::$name => $image_layout),+ }) .fold(vk::ImageLayout::UNDEFINED, |m, u| { if m == u { m } else if m == vk::ImageLayout::UNDEFINED { u } else { panic!("cannot set image layouts {} and {} at the same time", m, u) } }) } pub fn as_access_category(self) -> AccessCategory { self.iter_set_bits() .map(|bit| match bit { $(ImageUsageBit::$name => $access_category),+ }) .fold(AccessCategory::empty(), |m, u| m | u) } } } } image_usage_impl! { ( TRANSFER_WRITE, vk::ImageUsageFlags::TRANSFER_DST, vk::PipelineStageFlags::TRANSFER, vk::AccessFlags::TRANSFER_WRITE, vk::ImageLayout::TRANSFER_DST_OPTIMAL, AccessCategory::WRITE ), ( SWAPCHAIN, vk::ImageUsageFlags::empty(), vk::PipelineStageFlags::empty(), vk::AccessFlags::empty(), vk::ImageLayout::PRESENT_SRC_KHR, AccessCategory::READ ), ( COLOR_ATTACHMENT_WRITE, vk::ImageUsageFlags::COLOR_ATTACHMENT, vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT, vk::AccessFlags::COLOR_ATTACHMENT_WRITE, vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL, AccessCategory::WRITE ), ( DEPTH_ATTACHMENT, vk::ImageUsageFlags::DEPTH_STENCIL_ATTACHMENT, vk::PipelineStageFlags::EARLY_FRAGMENT_TESTS | vk::PipelineStageFlags::LATE_FRAGMENT_TESTS, vk::AccessFlags::DEPTH_STENCIL_ATTACHMENT_READ | vk::AccessFlags::DEPTH_STENCIL_ATTACHMENT_WRITE, vk::ImageLayout::DEPTH_ATTACHMENT_OPTIMAL, AccessCategory::READ | AccessCategory::WRITE ), ( FRAGMENT_STORAGE_READ, vk::ImageUsageFlags::STORAGE, vk::PipelineStageFlags::FRAGMENT_SHADER, vk::AccessFlags::SHADER_READ, vk::ImageLayout::GENERAL, AccessCategory::READ ), ( FRAGMENT_SAMPLED, vk::ImageUsageFlags::SAMPLED, vk::PipelineStageFlags::FRAGMENT_SHADER, vk::AccessFlags::SHADER_READ, vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL, AccessCategory::READ ), ( COMPUTE_STORAGE_READ, vk::ImageUsageFlags::STORAGE, vk::PipelineStageFlags::COMPUTE_SHADER, vk::AccessFlags::SHADER_READ, vk::ImageLayout::GENERAL, AccessCategory::READ ), ( COMPUTE_STORAGE_WRITE, vk::ImageUsageFlags::STORAGE, vk::PipelineStageFlags::COMPUTE_SHADER, vk::AccessFlags::SHADER_WRITE, vk::ImageLayout::GENERAL, AccessCategory::WRITE ), ( COMPUTE_SAMPLED, vk::ImageUsageFlags::SAMPLED, vk::PipelineStageFlags::COMPUTE_SHADER, vk::AccessFlags::SHADER_READ, vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL, AccessCategory::READ ), ( TRANSIENT_COLOR_ATTACHMENT, vk::ImageUsageFlags::TRANSIENT_ATTACHMENT | vk::ImageUsageFlags::COLOR_ATTACHMENT, vk::PipelineStageFlags::empty(), vk::AccessFlags::empty(), vk::ImageLayout::UNDEFINED, AccessCategory::READ | AccessCategory::WRITE ), ( TRANSIENT_DEPTH_ATTACHMENT, vk::ImageUsageFlags::TRANSIENT_ATTACHMENT | vk::ImageUsageFlags::DEPTH_STENCIL_ATTACHMENT, vk::PipelineStageFlags::empty(), vk::AccessFlags::empty(), vk::ImageLayout::UNDEFINED, AccessCategory::READ | AccessCategory::WRITE ), ( RAY_TRACING_STORAGE_READ, vk::ImageUsageFlags::STORAGE, vk::PipelineStageFlags::RAY_TRACING_SHADER_KHR, vk::AccessFlags::SHADER_READ, vk::ImageLayout::GENERAL, AccessCategory::READ ), ( RAY_TRACING_STORAGE_WRITE, vk::ImageUsageFlags::STORAGE, vk::PipelineStageFlags::RAY_TRACING_SHADER_KHR, vk::AccessFlags::SHADER_WRITE, vk::ImageLayout::GENERAL, AccessCategory::WRITE ), ( RAY_TRACING_SAMPLED, vk::ImageUsageFlags::SAMPLED, vk::PipelineStageFlags::RAY_TRACING_SHADER_KHR, vk::AccessFlags::SHADER_READ, vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL, AccessCategory::READ ), } pub fn emit_image_barrier( old_usage: ImageUsage, new_usage: ImageUsage, image: vk::Image, aspect_mask: vk::ImageAspectFlags, device: &Device, cmd: vk::CommandBuffer, ) { let image_memory_barrier = vk::ImageMemoryBarrier { src_access_mask: old_usage.as_access_mask(), dst_access_mask: new_usage.as_access_mask(), old_layout: old_usage.as_image_layout(), new_layout: new_usage.as_image_layout(), src_queue_family_index: vk::QUEUE_FAMILY_IGNORED, dst_queue_family_index: vk::QUEUE_FAMILY_IGNORED, image, subresource_range: vk::ImageSubresourceRange { aspect_mask, base_mip_level: 0, level_count: vk::REMAINING_MIP_LEVELS, base_array_layer: 0, layer_count: vk::REMAINING_ARRAY_LAYERS, }, ..Default::default() }; let old_stage_mask = old_usage.as_stage_mask(); let new_stage_mask = new_usage.as_stage_mask(); unsafe { device.cmd_pipeline_barrier( cmd, if old_stage_mask.is_empty() { vk::PipelineStageFlags::BOTTOM_OF_PIPE } else { old_stage_mask }, if new_stage_mask.is_empty() { vk::PipelineStageFlags::TOP_OF_PIPE } else { new_stage_mask }, vk::DependencyFlags::empty(), &[], &[], slice::from_ref(&image_memory_barrier), ) } }
rust
MIT
42fc4b496cce21e907eca7112e6d6334d35fc41a
2026-01-04T20:23:56.526296Z
false
sjb3d/caldera
https://github.com/sjb3d/caldera/blob/42fc4b496cce21e907eca7112e6d6334d35fc41a/caldera/src/app_base.rs
caldera/src/app_base.rs
use crate::prelude::*; use spark::{vk, Device}; use std::slice; use winit::{ event::Event, event_loop::{ControlFlow, EventLoopWindowTarget}, window::Window, }; pub fn set_viewport_helper(device: &Device, cmd: vk::CommandBuffer, size: UVec2) { let viewport = vk::Viewport { width: size.x as f32, height: size.y as f32, max_depth: 1.0, ..Default::default() }; let scissor = vk::Rect2D { extent: vk::Extent2D { width: size.x, height: size.y, }, ..Default::default() }; unsafe { device.cmd_set_viewport(cmd, 0, slice::from_ref(&viewport)); device.cmd_set_scissor(cmd, 0, slice::from_ref(&scissor)); } } pub fn dispatch_helper( device: &Device, pipeline_cache: &PipelineCache, cmd: vk::CommandBuffer, shader_name: &str, constants: &[SpecializationConstant], descriptor_set: DescriptorSet, grid_size: UVec2, ) { let pipeline_layout = pipeline_cache.get_pipeline_layout(slice::from_ref(&descriptor_set.layout)); let pipeline = pipeline_cache.get_compute(shader_name, constants, pipeline_layout); unsafe { device.cmd_bind_pipeline(cmd, vk::PipelineBindPoint::COMPUTE, pipeline); device.cmd_bind_descriptor_sets( cmd, vk::PipelineBindPoint::COMPUTE, pipeline_layout, 0, slice::from_ref(&descriptor_set.set), &[], ); device.cmd_dispatch(cmd, grid_size.x, grid_size.y, 1); } } #[allow(clippy::too_many_arguments)] pub fn draw_helper( device: &Device, pipeline_cache: &PipelineCache, cmd: vk::CommandBuffer, state: &GraphicsPipelineState, vertex_shader_name: &str, fragment_shader_name: &str, descriptor_set: DescriptorSet, vertex_count: u32, ) { let pipeline_layout = pipeline_cache.get_pipeline_layout(slice::from_ref(&descriptor_set.layout)); let pipeline = pipeline_cache.get_graphics( VertexShaderDesc::standard(vertex_shader_name), fragment_shader_name, pipeline_layout, state, ); unsafe { device.cmd_bind_pipeline(cmd, vk::PipelineBindPoint::GRAPHICS, pipeline); device.cmd_bind_descriptor_sets( cmd, vk::PipelineBindPoint::GRAPHICS, pipeline_layout, 0, slice::from_ref(&descriptor_set.set), &[], ); device.cmd_draw(cmd, vertex_count, 1, 0, 0); } } pub struct AppDisplay { pub swapchain: Swapchain, pub recreate_swapchain: bool, } pub struct AppSystems { pub task_system: BackgroundTaskSystem, pub descriptor_pool: DescriptorPool, pub pipeline_cache: PipelineCache, pub command_buffer_pool: CommandBufferPool, pub query_pool: QueryPool, pub render_graph: RenderGraph, pub resource_loader: ResourceLoader, } pub struct AppBase { pub window: Window, pub exit_requested: bool, pub context: SharedContext, pub display: AppDisplay, pub egui_ctx: egui::Context, pub egui_winit: egui_winit::State, pub egui_renderer: spark_egui::Renderer, pub systems: AppSystems, } impl AppDisplay { pub const SWAPCHAIN_USAGE: vk::ImageUsageFlags = vk::ImageUsageFlags::COLOR_ATTACHMENT; pub fn new(context: &SharedContext, window: &Window) -> Self { let window_extent = { let inner_size = window.inner_size(); vk::Extent2D { width: inner_size.width, height: inner_size.height, } }; let swapchain = Swapchain::new(context, window_extent, Self::SWAPCHAIN_USAGE); Self { swapchain, recreate_swapchain: false, } } pub fn acquire(&mut self, window: &Window, image_available_semaphore: vk::Semaphore) -> UniqueImage { loop { if self.recreate_swapchain { let window_extent = { let inner_size = window.inner_size(); vk::Extent2D { width: inner_size.width, height: inner_size.height, } }; self.swapchain.recreate(window_extent, Self::SWAPCHAIN_USAGE); self.recreate_swapchain = false; } match self.swapchain.acquire(image_available_semaphore) { SwapchainAcquireResult::Ok(image) => break image, SwapchainAcquireResult::RecreateSoon(image) => { self.recreate_swapchain = true; break image; } SwapchainAcquireResult::RecreateNow => self.recreate_swapchain = true, }; } } pub fn present(&mut self, swap_image: UniqueImage, rendering_finished_semaphore: vk::Semaphore) { self.swapchain.present(swap_image, rendering_finished_semaphore); } } impl AppSystems { pub fn new(context: &SharedContext) -> Self { let task_system = BackgroundTaskSystem::new(); let descriptor_pool = DescriptorPool::new(context); let pipeline_cache = PipelineCache::new(context, "spv/bin"); let command_buffer_pool = CommandBufferPool::new(context); let query_pool = QueryPool::new(context); const CHUNK_SIZE: u32 = 128 * 1024 * 1024; const STAGING_SIZE: u32 = 4 * 1024 * 1024; let resources = Resources::new(context, CHUNK_SIZE); let render_graph = RenderGraph::new(context, &resources, CHUNK_SIZE, CHUNK_SIZE, STAGING_SIZE); let resource_loader = ResourceLoader::new(context, &resources, CHUNK_SIZE); Self { task_system, descriptor_pool, pipeline_cache, command_buffer_pool, query_pool, render_graph, resource_loader, } } pub fn acquire_command_buffer(&mut self) -> CommandBufferAcquireResult { let cbar = self.command_buffer_pool.acquire(); self.pipeline_cache.begin_frame(); self.render_graph.begin_frame(); self.descriptor_pool.begin_frame(); self.query_pool.begin_frame(cbar.pre_swapchain_cmd); self.resource_loader.begin_frame(cbar.pre_swapchain_cmd); cbar } pub fn draw_ui(&mut self, ctx: &egui::Context) { egui::Window::new("Memory") .default_pos([360.0, 5.0]) .default_size([270.0, 310.0]) .default_open(false) .show(ctx, |ui| { egui::Grid::new("memory_grid").show(ui, |ui| { ui.label("Stat"); ui.label("Value"); ui.end_row(); self.pipeline_cache.ui_stats_table_rows(ui); self.render_graph.ui_stats_table_rows(ui); self.descriptor_pool.ui_stats_table_rows(ui); }); }); egui::Window::new("Timestamps") .default_pos([410.0, 30.0]) .default_size([220.0, 120.0]) .show(ctx, |ui| { self.query_pool.ui_timestamp_table(ui); }); } pub fn submit_command_buffer(&mut self, cbar: &CommandBufferAcquireResult) -> Option<vk::Semaphore> { self.query_pool.end_frame(cbar.post_swapchain_cmd); self.descriptor_pool.end_frame(); self.render_graph.end_frame(); self.command_buffer_pool.submit() } } pub enum AppEventResult { None, Redraw, Destroy, } impl AppBase { pub fn new(window: Window, params: &ContextParams) -> Self { let context = Context::new(Some(&window), params); let display = AppDisplay::new(&context, &window); let egui_max_vertex_count = 64 * 1024; let egui_max_texture_side = context .physical_device_properties .limits .max_image_dimension_2d .min(2048); let egui_ctx = egui::Context::default(); let mut egui_winit = egui_winit::State::new(&window); egui_winit.set_pixels_per_point(window.scale_factor() as f32); egui_winit.set_max_texture_side(egui_max_texture_side as usize); let egui_renderer = spark_egui::Renderer::new( &context.device, &context.physical_device_properties, &context.physical_device_memory_properties, egui_max_vertex_count, egui_max_texture_side, ); let systems = AppSystems::new(&context); Self { window, exit_requested: false, context, display, egui_ctx, egui_winit, egui_renderer, systems, } } pub fn ui_begin_frame(&mut self) { let raw_input = self.egui_winit.take_egui_input(&self.window); self.egui_ctx.begin_frame(raw_input); } pub fn ui_end_frame(&mut self, cmd: vk::CommandBuffer) { let egui::FullOutput { platform_output, repaint_after: _repaint_after, textures_delta, shapes, } = self.egui_ctx.end_frame(); self.egui_winit .handle_platform_output(&self.window, &self.egui_ctx, platform_output); let clipped_primitives = self.egui_ctx.tessellate(shapes); self.egui_renderer.update( &self.context.device, &self.context.physical_device_memory_properties, cmd, clipped_primitives, textures_delta, ); } pub fn process_event<T>( &mut self, event: &Event<'_, T>, _target: &EventLoopWindowTarget<T>, control_flow: &mut ControlFlow, ) -> AppEventResult { let mut result = AppEventResult::None; match event { Event::RedrawEventsCleared => { result = AppEventResult::Redraw; } Event::WindowEvent { event, .. } => { let event_response = self.egui_winit.on_event(&self.egui_ctx, &event); if event_response.repaint { self.window.request_redraw(); } } Event::LoopDestroyed => { result = AppEventResult::Destroy; } _ => {} } if self.exit_requested { control_flow.set_exit(); } else { control_flow.set_poll(); } result } } impl Drop for AppBase { fn drop(&mut self) { unsafe { self.context.device.device_wait_idle() }.unwrap(); self.egui_renderer.destroy(&self.context.device); } }
rust
MIT
42fc4b496cce21e907eca7112e6d6334d35fc41a
2026-01-04T20:23:56.526296Z
false
sjb3d/caldera
https://github.com/sjb3d/caldera/blob/42fc4b496cce21e907eca7112e6d6334d35fc41a/caldera/src/allocator.rs
caldera/src/allocator.rs
use crate::context::*; use spark::{vk, Builder}; #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub struct Alloc { pub mem: vk::DeviceMemory, pub offset: vk::DeviceSize, } struct Chunk { context: SharedContext, memory_type_index: u32, mem: vk::DeviceMemory, size: u32, offset: u32, } impl Chunk { pub fn new(context: &SharedContext, memory_type_index: u32, size: u32) -> Self { let mem = { let mut memory_allocate_info = vk::MemoryAllocateInfo::builder() .allocation_size(vk::DeviceSize::from(size)) .memory_type_index(memory_type_index); let mut flags_info = vk::MemoryAllocateFlagsInfo { flags: vk::MemoryAllocateFlagsKHR::DEVICE_ADDRESS_KHR, ..Default::default() }; if context .physical_device_features .buffer_device_address .buffer_device_address .as_bool() { memory_allocate_info = memory_allocate_info.insert_next(&mut flags_info); } unsafe { context.device.allocate_memory(&memory_allocate_info, None) }.unwrap() }; Self { context: SharedContext::clone(context), memory_type_index, mem, size, offset: 0, } } pub fn allocate(&mut self, mem_req: &vk::MemoryRequirements) -> Option<Alloc> { let alignment_mask = (mem_req.alignment as u32) - 1; let size = mem_req.size as u32; let offset = (self.offset + alignment_mask) & !alignment_mask; let next_offset = offset + size; if next_offset <= self.size { self.offset = next_offset; Some(Alloc { mem: self.mem, offset: vk::DeviceSize::from(offset), }) } else { None } } pub fn reset(&mut self) { self.offset = 0; } } impl Drop for Chunk { fn drop(&mut self) { unsafe { self.context.device.free_memory(self.mem, None); } } } pub struct Allocator { context: SharedContext, chunks: Vec<Chunk>, chunk_size: u32, } impl Allocator { pub fn new(context: &SharedContext, chunk_size: u32) -> Self { Self { context: SharedContext::clone(context), chunks: Vec::new(), chunk_size, } } pub fn allocate( &mut self, mem_req: &vk::MemoryRequirements, memory_property_flags: vk::MemoryPropertyFlags, ) -> Alloc { let memory_type_index = self .context .get_memory_type_index(mem_req.memory_type_bits, memory_property_flags) .unwrap(); for chunk in self.chunks.iter_mut() { if chunk.memory_type_index == memory_type_index { if let Some(alloc) = chunk.allocate(mem_req) { return alloc; } } } let mut alloc_size = self.chunk_size; if (alloc_size as vk::DeviceSize) < mem_req.size { alloc_size = mem_req.size.next_power_of_two() as u32; println!("allocator: adding large chunk size {} MB", alloc_size / (1024 * 1024)); } let mut chunk = Chunk::new(&self.context, memory_type_index, alloc_size); let alloc = chunk.allocate(mem_req); self.chunks.push(chunk); alloc.unwrap() } pub fn reset(&mut self) { for chunk in self.chunks.iter_mut() { chunk.reset(); } } pub fn ui_stats_table_rows(&self, ui: &mut egui::Ui, name: &str) { ui.label(name); ui.label(format!( "{} MB", self.chunks.iter().map(|chunk| chunk.size as usize).sum::<usize>() / (1024 * 1024) )); ui.end_row(); } }
rust
MIT
42fc4b496cce21e907eca7112e6d6334d35fc41a
2026-01-04T20:23:56.526296Z
false
sjb3d/caldera
https://github.com/sjb3d/caldera/blob/42fc4b496cce21e907eca7112e6d6334d35fc41a/caldera/src/color_space.rs
caldera/src/color_space.rs
use crate::maths::*; fn lerp_mat3(a: &Mat3, b: &Mat3, t: f32) -> Mat3 { (*a) * (1.0 - t) + (*b) * t } pub trait Gamma { fn into_linear(self) -> Self; fn into_gamma(self) -> Self; } impl Gamma for Vec3 { fn into_linear(self) -> Self { self.map(|x: f32| { if x < 0.04045 { x / 12.92 } else { ((x + 0.055) / 1.055).powf(2.4) } }) } fn into_gamma(self) -> Self { self.map(|x: f32| { if x < 0.0031308 { x * 12.92 } else { (x.powf(1.0 / 2.4) * 1.055) - 0.055 } }) } } // assumes Rec709 primaries pub trait Luminance { fn luminance(&self) -> f32; } impl Luminance for Vec3 { #[allow(clippy::excessive_precision)] fn luminance(&self) -> f32 { self.dot(Vec3::new(0.2126729, 0.7151522, 0.0721750)) } } #[allow(clippy::excessive_precision)] pub const fn xyz_from_rec709_matrix() -> Mat3 { // reference: http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html Mat3::new( Vec3::new(0.4124564, 0.2126729, 0.0193339), Vec3::new(0.3575761, 0.7151522, 0.1191920), Vec3::new(0.1804375, 0.0721750, 0.9503041), ) } #[allow(clippy::excessive_precision)] pub const fn rec709_from_xyz_matrix() -> Mat3 { // reference: http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html Mat3::new( Vec3::new(3.2404542, -0.9692660, 0.0556434), Vec3::new(-1.5371385, 1.8760108, -0.2040259), Vec3::new(-0.4985314, 0.0415560, 1.0572252), ) } #[allow(clippy::excessive_precision)] pub const fn ap1_from_xyz_matrix() -> Mat3 { // reference: https://github.com/ampas/aces-dev/blob/master/transforms/ctl/README-MATRIX.md Mat3::new( Vec3::new(1.6410233797, -0.6636628587, 0.0117218943), Vec3::new(-0.3248032942, 1.6153315917, -0.0082844420), Vec3::new(-0.2364246952, 0.0167563477, 0.9883948585), ) } #[allow(clippy::excessive_precision)] pub const fn xyz_from_ap1_matrix() -> Mat3 { // reference: https://github.com/ampas/aces-dev/blob/master/transforms/ctl/README-MATRIX.md Mat3::new( Vec3::new(0.6624541811, 0.2722287168, -0.0055746495), Vec3::new(0.1340042065, 0.6740817658, 0.0040607335), Vec3::new(0.1561876870, 0.0536895174, 1.0103391003), ) } #[allow(clippy::excessive_precision)] pub fn derive_aces_fit_matrices() { let xyz_from_rec709 = xyz_from_rec709_matrix(); let d60_from_d65 = chromatic_adaptation_matrix(bradford_lms_from_xyz_matrix(), WhitePoint::D60, WhitePoint::D65); let ap1_from_xyz = ap1_from_xyz_matrix(); // reference: https://github.com/ampas/aces-dev/blob/master/transforms/ctl/README-MATRIX.md // reference: https://github.com/ampas/aces-dev/blob/master/transforms/ctl/rrt/RRT.ctl (RRT_SAT_MAT) // reference: https://github.com/ampas/aces-dev/blob/master/transforms/ctl/odt/sRGB/ODT.Academy.sRGB_100nits_dim.ctl (ODT_SAT_MAT) let luma_from_ap1_vec = Vec3::new(0.2722287168, 0.6740817658, 0.0536895174); let luma_from_ap1 = Mat3::new(luma_from_ap1_vec, luma_from_ap1_vec, luma_from_ap1_vec).transposed(); let rrt_sat_factor = 0.96; let rrt_sat = lerp_mat3(&luma_from_ap1, &Mat3::identity(), rrt_sat_factor); let odt_sat_factor = 0.93; let odt_sat = lerp_mat3(&luma_from_ap1, &Mat3::identity(), odt_sat_factor); let acescg_from_rec709 = ap1_from_xyz * d60_from_d65 * xyz_from_rec709; let rec709_from_acescg = acescg_from_rec709.inversed(); println!("acescg_from_rec709 = {:#?}", acescg_from_rec709); println!("rec709_from_acescg = {:#?}", rec709_from_acescg); // expected to match https://github.com/TheRealMJP/BakingLab/blob/master/BakingLab/ACES.hlsl let fit_from_rec709 = rrt_sat * acescg_from_rec709; let rec709_from_fit = rec709_from_acescg * odt_sat; println!("fit_from_rec709 = {:#?}", fit_from_rec709); println!("rec709_from_fit = {:#?}", rec709_from_fit); } pub trait ToXYZ { type Output; fn to_xyz(&self) -> Self::Output; } impl ToXYZ for Vec2 { type Output = Vec3; fn to_xyz(&self) -> Self::Output { Vec3::new(self.x / self.y, 1.0, (1.0 - self.x - self.y) / self.y) } } #[derive(Debug, Clone, Copy)] pub enum WhitePoint { D60, D65, E, Custom { chroma: Vec2 }, } impl Default for WhitePoint { fn default() -> Self { Self::D65 } } impl WhitePoint { fn to_chroma(self) -> Vec2 { match self { Self::D60 => Vec2::new(0.32168, 0.33767), Self::D65 => Vec2::new(0.31270, 0.32900), Self::E => Vec2::new(0.3333, 0.3333), Self::Custom { chroma } => chroma, } } } #[allow(clippy::excessive_precision)] pub const fn bradford_lms_from_xyz_matrix() -> Mat3 { Mat3::new( Vec3::new(0.8951000, -0.7502000, 0.0389000), Vec3::new(0.2664000, 1.7135000, -0.0685000), Vec3::new(-0.1614000, 0.0367000, 1.0296000), ) } pub fn chromatic_adaptation_matrix(lms_from_xyz: Mat3, dst: WhitePoint, src: WhitePoint) -> Mat3 { let dst_lms = lms_from_xyz * dst.to_chroma().to_xyz(); let src_lms = lms_from_xyz * src.to_chroma().to_xyz(); lms_from_xyz.inversed() * Mat3::from_nonuniform_scale(dst_lms / src_lms) * lms_from_xyz }
rust
MIT
42fc4b496cce21e907eca7112e6d6334d35fc41a
2026-01-04T20:23:56.526296Z
false
sjb3d/caldera
https://github.com/sjb3d/caldera/blob/42fc4b496cce21e907eca7112e6d6334d35fc41a/caldera/src/loader.rs
caldera/src/loader.rs
use crate::{heap::*, prelude::*}; use bytemuck::Pod; use slotmap::{new_key_type, SlotMap}; use spark::vk; use std::{ collections::VecDeque, future::Future, mem, pin::Pin, slice, sync::{Arc, Mutex}, task::{Context as PollCtx, Poll, Waker}, thread, }; use tokio::{ runtime::Builder, sync::{mpsc, oneshot}, }; type BackgroundTask = Pin<Box<dyn Future<Output = ()> + Send>>; pub struct BackgroundTaskSystem { send: mpsc::Sender<BackgroundTask>, } impl BackgroundTaskSystem { pub fn new() -> Self { let (send, mut recv) = mpsc::channel(1); thread::spawn({ move || { let rt = Builder::new_multi_thread().enable_all().build().unwrap(); rt.block_on(async { while let Some(task) = recv.recv().await { rt.spawn(task); } }); } }); Self { send } } pub fn spawn_task<F, T>(&self, f: F) -> TaskOutput<T> where F: Future<Output = T> + Send + 'static, T: Send + 'static, { let (tx, rx) = oneshot::channel(); let task = async move { let output = f.await; tx.send(output) .unwrap_or_else(|_e| panic!("failed to send output to receiver")); }; self.send .blocking_send(Box::pin(task)) .unwrap_or_else(|_e| panic!("failed to send task to runner")); TaskOutput::Waiting(rx) } } pub enum TaskOutput<T> { Waiting(oneshot::Receiver<T>), Received(T), } impl<T> TaskOutput<T> { pub fn get_mut(&mut self) -> Option<&mut T> { if let Self::Waiting(rx) = self { match rx.try_recv() { Ok(t) => *self = Self::Received(t), Err(oneshot::error::TryRecvError::Closed) => panic!(), Err(oneshot::error::TryRecvError::Empty) => {} } } if let Self::Received(t) = self { Some(t) } else { None } } pub fn get(&mut self) -> Option<&T> { self.get_mut().map(|value| &*value) } } struct StagingMapping(*mut u8); unsafe impl Send for StagingMapping {} unsafe impl Sync for StagingMapping {} new_key_type! { struct StagingAllocId; } enum StagingAllocState { Pending { waker: Option<Waker> }, Done { offset: u32 }, } struct StagingAlloc { size: u32, alignment: u32, state: StagingAllocState, } #[derive(Clone, Copy)] struct StagingRegion { offset: u32, size: u32, } struct StagingDesc { _buffer_id: BufferId, buffer: vk::Buffer, mapping: StagingMapping, alignment: u32, } impl StagingDesc { fn new(context: &SharedContext, resources: &SharedResources, size: u32) -> Self { let mut resources_lock = resources.lock().unwrap(); let buffer_desc = BufferDesc::new(size as usize); let buffer_id = resources_lock.create_buffer( &buffer_desc, BufferUsage::TRANSFER_READ, vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT, ); let buffer_resource = resources_lock.buffer_resource(buffer_id); let buffer = buffer_resource.buffer().0; let mapping = StagingMapping({ let alloc = buffer_resource.alloc().unwrap(); unsafe { context .device .map_memory(alloc.mem, alloc.offset, vk::WHOLE_SIZE, vk::MemoryMapFlags::empty()) } .unwrap() as *mut u8 }); let alignment = context .physical_device_properties .limits .min_storage_buffer_offset_alignment as u32; Self { _buffer_id: buffer_id, buffer, mapping, alignment, } } } struct StagingState { heap: HeapAllocator, allocs: SlotMap<StagingAllocId, StagingAlloc>, queue: VecDeque<StagingAllocId>, } impl StagingState { fn new(staging_size: u32) -> Self { Self { heap: HeapAllocator::new(staging_size), allocs: SlotMap::with_key(), queue: VecDeque::new(), } } fn alloc(&mut self, size: u32, alignment: u32) -> StagingAllocId { let id = self.allocs.insert(StagingAlloc { size, alignment, state: StagingAllocState::Pending { waker: None }, }); self.queue.push_back(id); self.process_queue(); id } fn poll_alloc(&mut self, id: StagingAllocId, cx: &mut PollCtx<'_>) -> Poll<u32> { let alloc = self.allocs.get_mut(id).unwrap(); if let StagingAllocState::Done { offset } = alloc.state { self.allocs.remove(id); Poll::Ready(offset) } else { alloc.state = StagingAllocState::Pending { waker: Some(cx.waker().clone()), }; Poll::Pending } } fn process_queue(&mut self) { while let Some(id) = self.queue.pop_front() { let alloc = &mut self.allocs[id]; if let Some(offset) = self.heap.alloc(alloc.size, alloc.alignment) { let mut state = StagingAllocState::Done { offset }; mem::swap(&mut state, &mut alloc.state); match state { StagingAllocState::Pending { mut waker } => { if let Some(waker) = waker.take() { waker.wake(); } } _ => unreachable!(), } } else { self.queue.push_front(id); break; } } } fn free(&mut self, offset: u32) { self.heap.free(offset); self.process_queue(); } } struct ResourceStagingOffsetFuture { shared: Arc<ResourceLoaderShared>, id: StagingAllocId, } impl Future for ResourceStagingOffsetFuture { type Output = u32; fn poll(self: Pin<&mut Self>, cx: &mut PollCtx<'_>) -> Poll<Self::Output> { self.shared.staging_state.lock().unwrap().poll_alloc(self.id, cx) } } enum TransferTask { Buffer { staging_offset: u32, buffer_id: BufferId, initial_usage: BufferUsage, sender: oneshot::Sender<BufferId>, }, Image { staging_offset: u32, image_id: ImageId, initial_usage: ImageUsage, sender: oneshot::Sender<ImageId>, }, } struct FreeTask { staging_offset: u32, countdown: u32, } struct TransferState { transfers: VecDeque<TransferTask>, frees: Vec<FreeTask>, } impl TransferState { fn new() -> Self { Self { transfers: VecDeque::new(), frees: Vec::new(), } } } pub struct GraphicsTaskContext<'ctx, 'graph> { pub schedule: &'ctx mut RenderSchedule<'graph>, pub context: &'graph Context, pub descriptor_pool: &'graph DescriptorPool, pub pipeline_cache: &'graph PipelineCache, } struct GraphicsState { tasks: VecDeque<Box<dyn FnOnce(GraphicsTaskContext) + Send + 'static>>, } impl GraphicsState { fn new() -> Self { Self { tasks: VecDeque::new() } } } struct ResourceLoaderShared { context: SharedContext, resources: SharedResources, staging_desc: StagingDesc, staging_state: Mutex<StagingState>, transfer_state: Mutex<TransferState>, graphics_state: Mutex<GraphicsState>, } impl ResourceLoaderShared { unsafe fn staging_mapping(&self, region: StagingRegion, offset: usize, len: usize) -> &'_ mut [u8] { if (offset + len) > (region.size as usize) { panic!("mapping region out of bounds"); } slice::from_raw_parts_mut(self.staging_desc.mapping.0.add(region.offset as usize + offset), len) } fn transfer_buffer( &self, staging_offset: u32, buffer_id: BufferId, initial_usage: BufferUsage, ) -> impl Future<Output = BufferId> { let (tx, rx) = oneshot::channel(); self.transfer_state .lock() .unwrap() .transfers .push_back(TransferTask::Buffer { staging_offset, buffer_id, initial_usage, sender: tx, }); async { rx.await.unwrap() } } fn transfer_image( &self, staging_offset: u32, image_id: ImageId, initial_usage: ImageUsage, ) -> impl Future<Output = ImageId> { let (tx, rx) = oneshot::channel(); self.transfer_state .lock() .unwrap() .transfers .push_back(TransferTask::Image { staging_offset, image_id, initial_usage, sender: tx, }); async { rx.await.unwrap() } } } #[derive(Clone)] pub struct ResourceLoader { shared: Arc<ResourceLoaderShared>, } impl ResourceLoader { pub(crate) fn new(context: &SharedContext, resources: &SharedResources, staging_size: u32) -> Self { Self { shared: Arc::new(ResourceLoaderShared { context: SharedContext::clone(context), resources: SharedResources::clone(resources), staging_desc: StagingDesc::new(context, resources, staging_size), staging_state: Mutex::new(StagingState::new(staging_size)), transfer_state: Mutex::new(TransferState::new()), graphics_state: Mutex::new(GraphicsState::new()), }), } } pub(crate) fn begin_frame(&self, cmd: vk::CommandBuffer) { let mut transfer_state = self.shared.transfer_state.lock().unwrap(); let mut has_free = false; for free in transfer_state.frees.iter_mut() { free.countdown -= 1; if free.countdown == 0 { has_free = true; } } if has_free { let mut staging_state = self.shared.staging_state.lock().unwrap(); transfer_state.frees.retain(|free| { if free.countdown == 0 { staging_state.free(free.staging_offset); false } else { true } }); } let device = &self.shared.context.device; let mut resources = self.shared.resources.lock().unwrap(); while let Some(transfer) = transfer_state.transfers.pop_front() { let staging_offset = match transfer { TransferTask::Buffer { staging_offset, buffer_id, initial_usage, sender, } => { let buffer_resource = resources.buffer_resource_mut(buffer_id); buffer_resource.transition_usage(BufferUsage::TRANSFER_WRITE, device, cmd); let desc = buffer_resource.desc(); let region = vk::BufferCopy { src_offset: staging_offset as vk::DeviceSize, dst_offset: 0, size: desc.size as vk::DeviceSize, }; unsafe { device.cmd_copy_buffer( cmd, self.shared.staging_desc.buffer, buffer_resource.buffer().0, slice::from_ref(&region), ) }; buffer_resource.transition_usage(initial_usage, device, cmd); sender.send(buffer_id).unwrap(); staging_offset } TransferTask::Image { staging_offset, image_id, initial_usage, sender, } => { let image_resource = resources.image_resource_mut(image_id); image_resource.transition_usage(ImageUsage::TRANSFER_WRITE, device, cmd); let desc = image_resource.desc(); let bits_per_elements = desc.first_format().bits_per_element(); let layer_count = desc.layer_count_or_zero.max(1) as usize; let mut mip_width = desc.width as usize; let mut mip_height = desc.height_or_zero.max(1) as usize; let mut mip_offset = 0; for mip_index in 0..desc.mip_count { let region = vk::BufferImageCopy { buffer_offset: ((staging_offset as usize) + mip_offset) as vk::DeviceSize, buffer_row_length: mip_width as u32, buffer_image_height: mip_height as u32, image_subresource: vk::ImageSubresourceLayers { aspect_mask: desc.aspect_mask, mip_level: mip_index as u32, base_array_layer: 0, layer_count: layer_count as u32, }, image_offset: vk::Offset3D { x: 0, y: 0, z: 0 }, image_extent: vk::Extent3D { width: mip_width as u32, height: mip_height as u32, depth: 1, }, }; unsafe { device.cmd_copy_buffer_to_image( cmd, self.shared.staging_desc.buffer, image_resource.image().0, vk::ImageLayout::TRANSFER_DST_OPTIMAL, slice::from_ref(&region), ) }; let mip_layer_size = (mip_width * mip_height * bits_per_elements) / 8; mip_offset += mip_layer_size * layer_count; mip_width /= 2; mip_height /= 2; } image_resource.transition_usage(initial_usage, device, cmd); sender.send(image_id).unwrap(); staging_offset } }; transfer_state.frees.push(FreeTask { staging_offset, countdown: CommandBufferPool::COUNT as u32, }); } } pub fn context(&self) -> SharedContext { Arc::clone(&self.shared.context) } pub fn bindless_descriptor_set_layout(&self) -> vk::DescriptorSetLayout { self.shared.resources.lock().unwrap().bindless_descriptor_set_layout() } pub fn begin_schedule<'graph>( &self, render_graph: &'graph mut RenderGraph, context: &'graph Context, descriptor_pool: &'graph DescriptorPool, pipeline_cache: &'graph PipelineCache, ) -> RenderSchedule<'graph> { let mut schedule = RenderSchedule::new(render_graph); let mut graphics_state = self.shared.graphics_state.lock().unwrap(); while let Some(task) = graphics_state.tasks.pop_front() { task(GraphicsTaskContext { schedule: &mut schedule, context, descriptor_pool, pipeline_cache, }); } schedule } pub fn buffer_writer(&self, desc: &BufferDesc, all_usage: BufferUsage) -> impl Future<Output = BufferWriter> { let buffer_id = self.shared.resources.lock().unwrap().create_buffer( desc, all_usage | BufferUsage::TRANSFER_WRITE, vk::MemoryPropertyFlags::DEVICE_LOCAL, ); let size = desc.size as u32; let offset = ResourceStagingOffsetFuture { shared: Arc::clone(&self.shared), id: self .shared .staging_state .lock() .unwrap() .alloc(size, self.shared.staging_desc.alignment), }; let shared = Arc::clone(&self.shared); async move { BufferWriter { shared, buffer_id, initial_usage: all_usage, staging_region: StagingRegion { offset: offset.await, size, }, write_offset: 0, } } } pub fn get_buffer(&self, id: BufferId) -> vk::Buffer { self.shared.resources.lock().unwrap().buffer_resource(id).buffer().0 } pub fn get_buffer_accel(&self, id: BufferId) -> vk::AccelerationStructureKHR { self.shared .resources .lock() .unwrap() .buffer_resource(id) .accel() .unwrap() } pub fn get_buffer_bindless_id(&self, id: BufferId) -> BindlessId { self.shared .resources .lock() .unwrap() .buffer_resource(id) .bindless_id() .unwrap() } pub fn image_writer(&self, desc: &ImageDesc, all_usage: ImageUsage) -> impl Future<Output = ImageWriter> { let image_id = self.shared .resources .lock() .unwrap() .create_image(desc, all_usage | ImageUsage::TRANSFER_WRITE, None); let size = desc.staging_size() as u32; let offset = ResourceStagingOffsetFuture { shared: Arc::clone(&self.shared), id: self .shared .staging_state .lock() .unwrap() .alloc(size, self.shared.staging_desc.alignment), }; let shared = Arc::clone(&self.shared); async move { ImageWriter { shared, image_id, initial_usage: all_usage, staging_region: StagingRegion { offset: offset.await, size, }, write_offset: 0, } } } pub fn get_image_view(&self, id: ImageId, view_desc: ImageViewDesc) -> vk::ImageView { self.shared.resources.lock().unwrap().image_view(id, view_desc).0 } pub fn get_image_bindless_id(&self, id: ImageId) -> BindlessId { self.shared .resources .lock() .unwrap() .image_resource(id) .bindless_id() .unwrap() } pub fn graphics<F, T>(&self, func: F) -> impl Future<Output = T> where F: FnOnce(GraphicsTaskContext) -> T + Send + 'static, T: Send + 'static, { let mut graphics_state = self.shared.graphics_state.lock().unwrap(); let (tx, rx) = oneshot::channel(); graphics_state.tasks.push_back(Box::new(move |ctx| { tx.send(func(ctx)) .unwrap_or_else(|_| panic!("failed to send remote call result")) })); async { rx.await.unwrap() } } } pub fn spawn<F>(fut: F) -> SpawnResult<F::Output> where F: Future + Send + 'static, F::Output: Send + 'static, { SpawnResult(tokio::spawn(fut)) } pub fn spawn_blocking<F, R>(f: F) -> SpawnResult<R> where F: FnOnce() -> R + Send + 'static, R: Send + 'static, { SpawnResult(tokio::task::spawn_blocking(f)) } pub struct SpawnResult<T>(tokio::task::JoinHandle<T>); impl<T> Future for SpawnResult<T> { type Output = T; fn poll(self: Pin<&mut Self>, cx: &mut PollCtx<'_>) -> Poll<Self::Output> { let fut = unsafe { self.map_unchecked_mut(|r| &mut r.0) }; match fut.poll(cx) { Poll::Ready(t) => Poll::Ready(t.unwrap()), Poll::Pending => Poll::Pending, } } } pub trait AsBytes { fn as_bytes(&self) -> &[u8]; } impl<T: Pod> AsBytes for T { fn as_bytes(&self) -> &[u8] { bytemuck::bytes_of(self) } } impl<T: Pod> AsBytes for [T] { fn as_bytes(&self) -> &[u8] { bytemuck::cast_slice(self) } } pub trait StagingWriter { fn write<T: AsBytes + ?Sized>(&mut self, pod: &T); fn written(&self) -> usize; fn write_zeros(&mut self, len: usize); } macro_rules! writer_impl { ($name:ident) => { impl StagingWriter for $name { fn write<T: AsBytes + ?Sized>(&mut self, pod: &T) { let src_bytes = pod.as_bytes(); let dst_bytes = unsafe { self.shared .staging_mapping(self.staging_region, self.write_offset, src_bytes.len()) }; dst_bytes.copy_from_slice(src_bytes); self.write_offset += src_bytes.len(); } fn written(&self) -> usize { self.write_offset } fn write_zeros(&mut self, len: usize) { let dst_bytes = unsafe { self.shared .staging_mapping(self.staging_region, self.write_offset, len) }; for dst in dst_bytes.iter_mut() { *dst = 0; } self.write_offset += len; } } }; } pub struct BufferWriter { shared: Arc<ResourceLoaderShared>, staging_region: StagingRegion, write_offset: usize, buffer_id: BufferId, initial_usage: BufferUsage, } impl BufferWriter { pub fn finish(mut self) -> impl Future<Output = BufferId> { self.write_zeros(self.staging_region.size as usize - self.write_offset); self.shared .transfer_buffer(self.staging_region.offset, self.buffer_id, self.initial_usage) } } writer_impl!(BufferWriter); pub struct ImageWriter { shared: Arc<ResourceLoaderShared>, staging_region: StagingRegion, write_offset: usize, image_id: ImageId, initial_usage: ImageUsage, } impl ImageWriter { pub fn finish(mut self) -> impl Future<Output = ImageId> { self.write_zeros(self.staging_region.size as usize - self.write_offset); self.shared .transfer_image(self.staging_region.offset, self.image_id, self.initial_usage) } } writer_impl!(ImageWriter);
rust
MIT
42fc4b496cce21e907eca7112e6d6334d35fc41a
2026-01-04T20:23:56.526296Z
false
sjb3d/caldera
https://github.com/sjb3d/caldera/blob/42fc4b496cce21e907eca7112e6d6334d35fc41a/caldera/src/query.rs
caldera/src/query.rs
use crate::{command_buffer::*, context::*}; use arrayvec::ArrayVec; use spark::{vk, Device}; use std::{ffi::CStr, mem}; #[macro_export] macro_rules! command_name { ($e:tt) => { unsafe { ::std::ffi::CStr::from_bytes_with_nul_unchecked(concat!($e, "\0").as_bytes()) } }; } #[derive(Debug)] struct QuerySet { query_pool: vk::QueryPool, names: ArrayVec<Option<&'static CStr>, { Self::MAX_PER_FRAME as usize }>, } impl QuerySet { const MAX_PER_FRAME: u32 = 64; fn new(device: &Device) -> Self { let query_pool = { let create_info = vk::QueryPoolCreateInfo { query_type: vk::QueryType::TIMESTAMP, query_count: Self::MAX_PER_FRAME, ..Default::default() }; unsafe { device.create_query_pool(&create_info, None) }.unwrap() }; Self { query_pool, names: ArrayVec::new(), } } } pub struct QueryPool { context: SharedContext, sets: [QuerySet; Self::COUNT], last_us: ArrayVec<(&'static CStr, f32), { QuerySet::MAX_PER_FRAME as usize }>, timestamp_valid_mask: u64, timestamp_period_us: f32, index: usize, is_enabled: bool, } impl QueryPool { const COUNT: usize = CommandBufferPool::COUNT; pub fn new(context: &SharedContext) -> Self { let mut sets = ArrayVec::new(); for _ in 0..Self::COUNT { sets.push(QuerySet::new(&context.device)); } Self { context: SharedContext::clone(context), sets: sets.into_inner().unwrap(), last_us: ArrayVec::new(), timestamp_valid_mask: 1u64 .checked_shl(context.queue_family_properties.timestamp_valid_bits) .unwrap_or(0) .wrapping_sub(1), timestamp_period_us: context.physical_device_properties.limits.timestamp_period / 1000.0, index: 0, is_enabled: true, } } pub fn begin_frame(&mut self, cmd: vk::CommandBuffer) { self.index = (self.index + 1) % Self::COUNT; self.last_us.clear(); let set = &mut self.sets[self.index]; if !set.names.is_empty() { let mut query_results = [0u64; QuerySet::MAX_PER_FRAME as usize]; unsafe { self.context.device.get_query_pool_results( set.query_pool, 0, set.names.len() as u32, bytemuck::cast_slice_mut(&mut query_results[0..set.names.len()]), mem::size_of::<u64>() as vk::DeviceSize, vk::QueryResultFlags::N64 | vk::QueryResultFlags::WAIT, ) } .unwrap(); for (i, name) in set .names .iter() .take(QuerySet::MAX_PER_FRAME as usize - 1) .enumerate() .filter_map(|(i, name)| name.map(|name| (i, name))) { let timestamp_delta = (query_results[i + 1] - query_results[i]) & self.timestamp_valid_mask; self.last_us .push((name, (timestamp_delta as f32) * self.timestamp_period_us)); } } set.names.clear(); unsafe { self.context .device .cmd_reset_query_pool(cmd, set.query_pool, 0, QuerySet::MAX_PER_FRAME) }; } fn emit_timestamp_impl(&mut self, cmd: vk::CommandBuffer, name: Option<&'static CStr>) { let set = &mut self.sets[self.index]; if self.is_enabled && !set.names.is_full() { unsafe { self.context.device.cmd_write_timestamp( cmd, vk::PipelineStageFlags::BOTTOM_OF_PIPE, set.query_pool, set.names.len() as u32, ) }; set.names.push(name); } } pub fn emit_timestamp(&mut self, cmd: vk::CommandBuffer, name: &'static CStr) { self.emit_timestamp_impl(cmd, Some(name)); } pub fn end_frame(&mut self, cmd: vk::CommandBuffer) { self.emit_timestamp_impl(cmd, None); } pub fn ui_timestamp_table(&mut self, ui: &mut egui::Ui) { ui.checkbox(&mut self.is_enabled, "Enabled"); egui::Grid::new("timestamp_grid").show(ui, |ui| { ui.label("Pass"); ui.label("Time (us)"); ui.end_row(); for (name, time_us) in &self.last_us { ui.label(name.to_str().unwrap()); ui.label(format!("{:>7.1}", time_us)); ui.end_row(); } }); } } impl Drop for QueryPool { fn drop(&mut self) { for set in self.sets.iter() { unsafe { self.context.device.destroy_query_pool(set.query_pool, None); } } } }
rust
MIT
42fc4b496cce21e907eca7112e6d6334d35fc41a
2026-01-04T20:23:56.526296Z
false
sjb3d/caldera
https://github.com/sjb3d/caldera/blob/42fc4b496cce21e907eca7112e6d6334d35fc41a/caldera/src/context.rs
caldera/src/context.rs
use crate::window_surface; use raw_window_handle::{HasRawDisplayHandle, HasRawWindowHandle}; use spark::{vk, Builder, Device, DeviceExtensions, Globals, Instance, InstanceExtensions}; use std::{ ffi::CStr, num, os::raw::c_void, slice, sync::atomic::{AtomicU64, Ordering}, sync::Arc, }; use strum::{EnumString, EnumVariantNames}; use winit::window::Window; pub trait AsBool { fn as_bool(self) -> bool; } impl AsBool for vk::Bool32 { fn as_bool(self) -> bool { self != vk::FALSE } } unsafe extern "system" fn debug_messenger( message_severity: vk::DebugUtilsMessageSeverityFlagsEXT, message_types: vk::DebugUtilsMessageTypeFlagsEXT, p_callback_data: *const vk::DebugUtilsMessengerCallbackDataEXT, _: *mut c_void, ) -> vk::Bool32 { if let Some(data) = p_callback_data.as_ref() { let message = CStr::from_ptr(data.p_message); println!("{}, {}: {:?}", message_severity, message_types, message); } vk::FALSE } pub trait DeviceExt { unsafe fn get_buffer_device_address_helper(&self, buffer: vk::Buffer) -> vk::DeviceAddress; } impl DeviceExt for Device { unsafe fn get_buffer_device_address_helper(&self, buffer: vk::Buffer) -> vk::DeviceAddress { let info = vk::BufferDeviceAddressInfo { buffer, ..Default::default() }; self.get_buffer_device_address(&info) } } trait PhysicalDeviceMemoryPropertiesExt { fn types(&self) -> &[vk::MemoryType]; fn heaps(&self) -> &[vk::MemoryHeap]; } impl PhysicalDeviceMemoryPropertiesExt for vk::PhysicalDeviceMemoryProperties { fn types(&self) -> &[vk::MemoryType] { &self.memory_types[..self.memory_type_count as usize] } fn heaps(&self) -> &[vk::MemoryHeap] { &self.memory_heaps[..self.memory_heap_count as usize] } } #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub struct Unique<T>(pub T, u64); impl<T> Unique<T> { pub fn new(obj: T, uid: u64) -> Self { Self(obj, uid) } } pub type UniqueBuffer = Unique<vk::Buffer>; pub type UniqueImage = Unique<vk::Image>; pub type UniqueImageView = Unique<vk::ImageView>; pub type UniqueRenderPass = Unique<vk::RenderPass>; pub type UniqueFramebuffer = Unique<vk::Framebuffer>; #[derive(Debug, Clone, Copy, PartialEq, Eq, EnumString, EnumVariantNames)] #[strum(serialize_all = "kebab_case")] pub enum ContextFeature { Disable, Optional, Require, } impl ContextFeature { fn apply(&self, is_supported: impl FnOnce() -> bool, enable_support: impl FnOnce(), on_error: impl FnOnce()) { match self { ContextFeature::Disable => {} ContextFeature::Optional => { if is_supported() { enable_support(); } } ContextFeature::Require => { if !is_supported() { on_error(); } enable_support(); } } } } pub fn try_version_from_str(s: &str) -> Result<vk::Version, num::ParseIntError> { let mut parts = s.split('.'); let major = parts.next().unwrap_or("").parse::<u32>()?; let minor = parts.next().unwrap_or("0").parse::<u32>()?; let patch = parts.next().unwrap_or("0").parse::<u32>()?; Ok(vk::Version::from_raw_parts(major, minor, patch)) } pub struct ContextParams { pub version: vk::Version, pub debug_utils: ContextFeature, pub scalar_block_layout: ContextFeature, pub image_format_list: ContextFeature, pub pipeline_creation_cache_control: ContextFeature, pub geometry_shader: ContextFeature, pub inline_uniform_block: ContextFeature, pub bindless: ContextFeature, pub ray_tracing: ContextFeature, pub ray_query: ContextFeature, pub mesh_shader: ContextFeature, pub subgroup_size_control: ContextFeature, } impl Default for ContextParams { fn default() -> Self { Self { version: Default::default(), debug_utils: ContextFeature::Disable, scalar_block_layout: ContextFeature::Require, image_format_list: ContextFeature::Require, pipeline_creation_cache_control: ContextFeature::Disable, geometry_shader: ContextFeature::Disable, inline_uniform_block: ContextFeature::Optional, bindless: ContextFeature::Disable, ray_tracing: ContextFeature::Disable, ray_query: ContextFeature::Disable, mesh_shader: ContextFeature::Disable, subgroup_size_control: ContextFeature::Disable, } } } pub struct PhysicalDeviceExtraProperties { pub ray_tracing_pipeline: vk::PhysicalDeviceRayTracingPipelinePropertiesKHR, pub mesh_shader: vk::PhysicalDeviceMeshShaderPropertiesNV, pub subgroup_size_control: vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT, } #[derive(Default)] pub struct DeviceFeatures { pub base: vk::PhysicalDeviceFeatures, pub scalar_block_layout: vk::PhysicalDeviceScalarBlockLayoutFeaturesEXT, pub pipeline_creation_cache_control: vk::PhysicalDevicePipelineCreationCacheControlFeaturesEXT, pub inline_uniform_block: vk::PhysicalDeviceInlineUniformBlockFeaturesEXT, pub buffer_device_address: vk::PhysicalDeviceBufferDeviceAddressFeaturesKHR, pub acceleration_structure: vk::PhysicalDeviceAccelerationStructureFeaturesKHR, pub ray_tracing_pipeline: vk::PhysicalDeviceRayTracingPipelineFeaturesKHR, pub ray_query: vk::PhysicalDeviceRayQueryFeaturesKHR, pub descriptor_indexing: vk::PhysicalDeviceDescriptorIndexingFeatures, pub mesh_shader: vk::PhysicalDeviceMeshShaderFeaturesNV, pub subgroup_size_control: vk::PhysicalDeviceSubgroupSizeControlFeatures, } pub struct Context { pub _globals: Globals, pub instance: Instance, pub debug_utils_messenger: vk::DebugUtilsMessengerEXT, pub surface: vk::SurfaceKHR, pub physical_device: vk::PhysicalDevice, pub physical_device_properties: vk::PhysicalDeviceProperties, pub physical_device_memory_properties: vk::PhysicalDeviceMemoryProperties, pub physical_device_extra_properties: Option<PhysicalDeviceExtraProperties>, pub physical_device_features: DeviceFeatures, pub queue_family_index: u32, pub queue_family_properties: vk::QueueFamilyProperties, pub queue: vk::Queue, pub device: Device, pub next_handle_uid: AtomicU64, } pub type SharedContext = Arc<Context>; impl Context { pub fn new(window: Option<&Window>, params: &ContextParams) -> SharedContext { let globals = Globals::new().unwrap(); let instance = { let instance_version = unsafe { globals.enumerate_instance_version() }.unwrap(); println!( "loading instance version {} ({} supported)", params.version, instance_version ); if instance_version < params.version { panic!( "requested instance version {} is greater than the available version {}", params.version, instance_version ); } let available_extensions = { let extension_properties = unsafe { globals.enumerate_instance_extension_properties_to_vec(None) }.unwrap(); InstanceExtensions::from_properties(params.version, &extension_properties) }; let mut extensions = InstanceExtensions::new(params.version); if let Some(window) = window { window_surface::enable_extensions(&window.raw_display_handle(), &mut extensions); } params.debug_utils.apply( || available_extensions.supports_ext_debug_utils(), || extensions.enable_ext_debug_utils(), || panic!("EXT_debug_utils not supported"), ); params.scalar_block_layout.apply( || available_extensions.supports_ext_scalar_block_layout(), || extensions.enable_ext_scalar_block_layout(), || panic!("EXT_scalar_block_layout not supported"), ); params.inline_uniform_block.apply( || available_extensions.supports_ext_inline_uniform_block(), || extensions.enable_ext_inline_uniform_block(), || panic!("EXT_inline_uniform_block not supported"), ); params.bindless.apply( || available_extensions.supports_ext_descriptor_indexing(), || extensions.enable_ext_descriptor_indexing(), || panic!("EXT_descriptor_indexing not supported"), ); params.ray_tracing.apply( || { available_extensions.supports_khr_acceleration_structure() && available_extensions.supports_khr_ray_tracing_pipeline() }, || { extensions.enable_khr_acceleration_structure(); extensions.enable_khr_ray_tracing_pipeline(); }, || panic!("KHR_acceleration_structure/KHR_ray_tracing_pipeline not supported"), ); params.ray_query.apply( || { available_extensions.supports_khr_acceleration_structure() && available_extensions.supports_khr_ray_query() }, || { extensions.enable_khr_acceleration_structure(); extensions.enable_khr_ray_query(); }, || panic!("KHR_acceleration_structure/KHR_ray_query not supported"), ); params.mesh_shader.apply( || available_extensions.supports_nv_mesh_shader(), || extensions.enable_nv_mesh_shader(), || panic!("NV_mesh_shader not supported"), ); params.subgroup_size_control.apply( || available_extensions.supports_khr_get_physical_device_properties2(), || extensions.enable_khr_get_physical_device_properties2(), || panic!("KHR_get_physical_device_properties2 not supported"), ); let extension_names = extensions.to_name_vec(); for &name in extension_names.iter() { println!("loading instance extension {:?}", name); } let app_info = vk::ApplicationInfo::builder() .p_application_name(Some(CStr::from_bytes_with_nul(b"caldera\0").unwrap())) .api_version(params.version); let extension_name_ptrs: Vec<_> = extension_names.iter().map(|s| s.as_ptr()).collect(); let instance_create_info = vk::InstanceCreateInfo::builder() .p_application_info(Some(&app_info)) .pp_enabled_extension_names(&extension_name_ptrs); unsafe { globals.create_instance_commands(&instance_create_info, None) }.unwrap() }; let debug_utils_messenger = if instance.extensions.supports_ext_debug_utils() { let create_info = vk::DebugUtilsMessengerCreateInfoEXT { message_severity: vk::DebugUtilsMessageSeverityFlagsEXT::ERROR | vk::DebugUtilsMessageSeverityFlagsEXT::WARNING, message_type: vk::DebugUtilsMessageTypeFlagsEXT::GENERAL | vk::DebugUtilsMessageTypeFlagsEXT::VALIDATION | vk::DebugUtilsMessageTypeFlagsEXT::PERFORMANCE, pfn_user_callback: Some(debug_messenger), ..Default::default() }; unsafe { instance.create_debug_utils_messenger_ext(&create_info, None) }.unwrap() } else { vk::DebugUtilsMessengerEXT::null() }; let surface = window .map(|window| { window_surface::create(&instance, &window.raw_display_handle(), &window.raw_window_handle()).unwrap() }) .unwrap_or(vk::SurfaceKHR::null()); let physical_device = { let physical_devices = unsafe { instance.enumerate_physical_devices_to_vec() }.unwrap(); for physical_device in &physical_devices { let props = unsafe { instance.get_physical_device_properties(*physical_device) }; println!("physical device ({}): {:?}", props.device_type, unsafe { CStr::from_ptr(props.device_name.as_ptr()) }); } physical_devices[0] }; let physical_device_properties = unsafe { instance.get_physical_device_properties(physical_device) }; let device_version = physical_device_properties.api_version; let physical_device_extra_properties = if instance.extensions.supports_khr_get_physical_device_properties2() { let mut ray_tracing_pipeline = vk::PhysicalDeviceRayTracingPipelinePropertiesKHR::default(); let mut mesh_shader = vk::PhysicalDeviceMeshShaderPropertiesNV::default(); let mut subgroup_size_control = vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT::default(); let mut properties2 = vk::PhysicalDeviceProperties2::builder() .insert_next(&mut ray_tracing_pipeline) .insert_next(&mut mesh_shader) .insert_next(&mut subgroup_size_control); unsafe { instance.get_physical_device_properties2(physical_device, properties2.get_mut()) }; Some(PhysicalDeviceExtraProperties { ray_tracing_pipeline, mesh_shader, subgroup_size_control, }) } else { None }; let available_features = if instance.extensions.supports_khr_get_physical_device_properties2() { let mut device_features = DeviceFeatures::default(); let mut features2 = vk::PhysicalDeviceFeatures2::builder() .insert_next(&mut device_features.scalar_block_layout) .insert_next(&mut device_features.pipeline_creation_cache_control) .insert_next(&mut device_features.inline_uniform_block) .insert_next(&mut device_features.buffer_device_address) .insert_next(&mut device_features.acceleration_structure) .insert_next(&mut device_features.ray_tracing_pipeline) .insert_next(&mut device_features.ray_query) .insert_next(&mut device_features.descriptor_indexing) .insert_next(&mut device_features.mesh_shader) .insert_next(&mut device_features.subgroup_size_control); unsafe { instance.get_physical_device_features2(physical_device, features2.get_mut()) }; device_features.base = features2.features; device_features } else { DeviceFeatures { base: unsafe { instance.get_physical_device_features(physical_device) }, ..Default::default() } }; let physical_device_memory_properties = unsafe { instance.get_physical_device_memory_properties(physical_device) }; for (i, mt) in physical_device_memory_properties.types().iter().enumerate() { println!("memory type {}: {}, heap {}", i, mt.property_flags, mt.heap_index); } for (i, mh) in physical_device_memory_properties.heaps().iter().enumerate() { println!("heap {}: {} bytes {}", i, mh.size, mh.flags); } let (queue_family_index, queue_family_properties) = { let queue_flags = vk::QueueFlags::GRAPHICS | vk::QueueFlags::COMPUTE; unsafe { instance.get_physical_device_queue_family_properties_to_vec(physical_device) } .iter() .enumerate() .filter_map(|(index, info)| { if info.queue_flags.contains(queue_flags) && (surface.is_null() || unsafe { instance.get_physical_device_surface_support_khr(physical_device, index as u32, surface) } .unwrap()) { Some((index as u32, *info)) } else { None } }) .next() .unwrap() }; let mut features = DeviceFeatures::default(); let device = { println!( "loading device version {} ({} supported)", params.version, device_version ); if device_version < params.version { panic!( "requested device version {} is greater than the available version {}", params.version, device_version ); } let queue_priorities = [1.0]; let device_queue_create_info = vk::DeviceQueueCreateInfo::builder() .queue_family_index(queue_family_index) .p_queue_priorities(&queue_priorities); let available_extensions = { let extension_properties = unsafe { instance.enumerate_device_extension_properties_to_vec(physical_device, None) }.unwrap(); DeviceExtensions::from_properties(params.version, &extension_properties) }; let mut extensions = DeviceExtensions::new(params.version); if window.is_some() { extensions.enable_khr_swapchain(); } params.geometry_shader.apply( || available_features.base.geometry_shader.as_bool(), || features.base.geometry_shader = vk::TRUE, || panic!("geometry shaders not supported"), ); params.scalar_block_layout.apply( || { available_extensions.supports_ext_scalar_block_layout() && available_features.scalar_block_layout.scalar_block_layout.as_bool() }, || { extensions.enable_ext_scalar_block_layout(); features.scalar_block_layout.scalar_block_layout = vk::TRUE; }, || panic!("EXT_scalar_block_layout not supported"), ); params.image_format_list.apply( || available_extensions.supports_khr_image_format_list(), || extensions.enable_khr_image_format_list(), || panic!("KHR_image_format_list not supported"), ); params.pipeline_creation_cache_control.apply( || { available_extensions.supports_ext_pipeline_creation_cache_control() && available_features .pipeline_creation_cache_control .pipeline_creation_cache_control .as_bool() }, || { extensions.enable_ext_pipeline_creation_cache_control(); features.pipeline_creation_cache_control.pipeline_creation_cache_control = vk::TRUE; }, || panic!("EXT_pipeline_creation_cache_control not support"), ); params.inline_uniform_block.apply( || { available_extensions.supports_ext_inline_uniform_block() && available_features.inline_uniform_block.inline_uniform_block.as_bool() }, || { extensions.enable_ext_inline_uniform_block(); features.inline_uniform_block.inline_uniform_block = vk::TRUE; }, || panic!("EXT_inline_uniform_block not supported"), ); params.bindless.apply( || { available_extensions.supports_ext_descriptor_indexing() && available_features .descriptor_indexing .descriptor_binding_storage_buffer_update_after_bind .as_bool() && available_features .descriptor_indexing .descriptor_binding_sampled_image_update_after_bind .as_bool() && available_features .descriptor_indexing .shader_storage_buffer_array_non_uniform_indexing .as_bool() && available_features .descriptor_indexing .shader_sampled_image_array_non_uniform_indexing .as_bool() && available_features .descriptor_indexing .descriptor_binding_update_unused_while_pending .as_bool() && available_features .descriptor_indexing .descriptor_binding_partially_bound .as_bool() }, || { extensions.enable_ext_descriptor_indexing(); features .descriptor_indexing .descriptor_binding_storage_buffer_update_after_bind = vk::TRUE; features .descriptor_indexing .descriptor_binding_sampled_image_update_after_bind = vk::TRUE; features .descriptor_indexing .shader_storage_buffer_array_non_uniform_indexing = vk::TRUE; features .descriptor_indexing .shader_sampled_image_array_non_uniform_indexing = vk::TRUE; features .descriptor_indexing .descriptor_binding_update_unused_while_pending = vk::TRUE; features.descriptor_indexing.descriptor_binding_partially_bound = vk::TRUE; }, || panic!("EXT_descriptor_indexing not supported"), ); params.ray_tracing.apply( || { available_extensions.supports_khr_ray_tracing_pipeline() && available_features.buffer_device_address.buffer_device_address.as_bool() && available_features.base.shader_int64.as_bool() && available_features .acceleration_structure .acceleration_structure .as_bool() && available_features.ray_tracing_pipeline.ray_tracing_pipeline.as_bool() }, || { extensions.enable_khr_ray_tracing_pipeline(); features.buffer_device_address.buffer_device_address = vk::TRUE; features.base.shader_int64 = vk::TRUE; features.acceleration_structure.acceleration_structure = vk::TRUE; features.ray_tracing_pipeline.ray_tracing_pipeline = vk::TRUE; }, || panic!("KHR_acceleration_structure/KHR_ray_tracing_pipeline not supported"), ); params.ray_query.apply( || { available_extensions.supports_khr_ray_query() && available_features.buffer_device_address.buffer_device_address.as_bool() && available_features.base.shader_int64.as_bool() && available_features .acceleration_structure .acceleration_structure .as_bool() && available_features.ray_query.ray_query.as_bool() }, || { extensions.enable_khr_ray_query(); features.buffer_device_address.buffer_device_address = vk::TRUE; features.base.shader_int64 = vk::TRUE; features.acceleration_structure.acceleration_structure = vk::TRUE; features.ray_query.ray_query = vk::TRUE; }, || panic!("KHR_acceleration_structure/KHR_ray_query not supported"), ); params.mesh_shader.apply( || { available_extensions.supports_nv_mesh_shader() && available_features.mesh_shader.task_shader.as_bool() && available_features.mesh_shader.mesh_shader.as_bool() }, || { extensions.enable_nv_mesh_shader(); features.mesh_shader.task_shader = vk::TRUE; features.mesh_shader.mesh_shader = vk::TRUE; }, || panic!("NV_mesh_shader not supported"), ); params.subgroup_size_control.apply( || { available_extensions.supports_ext_subgroup_size_control() && available_features.subgroup_size_control.subgroup_size_control.as_bool() && available_features .subgroup_size_control .compute_full_subgroups .as_bool() }, || { extensions.enable_ext_subgroup_size_control(); features.subgroup_size_control.subgroup_size_control = vk::TRUE; features.subgroup_size_control.compute_full_subgroups = vk::TRUE; }, || panic!("EXT_subgroup_size_control not supported"), ); let extension_names = extensions.to_name_vec(); for &name in extension_names.iter() { println!("loading device extension {:?}", name); } let extension_name_ptrs: Vec<_> = extension_names.iter().map(|s| s.as_ptr()).collect(); let device_create_info = vk::DeviceCreateInfo::builder() .p_queue_create_infos(slice::from_ref(&device_queue_create_info)) .pp_enabled_extension_names(&extension_name_ptrs) .p_enabled_features(Some(&features.base)) .insert_next(&mut features.scalar_block_layout) .insert_next(&mut features.pipeline_creation_cache_control) .insert_next(&mut features.inline_uniform_block) .insert_next(&mut features.buffer_device_address) .insert_next(&mut features.acceleration_structure) .insert_next(&mut features.ray_tracing_pipeline) .insert_next(&mut features.ray_query) .insert_next(&mut features.descriptor_indexing) .insert_next(&mut features.mesh_shader) .insert_next(&mut features.subgroup_size_control); unsafe { instance.create_device_commands(&globals, physical_device, &device_create_info, None) }.unwrap() }; let queue = unsafe { device.get_device_queue(queue_family_index, 0) }; SharedContext::new(Self { _globals: globals, instance, debug_utils_messenger, surface, physical_device, physical_device_properties, physical_device_memory_properties, physical_device_extra_properties, physical_device_features: features, queue_family_index, queue_family_properties, queue, device, next_handle_uid: AtomicU64::new(0), }) } pub fn allocate_handle_uid(&self) -> u64 { self.next_handle_uid.fetch_add(1, Ordering::SeqCst) } pub fn get_memory_type_index(&self, type_filter: u32, property_flags: vk::MemoryPropertyFlags) -> Option<u32> { for (i, mt) in self.physical_device_memory_properties.types().iter().enumerate() { let i = i as u32; if (type_filter & (1 << i)) != 0 && mt.property_flags.contains(property_flags) { return Some(i); } } None } } impl Drop for Context { fn drop(&mut self) { unsafe { self.device.destroy_device(None); if !self.surface.is_null() { self.instance.destroy_surface_khr(self.surface, None); } if !self.debug_utils_messenger.is_null() { self.instance .destroy_debug_utils_messenger_ext(self.debug_utils_messenger, None); } self.instance.destroy_instance(None); } } }
rust
MIT
42fc4b496cce21e907eca7112e6d6334d35fc41a
2026-01-04T20:23:56.526296Z
false
sjb3d/caldera
https://github.com/sjb3d/caldera/blob/42fc4b496cce21e907eca7112e6d6334d35fc41a/caldera/src/window_surface.rs
caldera/src/window_surface.rs
use raw_window_handle::{RawDisplayHandle, RawWindowHandle}; use spark::{vk, Instance, InstanceExtensions, Result}; pub fn enable_extensions(display_handle: &RawDisplayHandle, extensions: &mut InstanceExtensions) { match display_handle { #[cfg(target_os = "linux")] RawDisplayHandle::Xlib(_) => extensions.enable_khr_xlib_surface(), #[cfg(target_os = "linux")] RawDisplayHandle::Wayland(_) => extensions.enable_khr_wayland_surface(), #[cfg(target_os = "windows")] RawDisplayHandle::Windows(_) => extensions.enable_khr_win32_surface(), #[cfg(target_os = "android")] RawDisplayHandle::AndroidNdk(_) => extensions.enable_khr_android_surface(), _ => unimplemented!(), } } pub fn create( instance: &Instance, display_handle: &RawDisplayHandle, window_handle: &RawWindowHandle, ) -> Result<vk::SurfaceKHR> { match (display_handle, window_handle) { #[cfg(target_os = "linux")] (RawDisplayHandle::Xlib(display_handle), RawWindowHandle::Xlib(window_handle)) => { let create_info = vk::XlibSurfaceCreateInfoKHR { dpy: display_handle.display as _, window: window_handle.window, ..Default::default() }; unsafe { instance.create_xlib_surface_khr(&create_info, None) } } #[cfg(target_os = "linux")] (RawDisplayHandle::Wayland(display_handle), RawWindowHandle::Wayland(window_handle)) => { let create_info = vk::WaylandSurfaceCreateInfoKHR { display: display_handle.display as _, surface: window_handle.surface as _, ..Default::default() }; unsafe { instance.create_wayland_surface_khr(&create_info, None) } } #[cfg(target_os = "windows")] (RawDisplayHandle::Windows(_), RawWindowHandle::Win32(window_handle)) => { let create_info = vk::Win32SurfaceCreateInfoKHR { hwnd: window_handle.hwnd, ..Default::default() }; unsafe { instance.create_win32_surface_khr(&create_info, None) } } #[cfg(target_os = "android")] (RawDisplayHandle::AndroidNdk(_), RawWindowHandle::AndroidNdk(window_handle)) => { let create_info = vk::AndroidSurfaceCreateInfoKHR { window: window_handle.a_native_window as _, ..Default::default() }; unsafe { instance.create_android_surface_khr(&create_info, None) } } _ => unimplemented!(), } }
rust
MIT
42fc4b496cce21e907eca7112e6d6334d35fc41a
2026-01-04T20:23:56.526296Z
false
sjb3d/caldera
https://github.com/sjb3d/caldera/blob/42fc4b496cce21e907eca7112e6d6334d35fc41a/caldera/src/heap.rs
caldera/src/heap.rs
#[derive(Debug, Clone, Copy)] struct HeapBlock { begin: u32, end: u32, } #[derive(Debug)] pub(crate) struct HeapAllocator { sorted_free_list: Vec<HeapBlock>, alloc_list: Vec<HeapBlock>, } impl HeapAllocator { pub fn new(size: u32) -> Self { Self { sorted_free_list: vec![HeapBlock { begin: 0, end: size }], alloc_list: Vec::new(), } } pub fn alloc(&mut self, size: u32, align: u32) -> Option<u32> { let align_mask = align - 1; for (index, block) in self.sorted_free_list.iter().enumerate() { let aligned = (block.begin + align_mask) & !align_mask; let alloc = HeapBlock { begin: aligned, end: aligned + size, }; if alloc.end <= block.end { let block = block.clone(); self.sorted_free_list.remove(index); if alloc.end != block.end { self.sorted_free_list.insert( index, HeapBlock { begin: alloc.end, end: block.end, }, ); } if alloc.begin != block.begin { self.sorted_free_list.insert( index, HeapBlock { begin: block.begin, end: alloc.begin, }, ) } self.alloc_list.push(alloc); return Some(alloc.begin); } } None } pub fn free(&mut self, alloc: u32) { let mut alloc = { let remove_index = self .alloc_list .iter() .enumerate() .find_map(|(index, block)| (block.begin == alloc).then(|| index)) .expect("failed to find allocation"); self.alloc_list.swap_remove(remove_index) }; let mut insert_index = self .sorted_free_list .iter() .enumerate() .find_map( |(index, block)| { if alloc.end <= block.begin { Some(index) } else { None } }, ) .unwrap_or(self.sorted_free_list.len()); if let Some(next) = self.sorted_free_list.get(insert_index) { if alloc.end == next.begin { alloc.end = next.end; self.sorted_free_list.remove(insert_index); } } let prev_index = insert_index.wrapping_sub(1); if let Some(prev) = self.sorted_free_list.get(prev_index) { if prev.end == alloc.begin { alloc.begin = prev.begin; self.sorted_free_list.remove(prev_index); insert_index = prev_index; } } self.sorted_free_list.insert(insert_index, alloc); } }
rust
MIT
42fc4b496cce21e907eca7112e6d6334d35fc41a
2026-01-04T20:23:56.526296Z
false
sjb3d/caldera
https://github.com/sjb3d/caldera/blob/42fc4b496cce21e907eca7112e6d6334d35fc41a/caldera/examples/test_mesh_shader/cluster.rs
caldera/examples/test_mesh_shader/cluster.rs
use bitvec::prelude::*; use bytemuck::{Pod, Zeroable}; use caldera::prelude::*; pub const MAX_VERTICES_PER_CLUSTER: usize = 64; pub const MAX_TRIANGLES_PER_CLUSTER: usize = 124; pub struct Mesh { pub positions: Vec<Vec3>, pub normals: Vec<Vec3>, pub triangles: Vec<UVec3>, pub face_normals: Vec<Vec3>, } #[repr(C)] #[derive(Debug, Clone, Copy, Pod, Zeroable)] pub struct BoxBounds { pub min: Vec3, pub max: Vec3, } impl BoxBounds { pub fn new() -> Self { Self { min: Vec3::broadcast(f32::MAX), max: Vec3::broadcast(f32::MIN), } } pub fn union_with_point(&mut self, p: Vec3) { self.min = self.min.min_by_component(p); self.max = self.max.max_by_component(p); } pub fn centre(&self) -> Vec3 { 0.5 * (self.max + self.min) } pub fn half_extent(&self) -> Vec3 { 0.5 * (self.max - self.min) } } #[repr(C)] #[derive(Debug, Clone, Copy, Pod, Zeroable)] pub struct SphereBounds { pub centre: Vec3, pub radius: f32, } impl SphereBounds { pub fn from_box(aabb: BoxBounds) -> Self { Self { centre: aabb.centre(), radius: aabb.half_extent().mag(), } } } #[repr(C)] #[derive(Debug, Clone, Copy, Pod, Zeroable)] pub struct ConeBounds { pub dir: Vec3, pub cos_angle: f32, } impl ConeBounds { pub fn from_box(aabb: BoxBounds) -> Self { // construct a cone that bounds the sphere let sphere = SphereBounds::from_box(aabb); let centre_dist = sphere.centre.mag(); let sin_theta = sphere.radius / centre_dist; if sin_theta < 0.999 { Self { dir: sphere.centre.normalized(), cos_angle: (1.0 - sin_theta * sin_theta).max(0.0).sqrt(), } } else { Self { dir: Vec3::unit_x(), cos_angle: -1.0, // whole sphere } } } } #[derive(Debug)] pub struct Cluster { pub position_bounds: BoxBounds, pub face_normal_bounds: BoxBounds, pub mesh_vertices: Vec<u32>, pub triangles: Vec<UVec3>, pub mesh_triangles: Vec<u32>, } impl Cluster { fn new() -> Self { Self { position_bounds: BoxBounds::new(), face_normal_bounds: BoxBounds::new(), mesh_vertices: Vec::new(), triangles: Vec::new(), mesh_triangles: Vec::new(), } } } struct TriangleListPerVertex { offset_per_vertex: Vec<u32>, triangle_indices: Vec<u32>, } impl TriangleListPerVertex { fn new(mesh: &Mesh) -> Self { let vertex_count = mesh.positions.len(); let triangle_count = mesh.triangles.len(); let corner_count = 3 * triangle_count; let mut offset_per_vertex = vec![0u32; vertex_count + 1]; for triangle in mesh.triangles.iter() { for &vertex in triangle.as_slice() { offset_per_vertex[vertex as usize] += 1; } } let mut postfix_sum = 0u32; for offset in offset_per_vertex.iter_mut() { postfix_sum += *offset; *offset = postfix_sum; } let mut triangle_indices = vec![u32::MAX; corner_count]; for (triangle_index, triangle) in mesh.triangles.iter().enumerate() { for &vertex in triangle.as_slice() { let offset_slot = &mut offset_per_vertex[vertex as usize]; let offset = *offset_slot - 1; triangle_indices[offset as usize] = triangle_index as u32; *offset_slot = offset; } } Self { offset_per_vertex, triangle_indices, } } fn triangle_indices_for_vertex(&self, vertex: u32) -> &[u32] { let begin = self.offset_per_vertex[vertex as usize] as usize; let end = self.offset_per_vertex[vertex as usize + 1] as usize; &self.triangle_indices[begin..end] } } struct ClusterVertexRemap<'m> { mesh_positions: &'m [Vec3], position_bounds: BoxBounds, cluster_vertices: Vec<u8>, } impl<'m> ClusterVertexRemap<'m> { fn new(mesh: &'m Mesh) -> Self { Self { mesh_positions: &mesh.positions, position_bounds: BoxBounds::new(), cluster_vertices: vec![u8::MAX; mesh.positions.len()], } } fn get_or_insert(&mut self, mesh_vertex: u32, cluster: &mut Cluster) -> u32 { let mut cluster_vertex = self.cluster_vertices[mesh_vertex as usize]; if cluster_vertex == u8::MAX { cluster_vertex = cluster.mesh_vertices.len() as u8; cluster.mesh_vertices.push(mesh_vertex); self.position_bounds .union_with_point(self.mesh_positions[mesh_vertex as usize]); self.cluster_vertices[mesh_vertex as usize] = cluster_vertex as u8; } cluster_vertex as u32 } fn contains(&self, mesh_vertex: u32) -> bool { self.cluster_vertices[mesh_vertex as usize] != u8::MAX } fn finish(&mut self, cluster: &mut Cluster) { for &mesh_vertex in &cluster.mesh_vertices { self.cluster_vertices[mesh_vertex as usize] = u8::MAX; } cluster.position_bounds = self.position_bounds; self.position_bounds = BoxBounds::new(); } } struct ClusterBuilder<'m> { mesh: &'m Mesh, triangle_list_per_vertex: TriangleListPerVertex, available_triangles: BitVec, vertex_remap: ClusterVertexRemap<'m>, } impl<'m> ClusterBuilder<'m> { fn new(mesh: &'m Mesh) -> Self { Self { mesh, triangle_list_per_vertex: TriangleListPerVertex::new(mesh), available_triangles: BitVec::repeat(true, mesh.triangles.len()), vertex_remap: ClusterVertexRemap::new(mesh), } } fn find_next_triangle(&self, cluster: &Cluster) -> Option<u32> { // early out if full if cluster.mesh_vertices.len() == MAX_VERTICES_PER_CLUSTER || cluster.triangles.len() == MAX_TRIANGLES_PER_CLUSTER { return None; } // select any triangle if the cluster is empty if cluster.triangles.is_empty() { return self .available_triangles .first_one() .map(|triangle_index| triangle_index as u32); } // HACK: just return the first one for now // TODO: build score using effect on cluster position and normal bounds cluster .mesh_vertices .iter() .flat_map(|&vertex| self.triangle_list_per_vertex.triangle_indices_for_vertex(vertex)) .copied() .filter(|&triangle_index| self.available_triangles[triangle_index as usize]) .filter(|&triangle_index| { let new_vertex_count = self.mesh.triangles[triangle_index as usize] .as_slice() .iter() .copied() .filter(|&vertex| !self.vertex_remap.contains(vertex)) .count(); cluster.mesh_vertices.len() + new_vertex_count <= MAX_VERTICES_PER_CLUSTER }) .next() } fn build(mut self) -> Vec<Cluster> { let mut clusters = Vec::new(); loop { let mut cluster = Cluster::new(); while let Some(triangle_index) = self.find_next_triangle(&cluster) { let triangle = self.mesh.triangles[triangle_index as usize] .map_mut(|mesh_vertex| self.vertex_remap.get_or_insert(mesh_vertex, &mut cluster)); cluster.triangles.push(triangle); cluster.mesh_triangles.push(triangle_index); cluster .face_normal_bounds .union_with_point(self.mesh.face_normals[triangle_index as usize]); self.available_triangles.set(triangle_index as usize, false); } if cluster.triangles.is_empty() { break; } self.vertex_remap.finish(&mut cluster); clusters.push(cluster); } clusters } } pub fn build_clusters(mut mesh: Mesh) -> (Mesh, Vec<Cluster>) { let mut clusters = ClusterBuilder::new(&mesh).build(); // re-order vertices and triangles to appear in the order they are referenced by cluster triangles let mut new_vertex_from_old = vec![u32::MAX; mesh.positions.len()]; let mut positions = Vec::new(); let mut normals = Vec::new(); mesh.triangles.clear(); for cluster in clusters.iter_mut() { for mesh_vertex in cluster.mesh_vertices.iter_mut() { let old_vertex = *mesh_vertex; let mut new_vertex = new_vertex_from_old[old_vertex as usize]; if new_vertex == u32::MAX { new_vertex = positions.len() as u32; new_vertex_from_old[old_vertex as usize] = new_vertex; positions.push(mesh.positions[old_vertex as usize]); normals.push(mesh.normals[old_vertex as usize]); } *mesh_vertex = new_vertex; } cluster.mesh_triangles.clear(); for &triangle in &cluster.triangles { cluster.mesh_triangles.push(mesh.triangles.len() as u32); mesh.triangles .push(triangle.map_mut(|cluster_vertex| cluster.mesh_vertices[cluster_vertex as usize])); } } mesh.positions = positions; mesh.normals = normals; (mesh, clusters) }
rust
MIT
42fc4b496cce21e907eca7112e6d6334d35fc41a
2026-01-04T20:23:56.526296Z
false
sjb3d/caldera
https://github.com/sjb3d/caldera/blob/42fc4b496cce21e907eca7112e6d6334d35fc41a/caldera/examples/test_mesh_shader/loader.rs
caldera/examples/test_mesh_shader/loader.rs
use crate::cluster::Mesh; use caldera::prelude::*; use ply_rs::{parser, ply}; use std::{fs::File, io::BufReader, path::Path}; pub fn load_ply_mesh(file_name: &Path) -> Mesh { let vertex_parser = parser::Parser::<PlyVertex>::new(); let face_parser = parser::Parser::<PlyFace>::new(); let mut f = BufReader::new(File::open(file_name).unwrap()); let header = vertex_parser.read_header(&mut f).unwrap(); let mut vertices = Vec::new(); let mut faces = Vec::new(); for (_key, element) in header.elements.iter() { match element.name.as_ref() { "vertex" => { vertices = vertex_parser .read_payload_for_element(&mut f, element, &header) .unwrap(); } "face" => { faces = face_parser.read_payload_for_element(&mut f, element, &header).unwrap(); } _ => panic!("unexpected element {:?}", element), } } let mut normals = vec![Vec3::zero(); vertices.len()]; let mut face_normals = Vec::new(); for src in faces.iter() { let v0 = vertices[src.indices[0] as usize].pos; let v1 = vertices[src.indices[1] as usize].pos; let v2 = vertices[src.indices[2] as usize].pos; let face_normal = (v2 - v1).cross(v0 - v1).normalized(); face_normals.push(if face_normal.is_nan() { Vec3::zero() } else { // TODO: weight by angle at vertex? normals[src.indices[0] as usize] += face_normal; normals[src.indices[1] as usize] += face_normal; normals[src.indices[2] as usize] += face_normal; face_normal }); } for n in normals.iter_mut() { let u = n.normalized(); if !u.is_nan() { *n = u; } } Mesh { positions: vertices.drain(..).map(|v| v.pos).collect(), normals, triangles: faces.drain(..).map(|f| f.indices).collect(), face_normals, } } #[derive(Clone, Copy)] struct PlyVertex { pos: Vec3, } #[derive(Clone, Copy)] struct PlyFace { indices: UVec3, } impl ply::PropertyAccess for PlyVertex { fn new() -> Self { Self { pos: Vec3::zero() } } fn set_property(&mut self, key: String, property: ply::Property) { match (key.as_ref(), property) { ("x", ply::Property::Float(v)) => self.pos.x = v, ("y", ply::Property::Float(v)) => self.pos.y = v, ("z", ply::Property::Float(v)) => self.pos.z = v, _ => {} } } } impl ply::PropertyAccess for PlyFace { fn new() -> Self { Self { indices: UVec3::zero() } } fn set_property(&mut self, key: String, property: ply::Property) { match (key.as_ref(), property) { ("vertex_indices", ply::Property::ListInt(v)) => { assert_eq!(v.len(), 3); for (dst, src) in self.indices.as_mut_slice().iter_mut().zip(v.iter()) { *dst = *src as u32; } } (k, _) => panic!("unknown key {}", k), } } }
rust
MIT
42fc4b496cce21e907eca7112e6d6334d35fc41a
2026-01-04T20:23:56.526296Z
false
sjb3d/caldera
https://github.com/sjb3d/caldera/blob/42fc4b496cce21e907eca7112e6d6334d35fc41a/caldera/examples/test_mesh_shader/main.rs
caldera/examples/test_mesh_shader/main.rs
mod cluster; mod loader; use crate::{cluster::*, loader::*}; use bytemuck::{Pod, Zeroable}; use caldera::prelude::*; use spark::vk; use std::{ mem, path::{Path, PathBuf}, slice, }; use structopt::StructOpt; use strum::VariantNames; use winit::{ dpi::{LogicalSize, Size}, event_loop::EventLoop, window::WindowBuilder, }; #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod)] struct PackedTransform { translation: Vec3, scale: f32, rotation_quat: [f32; 4], } impl From<Similarity3> for PackedTransform { fn from(s: Similarity3) -> Self { Self { translation: s.translation, scale: s.scale, rotation_quat: s.rotation.into_quaternion_array(), } } } #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod)] struct StandardUniforms { proj_from_view: Mat4, view_from_local: PackedTransform, } descriptor_set!(StandardDescriptorSet { standard_uniforms: UniformData<StandardUniforms>, }); const MAX_PACKED_INDICES_PER_CLUSTER: usize = (MAX_TRIANGLES_PER_CLUSTER * 3) / 4; #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod)] struct ClusterDesc { position_sphere: SphereBounds, face_normal_cone: ConeBounds, vertex_count: u32, triangle_count: u32, vertices: [u32; MAX_VERTICES_PER_CLUSTER], packed_indices: [u32; MAX_PACKED_INDICES_PER_CLUSTER], } #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod)] struct ClusterUniforms { proj_from_view: Mat4, view_from_local: PackedTransform, do_backface_culling: u32, task_count: u32, } descriptor_set!(ClusterDescriptorSet { cluster_uniforms: UniformData<ClusterUniforms>, position: StorageBuffer, normal: StorageBuffer, cluster_desc: StorageBuffer, }); struct MeshInfo { triangle_count: u32, cluster_count: u32, min: Vec3, max: Vec3, position_buffer: vk::Buffer, normal_buffer: vk::Buffer, index_buffer: vk::Buffer, cluster_buffer: vk::Buffer, } impl MeshInfo { fn get_world_from_local(&self) -> Similarity3 { let scale = 0.9 / (self.max.y - self.min.y); let offset = (-0.5 * scale) * (self.max + self.min); Similarity3::new(offset, Rotor3::identity(), scale) } async fn load(resource_loader: ResourceLoader, mesh_file_name: &Path, with_mesh_shader: bool) -> Self { let mesh_buffer_usage = if with_mesh_shader { BufferUsage::MESH_STORAGE_READ } else { BufferUsage::empty() }; let mesh = load_ply_mesh(&mesh_file_name); println!( "loaded mesh: {} vertices, {} triangles", mesh.positions.len(), mesh.triangles.len() ); let (mesh, clusters) = build_clusters(mesh); let position_buffer_desc = BufferDesc::new(mesh.positions.len() * mem::size_of::<Vec3>()); let mut writer = resource_loader .buffer_writer(&position_buffer_desc, BufferUsage::VERTEX_BUFFER | mesh_buffer_usage) .await; let mut min = Vec3::broadcast(f32::MAX); let mut max = Vec3::broadcast(f32::MIN); for &pos in &mesh.positions { writer.write(&pos); min = min.min_by_component(pos); max = max.max_by_component(pos); } let position_buffer_id = writer.finish(); let normal_buffer_desc = BufferDesc::new(mesh.normals.len() * mem::size_of::<Vec3>()); let mut writer = resource_loader .buffer_writer(&normal_buffer_desc, BufferUsage::VERTEX_BUFFER | mesh_buffer_usage) .await; for &normal in &mesh.normals { writer.write(&normal); } let normal_buffer_id = writer.finish(); let index_buffer_desc = BufferDesc::new(mesh.triangles.len() * mem::size_of::<UVec3>()); let mut writer = resource_loader .buffer_writer(&index_buffer_desc, BufferUsage::INDEX_BUFFER) .await; for &tri in &mesh.triangles { writer.write(&tri); } let index_buffer_id = writer.finish(); let cluster_buffer_desc = BufferDesc::new(clusters.len() * mem::size_of::<ClusterDesc>()); let mut writer = resource_loader .buffer_writer(&cluster_buffer_desc, mesh_buffer_usage) .await; for cluster in &clusters { let mut desc = ClusterDesc { position_sphere: SphereBounds::from_box(cluster.position_bounds), face_normal_cone: ConeBounds::from_box(cluster.face_normal_bounds), vertex_count: cluster.mesh_vertices.len() as u32, triangle_count: cluster.triangles.len() as u32, vertices: [0u32; MAX_VERTICES_PER_CLUSTER], packed_indices: [0u32; MAX_PACKED_INDICES_PER_CLUSTER], }; for (src, dst) in cluster.mesh_vertices.iter().zip(desc.vertices.iter_mut()) { *dst = *src; } let indices: &mut [u8] = bytemuck::cast_slice_mut(&mut desc.packed_indices); for (src, dst) in cluster .triangles .iter() .flat_map(|tri| tri.as_slice().iter()) .zip(indices.iter_mut()) { *dst = *src as u8; } writer.write(&desc); } let cluster_buffer_id = writer.finish(); Self { triangle_count: mesh.triangles.len() as u32, cluster_count: clusters.len() as u32, min, max, position_buffer: resource_loader.get_buffer(position_buffer_id.await), normal_buffer: resource_loader.get_buffer(normal_buffer_id.await), index_buffer: resource_loader.get_buffer(index_buffer_id.await), cluster_buffer: resource_loader.get_buffer(cluster_buffer_id.await), } } } #[derive(Clone, Copy, Eq, PartialEq)] enum RenderMode { Standard, Clusters, } struct App { has_mesh_shader: bool, task_group_size: u32, mesh_info: TaskOutput<MeshInfo>, render_mode: RenderMode, do_backface_culling: bool, is_rotating: bool, angle: f32, } impl App { fn new(base: &mut AppBase, mesh_file_name: PathBuf) -> Self { let has_mesh_shader = base.context.physical_device_features.mesh_shader.mesh_shader.as_bool() && base .context .physical_device_features .subgroup_size_control .subgroup_size_control .as_bool(); let task_group_size = base .context .physical_device_extra_properties .as_ref() .unwrap() .subgroup_size_control .max_subgroup_size; println!("task group size: {}", task_group_size); let resource_loader = base.systems.resource_loader.clone(); let mesh_info = base .systems .task_system .spawn_task(async move { MeshInfo::load(resource_loader, &mesh_file_name, has_mesh_shader).await }); Self { has_mesh_shader, task_group_size, mesh_info, render_mode: if has_mesh_shader { RenderMode::Clusters } else { RenderMode::Standard }, do_backface_culling: true, is_rotating: false, angle: 0.0, } } fn render(&mut self, base: &mut AppBase) { let cbar = base.systems.acquire_command_buffer(); base.ui_begin_frame(); base.egui_ctx.clone().input(|i| { if i.key_pressed(egui::Key::Escape) { base.exit_requested = true; } }); egui::Window::new("Debug") .default_pos([5.0, 5.0]) .default_size([350.0, 150.0]) .show(&base.egui_ctx, |ui| { ui.checkbox(&mut self.is_rotating, "Rotate"); ui.label("Render Mode:"); ui.radio_value(&mut self.render_mode, RenderMode::Standard, "Standard"); if self.has_mesh_shader { ui.radio_value(&mut self.render_mode, RenderMode::Clusters, "Clusters"); } else { ui.label("Mesh Shaders Not Supported!"); } ui.label("Cluster Settings:"); ui.checkbox(&mut self.do_backface_culling, "Backface Culling"); }); base.systems.draw_ui(&base.egui_ctx); base.ui_end_frame(cbar.pre_swapchain_cmd); let mut schedule = base.systems.resource_loader.begin_schedule( &mut base.systems.render_graph, base.context.as_ref(), &base.systems.descriptor_pool, &base.systems.pipeline_cache, ); let swap_vk_image = base .display .acquire(&base.window, cbar.image_available_semaphore.unwrap()); let swap_size = base.display.swapchain.get_size(); let swap_format = base.display.swapchain.get_format(); let swap_image = schedule.import_image( &ImageDesc::new_2d(swap_size, swap_format, vk::ImageAspectFlags::COLOR), ImageUsage::COLOR_ATTACHMENT_WRITE | ImageUsage::SWAPCHAIN, swap_vk_image, ImageUsage::empty(), ImageUsage::SWAPCHAIN, ); let main_sample_count = vk::SampleCountFlags::N1; let depth_image_desc = ImageDesc::new_2d(swap_size, vk::Format::D32_SFLOAT, vk::ImageAspectFlags::DEPTH); let depth_image = schedule.describe_image(&depth_image_desc); let main_render_state = RenderState::new() .with_color(swap_image, &[0.1f32, 0.1f32, 0.1f32, 0f32]) .with_depth(depth_image, AttachmentLoadOp::Clear, AttachmentStoreOp::None); let view_from_world = Similarity3::new( Vec3::new(0.0, 0.0, -2.5), Rotor3::from_rotation_yz(0.2) * Rotor3::from_rotation_xz(self.angle), 1.0, ); let vertical_fov = PI / 7.0; let aspect_ratio = (swap_size.x as f32) / (swap_size.y as f32); let proj_from_view = projection::rh_yup::perspective_reversed_infinite_z_vk(vertical_fov, aspect_ratio, 0.1); let mesh_info = self.mesh_info.get(); schedule.add_graphics(command_name!("main"), main_render_state, |_params| {}, { let context = base.context.as_ref(); let descriptor_pool = &base.systems.descriptor_pool; let pipeline_cache = &base.systems.pipeline_cache; let task_group_size = self.task_group_size; let render_mode = self.render_mode; let do_backface_culling = self.do_backface_culling; let pixels_per_point = base.egui_ctx.pixels_per_point(); let egui_renderer = &mut base.egui_renderer; move |_params, cmd, render_pass| { set_viewport_helper(&context.device, cmd, swap_size); if let Some(mesh_info) = mesh_info { let world_from_local = mesh_info.get_world_from_local(); let view_from_local = view_from_world * world_from_local; match render_mode { RenderMode::Standard => { let standard_descriptor_set = StandardDescriptorSet::create(descriptor_pool, |buf| { *buf = StandardUniforms { proj_from_view, view_from_local: view_from_local.into(), } }); let state = GraphicsPipelineState::new(render_pass, main_sample_count).with_vertex_inputs( &[ vk::VertexInputBindingDescription { binding: 0, stride: mem::size_of::<Vec3>() as u32, input_rate: vk::VertexInputRate::VERTEX, }, vk::VertexInputBindingDescription { binding: 1, stride: mem::size_of::<Vec3>() as u32, input_rate: vk::VertexInputRate::VERTEX, }, ], &[ vk::VertexInputAttributeDescription { location: 0, binding: 0, format: vk::Format::R32G32B32_SFLOAT, offset: 0, }, vk::VertexInputAttributeDescription { location: 1, binding: 1, format: vk::Format::R32G32B32_SFLOAT, offset: 0, }, ], ); let standard_pipeline_layout = pipeline_cache.get_pipeline_layout(slice::from_ref(&standard_descriptor_set.layout)); let pipeline = pipeline_cache.get_graphics( VertexShaderDesc::standard("test_mesh_shader/standard.vert.spv"), "test_mesh_shader/test.frag.spv", standard_pipeline_layout, &state, ); unsafe { context .device .cmd_bind_pipeline(cmd, vk::PipelineBindPoint::GRAPHICS, pipeline); context.device.cmd_bind_descriptor_sets( cmd, vk::PipelineBindPoint::GRAPHICS, standard_pipeline_layout, 0, slice::from_ref(&standard_descriptor_set.set), &[], ); context.device.cmd_bind_vertex_buffers( cmd, 0, &[mesh_info.position_buffer, mesh_info.normal_buffer], &[0, 0], ); context.device.cmd_bind_index_buffer( cmd, mesh_info.index_buffer, 0, vk::IndexType::UINT32, ); context .device .cmd_draw_indexed(cmd, mesh_info.triangle_count * 3, 1, 0, 0, 0); } } RenderMode::Clusters => { // draw cluster test let task_count = mesh_info.cluster_count; let cluster_descriptor_set = ClusterDescriptorSet::create( descriptor_pool, |buf: &mut ClusterUniforms| { *buf = ClusterUniforms { proj_from_view, view_from_local: view_from_local.into(), do_backface_culling: if do_backface_culling { 1 } else { 0 }, task_count, } }, mesh_info.position_buffer, mesh_info.normal_buffer, mesh_info.cluster_buffer, ); let state = GraphicsPipelineState::new(render_pass, main_sample_count); let cluster_pipeline_layout = pipeline_cache.get_pipeline_layout(slice::from_ref(&cluster_descriptor_set.layout)); let pipeline = pipeline_cache.get_graphics( VertexShaderDesc::mesh( "test_mesh_shader/cluster.task.spv", &[SpecializationConstant::new(0, task_group_size)], Some(task_group_size), "test_mesh_shader/cluster.mesh.spv", &[SpecializationConstant::new(0, task_group_size)], ), "test_mesh_shader/test.frag.spv", cluster_pipeline_layout, &state, ); let device = &context.device; unsafe { device.cmd_bind_pipeline(cmd, vk::PipelineBindPoint::GRAPHICS, pipeline); device.cmd_bind_descriptor_sets( cmd, vk::PipelineBindPoint::GRAPHICS, cluster_pipeline_layout, 0, slice::from_ref(&cluster_descriptor_set.set), &[], ); device.cmd_draw_mesh_tasks_nv(cmd, task_count.div_round_up(task_group_size), 0); } } } } // draw ui let egui_pipeline = pipeline_cache.get_ui(egui_renderer, render_pass, main_sample_count); egui_renderer.render( &context.device, cmd, egui_pipeline, swap_size.x, swap_size.y, pixels_per_point, ); } }); schedule.run( &base.context, cbar.pre_swapchain_cmd, cbar.post_swapchain_cmd, Some(swap_image), &mut base.systems.query_pool, ); let rendering_finished_semaphore = base.systems.submit_command_buffer(&cbar); base.display .present(swap_vk_image, rendering_finished_semaphore.unwrap()); if self.is_rotating { self.angle += base.egui_ctx.input(|i| i.stable_dt); } } } #[derive(Debug, StructOpt)] #[structopt(no_version)] struct AppParams { /// Core Vulkan version to load #[structopt(short, long, parse(try_from_str=try_version_from_str), default_value="1.1")] version: vk::Version, /// Whether to use EXT_inline_uniform_block #[structopt(long, possible_values=&ContextFeature::VARIANTS, default_value="optional")] inline_uniform_block: ContextFeature, /// Whether to use NV_mesh_shader #[structopt(long, possible_values=&ContextFeature::VARIANTS, default_value="optional")] mesh_shader: ContextFeature, /// The PLY file to load mesh_file_name: PathBuf, } fn main() { let app_params = AppParams::from_args(); let context_params = ContextParams { version: app_params.version, inline_uniform_block: app_params.inline_uniform_block, mesh_shader: app_params.mesh_shader, subgroup_size_control: app_params.mesh_shader, ..Default::default() }; let event_loop = EventLoop::new(); let window = WindowBuilder::new() .with_title("test_mesh_shader") .with_inner_size(Size::Logical(LogicalSize::new(1920.0, 1080.0))) .build(&event_loop) .unwrap(); let mut base = AppBase::new(window, &context_params); let app = App::new(&mut base, app_params.mesh_file_name); let mut apps = Some((base, app)); event_loop.run(move |event, target, control_flow| { match apps .as_mut() .map(|(base, _)| base) .unwrap() .process_event(&event, target, control_flow) { AppEventResult::None => {} AppEventResult::Redraw => { let (base, app) = apps.as_mut().unwrap(); app.render(base); } AppEventResult::Destroy => { apps.take(); } } }); }
rust
MIT
42fc4b496cce21e907eca7112e6d6334d35fc41a
2026-01-04T20:23:56.526296Z
false
sjb3d/caldera
https://github.com/sjb3d/caldera/blob/42fc4b496cce21e907eca7112e6d6334d35fc41a/caldera/examples/test_compute/main.rs
caldera/examples/test_compute/main.rs
use bytemuck::{Pod, Zeroable}; use caldera::prelude::*; use rand::{prelude::*, rngs::SmallRng}; use rayon::prelude::*; use spark::vk; use structopt::StructOpt; use strum::VariantNames; use winit::{ dpi::{LogicalSize, Size}, event_loop::EventLoop, monitor::VideoMode, window::{Fullscreen, WindowBuilder}, }; #[derive(Clone, Copy, Zeroable, Pod)] #[repr(C)] struct TraceData { dims: UVec2, dims_rcp: Vec2, pass_index: u32, } descriptor_set!(TraceDescriptorSet { trace: UniformData<TraceData>, result: [StorageImage; 3], samples: StorageImage, }); #[derive(Clone, Copy, Zeroable, Pod)] #[repr(C)] struct CopyData { offset: IVec2, trace_dims: UVec2, trace_scale: f32, } descriptor_set!(CopyDescriptorSet { copy: UniformData<CopyData>, image: [StorageImage; 3], }); struct App { sample_image_view: TaskOutput<vk::ImageView>, trace_image_ids: (ImageId, ImageId, ImageId), log2_exposure_scale: f32, target_pass_count: u32, next_pass_index: u32, } impl App { const SEQUENCE_COUNT: u32 = 1024; const SAMPLES_PER_SEQUENCE: u32 = 256; const MAX_PASS_COUNT: u32 = Self::SAMPLES_PER_SEQUENCE / 4; fn trace_image_size() -> UVec2 { UVec2::new(640, 480) } fn new(base: &mut AppBase) -> Self { let resource_loader = base.systems.resource_loader.clone(); let sample_image_view = base.systems.task_system.spawn_task(async move { let sequences: Vec<Vec<_>> = (0..Self::SEQUENCE_COUNT) .into_par_iter() .map(|i| { let mut rng = SmallRng::seed_from_u64(i as u64); pmj::generate(Self::SAMPLES_PER_SEQUENCE as usize, 4, &mut rng) }) .collect(); let desc = ImageDesc::new_2d( UVec2::new(Self::SAMPLES_PER_SEQUENCE, Self::SEQUENCE_COUNT), vk::Format::R32G32_SFLOAT, vk::ImageAspectFlags::COLOR, ); let mut writer = resource_loader .image_writer(&desc, ImageUsage::COMPUTE_STORAGE_READ) .await; for sample in sequences.iter().flat_map(|sequence| sequence.iter()) { let pixel: [f32; 2] = [sample.x(), sample.y()]; writer.write(&pixel); } resource_loader.get_image_view(writer.finish().await, ImageViewDesc::default()) }); let trace_image_ids = { let size = Self::trace_image_size(); let desc = ImageDesc::new_2d(size, vk::Format::R32_SFLOAT, vk::ImageAspectFlags::COLOR); let usage = ImageUsage::FRAGMENT_STORAGE_READ | ImageUsage::COMPUTE_STORAGE_READ | ImageUsage::COMPUTE_STORAGE_WRITE; let render_graph = &mut base.systems.render_graph; ( render_graph.create_image(&desc, usage), render_graph.create_image(&desc, usage), render_graph.create_image(&desc, usage), ) }; Self { sample_image_view, trace_image_ids, log2_exposure_scale: 0f32, target_pass_count: 16, next_pass_index: 0, } } fn render(&mut self, base: &mut AppBase) { let cbar = base.systems.acquire_command_buffer(); base.ui_begin_frame(); base.egui_ctx.clone().input(|i| { if i.key_pressed(egui::Key::Escape) { base.exit_requested = true; } }); egui::Window::new("Debug") .default_pos([5.0, 5.0]) .default_size([350.0, 150.0]) .show(&base.egui_ctx, |ui| { ui.add( egui::DragValue::new(&mut self.log2_exposure_scale) .speed(0.05f32) .prefix("Exposure: "), ); ui.add( egui::Slider::new(&mut self.target_pass_count, 1..=Self::MAX_PASS_COUNT).prefix("Max Pass Count: "), ); ui.label(format!("Passes: {}", self.next_pass_index)); if ui.button("Reset").clicked() { self.next_pass_index = 0; } }); base.systems.draw_ui(&base.egui_ctx); base.ui_end_frame(cbar.pre_swapchain_cmd); let mut schedule = base.systems.resource_loader.begin_schedule( &mut base.systems.render_graph, base.context.as_ref(), &base.systems.descriptor_pool, &base.systems.pipeline_cache, ); let sample_image_view = self.sample_image_view.get().copied(); let trace_image_size = Self::trace_image_size(); let pass_count = if let Some(sample_image_view) = sample_image_view.filter(|_| self.next_pass_index != self.target_pass_count) { if self.next_pass_index > self.target_pass_count { self.next_pass_index = 0; } schedule.add_compute( command_name!("trace"), |params| { params.add_image( self.trace_image_ids.0, ImageUsage::COMPUTE_STORAGE_READ | ImageUsage::COMPUTE_STORAGE_WRITE, ); params.add_image( self.trace_image_ids.1, ImageUsage::COMPUTE_STORAGE_READ | ImageUsage::COMPUTE_STORAGE_WRITE, ); params.add_image( self.trace_image_ids.2, ImageUsage::COMPUTE_STORAGE_READ | ImageUsage::COMPUTE_STORAGE_WRITE, ); }, { let context = base.context.as_ref(); let descriptor_pool = &base.systems.descriptor_pool; let pipeline_cache = &base.systems.pipeline_cache; let trace_image_ids = &self.trace_image_ids; let next_pass_index = self.next_pass_index; move |params, cmd| { let sample_image_view = sample_image_view; let trace_image_views = [ params.get_image_view(trace_image_ids.0, ImageViewDesc::default()), params.get_image_view(trace_image_ids.1, ImageViewDesc::default()), params.get_image_view(trace_image_ids.2, ImageViewDesc::default()), ]; let descriptor_set = TraceDescriptorSet::create( descriptor_pool, |buf: &mut TraceData| { let dims_rcp = Vec2::broadcast(1.0) / trace_image_size.as_float(); *buf = TraceData { dims: trace_image_size, dims_rcp, pass_index: next_pass_index, }; }, &trace_image_views, sample_image_view, ); dispatch_helper( &context.device, pipeline_cache, cmd, "test_compute/trace.comp.spv", &[], descriptor_set, trace_image_size.div_round_up(16), ); } }, ); self.next_pass_index + 1 } else { self.next_pass_index }; let swap_vk_image = base .display .acquire(&base.window, cbar.image_available_semaphore.unwrap()); let swap_size = base.display.swapchain.get_size(); let swap_format = base.display.swapchain.get_format(); let swap_image = schedule.import_image( &ImageDesc::new_2d(swap_size, swap_format, vk::ImageAspectFlags::COLOR), ImageUsage::COLOR_ATTACHMENT_WRITE | ImageUsage::SWAPCHAIN, swap_vk_image, ImageUsage::empty(), ImageUsage::SWAPCHAIN, ); let main_sample_count = vk::SampleCountFlags::N1; let main_render_state = RenderState::new().with_color(swap_image, &[0f32, 0f32, 0f32, 0f32]); schedule.add_graphics( command_name!("main"), main_render_state, |params| { params.add_image(self.trace_image_ids.0, ImageUsage::FRAGMENT_STORAGE_READ); params.add_image(self.trace_image_ids.1, ImageUsage::FRAGMENT_STORAGE_READ); params.add_image(self.trace_image_ids.2, ImageUsage::FRAGMENT_STORAGE_READ); }, { let context = base.context.as_ref(); let descriptor_pool = &base.systems.descriptor_pool; let pipeline_cache = &base.systems.pipeline_cache; let trace_images = &self.trace_image_ids; let log2_exposure_scale = self.log2_exposure_scale; let pixels_per_point = base.egui_ctx.pixels_per_point(); let egui_renderer = &mut base.egui_renderer; move |params, cmd, render_pass| { let trace_image_views = [ params.get_image_view(trace_images.0, ImageViewDesc::default()), params.get_image_view(trace_images.1, ImageViewDesc::default()), params.get_image_view(trace_images.2, ImageViewDesc::default()), ]; set_viewport_helper(&context.device, cmd, swap_size); let copy_descriptor_set = CopyDescriptorSet::create( descriptor_pool, |buf| { *buf = CopyData { offset: ((trace_image_size.as_signed() - swap_size.as_signed()) / 2), trace_dims: trace_image_size, trace_scale: log2_exposure_scale.exp2() / (pass_count as f32), }; }, &trace_image_views, ); draw_helper( &context.device, pipeline_cache, cmd, &GraphicsPipelineState::new(render_pass, main_sample_count), "test_compute/copy.vert.spv", "test_compute/copy.frag.spv", copy_descriptor_set, 3, ); // draw ui let egui_pipeline = pipeline_cache.get_ui(egui_renderer, render_pass, main_sample_count); egui_renderer.render( &context.device, cmd, egui_pipeline, swap_size.x, swap_size.y, pixels_per_point, ); } }, ); schedule.run( &base.context, cbar.pre_swapchain_cmd, cbar.post_swapchain_cmd, Some(swap_image), &mut base.systems.query_pool, ); let rendering_finished_semaphore = base.systems.submit_command_buffer(&cbar); base.display .present(swap_vk_image, rendering_finished_semaphore.unwrap()); self.next_pass_index = pass_count; } } #[derive(Debug, StructOpt)] #[structopt(no_version)] struct AppParams { /// Core Vulkan version to load #[structopt(short, long, parse(try_from_str=try_version_from_str), default_value="1.0")] version: vk::Version, /// Whether to use EXT_inline_uniform_block #[structopt(long, possible_values=&ContextFeature::VARIANTS, default_value="optional")] inline_uniform_block: ContextFeature, /// Run fullscreen #[structopt(short, long)] fullscreen: bool, /// Test ACES fit matrices and exit #[structopt(long)] test: bool, } fn main() { let app_params = AppParams::from_args(); let context_params = ContextParams { version: app_params.version, inline_uniform_block: app_params.inline_uniform_block, ..Default::default() }; if app_params.test { derive_aces_fit_matrices(); return; } let event_loop = EventLoop::new(); let mut window_builder = WindowBuilder::new().with_title("compute"); window_builder = if app_params.fullscreen { let monitor = event_loop.primary_monitor().unwrap(); let size = monitor.size(); let video_mode = monitor .video_modes() .filter(|m| m.size() == size) .max_by(|a, b| { let t = |m: &VideoMode| (m.bit_depth(), m.refresh_rate_millihertz()); Ord::cmp(&t(a), &t(b)) }) .unwrap(); println!( "full screen mode: {}x{} {}bpp {}mHz", video_mode.size().width, video_mode.size().height, video_mode.bit_depth(), video_mode.refresh_rate_millihertz() ); window_builder.with_fullscreen(Some(Fullscreen::Exclusive(video_mode))) } else { window_builder.with_inner_size(Size::Logical(LogicalSize::new(640.0, 480.0))) }; let window = window_builder.build(&event_loop).unwrap(); let mut base = AppBase::new(window, &context_params); let app = App::new(&mut base); let mut apps = Some((base, app)); event_loop.run(move |event, target, control_flow| { match apps .as_mut() .map(|(base, _)| base) .unwrap() .process_event(&event, target, control_flow) { AppEventResult::None => {} AppEventResult::Redraw => { let (base, app) = apps.as_mut().unwrap(); app.render(base); } AppEventResult::Destroy => { apps.take(); } } }); }
rust
MIT
42fc4b496cce21e907eca7112e6d6334d35fc41a
2026-01-04T20:23:56.526296Z
false
sjb3d/caldera
https://github.com/sjb3d/caldera/blob/42fc4b496cce21e907eca7112e6d6334d35fc41a/caldera/examples/coherent_hashing/main.rs
caldera/examples/coherent_hashing/main.rs
use arrayvec::ArrayVec; use bytemuck::{Pod, Zeroable}; use caldera::prelude::*; use primes::{PrimeSet as _, Sieve}; use rand::{distributions::Uniform, prelude::*, rngs::SmallRng}; use spark::vk; use std::mem; use structopt::StructOpt; use strum::VariantNames; use winit::{ dpi::{LogicalSize, Size}, event_loop::EventLoop, window::WindowBuilder, }; struct Primes(Sieve); impl Primes { fn new() -> Self { Self(Sieve::new()) } fn next_after(&mut self, n: u32) -> u32 { self.0.find(n as u64).1 as u32 } } const MAX_AGE: usize = 15; #[repr(C)] #[derive(Debug, Clone, Copy, Pod, Zeroable)] struct HashTableInfo { entry_count: u32, store_max_age: u32, offsets: [u32; MAX_AGE], } #[repr(C)] #[derive(Debug, Clone, Copy, Pod, Zeroable)] struct CircleParams { centre: Vec2, radius: f32, } const CIRCLE_COUNT: usize = 4; #[repr(C)] #[derive(Debug, Clone, Copy, Pod, Zeroable)] struct GenerateImageUniforms { circles: [CircleParams; CIRCLE_COUNT], } descriptor_set!(GenerateImageDescriptorSet { uniforms: UniformData<GenerateImageUniforms>, image: StorageImage }); descriptor_set!(ClearHashTableDescriptorSet { hash_table_info: UniformData<HashTableInfo>, entries: StorageBuffer, max_ages: StorageBuffer, age_histogram: StorageBuffer, }); descriptor_set!(UpdateHashTableDescriptorSet { hash_table_info: UniformData<HashTableInfo>, entries: StorageBuffer, max_ages: StorageBuffer, image: StorageImage, }); #[repr(C)] #[derive(Clone, Copy, Pod, Zeroable)] struct DebugQuadUniforms { ortho_from_quad: Scale2Offset2, } descriptor_set!(DebugImageDescriptorSet { debug_quad: UniformData<DebugQuadUniforms>, input_image: StorageImage, output_image: StorageImage }); descriptor_set!(DebugHashTableDescriptorSet { debug_quad: UniformData<DebugQuadUniforms>, hash_table_info: UniformData<HashTableInfo>, entries: StorageBuffer, }); descriptor_set!(MakeAgeHistogramDescriptorSet { hash_table_info: UniformData<HashTableInfo>, entries: StorageBuffer, age_histogram: StorageBuffer, }); descriptor_set!(DebugAgeHistogramDescriptorSet { debug_quad: UniformData<DebugQuadUniforms>, hash_table_info: UniformData<HashTableInfo>, age_histogram: StorageBuffer, }); struct App { rng: SmallRng, primes: Primes, store_max_age: bool, table_size: f32, circles: [CircleParams; CIRCLE_COUNT], hash_table_offsets: [u32; MAX_AGE], } fn make_circles(rng: &mut SmallRng) -> [CircleParams; CIRCLE_COUNT] { let mut circles = ArrayVec::new(); let dist = Uniform::new(0.0, 1.0); for _ in 0..CIRCLE_COUNT { circles.push(CircleParams { centre: Vec2::new(rng.sample(dist), rng.sample(dist)) * 1024.0, radius: rng.sample(dist) * 512.0, }); } circles.into_inner().unwrap() } fn make_hash_table_offsets(rng: &mut SmallRng, primes: &mut Primes) -> [u32; MAX_AGE] { let dist = Uniform::new(1_000_000, 10_000_000); let mut offsets = ArrayVec::new(); offsets.push(0); for _ in 1..MAX_AGE { let random_not_prime = rng.sample(dist); offsets.push(primes.next_after(random_not_prime)); } offsets.into_inner().unwrap() } impl App { fn new(_base: &mut AppBase) -> Self { let mut rng = SmallRng::seed_from_u64(0); let mut primes = Primes::new(); let circles = make_circles(&mut rng); let hash_table_offsets = make_hash_table_offsets(&mut rng, &mut primes); println!("{:?}", hash_table_offsets); Self { rng, primes, store_max_age: true, table_size: 0.05, circles, hash_table_offsets, } } fn render(&mut self, base: &mut AppBase) { let cbar = base.systems.acquire_command_buffer(); base.ui_begin_frame(); base.egui_ctx.clone().input(|i| { if i.key_pressed(egui::Key::Escape) { base.exit_requested = true; } }); egui::Window::new("Debug") .default_pos([5.0, 5.0]) .default_size([350.0, 150.0]) .show(&base.egui_ctx, |ui| { if ui.button("Random circles").clicked() { self.circles = make_circles(&mut self.rng); } ui.add(egui::Slider::new(&mut self.table_size, 0.001..=0.12).prefix("Table size: ")); ui.checkbox(&mut self.store_max_age, "Store max age"); if ui.button("Random offsets").clicked() { self.hash_table_offsets = make_hash_table_offsets(&mut self.rng, &mut self.primes); } }); base.systems.draw_ui(&base.egui_ctx); base.ui_end_frame(cbar.pre_swapchain_cmd); let mut schedule = base.systems.resource_loader.begin_schedule( &mut base.systems.render_graph, base.context.as_ref(), &base.systems.descriptor_pool, &base.systems.pipeline_cache, ); let swap_vk_image = base .display .acquire(&base.window, cbar.image_available_semaphore.unwrap()); let swap_size = base.display.swapchain.get_size(); let swap_format = base.display.swapchain.get_format(); let swap_image = schedule.import_image( &ImageDesc::new_2d(swap_size, swap_format, vk::ImageAspectFlags::COLOR), ImageUsage::COLOR_ATTACHMENT_WRITE | ImageUsage::SWAPCHAIN, swap_vk_image, ImageUsage::empty(), ImageUsage::SWAPCHAIN, ); let main_sample_count = vk::SampleCountFlags::N1; let main_render_state = RenderState::new().with_color(swap_image, &[0.1f32, 0.1f32, 0.1f32, 0f32]); let image_size = UVec2::new(1024, 1024); let image_desc = ImageDesc::new_2d(image_size, vk::Format::R8_UNORM, vk::ImageAspectFlags::COLOR); let input_image = schedule.describe_image(&image_desc); let output_image = schedule.describe_image(&image_desc); let entry_count = ((1024.0 * 1024.0 * self.table_size) as u32) | 1; let hash_table_info = HashTableInfo { entry_count, store_max_age: if self.store_max_age { 1 } else { 0 }, offsets: self.hash_table_offsets, }; let buffer_desc = BufferDesc::new((entry_count as usize) * mem::size_of::<u32>()); let entries_buffer_id = schedule.describe_buffer(&buffer_desc); let max_ages_buffer_id = schedule.describe_buffer(&buffer_desc); let age_histogram_buffer_id = schedule.describe_buffer(&BufferDesc::new(MAX_AGE * mem::size_of::<u32>())); schedule.add_compute( command_name!("generate_image"), |params| { params.add_image(input_image, ImageUsage::COMPUTE_STORAGE_WRITE); }, { let context = base.context.as_ref(); let descriptor_pool = &base.systems.descriptor_pool; let pipeline_cache = &base.systems.pipeline_cache; let circles = &self.circles; move |params, cmd| { let descriptor_set = GenerateImageDescriptorSet::create( descriptor_pool, |buf: &mut GenerateImageUniforms| *buf = GenerateImageUniforms { circles: *circles }, params.get_image_view(input_image, ImageViewDesc::default()), ); dispatch_helper( &context.device, pipeline_cache, cmd, "coherent_hashing/generate_image.comp.spv", &[], descriptor_set, image_size.div_round_up(16), ); } }, ); schedule.add_compute( command_name!("clear_hash_table"), |params| { params.add_buffer(entries_buffer_id, BufferUsage::COMPUTE_STORAGE_WRITE); params.add_buffer(max_ages_buffer_id, BufferUsage::COMPUTE_STORAGE_WRITE); params.add_buffer(age_histogram_buffer_id, BufferUsage::COMPUTE_STORAGE_WRITE); }, { let context = base.context.as_ref(); let descriptor_pool = &base.systems.descriptor_pool; let pipeline_cache = &base.systems.pipeline_cache; move |params, cmd| { let descriptor_set = ClearHashTableDescriptorSet::create( descriptor_pool, |buf: &mut HashTableInfo| *buf = hash_table_info, params.get_buffer(entries_buffer_id), params.get_buffer(max_ages_buffer_id), params.get_buffer(age_histogram_buffer_id), ); dispatch_helper( &context.device, pipeline_cache, cmd, "coherent_hashing/clear_hash_table.comp.spv", &[], descriptor_set, UVec2::new(entry_count.div_round_up(64), 1), ); } }, ); schedule.add_compute( command_name!("write_hash_table"), |params| { params.add_buffer(entries_buffer_id, BufferUsage::COMPUTE_STORAGE_ATOMIC); params.add_buffer(max_ages_buffer_id, BufferUsage::COMPUTE_STORAGE_ATOMIC); params.add_image(input_image, ImageUsage::COMPUTE_STORAGE_READ); }, { let context = base.context.as_ref(); let descriptor_pool = &base.systems.descriptor_pool; let pipeline_cache = &base.systems.pipeline_cache; move |params, cmd| { let descriptor_set = UpdateHashTableDescriptorSet::create( descriptor_pool, |buf: &mut HashTableInfo| *buf = hash_table_info, params.get_buffer(entries_buffer_id), params.get_buffer(max_ages_buffer_id), params.get_image_view(input_image, ImageViewDesc::default()), ); dispatch_helper( &context.device, pipeline_cache, cmd, "coherent_hashing/write_hash_table.comp.spv", &[], descriptor_set, image_size.div_round_up(16), ); } }, ); schedule.add_compute( command_name!("make_age_histogram"), |params| { params.add_buffer(entries_buffer_id, BufferUsage::COMPUTE_STORAGE_READ); params.add_buffer(age_histogram_buffer_id, BufferUsage::COMPUTE_STORAGE_ATOMIC); }, { let context = base.context.as_ref(); let descriptor_pool = &base.systems.descriptor_pool; let pipeline_cache = &base.systems.pipeline_cache; move |params, cmd| { let descriptor_set = MakeAgeHistogramDescriptorSet::create( descriptor_pool, |buf: &mut HashTableInfo| *buf = hash_table_info, params.get_buffer(entries_buffer_id), params.get_buffer(age_histogram_buffer_id), ); dispatch_helper( &context.device, pipeline_cache, cmd, "coherent_hashing/make_age_histogram.comp.spv", &[], descriptor_set, UVec2::new(entry_count.div_round_up(64), 1), ); } }, ); schedule.add_compute( command_name!("read_hash_table"), |params| { params.add_buffer(entries_buffer_id, BufferUsage::COMPUTE_STORAGE_READ); params.add_buffer(max_ages_buffer_id, BufferUsage::COMPUTE_STORAGE_READ); params.add_image(output_image, ImageUsage::COMPUTE_STORAGE_WRITE); }, { let context = base.context.as_ref(); let descriptor_pool = &base.systems.descriptor_pool; let pipeline_cache = &base.systems.pipeline_cache; move |params, cmd| { let descriptor_set = UpdateHashTableDescriptorSet::create( descriptor_pool, |buf: &mut HashTableInfo| *buf = hash_table_info, params.get_buffer(entries_buffer_id), params.get_buffer(max_ages_buffer_id), params.get_image_view(output_image, ImageViewDesc::default()), ); dispatch_helper( &context.device, pipeline_cache, cmd, "coherent_hashing/read_hash_table.comp.spv", &[], descriptor_set, image_size.div_round_up(16), ); } }, ); schedule.add_graphics( command_name!("main"), main_render_state, |params| { params.add_image(input_image, ImageUsage::FRAGMENT_STORAGE_READ); params.add_image(output_image, ImageUsage::FRAGMENT_STORAGE_READ); params.add_buffer(entries_buffer_id, BufferUsage::FRAGMENT_STORAGE_READ); params.add_buffer(age_histogram_buffer_id, BufferUsage::FRAGMENT_STORAGE_READ); }, { let context = base.context.as_ref(); let descriptor_pool = &base.systems.descriptor_pool; let pipeline_cache = &base.systems.pipeline_cache; let pixels_per_point = base.egui_ctx.pixels_per_point(); let egui_renderer = &mut base.egui_renderer; move |params, cmd, render_pass| { set_viewport_helper(&context.device, cmd, swap_size); let ortho_from_screen = Scale2Offset2::new(Vec2::broadcast(2.0) / swap_size.as_float(), Vec2::broadcast(-1.0)); // visualise results let screen_from_image = Scale2Offset2::new(image_size.as_float(), Vec2::broadcast(10.0)); let descriptor_set = DebugImageDescriptorSet::create( descriptor_pool, |buf: &mut DebugQuadUniforms| { *buf = DebugQuadUniforms { ortho_from_quad: ortho_from_screen * screen_from_image, }; }, params.get_image_view(input_image, ImageViewDesc::default()), params.get_image_view(output_image, ImageViewDesc::default()), ); let state = GraphicsPipelineState::new(render_pass, main_sample_count) .with_topology(vk::PrimitiveTopology::TRIANGLE_STRIP); draw_helper( &context.device, pipeline_cache, cmd, &state, "coherent_hashing/debug_quad.vert.spv", "coherent_hashing/debug_image.frag.spv", descriptor_set, 4, ); let screen_from_table = Scale2Offset2::new(Vec2::new(128.0, 1024.0), Vec2::new(1044.0, 10.0)); let descriptor_set = DebugHashTableDescriptorSet::create( descriptor_pool, |buf: &mut DebugQuadUniforms| { *buf = DebugQuadUniforms { ortho_from_quad: ortho_from_screen * screen_from_table, }; }, |buf: &mut HashTableInfo| { *buf = hash_table_info; }, params.get_buffer(entries_buffer_id), ); draw_helper( &context.device, pipeline_cache, cmd, &state, "coherent_hashing/debug_quad.vert.spv", "coherent_hashing/debug_hash_table.frag.spv", descriptor_set, 4, ); let screen_from_histogram = Scale2Offset2::new(Vec2::new(160.0, 80.0), Vec2::new(1184.0, 10.0)); let descriptor_set = DebugAgeHistogramDescriptorSet::create( descriptor_pool, |buf: &mut DebugQuadUniforms| { *buf = DebugQuadUniforms { ortho_from_quad: ortho_from_screen * screen_from_histogram, }; }, |buf: &mut HashTableInfo| { *buf = hash_table_info; }, params.get_buffer(age_histogram_buffer_id), ); draw_helper( &context.device, pipeline_cache, cmd, &state, "coherent_hashing/debug_quad.vert.spv", "coherent_hashing/debug_age_histogram.frag.spv", descriptor_set, 4, ); // draw ui let egui_pipeline = pipeline_cache.get_ui(egui_renderer, render_pass, main_sample_count); egui_renderer.render( &context.device, cmd, egui_pipeline, swap_size.x, swap_size.y, pixels_per_point, ); } }, ); schedule.run( &base.context, cbar.pre_swapchain_cmd, cbar.post_swapchain_cmd, Some(swap_image), &mut base.systems.query_pool, ); let rendering_finished_semaphore = base.systems.submit_command_buffer(&cbar); base.display .present(swap_vk_image, rendering_finished_semaphore.unwrap()); } } #[derive(Debug, StructOpt)] #[structopt(no_version)] struct AppParams { /// Core Vulkan version to load #[structopt(short, long, parse(try_from_str=try_version_from_str), default_value="1.1")] version: vk::Version, /// Whether to use EXT_inline_uniform_block #[structopt(long, possible_values=&ContextFeature::VARIANTS, default_value="optional")] inline_uniform_block: ContextFeature, } fn main() { let app_params = AppParams::from_args(); let context_params = ContextParams { version: app_params.version, inline_uniform_block: app_params.inline_uniform_block, ..Default::default() }; let event_loop = EventLoop::new(); let window = WindowBuilder::new() .with_title("coherent_hashing") .with_inner_size(Size::Logical(LogicalSize::new(1354.0, 1044.0))) .build(&event_loop) .unwrap(); let mut base = AppBase::new(window, &context_params); let app = App::new(&mut base); let mut apps = Some((base, app)); event_loop.run(move |event, target, control_flow| { match apps .as_mut() .map(|(base, _)| base) .unwrap() .process_event(&event, target, control_flow) { AppEventResult::None => {} AppEventResult::Redraw => { let (base, app) = apps.as_mut().unwrap(); app.render(base); } AppEventResult::Destroy => { apps.take(); } } }); }
rust
MIT
42fc4b496cce21e907eca7112e6d6334d35fc41a
2026-01-04T20:23:56.526296Z
false
sjb3d/caldera
https://github.com/sjb3d/caldera/blob/42fc4b496cce21e907eca7112e6d6334d35fc41a/caldera/examples/path_tracer/tungsten.rs
caldera/examples/path_tracer/tungsten.rs
use crate::scene; use bytemuck::{Pod, Zeroable}; use caldera::prelude::*; use serde::{Deserialize, Serialize}; use std::path::Path; use std::{fs::File, io::BufReader, io::Read, mem}; #[derive(Debug, Clone, Copy, Serialize, Deserialize)] #[serde(untagged)] enum ScalarOrVec3 { Scalar(f32), Vec3([f32; 3]), } #[derive(Debug, Serialize, Deserialize)] #[serde(untagged)] enum TextureOrValue { Value(ScalarOrVec3), Texture(String), } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] enum BsdfType { Null, Lambert, Mirror, Plastic, RoughPlastic, Dielectric, RoughDielectric, Conductor, RoughConductor, Transparency, #[serde(rename = "thinsheet")] ThinSheet, OrenNayar, LambertianFiber, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] #[allow(clippy::upper_case_acronyms)] enum Distribution { Beckmann, #[serde(rename = "ggx")] GGX, } #[derive(Debug, Serialize, Deserialize)] enum Material { Ag, Al, AlSb, Au, Cr, Fe, Li, TiN, V, VN, W, } #[derive(Debug, Serialize, Deserialize)] struct Bsdf { name: Option<String>, #[serde(rename = "type")] bsdf_type: BsdfType, albedo: TextureOrValue, distribution: Option<Distribution>, roughness: Option<f32>, material: Option<Material>, eta: Option<f32>, k: Option<f32>, ior: Option<f32>, } #[derive(Debug, Serialize, Deserialize)] struct PrimitiveTransform { position: Option<[f32; 3]>, rotation: Option<[f32; 3]>, scale: Option<ScalarOrVec3>, } impl ScalarOrVec3 { fn into_vec3(self) -> Vec3 { match self { ScalarOrVec3::Scalar(s) => Vec3::broadcast(s), ScalarOrVec3::Vec3(v) => v.into(), } } fn ungamma_colour(self) -> Self { match self { ScalarOrVec3::Scalar(s) => ScalarOrVec3::Scalar(s), ScalarOrVec3::Vec3(v) => ScalarOrVec3::Vec3(Vec3::from(v).into_linear().into()), } } } impl PrimitiveTransform { fn decompose(&self) -> (Similarity3, Option<Vec3>) { let translation = self.position.map(Vec3::from).unwrap_or_else(Vec3::zero); let mut rotation = self .rotation .map(|r| { let r = Vec3::from(r) * PI / 180.0; Rotor3::from_euler_angles(r.z, r.x, r.y) }) .unwrap_or_else(Rotor3::identity); let (scale, vector_scale) = self .scale .as_ref() .map(|s| match s { ScalarOrVec3::Scalar(s) => (*s, None), ScalarOrVec3::Vec3(v) => { // move pairs of sign flips to 180 degree rotations, make vector scale positive let sign_bit_set = |x: f32| (x.to_bits() & 0x80_00_00_00) != 0; let v = Vec3::from(v); match (sign_bit_set(v.x), sign_bit_set(v.y), sign_bit_set(v.z)) { (false, false, false) | (true, true, true) => (1.0_f32.copysign(v.x), Some(v.abs())), (true, false, false) | (false, true, true) => { rotation = rotation * Rotor3::from_rotation_yz(PI); (1.0_f32.copysign(v.x), Some(v.abs())) } (false, true, false) | (true, false, true) => { rotation = rotation * Rotor3::from_rotation_xz(PI); (1.0_f32.copysign(v.y), Some(v.abs())) } (false, false, true) | (true, true, false) => { rotation = rotation * Rotor3::from_rotation_xy(PI); (1.0_f32.copysign(v.z), Some(v.abs())) } } } }) .unwrap_or((1.0, None)); (Similarity3::new(translation, rotation, scale), vector_scale) } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] enum PrimitiveType { Mesh, Quad, Sphere, InfiniteSphereCap, InfiniteSphere, Skydome, Curves, Disk, } #[derive(Debug, Serialize, Deserialize)] #[serde(untagged)] enum BsdfRef { Named(String), Inline(Bsdf), } #[derive(Debug, Serialize, Deserialize)] struct Primitive { transform: PrimitiveTransform, #[serde(rename = "type")] primitive_type: PrimitiveType, file: Option<String>, power: Option<ScalarOrVec3>, emission: Option<TextureOrValue>, bsdf: Option<BsdfRef>, cap_angle: Option<f32>, } #[derive(Debug, Serialize, Deserialize)] struct CameraTransform { position: [f32; 3], look_at: [f32; 3], up: [f32; 3], } #[derive(Debug, Serialize, Deserialize)] #[serde(untagged)] enum Resolution { Square(f32), Rectangular(f32, f32), } impl Resolution { fn aspect_ratio(&self) -> f32 { match self { Resolution::Square(_) => 1.0, Resolution::Rectangular(width, height) => width / height, } } } #[derive(Debug, Serialize, Deserialize)] struct Camera { transform: CameraTransform, resolution: Resolution, fov: f32, } #[derive(Debug, Serialize, Deserialize)] struct Scene { bsdfs: Vec<Bsdf>, primitives: Vec<Primitive>, camera: Camera, } #[repr(C)] #[derive(Clone, Copy, Pod, Zeroable)] struct Vertex { pos: Vec3, normal: Vec3, uv: Vec2, } #[repr(C)] #[derive(Clone, Copy, Pod, Zeroable)] struct Triangle { indices: IVec3, mat: i32, } fn load_mesh<P: AsRef<Path>>(path: P, extra_scale: Option<Vec3>, reverse_winding: bool) -> scene::Geometry { let mut reader = BufReader::new(File::open(path).unwrap()); let mut vertex_count = 0u64; reader.read_exact(bytemuck::bytes_of_mut(&mut vertex_count)).unwrap(); let mut vertices = vec![Vertex::zeroed(); vertex_count as usize]; reader .read_exact(bytemuck::cast_slice_mut(vertices.as_mut_slice())) .unwrap(); let mut triangle_count = 0u64; reader.read_exact(bytemuck::bytes_of_mut(&mut triangle_count)).unwrap(); let mut triangles = vec![Triangle::zeroed(); triangle_count as usize]; reader .read_exact(bytemuck::cast_slice_mut(triangles.as_mut_slice())) .unwrap(); if reverse_winding { for vtx in vertices.iter_mut() { vtx.normal = -vtx.normal; } for tri in triangles.iter_mut() { mem::swap(&mut tri.indices.x, &mut tri.indices.z); } } if let Some(extra_scale) = extra_scale { for v in vertices.iter_mut() { v.pos *= extra_scale; v.normal /= extra_scale; } } let mut min = Vec3::broadcast(f32::INFINITY); let mut max = Vec3::broadcast(-f32::INFINITY); for v in vertices.iter() { min = min.min_by_component(v.pos); max = max.max_by_component(v.pos); } let mut area = 0.0; for t in triangles.iter() { let p0 = vertices[t.indices.x as usize].pos; let p1 = vertices[t.indices.y as usize].pos; let p2 = vertices[t.indices.z as usize].pos; area += (0.5 * (p2 - p1).cross(p0 - p1).mag()) as f64; } scene::Geometry::TriangleMesh { positions: vertices.iter().map(|v| v.pos).collect(), normals: Some(vertices.iter().map(|v| v.normal.normalized()).collect()), uvs: Some(vertices.iter().map(|v| Vec2::new(v.uv.x, 1.0 - v.uv.y)).collect()), indices: triangles.drain(..).map(|t| t.indices.as_unsigned()).collect(), min, max, area: area as f32, } } pub fn load_scene<P: AsRef<Path>>(path: P, illuminant: scene::Illuminant) -> scene::Scene { let reader = BufReader::new(File::open(&path).unwrap()); let scene: Scene = serde_json::from_reader(reader).unwrap(); let load_emission = |primitive: &Primitive, area: f32| { let mut tint = None; if let Some(s) = primitive.power.as_ref() { tint = Some(s.into_vec3() / (area * PI)); } if let Some(TextureOrValue::Value(v)) = &primitive.emission { tint = Some(v.into_vec3()); } tint.map(|tint| scene::Emission { illuminant, intensity: tint, }) }; let load_material = |bsdf_ref: &BsdfRef| { let bsdf = match bsdf_ref { BsdfRef::Inline(bsdf) => bsdf, BsdfRef::Named(name) => scene .bsdfs .iter() .find(|bsdf| bsdf.name.as_ref() == Some(name)) .unwrap(), }; let reflectance = match &bsdf.albedo { TextureOrValue::Value(value) => scene::Reflectance::Constant(value.ungamma_colour().into_vec3()), TextureOrValue::Texture(filename) => scene::Reflectance::Texture(path.as_ref().with_file_name(filename)), }; let conductor = || { bsdf.material .as_ref() .map(|material| match material { Material::Ag => scene::Conductor::Silver, Material::Al => scene::Conductor::Aluminium, Material::AlSb => scene::Conductor::AluminiumAntimonide, Material::Au => scene::Conductor::Gold, Material::Cr => scene::Conductor::Chromium, Material::Fe => scene::Conductor::Iron, Material::Li => scene::Conductor::Lithium, Material::TiN => scene::Conductor::TitaniumNitride, Material::V => scene::Conductor::Vanadium, Material::VN => scene::Conductor::VanadiumNitride, Material::W => scene::Conductor::Tungsten, }) .or_else(|| { bsdf.eta.zip(bsdf.k).and_then(|(eta, k)| { #[allow(clippy::float_cmp)] if eta == 2.0 && k == 0.0 { Some(scene::Conductor::Custom) } else { println!("TODO: unknown conductor eta={}, k={}", eta, k); None } }) }) .unwrap_or(scene::Conductor::Aluminium) }; let surface = match bsdf.bsdf_type { BsdfType::Null => scene::Surface::None, BsdfType::Lambert => scene::Surface::Diffuse, BsdfType::Mirror => scene::Surface::Mirror, BsdfType::Dielectric => scene::Surface::SmoothDielectric, BsdfType::RoughDielectric => scene::Surface::RoughDielectric { roughness: bsdf.roughness.unwrap().sqrt(), }, BsdfType::Conductor => scene::Surface::RoughConductor { conductor: conductor(), roughness: 0.0, }, BsdfType::RoughConductor => scene::Surface::RoughConductor { conductor: conductor(), roughness: bsdf.roughness.unwrap().sqrt(), }, BsdfType::Plastic => scene::Surface::SmoothPlastic, BsdfType::RoughPlastic => scene::Surface::RoughPlastic { roughness: bsdf.roughness.unwrap().sqrt(), }, _ => scene::Surface::Diffuse, }; let reverse_winding = bsdf.ior.map(|ior| ior < 1.0).unwrap_or(false); ( scene::Material { reflectance, surface, emission: None, }, reverse_winding, ) }; let mut output = scene::Scene::default(); for primitive in scene.primitives.iter() { match primitive.primitive_type { PrimitiveType::Quad => { let (world_from_local, extra_scale) = primitive.transform.decompose(); let size = extra_scale .map(|v| Vec2::new(v.x, v.z)) .unwrap_or_else(|| Vec2::broadcast(1.0)); let geometry = scene::Geometry::Quad { local_from_quad: Similarity3::new(Vec3::zero(), Rotor3::from_rotation_yz(-PI / 2.0), 1.0), size, }; let area = (size.x * size.y * world_from_local.scale * world_from_local.scale).abs(); let (mut material, _) = load_material(primitive.bsdf.as_ref().unwrap()); material.emission = load_emission(primitive, area); let geometry_ref = output.add_geometry(geometry); let transform_ref = output.add_transform(scene::Transform::new(world_from_local)); let material_ref = output.add_material(material); output.add_instance(scene::Instance::new(transform_ref, geometry_ref, material_ref)); } PrimitiveType::Disk => { let (world_from_local, extra_scale) = primitive.transform.decompose(); assert!(extra_scale.is_none(), "non-uniform sphere not supported"); let radius = 1.0; let geometry = scene::Geometry::Disc { local_from_disc: Similarity3::new(Vec3::zero(), Rotor3::from_rotation_yz(-PI / 2.0), 1.0), radius, }; let area = (PI * radius * radius * world_from_local.scale * world_from_local.scale).abs(); let (mut material, _) = load_material(primitive.bsdf.as_ref().unwrap()); material.emission = load_emission(primitive, area); let geometry_ref = output.add_geometry(geometry); let transform_ref = output.add_transform(scene::Transform::new(world_from_local)); let material_ref = output.add_material(material); output.add_instance(scene::Instance::new(transform_ref, geometry_ref, material_ref)); } PrimitiveType::Mesh => { let (world_from_local, extra_scale) = primitive.transform.decompose(); let (mut material, reverse_winding) = load_material(primitive.bsdf.as_ref().unwrap()); let mesh = load_mesh( path.as_ref().with_file_name(primitive.file.as_ref().unwrap()), extra_scale, reverse_winding, ); let area = match mesh { scene::Geometry::TriangleMesh { area, .. } => area, _ => panic!("expected a mesh"), }; material.emission = load_emission(primitive, area); let geometry_ref = output.add_geometry(mesh); let transform_ref = output.add_transform(scene::Transform::new(world_from_local)); let material_ref = output.add_material(material); output.add_instance(scene::Instance::new(transform_ref, geometry_ref, material_ref)); } PrimitiveType::Sphere => { let (world_from_local, extra_scale) = primitive.transform.decompose(); if extra_scale.is_some() { unimplemented!(); } let centre = world_from_local.translation; let radius = world_from_local.scale.abs(); let area = 4.0 * PI * radius * radius; let (mut material, _) = load_material(primitive.bsdf.as_ref().unwrap()); material.emission = load_emission(primitive, area); let geometry_ref = output.add_geometry(scene::Geometry::Sphere { centre, radius }); let transform_ref = output.add_transform(scene::Transform::new(world_from_local)); let material_ref = output.add_material(material); output.add_instance(scene::Instance::new(transform_ref, geometry_ref, material_ref)); } PrimitiveType::InfiniteSphereCap => { let (world_from_local, _extra_scale) = primitive.transform.decompose(); let theta = primitive.cap_angle.unwrap() * PI / 180.0; let solid_angle = 2.0 * PI * (1.0 - theta.cos()); let emission = primitive.power.as_ref().map(|p| p.into_vec3() / solid_angle).unwrap(); let direction_ws = world_from_local.rotation * Vec3::unit_y(); output.add_light(scene::Light::SolidAngle { emission: scene::Emission::new_uniform(emission), direction_ws, solid_angle, }); } PrimitiveType::InfiniteSphere => { let emission = match primitive.emission.as_ref().unwrap() { TextureOrValue::Value(v) => v.into_vec3(), TextureOrValue::Texture(_) => { println!("TODO: InfiniteSphere texture!"); Vec3::new(0.2, 0.3, 0.4) } }; output.add_light(scene::Light::Dome { emission: scene::Emission { illuminant, intensity: emission, }, }); } PrimitiveType::Skydome => { println!("TODO: convert Skydome geometry!"); output.add_light(scene::Light::Dome { emission: scene::Emission { illuminant, intensity: Vec3::new(0.2, 0.3, 0.4), }, }); } PrimitiveType::Curves => { println!("TODO: curves!"); } } } { let camera = &scene.camera; let world_from_local = { let isometry = Mat4::look_at( camera.transform.position.into(), camera.transform.look_at.into(), camera.transform.up.into(), ) .into_isometry() .inversed(); Similarity3::new( isometry.translation, isometry.rotation * Rotor3::from_rotation_xz(PI), 1.0, ) }; let aspect_ratio = camera.resolution.aspect_ratio(); output.add_camera(scene::Camera::Pinhole { world_from_camera: world_from_local, fov_y: camera.fov * (PI / 180.0) / aspect_ratio, }); } output.bake_unique_geometry(); output }
rust
MIT
42fc4b496cce21e907eca7112e6d6334d35fc41a
2026-01-04T20:23:56.526296Z
false
sjb3d/caldera
https://github.com/sjb3d/caldera/blob/42fc4b496cce21e907eca7112e6d6334d35fc41a/caldera/examples/path_tracer/renderer.rs
caldera/examples/path_tracer/renderer.rs
use crate::{accel::*, prelude::*, scene::*}; use bytemuck::{Contiguous, Pod, Zeroable}; use caldera::prelude::*; use rand::{prelude::*, rngs::SmallRng}; use rayon::prelude::*; use spark::vk; use std::{ collections::HashMap, fs::File, io, mem, ops::{BitOr, BitOrAssign}, path::{Path, PathBuf}, sync::Arc, }; use structopt::StructOpt; use strum::{EnumString, EnumVariantNames, VariantNames}; trait UnitScale { fn unit_scale(&self, world_from_local: Similarity3) -> f32; } impl UnitScale for Geometry { fn unit_scale(&self, world_from_local: Similarity3) -> f32 { let local_offset = match self { Geometry::TriangleMesh { min, max, .. } => max.abs().max_by_component(min.abs()).component_max(), Geometry::Quad { local_from_quad, size } => { local_from_quad.translation.abs().component_max() + local_from_quad.scale.abs() * size.abs().component_max() } Geometry::Disc { local_from_disc, radius, } => local_from_disc.translation.abs().component_max() + local_from_disc.scale.abs() * radius.abs(), Geometry::Sphere { centre, radius } => centre.abs().component_max() + radius, Geometry::Mandelbulb { local_from_bulb } => { local_from_bulb.translation.abs().component_max() + local_from_bulb.scale.abs() * MANDELBULB_RADIUS } }; let world_offset = world_from_local.translation.abs().component_max(); world_offset.max(world_from_local.scale.abs() * local_offset) } } trait LightCanBeSampled { fn can_be_sampled(&self) -> bool; } impl LightCanBeSampled for Light { fn can_be_sampled(&self) -> bool { match self { Light::Dome { .. } => false, Light::SolidAngle { .. } => true, } } } #[repr(u32)] #[derive(Clone, Copy, Contiguous, PartialEq, Eq)] enum LightType { TriangleMesh, Quad, Disc, Sphere, Dome, SolidAngle, } #[repr(u32)] #[derive(Debug, Clone, Copy, Contiguous, PartialEq, Eq, EnumString, EnumVariantNames)] #[strum(serialize_all = "kebab_case")] pub enum SequenceType { Pmj, Sobol, } #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod)] struct LightInfoEntry { light_flags: u32, probability: f32, params_offset: u32, } #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod)] struct TriangleMeshLightParams { alias_table_address: u64, index_buffer_address: u64, position_buffer_address: u64, world_from_local: Transform3, illuminant_tint: Vec3, triangle_count: u32, area_pdf: f32, unit_scale: f32, } #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod)] struct PlanarLightParams { illuminant_tint: Vec3, unit_scale: f32, area_pdf: f32, normal_ws: Vec3, point_ws: Vec3, vec0_ws: Vec3, vec1_ws: Vec3, } #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod)] struct SphereLightParams { illuminant_tint: Vec3, unit_scale: f32, centre_ws: Vec3, radius_ws: f32, } #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod)] struct DomeLightParams { illuminant_tint: Vec3, } #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod)] struct SolidAngleLightParams { illuminant_tint: Vec3, direction_ws: Vec3, solid_angle: f32, } #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod, Default)] struct PathTraceFlags(u32); impl PathTraceFlags { const ACCUMULATE_ROUGHNESS: PathTraceFlags = PathTraceFlags(0x1); const ALLOW_LIGHT_SAMPLING: PathTraceFlags = PathTraceFlags(0x2); const ALLOW_BSDF_SAMPLING: PathTraceFlags = PathTraceFlags(0x4); const SPHERE_LIGHTS_SAMPLE_SOLID_ANGLE: PathTraceFlags = PathTraceFlags(0x8); const PLANAR_LIGHTS_ARE_TWO_SIDED: PathTraceFlags = PathTraceFlags(0x10); const CHECK_HIT_FACE: PathTraceFlags = PathTraceFlags(0x20); } impl BitOr for PathTraceFlags { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl BitOrAssign for PathTraceFlags { fn bitor_assign(&mut self, rhs: Self) { self.0 |= rhs.0; } } #[repr(u32)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Contiguous, EnumString, EnumVariantNames)] #[strum(serialize_all = "kebab_case")] pub enum MultipleImportanceHeuristic { None, Balance, Power2, } #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod)] struct CameraParams { world_from_local: Transform3, fov_size_at_unit_z: Vec2, aperture_radius_ls: f32, focus_distance_ls: f32, pixel_size_at_unit_z: f32, } #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod)] struct PathTraceUniforms { light_info_table_address: u64, light_alias_table_address: u64, light_params_base_address: u64, sampled_light_count: u32, external_light_begin: u32, external_light_end: u32, camera: CameraParams, sample_index: u32, max_segment_count: u32, mis_heuristic: u32, sequence_type: u32, wavelength_sampling_method: u32, flags: PathTraceFlags, } #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod)] struct LightAliasEntry { split: f32, indices: u32, } descriptor_set!(PathTraceDescriptorSet { path_trace_uniforms: UniformData<PathTraceUniforms>, accel: AccelerationStructure, pmj_samples: StorageImage, sobol_samples: StorageImage, illuminants: CombinedImageSampler, conductors: CombinedImageSampler, smits_table: CombinedImageSampler, wavelength_inv_cdf: CombinedImageSampler, wavelength_pdf: CombinedImageSampler, xyz_matching: CombinedImageSampler, result: [StorageImage; 3], linear_sampler: Sampler, }); #[derive(Clone, Copy, Default)] struct ShaderData { reflectance_texture_id: Option<BindlessId>, } #[derive(Clone, Copy, Default)] struct GeometryAttribRequirements { normal_buffer: bool, uv_buffer: bool, alias_table: bool, } #[derive(Clone, Copy, Default)] struct GeometryAttribData { normal_buffer: Option<vk::Buffer>, uv_buffer: Option<vk::Buffer>, alias_table: Option<vk::Buffer>, } #[derive(Clone, Copy)] enum GeometryRecordData { Triangles { index_buffer_address: u64, position_buffer_address: u64, normal_buffer_address: u64, uv_buffer_address: u64, alias_table_address: u64, }, Procedural, } #[derive(Debug, Clone, Copy, PartialEq, Eq, EnumString, EnumVariantNames)] #[strum(serialize_all = "kebab_case")] pub enum SamplingTechnique { LightsOnly, SurfacesOnly, LightsAndSurfaces, } #[repr(u32)] #[derive(Clone, Copy, PartialEq, Eq, Contiguous)] enum BsdfType { None, Diffuse, Mirror, SmoothDielectric, RoughDielectric, SmoothPlastic, RoughPlastic, RoughConductor, } const MIN_ROUGHNESS: f32 = 0.03; trait IntoExtendShader { fn bsdf_type(&self) -> BsdfType; fn material_index(&self) -> u32; fn roughness(&self) -> f32; } impl IntoExtendShader for Surface { fn bsdf_type(&self) -> BsdfType { match self { Surface::None => BsdfType::None, Surface::Diffuse => BsdfType::Diffuse, Surface::Mirror => BsdfType::Mirror, Surface::SmoothDielectric => BsdfType::SmoothDielectric, Surface::RoughDielectric { .. } => BsdfType::RoughDielectric, Surface::SmoothPlastic => BsdfType::SmoothPlastic, Surface::RoughPlastic { .. } => BsdfType::RoughPlastic, Surface::RoughConductor { .. } => BsdfType::RoughConductor, } } fn material_index(&self) -> u32 { match self { Surface::None | Surface::Diffuse | Surface::Mirror | Surface::SmoothDielectric | Surface::SmoothPlastic | Surface::RoughDielectric { .. } | Surface::RoughPlastic { .. } => 0, Surface::RoughConductor { conductor, .. } => conductor.into_integer(), } } fn roughness(&self) -> f32 { match self { Surface::None | Surface::Diffuse => 1.0, Surface::Mirror | Surface::SmoothDielectric | Surface::SmoothPlastic => 0.0, Surface::RoughDielectric { roughness } | Surface::RoughPlastic { roughness } | Surface::RoughConductor { roughness, .. } => roughness.max(MIN_ROUGHNESS), } } } #[repr(transparent)] #[derive(Clone, Copy, Zeroable, Pod, Default)] struct ExtendShaderFlags(u32); impl ExtendShaderFlags { const HAS_NORMALS: ExtendShaderFlags = ExtendShaderFlags(0x0100_0000); const HAS_TEXTURE: ExtendShaderFlags = ExtendShaderFlags(0x0200_0000); const IS_EMISSIVE: ExtendShaderFlags = ExtendShaderFlags(0x0400_0000); const IS_CHECKERBOARD: ExtendShaderFlags = ExtendShaderFlags(0x0800_0000); fn new(bsdf_type: BsdfType, material_index: u32, texture_id: Option<BindlessId>) -> Self { let mut flags = Self((material_index << 20) | (bsdf_type.into_integer() << 16)); if let Some(texture_id) = texture_id { flags |= Self(texture_id.index as u32) | Self::HAS_TEXTURE; } flags } } impl BitOr for ExtendShaderFlags { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl BitOrAssign for ExtendShaderFlags { fn bitor_assign(&mut self, rhs: Self) { self.0 |= rhs.0; } } #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod, Default)] struct ExtendShader { flags: ExtendShaderFlags, reflectance: Vec3, roughness: f32, light_index: u32, } impl ExtendShader { fn new(reflectance: &Reflectance, surface: &Surface, texture_id: Option<BindlessId>) -> Self { let mut flags = ExtendShaderFlags::new(surface.bsdf_type(), surface.material_index(), texture_id); let reflectance = match reflectance { Reflectance::Checkerboard(c) => { flags |= ExtendShaderFlags::IS_CHECKERBOARD; *c } Reflectance::Constant(c) => *c, Reflectance::Texture(_) => Vec3::zero(), } .clamped(Vec3::zero(), Vec3::one()); Self { flags, reflectance, roughness: surface.roughness(), light_index: 0, } } } #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod)] struct ExtendTriangleHitRecord { index_buffer_address: u64, position_buffer_address: u64, normal_buffer_address: u64, uv_buffer_address: u64, unit_scale: f32, shader: ExtendShader, _pad: u32, } #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod)] struct ProceduralHitRecordHeader { unit_scale: f32, shader: ExtendShader, } #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod)] struct IntersectDiscRecord { header: ProceduralHitRecordHeader, centre: Vec3, normal: Vec3, radius: f32, } #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod)] struct IntersectSphereRecord { header: ProceduralHitRecordHeader, centre: Vec3, radius: f32, } #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod)] struct IntersectMandelbulbRecord { header: ProceduralHitRecordHeader, centre: Vec3, // TODO: local transform } #[repr(usize)] #[derive(Clone, Copy, Contiguous)] enum ShaderGroup { RayGenerator, ExtendMiss, ExtendHitTriangle, ExtendHitDisc, ExtendHitSphere, ExtendHitMandelbulb, OcclusionMiss, OcclusionHitTriangle, OcclusionHitDisc, OcclusionHitSphere, OcclusionHitMandelbulb, } #[derive(Clone, Copy)] struct ShaderBindingRegion { offset: u32, stride: u32, size: u32, } impl ShaderBindingRegion { fn new( rtpp: &vk::PhysicalDeviceRayTracingPipelinePropertiesKHR, next_offset: u32, record_size: u32, entry_count: u32, ) -> (Self, u32) { let align_up = |n: u32, a: u32| (n + a - 1) & !(a - 1); let offset = align_up(next_offset, rtpp.shader_group_base_alignment); let stride = align_up( rtpp.shader_group_handle_size + record_size, rtpp.shader_group_handle_alignment, ); let size = stride * entry_count; (Self { offset, stride, size }, offset + size) } fn into_device_address_region(self, base_device_address: vk::DeviceAddress) -> vk::StridedDeviceAddressRegionKHR { vk::StridedDeviceAddressRegionKHR { device_address: base_device_address + self.offset as vk::DeviceSize, stride: self.stride as vk::DeviceSize, size: self.size as vk::DeviceSize, } } } struct ShaderBindingData { raygen_region: ShaderBindingRegion, miss_region: ShaderBindingRegion, hit_region: ShaderBindingRegion, shader_binding_table: vk::Buffer, light_info_table: vk::Buffer, sampled_light_count: u32, external_light_begin: u32, external_light_end: u32, } #[repr(u32)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Contiguous, EnumString, EnumVariantNames)] #[strum(serialize_all = "kebab_case")] pub enum ToneMapMethod { None, FilmicSrgb, AcesFit, } #[repr(u32)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Contiguous, EnumString, EnumVariantNames)] #[strum(serialize_all = "kebab_case")] pub enum FilterType { Box, Gaussian, Mitchell, } pub fn try_bool_from_str(s: &str) -> Result<bool, String> { match s { "enable" => Ok(true), "disable" => Ok(false), _ => Err(format!("{:?} is not one of enable/disable.", s)), } } type BoolParam = bool; #[repr(u32)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Contiguous, EnumString, EnumVariantNames)] #[strum(serialize_all = "kebab_case")] pub enum WavelengthSamplingMethod { Uniform, HeroMIS, ContinuousMIS, } #[derive(Debug, StructOpt)] pub struct RendererParams { /// Image width #[structopt(short, long, default_value = "1920", global = true, display_order = 1)] pub width: u32, /// Image height #[structopt(short, long, default_value = "1080", global = true, display_order = 2)] pub height: u32, /// Maximum number eye path bounces #[structopt(short = "b", long, default_value = "8", global = true)] pub max_bounces: u32, /// Roughness accumulates along eye paths #[structopt(long, parse(try_from_str=try_bool_from_str), default_value="enable", global=true)] pub accumulate_roughness: BoolParam, /// Sample sphere lights by solid angle from the target point #[structopt(long, parse(try_from_str=try_bool_from_str), default_value="enable", global=true)] pub sphere_lights_sample_solid_angle: BoolParam, /// Quad and disc lights emit light from both sides #[structopt(long, parse(try_from_str=try_bool_from_str), default_value="disable", global=true)] pub planar_lights_are_two_sided: BoolParam, /// Override all materials to be diffuse with white front faces and red back faces #[structopt(long, parse(try_from_str=try_bool_from_str), default_value="disable", global=true)] pub check_hit_face: BoolParam, /// Which sampling techniques are allowed #[structopt(long, possible_values=SamplingTechnique::VARIANTS, default_value = "lights-and-surfaces", global=true)] pub sampling_technique: SamplingTechnique, /// How to combine samples between techniques #[structopt(short, long, possible_values=MultipleImportanceHeuristic::VARIANTS, default_value = "balance", global=true)] pub mis_heuristic: MultipleImportanceHeuristic, /// Image reconstruction filter #[structopt(short, long, possible_values=FilterType::VARIANTS, default_value = "gaussian", global=true)] pub filter_type: FilterType, /// Tone mapping method #[structopt(short, long, possible_values=ToneMapMethod::VARIANTS, default_value = "aces-fit", global=true)] pub tone_map_method: ToneMapMethod, /// Exposure bias #[structopt( name = "exposure-bias", short, long, allow_hyphen_values = true, default_value = "0", global = true )] pub log2_exposure_scale: f32, /// Override the camera vertical field of view #[structopt(name = "fov", long, global = true)] pub fov_y_override: Option<f32>, #[structopt(name = "sample-count-log2", short, long, default_value = "8", global = true)] pub log2_sample_count: u32, #[structopt(long, default_value = "sobol", global = true)] pub sequence_type: SequenceType, #[structopt(long, global = true)] pub d65_observer: bool, #[structopt(long, possible_values=WavelengthSamplingMethod::VARIANTS, default_value = "continuous-mis", global = true)] pub wavelength_sampling_method: WavelengthSamplingMethod, } impl RendererParams { pub fn size(&self) -> UVec2 { UVec2::new(self.width, self.height) } pub fn sample_count(&self) -> u32 { 1 << self.log2_sample_count } pub fn observer_illuminant(&self) -> Illuminant { if self.d65_observer { Illuminant::D65 } else { Illuminant::E } } pub fn observer_white_point(&self) -> WhitePoint { self.observer_illuminant().white_point() } } #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod)] struct FilterData { image_size: UVec2, sequence_type: u32, sample_index: u32, filter_type: u32, } descriptor_set!(FilterDescriptorSet { data: UniformData<FilterData>, pmj_samples: StorageImage, sobol_samples: StorageImage, input: [StorageImage; 3], result: StorageImage, }); pub struct RenderProgress { next_sample_index: u32, } impl RenderProgress { pub fn new() -> Self { Self { next_sample_index: 0 } } pub fn reset(&mut self) { self.next_sample_index = 0; } pub fn fraction(&self, params: &RendererParams) -> f32 { (self.next_sample_index as f32) / (params.sample_count() as f32) } pub fn done(&self, params: &RendererParams) -> bool { self.next_sample_index >= params.sample_count() } } struct AliasTable { under: Vec<(u32, f32)>, over: Vec<(u32, f32)>, } impl AliasTable { pub fn new() -> Self { Self { under: Vec::new(), over: Vec::new(), } } pub fn push(&mut self, u: f32) { let i = (self.under.len() + self.over.len()) as u32; if u < 1.0 { self.under.push((i, u)); } else { self.over.push((i, u)); } } pub fn into_iter(self) -> AliasTableIterator { AliasTableIterator { table: self } } } struct AliasTableIterator { table: AliasTable, } impl Iterator for AliasTableIterator { type Item = (f32, u32, u32); fn next(&mut self) -> Option<Self::Item> { if let Some((small_i, small_u)) = self.table.under.pop() { if let Some((big_i, big_u)) = self.table.over.pop() { let remain_u = big_u - (1.0 - small_u); if remain_u < 1.0 { self.table.under.push((big_i, remain_u)); } else { self.table.over.push((big_i, remain_u)); } Some((small_u, small_i, big_i)) } else { println!("no alias found for {} (entry {})", small_u, small_i); Some((1.0, small_i, small_i)) } } else if let Some((big_i, big_u)) = self.table.over.pop() { if big_u > 1.0 { println!("no alias found for {} (entry {})", big_u, big_i); } Some((1.0, big_i, big_i)) } else { None } } } pub struct Renderer { context: SharedContext, accel: SceneAccel, path_trace_pipeline_layout: vk::PipelineLayout, path_trace_pipeline: vk::Pipeline, clamp_point_sampler: vk::Sampler, clamp_linear_sampler: vk::Sampler, linear_sampler: vk::Sampler, shader_binding_data: ShaderBindingData, pmj_samples_image_view: vk::ImageView, sobol_samples_image_view: vk::ImageView, smits_table_image_view: vk::ImageView, illuminants_image_view: vk::ImageView, conductors_image_view: vk::ImageView, wavelength_inv_cdf_image_view: vk::ImageView, wavelength_pdf_image_view: vk::ImageView, xyz_matching_image_view: vk::ImageView, result_image_id: ImageId, pub params: RendererParams, } fn image_load_from_reader<R>(reader: &mut R) -> (stb::image::Info, Vec<u8>) where R: io::Read + io::Seek, { let (info, data) = stb::image::stbi_load_from_reader(reader, stb::image::Channels::RgbAlpha).unwrap(); (info, data.into_vec()) } async fn image_load(resource_loader: ResourceLoader, filename: &Path) -> BindlessId { let mut reader = File::open(filename).unwrap(); let (info, data) = image_load_from_reader(&mut reader); let can_bc_compress = (info.width % 4) == 0 && (info.height % 4) == 0; let size_in_pixels = UVec2::new(info.width as u32, info.height as u32); println!( "loaded {:?}: {}x{} ({})", filename.file_name().unwrap(), size_in_pixels.x, size_in_pixels.y, if can_bc_compress { "bc1" } else { "rgba" } ); let image_id = if can_bc_compress { // compress on write let image_desc = ImageDesc::new_2d( size_in_pixels, vk::Format::BC1_RGB_SRGB_BLOCK, vk::ImageAspectFlags::COLOR, ); let mut writer = resource_loader .image_writer(&image_desc, ImageUsage::RAY_TRACING_SAMPLED) .await; let size_in_blocks = size_in_pixels / 4; let mut tmp_rgba = [0xffu8; 16 * 4]; let mut dst_bc1 = [0u8; 8]; for block_y in 0..size_in_blocks.y { for block_x in 0..size_in_blocks.x { for pixel_y in 0..4 { let tmp_offset = (pixel_y * 4 * 4) as usize; let tmp_row = &mut tmp_rgba[tmp_offset..(tmp_offset + 16)]; let src_offset = (((block_y * 4 + pixel_y) * size_in_pixels.x + block_x * 4) * 4) as usize; let src_row = &data.as_slice()[src_offset..(src_offset + 16)]; for pixel_x in 0..4 { for component in 0..3 { let row_offset = (4 * pixel_x + component) as usize; unsafe { *tmp_row.get_unchecked_mut(row_offset) = *src_row.get_unchecked(row_offset) }; } } } stb::dxt::stb_compress_dxt_block(&mut dst_bc1, &tmp_rgba, 0, stb::dxt::CompressionMode::Normal); writer.write(&dst_bc1); } } writer.finish().await } else { // load uncompressed let image_desc = ImageDesc::new_2d(size_in_pixels, vk::Format::R8G8B8A8_SRGB, vk::ImageAspectFlags::COLOR); let mut writer = resource_loader .image_writer(&image_desc, ImageUsage::RAY_TRACING_SAMPLED) .await; writer.write(data.as_slice()); writer.finish().await }; resource_loader.get_image_bindless_id(image_id) } impl Renderer { const PMJ_SEQUENCE_COUNT: u32 = 1024; const LOG2_MAX_SAMPLES_PER_SEQUENCE: u32 = if cfg!(debug_assertions) { 10 } else { 12 }; const MAX_SAMPLES_PER_SEQUENCE: u32 = 1 << Self::LOG2_MAX_SAMPLES_PER_SEQUENCE; const HIT_ENTRY_COUNT_PER_INSTANCE: u32 = 2; const MISS_ENTRY_COUNT: u32 = 2; #[allow(clippy::too_many_arguments)] pub async fn new(resource_loader: ResourceLoader, scene: SharedScene, mut params: RendererParams) -> Self { let context = resource_loader.context(); let accel = SceneAccel::new( resource_loader.clone(), Arc::clone(&scene), Self::HIT_ENTRY_COUNT_PER_INSTANCE, ) .await; // sanitise parameters params.log2_sample_count = params.log2_sample_count.min(Self::LOG2_MAX_SAMPLES_PER_SEQUENCE); // load textures and attributes for all meshes let mut geometry_attrib_req = vec![GeometryAttribRequirements::default(); scene.geometries.len()]; let mut shader_needs_texture = vec![false; scene.materials.len()]; for instance_ref in accel.clusters().instance_iter().copied() { let instance = scene.instance(instance_ref); let material_ref = instance.material_ref; let geometry_ref = instance.geometry_ref; let material = scene.material(material_ref); let geometry = scene.geometry(geometry_ref); let has_normals = matches!(geometry, Geometry::TriangleMesh { normals: Some(_), .. }); let has_uvs_and_texture = matches!(geometry, Geometry::TriangleMesh { uvs: Some(_), .. }) && matches!(material.reflectance, Reflectance::Texture(_)); let has_emissive_triangles = matches!(geometry, Geometry::TriangleMesh { .. }) && material.emission.is_some(); let req = &mut geometry_attrib_req[geometry_ref.0 as usize]; req.normal_buffer |= has_normals; req.uv_buffer |= has_uvs_and_texture; req.alias_table |= has_emissive_triangles; shader_needs_texture[material_ref.0 as usize] |= has_uvs_and_texture; } let mut geometry_attrib_tasks = Vec::new(); for geometry_ref in scene.geometry_ref_iter() { geometry_attrib_tasks.push({ let loader = resource_loader.clone(); let scene = Arc::clone(&scene); let req = geometry_attrib_req[geometry_ref.0 as usize]; spawn(async move { let normal_buffer = if req.normal_buffer { let normals = match scene.geometry(geometry_ref) { Geometry::TriangleMesh { normals: Some(normals), .. } => normals.as_slice(), _ => unreachable!(), }; let buffer_desc = BufferDesc::new(normals.len() * mem::size_of::<Vec3>()); let mut writer = loader .buffer_writer(&buffer_desc, BufferUsage::RAY_TRACING_STORAGE_READ) .await; for n in normals.iter() { writer.write(n); } let normal_buffer_id = writer.finish(); Some(loader.get_buffer(normal_buffer_id.await)) } else { None }; let uv_buffer = if req.uv_buffer { let uvs = match scene.geometry(geometry_ref) { Geometry::TriangleMesh { uvs: Some(uvs), .. } => uvs.as_slice(), _ => unreachable!(), }; let buffer_desc = BufferDesc::new(uvs.len() * mem::size_of::<Vec2>()); let mut writer = loader .buffer_writer(&buffer_desc, BufferUsage::RAY_TRACING_STORAGE_READ) .await; for uv in uvs.iter() { writer.write(uv); } let uv_buffer_id = writer.finish(); Some(loader.get_buffer(uv_buffer_id.await)) } else { None }; let alias_table = if req.alias_table { let (positions, indices, total_area) = match scene.geometry(geometry_ref) { Geometry::TriangleMesh { positions, indices, area, .. } => (positions, indices, area), _ => unreachable!(), }; let triangle_count = indices.len(); let mut alias_table_tmp = AliasTable::new(); for tri in indices.iter() { let p0 = positions[tri.x as usize]; let p1 = positions[tri.y as usize]; let p2 = positions[tri.z as usize]; let area = 0.5 * (p2 - p1).cross(p0 - p1).mag(); let p = area / total_area; alias_table_tmp.push(p * (triangle_count as f32)); } let alias_table_desc = BufferDesc::new(triangle_count * mem::size_of::<LightAliasEntry>()); let mut writer = loader .buffer_writer(&alias_table_desc, BufferUsage::RAY_TRACING_STORAGE_READ) .await; for (u, i, j) in alias_table_tmp.into_iter() { let entry = LightAliasEntry { split: u, indices: (j << 16) | i, }; writer.write(&entry); } let alias_table_id = writer.finish(); Some(loader.get_buffer(alias_table_id.await)) } else { None }; GeometryAttribData { normal_buffer, uv_buffer, alias_table, } }) }); } let mut task_index_paths = HashMap::<PathBuf, usize>::new(); let mut shader_data_task_index = Vec::new(); let mut texture_bindless_index_tasks = Vec::new(); for material_ref in scene.material_ref_iter() { let task_index = if shader_needs_texture[material_ref.0 as usize] { let material = scene.material(material_ref); let filename = match &material.reflectance { Reflectance::Texture(filename) => filename, _ => unreachable!(), }; Some(*task_index_paths.entry(filename.clone()).or_insert_with(|| { let task_index = texture_bindless_index_tasks.len(); texture_bindless_index_tasks.push(spawn({ let loader = resource_loader.clone(); let filename = filename.clone(); async move { image_load(loader, &filename).await } })); task_index })) } else { None }; shader_data_task_index.push(task_index); } let mut geometry_attrib_data = Vec::new(); for task in geometry_attrib_tasks.iter_mut() { geometry_attrib_data.push(task.await); } let mut texture_bindless_index = Vec::new(); for task in texture_bindless_index_tasks.iter_mut() { texture_bindless_index.push(task.await); } let shader_data: Vec<_> = shader_data_task_index .iter() .map(|task_index| ShaderData { reflectance_texture_id: task_index.map(|task_index| texture_bindless_index[task_index]), }) .collect(); let clamp_point_sampler = { let create_info = vk::SamplerCreateInfo { mag_filter: vk::Filter::NEAREST, min_filter: vk::Filter::NEAREST, address_mode_u: vk::SamplerAddressMode::CLAMP_TO_EDGE, address_mode_v: vk::SamplerAddressMode::CLAMP_TO_EDGE, ..Default::default() }; unsafe { context.device.create_sampler(&create_info, None) }.unwrap() }; let clamp_linear_sampler = { let create_info = vk::SamplerCreateInfo { mag_filter: vk::Filter::LINEAR, min_filter: vk::Filter::LINEAR, address_mode_u: vk::SamplerAddressMode::CLAMP_TO_EDGE, address_mode_v: vk::SamplerAddressMode::CLAMP_TO_EDGE, ..Default::default() }; unsafe { context.device.create_sampler(&create_info, None) }.unwrap() }; let linear_sampler = { let create_info = vk::SamplerCreateInfo { mag_filter: vk::Filter::LINEAR, min_filter: vk::Filter::LINEAR, ..Default::default() }; unsafe { context.device.create_sampler(&create_info, None) }.unwrap() };
rust
MIT
42fc4b496cce21e907eca7112e6d6334d35fc41a
2026-01-04T20:23:56.526296Z
true
sjb3d/caldera
https://github.com/sjb3d/caldera/blob/42fc4b496cce21e907eca7112e6d6334d35fc41a/caldera/examples/path_tracer/scene.rs
caldera/examples/path_tracer/scene.rs
use crate::prelude::*; use bytemuck::Contiguous; use caldera::prelude::*; use ply_rs::{parser, ply}; use std::{ fs::File, io::BufReader, path::{Path, PathBuf}, sync::Arc, }; use strum::{EnumString, EnumVariantNames}; #[derive(Debug, Default)] pub struct Transform { pub world_from_local: Similarity3, } impl Transform { pub fn new(world_from_local: Similarity3) -> Self { Self { world_from_local } } } #[derive(Debug)] pub enum Geometry { TriangleMesh { positions: Vec<Vec3>, normals: Option<Vec<Vec3>>, uvs: Option<Vec<Vec2>>, indices: Vec<UVec3>, min: Vec3, max: Vec3, area: f32, }, Quad { local_from_quad: Similarity3, size: Vec2, }, Disc { local_from_disc: Similarity3, radius: f32, }, Sphere { centre: Vec3, radius: f32, }, #[allow(dead_code)] Mandelbulb { local_from_bulb: Similarity3, }, } pub const MANDELBULB_RADIUS: f32 = 1.1; #[derive(Debug)] pub enum Reflectance { Checkerboard(Vec3), // HACK! TODO: proper shaders Constant(Vec3), Texture(PathBuf), } #[derive(Debug, Clone, Copy, Contiguous, Eq, PartialEq)] #[repr(u32)] pub enum Conductor { Aluminium, AluminiumAntimonide, Chromium, Copper, Iron, Lithium, Gold, Silver, TitaniumNitride, Tungsten, Vanadium, VanadiumNitride, Custom, // eta=2, k=0, TODO: proper custom spectra } #[derive(Debug, Clone, Copy)] pub enum Surface { None, Diffuse, Mirror, SmoothDielectric, RoughDielectric { roughness: f32 }, SmoothPlastic, RoughPlastic { roughness: f32 }, RoughConductor { conductor: Conductor, roughness: f32 }, } #[repr(u32)] #[derive(Debug, Clone, Copy, Contiguous, Eq, PartialEq, EnumString, EnumVariantNames)] #[strum(serialize_all = "kebab_case")] pub enum Illuminant { E, CornellBox, D65, F10, } impl Illuminant { pub fn white_point(&self) -> WhitePoint { match self { Self::E => WhitePoint::E, Self::CornellBox => unimplemented!(), Self::D65 => WhitePoint::D65, Self::F10 => unimplemented!(), } } } #[derive(Debug, Clone, Copy)] pub struct Emission { pub illuminant: Illuminant, pub intensity: Vec3, } impl Emission { pub fn new_uniform(intensity: Vec3) -> Self { Self { illuminant: Illuminant::E, intensity, } } } /* Eventually this would be some kind of graph/script that we can runtime compile to a GLSL callable shader. The graph would read interpolated data from the geometry (e.g. texture coordinates) and uniform data from the instance (e.g. textures, constants) and produces a closure for the BRDF (and emitter if present). For now we just enumerate some fixed options for the result of this shader: * Reflectance is a constant colour or a texture read * Pick from a fixed set of surface models (some also have a roughness parameter. * Geometry can optionally emit a fixed colour (quads/spheres only for now). */ #[derive(Debug)] pub struct Material { pub reflectance: Reflectance, pub surface: Surface, pub emission: Option<Emission>, } #[derive(Debug)] pub struct Instance { pub transform_ref: TransformRef, pub geometry_ref: GeometryRef, pub material_ref: MaterialRef, } #[derive(Debug)] pub enum Light { Dome { emission: Emission, }, SolidAngle { emission: Emission, direction_ws: Vec3, solid_angle: f32, }, } #[derive(Debug, Clone, Copy)] pub enum Camera { Pinhole { world_from_camera: Similarity3, fov_y: f32, }, ThinLens { world_from_camera: Similarity3, fov_y: f32, aperture_radius: f32, focus_distance: f32, }, } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct TransformRef(pub u32); #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct GeometryRef(pub u32); #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct MaterialRef(pub u32); #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct InstanceRef(pub u32); #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct LightRef(pub u32); #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct CameraRef(pub u32); impl Instance { pub fn new(transform_ref: TransformRef, geometry_ref: GeometryRef, material_ref: MaterialRef) -> Self { Self { transform_ref, geometry_ref, material_ref, } } } pub type SharedScene = Arc<Scene>; #[derive(Debug, Default)] pub struct Scene { pub transforms: Vec<Transform>, pub geometries: Vec<Geometry>, pub materials: Vec<Material>, pub instances: Vec<Instance>, pub lights: Vec<Light>, pub cameras: Vec<Camera>, } impl Scene { pub fn add_transform(&mut self, transform: Transform) -> TransformRef { let index = self.transforms.len(); self.transforms.push(transform); TransformRef(index as u32) } pub fn add_geometry(&mut self, geometry: Geometry) -> GeometryRef { let index = self.geometries.len(); self.geometries.push(geometry); GeometryRef(index as u32) } pub fn add_material(&mut self, material: Material) -> MaterialRef { let index = self.materials.len(); self.materials.push(material); MaterialRef(index as u32) } pub fn add_instance(&mut self, instance: Instance) -> InstanceRef { let index = self.instances.len(); self.instances.push(instance); InstanceRef(index as u32) } pub fn add_light(&mut self, light: Light) -> LightRef { let index = self.lights.len(); self.lights.push(light); LightRef(index as u32) } pub fn add_camera(&mut self, camera: Camera) -> CameraRef { let index = self.cameras.len(); self.cameras.push(camera); CameraRef(index as u32) } pub fn geometry_ref_iter(&self) -> impl Iterator<Item = GeometryRef> { (0..self.geometries.len()).map(|i| GeometryRef(i as u32)) } pub fn material_ref_iter(&self) -> impl Iterator<Item = MaterialRef> { (0..self.materials.len()).map(|i| MaterialRef(i as u32)) } pub fn instance_ref_iter(&self) -> impl Iterator<Item = InstanceRef> { (0..self.instances.len()).map(|i| InstanceRef(i as u32)) } pub fn camera_ref_iter(&self) -> impl Iterator<Item = CameraRef> { (0..self.cameras.len()).map(|i| CameraRef(i as u32)) } pub fn transform(&self, r: TransformRef) -> &Transform { self.transforms.get(r.0 as usize).unwrap() } pub fn geometry(&self, r: GeometryRef) -> &Geometry { self.geometries.get(r.0 as usize).unwrap() } pub fn material(&self, r: MaterialRef) -> &Material { self.materials.get(r.0 as usize).unwrap() } pub fn instance(&self, r: InstanceRef) -> &Instance { self.instances.get(r.0 as usize).unwrap() } pub fn camera(&self, r: CameraRef) -> &Camera { self.cameras.get(r.0 as usize).unwrap() } pub fn bake_unique_geometry(&mut self) { let mut instance_counts = vec![0u32; self.geometries.len()]; for instance in self.instances.iter() { instance_counts[instance.geometry_ref.0 as usize] += 1; } let identity_ref = self.add_transform(Transform::default()); for instance in self.instances.iter_mut() { if instance_counts[instance.geometry_ref.0 as usize] == 1 { let world_from_local = self .transforms .get(instance.transform_ref.0 as usize) .unwrap() .world_from_local; match self.geometries.get_mut(instance.geometry_ref.0 as usize).unwrap() { Geometry::TriangleMesh { positions, normals, .. } => { for pos in positions.iter_mut() { *pos = world_from_local * *pos; } if let Some(normals) = normals { for normal in normals.iter_mut() { *normal = world_from_local.transform_vec3(*normal).normalized(); } } } Geometry::Quad { local_from_quad, .. } => { *local_from_quad = world_from_local * *local_from_quad; } Geometry::Disc { local_from_disc, .. } => { *local_from_disc = world_from_local * *local_from_disc; } Geometry::Sphere { centre, radius } => { *centre = world_from_local * *centre; *radius *= world_from_local.scale.abs(); } Geometry::Mandelbulb { local_from_bulb } => { *local_from_bulb = world_from_local * *local_from_bulb; } } instance.transform_ref = identity_ref; } } } } pub struct TriangleMeshBuilder { pub positions: Vec<Vec3>, pub normals: Vec<Vec3>, pub uvs: Vec<Vec2>, pub indices: Vec<UVec3>, pub area: f32, } impl TriangleMeshBuilder { pub fn new() -> Self { Self { positions: Vec::new(), normals: Vec::new(), uvs: Vec::new(), indices: Vec::new(), area: 0.0, } } pub fn with_quad(mut self, v0: Vec3, v1: Vec3, v2: Vec3, v3: Vec3) -> Self { let base = UVec3::broadcast(self.positions.len() as u32); let normal_vec0 = (v2 - v1).cross(v0 - v1); let normal_vec1 = (v0 - v3).cross(v2 - v3); let normal = (normal_vec0 + normal_vec1).normalized(); self.positions.push(v0); self.positions.push(v1); self.positions.push(v2); self.positions.push(v3); self.normals.push(normal); self.normals.push(normal); self.normals.push(normal); self.normals.push(normal); self.uvs.push(Vec2::new(0.0, 0.0)); self.uvs.push(Vec2::new(1.0, 0.0)); self.uvs.push(Vec2::new(1.0, 1.0)); self.uvs.push(Vec2::new(0.0, 1.0)); self.indices.push(base + UVec3::new(0, 1, 2)); self.indices.push(base + UVec3::new(2, 3, 0)); self.area += 0.5 * (normal_vec0.mag() + normal_vec1.mag()); self } pub fn build(self) -> Geometry { let mut min = Vec3::broadcast(f32::INFINITY); let mut max = Vec3::broadcast(-f32::INFINITY); for pos in self.positions.iter() { min = min.min_by_component(*pos); max = max.max_by_component(*pos); } Geometry::TriangleMesh { positions: self.positions, normals: Some(self.normals), uvs: Some(self.uvs), indices: self.indices, min, max, area: self.area, } } } macro_rules! spectrum_samples { ($(($w:literal, $v:literal)),+) => { [ $( ($w, $v), )+ ] } } // reference: https://www.graphics.cornell.edu/online/box/data.html #[rustfmt::skip] const CORNELL_BOX_WHITE_SAMPLES: &[(f32, f32)] = &spectrum_samples!( (400.0, 0.343),(404.0, 0.445),(408.0, 0.551),(412.0, 0.624),(416.0, 0.665), (420.0, 0.687),(424.0, 0.708),(428.0, 0.723),(432.0, 0.715),(436.0, 0.710), (440.0, 0.745),(444.0, 0.758),(448.0, 0.739),(452.0, 0.767),(456.0, 0.777), (460.0, 0.765),(464.0, 0.751),(468.0, 0.745),(472.0, 0.748),(476.0, 0.729), (480.0, 0.745),(484.0, 0.757),(488.0, 0.753),(492.0, 0.750),(496.0, 0.746), (500.0, 0.747),(504.0, 0.735),(508.0, 0.732),(512.0, 0.739),(516.0, 0.734), (520.0, 0.725),(524.0, 0.721),(528.0, 0.733),(532.0, 0.725),(536.0, 0.732), (540.0, 0.743),(544.0, 0.744),(548.0, 0.748),(552.0, 0.728),(556.0, 0.716), (560.0, 0.733),(564.0, 0.726),(568.0, 0.713),(572.0, 0.740),(576.0, 0.754), (580.0, 0.764),(584.0, 0.752),(588.0, 0.736),(592.0, 0.734),(596.0, 0.741), (600.0, 0.740),(604.0, 0.732),(608.0, 0.745),(612.0, 0.755),(616.0, 0.751), (620.0, 0.744),(624.0, 0.731),(628.0, 0.733),(632.0, 0.744),(636.0, 0.731), (640.0, 0.712),(644.0, 0.708),(648.0, 0.729),(652.0, 0.730),(656.0, 0.727), (660.0, 0.707),(664.0, 0.703),(668.0, 0.729),(672.0, 0.750),(676.0, 0.760), (680.0, 0.751),(684.0, 0.739),(688.0, 0.724),(692.0, 0.730),(696.0, 0.740), (700.0, 0.737) ); #[rustfmt::skip] const CORNELL_BOX_GREEN_SAMPLES: &[(f32, f32)] = &spectrum_samples!( (400.0, 0.092),(404.0, 0.096),(408.0, 0.098),(412.0, 0.097),(416.0, 0.098), (420.0, 0.095),(424.0, 0.095),(428.0, 0.097),(432.0, 0.095),(436.0, 0.094), (440.0, 0.097),(444.0, 0.098),(448.0, 0.096),(452.0, 0.101),(456.0, 0.103), (460.0, 0.104),(464.0, 0.107),(468.0, 0.109),(472.0, 0.112),(476.0, 0.115), (480.0, 0.125),(484.0, 0.140),(488.0, 0.160),(492.0, 0.187),(496.0, 0.229), (500.0, 0.285),(504.0, 0.343),(508.0, 0.390),(512.0, 0.435),(516.0, 0.464), (520.0, 0.472),(524.0, 0.476),(528.0, 0.481),(532.0, 0.462),(536.0, 0.447), (540.0, 0.441),(544.0, 0.426),(548.0, 0.406),(552.0, 0.373),(556.0, 0.347), (560.0, 0.337),(564.0, 0.314),(568.0, 0.285),(572.0, 0.277),(576.0, 0.266), (580.0, 0.250),(584.0, 0.230),(588.0, 0.207),(592.0, 0.186),(596.0, 0.171), (600.0, 0.160),(604.0, 0.148),(608.0, 0.141),(612.0, 0.136),(616.0, 0.130), (620.0, 0.126),(624.0, 0.123),(628.0, 0.121),(632.0, 0.122),(636.0, 0.119), (640.0, 0.114),(644.0, 0.115),(648.0, 0.117),(652.0, 0.117),(656.0, 0.118), (660.0, 0.120),(664.0, 0.122),(668.0, 0.128),(672.0, 0.132),(676.0, 0.139), (680.0, 0.144),(684.0, 0.146),(688.0, 0.150),(692.0, 0.152),(696.0, 0.157), (700.0, 0.159) ); #[rustfmt::skip] const CORNELL_BOX_RED_SAMPLES: &[(f32, f32)] = &spectrum_samples!( (400.0, 0.040),(404.0, 0.046),(408.0, 0.048),(412.0, 0.053),(416.0, 0.049), (420.0, 0.050),(424.0, 0.053),(428.0, 0.055),(432.0, 0.057),(436.0, 0.056), (440.0, 0.059),(444.0, 0.057),(448.0, 0.061),(452.0, 0.061),(456.0, 0.060), (460.0, 0.062),(464.0, 0.062),(468.0, 0.062),(472.0, 0.061),(476.0, 0.062), (480.0, 0.060),(484.0, 0.059),(488.0, 0.057),(492.0, 0.058),(496.0, 0.058), (500.0, 0.058),(504.0, 0.056),(508.0, 0.055),(512.0, 0.056),(516.0, 0.059), (520.0, 0.057),(524.0, 0.055),(528.0, 0.059),(532.0, 0.059),(536.0, 0.058), (540.0, 0.059),(544.0, 0.061),(548.0, 0.061),(552.0, 0.063),(556.0, 0.063), (560.0, 0.067),(564.0, 0.068),(568.0, 0.072),(572.0, 0.080),(576.0, 0.090), (580.0, 0.099),(584.0, 0.124),(588.0, 0.154),(592.0, 0.192),(596.0, 0.255), (600.0, 0.287),(604.0, 0.349),(608.0, 0.402),(612.0, 0.443),(616.0, 0.487), (620.0, 0.513),(624.0, 0.558),(628.0, 0.584),(632.0, 0.620),(636.0, 0.606), (640.0, 0.609),(644.0, 0.651),(648.0, 0.612),(652.0, 0.610),(656.0, 0.650), (660.0, 0.638),(664.0, 0.627),(668.0, 0.620),(672.0, 0.630),(676.0, 0.628), (680.0, 0.642),(684.0, 0.639),(688.0, 0.657),(692.0, 0.639),(696.0, 0.635), (700.0, 0.642) ); #[rustfmt::skip] pub const CORNELL_BOX_ILLUMINANT: RegularlySampledIlluminant = RegularlySampledIlluminant { samples: &[0.0, 8.0, 15.6, 18.4, 0.0], sample_norm: 1.0, wavelength_base: 400.0, wavelength_step_size: 100.0, }; #[derive(Debug, EnumString, EnumVariantNames)] #[strum(serialize_all = "kebab_case")] pub enum CornellBoxVariant { Original, DomeLight, Conductor, } #[allow(clippy::excessive_precision)] pub fn create_cornell_box_scene(variant: &CornellBoxVariant) -> Scene { let mut scene = Scene::default(); let floor = scene.add_geometry( TriangleMeshBuilder::new() .with_quad( Vec3::new(0.5528, 0.0, 0.0), Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 0.5592), Vec3::new(0.5496, 0.0, 0.5592), ) .build(), ); let ceiling = scene.add_geometry( TriangleMeshBuilder::new() .with_quad( Vec3::new(0.556, 0.5488, 0.0), Vec3::new(0.556, 0.5488, 0.5592), Vec3::new(0.0, 0.5488, 0.5592), Vec3::new(0.0, 0.5488, 0.0), ) .build(), ); let grey_wall = scene.add_geometry( TriangleMeshBuilder::new() .with_quad( Vec3::new(0.5496, 0.0, 0.5592), Vec3::new(0.0, 0.0, 0.5592), Vec3::new(0.0, 0.5488, 0.5592), Vec3::new(0.556, 0.5488, 0.5592), ) .build(), ); let red_wall = scene.add_geometry( TriangleMeshBuilder::new() .with_quad( Vec3::new(0.5528, 0.0, 0.0), Vec3::new(0.5496, 0.0, 0.5592), Vec3::new(0.556, 0.5488, 0.5592), Vec3::new(0.556, 0.5488, 0.0), ) .build(), ); let green_wall = scene.add_geometry( TriangleMeshBuilder::new() .with_quad( Vec3::new(0.0, 0.0, 0.5592), Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.5488, 0.0), Vec3::new(0.0, 0.5488, 0.5592), ) .build(), ); let short_block = scene.add_geometry( TriangleMeshBuilder::new() .with_quad( Vec3::new(0.130, 0.165, 0.065), Vec3::new(0.082, 0.165, 0.225), Vec3::new(0.240, 0.165, 0.272), Vec3::new(0.290, 0.165, 0.114), ) .with_quad( Vec3::new(0.290, 0.0, 0.114), Vec3::new(0.290, 0.165, 0.114), Vec3::new(0.240, 0.165, 0.272), Vec3::new(0.240, 0.0, 0.272), ) .with_quad( Vec3::new(0.130, 0.0, 0.065), Vec3::new(0.130, 0.165, 0.065), Vec3::new(0.290, 0.165, 0.114), Vec3::new(0.290, 0.0, 0.114), ) .with_quad( Vec3::new(0.082, 0.0, 0.225), Vec3::new(0.082, 0.165, 0.225), Vec3::new(0.130, 0.165, 0.065), Vec3::new(0.130, 0.0, 0.065), ) .with_quad( Vec3::new(0.240, 0.0, 0.272), Vec3::new(0.240, 0.165, 0.272), Vec3::new(0.082, 0.165, 0.225), Vec3::new(0.082, 0.0, 0.225), ) .build(), ); let tall_block = scene.add_geometry( TriangleMeshBuilder::new() .with_quad( Vec3::new(0.423, 0.330, 0.247), Vec3::new(0.265, 0.330, 0.296), Vec3::new(0.314, 0.330, 0.456), Vec3::new(0.472, 0.330, 0.406), ) .with_quad( Vec3::new(0.423, 0.0, 0.247), Vec3::new(0.423, 0.330, 0.247), Vec3::new(0.472, 0.330, 0.406), Vec3::new(0.472, 0.0, 0.406), ) .with_quad( Vec3::new(0.472, 0.0, 0.406), Vec3::new(0.472, 0.330, 0.406), Vec3::new(0.314, 0.330, 0.456), Vec3::new(0.314, 0.0, 0.456), ) .with_quad( Vec3::new(0.314, 0.0, 0.456), Vec3::new(0.314, 0.330, 0.456), Vec3::new(0.265, 0.330, 0.296), Vec3::new(0.265, 0.0, 0.296), ) .with_quad( Vec3::new(0.265, 0.0, 0.296), Vec3::new(0.265, 0.330, 0.296), Vec3::new(0.423, 0.330, 0.247), Vec3::new(0.423, 0.0, 0.247), ) .build(), ); let rgb_from_xyz = rec709_from_xyz_matrix(); let white_reflectance = rgb_from_xyz * xyz_from_spectral_reflectance_sweep( CORNELL_BOX_WHITE_SAMPLES.iter().copied().into_sweep(), D65_ILLUMINANT.iter().into_sweep(), ); let red_reflectance = rgb_from_xyz * xyz_from_spectral_reflectance_sweep( CORNELL_BOX_RED_SAMPLES.iter().copied().into_sweep(), D65_ILLUMINANT.iter().into_sweep(), ); let green_reflectance = rgb_from_xyz * xyz_from_spectral_reflectance_sweep( CORNELL_BOX_GREEN_SAMPLES.iter().copied().into_sweep(), D65_ILLUMINANT.iter().into_sweep(), ); let white_material = scene.add_material(Material { reflectance: Reflectance::Constant(white_reflectance), surface: Surface::Diffuse, emission: None, }); let red_material = scene.add_material(Material { reflectance: Reflectance::Constant(red_reflectance), surface: Surface::Diffuse, emission: None, }); let green_material = scene.add_material(Material { reflectance: Reflectance::Constant(green_reflectance), surface: Surface::Diffuse, emission: None, }); let tall_block_material = match variant { CornellBoxVariant::DomeLight => scene.add_material(Material { reflectance: Reflectance::Constant(Vec3::broadcast(1.0)), surface: Surface::Mirror, emission: None, }), _ => white_material, }; let identity = scene.add_transform(Transform::default()); scene.add_instance(Instance::new(identity, floor, white_material)); scene.add_instance(Instance::new(identity, ceiling, white_material)); scene.add_instance(Instance::new(identity, grey_wall, white_material)); scene.add_instance(Instance::new(identity, red_wall, red_material)); scene.add_instance(Instance::new(identity, green_wall, green_material)); if !matches!(variant, CornellBoxVariant::Conductor) { scene.add_instance(Instance::new(identity, short_block, white_material)); scene.add_instance(Instance::new(identity, tall_block, tall_block_material)); } match variant { CornellBoxVariant::DomeLight => { scene.add_light(Light::Dome { emission: Emission::new_uniform(Vec3::new(0.4, 0.6, 0.8) * 0.8), }); let solid_angle = PI / 4096.0; scene.add_light(Light::SolidAngle { emission: Emission::new_uniform(Vec3::new(1.0, 0.8, 0.6) * 2.0 / solid_angle), direction_ws: Vec3::new(-1.0, 8.0, -5.0).normalized(), solid_angle, }); } CornellBoxVariant::Conductor => { let light_x = 0.45; let light_z = 0.1; let r_a = 0.05; let r_b = 0.0005; let power = 0.005; for i in 0..4 { let r = r_a + (r_b - r_a) * ((i as f32) / 3.0).powf(0.5); let sphere = scene.add_geometry(Geometry::Sphere { centre: Vec3::new(light_x, 0.1 + 0.1 * (i as f32), light_z), radius: r, }); let material = scene.add_material(Material { reflectance: Reflectance::Constant(Vec3::zero()), surface: Surface::None, emission: Some(Emission { illuminant: Illuminant::CornellBox, intensity: Vec3::broadcast(power / (4.0 * PI * r * r)), }), }); scene.add_instance(Instance::new(identity, sphere, material)); } let camera_x = 0.278; let camera_z = -0.8; let roughness = [0.05, 0.1, 0.25, 0.5]; for (i, roughness) in roughness.iter().copied().enumerate() { let x = 0.35 - 0.11 * (i as f32).powf(0.85); let y = 0.5488 / 2.0; let z = 0.25 - 0.06 * (i as f32).powf(1.2); let look_dir = Vec3::new(camera_x - x, 0.0, camera_z - z).normalized(); let light_dir = Vec3::new(light_x - x, 0.0, light_z - z).normalized(); let half_dir = (look_dir + light_dir).normalized(); let rotation = Rotor3::from_rotation_between(Vec3::unit_z(), half_dir); let quad = scene.add_geometry(Geometry::Quad { local_from_quad: Similarity3 { translation: Vec3::new(x, y, z), rotation, scale: 1.0, }, size: Vec2::new(0.1, 0.5488 * 0.9), }); let material = scene.add_material(Material { reflectance: Reflectance::Constant(Vec3::broadcast(0.8)), surface: Surface::RoughConductor { conductor: Conductor::Aluminium, roughness, }, emission: None, }); scene.add_instance(Instance::new(identity, quad, material)); } } _ => { let light_x0 = 0.213; let light_x1 = 0.343; let light_z0 = 0.227; let light_z1 = 0.332; let light_y = 0.5488 - 0.0001; let light_geometry = scene.add_geometry(Geometry::Quad { local_from_quad: Similarity3::new( Vec3::new(0.5 * (light_x1 + light_x0), light_y, 0.5 * (light_z1 + light_z0)), Rotor3::from_rotation_yz(0.5 * PI), 1.0, ), size: Vec2::new(light_x1 - light_x0, light_z1 - light_z0), }); let light_material = scene.add_material(Material { reflectance: Reflectance::Constant(Vec3::broadcast(0.78)), surface: Surface::Diffuse, emission: Some(Emission { illuminant: Illuminant::CornellBox, intensity: Vec3::broadcast(1.0), }), }); scene.add_instance(Instance::new(identity, light_geometry, light_material)); } } scene.add_camera(Camera::Pinhole { world_from_camera: Similarity3::new(Vec3::new(0.278, 0.273, -0.8), Rotor3::identity(), 0.25), fov_y: 2.0 * (0.025f32 / 2.0).atan2(0.035), }); scene } #[derive(Clone, Copy)] struct PlyVertex { pos: Vec3, } #[derive(Clone, Copy)] struct PlyFace { indices: UVec3, } impl ply::PropertyAccess for PlyVertex { fn new() -> Self { Self { pos: Vec3::zero() } } fn set_property(&mut self, key: String, property: ply::Property) { match (key.as_ref(), property) { ("x", ply::Property::Float(v)) => self.pos.x = v, ("y", ply::Property::Float(v)) => self.pos.y = v, ("z", ply::Property::Float(v)) => self.pos.z = v, _ => {} } } } impl ply::PropertyAccess for PlyFace { fn new() -> Self { Self { indices: UVec3::zero() } } fn set_property(&mut self, key: String, property: ply::Property) { match (key.as_ref(), property) { ("vertex_indices", ply::Property::ListInt(v)) => { assert_eq!(v.len(), 3); for (dst, src) in self.indices.as_mut_slice().iter_mut().zip(v.iter()) { *dst = *src as u32; } } _ => {} } } } pub fn load_ply(filename: &Path) -> Geometry { println!("loading {:?}", filename); let mut f = BufReader::new(File::open(filename).unwrap()); let vertex_parser = parser::Parser::<PlyVertex>::new(); let face_parser = parser::Parser::<PlyFace>::new(); let header = vertex_parser.read_header(&mut f).unwrap(); let mut vertices = Vec::new(); let mut faces = Vec::new(); for (_key, element) in header.elements.iter() { match element.name.as_ref() { "vertex" => { vertices = vertex_parser .read_payload_for_element(&mut f, element, &header) .unwrap(); } "face" => { faces = face_parser.read_payload_for_element(&mut f, element, &header).unwrap(); } _ => {} } } let mut min = Vec3::broadcast(f32::INFINITY); let mut max = Vec3::broadcast(-f32::INFINITY); for v in vertices.iter() { min = min.min_by_component(v.pos); max = max.max_by_component(v.pos); } let mut normals = vec![Vec3::zero(); vertices.len()]; let mut area = 0.0; for src in faces.iter() { let v0 = vertices[src.indices[0] as usize].pos; let v1 = vertices[src.indices[1] as usize].pos; let v2 = vertices[src.indices[2] as usize].pos; area += (0.5 * (v2 - v1).cross(v0 - v1).mag()) as f64; let normal = (v2 - v1).cross(v0 - v1).normalized(); if !normal.is_nan() { // TODO: weight by angle at vertex? normals[src.indices[0] as usize] += normal; normals[src.indices[1] as usize] += normal; normals[src.indices[2] as usize] += normal; } } for n in normals.iter_mut() { let u = n.normalized(); if !u.is_nan() { *n = u; } } let uvs = vec![Vec2::zero(); normals.len()]; Geometry::TriangleMesh { positions: vertices.drain(..).map(|v| v.pos).collect(), normals: Some(normals), uvs: Some(uvs), indices: faces.drain(..).map(|f| f.indices).collect(), min, max, area: area as f32, } } pub fn create_material_test_scene(ply_filename: &Path, surfaces: &[Surface], illuminant: Illuminant) -> Scene { let mut scene = Scene::default(); let eps = 0.001; let wall_distance = 4.0 - eps; let floor_size = 8.0 - eps; let floor_geometry = scene.add_geometry( TriangleMeshBuilder::new() .with_quad( Vec3::new(-floor_size, eps, wall_distance), Vec3::new(floor_size, eps, wall_distance), Vec3::new(floor_size, eps, -floor_size), Vec3::new(-floor_size, eps, -floor_size), ) .with_quad( Vec3::new(-floor_size, eps, wall_distance), Vec3::new(-floor_size, floor_size, wall_distance), Vec3::new(floor_size, floor_size, wall_distance), Vec3::new(floor_size, eps, wall_distance), ) .build(), ); let floor_material = scene.add_material(Material { reflectance: Reflectance::Checkerboard(Vec3::broadcast(0.8)), surface: Surface::Diffuse, emission: None, }); let identity = scene.add_transform(Transform::default()); scene.add_instance(Instance::new(identity, floor_geometry, floor_material)); let object_mesh = load_ply(ply_filename); let (centre, half_extent) = match object_mesh { Geometry::TriangleMesh { min, max, .. } => (0.5 * (max + min), 0.5 * (max - min)), _ => panic!("expected a triangle mesh"), }; let object_geometry = scene.add_geometry(object_mesh); let max_half_extent = half_extent.component_max(); let y_offset = 1.01 * half_extent.y / max_half_extent; let spacing = 1.5; for (i, surface) in surfaces.iter().enumerate() { let object_transform = scene.add_transform(Transform { world_from_local: Similarity3::new( Vec3::new( ((i as f32) - (surfaces.len() as f32 - 1.0) * 0.5) * spacing, y_offset, 0.0, ), Rotor3::from_rotation_xz(0.75 * PI), 1.0 / max_half_extent, ) * Similarity3::new(-centre, Rotor3::identity(), 1.0), }); let object_material = scene.add_material(Material { reflectance: Reflectance::Constant(Vec3::one()), surface: *surface, emission: None, }); scene.add_instance(Instance::new(object_transform, object_geometry, object_material)); } let light1_geometry = scene.add_geometry(Geometry::Quad { local_from_quad: Similarity3::new(Vec3::new(0.0, 6.0, 0.0), Rotor3::from_rotation_yz(0.5 * PI), 1.0), size: Vec2::new(5.0, 5.0), }); let light2_geometry = scene.add_geometry(Geometry::Quad { local_from_quad: Similarity3::new(Vec3::new(-6.0, 3.0, 0.0), Rotor3::from_rotation_xz(-0.5 * PI), 1.0),
rust
MIT
42fc4b496cce21e907eca7112e6d6334d35fc41a
2026-01-04T20:23:56.526296Z
true
sjb3d/caldera
https://github.com/sjb3d/caldera/blob/42fc4b496cce21e907eca7112e6d6334d35fc41a/caldera/examples/path_tracer/sobol.rs
caldera/examples/path_tracer/sobol.rs
struct SobolIterator { v: [u32; 1 + Self::MAX_INDEX_BITS], x: u32, i: u32, } impl SobolIterator { const MAX_INDEX_BITS: usize = 16; const MAX_INDEX: u32 = ((1 << Self::MAX_INDEX_BITS) - 1) as u32; fn new(a: u32, m: &[u32]) -> Self { let mut v = [0u32; 1 + Self::MAX_INDEX_BITS]; for (i, (v, m)) in v.iter_mut().zip(m.iter()).enumerate() { *v = m << (31 - i); } let s = m.len(); for i in s..=Self::MAX_INDEX_BITS { let j = i - s; v[i] = v[j] ^ (v[j] >> s); for k in 0..(s - 1) { if ((a >> k) & 1) != 0 { v[i] ^= v[j + 1 + k]; } } } Self { v, x: 0, i: u32::MAX } } fn advance(&mut self) -> u32 { // compute the next value in gray code order self.i = self.i.wrapping_add(1); self.x ^= self.v[self.i.trailing_ones() as usize]; self.x } } impl Iterator for SobolIterator { type Item = u32; fn next(&mut self) -> Option<Self::Item> { (self.i != Self::MAX_INDEX).then(|| self.advance()) } } pub fn sobol(d: u32) -> impl Iterator<Item = u32> { // direction numbers from new-joe-kuo-6.21201, see https://web.maths.unsw.edu.au/~fkuo/sobol/ let (a, m): (_, &[_]) = match d { 0 => (0, &[1; 32]), 1 => (0, &[1]), 2 => (1, &[1, 3]), 3 => (1, &[1, 3, 1]), 4 => (2, &[1, 1, 1]), 5 => (1, &[1, 1, 3, 3]), 6 => (4, &[1, 3, 5, 13]), 7 => (2, &[1, 1, 5, 5, 17]), _ => unimplemented!(), }; SobolIterator::new(a, m) }
rust
MIT
42fc4b496cce21e907eca7112e6d6334d35fc41a
2026-01-04T20:23:56.526296Z
false
sjb3d/caldera
https://github.com/sjb3d/caldera/blob/42fc4b496cce21e907eca7112e6d6334d35fc41a/caldera/examples/path_tracer/main.rs
caldera/examples/path_tracer/main.rs
mod accel; mod import; mod renderer; mod scene; mod sobol; mod spectrum; mod tungsten; mod prelude { pub use crate::sobol::*; pub use crate::spectrum::*; } use crate::{renderer::*, scene::*}; use bytemuck::{Contiguous, Pod, Zeroable}; use caldera::prelude::*; use spark::vk; use std::{ ffi::CString, ops::Deref, path::{Path, PathBuf}, slice, sync::Arc, time::Instant, }; use structopt::StructOpt; use strum::{EnumString, EnumVariantNames, VariantNames}; use winit::{ dpi::{PhysicalSize, Size}, event_loop::EventLoop, monitor::VideoMode, window::{Fullscreen, WindowBuilder}, }; #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod)] struct CopyData { exposure_scale: f32, rec709_from_xyz: Mat3, acescg_from_xyz: Mat3, tone_map_method: u32, } descriptor_set!(CopyDescriptorSet { data: UniformData<CopyData>, result: StorageImage, }); #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod)] struct CaptureData { size: UVec2, exposure_scale: f32, rec709_from_xyz: Mat3, acescg_from_xyz: Mat3, tone_map_method: u32, } descriptor_set!(CaptureDescriptorSet { data: UniformData<CaptureData>, output: StorageBuffer, input: StorageImage, }); struct ViewAdjust { translation: Vec3, rotation: Rotor3, log2_scale: f32, drag_start: Option<(Rotor3, Vec3)>, fov_y: f32, aperture_radius: f32, focus_distance: f32, } impl ViewAdjust { fn new(camera: &Camera, fov_y_override: Option<f32>) -> Self { let (world_from_camera, fov_y, aperture_radius, focus_distance) = match *camera { Camera::Pinhole { world_from_camera, fov_y, } => (world_from_camera, fov_y, 0.0, 2.0), Camera::ThinLens { world_from_camera, fov_y, aperture_radius, focus_distance, } => (world_from_camera, fov_y, aperture_radius, focus_distance), }; Self { translation: world_from_camera.translation, rotation: world_from_camera.rotation, log2_scale: world_from_camera.scale.abs().log2(), drag_start: None, fov_y: fov_y_override.unwrap_or(fov_y), aperture_radius, focus_distance, } } fn update(&mut self, response: egui::Response) -> bool { let mut was_updated = false; { let origin = Vec2::new(response.rect.min.x, response.rect.min.y); let size = Vec2::new(response.rect.width(), response.rect.height()); let aspect_ratio = (size.x as f32) / (size.y as f32); let xy_from_st = Scale2Offset2::new(Vec2::new(aspect_ratio, 1.0) * (0.5 * self.fov_y).tan(), Vec2::zero()); let st_from_uv = Scale2Offset2::new(Vec2::new(-2.0, -2.0), Vec2::new(1.0, 1.0)); let coord_from_uv = Scale2Offset2::new(size, origin); let xy_from_coord = xy_from_st * st_from_uv * coord_from_uv.inversed(); let dir_from_coord = |coord: egui::Pos2| { let coord = Vec2::new(coord.x, coord.y); (xy_from_coord * coord).into_homogeneous_point().normalized() }; if response.drag_started_by(egui::PointerButton::Primary) { self.drag_start = response .interact_pointer_pos() .map(|coord| (self.rotation, dir_from_coord(coord))); } if response.dragged_by(egui::PointerButton::Primary) { if let Some((rotation_start, dir_start)) = self.drag_start { if let Some(coord_now) = response.ctx.input(|i| i.pointer.latest_pos()) { let dir_now = dir_from_coord(coord_now); self.rotation = rotation_start * Rotor3::from_rotation_between(dir_now, dir_start); was_updated = true; } } } } response.ctx.input(|i| { let step_size = 5.0 * i.stable_dt * self.log2_scale.exp(); if i.key_down(egui::Key::W) { let v = if i.modifiers.shift { Vec3::unit_y() } else { Vec3::unit_z() }; self.translation += step_size * (self.rotation * v); was_updated = true; } if i.key_down(egui::Key::S) { let v = if i.modifiers.shift { -Vec3::unit_y() } else { -Vec3::unit_z() }; self.translation += step_size * (self.rotation * v); was_updated = true; } if i.key_down(egui::Key::A) { let v = Vec3::unit_x(); self.translation += step_size * (self.rotation * v); was_updated = true; } if i.key_down(egui::Key::D) { let v = -Vec3::unit_x(); self.translation += step_size * (self.rotation * v); was_updated = true; } }); was_updated } fn to_camera(&self) -> Camera { Camera::ThinLens { world_from_camera: Similarity3::new(self.translation, self.rotation, 1.0), fov_y: self.fov_y, aperture_radius: self.aperture_radius, focus_distance: self.focus_distance, } } } struct App { scene: SharedScene, renderer: TaskOutput<Renderer>, progress: RenderProgress, show_debug_ui: bool, view_adjust: ViewAdjust, } impl App { fn new(base: &mut AppBase, scene: Scene, renderer_params: RendererParams) -> Self { let fov_y_override = renderer_params.fov_y_override; let scene = Arc::new(scene); let renderer = base.systems.task_system.spawn_task({ Renderer::new( base.systems.resource_loader.clone(), Arc::clone(&scene), renderer_params, ) }); let progress = RenderProgress::new(); let view_adjust = ViewAdjust::new(scene.cameras.first().unwrap(), fov_y_override); Self { scene, renderer, progress, show_debug_ui: true, view_adjust, } } fn render(&mut self, base: &mut AppBase) { let cbar = base.systems.acquire_command_buffer(); base.ui_begin_frame(); base.egui_ctx.clone().input(|i| { if i.key_pressed(egui::Key::Escape) { base.exit_requested = true; } self.show_debug_ui ^= i.pointer.secondary_clicked(); }); egui::Window::new("Debug") .default_pos([5.0, 5.0]) .default_size([350.0, 600.0]) .vscroll(true) .show(&base.egui_ctx, |ui| { if let Some(renderer) = self.renderer.get_mut() { renderer.debug_ui(&mut self.progress, ui); } let mut needs_reset = false; egui::CollapsingHeader::new("Camera").default_open(true).show(ui, |ui| { let scene = self.scene.deref(); ui.label("Cameras:"); for camera_ref in scene.camera_ref_iter() { if ui.small_button(format!("Camera {}", camera_ref.0)).clicked() { self.view_adjust = ViewAdjust::new( scene.camera(camera_ref), if let Some(renderer) = self.renderer.get_mut() { renderer.params.fov_y_override } else { None }, ); needs_reset = true; } } ui.add( egui::DragValue::new(&mut self.view_adjust.log2_scale) .speed(0.05) .prefix("Camera Scale Bias: "), ); needs_reset |= ui .add( egui::DragValue::new(&mut self.view_adjust.fov_y) .speed(0.005) .prefix("Camera FOV: "), ) .changed(); needs_reset |= ui .add( egui::Slider::new(&mut self.view_adjust.aperture_radius, 0.0..=0.1) .prefix("Aperture Radius: "), ) .changed(); needs_reset |= ui .add( egui::Slider::new(&mut self.view_adjust.focus_distance, 0.0..=10.0) .prefix("Focus Distance: "), ) .changed(); }); if needs_reset { self.progress.reset(); } }); egui::CentralPanel::default() .frame(egui::Frame::none()) .show(&base.egui_ctx, |ui| { let response = ui.allocate_response(ui.available_size(), egui::Sense::drag()); if self.view_adjust.update(response) { self.progress.reset(); } }); base.systems.draw_ui(&base.egui_ctx); base.ui_end_frame(cbar.pre_swapchain_cmd); // start render let mut schedule = base.systems.resource_loader.begin_schedule( &mut base.systems.render_graph, base.context.as_ref(), &base.systems.descriptor_pool, &base.systems.pipeline_cache, ); let renderer = self.renderer.get(); let result_image = if let Some(renderer) = renderer { Some(renderer.render( &mut self.progress, &base.context, &mut schedule, &base.systems.pipeline_cache, &base.systems.descriptor_pool, &self.view_adjust.to_camera(), )) } else { None }; let swap_vk_image = base .display .acquire(&base.window, cbar.image_available_semaphore.unwrap()); let swap_size = base.display.swapchain.get_size(); let swap_format = base.display.swapchain.get_format(); let swap_image = schedule.import_image( &ImageDesc::new_2d(swap_size, swap_format, vk::ImageAspectFlags::COLOR), ImageUsage::COLOR_ATTACHMENT_WRITE | ImageUsage::SWAPCHAIN, swap_vk_image, ImageUsage::empty(), ImageUsage::SWAPCHAIN, ); let main_sample_count = vk::SampleCountFlags::N1; let main_render_state = RenderState::new().with_color(swap_image, &[0f32, 0f32, 0f32, 0f32]); schedule.add_graphics( command_name!("main"), main_render_state, |params| { if let Some(result_image) = result_image { params.add_image(result_image, ImageUsage::FRAGMENT_STORAGE_READ); } }, { let context = base.context.as_ref(); let descriptor_pool = &base.systems.descriptor_pool; let pipeline_cache = &base.systems.pipeline_cache; let pixels_per_point = base.egui_ctx.pixels_per_point(); let egui_renderer = &mut base.egui_renderer; let show_debug_ui = self.show_debug_ui; move |params, cmd, render_pass| { set_viewport_helper(&context.device, cmd, swap_size); if let Some(result_image) = result_image { let renderer_params = &renderer.unwrap().params; let rec709_from_xyz = rec709_from_xyz_matrix() * chromatic_adaptation_matrix( bradford_lms_from_xyz_matrix(), WhitePoint::D65, renderer_params.observer_white_point(), ); let acescg_from_xyz = ap1_from_xyz_matrix() * chromatic_adaptation_matrix( bradford_lms_from_xyz_matrix(), WhitePoint::D60, renderer_params.observer_white_point(), ); let copy_descriptor_set = CopyDescriptorSet::create( descriptor_pool, |buf: &mut CopyData| { *buf = CopyData { exposure_scale: renderer_params.log2_exposure_scale.exp2(), rec709_from_xyz, acescg_from_xyz, tone_map_method: renderer_params.tone_map_method.into_integer(), } }, params.get_image_view(result_image, ImageViewDesc::default()), ); let state = GraphicsPipelineState::new(render_pass, main_sample_count); draw_helper( &context.device, pipeline_cache, cmd, &state, "path_tracer/copy.vert.spv", "path_tracer/copy.frag.spv", copy_descriptor_set, 3, ); } // draw ui if show_debug_ui { let egui_pipeline = pipeline_cache.get_ui(egui_renderer, render_pass, main_sample_count); egui_renderer.render( &context.device, cmd, egui_pipeline, swap_size.x, swap_size.y, pixels_per_point, ); } } }, ); schedule.run( &base.context, cbar.pre_swapchain_cmd, cbar.post_swapchain_cmd, Some(swap_image), &mut base.systems.query_pool, ); let rendering_finished_semaphore = base.systems.submit_command_buffer(&cbar); base.display .present(swap_vk_image, rendering_finished_semaphore.unwrap()); } } struct CaptureBuffer { context: SharedContext, size: u32, mem: vk::DeviceMemory, buffer: UniqueBuffer, mapping: *const u8, } impl CaptureBuffer { fn new(context: &SharedContext, size: u32) -> Self { let buffer = { let create_info = vk::BufferCreateInfo { size: size as vk::DeviceSize, usage: vk::BufferUsageFlags::STORAGE_BUFFER, ..Default::default() }; unsafe { context.device.create_buffer(&create_info, None) }.unwrap() }; let mem_req = unsafe { context.device.get_buffer_memory_requirements(buffer) }; let mem = { let memory_type_index = context .get_memory_type_index(mem_req.memory_type_bits, vk::MemoryPropertyFlags::HOST_VISIBLE) .unwrap(); let memory_allocate_info = vk::MemoryAllocateInfo { allocation_size: size as vk::DeviceSize, memory_type_index, ..Default::default() }; unsafe { context.device.allocate_memory(&memory_allocate_info, None) }.unwrap() }; unsafe { context.device.bind_buffer_memory(buffer, mem, 0) }.unwrap(); let mapping = unsafe { context.device.map_memory(mem, 0, vk::WHOLE_SIZE, Default::default()) }.unwrap(); let mapped_memory_range = vk::MappedMemoryRange { memory: mem, offset: 0, size: vk::WHOLE_SIZE, ..Default::default() }; unsafe { context .device .flush_mapped_memory_ranges(slice::from_ref(&mapped_memory_range)) } .unwrap(); Self { context: SharedContext::clone(context), size, mem, buffer: Unique::new(buffer, context.allocate_handle_uid()), mapping: mapping as *const _, } } fn mapping(&self) -> &[u8] { let mapped_memory_range = vk::MappedMemoryRange { memory: self.mem, offset: 0, size: vk::WHOLE_SIZE, ..Default::default() }; unsafe { self.context .device .invalidate_mapped_memory_ranges(slice::from_ref(&mapped_memory_range)) } .unwrap(); unsafe { slice::from_raw_parts(self.mapping, self.size as usize) } } } impl Drop for CaptureBuffer { fn drop(&mut self) { unsafe { self.context.device.destroy_buffer(self.buffer.0, None); self.context.device.unmap_memory(self.mem); self.context.device.free_memory(self.mem, None); } } } struct CommandlineApp { context: SharedContext, systems: AppSystems, scene: SharedScene, renderer: TaskOutput<Renderer>, progress: RenderProgress, capture_buffer: CaptureBuffer, } impl CommandlineApp { fn new(context_params: &ContextParams, scene: Scene, renderer_params: RendererParams) -> Self { let context = Context::new(None, context_params); let systems = AppSystems::new(&context); let capture_buffer_size = renderer_params.width * renderer_params.height * 3; let scene = Arc::new(scene); let renderer = systems.task_system.spawn_task(Renderer::new( systems.resource_loader.clone(), Arc::clone(&scene), renderer_params, )); let progress = RenderProgress::new(); let capture_buffer = CaptureBuffer::new(&context, capture_buffer_size); Self { context, systems, scene, renderer, progress, capture_buffer, } } fn run(&mut self, filename: &Path) { let mut start_instant = None; loop { let cbar = self.systems.acquire_command_buffer(); let mut schedule = self.systems.resource_loader.begin_schedule( &mut self.systems.render_graph, self.context.as_ref(), &self.systems.descriptor_pool, &self.systems.pipeline_cache, ); let mut copy_done = false; if let Some(renderer) = self.renderer.get() { let mut camera = *self.scene.cameras.first().unwrap(); if let Some(fov_y_override) = renderer.params.fov_y_override { *match &mut camera { Camera::Pinhole { fov_y, .. } => fov_y, Camera::ThinLens { fov_y, .. } => fov_y, } = fov_y_override; } let result_image = renderer.render( &mut self.progress, &self.context, &mut schedule, &self.systems.pipeline_cache, &self.systems.descriptor_pool, &camera, ); if start_instant.is_none() { println!("starting render"); start_instant = Some(Instant::now()); } if self.progress.done(&renderer.params) { let capture_desc = BufferDesc::new(self.capture_buffer.size as usize); let capture_buffer = schedule.import_buffer( &capture_desc, BufferUsage::COMPUTE_STORAGE_WRITE, self.capture_buffer.buffer, BufferUsage::empty(), BufferUsage::empty(), ); schedule.add_compute( command_name!("capture"), |params| { params.add_image(result_image, ImageUsage::COMPUTE_STORAGE_READ); params.add_buffer(capture_buffer, BufferUsage::COMPUTE_STORAGE_WRITE); }, { let pipeline_cache = &self.systems.pipeline_cache; let descriptor_pool = &self.systems.descriptor_pool; let context = &self.context; let renderer_params = &renderer.params; move |params, cmd| { let rec709_from_xyz = rec709_from_xyz_matrix() * chromatic_adaptation_matrix( bradford_lms_from_xyz_matrix(), WhitePoint::D65, WhitePoint::E, ); let acescg_from_xyz = ap1_from_xyz_matrix() * chromatic_adaptation_matrix( bradford_lms_from_xyz_matrix(), WhitePoint::D60, WhitePoint::E, ); let descriptor_set = CaptureDescriptorSet::create( descriptor_pool, |buf: &mut CaptureData| { *buf = CaptureData { size: renderer_params.size(), exposure_scale: renderer_params.log2_exposure_scale.exp2(), rec709_from_xyz, acescg_from_xyz, tone_map_method: renderer_params.tone_map_method.into_integer(), }; }, params.get_buffer(capture_buffer), params.get_image_view(result_image, ImageViewDesc::default()), ); dispatch_helper( &context.device, pipeline_cache, cmd, "path_tracer/capture.comp.spv", &[], descriptor_set, renderer_params.size().div_round_up(16), ); } }, ); copy_done = true; } } else { // waiting for async load std::thread::sleep(std::time::Duration::from_millis(5)); } schedule.run( &self.context, cbar.pre_swapchain_cmd, cbar.post_swapchain_cmd, None, &mut self.systems.query_pool, ); self.systems.submit_command_buffer(&cbar); if copy_done { break; } } println!("waiting for fence"); self.systems.command_buffer_pool.wait_after_submit(); println!( "render time for {} samples: {} seconds", self.renderer.get().unwrap().params.sample_count(), Instant::now().duration_since(start_instant.unwrap()).as_secs_f32() ); println!("saving image to {:?}", filename); let params = &self.renderer.get().unwrap().params; match filename.extension().unwrap().to_str().unwrap() { "png" => { stb::image_write::stbi_write_png( CString::new(filename.to_str().unwrap()).unwrap().as_c_str(), params.width as i32, params.height as i32, 3, self.capture_buffer.mapping(), (params.width * 3) as i32, ) .unwrap(); } "tga" => { stb::image_write::stbi_write_tga( CString::new(filename.to_str().unwrap()).unwrap().as_c_str(), params.width as i32, params.height as i32, 3, self.capture_buffer.mapping(), ) .unwrap(); } "jpg" => { let quality = 95; stb::image_write::stbi_write_jpg( CString::new(filename.to_str().unwrap()).unwrap().as_c_str(), params.width as i32, params.height as i32, 3, self.capture_buffer.mapping(), quality, ) .unwrap(); } _ => panic!("unknown extension"), } println!("shutting down"); } } #[derive(Debug, EnumString, EnumVariantNames)] #[strum(serialize_all = "kebab_case")] enum MaterialTestVariant { Conductors, Gold, } #[derive(Debug, StructOpt)] enum SceneDesc { /// Load a cornell box scene CornellBox { #[structopt(possible_values=&CornellBoxVariant::VARIANTS, default_value="original")] variant: CornellBoxVariant, }, /// Import from .caldera file Import { filename: PathBuf }, /// Import from Tungsten scene.json file Tungsten { filename: PathBuf }, /// Material test scene MaterialTest { ply_filename: PathBuf, #[structopt(possible_values=&MaterialTestVariant::VARIANTS)] variant: MaterialTestVariant, illuminant: Illuminant, }, } #[derive(Debug, StructOpt)] #[structopt(no_version)] struct AppParams { /// Core Vulkan version to load #[structopt(short, long, parse(try_from_str=try_version_from_str), default_value="1.1", global=true)] version: vk::Version, /// Whether to use EXT_inline_uniform_block #[structopt(long, possible_values=&ContextFeature::VARIANTS, default_value="optional", global=true)] inline_uniform_block: ContextFeature, /// Run without a window and output to file #[structopt(short, long, global = true, display_order = 3)] output: Option<PathBuf>, /// Run fullscreen #[structopt(long, global = true)] fullscreen: bool, #[structopt(flatten)] renderer_params: RendererParams, #[structopt(subcommand)] scene_desc: Option<SceneDesc>, } fn main() { let app_params = AppParams::from_args(); let context_params = ContextParams { version: app_params.version, inline_uniform_block: app_params.inline_uniform_block, bindless: ContextFeature::Require, ray_tracing: ContextFeature::Require, ..Default::default() }; let renderer_params = app_params.renderer_params; let scene = match app_params.scene_desc.as_ref().unwrap_or(&SceneDesc::CornellBox { variant: CornellBoxVariant::Original, }) { SceneDesc::CornellBox { variant } => create_cornell_box_scene(variant), SceneDesc::Import { filename } => { let contents = std::fs::read_to_string(filename).unwrap(); import::load_scene(&contents) } SceneDesc::Tungsten { filename } => tungsten::load_scene(filename, renderer_params.observer_illuminant()), SceneDesc::MaterialTest { ply_filename, variant, illuminant, } => { let surfaces: &[Surface] = match variant { MaterialTestVariant::Conductors => &[ Surface::RoughConductor { conductor: Conductor::Gold, roughness: 0.2, }, Surface::RoughConductor { conductor: Conductor::Iron, roughness: 0.2, }, Surface::RoughConductor { conductor: Conductor::Copper, roughness: 0.2, }, ], MaterialTestVariant::Gold => &[Surface::RoughConductor { conductor: Conductor::Gold, roughness: 0.2, }], }; create_material_test_scene(ply_filename, surfaces, *illuminant) } }; if scene.cameras.is_empty() { panic!("scene must contain at least one camera!"); } if let Some(output) = app_params.output { let mut app = CommandlineApp::new(&context_params, scene, renderer_params); app.run(&output); } else { let event_loop = EventLoop::new(); let mut window_builder = WindowBuilder::new().with_title("trace"); window_builder = if app_params.fullscreen { let monitor = event_loop.primary_monitor().unwrap(); let size = PhysicalSize::new(renderer_params.width, renderer_params.height); let video_mode = monitor .video_modes() .filter(|m| m.size() == size) .max_by(|a, b| { let t = |m: &VideoMode| (m.bit_depth(), m.refresh_rate_millihertz()); Ord::cmp(&t(a), &t(b)) }) .unwrap(); window_builder.with_fullscreen(Some(Fullscreen::Exclusive(video_mode))) } else { window_builder.with_inner_size(Size::Physical(PhysicalSize::new( renderer_params.width, renderer_params.height, ))) }; let window = window_builder.build(&event_loop).unwrap(); let mut base = AppBase::new(window, &context_params); let app = App::new(&mut base, scene, renderer_params); let mut apps = Some((base, app)); event_loop.run(move |event, target, control_flow| { match apps .as_mut() .map(|(base, _)| base) .unwrap() .process_event(&event, target, control_flow) { AppEventResult::None => {} AppEventResult::Redraw => { let (base, app) = apps.as_mut().unwrap(); app.render(base); } AppEventResult::Destroy => { apps.take(); } } }); } }
rust
MIT
42fc4b496cce21e907eca7112e6d6334d35fc41a
2026-01-04T20:23:56.526296Z
false
sjb3d/caldera
https://github.com/sjb3d/caldera/blob/42fc4b496cce21e907eca7112e6d6334d35fc41a/caldera/examples/path_tracer/import.rs
caldera/examples/path_tracer/import.rs
use crate::scene::*; use caldera::prelude::*; use nom::{ branch::alt, bytes::complete::{tag, take_till1}, character::complete::{char, digit1, multispace0, multispace1}, combinator::{all_consuming, map, map_res}, multi::many1, number::complete::float, sequence::{delimited, preceded, terminated, tuple}, IResult, }; use std::collections::HashMap; enum Element<'a> { Transform { name: &'a str, world_from_local: Similarity3, }, Mesh { name: &'a str, positions: Vec<Vec3>, normals: Vec<Vec3>, indices: Vec<UVec3>, }, Instance { transform_ref: &'a str, geometry_ref: &'a str, surface: Surface, reflectance: Vec3, }, Camera { transform_ref: &'a str, fov_y: f32, }, SolidAngleLight { angle: f32, direction: Vec3, emission: Vec3, }, } fn rotor3_from_quaternion(q: Vec4) -> Rotor3 { Rotor3::new(q.x, Bivec3::new(-q.w, q.z, -q.y)) } fn vec4(i: &str) -> IResult<&str, Vec4> { map( tuple(( float, preceded(multispace1, float), preceded(multispace1, float), preceded(multispace1, float), )), |(x, y, z, w)| Vec4::new(x, y, z, w), )(i) } fn similarity3(i: &str) -> IResult<&str, Similarity3> { map( tuple((vec3, preceded(multispace1, vec4), preceded(multispace1, float))), |(translation, rotation, scale)| Similarity3::new(translation, rotor3_from_quaternion(rotation), scale), )(i) } fn quoted_name(i: &str) -> IResult<&str, &str> { delimited(char('"'), take_till1(|c| c == '"'), char('"'))(i) } fn element_transform(i: &str) -> IResult<&str, Element> { let (i, name) = quoted_name(i)?; let (i, world_from_local) = preceded(multispace0, similarity3)(i)?; Ok((i, Element::Transform { name, world_from_local })) } fn vec3(i: &str) -> IResult<&str, Vec3> { map( tuple((float, preceded(multispace1, float), preceded(multispace1, float))), |(x, y, z)| Vec3::new(x, y, z), )(i) } fn uint(i: &str) -> IResult<&str, u32> { map_res(digit1, str::parse::<u32>)(i) } fn uvec3(i: &str) -> IResult<&str, UVec3> { map( tuple((uint, preceded(multispace1, uint), preceded(multispace1, uint))), |(x, y, z)| UVec3::new(x, y, z), )(i) } fn element_mesh(i: &str) -> IResult<&str, Element> { let (i, name) = quoted_name(i)?; let (i, positions) = delimited( tuple((multispace0, tag("positions"), multispace0, char('{'))), many1(preceded(multispace0, vec3)), preceded(multispace0, char('}')), )(i)?; let (i, normals) = delimited( tuple((multispace0, tag("normals"), multispace0, char('{'))), many1(preceded(multispace0, vec3)), preceded(multispace0, char('}')), )(i)?; let (i, indices) = delimited( tuple((multispace0, tag("indices"), multispace0, char('{'))), many1(preceded(multispace0, uvec3)), preceded(multispace0, char('}')), )(i)?; Ok(( i, Element::Mesh { name, positions, normals, indices, }, )) } fn element_camera(i: &str) -> IResult<&str, Element> { let (i, transform_ref) = quoted_name(i)?; let (i, fov_y) = preceded(multispace0, float)(i)?; Ok((i, Element::Camera { transform_ref, fov_y })) } fn surface(i: &str) -> IResult<&str, Surface> { alt(( map(tag("diffuse"), |_| Surface::Diffuse), map(tag("mirror"), |_| Surface::Mirror), map( preceded(tuple((tag("rough_conductor"), multispace1)), float), |roughness| Surface::RoughConductor { conductor: Conductor::Aluminium, roughness, }, ), map( preceded(tuple((tag("rough_plastic"), multispace1)), float), |roughness| Surface::RoughPlastic { roughness }, ), ))(i) } fn element_instance(i: &str) -> IResult<&str, Element> { let (i, transform_ref) = quoted_name(i)?; let (i, geometry_ref) = preceded(multispace0, quoted_name)(i)?; let (i, surface) = preceded(multispace0, surface)(i)?; let (i, reflectance) = preceded(multispace1, vec3)(i)?; Ok(( i, Element::Instance { transform_ref, geometry_ref, surface, reflectance, }, )) } fn element_solid_angle_light(i: &str) -> IResult<&str, Element> { let (i, angle) = float(i)?; let (i, direction) = preceded(multispace1, vec3)(i)?; let (i, emission) = preceded(multispace1, vec3)(i)?; Ok(( i, Element::SolidAngleLight { angle, direction, emission, }, )) } fn element(i: &str) -> IResult<&str, Element> { alt(( preceded(tag("transform"), preceded(multispace0, element_transform)), preceded(tag("mesh"), preceded(multispace0, element_mesh)), preceded(tag("instance"), preceded(multispace0, element_instance)), preceded(tag("camera"), preceded(multispace0, element_camera)), preceded( tag("solid_angle_light"), preceded(multispace0, element_solid_angle_light), ), ))(i) } pub fn load_scene(i: &str) -> Scene { let mut elements = all_consuming(terminated(many1(preceded(multispace0, element)), multispace0))(i) .unwrap() .1; let mut scene = Scene::default(); let mut transform_refs = HashMap::new(); let mut geometry_refs = HashMap::new(); for element in elements.drain(..) { match element { Element::Transform { name, world_from_local } => { let transform_ref = scene.add_transform(Transform::new(world_from_local)); if transform_refs.insert(name, transform_ref).is_some() { panic!("multiple transforms with name \"{}\"", name); } } Element::Mesh { name, positions, normals, indices, } => { let mut min = Vec3::broadcast(f32::INFINITY); let mut max = Vec3::broadcast(-f32::INFINITY); for pos in positions.iter() { min = min.min_by_component(*pos); max = max.max_by_component(*pos); } let mut area = 0.0; for tri in indices.iter() { let p0 = positions[tri.x as usize]; let p1 = positions[tri.y as usize]; let p2 = positions[tri.z as usize]; area += (0.5 * (p2 - p1).cross(p0 - p1).mag()) as f64; } let geometry_ref = scene.add_geometry(Geometry::TriangleMesh { positions, normals: Some(normals), uvs: None, indices, min, max, area: area as f32, }); if geometry_refs.insert(name, geometry_ref).is_some() { panic!("multiple geometry with name \"{}\"", name); } } Element::Instance { transform_ref, geometry_ref, surface, reflectance, } => { let material_ref = scene.add_material(Material { reflectance: Reflectance::Constant(reflectance), surface, emission: None, }); scene.add_instance(Instance::new( *transform_refs.get(transform_ref).unwrap(), *geometry_refs.get(geometry_ref).unwrap(), material_ref, )); } Element::Camera { transform_ref, fov_y } => { let transform_ref = *transform_refs.get(transform_ref).unwrap(); scene.add_camera(Camera::Pinhole { world_from_camera: scene.transform(transform_ref).world_from_local, fov_y, }); } Element::SolidAngleLight { angle, direction, emission, } => { let solid_angle = 2.0 * PI * (1.0 - angle.cos()); scene.add_light(Light::SolidAngle { solid_angle, direction_ws: direction, emission: Emission::new_uniform(emission / solid_angle), }); } } } scene.bake_unique_geometry(); scene }
rust
MIT
42fc4b496cce21e907eca7112e6d6334d35fc41a
2026-01-04T20:23:56.526296Z
false
sjb3d/caldera
https://github.com/sjb3d/caldera/blob/42fc4b496cce21e907eca7112e6d6334d35fc41a/caldera/examples/path_tracer/accel.rs
caldera/examples/path_tracer/accel.rs
use crate::scene::*; use bytemuck::{Pod, Zeroable}; use caldera::prelude::*; use spark::{vk, Builder}; use std::sync::Arc; use std::{mem, slice}; type PositionData = Vec3; type IndexData = UVec3; #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod)] struct AabbData { min: Vec3, max: Vec3, } // vk::AccelerationStructureInstanceKHR with Pod trait #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod)] struct AccelerationStructureInstance { transform: TransposedTransform3, instance_custom_index_and_mask: u32, instance_shader_binding_table_record_offset_and_flags: u32, acceleration_structure_reference: u64, } pub enum GeometryAccelData { Triangles { index_buffer: vk::Buffer, position_buffer: vk::Buffer, }, Procedural { aabb_buffer: vk::Buffer, }, } #[derive(PartialEq, Eq, PartialOrd, Ord)] struct ClusterElement { geometry_ref: GeometryRef, instance_refs: Vec<InstanceRef>, // stored in transform order (matches parent transform_refs) } #[derive(PartialEq, Eq, PartialOrd, Ord)] enum PrimitiveType { Triangles, Procedural, } #[derive(PartialEq, Eq, PartialOrd, Ord)] struct Cluster { transform_refs: Vec<TransformRef>, primitive_type: PrimitiveType, elements: Vec<ClusterElement>, } impl Cluster { fn unique_primitive_count(&self, scene: &Scene) -> usize { self.elements .iter() .map(|element| match scene.geometry(element.geometry_ref) { Geometry::TriangleMesh { indices, .. } => indices.len(), Geometry::Quad { .. } => 2, Geometry::Disc { .. } => 1, Geometry::Sphere { .. } => 1, Geometry::Mandelbulb { .. } => 1, }) .sum() } fn instanced_primitive_count(&self, scene: &Scene) -> usize { self.transform_refs.len() * self.unique_primitive_count(scene) } } pub struct SceneClusters(Vec<Cluster>); impl SceneClusters { fn new(scene: &Scene) -> Self { // gather a vector of instances per geometry let mut instance_refs_per_geometry = vec![Vec::new(); scene.geometries.len()]; for instance_ref in scene.instance_ref_iter() { let instance = scene.instance(instance_ref); instance_refs_per_geometry .get_mut(instance.geometry_ref.0 as usize) .unwrap() .push(instance_ref); } // convert to single-geometry clusters, with instances sorted by transform reference let mut clusters: Vec<_> = scene .geometry_ref_iter() .zip(instance_refs_per_geometry.drain(..)) .filter(|(_, instance_refs)| !instance_refs.is_empty()) .map(|(geometry_ref, instance_refs)| { let mut pairs: Vec<_> = instance_refs .iter() .map(|&instance_ref| (scene.instance(instance_ref).transform_ref, instance_ref)) .collect(); pairs.sort_unstable(); let (transform_refs, instance_refs): (Vec<_>, Vec<_>) = pairs.drain(..).unzip(); let primitive_type = match scene.geometry(geometry_ref) { Geometry::TriangleMesh { .. } | Geometry::Quad { .. } => PrimitiveType::Triangles, Geometry::Disc { .. } | Geometry::Sphere { .. } | Geometry::Mandelbulb { .. } => { PrimitiveType::Procedural } }; Cluster { transform_refs, primitive_type, elements: vec![ClusterElement { geometry_ref, instance_refs, }], } }) .collect(); // sort the clusters by transform set so that we can merge in a single pass clusters.sort_unstable(); // merge clusters that are used with the same set of transforms let mut merged = Vec::<Cluster>::new(); for mut cluster in clusters.drain(..) { if let Some(prev) = merged.last_mut().filter(|prev| { prev.transform_refs == cluster.transform_refs && prev.primitive_type == cluster.primitive_type }) { prev.elements.append(&mut cluster.elements); } else { merged.push(cluster); } } Self(merged) } pub fn unique_accel_count(&self) -> usize { self.0.len() } pub fn instanced_accel_count(&self) -> usize { self.0.iter().map(|cluster| cluster.transform_refs.len()).sum() } pub fn geometry_iter(&self) -> impl Iterator<Item = &GeometryRef> { self.0 .iter() .flat_map(|cluster| cluster.elements.iter().map(|element| &element.geometry_ref)) } pub fn instance_iter(&self) -> impl Iterator<Item = &InstanceRef> { // iterate in shader binding table order self.0.iter().flat_map(|cluster| { (0..cluster.transform_refs.len()).flat_map({ let elements = &cluster.elements; move |transform_index| { elements .iter() .map(move |element| element.instance_refs.get(transform_index).unwrap()) } }) }) } } struct BottomLevelAccel { buffer_id: BufferId, } struct TopLevelAccel { buffer_id: BufferId, } pub struct SceneAccel { scene: SharedScene, clusters: SceneClusters, geometry_accel_data: Vec<Option<GeometryAccelData>>, cluster_accel: Vec<BottomLevelAccel>, top_level_accel: TopLevelAccel, } impl SceneAccel { pub fn unique_bottom_level_accel_count(&self) -> usize { self.clusters.unique_accel_count() } pub fn instanced_bottom_level_accel_count(&self) -> usize { self.clusters.instanced_accel_count() } pub fn unique_primitive_count(&self) -> usize { self.clusters .0 .iter() .map(|cluster| cluster.unique_primitive_count(&self.scene)) .sum() } pub fn instanced_primitive_count(&self) -> usize { self.clusters .0 .iter() .map(|cluster| cluster.instanced_primitive_count(&self.scene)) .sum() } pub fn clusters(&self) -> &SceneClusters { &self.clusters } pub fn geometry_accel_data(&self, geometry_ref: GeometryRef) -> Option<&GeometryAccelData> { self.geometry_accel_data[geometry_ref.0 as usize].as_ref() } pub async fn new(resource_loader: ResourceLoader, scene: SharedScene, hit_group_count_per_instance: u32) -> Self { let clusters = SceneClusters::new(&scene); let geometry_accel_data = SceneAccel::create_geometry_accel_data(resource_loader.clone(), Arc::clone(&scene), &clusters).await; let mut cluster_accel = Vec::new(); for cluster in clusters.0.iter() { cluster_accel.push( SceneAccel::create_bottom_level_accel( cluster, resource_loader.clone(), Arc::clone(&scene), &geometry_accel_data, ) .await, ); } let instance_buffer = SceneAccel::create_instance_buffer( resource_loader.clone(), Arc::clone(&scene), &clusters, &cluster_accel, hit_group_count_per_instance, ) .await; let top_level_accel = SceneAccel::create_top_level_accel(resource_loader.clone(), &clusters, &cluster_accel, instance_buffer) .await; Self { scene, clusters, geometry_accel_data, cluster_accel, top_level_accel, } } async fn create_geometry_accel_data( resource_loader: ResourceLoader, scene: SharedScene, clusters: &SceneClusters, ) -> Vec<Option<GeometryAccelData>> { // make vertex/index buffers for each referenced geometry let mut tasks = Vec::new(); for &geometry_ref in clusters.geometry_iter() { let loader = resource_loader.clone(); let scene = Arc::clone(&scene); tasks.push(spawn(async move { let geometry = scene.geometry(geometry_ref); match geometry { Geometry::TriangleMesh { .. } | Geometry::Quad { .. } => { let mut mesh_builder = TriangleMeshBuilder::new(); let (positions, indices) = match *scene.geometry(geometry_ref) { Geometry::TriangleMesh { ref positions, ref indices, .. } => (positions.as_slice(), indices.as_slice()), Geometry::Quad { local_from_quad, size } => { let half_size = 0.5 * size; mesh_builder = mesh_builder.with_quad( local_from_quad * Vec3::new(-half_size.x, -half_size.y, 0.0), local_from_quad * Vec3::new(half_size.x, -half_size.y, 0.0), local_from_quad * Vec3::new(half_size.x, half_size.y, 0.0), local_from_quad * Vec3::new(-half_size.x, half_size.y, 0.0), ); (mesh_builder.positions.as_slice(), mesh_builder.indices.as_slice()) } Geometry::Disc { .. } | Geometry::Sphere { .. } | Geometry::Mandelbulb { .. } => { unreachable!() } }; let index_buffer_desc = BufferDesc::new(indices.len() * mem::size_of::<IndexData>()); let mut writer = loader .buffer_writer( &index_buffer_desc, BufferUsage::ACCELERATION_STRUCTURE_BUILD_INPUT | BufferUsage::RAY_TRACING_STORAGE_READ, ) .await; for face in indices.iter() { writer.write(face); } let index_buffer_id = writer.finish(); let position_buffer_desc = BufferDesc::new(positions.len() * mem::size_of::<PositionData>()); let mut writer = loader .buffer_writer( &position_buffer_desc, BufferUsage::ACCELERATION_STRUCTURE_BUILD_INPUT | BufferUsage::RAY_TRACING_STORAGE_READ, ) .await; for pos in positions.iter() { writer.write(pos); } let position_buffer_id = writer.finish(); GeometryAccelData::Triangles { position_buffer: loader.get_buffer(position_buffer_id.await), index_buffer: loader.get_buffer(index_buffer_id.await), } } Geometry::Disc { local_from_disc, radius, } => { let centre = local_from_disc.translation; let normal = local_from_disc.transform_vec3(Vec3::unit_z()).normalized(); let radius = (radius * local_from_disc.scale).abs(); let half_extent = normal.map(|s| (1.0 - s * s).max(0.0).sqrt() * radius); let buffer_desc = BufferDesc::new(mem::size_of::<AabbData>()); let mut writer = loader .buffer_writer(&buffer_desc, BufferUsage::ACCELERATION_STRUCTURE_BUILD_INPUT) .await; writer.write(&AabbData { min: centre - half_extent, max: centre + half_extent, }); let aabb_buffer_id = writer.finish(); GeometryAccelData::Procedural { aabb_buffer: loader.get_buffer(aabb_buffer_id.await), } } Geometry::Sphere { centre, radius } => { let centre = *centre; let radius = *radius; let buffer_desc = BufferDesc::new(mem::size_of::<AabbData>()); let mut writer = loader .buffer_writer(&buffer_desc, BufferUsage::ACCELERATION_STRUCTURE_BUILD_INPUT) .await; writer.write(&AabbData { min: centre - Vec3::broadcast(radius), max: centre + Vec3::broadcast(radius), }); let aabb_buffer_id = writer.finish(); GeometryAccelData::Procedural { aabb_buffer: loader.get_buffer(aabb_buffer_id.await), } } Geometry::Mandelbulb { local_from_bulb } => { let centre = local_from_bulb.translation; let radius = MANDELBULB_RADIUS * local_from_bulb.scale.abs(); let buffer_desc = BufferDesc::new(mem::size_of::<AabbData>()); let mut writer = loader .buffer_writer(&buffer_desc, BufferUsage::ACCELERATION_STRUCTURE_BUILD_INPUT) .await; writer.write(&AabbData { min: centre - Vec3::broadcast(radius), max: centre + Vec3::broadcast(radius), }); let aabb_buffer_id = writer.finish(); GeometryAccelData::Procedural { aabb_buffer: loader.get_buffer(aabb_buffer_id.await), } } } })); } // make vertex/index buffers for each referenced geometry let mut geometry_accel_data: Vec<_> = scene.geometries.iter().map(|_| None).collect(); for (&geometry_ref, task) in clusters.geometry_iter().zip(tasks.iter_mut()) { geometry_accel_data[geometry_ref.0 as usize] = Some(task.await); } geometry_accel_data } async fn create_bottom_level_accel( cluster: &Cluster, resource_loader: ResourceLoader, scene: SharedScene, geometry_accel_data: &[Option<GeometryAccelData>], ) -> BottomLevelAccel { let context = resource_loader.context(); let mut accel_geometry = Vec::new(); let mut max_primitive_counts = Vec::new(); let mut build_range_info = Vec::new(); for geometry_ref in cluster.elements.iter().map(|element| element.geometry_ref) { let geometry = scene.geometry(geometry_ref); let geometry_accel_data = geometry_accel_data[geometry_ref.0 as usize].as_ref().unwrap(); match geometry_accel_data { GeometryAccelData::Triangles { index_buffer, position_buffer, } => { let position_buffer_address = unsafe { context.device.get_buffer_device_address_helper(*position_buffer) }; let index_buffer_address = unsafe { context.device.get_buffer_device_address_helper(*index_buffer) }; let (vertex_count, triangle_count) = match geometry { Geometry::TriangleMesh { positions, indices, .. } => { (positions.len() as u32, indices.len() as u32) } Geometry::Quad { .. } => (4, 2), Geometry::Disc { .. } | Geometry::Sphere { .. } | Geometry::Mandelbulb { .. } => unreachable!(), }; accel_geometry.push(vk::AccelerationStructureGeometryKHR { geometry_type: vk::GeometryTypeKHR::TRIANGLES, geometry: vk::AccelerationStructureGeometryDataKHR { triangles: vk::AccelerationStructureGeometryTrianglesDataKHR { vertex_format: vk::Format::R32G32B32_SFLOAT, vertex_data: vk::DeviceOrHostAddressConstKHR { device_address: position_buffer_address, }, vertex_stride: mem::size_of::<PositionData>() as vk::DeviceSize, max_vertex: vertex_count, index_type: vk::IndexType::UINT32, index_data: vk::DeviceOrHostAddressConstKHR { device_address: index_buffer_address, }, ..Default::default() }, }, flags: vk::GeometryFlagsKHR::OPAQUE, ..Default::default() }); max_primitive_counts.push(triangle_count); build_range_info.push(vk::AccelerationStructureBuildRangeInfoKHR { primitive_count: triangle_count, primitive_offset: 0, first_vertex: 0, transform_offset: 0, }); } GeometryAccelData::Procedural { aabb_buffer } => { let aabb_buffer_address = unsafe { context.device.get_buffer_device_address_helper(*aabb_buffer) }; accel_geometry.push(vk::AccelerationStructureGeometryKHR { geometry_type: vk::GeometryTypeKHR::AABBS, geometry: vk::AccelerationStructureGeometryDataKHR { aabbs: vk::AccelerationStructureGeometryAabbsDataKHR { data: vk::DeviceOrHostAddressConstKHR { device_address: aabb_buffer_address, }, stride: mem::size_of::<AabbData>() as vk::DeviceSize, ..Default::default() }, }, flags: vk::GeometryFlagsKHR::OPAQUE, ..Default::default() }); max_primitive_counts.push(1); build_range_info.push(vk::AccelerationStructureBuildRangeInfoKHR { primitive_count: 1, primitive_offset: 0, first_vertex: 0, transform_offset: 0, }); } } } let build_info = vk::AccelerationStructureBuildGeometryInfoKHR::builder() .ty(vk::AccelerationStructureTypeKHR::BOTTOM_LEVEL) .flags(vk::BuildAccelerationStructureFlagsKHR::PREFER_FAST_TRACE) .mode(vk::BuildAccelerationStructureModeKHR::BUILD) .p_geometries(Some(&accel_geometry), None); let sizes = { let mut sizes = vk::AccelerationStructureBuildSizesInfoKHR::default(); unsafe { context.device.get_acceleration_structure_build_sizes_khr( vk::AccelerationStructureBuildTypeKHR::DEVICE, &build_info, Some(&max_primitive_counts), &mut sizes, ) }; sizes }; println!( "geometry count: {} (to be instanced {} times)", cluster.elements.len(), cluster.transform_refs.len() ); println!("build scratch size: {}", sizes.build_scratch_size); println!("acceleration structure size: {}", sizes.acceleration_structure_size); let buffer_id = resource_loader .graphics(move |ctx: GraphicsTaskContext| { let context = ctx.context; let schedule = ctx.schedule; let buffer_id = schedule.create_buffer( &BufferDesc::new(sizes.acceleration_structure_size as usize), BufferUsage::BOTTOM_LEVEL_ACCELERATION_STRUCTURE_WRITE | BufferUsage::BOTTOM_LEVEL_ACCELERATION_STRUCTURE_READ | BufferUsage::RAY_TRACING_ACCELERATION_STRUCTURE, ); let scratch_buffer_id = schedule.describe_buffer(&BufferDesc::new(sizes.build_scratch_size as usize)); schedule.add_compute( command_name!("build"), |params| { params.add_buffer(buffer_id, BufferUsage::BOTTOM_LEVEL_ACCELERATION_STRUCTURE_WRITE); params.add_buffer(scratch_buffer_id, BufferUsage::ACCELERATION_STRUCTURE_BUILD_SCRATCH); }, { let accel_geometry = accel_geometry; let build_range_info = build_range_info; move |params, cmd| { let accel = params.get_buffer_accel(buffer_id); let scratch_buffer = params.get_buffer(scratch_buffer_id); let scratch_buffer_address = unsafe { context.device.get_buffer_device_address_helper(scratch_buffer) }; let build_info = vk::AccelerationStructureBuildGeometryInfoKHR::builder() .ty(vk::AccelerationStructureTypeKHR::BOTTOM_LEVEL) .flags(vk::BuildAccelerationStructureFlagsKHR::PREFER_FAST_TRACE) .mode(vk::BuildAccelerationStructureModeKHR::BUILD) .dst_acceleration_structure(accel) .p_geometries(Some(&accel_geometry), None) .scratch_data(vk::DeviceOrHostAddressKHR { device_address: scratch_buffer_address, }); unsafe { context.device.cmd_build_acceleration_structures_khr( cmd, slice::from_ref(&build_info), slice::from_ref(&build_range_info.as_ptr()), ) }; } }, ); buffer_id }) .await; BottomLevelAccel { buffer_id } } async fn create_instance_buffer( resource_loader: ResourceLoader, scene: SharedScene, clusters: &SceneClusters, cluster_accel: &[BottomLevelAccel], hit_group_count_per_instance: u32, ) -> vk::Buffer { let context = resource_loader.context(); let count = clusters.instanced_accel_count(); let desc = BufferDesc::new(count * mem::size_of::<AccelerationStructureInstance>()); let mut writer = resource_loader .buffer_writer(&desc, BufferUsage::ACCELERATION_STRUCTURE_BUILD_INPUT) .await; let mut record_offset = 0; for (cluster, cluster_accel) in clusters.0.iter().zip(cluster_accel.iter()) { let info = vk::AccelerationStructureDeviceAddressInfoKHR { acceleration_structure: resource_loader.get_buffer_accel(cluster_accel.buffer_id), ..Default::default() }; let acceleration_structure_reference = unsafe { context.device.get_acceleration_structure_device_address_khr(&info) }; for transform_ref in cluster.transform_refs.iter().copied() { let custom_index = transform_ref.0 & 0x00_ff_ff_ff; let transform = scene.transform(transform_ref); let instance = AccelerationStructureInstance { transform: transform.world_from_local.into_transform().transposed(), instance_custom_index_and_mask: 0xff_00_00_00 | custom_index, instance_shader_binding_table_record_offset_and_flags: record_offset, acceleration_structure_reference, }; writer.write(&instance); record_offset += (cluster.elements.len() as u32) * hit_group_count_per_instance; } } let instance_buffer_id = writer.finish(); resource_loader.get_buffer(instance_buffer_id.await) } async fn create_top_level_accel( resource_loader: ResourceLoader, clusters: &SceneClusters, cluster_accel: &[BottomLevelAccel], instance_buffer: vk::Buffer, ) -> TopLevelAccel { let context = resource_loader.context(); let instance_buffer_address = unsafe { context.device.get_buffer_device_address_helper(instance_buffer) }; let accel_geometry = vk::AccelerationStructureGeometryKHR { geometry_type: vk::GeometryTypeKHR::INSTANCES, geometry: vk::AccelerationStructureGeometryDataKHR { instances: vk::AccelerationStructureGeometryInstancesDataKHR { data: vk::DeviceOrHostAddressConstKHR { device_address: instance_buffer_address, }, ..Default::default() }, }, ..Default::default() }; let build_info = vk::AccelerationStructureBuildGeometryInfoKHR::builder() .ty(vk::AccelerationStructureTypeKHR::TOP_LEVEL) .flags(vk::BuildAccelerationStructureFlagsKHR::PREFER_FAST_TRACE) .mode(vk::BuildAccelerationStructureModeKHR::BUILD) .p_geometries(Some(slice::from_ref(&accel_geometry)), None); let instance_count = clusters.instanced_accel_count() as u32; let sizes = { let mut sizes = vk::AccelerationStructureBuildSizesInfoKHR::default(); unsafe { context.device.get_acceleration_structure_build_sizes_khr( vk::AccelerationStructureBuildTypeKHR::DEVICE, &build_info, Some(slice::from_ref(&instance_count)), &mut sizes, ) }; sizes }; println!("instance count: {}", instance_count); println!("build scratch size: {}", sizes.build_scratch_size); println!("acceleration structure size: {}", sizes.acceleration_structure_size); let buffer_id = resource_loader .graphics({ let accel_buffer_ids: Vec<_> = cluster_accel.iter().map(|accel| accel.buffer_id).collect(); move |ctx: GraphicsTaskContext| { let context = ctx.context; let schedule = ctx.schedule; let buffer_id = schedule.create_buffer( &BufferDesc::new(sizes.acceleration_structure_size as usize), BufferUsage::TOP_LEVEL_ACCELERATION_STRUCTURE_WRITE | BufferUsage::RAY_TRACING_ACCELERATION_STRUCTURE, ); let scratch_buffer_id = schedule.describe_buffer(&BufferDesc::new(sizes.build_scratch_size as usize)); schedule.add_compute( command_name!("build"), |params| { for &buffer_id in accel_buffer_ids.iter() { params.add_buffer(buffer_id, BufferUsage::BOTTOM_LEVEL_ACCELERATION_STRUCTURE_READ); } params.add_buffer(buffer_id, BufferUsage::TOP_LEVEL_ACCELERATION_STRUCTURE_WRITE); params.add_buffer(scratch_buffer_id, BufferUsage::ACCELERATION_STRUCTURE_BUILD_SCRATCH); }, move |params, cmd| { let accel = params.get_buffer_accel(buffer_id); let scratch_buffer = params.get_buffer(scratch_buffer_id); let scratch_buffer_address = unsafe { context.device.get_buffer_device_address_helper(scratch_buffer) }; let build_info = vk::AccelerationStructureBuildGeometryInfoKHR::builder() .ty(vk::AccelerationStructureTypeKHR::TOP_LEVEL) .flags(vk::BuildAccelerationStructureFlagsKHR::PREFER_FAST_TRACE) .mode(vk::BuildAccelerationStructureModeKHR::BUILD) .dst_acceleration_structure(accel) .p_geometries(Some(slice::from_ref(&accel_geometry)), None) .scratch_data(vk::DeviceOrHostAddressKHR { device_address: scratch_buffer_address, }); let build_range_info = vk::AccelerationStructureBuildRangeInfoKHR { primitive_count: instance_count, primitive_offset: 0, first_vertex: 0, transform_offset: 0, }; unsafe { context.device.cmd_build_acceleration_structures_khr( cmd, slice::from_ref(&build_info), &[&build_range_info], ) }; }, ); buffer_id } }) .await; TopLevelAccel { buffer_id } } pub fn top_level_buffer_id(&self) -> BufferId { self.top_level_accel.buffer_id } pub fn declare_parameters(&self, params: &mut RenderParameterDeclaration) { for bottom_level_accel in self.cluster_accel.iter() { params.add_buffer( bottom_level_accel.buffer_id, BufferUsage::RAY_TRACING_ACCELERATION_STRUCTURE, ); } params.add_buffer( self.top_level_accel.buffer_id, BufferUsage::RAY_TRACING_ACCELERATION_STRUCTURE, ); } }
rust
MIT
42fc4b496cce21e907eca7112e6d6334d35fc41a
2026-01-04T20:23:56.526296Z
false
sjb3d/caldera
https://github.com/sjb3d/caldera/blob/42fc4b496cce21e907eca7112e6d6334d35fc41a/caldera/examples/path_tracer/spectrum.rs
caldera/examples/path_tracer/spectrum.rs
use caldera::prelude::*; use std::{ default::Default, ops::{Add, Mul}, }; // reference: http://cvrl.ioo.ucl.ac.uk/ (CIE 1931 2 degree XYZ CMFs) const CIE_WAVELENGTH_BASE: f32 = 360.0; const CIE_WAVELENGTH_STEP_SIZE: f32 = 1.0; macro_rules! cie_samples { ($(($x:literal, $y:literal, $z:literal)),+) => { [ $( Vec3::new($x, $y, $z), )+ ] } } #[allow(clippy::excessive_precision)] const CIE_SAMPLES: &[Vec3] = &cie_samples!( (0.000129900000, 0.000003917000, 0.000606100000), (0.000145847000, 0.000004393581, 0.000680879200), (0.000163802100, 0.000004929604, 0.000765145600), (0.000184003700, 0.000005532136, 0.000860012400), (0.000206690200, 0.000006208245, 0.000966592800), (0.000232100000, 0.000006965000, 0.001086000000), (0.000260728000, 0.000007813219, 0.001220586000), (0.000293075000, 0.000008767336, 0.001372729000), (0.000329388000, 0.000009839844, 0.001543579000), (0.000369914000, 0.000011043230, 0.001734286000), (0.000414900000, 0.000012390000, 0.001946000000), (0.000464158700, 0.000013886410, 0.002177777000), (0.000518986000, 0.000015557280, 0.002435809000), (0.000581854000, 0.000017442960, 0.002731953000), (0.000655234700, 0.000019583750, 0.003078064000), (0.000741600000, 0.000022020000, 0.003486000000), (0.000845029600, 0.000024839650, 0.003975227000), (0.000964526800, 0.000028041260, 0.004540880000), (0.001094949000, 0.000031531040, 0.005158320000), (0.001231154000, 0.000035215210, 0.005802907000), (0.001368000000, 0.000039000000, 0.006450001000), (0.001502050000, 0.000042826400, 0.007083216000), (0.001642328000, 0.000046914600, 0.007745488000), (0.001802382000, 0.000051589600, 0.008501152000), (0.001995757000, 0.000057176400, 0.009414544000), (0.002236000000, 0.000064000000, 0.010549990000), (0.002535385000, 0.000072344210, 0.011965800000), (0.002892603000, 0.000082212240, 0.013655870000), (0.003300829000, 0.000093508160, 0.015588050000), (0.003753236000, 0.000106136100, 0.017730150000), (0.004243000000, 0.000120000000, 0.020050010000), (0.004762389000, 0.000134984000, 0.022511360000), (0.005330048000, 0.000151492000, 0.025202880000), (0.005978712000, 0.000170208000, 0.028279720000), (0.006741117000, 0.000191816000, 0.031897040000), (0.007650000000, 0.000217000000, 0.036210000000), (0.008751373000, 0.000246906700, 0.041437710000), (0.010028880000, 0.000281240000, 0.047503720000), (0.011421700000, 0.000318520000, 0.054119880000), (0.012869010000, 0.000357266700, 0.060998030000), (0.014310000000, 0.000396000000, 0.067850010000), (0.015704430000, 0.000433714700, 0.074486320000), (0.017147440000, 0.000473024000, 0.081361560000), (0.018781220000, 0.000517876000, 0.089153640000), (0.020748010000, 0.000572218700, 0.098540480000), (0.023190000000, 0.000640000000, 0.110200000000), (0.026207360000, 0.000724560000, 0.124613300000), (0.029782480000, 0.000825500000, 0.141701700000), (0.033880920000, 0.000941160000, 0.161303500000), (0.038468240000, 0.001069880000, 0.183256800000), (0.043510000000, 0.001210000000, 0.207400000000), (0.048995600000, 0.001362091000, 0.233692100000), (0.055022600000, 0.001530752000, 0.262611400000), (0.061718800000, 0.001720368000, 0.294774600000), (0.069212000000, 0.001935323000, 0.330798500000), (0.077630000000, 0.002180000000, 0.371300000000), (0.086958110000, 0.002454800000, 0.416209100000), (0.097176720000, 0.002764000000, 0.465464200000), (0.108406300000, 0.003117800000, 0.519694800000), (0.120767200000, 0.003526400000, 0.579530300000), (0.134380000000, 0.004000000000, 0.645600000000), (0.149358200000, 0.004546240000, 0.718483800000), (0.165395700000, 0.005159320000, 0.796713300000), (0.181983100000, 0.005829280000, 0.877845900000), (0.198611000000, 0.006546160000, 0.959439000000), (0.214770000000, 0.007300000000, 1.039050100000), (0.230186800000, 0.008086507000, 1.115367300000), (0.244879700000, 0.008908720000, 1.188497100000), (0.258777300000, 0.009767680000, 1.258123300000), (0.271807900000, 0.010664430000, 1.323929600000), (0.283900000000, 0.011600000000, 1.385600000000), (0.294943800000, 0.012573170000, 1.442635200000), (0.304896500000, 0.013582720000, 1.494803500000), (0.313787300000, 0.014629680000, 1.542190300000), (0.321645400000, 0.015715090000, 1.584880700000), (0.328500000000, 0.016840000000, 1.622960000000), (0.334351300000, 0.018007360000, 1.656404800000), (0.339210100000, 0.019214480000, 1.685295900000), (0.343121300000, 0.020453920000, 1.709874500000), (0.346129600000, 0.021718240000, 1.730382100000), (0.348280000000, 0.023000000000, 1.747060000000), (0.349599900000, 0.024294610000, 1.760044600000), (0.350147400000, 0.025610240000, 1.769623300000), (0.350013000000, 0.026958570000, 1.776263700000), (0.349287000000, 0.028351250000, 1.780433400000), (0.348060000000, 0.029800000000, 1.782600000000), (0.346373300000, 0.031310830000, 1.782968200000), (0.344262400000, 0.032883680000, 1.781699800000), (0.341808800000, 0.034521120000, 1.779198200000), (0.339094100000, 0.036225710000, 1.775867100000), (0.336200000000, 0.038000000000, 1.772110000000), (0.333197700000, 0.039846670000, 1.768258900000), (0.330041100000, 0.041768000000, 1.764039000000), (0.326635700000, 0.043766000000, 1.758943800000), (0.322886800000, 0.045842670000, 1.752466300000), (0.318700000000, 0.048000000000, 1.744100000000), (0.314025100000, 0.050243680000, 1.733559500000), (0.308884000000, 0.052573040000, 1.720858100000), (0.303290400000, 0.054980560000, 1.705936900000), (0.297257900000, 0.057458720000, 1.688737200000), (0.290800000000, 0.060000000000, 1.669200000000), (0.283970100000, 0.062601970000, 1.647528700000), (0.276721400000, 0.065277520000, 1.623412700000), (0.268917800000, 0.068042080000, 1.596022300000), (0.260422700000, 0.070911090000, 1.564528000000), (0.251100000000, 0.073900000000, 1.528100000000), (0.240847500000, 0.077016000000, 1.486111400000), (0.229851200000, 0.080266400000, 1.439521500000), (0.218407200000, 0.083666800000, 1.389879900000), (0.206811500000, 0.087232800000, 1.338736200000), (0.195360000000, 0.090980000000, 1.287640000000), (0.184213600000, 0.094917550000, 1.237422300000), (0.173327300000, 0.099045840000, 1.187824300000), (0.162688100000, 0.103367400000, 1.138761100000), (0.152283300000, 0.107884600000, 1.090148000000), (0.142100000000, 0.112600000000, 1.041900000000), (0.132178600000, 0.117532000000, 0.994197600000), (0.122569600000, 0.122674400000, 0.947347300000), (0.113275200000, 0.127992800000, 0.901453100000), (0.104297900000, 0.133452800000, 0.856619300000), (0.095640000000, 0.139020000000, 0.812950100000), (0.087299550000, 0.144676400000, 0.770517300000), (0.079308040000, 0.150469300000, 0.729444800000), (0.071717760000, 0.156461900000, 0.689913600000), (0.064580990000, 0.162717700000, 0.652104900000), (0.057950010000, 0.169300000000, 0.616200000000), (0.051862110000, 0.176243100000, 0.582328600000), (0.046281520000, 0.183558100000, 0.550416200000), (0.041150880000, 0.191273500000, 0.520337600000), (0.036412830000, 0.199418000000, 0.491967300000), (0.032010000000, 0.208020000000, 0.465180000000), (0.027917200000, 0.217119900000, 0.439924600000), (0.024144400000, 0.226734500000, 0.416183600000), (0.020687000000, 0.236857100000, 0.393882200000), (0.017540400000, 0.247481200000, 0.372945900000), (0.014700000000, 0.258600000000, 0.353300000000), (0.012161790000, 0.270184900000, 0.334857800000), (0.009919960000, 0.282293900000, 0.317552100000), (0.007967240000, 0.295050500000, 0.301337500000), (0.006296346000, 0.308578000000, 0.286168600000), (0.004900000000, 0.323000000000, 0.272000000000), (0.003777173000, 0.338402100000, 0.258817100000), (0.002945320000, 0.354685800000, 0.246483800000), (0.002424880000, 0.371698600000, 0.234771800000), (0.002236293000, 0.389287500000, 0.223453300000), (0.002400000000, 0.407300000000, 0.212300000000), (0.002925520000, 0.425629900000, 0.201169200000), (0.003836560000, 0.444309600000, 0.190119600000), (0.005174840000, 0.463394400000, 0.179225400000), (0.006982080000, 0.482939500000, 0.168560800000), (0.009300000000, 0.503000000000, 0.158200000000), (0.012149490000, 0.523569300000, 0.148138300000), (0.015535880000, 0.544512000000, 0.138375800000), (0.019477520000, 0.565690000000, 0.128994200000), (0.023992770000, 0.586965300000, 0.120075100000), (0.029100000000, 0.608200000000, 0.111700000000), (0.034814850000, 0.629345600000, 0.103904800000), (0.041120160000, 0.650306800000, 0.096667480000), (0.047985040000, 0.670875200000, 0.089982720000), (0.055378610000, 0.690842400000, 0.083845310000), (0.063270000000, 0.710000000000, 0.078249990000), (0.071635010000, 0.728185200000, 0.073208990000), (0.080462240000, 0.745463600000, 0.068678160000), (0.089739960000, 0.761969400000, 0.064567840000), (0.099456450000, 0.777836800000, 0.060788350000), (0.109600000000, 0.793200000000, 0.057250010000), (0.120167400000, 0.808110400000, 0.053904350000), (0.131114500000, 0.822496200000, 0.050746640000), (0.142367900000, 0.836306800000, 0.047752760000), (0.153854200000, 0.849491600000, 0.044898590000), (0.165500000000, 0.862000000000, 0.042160000000), (0.177257100000, 0.873810800000, 0.039507280000), (0.189140000000, 0.884962400000, 0.036935640000), (0.201169400000, 0.895493600000, 0.034458360000), (0.213365800000, 0.905443200000, 0.032088720000), (0.225749900000, 0.914850100000, 0.029840000000), (0.238320900000, 0.923734800000, 0.027711810000), (0.251066800000, 0.932092400000, 0.025694440000), (0.263992200000, 0.939922600000, 0.023787160000), (0.277101700000, 0.947225200000, 0.021989250000), (0.290400000000, 0.954000000000, 0.020300000000), (0.303891200000, 0.960256100000, 0.018718050000), (0.317572600000, 0.966007400000, 0.017240360000), (0.331438400000, 0.971260600000, 0.015863640000), (0.345482800000, 0.976022500000, 0.014584610000), (0.359700000000, 0.980300000000, 0.013400000000), (0.374083900000, 0.984092400000, 0.012307230000), (0.388639600000, 0.987418200000, 0.011301880000), (0.403378400000, 0.990312800000, 0.010377920000), (0.418311500000, 0.992811600000, 0.009529306000), (0.433449900000, 0.994950100000, 0.008749999000), (0.448795300000, 0.996710800000, 0.008035200000), (0.464336000000, 0.998098300000, 0.007381600000), (0.480064000000, 0.999112000000, 0.006785400000), (0.495971300000, 0.999748200000, 0.006242800000), (0.512050100000, 1.000000000000, 0.005749999000), (0.528295900000, 0.999856700000, 0.005303600000), (0.544691600000, 0.999304600000, 0.004899800000), (0.561209400000, 0.998325500000, 0.004534200000), (0.577821500000, 0.996898700000, 0.004202400000), (0.594500000000, 0.995000000000, 0.003900000000), (0.611220900000, 0.992600500000, 0.003623200000), (0.627975800000, 0.989742600000, 0.003370600000), (0.644760200000, 0.986444400000, 0.003141400000), (0.661569700000, 0.982724100000, 0.002934800000), (0.678400000000, 0.978600000000, 0.002749999000), (0.695239200000, 0.974083700000, 0.002585200000), (0.712058600000, 0.969171200000, 0.002438600000), (0.728828400000, 0.963856800000, 0.002309400000), (0.745518800000, 0.958134900000, 0.002196800000), (0.762100000000, 0.952000000000, 0.002100000000), (0.778543200000, 0.945450400000, 0.002017733000), (0.794825600000, 0.938499200000, 0.001948200000), (0.810926400000, 0.931162800000, 0.001889800000), (0.826824800000, 0.923457600000, 0.001840933000), (0.842500000000, 0.915400000000, 0.001800000000), (0.857932500000, 0.907006400000, 0.001766267000), (0.873081600000, 0.898277200000, 0.001737800000), (0.887894400000, 0.889204800000, 0.001711200000), (0.902318100000, 0.879781600000, 0.001683067000), (0.916300000000, 0.870000000000, 0.001650001000), (0.929799500000, 0.859861300000, 0.001610133000), (0.942798400000, 0.849392000000, 0.001564400000), (0.955277600000, 0.838622000000, 0.001513600000), (0.967217900000, 0.827581300000, 0.001458533000), (0.978600000000, 0.816300000000, 0.001400000000), (0.989385600000, 0.804794700000, 0.001336667000), (0.999548800000, 0.793082000000, 0.001270000000), (1.009089200000, 0.781192000000, 0.001205000000), (1.018006400000, 0.769154700000, 0.001146667000), (1.026300000000, 0.757000000000, 0.001100000000), (1.033982700000, 0.744754100000, 0.001068800000), (1.040986000000, 0.732422400000, 0.001049400000), (1.047188000000, 0.720003600000, 0.001035600000), (1.052466700000, 0.707496500000, 0.001021200000), (1.056700000000, 0.694900000000, 0.001000000000), (1.059794400000, 0.682219200000, 0.000968640000), (1.061799200000, 0.669471600000, 0.000929920000), (1.062806800000, 0.656674400000, 0.000886880000), (1.062909600000, 0.643844800000, 0.000842560000), (1.062200000000, 0.631000000000, 0.000800000000), (1.060735200000, 0.618155500000, 0.000760960000), (1.058443600000, 0.605314400000, 0.000723680000), (1.055224400000, 0.592475600000, 0.000685920000), (1.050976800000, 0.579637900000, 0.000645440000), (1.045600000000, 0.566800000000, 0.000600000000), (1.039036900000, 0.553961100000, 0.000547866700), (1.031360800000, 0.541137200000, 0.000491600000), (1.022666200000, 0.528352800000, 0.000435400000), (1.013047700000, 0.515632300000, 0.000383466700), (1.002600000000, 0.503000000000, 0.000340000000), (0.991367500000, 0.490468800000, 0.000307253300), (0.979331400000, 0.478030400000, 0.000283160000), (0.966491600000, 0.465677600000, 0.000265440000), (0.952847900000, 0.453403200000, 0.000251813300), (0.938400000000, 0.441200000000, 0.000240000000), (0.923194000000, 0.429080000000, 0.000229546700), (0.907244000000, 0.417036000000, 0.000220640000), (0.890502000000, 0.405032000000, 0.000211960000), (0.872920000000, 0.393032000000, 0.000202186700), (0.854449900000, 0.381000000000, 0.000190000000), (0.835084000000, 0.368918400000, 0.000174213300), (0.814946000000, 0.356827200000, 0.000155640000), (0.794186000000, 0.344776800000, 0.000135960000), (0.772954000000, 0.332817600000, 0.000116853300), (0.751400000000, 0.321000000000, 0.000100000000), (0.729583600000, 0.309338100000, 0.000086133330), (0.707588800000, 0.297850400000, 0.000074600000), (0.685602200000, 0.286593600000, 0.000065000000), (0.663810400000, 0.275624500000, 0.000056933330), (0.642400000000, 0.265000000000, 0.000049999990), (0.621514900000, 0.254763200000, 0.000044160000), (0.601113800000, 0.244889600000, 0.000039480000), (0.581105200000, 0.235334400000, 0.000035720000), (0.561397700000, 0.226052800000, 0.000032640000), (0.541900000000, 0.217000000000, 0.000030000000), (0.522599500000, 0.208161600000, 0.000027653330), (0.503546400000, 0.199548800000, 0.000025560000), (0.484743600000, 0.191155200000, 0.000023640000), (0.466193900000, 0.182974400000, 0.000021813330), (0.447900000000, 0.175000000000, 0.000020000000), (0.429861300000, 0.167223500000, 0.000018133330), (0.412098000000, 0.159646400000, 0.000016200000), (0.394644000000, 0.152277600000, 0.000014200000), (0.377533300000, 0.145125900000, 0.000012133330), (0.360800000000, 0.138200000000, 0.000010000000), (0.344456300000, 0.131500300000, 0.000007733333), (0.328516800000, 0.125024800000, 0.000005400000), (0.313019200000, 0.118779200000, 0.000003200000), (0.298001100000, 0.112769100000, 0.000001333333), (0.283500000000, 0.107000000000, 0.000000000000), (0.269544800000, 0.101476200000, 0.000000000000), (0.256118400000, 0.096188640000, 0.000000000000), (0.243189600000, 0.091122960000, 0.000000000000), (0.230727200000, 0.086264850000, 0.000000000000), (0.218700000000, 0.081600000000, 0.000000000000), (0.207097100000, 0.077120640000, 0.000000000000), (0.195923200000, 0.072825520000, 0.000000000000), (0.185170800000, 0.068710080000, 0.000000000000), (0.174832300000, 0.064769760000, 0.000000000000), (0.164900000000, 0.061000000000, 0.000000000000), (0.155366700000, 0.057396210000, 0.000000000000), (0.146230000000, 0.053955040000, 0.000000000000), (0.137490000000, 0.050673760000, 0.000000000000), (0.129146700000, 0.047549650000, 0.000000000000), (0.121200000000, 0.044580000000, 0.000000000000), (0.113639700000, 0.041758720000, 0.000000000000), (0.106465000000, 0.039084960000, 0.000000000000), (0.099690440000, 0.036563840000, 0.000000000000), (0.093330610000, 0.034200480000, 0.000000000000), (0.087400000000, 0.032000000000, 0.000000000000), (0.081900960000, 0.029962610000, 0.000000000000), (0.076804280000, 0.028076640000, 0.000000000000), (0.072077120000, 0.026329360000, 0.000000000000), (0.067686640000, 0.024708050000, 0.000000000000), (0.063600000000, 0.023200000000, 0.000000000000), (0.059806850000, 0.021800770000, 0.000000000000), (0.056282160000, 0.020501120000, 0.000000000000), (0.052971040000, 0.019281080000, 0.000000000000), (0.049818610000, 0.018120690000, 0.000000000000), (0.046770000000, 0.017000000000, 0.000000000000), (0.043784050000, 0.015903790000, 0.000000000000), (0.040875360000, 0.014837180000, 0.000000000000), (0.038072640000, 0.013810680000, 0.000000000000), (0.035404610000, 0.012834780000, 0.000000000000), (0.032900000000, 0.011920000000, 0.000000000000), (0.030564190000, 0.011068310000, 0.000000000000), (0.028380560000, 0.010273390000, 0.000000000000), (0.026344840000, 0.009533311000, 0.000000000000), (0.024452750000, 0.008846157000, 0.000000000000), (0.022700000000, 0.008210000000, 0.000000000000), (0.021084290000, 0.007623781000, 0.000000000000), (0.019599880000, 0.007085424000, 0.000000000000), (0.018237320000, 0.006591476000, 0.000000000000), (0.016987170000, 0.006138485000, 0.000000000000), (0.015840000000, 0.005723000000, 0.000000000000), (0.014790640000, 0.005343059000, 0.000000000000), (0.013831320000, 0.004995796000, 0.000000000000), (0.012948680000, 0.004676404000, 0.000000000000), (0.012129200000, 0.004380075000, 0.000000000000), (0.011359160000, 0.004102000000, 0.000000000000), (0.010629350000, 0.003838453000, 0.000000000000), (0.009938846000, 0.003589099000, 0.000000000000), (0.009288422000, 0.003354219000, 0.000000000000), (0.008678854000, 0.003134093000, 0.000000000000), (0.008110916000, 0.002929000000, 0.000000000000), (0.007582388000, 0.002738139000, 0.000000000000), (0.007088746000, 0.002559876000, 0.000000000000), (0.006627313000, 0.002393244000, 0.000000000000), (0.006195408000, 0.002237275000, 0.000000000000), (0.005790346000, 0.002091000000, 0.000000000000), (0.005409826000, 0.001953587000, 0.000000000000), (0.005052583000, 0.001824580000, 0.000000000000), (0.004717512000, 0.001703580000, 0.000000000000), (0.004403507000, 0.001590187000, 0.000000000000), (0.004109457000, 0.001484000000, 0.000000000000), (0.003833913000, 0.001384496000, 0.000000000000), (0.003575748000, 0.001291268000, 0.000000000000), (0.003334342000, 0.001204092000, 0.000000000000), (0.003109075000, 0.001122744000, 0.000000000000), (0.002899327000, 0.001047000000, 0.000000000000), (0.002704348000, 0.000976589600, 0.000000000000), (0.002523020000, 0.000911108800, 0.000000000000), (0.002354168000, 0.000850133200, 0.000000000000), (0.002196616000, 0.000793238400, 0.000000000000), (0.002049190000, 0.000740000000, 0.000000000000), (0.001910960000, 0.000690082700, 0.000000000000), (0.001781438000, 0.000643310000, 0.000000000000), (0.001660110000, 0.000599496000, 0.000000000000), (0.001546459000, 0.000558454700, 0.000000000000), (0.001439971000, 0.000520000000, 0.000000000000), (0.001340042000, 0.000483913600, 0.000000000000), (0.001246275000, 0.000450052800, 0.000000000000), (0.001158471000, 0.000418345200, 0.000000000000), (0.001076430000, 0.000388718400, 0.000000000000), (0.000999949300, 0.000361100000, 0.000000000000), (0.000928735800, 0.000335383500, 0.000000000000), (0.000862433200, 0.000311440400, 0.000000000000), (0.000800750300, 0.000289165600, 0.000000000000), (0.000743396000, 0.000268453900, 0.000000000000), (0.000690078600, 0.000249200000, 0.000000000000), (0.000640515600, 0.000231301900, 0.000000000000), (0.000594502100, 0.000214685600, 0.000000000000), (0.000551864600, 0.000199288400, 0.000000000000), (0.000512429000, 0.000185047500, 0.000000000000), (0.000476021300, 0.000171900000, 0.000000000000), (0.000442453600, 0.000159778100, 0.000000000000), (0.000411511700, 0.000148604400, 0.000000000000), (0.000382981400, 0.000138301600, 0.000000000000), (0.000356649100, 0.000128792500, 0.000000000000), (0.000332301100, 0.000120000000, 0.000000000000), (0.000309758600, 0.000111859500, 0.000000000000), (0.000288887100, 0.000104322400, 0.000000000000), (0.000269539400, 0.000097335600, 0.000000000000), (0.000251568200, 0.000090845870, 0.000000000000), (0.000234826100, 0.000084800000, 0.000000000000), (0.000219171000, 0.000079146670, 0.000000000000), (0.000204525800, 0.000073858000, 0.000000000000), (0.000190840500, 0.000068916000, 0.000000000000), (0.000178065400, 0.000064302670, 0.000000000000), (0.000166150500, 0.000060000000, 0.000000000000), (0.000155023600, 0.000055981870, 0.000000000000), (0.000144621900, 0.000052225600, 0.000000000000), (0.000134909800, 0.000048718400, 0.000000000000), (0.000125852000, 0.000045447470, 0.000000000000), (0.000117413000, 0.000042400000, 0.000000000000), (0.000109551500, 0.000039561040, 0.000000000000), (0.000102224500, 0.000036915120, 0.000000000000), (0.000095394450, 0.000034448680, 0.000000000000), (0.000089023900, 0.000032148160, 0.000000000000), (0.000083075270, 0.000030000000, 0.000000000000), (0.000077512690, 0.000027991250, 0.000000000000), (0.000072313040, 0.000026113560, 0.000000000000), (0.000067457780, 0.000024360240, 0.000000000000), (0.000062928440, 0.000022724610, 0.000000000000), (0.000058706520, 0.000021200000, 0.000000000000), (0.000054770280, 0.000019778550, 0.000000000000), (0.000051099180, 0.000018452850, 0.000000000000), (0.000047676540, 0.000017216870, 0.000000000000), (0.000044485670, 0.000016064590, 0.000000000000), (0.000041509940, 0.000014990000, 0.000000000000), (0.000038733240, 0.000013987280, 0.000000000000), (0.000036142030, 0.000013051550, 0.000000000000), (0.000033723520, 0.000012178180, 0.000000000000), (0.000031464870, 0.000011362540, 0.000000000000), (0.000029353260, 0.000010600000, 0.000000000000), (0.000027375730, 0.000009885877, 0.000000000000), (0.000025524330, 0.000009217304, 0.000000000000), (0.000023793760, 0.000008592362, 0.000000000000), (0.000022178700, 0.000008009133, 0.000000000000), (0.000020673830, 0.000007465700, 0.000000000000), (0.000019272260, 0.000006959567, 0.000000000000), (0.000017966400, 0.000006487995, 0.000000000000), (0.000016749910, 0.000006048699, 0.000000000000), (0.000015616480, 0.000005639396, 0.000000000000), (0.000014559770, 0.000005257800, 0.000000000000), (0.000013573870, 0.000004901771, 0.000000000000), (0.000012654360, 0.000004569720, 0.000000000000), (0.000011797230, 0.000004260194, 0.000000000000), (0.000010998440, 0.000003971739, 0.000000000000), (0.000010253980, 0.000003702900, 0.000000000000), (0.000009559646, 0.000003452163, 0.000000000000), (0.000008912044, 0.000003218302, 0.000000000000), (0.000008308358, 0.000003000300, 0.000000000000), (0.000007745769, 0.000002797139, 0.000000000000), (0.000007221456, 0.000002607800, 0.000000000000), (0.000006732475, 0.000002431220, 0.000000000000), (0.000006276423, 0.000002266531, 0.000000000000), (0.000005851304, 0.000002113013, 0.000000000000), (0.000005455118, 0.000001969943, 0.000000000000), (0.000005085868, 0.000001836600, 0.000000000000), (0.000004741466, 0.000001712230, 0.000000000000), (0.000004420236, 0.000001596228, 0.000000000000), (0.000004120783, 0.000001488090, 0.000000000000), (0.000003841716, 0.000001387314, 0.000000000000), (0.000003581652, 0.000001293400, 0.000000000000), (0.000003339127, 0.000001205820, 0.000000000000), (0.000003112949, 0.000001124143, 0.000000000000), (0.000002902121, 0.000001048009, 0.000000000000), (0.000002705645, 0.000000977058, 0.000000000000), (0.000002522525, 0.000000910930, 0.000000000000), (0.000002351726, 0.000000849251, 0.000000000000), (0.000002192415, 0.000000791721, 0.000000000000), (0.000002043902, 0.000000738090, 0.000000000000), (0.000001905497, 0.000000688110, 0.000000000000), (0.000001776509, 0.000000641530, 0.000000000000), (0.000001656215, 0.000000598090, 0.000000000000), (0.000001544022, 0.000000557575, 0.000000000000), (0.000001439440, 0.000000519808, 0.000000000000), (0.000001341977, 0.000000484612, 0.000000000000), (0.000001251141, 0.000000451810, 0.000000000000) ); const CIE_SAMPLE_NORM: f32 = 1.0 / 106.856834; pub struct RegularlySampledIlluminant { pub samples: &'static [f32], pub sample_norm: f32, pub wavelength_base: f32, pub wavelength_step_size: f32, } impl RegularlySampledIlluminant { pub fn iter(self) -> impl Iterator<Item = (f32, f32)> { self.samples.iter().enumerate().map(move |(i, v)| { ( self.wavelength_base + self.wavelength_step_size * (i as f32), v * self.sample_norm, ) }) } } pub const E_ILLUMINANT: RegularlySampledIlluminant = RegularlySampledIlluminant { samples: &[1.0, 1.0], sample_norm: 1.0, wavelength_base: 300.0, wavelength_step_size: 500.0, }; // from https://en.wikipedia.org/wiki/Illuminant_D65 #[allow(clippy::excessive_precision)] const D65_ILLUMINANT_SAMPLES: &[f32] = &[ 0.034100, 3.294500, 20.236000, 37.053500, 39.948800, 44.911700, 46.638300, 52.089100, 49.975500, 54.648200, 82.754900, 91.486000, 93.431800, 86.682300, 104.865000, 117.008000, 117.812000, 114.861000, 115.923000, 108.811000, 109.354000, 107.802000, 104.790000, 107.689000, 104.405000, 104.046000, 100.000000, 96.334200, 95.788000, 88.685600, 90.006200, 89.599100, 87.698700, 83.288600, 83.699200, 80.026800, 80.214600, 82.277800, 78.284200, 69.721300, 71.609100, 74.349000, 61.604000, 69.885600, 75.087000, 63.592700, 46.418200, 66.805400, 63.382800, ]; pub const D65_ILLUMINANT: RegularlySampledIlluminant = RegularlySampledIlluminant { samples: D65_ILLUMINANT_SAMPLES, sample_norm: 0.01, wavelength_base: 300.0, wavelength_step_size: 10.0, }; // from https://www.rit.edu/cos/colorscience/rc_useful_data.php const F10_ILLUMINANT_SAMPLES: &[f32] = &[ 1.11, 0.63, 0.62, 0.57, 1.48, 12.16, 2.12, 2.7, 3.74, 5.14, 6.75, 34.39, 14.86, 10.4, 10.76, 10.67, 10.11, 9.27, 8.29, 7.29, 7.91, 16.64, 16.73, 10.44, 5.94, 3.34, 2.35, 1.88, 1.59, 1.47, 1.8, 5.71, 40.98, 73.69, 33.61, 8.24, 3.38, 2.47, 2.14, 4.86, 11.45, 14.79, 12.16, 8.97, 6.52, 8.81, 44.12, 34.55, 12.09, 12.15, 10.52, 4.43, 1.95, 2.19, 3.19, 2.77, 2.29, 2.0, 1.52, 1.35, 1.47, 1.79, 1.74, 1.02, 1.14, 3.32, 4.49, 2.05, 0.49, 0.24, 0.21, 0.21, 0.24, 0.24, 0.21, 0.17, 0.21, 0.22, 0.17, 0.12, 0.09, ]; pub const F10_ILLUMINANT: RegularlySampledIlluminant = RegularlySampledIlluminant { samples: F10_ILLUMINANT_SAMPLES, sample_norm: 0.1, wavelength_base: 380.0, wavelength_step_size: 5.0, }; pub trait Sweep { type Item; fn next(&mut self, input: f32) -> Self::Item; #[allow(dead_code)] fn map<U, F>(self, f: F) -> SweepMap<Self::Item, U, Self, F> where Self: Sized, F: Fn(Self::Item) -> U, { SweepMap { a: self, f } } #[allow(dead_code)] fn product<U>(self, other: U) -> SweepProduct<Self::Item, Self, U> where Self: Sized, U: Sweep<Item = Self::Item>, Self::Item: Mul<Output = Self::Item>, { SweepProduct { a: self, b: other } } } impl<F, T> Sweep for F where F: Fn(f32) -> T, { type Item = T; fn next(&mut self, input: f32) -> Self::Item { self(input) } } pub struct SampleSweep<T, I> where I: Iterator<Item = (f32, T)>, T: Copy + Add<Output = T> + Mul<f32, Output = T> + Default, { iter: I, prev_sample: Option<(f32, T)>, next_sample: Option<(f32, T)>, prev_input: Option<f32>, } impl<T, I> SampleSweep<T, I> where I: Iterator<Item = (f32, T)>, T: Copy + Add<Output = T> + Mul<f32, Output = T> + Default, { fn new(iter: I) -> Self { Self { iter, prev_sample: None, next_sample: None, prev_input: None, } } } impl<T, I> Sweep for SampleSweep<T, I> where I: Iterator<Item = (f32, T)>, T: Copy + Add<Output = T> + Mul<f32, Output = T> + Default, { type Item = T; fn next(&mut self, input: f32) -> T { if let Some(prev_input) = self.prev_input { assert!( prev_input <= input, "sweep inputs must never decrease between calls to next()" ); } else { self.prev_sample = self.iter.next(); self.next_sample = self.iter.next(); } self.prev_input = Some(input); while let (Some(prev_sample), Some(next_sample)) = (self.prev_sample, self.next_sample) { if input < prev_sample.0 { break; } if input < next_sample.0 { let t = (input - prev_sample.0) / (next_sample.0 - prev_sample.0); return prev_sample.1 * (1.0 - t) + next_sample.1 * t; } self.prev_sample = self.next_sample; self.next_sample = self.iter.next(); } T::default() } } pub struct SweepMap<T, U, A, F> where A: Sweep<Item = T>, F: Fn(T) -> U, { a: A, f: F, } impl<T, U, A, F> Sweep for SweepMap<T, U, A, F> where A: Sweep<Item = T>, F: Fn(T) -> U, { type Item = U; fn next(&mut self, input: f32) -> U { let t = self.a.next(input); (self.f)(t) } } pub struct SweepProduct<T, A, B> where A: Sweep<Item = T>, B: Sweep<Item = T>, T: Mul<Output = T>, { a: A, b: B, } impl<T, A, B> Sweep for SweepProduct<T, A, B> where A: Sweep<Item = T>, B: Sweep<Item = T>, T: Mul<Output = T>, { type Item = T; fn next(&mut self, input: f32) -> T { self.a.next(input) * self.b.next(input) } } pub trait IntoSweep { type Item; type IntoType: Sweep<Item = Self::Item>; fn into_sweep(self) -> Self::IntoType; } impl<T, I> IntoSweep for I where I: Iterator<Item = (f32, T)>, T: Copy + Add<Output = T> + Mul<f32, Output = T> + Default, { type Item = T; type IntoType = SampleSweep<T, Self>; fn into_sweep(self) -> Self::IntoType { SampleSweep::new(self) } } fn xyz_matching_sample_iter() -> impl Iterator<Item = (f32, Vec3)> { CIE_SAMPLES.iter().enumerate().map(|(i, v)| { ( CIE_WAVELENGTH_BASE + CIE_WAVELENGTH_STEP_SIZE * (i as f32), *v * CIE_SAMPLE_NORM, ) }) } pub fn xyz_matching_sweep() -> impl Sweep<Item = Vec3> { xyz_matching_sample_iter().into_sweep() } pub fn xyz_from_spectral_reflectance_sweep( mut reflectance: impl Sweep<Item = f32>, mut illuminant: impl Sweep<Item = f32>, ) -> Vec3 { let mut sum = Vec3::zero(); let mut n = 0.0; for (wavelength, value) in xyz_matching_sample_iter() { let illum = illuminant.next(wavelength); sum += value * (illum * reflectance.next(wavelength)); n += value.y * illum; } sum * (CIE_WAVELENGTH_STEP_SIZE / n) } pub struct ConductorSample { pub wavelength: f32, pub eta: f32, pub k: f32, } macro_rules! conductor_samples {
rust
MIT
42fc4b496cce21e907eca7112e6d6334d35fc41a
2026-01-04T20:23:56.526296Z
true
sjb3d/caldera
https://github.com/sjb3d/caldera/blob/42fc4b496cce21e907eca7112e6d6334d35fc41a/caldera/examples/test_ray_tracing/loader.rs
caldera/examples/test_ray_tracing/loader.rs
use arrayvec::ArrayVec; use caldera::prelude::*; use ply_rs::{parser, ply}; use spark::vk; use std::{fs, io, mem, path::Path}; #[derive(Clone, Copy)] struct PlyVertex { pos: Vec3, } #[derive(Clone, Copy)] struct PlyFace { indices: UVec3, } impl ply::PropertyAccess for PlyVertex { fn new() -> Self { Self { pos: Vec3::zero() } } fn set_property(&mut self, key: String, property: ply::Property) { match (key.as_ref(), property) { ("x", ply::Property::Float(v)) => self.pos.x = v, ("y", ply::Property::Float(v)) => self.pos.y = v, ("z", ply::Property::Float(v)) => self.pos.z = v, _ => {} } } } impl ply::PropertyAccess for PlyFace { fn new() -> Self { Self { indices: UVec3::zero() } } fn set_property(&mut self, key: String, property: ply::Property) { match (key.as_ref(), property) { ("vertex_indices", ply::Property::ListInt(v)) => { assert_eq!(v.len(), 3); for (dst, src) in self.indices.as_mut_slice().iter_mut().zip(v.iter()) { *dst = *src as u32; } } (k, _) => panic!("unknown key {}", k), } } } pub type PositionData = Vec3; pub type AttributeData = Vec3; pub type InstanceData = TransposedTransform3; pub struct MeshInfo { pub vertex_count: u32, pub triangle_count: u32, pub instances: [Similarity3; Self::INSTANCE_COUNT], pub position_buffer: vk::Buffer, pub attribute_buffer: vk::Buffer, pub index_buffer: vk::Buffer, pub instance_buffer: vk::Buffer, } impl MeshInfo { pub const INSTANCE_COUNT: usize = 8; pub async fn load(resource_loader: ResourceLoader, mesh_file_name: &Path, with_ray_tracing: bool) -> Self { let vertex_parser = parser::Parser::<PlyVertex>::new(); let face_parser = parser::Parser::<PlyFace>::new(); let mut f = io::BufReader::new(fs::File::open(mesh_file_name).unwrap()); let header = vertex_parser.read_header(&mut f).unwrap(); let mut vertices = Vec::new(); let mut faces = Vec::new(); for (_key, element) in header.elements.iter() { match element.name.as_ref() { "vertex" => { vertices = vertex_parser .read_payload_for_element(&mut f, element, &header) .unwrap(); } "face" => { faces = face_parser.read_payload_for_element(&mut f, element, &header).unwrap(); } _ => panic!("unexpected element {:?}", element), } } let position_buffer_desc = BufferDesc::new(vertices.len() * mem::size_of::<PositionData>()); let mut writer = resource_loader .buffer_writer( &position_buffer_desc, if with_ray_tracing { BufferUsage::VERTEX_BUFFER | BufferUsage::ACCELERATION_STRUCTURE_BUILD_INPUT } else { BufferUsage::VERTEX_BUFFER }, ) .await; let mut min = Vec3::broadcast(f32::MAX); let mut max = Vec3::broadcast(f32::MIN); for src in vertices.iter() { let v = src.pos; writer.write(&v); min = min.min_by_component(v); max = max.max_by_component(v); } let position_buffer_id = writer.finish(); let index_buffer_desc = BufferDesc::new(faces.len() * 3 * mem::size_of::<u32>()); let mut writer = resource_loader .buffer_writer( &index_buffer_desc, if with_ray_tracing { BufferUsage::INDEX_BUFFER | BufferUsage::ACCELERATION_STRUCTURE_BUILD_INPUT } else { BufferUsage::INDEX_BUFFER }, ) .await; let mut normals = vec![Vec3::zero(); vertices.len()]; for src in faces.iter() { writer.write(&src.indices); let v0 = vertices[src.indices[0] as usize].pos; let v1 = vertices[src.indices[1] as usize].pos; let v2 = vertices[src.indices[2] as usize].pos; let normal = (v2 - v1).cross(v0 - v1).normalized(); if !normal.is_nan() { // TODO: weight by angle at vertex? normals[src.indices[0] as usize] += normal; normals[src.indices[1] as usize] += normal; normals[src.indices[2] as usize] += normal; } } let index_buffer_id = writer.finish(); for n in normals.iter_mut() { let u = n.normalized(); if !u.is_nan() { *n = u; } } let attribute_buffer_desc = BufferDesc::new(vertices.len() * mem::size_of::<AttributeData>()); let mut writer = resource_loader .buffer_writer( &attribute_buffer_desc, if with_ray_tracing { BufferUsage::VERTEX_BUFFER | BufferUsage::RAY_TRACING_STORAGE_READ } else { BufferUsage::VERTEX_BUFFER }, ) .await; for src in normals.iter() { writer.write(src); } let attribute_buffer_id = writer.finish(); let scale = 0.9 / (max - min).component_max(); let offset = (-0.5 * scale) * (max + min); let mut instances = ArrayVec::new(); for i in 0..Self::INSTANCE_COUNT { let corner = |i: usize, b| if ((i >> b) & 1usize) != 0usize { 0.5 } else { -0.5 }; instances.push(Similarity3::new( offset + Vec3::new(corner(i, 0), corner(i, 1), corner(i, 2)), Rotor3::identity(), scale, )); } let instance_buffer_desc = BufferDesc::new(Self::INSTANCE_COUNT * mem::size_of::<InstanceData>()); let mut writer = resource_loader .buffer_writer(&instance_buffer_desc, BufferUsage::VERTEX_BUFFER) .await; for src in instances.iter() { let instance_data = src.into_transform().transposed(); writer.write(&instance_data); } let instance_buffer_id = writer.finish(); Self { vertex_count: vertices.len() as u32, triangle_count: faces.len() as u32, instances: instances.into_inner().unwrap(), position_buffer: resource_loader.get_buffer(position_buffer_id.await), index_buffer: resource_loader.get_buffer(index_buffer_id.await), attribute_buffer: resource_loader.get_buffer(attribute_buffer_id.await), instance_buffer: resource_loader.get_buffer(instance_buffer_id.await), } } }
rust
MIT
42fc4b496cce21e907eca7112e6d6334d35fc41a
2026-01-04T20:23:56.526296Z
false
sjb3d/caldera
https://github.com/sjb3d/caldera/blob/42fc4b496cce21e907eca7112e6d6334d35fc41a/caldera/examples/test_ray_tracing/main.rs
caldera/examples/test_ray_tracing/main.rs
mod accel; mod loader; use crate::{accel::*, loader::*}; use bytemuck::{Pod, Zeroable}; use caldera::prelude::*; use spark::vk; use std::{mem, path::PathBuf, slice}; use structopt::StructOpt; use strum::VariantNames; use winit::{ dpi::{LogicalSize, Size}, event_loop::EventLoop, window::WindowBuilder, }; #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod)] struct RasterData { proj_from_world: Mat4, } descriptor_set!(RasterDescriptorSet { test: UniformData<RasterData>, }); descriptor_set!(CopyDescriptorSet { ids: StorageImage }); #[derive(Clone, Copy, Eq, PartialEq)] enum RenderMode { Raster, RasterMultisampled, RayTrace, } struct LoadResult { mesh_info: MeshInfo, accel_info: Option<AccelInfo>, } struct App { context: SharedContext, load_result: TaskOutput<LoadResult>, render_mode: RenderMode, is_rotating: bool, angle: f32, } impl App { fn new(base: &mut AppBase, mesh_file_name: PathBuf) -> Self { let context = SharedContext::clone(&base.context); let has_ray_tracing = context .physical_device_features .ray_tracing_pipeline .ray_tracing_pipeline .as_bool(); let resource_loader = base.systems.resource_loader.clone(); let load_result = base.systems.task_system.spawn_task(async move { let mesh_info = MeshInfo::load(resource_loader.clone(), &mesh_file_name, has_ray_tracing).await; let accel_info = if has_ray_tracing { Some(AccelInfo::new(resource_loader.clone(), &mesh_info).await) } else { None }; LoadResult { mesh_info, accel_info } }); Self { context, load_result, render_mode: if has_ray_tracing { RenderMode::RayTrace } else { RenderMode::Raster }, is_rotating: false, angle: PI / 8.0, } } fn render(&mut self, base: &mut AppBase) { let cbar = base.systems.acquire_command_buffer(); base.ui_begin_frame(); base.egui_ctx.clone().input(|i| { if i.key_pressed(egui::Key::Escape) { base.exit_requested = true; } }); egui::Window::new("Debug") .default_pos([5.0, 5.0]) .default_size([350.0, 150.0]) .show(&base.egui_ctx, |ui| { ui.checkbox(&mut self.is_rotating, "Rotate"); ui.label("Render Mode:"); ui.radio_value(&mut self.render_mode, RenderMode::Raster, "Raster"); ui.radio_value( &mut self.render_mode, RenderMode::RasterMultisampled, "Raster (Multisampled)", ); if self .context .physical_device_features .ray_tracing_pipeline .ray_tracing_pipeline .as_bool() { ui.radio_value(&mut self.render_mode, RenderMode::RayTrace, "Ray Trace"); } else { ui.label("Ray Tracing Not Supported!"); } }); base.systems.draw_ui(&base.egui_ctx); base.ui_end_frame(cbar.pre_swapchain_cmd); let mut schedule = base.systems.resource_loader.begin_schedule( &mut base.systems.render_graph, base.context.as_ref(), &base.systems.descriptor_pool, &base.systems.pipeline_cache, ); let swap_vk_image = base .display .acquire(&base.window, cbar.image_available_semaphore.unwrap()); let swap_size = base.display.swapchain.get_size(); let swap_format = base.display.swapchain.get_format(); let swap_image = schedule.import_image( &ImageDesc::new_2d(swap_size, swap_format, vk::ImageAspectFlags::COLOR), ImageUsage::COLOR_ATTACHMENT_WRITE | ImageUsage::SWAPCHAIN, swap_vk_image, ImageUsage::empty(), ImageUsage::SWAPCHAIN, ); let main_sample_count = if matches!(self.render_mode, RenderMode::RasterMultisampled) { vk::SampleCountFlags::N4 } else { vk::SampleCountFlags::N1 }; let depth_image_desc = ImageDesc::new_2d(swap_size, vk::Format::D32_SFLOAT, vk::ImageAspectFlags::DEPTH) .with_samples(main_sample_count); let depth_image = schedule.describe_image(&depth_image_desc); let mut main_render_state = RenderState::new() .with_color(swap_image, &[0.1f32, 0.1f32, 0.1f32, 0f32]) .with_depth(depth_image, AttachmentLoadOp::Clear, AttachmentStoreOp::None); if main_sample_count != vk::SampleCountFlags::N1 { let msaa_image = schedule.describe_image( &ImageDesc::new_2d(swap_size, swap_format, vk::ImageAspectFlags::COLOR).with_samples(main_sample_count), ); main_render_state = main_render_state.with_color_temp(msaa_image); } let load_result = self.load_result.get(); let view_from_world = Isometry3::new( Vec3::new(0.0, 0.0, -6.0), Rotor3::from_rotation_yz(0.5) * Rotor3::from_rotation_xz(self.angle), ); let vertical_fov = PI / 7.0; let aspect_ratio = (swap_size.x as f32) / (swap_size.y as f32); let proj_from_view = projection::rh_yup::perspective_reversed_infinite_z_vk(vertical_fov, aspect_ratio, 0.1); let mut trace_image = None; if let Some(load_result) = load_result { if let Some(accel_info) = load_result.accel_info.as_ref() { if matches!(self.render_mode, RenderMode::RayTrace) { let world_from_view = view_from_world.inversed(); let xy_from_st = Scale2Offset2::new(Vec2::new(aspect_ratio, 1.0) * (0.5 * vertical_fov).tan(), Vec2::zero()); let st_from_uv = Scale2Offset2::new(Vec2::new(-2.0, 2.0), Vec2::new(1.0, -1.0)); let coord_from_uv = Scale2Offset2::new(swap_size.as_float(), Vec2::zero()); let xy_from_coord = xy_from_st * st_from_uv * coord_from_uv.inversed(); let ray_origin = world_from_view.translation; let ray_vec_from_coord = world_from_view.rotation.into_matrix() * Mat3::from_scale(-1.0) * xy_from_coord.into_homogeneous_matrix(); trace_image = Some(accel_info.dispatch( &base.context, &mut schedule, &base.systems.descriptor_pool, swap_size, ray_origin, ray_vec_from_coord, )) } } } schedule.add_graphics( command_name!("main"), main_render_state, |params| { if let Some(trace_image) = trace_image { params.add_image(trace_image, ImageUsage::FRAGMENT_STORAGE_READ); } }, { let context = base.context.as_ref(); let descriptor_pool = &base.systems.descriptor_pool; let pipeline_cache = &base.systems.pipeline_cache; let pixels_per_point = base.egui_ctx.pixels_per_point(); let egui_renderer = &mut base.egui_renderer; move |params, cmd, render_pass| { set_viewport_helper(&context.device, cmd, swap_size); if let Some(trace_image) = trace_image { let copy_descriptor_set = CopyDescriptorSet::create( descriptor_pool, params.get_image_view(trace_image, ImageViewDesc::default()), ); let state = GraphicsPipelineState::new(render_pass, main_sample_count); draw_helper( &context.device, pipeline_cache, cmd, &state, "test_ray_tracing/copy.vert.spv", "test_ray_tracing/copy.frag.spv", copy_descriptor_set, 3, ); } else if let Some(mesh_info) = load_result.map(|load_result| &load_result.mesh_info) { let raster_descriptor_set = RasterDescriptorSet::create(descriptor_pool, |buf| { *buf = RasterData { proj_from_world: proj_from_view * view_from_world.into_homogeneous_matrix(), }; }); let state = GraphicsPipelineState::new(render_pass, main_sample_count).with_vertex_inputs( &[ vk::VertexInputBindingDescription { binding: 0, stride: mem::size_of::<PositionData>() as u32, input_rate: vk::VertexInputRate::VERTEX, }, vk::VertexInputBindingDescription { binding: 1, stride: mem::size_of::<AttributeData>() as u32, input_rate: vk::VertexInputRate::VERTEX, }, vk::VertexInputBindingDescription { binding: 2, stride: mem::size_of::<InstanceData>() as u32, input_rate: vk::VertexInputRate::INSTANCE, }, ], &[ vk::VertexInputAttributeDescription { location: 0, binding: 0, format: vk::Format::R32G32B32_SFLOAT, offset: 0, }, vk::VertexInputAttributeDescription { location: 1, binding: 1, format: vk::Format::R32G32B32_SFLOAT, offset: 0, }, vk::VertexInputAttributeDescription { location: 2, binding: 2, format: vk::Format::R32G32B32A32_SFLOAT, offset: 0, }, vk::VertexInputAttributeDescription { location: 3, binding: 2, format: vk::Format::R32G32B32A32_SFLOAT, offset: 16, }, vk::VertexInputAttributeDescription { location: 4, binding: 2, format: vk::Format::R32G32B32A32_SFLOAT, offset: 32, }, ], ); let raster_pipeline_layout = pipeline_cache.get_pipeline_layout(slice::from_ref(&raster_descriptor_set.layout)); let pipeline = pipeline_cache.get_graphics( VertexShaderDesc::standard("test_ray_tracing/raster.vert.spv"), "test_ray_tracing/raster.frag.spv", raster_pipeline_layout, &state, ); unsafe { context .device .cmd_bind_pipeline(cmd, vk::PipelineBindPoint::GRAPHICS, pipeline); context.device.cmd_bind_descriptor_sets( cmd, vk::PipelineBindPoint::GRAPHICS, raster_pipeline_layout, 0, slice::from_ref(&raster_descriptor_set.set), &[], ); context.device.cmd_bind_vertex_buffers( cmd, 0, &[ mesh_info.position_buffer, mesh_info.attribute_buffer, mesh_info.instance_buffer, ], &[0, 0, 0], ); context .device .cmd_bind_index_buffer(cmd, mesh_info.index_buffer, 0, vk::IndexType::UINT32); context.device.cmd_draw_indexed( cmd, mesh_info.triangle_count * 3, MeshInfo::INSTANCE_COUNT as u32, 0, 0, 0, ); } } // draw ui let egui_pipeline = pipeline_cache.get_ui(egui_renderer, render_pass, main_sample_count); egui_renderer.render( &context.device, cmd, egui_pipeline, swap_size.x, swap_size.y, pixels_per_point, ); } }, ); schedule.run( &base.context, cbar.pre_swapchain_cmd, cbar.post_swapchain_cmd, Some(swap_image), &mut base.systems.query_pool, ); let rendering_finished_semaphore = base.systems.submit_command_buffer(&cbar); base.display .present(swap_vk_image, rendering_finished_semaphore.unwrap()); if self.is_rotating { self.angle += base.egui_ctx.input(|i| i.stable_dt); } } } #[derive(Debug, StructOpt)] #[structopt(no_version)] struct AppParams { /// Core Vulkan version to load #[structopt(short, long, parse(try_from_str=try_version_from_str), default_value="1.1")] version: vk::Version, /// Whether to use EXT_inline_uniform_block #[structopt(long, possible_values=&ContextFeature::VARIANTS, default_value="optional")] inline_uniform_block: ContextFeature, /// Whether to use KHR_ray_tracing_pipeline #[structopt(long, possible_values=&ContextFeature::VARIANTS, default_value="optional")] ray_tracing: ContextFeature, /// The PLY file to load mesh_file_name: PathBuf, } fn main() { let app_params = AppParams::from_args(); let context_params = ContextParams { version: app_params.version, inline_uniform_block: app_params.inline_uniform_block, ray_tracing: app_params.ray_tracing, ..Default::default() }; let event_loop = EventLoop::new(); let window = WindowBuilder::new() .with_title("mesh") .with_inner_size(Size::Logical(LogicalSize::new(1920.0, 1080.0))) .build(&event_loop) .unwrap(); let mut base = AppBase::new(window, &context_params); let app = App::new(&mut base, app_params.mesh_file_name); let mut apps = Some((base, app)); event_loop.run(move |event, target, control_flow| { match apps .as_mut() .map(|(base, _)| base) .unwrap() .process_event(&event, target, control_flow) { AppEventResult::None => {} AppEventResult::Redraw => { let (base, app) = apps.as_mut().unwrap(); app.render(base); } AppEventResult::Destroy => { apps.take(); } } }); }
rust
MIT
42fc4b496cce21e907eca7112e6d6334d35fc41a
2026-01-04T20:23:56.526296Z
false
sjb3d/caldera
https://github.com/sjb3d/caldera/blob/42fc4b496cce21e907eca7112e6d6334d35fc41a/caldera/examples/test_ray_tracing/accel.rs
caldera/examples/test_ray_tracing/accel.rs
use crate::loader::*; use bytemuck::{Pod, Zeroable}; use caldera::prelude::*; use spark::vk; use std::{mem, slice}; #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod)] struct TraceData { ray_origin: Vec3, ray_vec_from_coord: Mat3, } #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod)] struct HitRecordData { index_buffer_address: u64, attribute_buffer_address: u64, } descriptor_set!(TraceDescriptorSet { trace: UniformData<TraceData>, accel: AccelerationStructure, output: StorageImage, }); // vk::AccelerationStructureInstanceKHR with Pod trait #[repr(C)] #[derive(Clone, Copy, Zeroable, Pod)] struct AccelerationStructureInstance { transform: TransposedTransform3, instance_custom_index_and_mask: u32, instance_shader_binding_table_record_offset_and_flags: u32, acceleration_structure_reference: u64, } struct AccelLevel { buffer_id: BufferId, } impl AccelLevel { async fn new_bottom_level(resource_loader: ResourceLoader, mesh_info: &MeshInfo) -> Self { let context = resource_loader.context(); let vertex_buffer_address = unsafe { context .device .get_buffer_device_address_helper(mesh_info.position_buffer) }; let index_buffer_address = unsafe { context.device.get_buffer_device_address_helper(mesh_info.index_buffer) }; let geometry_triangles_data = vk::AccelerationStructureGeometryTrianglesDataKHR { vertex_format: vk::Format::R32G32B32_SFLOAT, vertex_data: vk::DeviceOrHostAddressConstKHR { device_address: vertex_buffer_address, }, vertex_stride: mem::size_of::<PositionData>() as vk::DeviceSize, max_vertex: mesh_info.vertex_count - 1, index_type: vk::IndexType::UINT32, index_data: vk::DeviceOrHostAddressConstKHR { device_address: index_buffer_address, }, ..Default::default() }; let geometry = vk::AccelerationStructureGeometryKHR { geometry_type: vk::GeometryTypeKHR::TRIANGLES, geometry: vk::AccelerationStructureGeometryDataKHR { triangles: geometry_triangles_data, }, flags: vk::GeometryFlagsKHR::OPAQUE, ..Default::default() }; let build_info = vk::AccelerationStructureBuildGeometryInfoKHR { ty: vk::AccelerationStructureTypeKHR::BOTTOM_LEVEL, flags: vk::BuildAccelerationStructureFlagsKHR::PREFER_FAST_TRACE, mode: vk::BuildAccelerationStructureModeKHR::BUILD, geometry_count: 1, p_geometries: &geometry, ..Default::default() }; let sizes = { let max_primitive_count = mesh_info.triangle_count; let mut sizes = vk::AccelerationStructureBuildSizesInfoKHR::default(); unsafe { context.device.get_acceleration_structure_build_sizes_khr( vk::AccelerationStructureBuildTypeKHR::DEVICE, &build_info, Some(slice::from_ref(&max_primitive_count)), &mut sizes, ) }; sizes }; println!("build scratch size: {}", sizes.build_scratch_size); println!("acceleration structure size: {}", sizes.acceleration_structure_size); let triangle_count = mesh_info.triangle_count; let buffer_id = resource_loader .graphics(move |ctx: GraphicsTaskContext| { let context = ctx.context; let schedule = ctx.schedule; let buffer_id = schedule.create_buffer( &BufferDesc::new(sizes.acceleration_structure_size as usize), BufferUsage::BOTTOM_LEVEL_ACCELERATION_STRUCTURE_WRITE | BufferUsage::BOTTOM_LEVEL_ACCELERATION_STRUCTURE_READ | BufferUsage::RAY_TRACING_ACCELERATION_STRUCTURE, ); let scratch_buffer_id = schedule.describe_buffer(&BufferDesc::new(sizes.build_scratch_size as usize)); schedule.add_compute( command_name!("build"), |params| { params.add_buffer(buffer_id, BufferUsage::BOTTOM_LEVEL_ACCELERATION_STRUCTURE_WRITE); params.add_buffer(scratch_buffer_id, BufferUsage::ACCELERATION_STRUCTURE_BUILD_SCRATCH); }, { move |params, cmd| { let accel = params.get_buffer_accel(buffer_id); let scratch_buffer = params.get_buffer(scratch_buffer_id); let scratch_buffer_address = unsafe { context.device.get_buffer_device_address_helper(scratch_buffer) }; let build_info = vk::AccelerationStructureBuildGeometryInfoKHR { ty: vk::AccelerationStructureTypeKHR::BOTTOM_LEVEL, flags: vk::BuildAccelerationStructureFlagsKHR::PREFER_FAST_TRACE, mode: vk::BuildAccelerationStructureModeKHR::BUILD, dst_acceleration_structure: accel, geometry_count: 1, p_geometries: &geometry, scratch_data: vk::DeviceOrHostAddressKHR { device_address: scratch_buffer_address, }, ..Default::default() }; let build_range_info = vk::AccelerationStructureBuildRangeInfoKHR { primitive_count: triangle_count, primitive_offset: 0, first_vertex: 0, transform_offset: 0, }; unsafe { context.device.cmd_build_acceleration_structures_khr( cmd, slice::from_ref(&build_info), &[&build_range_info], ) }; } }, ); buffer_id }) .await; Self { buffer_id } } async fn new_top_level( resource_loader: ResourceLoader, bottom_level_buffer_id: BufferId, instance_buffer: vk::Buffer, ) -> Self { let context = resource_loader.context(); let instance_buffer_address = unsafe { context.device.get_buffer_device_address_helper(instance_buffer) }; let geometry = vk::AccelerationStructureGeometryKHR { geometry_type: vk::GeometryTypeKHR::INSTANCES, geometry: vk::AccelerationStructureGeometryDataKHR { instances: vk::AccelerationStructureGeometryInstancesDataKHR { data: vk::DeviceOrHostAddressConstKHR { device_address: instance_buffer_address, }, ..Default::default() }, }, ..Default::default() }; let build_info = vk::AccelerationStructureBuildGeometryInfoKHR { ty: vk::AccelerationStructureTypeKHR::TOP_LEVEL, flags: vk::BuildAccelerationStructureFlagsKHR::PREFER_FAST_TRACE, mode: vk::BuildAccelerationStructureModeKHR::BUILD, geometry_count: 1, p_geometries: &geometry, ..Default::default() }; let instance_count = MeshInfo::INSTANCE_COUNT as u32; let sizes = { let mut sizes = vk::AccelerationStructureBuildSizesInfoKHR::default(); unsafe { context.device.get_acceleration_structure_build_sizes_khr( vk::AccelerationStructureBuildTypeKHR::DEVICE, &build_info, Some(slice::from_ref(&instance_count)), &mut sizes, ) }; sizes }; println!("build scratch size: {}", sizes.build_scratch_size); println!("acceleration structure size: {}", sizes.acceleration_structure_size); let buffer_id = resource_loader .graphics(move |ctx: GraphicsTaskContext| { let context = ctx.context; let schedule = ctx.schedule; let buffer_id = schedule.create_buffer( &BufferDesc::new(sizes.acceleration_structure_size as usize), BufferUsage::TOP_LEVEL_ACCELERATION_STRUCTURE_WRITE | BufferUsage::RAY_TRACING_ACCELERATION_STRUCTURE, ); let scratch_buffer_id = schedule.describe_buffer(&BufferDesc::new(sizes.build_scratch_size as usize)); schedule.add_compute( command_name!("build"), |params| { params.add_buffer( bottom_level_buffer_id, BufferUsage::BOTTOM_LEVEL_ACCELERATION_STRUCTURE_READ, ); params.add_buffer(buffer_id, BufferUsage::TOP_LEVEL_ACCELERATION_STRUCTURE_WRITE); params.add_buffer(scratch_buffer_id, BufferUsage::ACCELERATION_STRUCTURE_BUILD_SCRATCH); }, move |params, cmd| { let accel = params.get_buffer_accel(buffer_id); let scratch_buffer = params.get_buffer(scratch_buffer_id); let scratch_buffer_address = unsafe { context.device.get_buffer_device_address_helper(scratch_buffer) }; let build_info = vk::AccelerationStructureBuildGeometryInfoKHR { ty: vk::AccelerationStructureTypeKHR::TOP_LEVEL, flags: vk::BuildAccelerationStructureFlagsKHR::PREFER_FAST_TRACE, mode: vk::BuildAccelerationStructureModeKHR::BUILD, dst_acceleration_structure: accel, geometry_count: 1, p_geometries: &geometry, scratch_data: vk::DeviceOrHostAddressKHR { device_address: scratch_buffer_address, }, ..Default::default() }; let build_range_info = vk::AccelerationStructureBuildRangeInfoKHR { primitive_count: instance_count, primitive_offset: 0, first_vertex: 0, transform_offset: 0, }; unsafe { context.device.cmd_build_acceleration_structures_khr( cmd, slice::from_ref(&build_info), &[&build_range_info], ) }; }, ); buffer_id }) .await; Self { buffer_id } } } #[derive(Clone, Copy)] struct ShaderBindingRegion { offset: u32, stride: u32, size: u32, } impl ShaderBindingRegion { fn new( rtpp: &vk::PhysicalDeviceRayTracingPipelinePropertiesKHR, next_offset: u32, record_size: u32, entry_count: u32, ) -> (Self, u32) { let align_up = |n: u32, a: u32| (n + a - 1) & !(a - 1); let offset = align_up(next_offset, rtpp.shader_group_base_alignment); let stride = align_up( rtpp.shader_group_handle_size + record_size, rtpp.shader_group_handle_alignment, ); let size = stride * entry_count; (Self { offset, stride, size }, offset + size) } fn into_device_address_region(self, base_device_address: vk::DeviceAddress) -> vk::StridedDeviceAddressRegionKHR { vk::StridedDeviceAddressRegionKHR { device_address: base_device_address + self.offset as vk::DeviceSize, stride: self.stride as vk::DeviceSize, size: self.size as vk::DeviceSize, } } } pub struct AccelInfo { trace_pipeline_layout: vk::PipelineLayout, trace_pipeline: vk::Pipeline, shader_binding_table_buffer: vk::Buffer, shader_binding_raygen_region: ShaderBindingRegion, shader_binding_miss_region: ShaderBindingRegion, shader_binding_hit_region: ShaderBindingRegion, bottom_level: AccelLevel, top_level: AccelLevel, } impl AccelInfo { pub async fn new(resource_loader: ResourceLoader, mesh_info: &MeshInfo) -> Self { let context = resource_loader.context(); let index_buffer_device_address = unsafe { context.device.get_buffer_device_address_helper(mesh_info.index_buffer) }; let attribute_buffer_device_address = unsafe { context .device .get_buffer_device_address_helper(mesh_info.attribute_buffer) }; // TODO: figure out live reload, needs to regenerate SBT! let (trace_pipeline_layout, trace_pipeline) = resource_loader .graphics(move |ctx: GraphicsTaskContext| { let descriptor_pool = ctx.descriptor_pool; let pipeline_cache = ctx.pipeline_cache; let trace_descriptor_set_layout = TraceDescriptorSet::layout(descriptor_pool); let trace_pipeline_layout = ctx .pipeline_cache .get_pipeline_layout(slice::from_ref(&trace_descriptor_set_layout)); let trace_pipeline = pipeline_cache.get_ray_tracing( &[ RayTracingShaderGroupDesc::Raygen("test_ray_tracing/trace.rgen.spv"), RayTracingShaderGroupDesc::Miss("test_ray_tracing/trace.rmiss.spv"), RayTracingShaderGroupDesc::Hit { closest_hit: "test_ray_tracing/trace.rchit.spv", any_hit: None, intersection: None, }, ], trace_pipeline_layout, ); (trace_pipeline_layout, trace_pipeline) }) .await; let ( shader_binding_raygen_region, shader_binding_miss_region, shader_binding_hit_region, shader_binding_table_size, ) = { let rtpp = &context .physical_device_extra_properties .as_ref() .unwrap() .ray_tracing_pipeline; let next_offset = 0; let raygen_record_size = 0; let (raygen_region, next_offset) = ShaderBindingRegion::new(rtpp, next_offset, raygen_record_size, 1); let miss_record_size = 0; let (miss_region, next_offset) = ShaderBindingRegion::new(rtpp, next_offset, miss_record_size, 1); let hit_record_size = mem::size_of::<HitRecordData>() as u32; let (hit_region, next_offset) = ShaderBindingRegion::new(rtpp, next_offset, hit_record_size, 1); (raygen_region, miss_region, hit_region, next_offset) }; let shader_binding_table_buffer_id = { let rtpp = &context .physical_device_extra_properties .as_ref() .unwrap() .ray_tracing_pipeline; let shader_group_count = 3; let handle_size = rtpp.shader_group_handle_size as usize; let mut handle_data = vec![0u8; (shader_group_count as usize) * handle_size]; unsafe { context.device.get_ray_tracing_shader_group_handles_khr( trace_pipeline, 0, shader_group_count, &mut handle_data, ) } .unwrap(); let remain = handle_data.as_slice(); let (raygen_group_handle, remain) = remain.split_at(handle_size); let (miss_group_handle, remain) = remain.split_at(handle_size); let hit_group_handle = remain; let hit_data = HitRecordData { index_buffer_address: index_buffer_device_address, attribute_buffer_address: attribute_buffer_device_address, }; let desc = BufferDesc::new(shader_binding_table_size as usize); let mut writer = resource_loader .buffer_writer(&desc, BufferUsage::RAY_TRACING_SHADER_BINDING_TABLE) .await; assert_eq!(shader_binding_raygen_region.offset, 0); writer.write(raygen_group_handle); writer.write_zeros(shader_binding_miss_region.offset as usize - writer.written()); writer.write(miss_group_handle); writer.write_zeros(shader_binding_hit_region.offset as usize - writer.written()); writer.write(hit_group_handle); writer.write(&hit_data); writer.finish().await }; let shader_binding_table_buffer = resource_loader.get_buffer(shader_binding_table_buffer_id); let bottom_level = AccelLevel::new_bottom_level(resource_loader.clone(), mesh_info).await; let bottom_level_device_address = { let info = vk::AccelerationStructureDeviceAddressInfoKHR { acceleration_structure: resource_loader.get_buffer_accel(bottom_level.buffer_id), ..Default::default() }; unsafe { context.device.get_acceleration_structure_device_address_khr(&info) } }; let instance_buffer_id = { let desc = BufferDesc::new(MeshInfo::INSTANCE_COUNT * mem::size_of::<vk::AccelerationStructureInstanceKHR>()); let mut writer = resource_loader .buffer_writer(&desc, BufferUsage::ACCELERATION_STRUCTURE_BUILD_INPUT) .await; for src in mesh_info.instances.iter() { let instance = AccelerationStructureInstance { transform: src.into_transform().transposed(), instance_custom_index_and_mask: 0xff_00_00_00, instance_shader_binding_table_record_offset_and_flags: 0, acceleration_structure_reference: bottom_level_device_address, }; writer.write(&instance); } writer.finish().await }; let instance_buffer = resource_loader.get_buffer(instance_buffer_id); let top_level = AccelLevel::new_top_level(resource_loader.clone(), bottom_level.buffer_id, instance_buffer).await; Self { trace_pipeline_layout, trace_pipeline, shader_binding_table_buffer, shader_binding_raygen_region, shader_binding_miss_region, shader_binding_hit_region, bottom_level, top_level, } } #[allow(clippy::too_many_arguments)] pub fn dispatch<'graph>( &'graph self, context: &'graph Context, schedule: &mut RenderSchedule<'graph>, descriptor_pool: &'graph DescriptorPool, swap_size: UVec2, ray_origin: Vec3, ray_vec_from_coord: Mat3, ) -> ImageId { let top_level = &self.top_level; let shader_binding_table_buffer = self.shader_binding_table_buffer; let shader_binding_table_address = unsafe { context .device .get_buffer_device_address_helper(shader_binding_table_buffer) }; let output_desc = ImageDesc::new_2d(swap_size, vk::Format::R32_UINT, vk::ImageAspectFlags::COLOR); let output_image_id = schedule.describe_image(&output_desc); schedule.add_compute( command_name!("trace"), |params| { params.add_buffer( self.bottom_level.buffer_id, BufferUsage::RAY_TRACING_ACCELERATION_STRUCTURE, ); params.add_buffer(top_level.buffer_id, BufferUsage::RAY_TRACING_ACCELERATION_STRUCTURE); params.add_image(output_image_id, ImageUsage::RAY_TRACING_STORAGE_WRITE); }, move |params, cmd| { let trace_descriptor_set = TraceDescriptorSet::create( descriptor_pool, |buf: &mut TraceData| { *buf = TraceData { ray_origin, ray_vec_from_coord, } }, params.get_buffer_accel(top_level.buffer_id), params.get_image_view(output_image_id, ImageViewDesc::default()), ); unsafe { context .device .cmd_bind_pipeline(cmd, vk::PipelineBindPoint::RAY_TRACING_KHR, self.trace_pipeline); context.device.cmd_bind_descriptor_sets( cmd, vk::PipelineBindPoint::RAY_TRACING_KHR, self.trace_pipeline_layout, 0, slice::from_ref(&trace_descriptor_set.set), &[], ); } let raygen_shader_binding_table = self .shader_binding_raygen_region .into_device_address_region(shader_binding_table_address); let miss_shader_binding_table = self .shader_binding_miss_region .into_device_address_region(shader_binding_table_address); let hit_shader_binding_table = self .shader_binding_hit_region .into_device_address_region(shader_binding_table_address); let callable_shader_binding_table = vk::StridedDeviceAddressRegionKHR::default(); unsafe { context.device.cmd_trace_rays_khr( cmd, &raygen_shader_binding_table, &miss_shader_binding_table, &hit_shader_binding_table, &callable_shader_binding_table, swap_size.x, swap_size.y, 1, ); } }, ); output_image_id } }
rust
MIT
42fc4b496cce21e907eca7112e6d6334d35fc41a
2026-01-04T20:23:56.526296Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/lib.rs
src/lib.rs
#![allow(clippy::arc_with_non_send_sync)] pub use common::CliResult; use inquire::ui::{Color, RenderConfig, StyleSheet, Styled}; pub mod commands; pub mod common; pub mod config; pub mod js_command_match; pub mod network; pub mod network_for_transaction; pub mod network_view_at_block; pub mod transaction_signature_options; pub mod types; pub mod utils_command; #[derive(Debug, Clone)] pub struct GlobalContext { pub config: crate::config::Config, pub offline: bool, pub verbosity: Verbosity, } #[derive(Debug, Copy, Clone, Default)] pub enum Verbosity { #[default] Interactive, TeachMe, Quiet, } pub fn setup_tracing(verbosity: Verbosity) -> CliResult { use tracing::{Event, Level, Subscriber}; use tracing_indicatif::style::ProgressStyle; use tracing_indicatif::IndicatifLayer; use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::util::SubscriberInitExt; use tracing_subscriber::EnvFilter; use tracing_subscriber::{ fmt::{format::Writer, FmtContext, FormatEvent, FormatFields}, registry::LookupSpan, }; struct SimpleFormatter; impl<S, N> FormatEvent<S, N> for SimpleFormatter where S: Subscriber + for<'a> LookupSpan<'a>, N: for<'a> FormatFields<'a> + 'static, { fn format_event( &self, ctx: &FmtContext<'_, S, N>, mut writer: Writer<'_>, event: &Event<'_>, ) -> std::fmt::Result { let level = *event.metadata().level(); let (icon, color_code) = match level { Level::TRACE => ("TRACE ", "\x1b[35m"), // Magenta Level::DEBUG => ("DEBUG ", "\x1b[34m"), // Blue Level::INFO => ("", ""), // Default Level::WARN => ("Warning: ", "\x1b[33m"), // Yellow Level::ERROR => ("ERROR ", "\x1b[31m"), // Red }; write!(writer, "{}├ {}", color_code, icon)?; write!(writer, "\x1b[0m")?; ctx.field_format().format_fields(writer.by_ref(), event)?; writeln!(writer) } } match verbosity { Verbosity::TeachMe => { let env_filter = EnvFilter::from_default_env() .add_directive(tracing::Level::WARN.into()) .add_directive("near_teach_me=info".parse()?) .add_directive("near_cli_rs=info".parse()?); tracing_subscriber::registry() .with(tracing_subscriber::fmt::layer().event_format(SimpleFormatter)) .with(env_filter) .init(); } Verbosity::Interactive => { let indicatif_layer = IndicatifLayer::new() .with_progress_style( ProgressStyle::with_template( "{spinner:.blue}{span_child_prefix} {span_name} {msg} {span_fields}", ) .unwrap() .tick_strings(&["◐", "◓", "◑", "◒"]), ) .with_span_child_prefix_symbol("↳ "); let env_filter = EnvFilter::from_default_env() .add_directive(tracing::Level::WARN.into()) .add_directive("near_cli_rs=info".parse()?); tracing_subscriber::registry() .with( tracing_subscriber::fmt::layer() .event_format(SimpleFormatter) .with_writer(indicatif_layer.get_stderr_writer()), ) .with(indicatif_layer) .with(env_filter) .init(); } Verbosity::Quiet => {} }; Ok(()) } pub fn get_global_render_config() -> RenderConfig<'static> { let mut render_config = RenderConfig::default_colored(); render_config.prompt_prefix = Styled::new("◆ ").with_fg(Color::DarkGreen); render_config.answered_prompt_prefix = Styled::new("◇ ").with_fg(Color::DarkGreen); render_config.highlighted_option_prefix = Styled::new(" ●").with_fg(Color::DarkGreen); render_config.unhighlighted_option_prefix = Styled::new(" ○").with_fg(Color::DarkGrey); render_config.selected_checkbox = Styled::new("◼").with_fg(Color::LightGreen); render_config.scroll_up_prefix = Styled::new("↑○").with_fg(Color::DarkGrey); render_config.scroll_down_prefix = Styled::new("↓○").with_fg(Color::DarkGrey); render_config.unselected_checkbox = Styled::new("◻").with_fg(Color::DarkGrey); render_config.option = StyleSheet::new().with_fg(Color::DarkGrey); render_config.selected_option = Some(StyleSheet::new().with_fg(Color::Grey)); render_config.new_line_prefix = Some(Styled::new("│ ").with_fg(Color::LightBlue)); render_config.answer_from_new_line = true; render_config.error_message = render_config .error_message .with_prefix(Styled::new("❌").with_fg(Color::LightRed)); render_config.text_input = StyleSheet::new().with_fg(Color::LightYellow); render_config.answer = StyleSheet::new().with_fg(Color::DarkGrey); render_config.help_message = StyleSheet::new().with_fg(Color::DarkYellow); render_config }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/main.rs
src/main.rs
#![allow( clippy::enum_variant_names, clippy::large_enum_variant, clippy::too_many_arguments )] use clap::Parser; #[cfg(feature = "self-update")] use color_eyre::eyre::WrapErr; use color_eyre::owo_colors::OwoColorize; use interactive_clap::ToCliArgs; pub use near_cli_rs::commands; pub use near_cli_rs::common::{self, CliResult}; pub use near_cli_rs::config; pub use near_cli_rs::js_command_match; pub use near_cli_rs::network; pub use near_cli_rs::network_for_transaction; pub use near_cli_rs::network_view_at_block; pub use near_cli_rs::transaction_signature_options; pub use near_cli_rs::types; pub use near_cli_rs::utils_command; pub use near_cli_rs::GlobalContext; pub use near_cli_rs::Verbosity; type ConfigContext = (crate::config::Config,); #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = ConfigContext)] #[interactive_clap(output_context = CmdContext)] struct Cmd { /// Offline mode #[interactive_clap(long)] offline: bool, /// Quiet mode #[interactive_clap(long)] quiet: bool, /// TEACH-ME mode #[interactive_clap(long)] teach_me: bool, #[interactive_clap(subcommand)] top_level: crate::commands::TopLevelCommand, } #[derive(Debug, Clone)] struct CmdContext(crate::GlobalContext); impl CmdContext { fn from_previous_context( previous_context: ConfigContext, scope: &<Cmd as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let verbosity = if scope.quiet { Verbosity::Quiet } else if scope.teach_me { Verbosity::TeachMe } else { Verbosity::Interactive }; Ok(Self(crate::GlobalContext { config: previous_context.0, offline: scope.offline, verbosity, })) } } impl From<CmdContext> for crate::GlobalContext { fn from(item: CmdContext) -> Self { item.0 } } fn main() -> crate::common::CliResult { inquire::set_global_render_config(near_cli_rs::get_global_render_config()); let config = crate::config::Config::get_config_toml()?; if !crate::common::is_used_account_list_exist(&config.credentials_home_dir) { crate::common::create_used_account_list_from_legacy_keychain(&config.credentials_home_dir)?; } #[cfg(not(debug_assertions))] let display_env_section = false; #[cfg(debug_assertions)] let display_env_section = true; color_eyre::config::HookBuilder::default() .display_env_section(display_env_section) .install()?; #[cfg(feature = "self-update")] let handle = std::thread::spawn(|| -> color_eyre::eyre::Result<String> { crate::commands::extensions::self_update::get_latest_version() }); let near_cli_exec_path = crate::common::get_near_exec_path(); let cli = match Cmd::try_parse() { Ok(cli) => cli, Err(cmd_error) => match cmd_error.kind() { clap::error::ErrorKind::DisplayHelp | clap::error::ErrorKind::DisplayVersion => { cmd_error.exit() } _ => { match crate::js_command_match::JsCmd::try_parse() { Ok(js_cmd) => { let vec_cmd = js_cmd.rust_command_generation(); let cmd = std::iter::once(near_cli_exec_path.to_owned()).chain(vec_cmd); Parser::parse_from(cmd) } Err(js_cmd_error) => { // js and rust both don't understand the subcommand if cmd_error.kind() == clap::error::ErrorKind::InvalidSubcommand && js_cmd_error.kind() == clap::error::ErrorKind::InvalidSubcommand { return crate::common::try_external_subcommand_execution(cmd_error); } // js understand the subcommand if js_cmd_error.kind() != clap::error::ErrorKind::InvalidSubcommand { js_cmd_error.exit(); } cmd_error.exit(); } } } }, }; let verbosity = if cli.quiet { Verbosity::Quiet } else if cli.teach_me { Verbosity::TeachMe } else { Verbosity::Interactive }; near_cli_rs::setup_tracing(verbosity)?; let cli_cmd = match <Cmd as interactive_clap::FromCli>::from_cli(Some(cli), (config,)) { interactive_clap::ResultFromCli::Ok(cli_cmd) | interactive_clap::ResultFromCli::Cancel(Some(cli_cmd)) => { let cli_cmd_str = shell_words::join( std::iter::once(&near_cli_exec_path).chain(&cli_cmd.to_cli_args()), ); if !cli_cmd.quiet { eprintln!( "\n\nHere is your console command if you need to script it or re-run:\n {}\n", cli_cmd_str.yellow() ); } crate::common::save_cli_command(&cli_cmd_str); Ok(Some(cli_cmd)) } interactive_clap::ResultFromCli::Cancel(None) => { eprintln!("\nGoodbye!"); Ok(None) } interactive_clap::ResultFromCli::Back => { unreachable!("TopLevelCommand does not have back option"); } interactive_clap::ResultFromCli::Err(optional_cli_cmd, err) => { if let Some(cli_cmd) = optional_cli_cmd { let cli_cmd_str = shell_words::join( std::iter::once(&near_cli_exec_path).chain(&cli_cmd.to_cli_args()), ); if !cli_cmd.quiet { eprintln!( "\nHere is your console command if you need to script it or re-run:\n {}\n", cli_cmd_str.yellow() ); } crate::common::save_cli_command(&cli_cmd_str); } Err(err) } }; #[cfg(feature = "self-update")] // We don't need to check the version if user has just called self-update if !matches!( cli_cmd, Ok(Some(CliCmd { top_level: Some(crate::commands::CliTopLevelCommand::Extensions( crate::commands::extensions::CliExtensionsCommands { extensions_actions: Some( crate::commands::extensions::CliExtensionsActions::SelfUpdate( crate::commands::extensions::self_update::CliSelfUpdateCommand {}, ) ), }, )), .. })) ) { if let Ok(Ok(latest_version)) = handle.join() { let current_version = semver::Version::parse(self_update::cargo_crate_version!()) .wrap_err("Failed to parse current version of `near` CLI")?; let latest_version = semver::Version::parse(&latest_version) .wrap_err("Failed to parse latest version of `near` CLI")?; if current_version < latest_version { eprintln!( "\n`near` CLI has a new update available \x1b[2m{current_version}\x1b[0m → \x1b[32m{latest_version}\x1b[0m" ); let self_update_cli_cmd = CliCmd { offline: false, quiet: false, teach_me: false, top_level: Some(crate::commands::CliTopLevelCommand::Extensions( crate::commands::extensions::CliExtensionsCommands { extensions_actions: Some(crate::commands::extensions::CliExtensionsActions::SelfUpdate( crate::commands::extensions::self_update::CliSelfUpdateCommand {}, )), }, )), }; eprintln!( "To update `near` CLI use: {}", shell_words::join( std::iter::once(near_cli_exec_path) .chain(self_update_cli_cmd.to_cli_args()) ) .yellow() ); } } }; cli_cmd.map(|_| ()) }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/common.rs
src/common.rs
use std::collections::VecDeque; use std::convert::{TryFrom, TryInto}; use std::fs::OpenOptions; use std::io::Write; use std::str::FromStr; use color_eyre::eyre::{ContextCompat, WrapErr}; use color_eyre::owo_colors::OwoColorize; use futures::{StreamExt, TryStreamExt}; use near_primitives::action::{GlobalContractDeployMode, GlobalContractIdentifier}; use prettytable::Table; use rust_decimal::prelude::FromPrimitive; use tracing_indicatif::span_ext::IndicatifSpanExt; use tracing_indicatif::suspend_tracing_indicatif; use near_primitives::{hash::CryptoHash, types::BlockReference, views::AccessKeyPermissionView}; pub type CliResult = color_eyre::eyre::Result<()>; /// A type alias was introduced to simplify the usage of `Result` with a boxed error type that was /// necessary to fix `clippy::result_large_err` warning pub type BoxedJsonRpcResult<T, E> = Result<T, Box<near_jsonrpc_client::errors::JsonRpcError<E>>>; use inquire::{Select, Text}; use strum::IntoEnumIterator; use crate::types::partial_protocol_config::get_partial_protocol_config; const FINAL_COMMAND_FILE_NAME: &str = "near-cli-rs-final-command.log"; pub fn get_near_exec_path() -> String { std::env::args() .next() .unwrap_or_else(|| "./near".to_owned()) } #[derive( Debug, Clone, strum_macros::IntoStaticStr, strum_macros::EnumString, strum_macros::EnumVariantNames, smart_default::SmartDefault, )] #[strum(serialize_all = "snake_case")] pub enum OutputFormat { #[default] Plaintext, Json, } impl std::fmt::Display for OutputFormat { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { OutputFormat::Plaintext => write!(f, "plaintext"), OutputFormat::Json => write!(f, "json"), } } } #[derive(Debug, Clone)] pub struct BlockHashAsBase58 { pub inner: near_primitives::hash::CryptoHash, } impl std::str::FromStr for BlockHashAsBase58 { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(Self { inner: bs58::decode(s) .into_vec() .map_err(|err| format!("base58 block hash sequence is invalid: {err}"))? .as_slice() .try_into() .map_err(|err| format!("block hash could not be collected: {err}"))?, }) } } impl std::fmt::Display for BlockHashAsBase58 { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "BlockHash {}", self.inner) } } pub use near_gas::NearGas; #[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd)] pub struct TransferAmount { amount: near_token::NearToken, } impl interactive_clap::ToCli for TransferAmount { type CliVariant = near_token::NearToken; } impl std::fmt::Display for TransferAmount { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.amount) } } impl TransferAmount { pub fn from( amount: near_token::NearToken, account_transfer_allowance: &AccountTransferAllowance, ) -> color_eyre::eyre::Result<Self> { if amount <= account_transfer_allowance.transfer_allowance() { Ok(Self { amount }) } else { Err(color_eyre::Report::msg( "the amount exceeds the transfer allowance", )) } } pub fn from_unchecked(amount: near_token::NearToken) -> Self { Self { amount } } pub fn as_yoctonear(&self) -> u128 { self.amount.as_yoctonear() } } impl From<TransferAmount> for near_token::NearToken { fn from(item: TransferAmount) -> Self { item.amount } } #[derive(Debug)] pub struct AccountTransferAllowance { account_id: near_primitives::types::AccountId, account_liquid_balance: near_token::NearToken, account_locked_balance: near_token::NearToken, storage_stake: near_token::NearToken, pessimistic_transaction_fee: near_token::NearToken, } impl std::fmt::Display for AccountTransferAllowance { fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(fmt, "{} account has {} available for transfer (the total balance is {}, but {} is locked for storage)", self.account_id, self.transfer_allowance(), self.account_liquid_balance, self.liquid_storage_stake(), ) } } impl AccountTransferAllowance { pub fn liquid_storage_stake(&self) -> near_token::NearToken { self.storage_stake .saturating_sub(self.account_locked_balance) } pub fn transfer_allowance(&self) -> near_token::NearToken { self.account_liquid_balance .saturating_sub(self.liquid_storage_stake()) .saturating_sub(self.pessimistic_transaction_fee) } } #[derive(Debug)] pub enum AccountStateError<E> { JsonRpcError(near_jsonrpc_client::errors::JsonRpcError<E>), Cancel, } #[tracing::instrument(name = "Getting the transfer allowance for the account ...", skip_all)] pub async fn get_account_transfer_allowance( network_config: &crate::config::NetworkConfig, account_id: near_primitives::types::AccountId, block_reference: BlockReference, ) -> color_eyre::eyre::Result<AccountTransferAllowance> { tracing::info!(target: "near_teach_me", "Getting the transfer allowance for the account ..."); let account_state = get_account_state(network_config, &account_id, block_reference.clone()).await; let account_view = match account_state { Ok(account_view) => account_view, Err(AccountStateError::JsonRpcError( near_jsonrpc_client::errors::JsonRpcError::ServerError( near_jsonrpc_client::errors::JsonRpcServerError::HandlerError( near_jsonrpc_primitives::types::query::RpcQueryError::UnknownAccount { .. }, ), ), )) if account_id.get_account_type().is_implicit() => { return Ok(AccountTransferAllowance { account_id, account_liquid_balance: near_token::NearToken::ZERO, account_locked_balance: near_token::NearToken::ZERO, storage_stake: near_token::NearToken::ZERO, pessimistic_transaction_fee: near_token::NearToken::ZERO, }); } Err(AccountStateError::JsonRpcError( near_jsonrpc_client::errors::JsonRpcError::TransportError(err), )) => { return color_eyre::eyre::Result::Err( color_eyre::eyre::eyre!("\nAccount information ({account_id}) cannot be fetched on <{}> network due to connectivity issue.\n{err}", network_config.network_name )); } Err(AccountStateError::JsonRpcError( near_jsonrpc_client::errors::JsonRpcError::ServerError(err), )) => { return color_eyre::eyre::Result::Err( color_eyre::eyre::eyre!("\nAccount information ({account_id}) cannot be fetched on <{}> network due to server error.\n{err}", network_config.network_name )); } Err(AccountStateError::Cancel) => { return color_eyre::eyre::Result::Err(color_eyre::eyre::eyre!( "Operation was canceled by the user" )); } }; let storage_amount_per_byte = get_partial_protocol_config(&network_config.json_rpc_client(), &block_reference) .await? .runtime_config .storage_amount_per_byte; Ok(AccountTransferAllowance { account_id, account_liquid_balance: account_view.amount, account_locked_balance: account_view.locked, storage_stake: storage_amount_per_byte.saturating_mul(account_view.storage_usage.into()), // pessimistic_transaction_fee = 10^21 - this value is set temporarily // In the future, its value will be calculated by the function: fn tx_cost(...) // https://github.com/near/nearcore/blob/8a377fda0b4ce319385c463f1ae46e4b0b29dcd9/runtime/runtime/src/config.rs#L178-L232 pessimistic_transaction_fee: near_token::NearToken::from_millinear(1), }) } #[allow(clippy::result_large_err)] #[tracing::instrument(name = "Account access key verification ...", skip_all)] pub fn verify_account_access_key( account_id: near_primitives::types::AccountId, public_key: near_crypto::PublicKey, network_config: crate::config::NetworkConfig, ) -> color_eyre::eyre::Result< near_primitives::views::AccessKeyView, AccountStateError<near_jsonrpc_primitives::types::query::RpcQueryError>, > { tracing::info!(target: "near_teach_me", "Account access key verification ..."); loop { match network_config .json_rpc_client() .blocking_call_view_access_key( &account_id, &public_key, near_primitives::types::BlockReference::latest(), ) .map_err(|err| *err) { Ok(rpc_query_response) => { if let near_jsonrpc_primitives::types::query::QueryResponseKind::AccessKey(result) = rpc_query_response.kind { return Ok(result); } else { return Err(AccountStateError::JsonRpcError(near_jsonrpc_client::errors::JsonRpcError::TransportError(near_jsonrpc_client::errors::RpcTransportError::RecvError( near_jsonrpc_client::errors::JsonRpcTransportRecvError::UnexpectedServerResponse( near_jsonrpc_primitives::message::Message::error(near_jsonrpc_primitives::errors::RpcError::parse_error("Transport error: unexpected server response".to_string())) ), )))); } } Err( err @ near_jsonrpc_client::errors::JsonRpcError::ServerError( near_jsonrpc_client::errors::JsonRpcServerError::HandlerError( near_jsonrpc_primitives::types::query::RpcQueryError::UnknownAccessKey { .. }, ), ), ) => { return Err(AccountStateError::JsonRpcError(err)); } Err(near_jsonrpc_client::errors::JsonRpcError::TransportError(err)) => { let need_check_account = need_check_account(format!("\nAccount information ({account_id}) cannot be fetched on <{}> network due to connectivity issue.", network_config.network_name)); if need_check_account.is_err() { return Err(AccountStateError::Cancel); } if let Ok(false) = need_check_account { return Err(AccountStateError::JsonRpcError( near_jsonrpc_client::errors::JsonRpcError::TransportError(err), )); } } Err(near_jsonrpc_client::errors::JsonRpcError::ServerError(err)) => { let need_check_account = need_check_account(format!("\nAccount information ({account_id}) cannot be fetched on <{}> network due to server error.", network_config.network_name)); if need_check_account.is_err() { return Err(AccountStateError::Cancel); } if let Ok(false) = need_check_account { return Err(AccountStateError::JsonRpcError( near_jsonrpc_client::errors::JsonRpcError::ServerError(err), )); } } } } } #[tracing::instrument(name = "Checking the existence of the account ...", skip_all)] pub fn is_account_exist( networks: &linked_hash_map::LinkedHashMap<String, crate::config::NetworkConfig>, account_id: near_primitives::types::AccountId, ) -> color_eyre::eyre::Result<bool> { tracing::info!(target: "near_teach_me", "Checking the existence of the account ..."); for (_, network_config) in networks { let result = tokio::runtime::Runtime::new() .unwrap() .block_on(get_account_state( network_config, &account_id, near_primitives::types::Finality::Final.into(), )); if result.is_ok() { return Ok(true); } if let Err(AccountStateError::Cancel) = result { return color_eyre::eyre::Result::Err(color_eyre::eyre::eyre!( "Operation was canceled by the user" )); } } Ok(false) } #[tracing::instrument(name = "Searching for a network where an account exists for", skip_all)] pub fn find_network_where_account_exist( context: &crate::GlobalContext, new_account_id: near_primitives::types::AccountId, ) -> color_eyre::eyre::Result<Option<crate::config::NetworkConfig>> { tracing::Span::current().pb_set_message(new_account_id.as_str()); tracing::info!(target: "near_teach_me", "Searching for a network where an account exists for {new_account_id} ..."); for (_, network_config) in context.config.network_connection.iter() { let result = tokio::runtime::Runtime::new() .unwrap() .block_on(get_account_state( network_config, &new_account_id, near_primitives::types::BlockReference::latest(), )); if result.is_ok() { return Ok(Some(network_config.clone())); } if let Err(AccountStateError::Cancel) = result { return color_eyre::eyre::Result::Err(color_eyre::eyre::eyre!( "Operation was canceled by the user" )); } } Ok(None) } pub fn ask_if_different_account_id_wanted() -> color_eyre::eyre::Result<bool> { #[derive(strum_macros::Display, PartialEq)] enum ConfirmOptions { #[strum(to_string = "Yes, I want to enter a new name for account ID.")] Yes, #[strum(to_string = "No, I want to keep using this name for account ID.")] No, } let select_choose_input = Select::new( "Do you want to enter a different name for the new account ID?", vec![ConfirmOptions::Yes, ConfirmOptions::No], ) .prompt()?; Ok(select_choose_input == ConfirmOptions::Yes) } #[tracing::instrument(name = "Getting account status information for", skip_all)] pub async fn get_account_state( network_config: &crate::config::NetworkConfig, account_id: &near_primitives::types::AccountId, block_reference: BlockReference, ) -> color_eyre::eyre::Result< near_primitives::views::AccountView, AccountStateError<near_jsonrpc_primitives::types::query::RpcQueryError>, > { loop { tracing::Span::current().pb_set_message(&format!( "<{account_id}> on network <{}> ...", network_config.network_name )); tracing::info!(target: "near_teach_me", "Getting account status information for <{account_id}> on network <{}> ...", network_config.network_name); let query_view_method_response = view_account( format!("{}", network_config.rpc_url), &network_config.json_rpc_client(), account_id, block_reference.clone(), ) .await; match query_view_method_response { Ok(rpc_query_response) => { if let near_jsonrpc_primitives::types::query::QueryResponseKind::ViewAccount( account_view, ) = rpc_query_response.kind { return Ok(account_view); } else { return Err(AccountStateError::JsonRpcError(near_jsonrpc_client::errors::JsonRpcError::TransportError(near_jsonrpc_client::errors::RpcTransportError::RecvError( near_jsonrpc_client::errors::JsonRpcTransportRecvError::UnexpectedServerResponse( near_jsonrpc_primitives::message::Message::error(near_jsonrpc_primitives::errors::RpcError::parse_error("Transport error: unexpected server response".to_string())) ), )))); } } Err( err @ near_jsonrpc_client::errors::JsonRpcError::ServerError( near_jsonrpc_client::errors::JsonRpcServerError::HandlerError( near_jsonrpc_primitives::types::query::RpcQueryError::UnknownAccount { .. }, ), ), ) => { return Err(AccountStateError::JsonRpcError(err)); } Err(near_jsonrpc_client::errors::JsonRpcError::TransportError(err)) => { let need_check_account = suspend_tracing_indicatif::< _, color_eyre::eyre::Result<bool>, >(|| { need_check_account(format!("\nAccount information ({account_id}) cannot be fetched on <{}> network due to connectivity issue.", network_config.network_name)) }); if need_check_account.is_err() { return Err(AccountStateError::Cancel); } if let Ok(false) = need_check_account { return Err(AccountStateError::JsonRpcError( near_jsonrpc_client::errors::JsonRpcError::TransportError(err), )); } } Err(near_jsonrpc_client::errors::JsonRpcError::ServerError(err)) => { let need_check_account = suspend_tracing_indicatif::< _, color_eyre::eyre::Result<bool>, >(|| { need_check_account(format!("\nAccount information ({account_id}) cannot be fetched on <{}> network due to server error.", network_config.network_name)) }); if need_check_account.is_err() { return Err(AccountStateError::Cancel); } if let Ok(false) = need_check_account { return Err(AccountStateError::JsonRpcError( near_jsonrpc_client::errors::JsonRpcError::ServerError(err), )); } } } } } #[tracing::instrument(name = "Receiving request via RPC", skip_all)] async fn view_account( instrument_message: String, json_rpc_client: &near_jsonrpc_client::JsonRpcClient, account_id: &near_primitives::types::AccountId, block_reference: BlockReference, ) -> Result< near_jsonrpc_primitives::types::query::RpcQueryResponse, near_jsonrpc_client::errors::JsonRpcError<near_jsonrpc_primitives::types::query::RpcQueryError>, > { tracing::Span::current().pb_set_message(&instrument_message); tracing::info!(target: "near_teach_me", "Receiving request via RPC {instrument_message}"); let query_view_method_request = near_jsonrpc_client::methods::query::RpcQueryRequest { block_reference, request: near_primitives::views::QueryRequest::ViewAccount { account_id: account_id.clone(), }, }; tracing::info!( target: "near_teach_me", parent: &tracing::Span::none(), "I am making HTTP call to NEAR JSON RPC to query information about `{}` account, learn more https://docs.near.org/api/rpc/contracts#view-account", account_id ); if let Ok(request_payload) = near_jsonrpc_client::methods::to_json(&query_view_method_request) { tracing::info!( target: "near_teach_me", parent: &tracing::Span::none(), "HTTP POST {}", json_rpc_client.server_addr() ); tracing::info!( target: "near_teach_me", parent: &tracing::Span::none(), "JSON Request Body:\n{}", indent_payload(&format!("{request_payload:#}")) ); } json_rpc_client .call(query_view_method_request) .await .inspect_err(|err| match err { near_jsonrpc_client::errors::JsonRpcError::TransportError(transport_error) => { tracing::info!( target: "near_teach_me", parent: &tracing::Span::none(), "JSON RPC Request failed due to connectivity issue:\n{}", indent_payload(&format!("{transport_error:#?}")) ); } near_jsonrpc_client::errors::JsonRpcError::ServerError( near_jsonrpc_client::errors::JsonRpcServerError::HandlerError(handler_error), ) => { tracing::info!( target: "near_teach_me", parent: &tracing::Span::none(), "JSON RPC Request returned a handling error:\n{}", indent_payload(&serde_json::to_string_pretty(handler_error).unwrap_or_else(|_| handler_error.to_string())) ); } near_jsonrpc_client::errors::JsonRpcError::ServerError(server_error) => { tracing::info!( target: "near_teach_me", parent: &tracing::Span::none(), "JSON RPC Request returned a generic server error:\n{}", indent_payload(&format!("{server_error:#?}")) ); } }) .inspect(teach_me_call_response) } fn need_check_account(message: String) -> color_eyre::eyre::Result<bool> { #[derive(strum_macros::Display, PartialEq)] enum ConfirmOptions { #[strum(to_string = "Yes, I want to check the account again.")] Yes, #[strum(to_string = "No, I want to skip the check and use the specified account ID.")] No, } let select_choose_input = Select::new( &format!("{message}\nDo you want to try again?"), vec![ConfirmOptions::Yes, ConfirmOptions::No], ) .prompt()?; Ok(select_choose_input == ConfirmOptions::Yes) } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct KeyPairProperties { pub seed_phrase_hd_path: crate::types::slip10::BIP32Path, pub master_seed_phrase: String, pub implicit_account_id: near_primitives::types::AccountId, #[serde(rename = "public_key")] pub public_key_str: String, #[serde(rename = "private_key")] pub secret_keypair_str: String, } pub fn get_key_pair_properties_from_seed_phrase( seed_phrase_hd_path: crate::types::slip10::BIP32Path, master_seed_phrase: String, ) -> color_eyre::eyre::Result<KeyPairProperties> { let master_seed = bip39::Mnemonic::parse(&master_seed_phrase)?.to_seed(""); let derived_private_key = slipped10::derive_key_from_path( &master_seed, slipped10::Curve::Ed25519, &seed_phrase_hd_path.clone().into(), ) .map_err(|err| { color_eyre::Report::msg(format!("Failed to derive a key from the master key: {err}")) })?; let signing_key = ed25519_dalek::SigningKey::from_bytes(&derived_private_key.key); let public_key = signing_key.verifying_key(); let implicit_account_id = near_primitives::types::AccountId::try_from(hex::encode(public_key))?; let public_key_str = format!("ed25519:{}", bs58::encode(&public_key).into_string()); let secret_keypair_str = format!( "ed25519:{}", bs58::encode(signing_key.to_keypair_bytes()).into_string() ); let key_pair_properties: KeyPairProperties = KeyPairProperties { seed_phrase_hd_path, master_seed_phrase, implicit_account_id, public_key_str, secret_keypair_str, }; Ok(key_pair_properties) } pub fn get_public_key_from_seed_phrase( seed_phrase_hd_path: slipped10::BIP32Path, master_seed_phrase: &str, ) -> color_eyre::eyre::Result<near_crypto::PublicKey> { let master_seed = bip39::Mnemonic::parse(master_seed_phrase)?.to_seed(""); let derived_private_key = slipped10::derive_key_from_path( &master_seed, slipped10::Curve::Ed25519, &seed_phrase_hd_path, ) .map_err(|err| { color_eyre::Report::msg(format!("Failed to derive a key from the master key: {err}")) })?; let signing_key = ed25519_dalek::SigningKey::from_bytes(&derived_private_key.key); let public_key_str = format!( "ed25519:{}", bs58::encode(&signing_key.verifying_key()).into_string() ); Ok(near_crypto::PublicKey::from_str(&public_key_str)?) } pub fn generate_keypair() -> color_eyre::eyre::Result<KeyPairProperties> { let generate_keypair: crate::utils_command::generate_keypair_subcommand::CliGenerateKeypair = crate::utils_command::generate_keypair_subcommand::CliGenerateKeypair::default(); let (master_seed_phrase, master_seed) = if let Some(master_seed_phrase) = generate_keypair.master_seed_phrase.as_deref() { ( master_seed_phrase.to_owned(), bip39::Mnemonic::parse(master_seed_phrase)?.to_seed(""), ) } else { let mnemonic = bip39::Mnemonic::generate(generate_keypair.new_master_seed_phrase_words_count)?; let master_seed_phrase = mnemonic.words().collect::<Vec<&str>>().join(" "); (master_seed_phrase, mnemonic.to_seed("")) }; let derived_private_key = slipped10::derive_key_from_path( &master_seed, slipped10::Curve::Ed25519, &generate_keypair.seed_phrase_hd_path.clone().into(), ) .map_err(|err| { color_eyre::Report::msg(format!("Failed to derive a key from the master key: {err}")) })?; let signing_key = ed25519_dalek::SigningKey::from_bytes(&derived_private_key.key); let public = signing_key.verifying_key(); let implicit_account_id = near_primitives::types::AccountId::try_from(hex::encode(public))?; let public_key_str = format!("ed25519:{}", bs58::encode(&public).into_string()); let secret_keypair_str = format!( "ed25519:{}", bs58::encode(signing_key.to_keypair_bytes()).into_string() ); let key_pair_properties: KeyPairProperties = KeyPairProperties { seed_phrase_hd_path: generate_keypair.seed_phrase_hd_path, master_seed_phrase, implicit_account_id, public_key_str, secret_keypair_str, }; Ok(key_pair_properties) } pub fn print_full_signed_transaction( transaction: near_primitives::transaction::SignedTransaction, ) -> String { let mut info_str = format!("\n{:<13} {}", "signature:", transaction.signature); info_str.push_str(&crate::common::print_full_unsigned_transaction( transaction.transaction, )); info_str } pub fn print_full_unsigned_transaction( transaction: near_primitives::transaction::Transaction, ) -> String { let mut info_str = format!( "\nunsigned transaction hash (Base58-encoded SHA-256 hash): {}", transaction.get_hash_and_size().0 ); info_str.push_str(&format!( "\n{:<13} {}", "public_key:", &transaction.public_key() )); info_str.push_str(&format!("\n{:<13} {}", "nonce:", &transaction.nonce())); info_str.push_str(&format!( "\n{:<13} {}", "block_hash:", &transaction.block_hash() )); let prepopulated = crate::commands::PrepopulatedTransaction::from(transaction); info_str.push_str(&print_unsigned_transaction(&prepopulated)); info_str } pub fn print_unsigned_transaction( transaction: &crate::commands::PrepopulatedTransaction, ) -> String { let mut info_str = String::new(); info_str.push_str(&format!("\n{:<13} {}", "signer_id:", transaction.signer_id)); info_str.push_str(&format!( "\n{:<13} {}", "receiver_id:", transaction.receiver_id )); if transaction .actions .iter() .any(|action| matches!(action, near_primitives::transaction::Action::Delegate(_))) { info_str.push_str("\nsigned delegate action:"); } else { info_str.push_str("\nactions:"); }; for action in &transaction.actions { match action { near_primitives::transaction::Action::CreateAccount(_) => { info_str.push_str(&format!( "\n{:>5} {:<20} {}", "--", "create account:", &transaction.receiver_id )); } near_primitives::transaction::Action::DeployContract(code) => { let code_hash = CryptoHash::hash_bytes(&code.code); info_str.push_str(&format!( "\n{:>5} {:<70}", "--", format!( "deploy code <{:?}> to a account <{}>", code_hash, transaction.receiver_id ) )) } near_primitives::transaction::Action::FunctionCall(function_call_action) => { info_str.push_str(&format!("\n{:>5} {:<20}", "--", "function call:")); info_str.push_str(&format!( "\n{:>18} {:<13} {}", "", "method name:", &function_call_action.method_name )); info_str.push_str(&format!( "\n{:>18} {:<13} {}", "", "args:", match serde_json::from_slice::<serde_json::Value>(&function_call_action.args) { Ok(parsed_args) => { serde_json::to_string_pretty(&parsed_args) .unwrap_or_else(|_| "".to_string()) .replace('\n', "\n ") } Err(_) => { if let Ok(args) = String::from_utf8(function_call_action.args.clone()) { args } else { format!( "<non-printable data ({})>", bytesize::ByteSize(function_call_action.args.len() as u64) ) } } } )); info_str.push_str(&format!( "\n{:>18} {:<13} {}", "", "gas:", function_call_action.gas )); info_str.push_str(&format!( "\n{:>18} {:<13} {}", "", "deposit:", function_call_action.deposit.exact_amount_display() )); } near_primitives::transaction::Action::Transfer(transfer_action) => { info_str.push_str(&format!( "\n{:>5} {:<20} {}", "--", "transfer deposit:", transfer_action.deposit.exact_amount_display() )); } near_primitives::transaction::Action::Stake(stake_action) => { info_str.push_str(&format!("\n{:>5} {:<20}", "--", "stake:")); info_str.push_str(&format!( "\n{:>18} {:<13} {}", "", "public key:", &stake_action.public_key )); info_str.push_str(&format!( "\n{:>18} {:<13} {}", "", "stake:", stake_action.stake.exact_amount_display() )); } near_primitives::transaction::Action::AddKey(add_key_action) => { info_str.push_str(&format!("\n{:>5} {:<20}", "--", "add access key:")); info_str.push_str(&format!( "\n{:>18} {:<13} {}", "", "public key:", &add_key_action.public_key )); info_str.push_str(&format!( "\n{:>18} {:<13} {}", "", "nonce:", &add_key_action.access_key.nonce )); info_str.push_str(&format!( "\n{:>18} {:<13} {:?}", "", "permission:", &add_key_action.access_key.permission )); } near_primitives::transaction::Action::DeleteKey(delete_key_action) => { info_str.push_str(&format!("\n{:>5} {:<20}", "--", "delete access key:"));
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
true
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/transaction_signature_options/mod.rs
src/transaction_signature_options/mod.rs
use serde::Deserialize; use strum::{EnumDiscriminants, EnumIter, EnumMessage}; pub mod display; pub mod save_to_file; pub mod send; pub mod sign_later; pub mod sign_with_access_key_file; pub mod sign_with_keychain; #[cfg(feature = "ledger")] pub mod sign_with_ledger; pub mod sign_with_legacy_keychain; pub mod sign_with_mpc; pub mod sign_with_private_key; pub mod sign_with_seed_phrase; pub mod submit_dao_proposal; pub const META_TRANSACTION_VALID_FOR_DEFAULT: u64 = 1000; #[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = crate::commands::TransactionContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Select a tool for signing the transaction: pub enum SignWith { #[strum_discriminants(strum( message = "sign-with-keychain - Sign the transaction with a key saved in the secure keychain" ))] /// Sign the transaction with a key saved in keychain SignWithKeychain(self::sign_with_keychain::SignKeychain), #[strum_discriminants(strum( message = "sign-with-legacy-keychain - Sign the transaction with a key saved in legacy keychain (compatible with the old near CLI)" ))] /// Sign the transaction with a key saved in legacy keychain (compatible with the old near CLI) SignWithLegacyKeychain(self::sign_with_legacy_keychain::SignLegacyKeychain), #[cfg(feature = "ledger")] #[strum_discriminants(strum( message = "sign-with-ledger - Sign the transaction with Ledger Nano device" ))] /// Sign the transaction with Ledger Nano device SignWithLedger(self::sign_with_ledger::SignLedger), #[strum_discriminants(strum( message = "sign-with-plaintext-private-key - Sign the transaction with a plaintext private key" ))] /// Sign the transaction with a plaintext private key SignWithPlaintextPrivateKey(self::sign_with_private_key::SignPrivateKey), #[strum_discriminants(strum( message = "sign-with-access-key-file - Sign the transaction using the account access key file (access-key-file.json)" ))] /// Sign the transaction using the account access key file (access-key-file.json) SignWithAccessKeyFile(self::sign_with_access_key_file::SignAccessKeyFile), #[strum_discriminants(strum( message = "sign-with-seed-phrase - Sign the transaction using the seed phrase" ))] /// Sign the transaction using the seed phrase SignWithSeedPhrase(self::sign_with_seed_phrase::SignSeedPhrase), #[strum_discriminants(strum( message = "sign-with-mpc - Sign and send the transaction with MPC" ))] /// Sign and send the transaction with MPC SignWithMpc(crate::transaction_signature_options::sign_with_mpc::SignMpc), #[strum_discriminants(strum( message = "sign-later - Prepare an unsigned transaction to sign it later" ))] /// Prepare unsigned transaction to sign it later SignLater(self::sign_later::SignLater), #[strum_discriminants(strum( message = "submit-as-dao-proposal - Convert current transaction to DAO proposal" ))] /// Prepare transaction as dao proposal SubmitAsDaoProposal(self::submit_dao_proposal::DaoProposal), } #[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = SubmitContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// How would you like to proceed? pub enum Submit { #[strum_discriminants(strum( message = "send - Send the transaction to the network" ))] /// Send the transaction to the network Send(self::send::Send), #[strum_discriminants(strum( message = "save-to-file - Save the signed transaction to file (if you want to send it later)" ))] /// Save the signed transaction to file (if you want to send it later) SaveToFile(self::save_to_file::SaveToFile), #[strum_discriminants(strum( message = "display - Print the signed transaction to terminal (if you want to send it later)" ))] /// Print the signed transaction to terminal (if you want to send it later) Display(self::display::Display), } #[derive(Debug, Deserialize)] pub struct AccountKeyPair { pub public_key: near_crypto::PublicKey, pub private_key: near_crypto::SecretKey, } pub type OnBeforeSendingTransactionCallback = std::sync::Arc< dyn Fn( &SignedTransactionOrSignedDelegateAction, &crate::config::NetworkConfig, ) -> color_eyre::eyre::Result<String>, >; pub type OnAfterSendingTransactionCallback = std::sync::Arc< dyn Fn( &near_primitives::views::FinalExecutionOutcomeView, &crate::config::NetworkConfig, ) -> crate::CliResult, >; #[derive(Clone)] pub struct SubmitContext { pub network_config: crate::config::NetworkConfig, pub global_context: crate::GlobalContext, pub signed_transaction_or_signed_delegate_action: SignedTransactionOrSignedDelegateAction, pub on_before_sending_transaction_callback: OnBeforeSendingTransactionCallback, pub on_after_sending_transaction_callback: OnAfterSendingTransactionCallback, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub enum SignedTransactionOrSignedDelegateAction { SignedTransaction(near_primitives::transaction::SignedTransaction), SignedDelegateAction(near_primitives::action::delegate::SignedDelegateAction), } impl From<near_primitives::transaction::SignedTransaction> for SignedTransactionOrSignedDelegateAction { fn from(signed_transaction: near_primitives::transaction::SignedTransaction) -> Self { Self::SignedTransaction(signed_transaction) } } impl From<near_primitives::action::delegate::SignedDelegateAction> for SignedTransactionOrSignedDelegateAction { fn from( signed_delegate_action: near_primitives::action::delegate::SignedDelegateAction, ) -> Self { Self::SignedDelegateAction(signed_delegate_action) } } pub fn get_signed_delegate_action( unsigned_transaction: near_primitives::transaction::Transaction, public_key: &near_crypto::PublicKey, private_key: near_crypto::SecretKey, max_block_height: u64, ) -> near_primitives::action::delegate::SignedDelegateAction { use near_primitives::signable_message::{SignableMessage, SignableMessageType}; let mut delegate_action = near_primitives::action::delegate::DelegateAction { sender_id: unsigned_transaction.signer_id().clone(), receiver_id: unsigned_transaction.receiver_id().clone(), actions: vec![], nonce: unsigned_transaction.nonce(), max_block_height, public_key: unsigned_transaction.public_key().clone(), }; delegate_action.actions = unsigned_transaction .take_actions() .into_iter() .map(near_primitives::action::delegate::NonDelegateAction::try_from) .collect::<Result<_, _>>() .expect("Internal error: can not convert the action to non delegate action (delegate action can not be delegated again)."); // create a new signature here signing the delegate action + discriminant let signable = SignableMessage::new(&delegate_action, SignableMessageType::DelegateAction); let signer = near_crypto::InMemorySigner::from_secret_key( delegate_action.sender_id.clone(), private_key, ); let signature = signable.sign(&signer); tracing::info!( parent: &tracing::Span::none(), "Your delegating action was signed successfully.{}", crate::common::indent_payload(&format!( "\nNote that the signed transaction is valid until block {max_block_height}. You can change the validity of a transaction by setting a flag in the command: --meta-transaction-valid-for 2000\nPublic key: {public_key}\nSignature: {signature}\n" )) ); near_primitives::action::delegate::SignedDelegateAction { delegate_action, signature, } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/transaction_signature_options/submit_dao_proposal/dao_kind_arguments.rs
src/transaction_signature_options/submit_dao_proposal/dao_kind_arguments.rs
use color_eyre::eyre::{eyre, Context}; use near_primitives::action::Action; use serde::{Deserialize, Serialize}; use serde_with::{base64::Base64, serde_as}; #[serde_as] #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ActionCall { method_name: String, #[serde_as(as = "Base64")] args: Vec<u8>, deposit: near_token::NearToken, gas: near_gas::NearGas, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct TransferArgs { #[serde(default)] token_id: String, receiver_id: near_primitives::types::AccountId, amount: crate::types::near_token::NearToken, msg: Option<String>, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct FunctionCallArgs { receiver_id: near_primitives::types::AccountId, actions: Vec<ActionCall>, } #[derive(Clone, Debug, Serialize, Deserialize)] /// Enum for DAO proposal arguments /// /// Directly translates to `{ "TransferKindName": TransferArguments }` pub enum ProposalKind { Transfer(TransferArgs), FunctionCall(FunctionCallArgs), } impl TryFrom<&crate::commands::PrepopulatedTransaction> for ProposalKind { type Error = color_eyre::eyre::Error; fn try_from( transaction: &crate::commands::PrepopulatedTransaction, ) -> Result<Self, Self::Error> { let Some(first_action) = transaction.actions.first() else { return Err(eyre!("No actions were found in transaction!")); }; match first_action { Action::Transfer(transfer_action) => { if transaction.actions.len() > 1 { Err(eyre!("Batch transfers are not supported for DAO proposals")) } else { Ok(ProposalKind::Transfer(TransferArgs { token_id: String::new(), receiver_id: transaction.receiver_id.clone(), amount: transfer_action.deposit.into(), msg: None, })) } } Action::FunctionCall(_) => { let action_calls: Vec<_> = transaction .actions .iter() .filter_map(|action| { if let Action::FunctionCall(function_call_action) = action { Some(ActionCall { method_name: function_call_action.method_name.clone(), args: function_call_action.args.clone(), deposit: function_call_action.deposit, gas: near_gas::NearGas::from_gas(function_call_action.gas.as_gas()), }) } else { None } }) .collect(); if action_calls.len() != transaction.actions.len() { Err(eyre!( "Mixed action types are not supported for DAO proposals" )) } else { Ok(ProposalKind::FunctionCall(FunctionCallArgs { receiver_id: transaction.receiver_id.clone(), actions: action_calls, })) } } _action => Err(eyre!( "Passed action type is not supported for DAO proposal", )), } } } impl ProposalKind { pub fn try_to_mpc_sign_request( self, network_config: &crate::config::NetworkConfig, ) -> Result< crate::transaction_signature_options::sign_with_mpc::mpc_sign_request::MpcSignRequest, color_eyre::eyre::Error, > { match self { ProposalKind::FunctionCall(fc_args) => { if fc_args.receiver_id != network_config.get_mpc_contract_account_id()? { return Err(color_eyre::eyre::eyre!( "ReceiverId of Function Call proposal doesn't match MPC contract AccountId in selected NetworkConfig!" )); } let mpc_sign_action = fc_args.actions.first().ok_or_else(|| { color_eyre::eyre::eyre!( "Function Call proposal has no actions, but MPC sign requires at least one" ) })?; if mpc_sign_action.method_name != "sign" { return Err(color_eyre::eyre::eyre!( "Method name for MPC sign Function Call is not \"sign\"" )); } serde_json::from_slice(&mpc_sign_action.args).wrap_err_with(|| { format!( "{}{}", "Failed to parse MPC sign request from Function Call action arguments.\n", "Expected SignRequest structure with 'request' field containing payload_v2, path, and domain_id." ) }) } _ => Err(eyre!( "Proposal Kind is not FunctionCall and cannot be turned to MpcSignRequest!" )), } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/transaction_signature_options/submit_dao_proposal/mod.rs
src/transaction_signature_options/submit_dao_proposal/mod.rs
use inquire::CustomType; use inquire::Text; pub mod dao_kind_arguments; pub mod dao_sign_with; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::commands::TransactionContext)] #[interactive_clap(output_context = DaoProposalContext)] pub struct DaoProposal { #[interactive_clap(skip_default_input_arg)] /// What is dao account ID? dao_account_id: crate::types::account_id::AccountId, #[interactive_clap(subargs)] /// Proposal function params proposal_arguments: DaoProposalArguments, } #[derive(Clone)] pub struct DaoProposalContext { global_context: crate::GlobalContext, network_config: crate::config::NetworkConfig, on_after_sending_transaction_callback: crate::transaction_signature_options::OnAfterSendingTransactionCallback, dao_account_id: near_primitives::types::AccountId, receiver_id: near_primitives::types::AccountId, proposal_kind: dao_kind_arguments::ProposalKind, } impl DaoProposalContext { pub fn from_previous_context( previous_context: crate::commands::TransactionContext, scope: &<DaoProposal as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let proposal_kind = dao_kind_arguments::ProposalKind::try_from(&previous_context.prepopulated_transaction)?; let on_after_sending_transaction_callback = if proposal_kind .clone() .try_to_mpc_sign_request(&previous_context.network_config) .is_ok() { previous_context.on_after_sending_transaction_callback } else { std::sync::Arc::new( |_final_outcome_view: &near_primitives::views::FinalExecutionOutcomeView, _network_config: &crate::config::NetworkConfig| Ok(()), ) }; Ok(Self { global_context: previous_context.global_context, network_config: previous_context.network_config, on_after_sending_transaction_callback, dao_account_id: scope.dao_account_id.clone().into(), receiver_id: previous_context.prepopulated_transaction.signer_id.clone(), proposal_kind, }) } } impl DaoProposal { pub fn input_dao_account_id( context: &crate::commands::TransactionContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { crate::common::input_signer_account_id_from_used_account_list( &context.global_context.config.credentials_home_dir, "What is the DAO member account ID?", ) } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = DaoProposalContext)] #[interactive_clap(output_context = DaoProposalArgumentsContext)] pub struct DaoProposalArguments { #[interactive_clap(skip_default_input_arg)] /// Enter proposal description: proposal_description: String, #[interactive_clap(named_arg)] /// Enter gas amount for DAO proposal: prepaid_gas: PrepaidGas, } #[derive(Clone)] pub struct DaoProposalArgumentsContext { global_context: crate::GlobalContext, network_config: crate::config::NetworkConfig, on_after_sending_transaction_callback: crate::transaction_signature_options::OnAfterSendingTransactionCallback, dao_account_id: near_primitives::types::AccountId, receiver_id: near_primitives::types::AccountId, proposal_args: Vec<u8>, } impl DaoProposalArgumentsContext { pub fn from_previous_context( previous_context: DaoProposalContext, scope: &<DaoProposalArguments as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let proposal_args = serde_json::to_vec(&serde_json::json!({ "proposal": { "description": scope.proposal_description, "kind": previous_context.proposal_kind, }, }))?; Ok(Self { global_context: previous_context.global_context, network_config: previous_context.network_config, on_after_sending_transaction_callback: previous_context .on_after_sending_transaction_callback, dao_account_id: previous_context.dao_account_id, receiver_id: previous_context.receiver_id, proposal_args, }) } } impl DaoProposalArguments { pub fn input_proposal_description( _context: &DaoProposalContext, ) -> color_eyre::eyre::Result<Option<String>> { Ok(Some( Text::new("Enter a description for the DAO proposal:").prompt()?, )) } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = DaoProposalArgumentsContext)] #[interactive_clap(output_context = PrepaidGasContext)] pub struct PrepaidGas { #[interactive_clap(skip_default_input_arg)] /// Enter gas amount for DAO proposal: gas: crate::common::NearGas, #[interactive_clap(named_arg)] /// Enter deposit for DAO proposal: attached_deposit: Deposit, } #[derive(Clone)] pub struct PrepaidGasContext { global_context: crate::GlobalContext, network_config: crate::config::NetworkConfig, on_after_sending_transaction_callback: crate::transaction_signature_options::OnAfterSendingTransactionCallback, dao_account_id: near_primitives::types::AccountId, receiver_id: near_primitives::types::AccountId, proposal_args: Vec<u8>, gas: crate::common::NearGas, } impl PrepaidGasContext { pub fn from_previous_context( previous_context: DaoProposalArgumentsContext, scope: &<PrepaidGas as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self { global_context: previous_context.global_context, network_config: previous_context.network_config, on_after_sending_transaction_callback: previous_context .on_after_sending_transaction_callback, dao_account_id: previous_context.dao_account_id, receiver_id: previous_context.receiver_id, proposal_args: previous_context.proposal_args, gas: scope.gas, }) } } impl PrepaidGas { pub fn input_gas( _context: &DaoProposalArgumentsContext, ) -> color_eyre::eyre::Result<Option<crate::common::NearGas>> { Ok(Some( CustomType::new( "What is the gas limit for adding a DAO proposal (if you're not sure, keep 10 Tgas)?", ) .with_starting_input("10 Tgas") .with_validator(move |gas: &crate::common::NearGas| { if gas > &near_gas::NearGas::from_tgas(300) { Ok(inquire::validator::Validation::Invalid( inquire::validator::ErrorMessage::Custom( "You need to enter a value of no more than 300 TeraGas".to_string(), ), )) } else { Ok(inquire::validator::Validation::Valid) } }) .prompt()?, )) } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context=PrepaidGasContext)] #[interactive_clap(output_context=DepositContext)] pub struct Deposit { #[interactive_clap(skip_default_input_arg)] /// Enter deposit for DAO proposal: deposit: crate::types::near_token::NearToken, #[interactive_clap(subcommand)] transaction_signature_options: dao_sign_with::DaoSignWith, } #[derive(Clone)] pub struct DepositContext { global_context: crate::GlobalContext, network_config: crate::config::NetworkConfig, on_after_sending_transaction_callback: crate::transaction_signature_options::OnAfterSendingTransactionCallback, dao_account_id: near_primitives::types::AccountId, receiver_id: near_primitives::types::AccountId, proposal_args: Vec<u8>, gas: crate::common::NearGas, deposit: crate::types::near_token::NearToken, } impl DepositContext { pub fn from_previous_context( previous_context: PrepaidGasContext, scope: &<Deposit as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self { global_context: previous_context.global_context, network_config: previous_context.network_config, on_after_sending_transaction_callback: previous_context .on_after_sending_transaction_callback, dao_account_id: previous_context.dao_account_id, receiver_id: previous_context.receiver_id, proposal_args: previous_context.proposal_args, gas: previous_context.gas, deposit: scope.deposit, }) } } impl Deposit { pub fn input_deposit( _context: &PrepaidGasContext, ) -> color_eyre::eyre::Result<Option<crate::types::near_token::NearToken>> { Ok(Some( CustomType::new("Enter deposit for adding a DAO proposal:") .with_starting_input("0 NEAR") .prompt()?, )) } } impl From<DepositContext> for crate::commands::TransactionContext { fn from(item: DepositContext) -> Self { let new_prepopulated_transaction = crate::commands::PrepopulatedTransaction { signer_id: item.dao_account_id, receiver_id: item.receiver_id, actions: vec![near_primitives::transaction::Action::FunctionCall( Box::new(near_primitives::transaction::FunctionCallAction { method_name: "add_proposal".to_string(), args: item.proposal_args.clone(), gas: near_primitives::gas::Gas::from_gas(item.gas.as_gas()), deposit: item.deposit.into(), }), )], }; tracing::info!( "{}{}", "Unsigned DAO proposal", crate::common::indent_payload(&crate::common::print_unsigned_transaction( &new_prepopulated_transaction, )) ); Self { global_context: item.global_context, network_config: item.network_config, prepopulated_transaction: new_prepopulated_transaction, on_before_signing_callback: std::sync::Arc::new( |_prepopulated_unsigned_transaction, _network_config| Ok(()), ), on_after_signing_callback: std::sync::Arc::new( |_signed_transaction, _network_config| Ok(()), ), on_before_sending_transaction_callback: std::sync::Arc::new( |_signed_transaction, _network_config| Ok(String::new()), ), on_after_sending_transaction_callback: item.on_after_sending_transaction_callback, } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/transaction_signature_options/submit_dao_proposal/dao_sign_with.rs
src/transaction_signature_options/submit_dao_proposal/dao_sign_with.rs
use strum::{EnumDiscriminants, EnumIter, EnumMessage}; #[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = crate::commands::TransactionContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Select a tool for signing the DAO proposal transaction: pub enum DaoSignWith { #[strum_discriminants(strum( message = "sign-with-keychain - Sign the transaction with a key saved in the secure keychain" ))] /// Sign the transaction with a key saved in keychain SignWithKeychain(crate::transaction_signature_options::sign_with_keychain::SignKeychain), #[strum_discriminants(strum( message = "sign-with-legacy-keychain - Sign the transaction with a key saved in legacy keychain (compatible with the old near CLI)" ))] /// Sign the transaction with a key saved in legacy keychain (compatible with the old near CLI) SignWithLegacyKeychain( crate::transaction_signature_options::sign_with_legacy_keychain::SignLegacyKeychain, ), #[cfg(feature = "ledger")] #[strum_discriminants(strum( message = "sign-with-ledger - Sign the transaction with Ledger Nano device" ))] /// Sign the transaction with Ledger Nano device SignWithLedger(crate::transaction_signature_options::sign_with_ledger::SignLedger), #[strum_discriminants(strum( message = "sign-with-plaintext-private-key - Sign the transaction with a plaintext private key" ))] /// Sign the transaction with a plaintext private key SignWithPlaintextPrivateKey( crate::transaction_signature_options::sign_with_private_key::SignPrivateKey, ), #[strum_discriminants(strum( message = "sign-with-access-key-file - Sign the transaction using the account access key file (access-key-file.json)" ))] /// Sign the transaction using the account access key file (access-key-file.json) SignWithAccessKeyFile( crate::transaction_signature_options::sign_with_access_key_file::SignAccessKeyFile, ), #[strum_discriminants(strum( message = "sign-with-seed-phrase - Sign the transaction using the seed phrase" ))] /// Sign the transaction using the seed phrase SignWithSeedPhrase(crate::transaction_signature_options::sign_with_seed_phrase::SignSeedPhrase), #[strum_discriminants(strum( message = "sign-later - Prepare an unsigned transaction to sign it later" ))] /// Prepare unsigned transaction to sign it later SignLater(crate::transaction_signature_options::sign_later::SignLater), }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/transaction_signature_options/display/mod.rs
src/transaction_signature_options/display/mod.rs
#[derive(Debug, Clone, interactive_clap_derive::InteractiveClap)] #[interactive_clap(input_context = super::SubmitContext)] #[interactive_clap(output_context = DisplayContext)] pub struct Display; #[derive(Debug, Clone)] pub struct DisplayContext; impl DisplayContext { pub fn from_previous_context( previous_context: super::SubmitContext, _scope: &<Display as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let storage_message = (previous_context.on_before_sending_transaction_callback)( &previous_context.signed_transaction_or_signed_delegate_action, &previous_context.network_config, ) .map_err(color_eyre::Report::msg)?; match previous_context.signed_transaction_or_signed_delegate_action { super::SignedTransactionOrSignedDelegateAction::SignedTransaction( signed_transaction, ) => { eprintln!( "\nSigned transaction (serialized as base64):\n{}\n", crate::types::signed_transaction::SignedTransactionAsBase64::from( signed_transaction ) ); eprintln!( "This base64-encoded signed transaction is ready to be sent to the network. You can call RPC server directly, or use a helper command on near CLI:\n$ {} transaction send-signed-transaction\n", crate::common::get_near_exec_path() ); eprintln!("{storage_message}"); } super::SignedTransactionOrSignedDelegateAction::SignedDelegateAction( signed_delegate_action, ) => { eprintln!( "\nSigned delegate action (serialized as base64):\n{}\n", crate::types::signed_delegate_action::SignedDelegateActionAsBase64::from( signed_delegate_action ) ); eprintln!( "This base64-encoded signed delegate action is ready to be sent to the meta-transaction relayer. There is a helper command on near CLI that can do that:\n$ {} transaction send-meta-transaction\n", crate::common::get_near_exec_path() ); eprintln!("{storage_message}"); } } Ok(Self) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/transaction_signature_options/sign_with_seed_phrase/mod.rs
src/transaction_signature_options/sign_with_seed_phrase/mod.rs
use std::str::FromStr; use color_eyre::eyre::{ContextCompat, WrapErr}; use inquire::CustomType; use near_primitives::transaction::Transaction; use near_primitives::transaction::TransactionV0; use crate::common::JsonRpcClientExt; use crate::common::RpcQueryResponseExt; #[derive(Debug, Clone, interactive_clap_derive::InteractiveClap)] #[interactive_clap(input_context = crate::commands::TransactionContext)] #[interactive_clap(output_context = SignSeedPhraseContext)] pub struct SignSeedPhrase { /// Enter the seed-phrase for this account: master_seed_phrase: String, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] seed_phrase_hd_path: crate::types::slip10::BIP32Path, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] pub nonce: Option<u64>, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] pub block_hash: Option<crate::types::crypto_hash::CryptoHash>, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] pub block_height: Option<near_primitives::types::BlockHeight>, #[interactive_clap(long)] #[interactive_clap(skip_interactive_input)] meta_transaction_valid_for: Option<u64>, #[interactive_clap(subcommand)] submit: super::Submit, } #[derive(Clone)] pub struct SignSeedPhraseContext { network_config: crate::config::NetworkConfig, global_context: crate::GlobalContext, signed_transaction_or_signed_delegate_action: super::SignedTransactionOrSignedDelegateAction, on_before_sending_transaction_callback: crate::transaction_signature_options::OnBeforeSendingTransactionCallback, on_after_sending_transaction_callback: crate::transaction_signature_options::OnAfterSendingTransactionCallback, } impl SignSeedPhraseContext { #[tracing::instrument(name = "Signing the transaction using the seed phrase ...", skip_all)] pub fn from_previous_context( previous_context: crate::commands::TransactionContext, scope: &<SignSeedPhrase as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { tracing::info!(target: "near_teach_me", "Signing the transaction using the seed phrase ..."); let network_config = previous_context.network_config.clone(); let key_pair_properties = crate::common::get_key_pair_properties_from_seed_phrase( scope.seed_phrase_hd_path.clone(), scope.master_seed_phrase.clone(), )?; let signer_secret_key: near_crypto::SecretKey = near_crypto::SecretKey::from_str(&key_pair_properties.secret_keypair_str)?; let signer_public_key = near_crypto::PublicKey::from_str(&key_pair_properties.public_key_str)?; let (nonce, block_hash, block_height) = if previous_context.global_context.offline { ( scope .nonce .wrap_err("Nonce is required to sign a transaction in offline mode")?, scope .block_hash .wrap_err("Block Hash is required to sign a transaction in offline mode")? .0, scope .block_height .wrap_err("Block Height is required to sign a transaction in offline mode")?, ) } else { let rpc_query_response = network_config .json_rpc_client() .blocking_call_view_access_key( &previous_context.prepopulated_transaction.signer_id, &signer_public_key, near_primitives::types::BlockReference::latest() ) .wrap_err_with(|| format!("Cannot sign a transaction due to an error while fetching the most recent nonce value on network <{}>", network_config.network_name) )?; ( rpc_query_response .access_key_view() .wrap_err("Error current_nonce")? .nonce + 1, rpc_query_response.block_hash, rpc_query_response.block_height, ) }; let mut unsigned_transaction = TransactionV0 { public_key: signer_public_key.clone(), block_hash, nonce, signer_id: previous_context.prepopulated_transaction.signer_id, receiver_id: previous_context.prepopulated_transaction.receiver_id, actions: previous_context.prepopulated_transaction.actions, }; (previous_context.on_before_signing_callback)(&mut unsigned_transaction, &network_config)?; let unsigned_transaction = Transaction::V0(unsigned_transaction); let signature = signer_secret_key.sign(unsigned_transaction.get_hash_and_size().0.as_ref()); if network_config.meta_transaction_relayer_url.is_some() { let max_block_height = block_height + scope .meta_transaction_valid_for .unwrap_or(super::META_TRANSACTION_VALID_FOR_DEFAULT); let signed_delegate_action = super::get_signed_delegate_action( unsigned_transaction, &signer_public_key, signer_secret_key, max_block_height, ); return Ok(Self { network_config: previous_context.network_config, global_context: previous_context.global_context, signed_transaction_or_signed_delegate_action: signed_delegate_action.into(), on_before_sending_transaction_callback: previous_context .on_before_sending_transaction_callback, on_after_sending_transaction_callback: previous_context .on_after_sending_transaction_callback, }); } let mut signed_transaction = near_primitives::transaction::SignedTransaction::new( signature.clone(), unsigned_transaction, ); tracing::info!( parent: &tracing::Span::none(), "Your transaction was signed successfully.{}", crate::common::indent_payload(&format!( "\nPublic key: {signer_public_key}\nSignature: {signature}\n " )) ); (previous_context.on_after_signing_callback)( &mut signed_transaction, &previous_context.network_config, )?; Ok(Self { network_config: previous_context.network_config, global_context: previous_context.global_context, signed_transaction_or_signed_delegate_action: signed_transaction.into(), on_before_sending_transaction_callback: previous_context .on_before_sending_transaction_callback, on_after_sending_transaction_callback: previous_context .on_after_sending_transaction_callback, }) } } impl From<SignSeedPhraseContext> for super::SubmitContext { fn from(item: SignSeedPhraseContext) -> Self { Self { network_config: item.network_config, global_context: item.global_context, signed_transaction_or_signed_delegate_action: item .signed_transaction_or_signed_delegate_action, on_before_sending_transaction_callback: item.on_before_sending_transaction_callback, on_after_sending_transaction_callback: item.on_after_sending_transaction_callback, } } } impl SignSeedPhrase { fn input_nonce( context: &crate::commands::TransactionContext, ) -> color_eyre::eyre::Result<Option<u64>> { if context.global_context.offline { return Ok(Some( CustomType::<u64>::new("Enter a nonce for the access key:").prompt()?, )); } Ok(None) } fn input_block_hash( context: &crate::commands::TransactionContext, ) -> color_eyre::eyre::Result<Option<crate::types::crypto_hash::CryptoHash>> { if context.global_context.offline { return Ok(Some( CustomType::<crate::types::crypto_hash::CryptoHash>::new( "Enter recent block hash:", ) .prompt()?, )); } Ok(None) } fn input_block_height( context: &crate::commands::TransactionContext, ) -> color_eyre::eyre::Result<Option<near_primitives::types::BlockHeight>> { if context.global_context.offline { return Ok(Some( CustomType::<near_primitives::types::BlockHeight>::new( "Enter recent block height:", ) .prompt()?, )); } Ok(None) } fn input_seed_phrase_hd_path( _context: &crate::commands::TransactionContext, ) -> color_eyre::eyre::Result<Option<crate::types::slip10::BIP32Path>> { input_seed_phrase_hd_path() } } pub fn input_seed_phrase_hd_path( ) -> color_eyre::eyre::Result<Option<crate::types::slip10::BIP32Path>> { Ok(Some( CustomType::new("Enter seed phrase HD Path (if you're not sure, keep the default):") .with_starting_input("m/44'/397'/0'") .prompt()?, )) }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/transaction_signature_options/sign_with_keychain/mod.rs
src/transaction_signature_options/sign_with_keychain/mod.rs
use color_eyre::eyre::{ContextCompat, WrapErr}; use inquire::CustomType; use near_primitives::transaction::Transaction; use near_primitives::transaction::TransactionV0; use tracing_indicatif::span_ext::IndicatifSpanExt; use crate::common::JsonRpcClientExt; use crate::common::RpcQueryResponseExt; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::commands::TransactionContext)] #[interactive_clap(output_context = SignKeychainContext)] pub struct SignKeychain { #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] signer_public_key: Option<crate::types::public_key::PublicKey>, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] nonce: Option<u64>, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] block_hash: Option<crate::types::crypto_hash::CryptoHash>, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] block_height: Option<near_primitives::types::BlockHeight>, #[interactive_clap(long)] #[interactive_clap(skip_interactive_input)] meta_transaction_valid_for: Option<u64>, #[interactive_clap(subcommand)] submit: super::Submit, } #[derive(Clone)] pub struct SignKeychainContext { network_config: crate::config::NetworkConfig, global_context: crate::GlobalContext, signed_transaction_or_signed_delegate_action: super::SignedTransactionOrSignedDelegateAction, on_before_sending_transaction_callback: crate::transaction_signature_options::OnBeforeSendingTransactionCallback, on_after_sending_transaction_callback: crate::transaction_signature_options::OnAfterSendingTransactionCallback, } impl From<super::sign_with_legacy_keychain::SignLegacyKeychainContext> for SignKeychainContext { fn from(value: super::sign_with_legacy_keychain::SignLegacyKeychainContext) -> Self { SignKeychainContext { network_config: value.network_config, global_context: value.global_context, signed_transaction_or_signed_delegate_action: value .signed_transaction_or_signed_delegate_action, on_before_sending_transaction_callback: value.on_before_sending_transaction_callback, on_after_sending_transaction_callback: value.on_after_sending_transaction_callback, } } } impl SignKeychainContext { #[tracing::instrument( name = "Signing the transaction with a key saved in the secure keychain ...", skip_all )] pub fn from_previous_context( previous_context: crate::commands::TransactionContext, scope: &<SignKeychain as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { tracing::info!(target: "near_teach_me", "Signing the transaction with a key saved in the secure keychain ..."); let network_config = previous_context.network_config.clone(); let service_name = std::borrow::Cow::Owned(format!( "near-{}-{}", network_config.network_name, previous_context.prepopulated_transaction.signer_id.as_str() )); let password = if previous_context.global_context.offline { let res = keyring::Entry::new( &service_name, &format!( "{}:{}", previous_context.prepopulated_transaction.signer_id, scope.signer_public_key.clone().wrap_err( "Signer public key is required to sign a transaction in offline mode" )? ), )? .get_password(); match res { Ok(password) => password, Err(err) => { match matches!(err, keyring::Error::NoEntry) { true => eprintln!("Warning: no access key found in keychain"), false => eprintln!("Warning: keychain was not able to be read, {err}"), } eprintln!("trying with the legacy keychain"); return from_legacy_keychain(previous_context, scope); } } } else { let access_key_list = network_config .json_rpc_client() .blocking_call_view_access_key_list( &previous_context.prepopulated_transaction.signer_id, near_primitives::types::Finality::Final.into(), ) .wrap_err_with(|| { format!( "Failed to fetch access key list for {}", previous_context.prepopulated_transaction.signer_id ) })? .access_key_list_view()?; let res = access_key_list .keys .into_iter() .filter(|key| { matches!( key.access_key.permission, near_primitives::views::AccessKeyPermissionView::FullAccess ) }) .map(|key| key.public_key) .find_map(|public_key| { let keyring = keyring::Entry::new( &service_name, &format!( "{}:{}", previous_context.prepopulated_transaction.signer_id, public_key ), ) .ok()?; keyring.get_password().ok() }); match res { Some(password) => password, None => { // no access keys found, try the legacy keychain warning_message("no access keys found in keychain, trying legacy keychain"); return from_legacy_keychain(previous_context, scope); } } }; let account_json: super::AccountKeyPair = serde_json::from_str(&password).wrap_err("Error reading data")?; let (nonce, block_hash, block_height) = if previous_context.global_context.offline { ( scope .nonce .wrap_err("Nonce is required to sign a transaction in offline mode")?, scope .block_hash .wrap_err("Block Hash is required to sign a transaction in offline mode")? .0, scope .block_height .wrap_err("Block Height is required to sign a transaction in offline mode")?, ) } else { let rpc_query_response = network_config .json_rpc_client() .blocking_call_view_access_key( &previous_context.prepopulated_transaction.signer_id, &account_json.public_key, near_primitives::types::BlockReference::latest(), ) .wrap_err_with(|| format!("Cannot sign a transaction due to an error while fetching the most recent nonce value on network <{}>", network_config.network_name) )?; ( rpc_query_response .access_key_view() .wrap_err("Error current_nonce")? .nonce + 1, rpc_query_response.block_hash, rpc_query_response.block_height, ) }; let mut unsigned_transaction = TransactionV0 { public_key: account_json.public_key.clone(), block_hash, nonce, signer_id: previous_context.prepopulated_transaction.signer_id, receiver_id: previous_context.prepopulated_transaction.receiver_id, actions: previous_context.prepopulated_transaction.actions, }; (previous_context.on_before_signing_callback)(&mut unsigned_transaction, &network_config)?; let unsigned_transaction = Transaction::V0(unsigned_transaction); let signature = account_json .private_key .sign(unsigned_transaction.get_hash_and_size().0.as_ref()); if network_config.meta_transaction_relayer_url.is_some() { let max_block_height = block_height + scope .meta_transaction_valid_for .unwrap_or(super::META_TRANSACTION_VALID_FOR_DEFAULT); let signed_delegate_action = super::get_signed_delegate_action( unsigned_transaction, &account_json.public_key, account_json.private_key, max_block_height, ); return Ok(Self { network_config: previous_context.network_config, global_context: previous_context.global_context, signed_transaction_or_signed_delegate_action: signed_delegate_action.into(), on_before_sending_transaction_callback: previous_context .on_before_sending_transaction_callback, on_after_sending_transaction_callback: previous_context .on_after_sending_transaction_callback, }); } let mut signed_transaction = near_primitives::transaction::SignedTransaction::new( signature.clone(), unsigned_transaction, ); tracing::info!( parent: &tracing::Span::none(), "Your transaction was signed successfully.{}", crate::common::indent_payload(&format!( "\nPublic key: {}\nSignature: {}\n ", account_json.public_key, signature )) ); (previous_context.on_after_signing_callback)( &mut signed_transaction, &previous_context.network_config, )?; Ok(Self { network_config: previous_context.network_config, global_context: previous_context.global_context, signed_transaction_or_signed_delegate_action: signed_transaction.into(), on_before_sending_transaction_callback: previous_context .on_before_sending_transaction_callback, on_after_sending_transaction_callback: previous_context .on_after_sending_transaction_callback, }) } } #[tracing::instrument(name = "Warning:", skip_all)] fn warning_message(instrument_message: &str) { tracing::Span::current().pb_set_message(instrument_message); tracing::warn!(target: "near_teach_me", "{instrument_message}"); std::thread::sleep(std::time::Duration::from_secs(1)); } #[tracing::instrument(name = "Trying to sign with the legacy keychain ...", skip_all)] fn from_legacy_keychain( previous_context: crate::commands::TransactionContext, scope: &<SignKeychain as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<SignKeychainContext> { tracing::info!(target: "near_teach_me", "Trying to sign with the legacy keychain ..."); let legacy_scope = super::sign_with_legacy_keychain::InteractiveClapContextScopeForSignLegacyKeychain { signer_public_key: scope.signer_public_key.clone(), nonce: scope.nonce, block_hash: scope.block_hash, block_height: scope.block_height, meta_transaction_valid_for: scope.meta_transaction_valid_for, }; Ok( super::sign_with_legacy_keychain::SignLegacyKeychainContext::from_previous_context( previous_context, &legacy_scope, )? .into(), ) } impl From<SignKeychainContext> for super::SubmitContext { fn from(item: SignKeychainContext) -> Self { Self { network_config: item.network_config, global_context: item.global_context, signed_transaction_or_signed_delegate_action: item .signed_transaction_or_signed_delegate_action, on_before_sending_transaction_callback: item.on_before_sending_transaction_callback, on_after_sending_transaction_callback: item.on_after_sending_transaction_callback, } } } impl SignKeychain { fn input_signer_public_key( context: &crate::commands::TransactionContext, ) -> color_eyre::eyre::Result<Option<crate::types::public_key::PublicKey>> { if context.global_context.offline { return Ok(Some( CustomType::<crate::types::public_key::PublicKey>::new("Enter public_key:") .prompt()?, )); } Ok(None) } fn input_nonce( context: &crate::commands::TransactionContext, ) -> color_eyre::eyre::Result<Option<u64>> { if context.global_context.offline { return Ok(Some( CustomType::<u64>::new("Enter a nonce for the access key:").prompt()?, )); } Ok(None) } fn input_block_hash( context: &crate::commands::TransactionContext, ) -> color_eyre::eyre::Result<Option<crate::types::crypto_hash::CryptoHash>> { if context.global_context.offline { return Ok(Some( CustomType::<crate::types::crypto_hash::CryptoHash>::new( "Enter recent block hash:", ) .prompt()?, )); } Ok(None) } fn input_block_height( context: &crate::commands::TransactionContext, ) -> color_eyre::eyre::Result<Option<near_primitives::types::BlockHeight>> { if context.global_context.offline { return Ok(Some( CustomType::<near_primitives::types::BlockHeight>::new( "Enter recent block height:", ) .prompt()?, )); } Ok(None) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/transaction_signature_options/sign_later/display.rs
src/transaction_signature_options/sign_later/display.rs
#[derive(Debug, Clone, interactive_clap_derive::InteractiveClap)] #[interactive_clap(input_context = super::SignLaterContext)] #[interactive_clap(output_context = DisplayContext)] pub struct Display; #[derive(Debug, Clone)] pub struct DisplayContext; impl DisplayContext { pub fn from_previous_context( previous_context: super::SignLaterContext, _scope: &<Display as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { println!( "\nTransaction hash to sign:\n{}.\n\nUnsigned transaction (serialized as base64):\n{}\n\nThis base64-encoded transaction can be signed and sent later. There is a helper command on near CLI that can do that:\n$ {} transaction sign-transaction", hex::encode(previous_context.unsigned_transaction.get_hash_and_size().0), crate::types::transaction::TransactionAsBase64::from(previous_context.unsigned_transaction), crate::common::get_near_exec_path() ); Ok(Self) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/transaction_signature_options/sign_later/mod.rs
src/transaction_signature_options/sign_later/mod.rs
use near_primitives::transaction::TransactionV0; use strum::{EnumDiscriminants, EnumIter, EnumMessage}; mod display; mod save_to_file; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::commands::TransactionContext)] #[interactive_clap(output_context = SignLaterContext)] pub struct SignLater { #[interactive_clap(long)] /// Enter sender (signer) public key: signer_public_key: crate::types::public_key::PublicKey, #[interactive_clap(long)] /// Enter a nonce for the access key: nonce: u64, #[interactive_clap(long)] /// Enter recent block hash: block_hash: crate::types::crypto_hash::CryptoHash, #[interactive_clap(subcommand)] output: Output, } #[derive(Debug, Clone)] pub struct SignLaterContext { global_context: crate::GlobalContext, unsigned_transaction: near_primitives::transaction::Transaction, } impl SignLaterContext { pub fn from_previous_context( previous_context: crate::commands::TransactionContext, scope: &<SignLater as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let unsigned_transaction = near_primitives::transaction::Transaction::V0(TransactionV0 { signer_id: previous_context.prepopulated_transaction.signer_id, public_key: scope.signer_public_key.clone().into(), nonce: scope.nonce, receiver_id: previous_context.prepopulated_transaction.receiver_id, block_hash: scope.block_hash.into(), actions: previous_context.prepopulated_transaction.actions, }); Ok(Self { global_context: previous_context.global_context, unsigned_transaction, }) } } #[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = SignLaterContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// How would you like to proceed? pub enum Output { #[strum_discriminants(strum( message = "save-to-file - Save the unsigned transaction to file" ))] /// Save the unsigned transaction to file SaveToFile(self::save_to_file::SaveToFile), #[strum_discriminants(strum( message = "display - Print the unsigned transaction to terminal" ))] /// Print the unsigned transaction to terminal Display(self::display::Display), }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/transaction_signature_options/sign_later/save_to_file.rs
src/transaction_signature_options/sign_later/save_to_file.rs
use std::io::Write; use color_eyre::eyre::Context; use inquire::CustomType; #[derive(Debug, Clone, interactive_clap_derive::InteractiveClap)] #[interactive_clap(input_context = super::SignLaterContext)] #[interactive_clap(output_context = SaveToFileContext)] pub struct SaveToFile { #[interactive_clap(skip_default_input_arg)] /// What is the location of the file to save the unsigned transaction (path/to/signed-transaction-info.json)? file_path: crate::types::path_buf::PathBuf, } #[derive(Debug, Clone)] pub struct SaveToFileContext; impl SaveToFileContext { pub fn from_previous_context( previous_context: super::SignLaterContext, scope: &<SaveToFile as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let file_path: std::path::PathBuf = scope.file_path.clone().into(); let data_unsigned_transaction = serde_json::json!({ "Transaction hash to sign": hex::encode(previous_context.unsigned_transaction.get_hash_and_size().0).to_string(), "Unsigned transaction (serialized as base64)": crate::types::transaction::TransactionAsBase64::from(previous_context.unsigned_transaction).to_string(), }); std::fs::File::create(&file_path) .wrap_err_with(|| format!("Failed to create file: {:?}", &file_path))? .write(&serde_json::to_vec_pretty(&data_unsigned_transaction)?) .wrap_err_with(|| format!("Failed to write to file: {:?}", &file_path))?; if let crate::Verbosity::Quiet = previous_context.global_context.verbosity { return Ok(Self); } eprintln!("\nThe file {:?} was created successfully. It has a unsigned transaction (serialized as base64).\nThis base64-encoded transaction can be signed and sent later. There is a helper command on near CLI that can do that:\n$ {} transaction sign-transaction", &file_path, crate::common::get_near_exec_path() ); Ok(Self) } } impl SaveToFile { fn input_file_path( _context: &super::SignLaterContext, ) -> color_eyre::eyre::Result<Option<crate::types::path_buf::PathBuf>> { Ok(Some( CustomType::new("Enter the file path where to save the unsigned transaction:") .with_starting_input("unsigned-transaction-info.json") .prompt()?, )) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/transaction_signature_options/sign_with_legacy_keychain/mod.rs
src/transaction_signature_options/sign_with_legacy_keychain/mod.rs
extern crate dirs; use std::str::FromStr; use color_eyre::eyre::{ContextCompat, WrapErr}; use inquire::{CustomType, Select}; use near_primitives::transaction::Transaction; use near_primitives::transaction::TransactionV0; use crate::common::JsonRpcClientExt; use crate::common::RpcQueryResponseExt; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::commands::TransactionContext)] #[interactive_clap(output_context = SignLegacyKeychainContext)] pub struct SignLegacyKeychain { #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] signer_public_key: Option<crate::types::public_key::PublicKey>, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] nonce: Option<u64>, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] pub block_hash: Option<crate::types::crypto_hash::CryptoHash>, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] pub block_height: Option<near_primitives::types::BlockHeight>, #[interactive_clap(long)] #[interactive_clap(skip_interactive_input)] meta_transaction_valid_for: Option<u64>, #[interactive_clap(subcommand)] submit: super::Submit, } #[derive(Clone)] pub struct SignLegacyKeychainContext { pub(crate) network_config: crate::config::NetworkConfig, pub(crate) global_context: crate::GlobalContext, pub(crate) signed_transaction_or_signed_delegate_action: super::SignedTransactionOrSignedDelegateAction, pub(crate) on_before_sending_transaction_callback: crate::transaction_signature_options::OnBeforeSendingTransactionCallback, pub(crate) on_after_sending_transaction_callback: crate::transaction_signature_options::OnAfterSendingTransactionCallback, } impl SignLegacyKeychainContext { #[tracing::instrument( name = "Signing the transaction with a key saved in legacy keychain ...", skip_all )] pub fn from_previous_context( previous_context: crate::commands::TransactionContext, scope: &<SignLegacyKeychain as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { tracing::info!(target: "near_teach_me", "Signing the transaction with a key saved in legacy keychain ..."); let network_config = previous_context.network_config.clone(); let keychain_folder = previous_context .global_context .config .credentials_home_dir .join(&network_config.network_name); let signer_keychain_folder = keychain_folder.join(previous_context.prepopulated_transaction.signer_id.as_str()); let signer_access_key_file_path: std::path::PathBuf = { if previous_context.global_context.offline { signer_keychain_folder.join(format!( "{}.json", scope .signer_public_key .as_ref() .wrap_err( "Signer public key is required to sign a transaction in offline mode" )? .to_string() .replace(':', "_") )) } else if signer_keychain_folder.exists() { let full_access_key_filenames = network_config .json_rpc_client() .blocking_call_view_access_key_list( &previous_context.prepopulated_transaction.signer_id, near_primitives::types::Finality::Final.into(), ) .wrap_err_with(|| { format!( "Failed to fetch access KeyList for {}", previous_context.prepopulated_transaction.signer_id ) })? .access_key_list_view()? .keys .iter() .filter( |access_key_info| match access_key_info.access_key.permission { near_primitives::views::AccessKeyPermissionView::FullAccess => true, near_primitives::views::AccessKeyPermissionView::FunctionCall { .. } => false, }, ) .map(|access_key_info| { format!( "{}.json", access_key_info.public_key.to_string().replace(":", "_") ) .into() }) .collect::<std::collections::HashSet<std::ffi::OsString>>(); signer_keychain_folder .read_dir() .wrap_err("There are no access keys found in the keychain for the signer account. Import an access key for an account before signing transactions with keychain.")? .filter_map(Result::ok) .find(|entry| full_access_key_filenames.contains(&entry.file_name())) .map(|signer_access_key| signer_access_key.path()) .unwrap_or_else(|| keychain_folder.join(format!( "{}.json", previous_context.prepopulated_transaction.signer_id ))) } else { keychain_folder.join(format!( "{}.json", previous_context.prepopulated_transaction.signer_id )) } }; let signer_access_key_json = std::fs::read(&signer_access_key_file_path).wrap_err_with(|| { format!( "Access key file for account <{}> on network <{}> not found! \nSearch location: {:?}", previous_context.prepopulated_transaction.signer_id, network_config.network_name, signer_access_key_file_path ) })?; let signer_access_key: super::AccountKeyPair = serde_json::from_slice(&signer_access_key_json).wrap_err_with(|| { format!( "Error reading data from file: {:?}", &signer_access_key_file_path ) })?; let (nonce, block_hash, block_height) = if previous_context.global_context.offline { ( scope .nonce .wrap_err("Nonce is required to sign a transaction in offline mode")?, scope .block_hash .wrap_err("Block Hash is required to sign a transaction in offline mode")? .0, scope .block_height .wrap_err("Block Height is required to sign a transaction in offline mode")?, ) } else { let rpc_query_response = network_config .json_rpc_client() .blocking_call_view_access_key( &previous_context.prepopulated_transaction.signer_id, &signer_access_key.public_key, near_primitives::types::BlockReference::latest() ) .wrap_err( "Cannot sign a transaction due to an error while fetching the most recent nonce value", )?; ( rpc_query_response .access_key_view() .wrap_err("Error current_nonce")? .nonce + 1, rpc_query_response.block_hash, rpc_query_response.block_height, ) }; let mut unsigned_transaction = TransactionV0 { public_key: signer_access_key.public_key.clone(), block_hash, nonce, signer_id: previous_context.prepopulated_transaction.signer_id, receiver_id: previous_context.prepopulated_transaction.receiver_id, actions: previous_context.prepopulated_transaction.actions, }; (previous_context.on_before_signing_callback)(&mut unsigned_transaction, &network_config)?; let unsigned_transaction = Transaction::V0(unsigned_transaction); if network_config.meta_transaction_relayer_url.is_some() { let max_block_height = block_height + scope .meta_transaction_valid_for .unwrap_or(super::META_TRANSACTION_VALID_FOR_DEFAULT); let signed_delegate_action = super::get_signed_delegate_action( unsigned_transaction, &signer_access_key.public_key, signer_access_key.private_key, max_block_height, ); return Ok(Self { network_config: previous_context.network_config, global_context: previous_context.global_context, signed_transaction_or_signed_delegate_action: signed_delegate_action.into(), on_before_sending_transaction_callback: previous_context .on_before_sending_transaction_callback, on_after_sending_transaction_callback: previous_context .on_after_sending_transaction_callback, }); } let signature = signer_access_key .private_key .sign(unsigned_transaction.get_hash_and_size().0.as_ref()); let mut signed_transaction = near_primitives::transaction::SignedTransaction::new( signature.clone(), unsigned_transaction, ); tracing::info!( parent: &tracing::Span::none(), "Your transaction was signed successfully.{}", crate::common::indent_payload(&format!( "\nPublic key: {}\nSignature: {}\n ", signer_access_key.public_key, signature )) ); (previous_context.on_after_signing_callback)( &mut signed_transaction, &previous_context.network_config, )?; Ok(Self { network_config: previous_context.network_config, global_context: previous_context.global_context, signed_transaction_or_signed_delegate_action: signed_transaction.into(), on_before_sending_transaction_callback: previous_context .on_before_sending_transaction_callback, on_after_sending_transaction_callback: previous_context .on_after_sending_transaction_callback, }) } } impl From<SignLegacyKeychainContext> for super::SubmitContext { fn from(item: SignLegacyKeychainContext) -> Self { Self { network_config: item.network_config, global_context: item.global_context, signed_transaction_or_signed_delegate_action: item .signed_transaction_or_signed_delegate_action, on_before_sending_transaction_callback: item.on_before_sending_transaction_callback, on_after_sending_transaction_callback: item.on_after_sending_transaction_callback, } } } impl SignLegacyKeychain { fn input_signer_public_key( context: &crate::commands::TransactionContext, ) -> color_eyre::eyre::Result<Option<crate::types::public_key::PublicKey>> { if context.global_context.offline { let network_config = context.network_config.clone(); let mut path = std::path::PathBuf::from(&context.global_context.config.credentials_home_dir); let dir_name = network_config.network_name; path.push(&dir_name); path.push(context.prepopulated_transaction.signer_id.to_string()); let signer_dir = path.read_dir()?; let key_list = signer_dir .filter_map(|entry| entry.ok()) .filter_map(|entry| entry.file_name().into_string().ok()) .filter(|file_name_str| file_name_str.starts_with("ed25519_")) .map(|file_name_str| file_name_str.replace(".json", "").replace('_', ":")) .collect::<Vec<_>>(); let selected_input = Select::new("Choose a public key:", key_list).prompt()?; return Ok(Some(crate::types::public_key::PublicKey::from_str( &selected_input, )?)); } Ok(None) } fn input_nonce( context: &crate::commands::TransactionContext, ) -> color_eyre::eyre::Result<Option<u64>> { if context.global_context.offline { return Ok(Some( CustomType::<u64>::new("Enter a nonce for the access key:").prompt()?, )); } Ok(None) } fn input_block_hash( context: &crate::commands::TransactionContext, ) -> color_eyre::eyre::Result<Option<crate::types::crypto_hash::CryptoHash>> { if context.global_context.offline { return Ok(Some( CustomType::<crate::types::crypto_hash::CryptoHash>::new( "Enter recent block hash:", ) .prompt()?, )); } Ok(None) } fn input_block_height( context: &crate::commands::TransactionContext, ) -> color_eyre::eyre::Result<Option<near_primitives::types::BlockHeight>> { if context.global_context.offline { return Ok(Some( CustomType::<near_primitives::types::BlockHeight>::new( "Enter recent block height:", ) .prompt()?, )); } Ok(None) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/transaction_signature_options/sign_with_mpc/mpc_sign_result.rs
src/transaction_signature_options/sign_with_mpc/mpc_sign_result.rs
use hex::FromHex; use near_crypto::Secp256K1Signature; #[derive(serde::Deserialize, Debug, Clone)] pub struct AffinePoint { pub affine_point: String, } #[derive(serde::Deserialize, Debug, Clone)] pub struct Scalar { pub scalar: String, } #[derive(serde::Deserialize, Debug, Clone)] pub struct SignResultSecp256K1 { pub big_r: AffinePoint, pub s: Scalar, pub recovery_id: u8, } impl From<SignResultSecp256K1> for Secp256K1Signature { fn from(value: SignResultSecp256K1) -> Self { // Get r and s from the sign result let big_r = value.big_r.affine_point; let s = value.s.scalar; // Remove first two bytes let r = &big_r[2..]; // Convert hex to bytes let r_bytes = <[u8; 32]>::from_hex(r).expect("Invalid hex in r"); let s_bytes = <[u8; 32]>::from_hex(s).expect("Invalid hex in s"); // Add individual bytes together in the correct order let mut signature_bytes = [0u8; 65]; signature_bytes[..32].copy_from_slice(&r_bytes); signature_bytes[32..64].copy_from_slice(&s_bytes); signature_bytes[64] = value.recovery_id; Secp256K1Signature::from(signature_bytes) } } #[derive(serde::Deserialize, Debug, Clone)] pub struct SignResultEd25519 { #[allow(unused)] pub scheme: String, pub signature: Vec<u8>, } impl From<SignResultEd25519> for ed25519_dalek::Signature { fn from(value: SignResultEd25519) -> Self { let signature_bytes: [u8; ed25519_dalek::SIGNATURE_LENGTH] = value .signature .try_into() .expect("Invalid signature length for Ed25519"); // Sanity check from near_crypto assert!( signature_bytes[ed25519_dalek::SIGNATURE_LENGTH - 1] & 0b1110_0000 == 0, "Signature error: Sanity check failed" ); ed25519_dalek::Signature::from_bytes(&signature_bytes) } } #[derive(serde::Deserialize, Debug, Clone)] #[serde(untagged)] pub enum SignResult { Secp256K1(SignResultSecp256K1), Ed25519(SignResultEd25519), } impl From<SignResult> for near_crypto::Signature { fn from(value: SignResult) -> Self { match value { SignResult::Secp256K1(secp) => near_crypto::Signature::SECP256K1(secp.into()), SignResult::Ed25519(ed) => near_crypto::Signature::ED25519(ed.into()), } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/transaction_signature_options/sign_with_mpc/mod.rs
src/transaction_signature_options/sign_with_mpc/mod.rs
use color_eyre::{eyre::Context, owo_colors::OwoColorize}; use inquire::CustomType; use near_primitives::transaction::{Transaction, TransactionV0}; use strum::{EnumDiscriminants, EnumIter, EnumMessage}; use crate::common::{JsonRpcClientExt, RpcQueryResponseExt}; pub mod mpc_sign_request; pub mod mpc_sign_result; mod mpc_sign_with; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::commands::TransactionContext)] #[interactive_clap(output_context = SignMpcContext)] pub struct SignMpc { #[interactive_clap(skip_default_input_arg)] /// What is the Admin account address? admin_account_id: crate::types::account_id::AccountId, #[interactive_clap(subcommand)] /// What is key type for deriving key? mpc_key_type: MpcKeyType, } #[derive(Clone)] pub struct SignMpcContext { admin_account_id: near_primitives::types::AccountId, tx_context: crate::commands::TransactionContext, } impl SignMpcContext { pub fn from_previous_context( previous_context: crate::commands::TransactionContext, scope: &<SignMpc as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { if previous_context.global_context.offline { eprintln!("\nInternet connection is required to sign with MPC!"); return Err(color_eyre::eyre::eyre!( "Internet connection is required to sign with MPC!" )); } if let Err(err) = previous_context .network_config .get_mpc_contract_account_id() { eprintln!( "\nCouldn't retrieve MPC contract account id from network config:\n {err}" ); return Err(color_eyre::eyre::eyre!( "Couldn't retrieve MPC contract account id from network config!" )); } Ok(SignMpcContext { admin_account_id: scope.admin_account_id.clone().into(), tx_context: previous_context, }) } } impl SignMpc { pub fn input_admin_account_id( context: &crate::commands::TransactionContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { crate::common::input_signer_account_id_from_used_account_list( &context.global_context.config.credentials_home_dir, "What is the Admin AccountId?", ) } } #[derive(Debug, Clone, EnumDiscriminants, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = SignMpcContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// What is the MPC key type for derivation (if unsure choose Secp256K1)? pub enum MpcKeyType { #[strum_discriminants(strum(message = "secp256k1 - use Secp256K1 key derivation"))] /// Use Secp256K1 key Secp256k1(MpcKeyTypeSecp), #[strum_discriminants(strum(message = "ed25519 - use Ed25519 key for derivation"))] /// Use Ed25519 key Ed25519(MpcKeyTypeEd), } #[derive(Clone)] pub struct MpcKeyTypeContext { admin_account_id: near_primitives::types::AccountId, key_type: near_crypto::KeyType, tx_context: crate::commands::TransactionContext, } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = SignMpcContext)] #[interactive_clap(output_context = MpcKeyTypeSecpContext)] pub struct MpcKeyTypeSecp { #[interactive_clap(named_arg)] /// What is the derivation path? derivation_path: MpcDeriveKey, } #[derive(Clone)] pub struct MpcKeyTypeSecpContext(MpcKeyTypeContext); impl MpcKeyTypeSecpContext { fn from_previous_context( previous_context: SignMpcContext, _scope: &<MpcKeyTypeSecp as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self(MpcKeyTypeContext { admin_account_id: previous_context.admin_account_id, key_type: near_crypto::KeyType::SECP256K1, tx_context: previous_context.tx_context, })) } } impl From<MpcKeyTypeSecpContext> for MpcKeyTypeContext { fn from(item: MpcKeyTypeSecpContext) -> Self { item.0 } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = SignMpcContext)] #[interactive_clap(output_context = MpcKeyTypeEdContext)] pub struct MpcKeyTypeEd { #[interactive_clap(named_arg)] /// What is the derivation path? derivation_path: MpcDeriveKey, } #[derive(Clone)] pub struct MpcKeyTypeEdContext(MpcKeyTypeContext); impl MpcKeyTypeEdContext { fn from_previous_context( previous_context: SignMpcContext, _scope: &<MpcKeyTypeEd as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self(MpcKeyTypeContext { admin_account_id: previous_context.admin_account_id, key_type: near_crypto::KeyType::ED25519, tx_context: previous_context.tx_context, })) } } impl From<MpcKeyTypeEdContext> for MpcKeyTypeContext { fn from(item: MpcKeyTypeEdContext) -> Self { item.0 } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = MpcKeyTypeContext)] #[interactive_clap(output_context = MpcDeriveKeyContext)] pub struct MpcDeriveKey { #[interactive_clap(skip_default_input_arg, always_quote)] /// What is the derivation path? derivation_path: String, #[interactive_clap(named_arg)] /// Prepaid Gas for calling MPC contract prepaid_gas: PrepaidGas, } #[derive(Clone)] pub struct MpcDeriveKeyContext { admin_account_id: near_primitives::types::AccountId, derived_public_key: near_crypto::PublicKey, derivation_path: String, nonce: near_primitives::types::Nonce, block_hash: near_primitives::hash::CryptoHash, tx_context: crate::commands::TransactionContext, } impl MpcDeriveKeyContext { pub fn from_previous_context( previous_context: MpcKeyTypeContext, scope: &<MpcDeriveKey as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let network_config = previous_context.tx_context.network_config.clone(); let controllable_account = previous_context .tx_context .prepopulated_transaction .signer_id .clone(); let derived_public_key = derive_public_key( &network_config.get_mpc_contract_account_id()?, &previous_context.admin_account_id, &scope.derivation_path, &previous_context.key_type, &network_config, )?; let json_rpc_response = network_config .json_rpc_client() .blocking_call_view_access_key( &controllable_account, &derived_public_key.clone(), near_primitives::types::BlockReference::latest(), ) .inspect_err(|err| { if let near_jsonrpc_client::errors::JsonRpcError::ServerError( near_jsonrpc_client::errors::JsonRpcServerError::HandlerError( near_jsonrpc_primitives::types::query::RpcQueryError::UnknownAccessKey { .. }, ), ) = &**err { tracing::error!( "Couldn't find a key on rpc. You can add it to controllable account using following command:" ); eprintln!("{}", format!( " {} account add-key {} grant-full-access use-manually-provided-public-key {}", crate::common::get_near_exec_path(), controllable_account, derived_public_key ).yellow() ); } }) .wrap_err_with(|| format!("Cannot sign MPC transaction for <{}> due to an error while checking if derived key exists on network <{}>", controllable_account, network_config.network_name) )?; tracing::info!( "Derived public key for <{}>:{}", controllable_account, crate::common::indent_payload(&format!("\n{derived_public_key}\n")) ); Ok(Self { admin_account_id: previous_context.admin_account_id, derived_public_key, derivation_path: scope.derivation_path.clone(), nonce: json_rpc_response .access_key_view() .wrap_err("Error current_nonce")? .nonce + 1, block_hash: json_rpc_response.block_hash, tx_context: previous_context.tx_context, }) } } impl MpcDeriveKey { pub fn input_derivation_path( context: &MpcKeyTypeContext, ) -> color_eyre::eyre::Result<Option<String>> { let derivation_path = inquire::Text::new("What is the derivation path?") .with_initial_value(&format!( "{}-{}", context.admin_account_id, context.tx_context.prepopulated_transaction.signer_id )) .prompt()?; Ok(Some(derivation_path)) } } #[tracing::instrument(name = "Retrieving derived public key from MPC contract ...", skip_all)] pub fn derive_public_key( mpc_contract_address: &near_primitives::types::AccountId, admin_account_id: &near_primitives::types::AccountId, derivation_path: &str, key_type: &near_crypto::KeyType, network_config: &crate::config::NetworkConfig, ) -> color_eyre::eyre::Result<near_crypto::PublicKey> { tracing::info!(target: "near_teach_me", "Retrieving derived public key from MPC contract ..."); let rpc_result = network_config .json_rpc_client() .blocking_call_view_function( mpc_contract_address, "derived_public_key", serde_json::to_vec(&serde_json::json!({ "path": derivation_path, "predecessor": admin_account_id, "domain_id": near_key_type_to_mpc_domain_id(*key_type) }))?, near_primitives::types::BlockReference::latest(), )?; let public_key: near_crypto::PublicKey = serde_json::from_slice(&rpc_result.result)?; Ok(public_key) } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = MpcDeriveKeyContext)] #[interactive_clap(output_context = PrepaidGasContext)] pub struct PrepaidGas { #[interactive_clap(skip_default_input_arg)] /// What is the gas limit for signing MPC? gas: crate::common::NearGas, #[interactive_clap(named_arg)] /// Deposit for contract call attached_deposit: Deposit, } #[derive(Clone)] pub struct PrepaidGasContext { admin_account_id: near_primitives::types::AccountId, derived_public_key: near_crypto::PublicKey, derivation_path: String, nonce: near_primitives::types::Nonce, block_hash: near_primitives::hash::CryptoHash, tx_context: crate::commands::TransactionContext, gas: crate::common::NearGas, } impl PrepaidGasContext { pub fn from_previous_context( previous_context: MpcDeriveKeyContext, scope: &<PrepaidGas as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(PrepaidGasContext { admin_account_id: previous_context.admin_account_id, derived_public_key: previous_context.derived_public_key, derivation_path: previous_context.derivation_path, nonce: previous_context.nonce, block_hash: previous_context.block_hash, tx_context: previous_context.tx_context, gas: scope.gas, }) } } impl PrepaidGas { pub fn input_gas( _context: &MpcDeriveKeyContext, ) -> color_eyre::eyre::Result<Option<crate::common::NearGas>> { Ok(Some( CustomType::new( "What is the gas limit for signing with MPC (if you're not sure, keep 15 Tgas)?", ) .with_starting_input("15 Tgas") .with_validator(move |gas: &crate::common::NearGas| { if gas < &near_gas::NearGas::from_tgas(15) { Ok(inquire::validator::Validation::Invalid( inquire::validator::ErrorMessage::Custom( "Sign call to MPC contract requires minimum of 15 TeraGas".to_string(), ), )) } else if gas > &near_gas::NearGas::from_tgas(300) { Ok(inquire::validator::Validation::Invalid( inquire::validator::ErrorMessage::Custom( "You need to enter a value of no more than 300 TeraGas".to_string(), ), )) } else { Ok(inquire::validator::Validation::Valid) } }) .prompt()?, )) } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = PrepaidGasContext)] #[interactive_clap(output_context = DepositContext)] pub struct Deposit { #[interactive_clap(skip_default_input_arg)] /// Enter deposit for MPC contract call: deposit: crate::types::near_token::NearToken, #[interactive_clap(subcommand)] transaction_signature_options: mpc_sign_with::MpcSignWith, } #[derive(Clone)] pub struct DepositContext { admin_account_id: near_primitives::types::AccountId, mpc_contract_address: near_primitives::types::AccountId, gas: crate::common::NearGas, deposit: crate::types::near_token::NearToken, original_payload_transaction: Transaction, mpc_sign_request: mpc_sign_request::MpcSignRequest, mpc_sign_request_serialized: Vec<u8>, global_context: crate::GlobalContext, network_config: crate::config::NetworkConfig, } impl DepositContext { pub fn from_previous_context( previous_context: PrepaidGasContext, scope: &<Deposit as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let controllable_account = previous_context .tx_context .prepopulated_transaction .signer_id; let mut payload = TransactionV0 { signer_id: controllable_account.clone(), receiver_id: previous_context .tx_context .prepopulated_transaction .receiver_id, public_key: previous_context.derived_public_key.clone(), nonce: previous_context.nonce, block_hash: previous_context.block_hash, actions: previous_context.tx_context.prepopulated_transaction.actions, }; (previous_context.tx_context.on_before_signing_callback)( &mut payload, &previous_context.tx_context.network_config, )?; let mpc_tx_payload = Transaction::V0(payload); let hashed_payload = near_primitives::hash::CryptoHash::hash_borsh(&mpc_tx_payload).0; let payload: mpc_sign_request::MpcSignPayload = match previous_context.derived_public_key.key_type() { near_crypto::KeyType::ED25519 => { mpc_sign_request::MpcSignPayload::Eddsa(hashed_payload.to_vec()) } near_crypto::KeyType::SECP256K1 => { mpc_sign_request::MpcSignPayload::Ecdsa(hashed_payload) } }; let mpc_sign_request = mpc_sign_request::MpcSignRequest { request: mpc_sign_request::MpcSignRequestArgs { payload, path: previous_context.derivation_path, domain_id: near_key_type_to_mpc_domain_id( previous_context.derived_public_key.key_type(), ), }, }; let mpc_sign_request_serialized = serde_json::to_vec(&mpc_sign_request)?; Ok(Self { admin_account_id: previous_context.admin_account_id, mpc_contract_address: previous_context .tx_context .network_config .get_mpc_contract_account_id()?, gas: previous_context.gas, deposit: scope.deposit, original_payload_transaction: mpc_tx_payload, mpc_sign_request, mpc_sign_request_serialized, global_context: previous_context.tx_context.global_context, network_config: previous_context.tx_context.network_config, }) } } impl Deposit { pub fn input_deposit( _context: &PrepaidGasContext, ) -> color_eyre::eyre::Result<Option<crate::types::near_token::NearToken>> { Ok(Some( CustomType::new( "What is the deposit for MPC contract call (if unsure, keep 1 yoctoNEAR)?", ) .with_starting_input("1 yoctoNEAR") .with_validator(move |deposit: &crate::types::near_token::NearToken| { if deposit < &crate::types::near_token::NearToken::from_yoctonear(1) { Ok(inquire::validator::Validation::Invalid( inquire::validator::ErrorMessage::Custom( "Sign call to MPC contract requires deposit no lower than 1 yoctoNEAR" .to_string(), ), )) } else { Ok(inquire::validator::Validation::Valid) } }) .prompt()?, )) } } impl From<DepositContext> for crate::commands::TransactionContext { fn from(item: DepositContext) -> Self { let mpc_sign_transaction = crate::commands::PrepopulatedTransaction { signer_id: item.admin_account_id.clone(), receiver_id: item.mpc_contract_address.clone(), actions: vec![near_primitives::transaction::Action::FunctionCall( Box::new(near_primitives::transaction::FunctionCallAction { method_name: "sign".to_string(), args: item.mpc_sign_request_serialized, gas: near_primitives::gas::Gas::from_gas(item.gas.as_gas()), deposit: item.deposit.into(), }), )], }; tracing::info!( "{}{}", "Unsigned transaction for signing with MPC contract", crate::common::indent_payload(&crate::common::print_unsigned_transaction( &mpc_sign_transaction, )) ); let original_transaction_for_signing = item.original_payload_transaction.clone(); let original_transaction_for_after_send = item.original_payload_transaction.clone(); let global_context_for_after_send = item.global_context.clone(); let on_after_signing_callback: crate::commands::OnAfterSigningCallback = std::sync::Arc::new({ move |signed_transaction_to_replace, network_config| { if let Some(near_primitives::action::Action::FunctionCall(fc)) = signed_transaction_to_replace.transaction.actions().first() { // NOTE: Early exit if it is a DAO, it will be required to enter different // flow for it if fc.method_name == "add_proposal" { return Ok(()); } } let unsigned_transaction = original_transaction_for_signing.clone(); let sender_id = unsigned_transaction.signer_id().clone(); let receiver_id = unsigned_transaction.receiver_id().clone(); let contract_id = item.mpc_contract_address.clone(); let sign_request_tx = signed_transaction_to_replace.clone(); let sign_outcome_view = match crate::transaction_signature_options::send::sending_signed_transaction( network_config, &sign_request_tx, ) { Ok(outcome_view) => outcome_view, Err(error) => return Err(error), }; let signed_transaction = match sign_outcome_view.status { near_primitives::views::FinalExecutionStatus::SuccessValue(result) => { let sign_result: mpc_sign_result::SignResult = serde_json::from_slice(&result)?; let signature: near_crypto::Signature = sign_result.into(); near_primitives::transaction::SignedTransaction::new( signature, unsigned_transaction, ) } _ => { let error_msg = format!("Failed to sign MPC transaction for <{sender_id}>\nUnexpected outcome view after sending to \"sign\" to <{contract_id}> contract."); eprintln!("{error_msg}"); return Err(color_eyre::eyre::eyre!(error_msg)); } }; tracing::info!( parent: &tracing::Span::none(), "Successfully signed original transaction from <{}> to <{}> via MPC contract <{}>:{}", sender_id, receiver_id, contract_id, crate::common::indent_payload(&format!( "\nSignature: {}\n", signed_transaction.signature, )) ); *signed_transaction_to_replace = signed_transaction; Ok(()) } }); let on_after_sending_transaction_callback: crate::transaction_signature_options::OnAfterSendingTransactionCallback = std::sync::Arc::new({ move |outcome_view, network_config| { let global_context = global_context_for_after_send.clone(); let unsigned_transaction = original_transaction_for_after_send.clone(); let mpc_sign_request = item.mpc_sign_request.clone(); // NOTE: checking if outcome view status is not failure is not necessary, as this // callback will be called only after `crate::common::print_transaction_status`, // which will check for failure of transaction already if let Some(near_primitives::views::ActionView::FunctionCall { method_name, args, .. }) = outcome_view.transaction.actions.first() { if method_name == "add_proposal" { if let Ok(Some(proposal)) = serde_json::from_slice::<serde_json::Value>(args).map(|parsed_args| parsed_args.get("proposal").cloned()) { if let Some(kind) = proposal.get("kind") { if serde_json::from_value::<super::submit_dao_proposal::dao_kind_arguments::ProposalKind>(kind.clone()).is_ok() { dao_sign_with_mpc_after_send_flow( &global_context, network_config, outcome_view, &unsigned_transaction, &mpc_sign_request )?; } } } } } Ok(()) } }); Self { global_context: item.global_context, network_config: item.network_config, prepopulated_transaction: mpc_sign_transaction, on_before_signing_callback: std::sync::Arc::new( |_prepopulated_unsigned_transaction, _network_config| Ok(()), ), on_after_signing_callback, on_before_sending_transaction_callback: std::sync::Arc::new( |_signed_transaction, _network_config| Ok(String::new()), ), on_after_sending_transaction_callback, } } } pub fn near_key_type_to_mpc_domain_id(key_type: near_crypto::KeyType) -> u64 { match key_type { near_crypto::KeyType::SECP256K1 => 0u64, near_crypto::KeyType::ED25519 => 1u64, } } pub fn dao_sign_with_mpc_after_send_flow( global_context: &crate::GlobalContext, network_config: &crate::config::NetworkConfig, outcome_view: &near_primitives::views::FinalExecutionOutcomeView, unsigned_mpc_transaction: &near_primitives::transaction::Transaction, original_sign_request: &mpc_sign_request::MpcSignRequest, ) -> color_eyre::eyre::Result<()> { use tracing_indicatif::suspend_tracing_indicatif; let signed_transaction = loop { let transaction_hash = match suspend_tracing_indicatif(|| { inquire::CustomType::new("Enter the transaction hash of the executed DAO proposal:") .prompt() }) { Ok(tx_hash) => tx_hash, Err( inquire::error::InquireError::OperationCanceled | inquire::error::InquireError::OperationInterrupted, ) => { return Ok(()); } Err(err) => { eprintln!("{}", format!("{err}").red()); continue; } }; let signed_transaction = match fetch_mpc_contract_response_from_dao_tx( network_config, original_sign_request, transaction_hash, "near".parse()?, outcome_view.transaction.receiver_id.clone(), ) { Ok(sign_result) => { let signature: near_crypto::Signature = sign_result.into(); near_primitives::transaction::SignedTransaction::new( signature, unsigned_mpc_transaction.clone(), ) } Err(err) => { eprintln!( "{}", format!("Failed to get signature from MPC contract:\n {err}").red() ); continue; } }; break signed_transaction; }; let submit_context = super::SubmitContext { network_config: network_config.clone(), global_context: global_context.clone(), signed_transaction_or_signed_delegate_action: crate::transaction_signature_options::SignedTransactionOrSignedDelegateAction::SignedTransaction( signed_transaction ), on_before_sending_transaction_callback: std::sync::Arc::new( |_signed_transaction, _network_config| Ok(String::new()), ), on_after_sending_transaction_callback: std::sync::Arc::new( |_outcome_view, _network_config| Ok(()), ), }; prompt_and_submit(submit_context) } #[tracing::instrument(name = "Fetching executed DAO proposal ...", skip_all)] fn fetch_mpc_contract_response_from_dao_tx( network_config: &crate::config::NetworkConfig, original_sign_request: &mpc_sign_request::MpcSignRequest, tx_hash: near_primitives::hash::CryptoHash, sender_account_id: near_primitives::types::AccountId, dao_address: near_primitives::types::AccountId, ) -> color_eyre::eyre::Result<mpc_sign_result::SignResult> { tracing::info!(target: "near_teach_me", "Fetching executed DAO proposal ..."); let request = near_jsonrpc_client::methods::tx::RpcTransactionStatusRequest { transaction_info: near_jsonrpc_client::methods::tx::TransactionInfo::TransactionId { tx_hash, sender_account_id, }, wait_until: near_primitives::views::TxExecutionStatus::Final, }; let exec_outcome_view = network_config .json_rpc_client() .blocking_call(request) .wrap_err("Couldn't fetch DAO transaction")? .final_execution_outcome .ok_or(color_eyre::eyre::eyre!("No final execution outcome"))? .into_outcome(); if exec_outcome_view.transaction.receiver_id != *dao_address { return Err(color_eyre::eyre::eyre!( "Transaction receiver is not dao account!" )); } if !matches!( exec_outcome_view.status, near_primitives::views::FinalExecutionStatus::SuccessValue(_) ) { return Err(color_eyre::eyre::eyre!("Transaction did not succeed")); } let act_proposal_args = exec_outcome_view .transaction .actions .iter() .find_map(|action| { if let near_primitives::views::ActionView::FunctionCall { method_name, args, .. } = action { if method_name == "act_proposal" { return Some(args); } } None }) .ok_or(color_eyre::eyre::eyre!("No act_proposal action found"))?; let act_proposal_args: serde_json::Value = serde_json::from_slice(act_proposal_args)?; let proposal = act_proposal_args .get("proposal") .ok_or(color_eyre::eyre::eyre!( "Couldn't find proposal in \"act_proposal\"" ))?; let proposal_kind: super::submit_dao_proposal::dao_kind_arguments::ProposalKind = serde_json::from_value(proposal.clone())?; let mpc_sign_request = proposal_kind.try_to_mpc_sign_request(network_config)?; if mpc_sign_request != *original_sign_request { return Err(color_eyre::eyre::eyre!("Fetched sign request from DAO proposal doesn't match original that was made in this session")); }; let mut sign_response_opt = None; let mpc_contract_address = network_config .get_mpc_contract_account_id() .expect("Already checked it before calling"); for receipt in exec_outcome_view.receipts_outcome { if receipt.outcome.executor_id == mpc_contract_address { if let near_primitives::views::ExecutionStatusView::SuccessValue(success_response) = receipt.outcome.status { sign_response_opt = Some(success_response); break; } } } let Some(sign_response_vec) = sign_response_opt else { return Err(color_eyre::eyre::eyre!( "Couldn't find response from MPC contract" )); }; let mpc_contract_sign_result: mpc_sign_result::SignResult = serde_json::from_slice(&sign_response_vec).map_err(|_| { color_eyre::eyre::eyre!("Couldn't parse sign response from MPC contract") })?; Ok(mpc_contract_sign_result) } fn prompt_and_submit(submit_context: super::SubmitContext) -> color_eyre::eyre::Result<()> { use strum::IntoEnumIterator; let choices: Vec<_> = super::SubmitDiscriminants::iter() .map(|variant| { let message = variant.get_message().unwrap_or("Unknown"); (message.to_string(), variant) }) .collect(); let display_options: Vec<&str> = choices.iter().map(|(msg, _)| msg.as_str()).collect(); let selected_msg = tracing_indicatif::suspend_tracing_indicatif(|| { inquire::Select::new("How would you like to proceed?", display_options).prompt() })?; let selected = choices .iter() .find(|(msg, _)| msg.as_str() == selected_msg) .map(|(_, variant)| variant) .unwrap(); match selected { super::SubmitDiscriminants::Send => { super::send::SendContext::from_previous_context( submit_context, &super::send::InteractiveClapContextScopeForSend {}, )?; } super::SubmitDiscriminants::Display => { super::display::DisplayContext::from_previous_context( submit_context, &super::display::InteractiveClapContextScopeForDisplay {}, )?; }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
true
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/transaction_signature_options/sign_with_mpc/mpc_sign_with.rs
src/transaction_signature_options/sign_with_mpc/mpc_sign_with.rs
use strum::{EnumDiscriminants, EnumIter, EnumMessage}; #[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = crate::commands::TransactionContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Select a tool for signing transaction to send to MPC: pub enum MpcSignWith { #[strum_discriminants(strum( message = "sign-mpc-tx-with-keychain - Sign MPC contract call a key saved in the secure keychain" ))] /// Sign MPC contract call with a key saved in keychain SignMpcWithKeychain(crate::transaction_signature_options::sign_with_keychain::SignKeychain), #[strum_discriminants(strum( message = "sign-mpc-with-legacy-keychain - Sign MPC contract call with a key saved in keychain (compatible with the old near CLI)" ))] /// Sign MPC contract call with a key saved in legacy keychain (compatible with the old near CLI) SignMpcWithLegacyKeychain( crate::transaction_signature_options::sign_with_legacy_keychain::SignLegacyKeychain, ), #[cfg(feature = "ledger")] #[strum_discriminants(strum( message = "sign-mpc-tx-with-ledger - Sign MPC contract call with Ledger Nano device" ))] /// Sign MPC contract call with Ledger Nano device SignMpcWithLedger(crate::transaction_signature_options::sign_with_ledger::SignLedger), #[strum_discriminants(strum( message = "sign-mpc-tx-with-plaintext-private-key - Sign MPC contract call with a plaintext private key" ))] /// Sign MPC contract call with a plaintext private key SignMpcWithPlaintextPrivateKey( crate::transaction_signature_options::sign_with_private_key::SignPrivateKey, ), #[strum_discriminants(strum( message = "sign-mpc-tx-with-access-key-file - Sign MPC contract call using the account access key file (access-key-file.json)" ))] /// Sign MPC contract call using the account access key file (access-key-file.json) SignMpcWithAccessKeyFile( crate::transaction_signature_options::sign_with_access_key_file::SignAccessKeyFile, ), #[strum_discriminants(strum( message = "sign-mpc-tx-with-seed-phrase - Sign MPC contract call using the seed phrase" ))] /// Sign MPC contract call using the seed phrase SignMpcWithSeedPhrase( crate::transaction_signature_options::sign_with_seed_phrase::SignSeedPhrase, ), #[strum_discriminants(strum( message = "submit-mpc-as-dao-proposal - Convert current MPC transaction to DAO proposal" ))] /// Prepare MPC transaction as dao proposal SubmitMpcAsDaoProposal(crate::transaction_signature_options::submit_dao_proposal::DaoProposal), }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/transaction_signature_options/sign_with_mpc/mpc_sign_request.rs
src/transaction_signature_options/sign_with_mpc/mpc_sign_request.rs
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)] /// Payload for Sign request to MPC pub enum MpcSignPayload { #[serde(with = "hex::serde")] Ecdsa([u8; 32]), #[serde(with = "hex::serde")] Eddsa(Vec<u8>), } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)] pub struct MpcSignRequestArgs { #[serde(rename = "payload_v2")] pub payload: MpcSignPayload, pub path: String, pub domain_id: u64, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)] pub struct MpcSignRequest { pub request: MpcSignRequestArgs, }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/transaction_signature_options/save_to_file/mod.rs
src/transaction_signature_options/save_to_file/mod.rs
use std::io::Write; use color_eyre::eyre::Context; use inquire::CustomType; use super::super::commands::transaction::send_meta_transaction::FileSignedMetaTransaction; use super::super::commands::transaction::send_signed_transaction::FileSignedTransaction; #[derive(Debug, Clone, interactive_clap_derive::InteractiveClap)] #[interactive_clap(input_context = super::SubmitContext)] #[interactive_clap(output_context = SaveToFileContext)] pub struct SaveToFile { #[interactive_clap(skip_default_input_arg)] /// What is the location of the file to save the transaction information (path/to/signed-transaction-info.json)? file_path: crate::types::path_buf::PathBuf, } #[derive(Debug, Clone)] pub struct SaveToFileContext; impl SaveToFileContext { pub fn from_previous_context( previous_context: super::SubmitContext, scope: &<SaveToFile as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let file_path: std::path::PathBuf = scope.file_path.clone().into(); let storage_message = (previous_context.on_before_sending_transaction_callback)( &previous_context.signed_transaction_or_signed_delegate_action, &previous_context.network_config, ) .map_err(color_eyre::Report::msg)?; match previous_context.signed_transaction_or_signed_delegate_action { super::SignedTransactionOrSignedDelegateAction::SignedTransaction( signed_transaction, ) => { let data_signed_transaction = serde_json::to_value(FileSignedTransaction { signed_transaction })?; std::fs::File::create(&file_path) .wrap_err_with(|| format!("Failed to create file: {:?}", &file_path))? .write(&serde_json::to_vec(&data_signed_transaction)?) .wrap_err_with(|| format!("Failed to write to file: {:?}", &file_path))?; eprintln!("\nThe file {:?} was created successfully. It has a signed transaction (serialized as base64).", &file_path); eprintln!( "This base64-encoded signed transaction is ready to be sent to the network. You can call RPC server directly, or use a helper command on near CLI:\n$ {} transaction send-signed-transaction\n", crate::common::get_near_exec_path() ); eprintln!("{storage_message}"); } super::SignedTransactionOrSignedDelegateAction::SignedDelegateAction( signed_delegate_action, ) => { let data_signed_delegate_action = serde_json::to_value(&FileSignedMetaTransaction { signed_delegate_action: signed_delegate_action.into(), })?; std::fs::File::create(&file_path) .wrap_err_with(|| format!("Failed to create file: {:?}", &file_path))? .write(&serde_json::to_vec(&data_signed_delegate_action)?) .wrap_err_with(|| format!("Failed to write to file: {:?}", &file_path))?; eprintln!("\nThe file {:?} was created successfully. It has a signed delegate action (serialized as base64).", &file_path); eprintln!( "This base64-encoded signed delegate action is ready to be sent to the meta-transaction relayer. There is a helper command on near CLI that can do that:\n$ {} transaction send-meta-transaction\n", crate::common::get_near_exec_path() ); eprintln!("{storage_message}"); } } Ok(Self) } } impl SaveToFile { fn input_file_path( context: &super::SubmitContext, ) -> color_eyre::eyre::Result<Option<crate::types::path_buf::PathBuf>> { let starting_input = match &context.signed_transaction_or_signed_delegate_action { super::SignedTransactionOrSignedDelegateAction::SignedTransaction(_) => { "signed-transaction-info.json" } super::SignedTransactionOrSignedDelegateAction::SignedDelegateAction(_) => { "signed-meta-transaction-info.json" } }; Ok(Some( CustomType::new( "What is the location of the file to save the transaction information?", ) .with_starting_input(starting_input) .prompt()?, )) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/transaction_signature_options/sign_with_private_key/mod.rs
src/transaction_signature_options/sign_with_private_key/mod.rs
use color_eyre::eyre::{ContextCompat, WrapErr}; use inquire::CustomType; use near_primitives::transaction::Transaction; use near_primitives::transaction::TransactionV0; use crate::common::JsonRpcClientExt; use crate::common::RpcQueryResponseExt; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::commands::TransactionContext)] #[interactive_clap(output_context = SignPrivateKeyContext)] pub struct SignPrivateKey { /// Enter sender (signer) private (secret) key: pub signer_private_key: crate::types::secret_key::SecretKey, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] pub nonce: Option<u64>, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] pub block_hash: Option<crate::types::crypto_hash::CryptoHash>, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] pub block_height: Option<near_primitives::types::BlockHeight>, #[interactive_clap(long)] #[interactive_clap(skip_interactive_input)] meta_transaction_valid_for: Option<u64>, #[interactive_clap(subcommand)] pub submit: super::Submit, } #[derive(Clone)] pub struct SignPrivateKeyContext { network_config: crate::config::NetworkConfig, global_context: crate::GlobalContext, signed_transaction_or_signed_delegate_action: super::SignedTransactionOrSignedDelegateAction, on_before_sending_transaction_callback: crate::transaction_signature_options::OnBeforeSendingTransactionCallback, on_after_sending_transaction_callback: crate::transaction_signature_options::OnAfterSendingTransactionCallback, } impl SignPrivateKeyContext { #[tracing::instrument( name = "Signing the transaction with a plaintext private key ...", skip_all )] pub fn from_previous_context( previous_context: crate::commands::TransactionContext, scope: &<SignPrivateKey as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { tracing::info!(target: "near_teach_me", "Signing the transaction with a plaintext private key ..."); let network_config = previous_context.network_config.clone(); let signer_secret_key: near_crypto::SecretKey = scope.signer_private_key.clone().into(); let public_key = signer_secret_key.public_key(); let (nonce, block_hash, block_height) = if previous_context.global_context.offline { ( scope .nonce .wrap_err("Nonce is required to sign a transaction in offline mode")?, scope .block_hash .wrap_err("Block Hash is required to sign a transaction in offline mode")? .0, scope .block_height .wrap_err("Block Height is required to sign a transaction in offline mode")?, ) } else { let rpc_query_response = network_config .json_rpc_client() .blocking_call_view_access_key( &previous_context.prepopulated_transaction.signer_id, &public_key, near_primitives::types::BlockReference::latest() ) .wrap_err_with(|| format!("Cannot sign a transaction due to an error while fetching the most recent nonce value on network <{}>", network_config.network_name) )?; ( rpc_query_response .access_key_view() .wrap_err("Error current_nonce")? .nonce + 1, rpc_query_response.block_hash, rpc_query_response.block_height, ) }; let mut unsigned_transaction = TransactionV0 { public_key: public_key.clone(), block_hash, nonce, signer_id: previous_context.prepopulated_transaction.signer_id, receiver_id: previous_context.prepopulated_transaction.receiver_id, actions: previous_context.prepopulated_transaction.actions, }; (previous_context.on_before_signing_callback)(&mut unsigned_transaction, &network_config)?; let unsigned_transaction = Transaction::V0(unsigned_transaction); let signature = signer_secret_key.sign(unsigned_transaction.get_hash_and_size().0.as_ref()); if network_config.meta_transaction_relayer_url.is_some() { let max_block_height = block_height + scope .meta_transaction_valid_for .unwrap_or(super::META_TRANSACTION_VALID_FOR_DEFAULT); let signed_delegate_action = super::get_signed_delegate_action( unsigned_transaction, &public_key, signer_secret_key, max_block_height, ); return Ok(Self { network_config: previous_context.network_config, global_context: previous_context.global_context, signed_transaction_or_signed_delegate_action: signed_delegate_action.into(), on_before_sending_transaction_callback: previous_context .on_before_sending_transaction_callback, on_after_sending_transaction_callback: previous_context .on_after_sending_transaction_callback, }); } let mut signed_transaction = near_primitives::transaction::SignedTransaction::new( signature.clone(), unsigned_transaction, ); tracing::info!( parent: &tracing::Span::none(), "Your transaction was signed successfully.{}", crate::common::indent_payload(&format!( "\nPublic key: {public_key}\nSignature: {signature}\n " )) ); (previous_context.on_after_signing_callback)( &mut signed_transaction, &previous_context.network_config, )?; Ok(Self { network_config: previous_context.network_config, global_context: previous_context.global_context, signed_transaction_or_signed_delegate_action: signed_transaction.into(), on_before_sending_transaction_callback: previous_context .on_before_sending_transaction_callback, on_after_sending_transaction_callback: previous_context .on_after_sending_transaction_callback, }) } } impl From<SignPrivateKeyContext> for super::SubmitContext { fn from(item: SignPrivateKeyContext) -> Self { Self { network_config: item.network_config, global_context: item.global_context, signed_transaction_or_signed_delegate_action: item .signed_transaction_or_signed_delegate_action, on_before_sending_transaction_callback: item.on_before_sending_transaction_callback, on_after_sending_transaction_callback: item.on_after_sending_transaction_callback, } } } impl SignPrivateKey { fn input_nonce( context: &crate::commands::TransactionContext, ) -> color_eyre::eyre::Result<Option<u64>> { if context.global_context.offline { return Ok(Some( CustomType::<u64>::new("Enter a nonce for the access key:").prompt()?, )); } Ok(None) } fn input_block_hash( context: &crate::commands::TransactionContext, ) -> color_eyre::eyre::Result<Option<crate::types::crypto_hash::CryptoHash>> { if context.global_context.offline { return Ok(Some( CustomType::<crate::types::crypto_hash::CryptoHash>::new( "Enter recent block hash:", ) .prompt()?, )); } Ok(None) } fn input_block_height( context: &crate::commands::TransactionContext, ) -> color_eyre::eyre::Result<Option<near_primitives::types::BlockHeight>> { if context.global_context.offline { return Ok(Some( CustomType::<near_primitives::types::BlockHeight>::new( "Enter recent block height:", ) .prompt()?, )); } Ok(None) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/transaction_signature_options/sign_with_ledger/mod.rs
src/transaction_signature_options/sign_with_ledger/mod.rs
use color_eyre::eyre::{ContextCompat, WrapErr}; use inquire::CustomType; use near_ledger::NEARLedgerError; use near_primitives::action::delegate::SignedDelegateAction; use near_primitives::borsh; use near_primitives::transaction::Transaction; use near_primitives::transaction::TransactionV0; use crate::common::JsonRpcClientExt; use crate::common::RpcQueryResponseExt; const SW_BUFFER_OVERFLOW: &str = "0x6990"; const ERR_OVERFLOW_MEMO: &str = "Buffer overflow on Ledger device occurred. \ Transaction is too large for signature. \ This is resolved in https://github.com/dj8yfo/app-near-rs . \ The status is tracked in `About` section."; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::commands::TransactionContext)] #[interactive_clap(output_context = SignLedgerContext)] #[interactive_clap(skip_default_from_cli)] pub struct SignLedger { #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] seed_phrase_hd_path: crate::types::slip10::BIP32Path, #[allow(dead_code)] #[interactive_clap(skip)] signer_public_key: crate::types::public_key::PublicKey, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] nonce: Option<u64>, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] pub block_hash: Option<crate::types::crypto_hash::CryptoHash>, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] block_height: Option<near_primitives::types::BlockHeight>, #[interactive_clap(long)] #[interactive_clap(skip_interactive_input)] meta_transaction_valid_for: Option<u64>, #[interactive_clap(subcommand)] submit: super::Submit, } #[derive(Clone)] pub struct SignLedgerContext { network_config: crate::config::NetworkConfig, global_context: crate::GlobalContext, signed_transaction_or_signed_delegate_action: super::SignedTransactionOrSignedDelegateAction, on_before_sending_transaction_callback: crate::transaction_signature_options::OnBeforeSendingTransactionCallback, on_after_sending_transaction_callback: crate::transaction_signature_options::OnAfterSendingTransactionCallback, } impl SignLedgerContext { #[tracing::instrument( name = "Signing the transaction with Ledger Nano device. Follow the instructions on the ledger ...", skip_all )] pub fn from_previous_context( previous_context: crate::commands::TransactionContext, scope: &<SignLedger as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { tracing::info!(target: "near_teach_me", "Signing the transaction with Ledger Nano device. Follow the instructions on the ledger ..."); let network_config = previous_context.network_config.clone(); let seed_phrase_hd_path: slipped10::BIP32Path = scope.seed_phrase_hd_path.clone().into(); let public_key: near_crypto::PublicKey = scope.signer_public_key.clone().into(); let (nonce, block_hash, block_height) = if previous_context.global_context.offline { ( scope .nonce .wrap_err("Nonce is required to sign a transaction in offline mode")?, scope .block_hash .wrap_err("Block Hash is required to sign a transaction in offline mode")? .0, scope .block_height .wrap_err("Block Height is required to sign a transaction in offline mode")?, ) } else { let rpc_query_response = network_config .json_rpc_client() .blocking_call_view_access_key( &previous_context.prepopulated_transaction.signer_id, &public_key, near_primitives::types::BlockReference::latest(), ) .wrap_err_with(|| format!("Cannot sign a transaction due to an error while fetching the most recent nonce value on network <{}>", network_config.network_name) )?; ( rpc_query_response .access_key_view() .wrap_err("Error current_nonce")? .nonce + 1, rpc_query_response.block_hash, rpc_query_response.block_height, ) }; let mut unsigned_transaction = TransactionV0 { public_key: scope.signer_public_key.clone().into(), block_hash, nonce, signer_id: previous_context.prepopulated_transaction.signer_id, receiver_id: previous_context.prepopulated_transaction.receiver_id, actions: previous_context.prepopulated_transaction.actions, }; (previous_context.on_before_signing_callback)(&mut unsigned_transaction, &network_config)?; let unsigned_transaction = Transaction::V0(unsigned_transaction); if network_config.meta_transaction_relayer_url.is_some() { let max_block_height = block_height + scope .meta_transaction_valid_for .unwrap_or(super::META_TRANSACTION_VALID_FOR_DEFAULT); let mut delegate_action = near_primitives::action::delegate::DelegateAction { sender_id: unsigned_transaction.signer_id().clone(), receiver_id: unsigned_transaction.receiver_id().clone(), actions: vec![], nonce: unsigned_transaction.nonce(), max_block_height, public_key: unsigned_transaction.public_key().clone(), }; delegate_action.actions = unsigned_transaction .take_actions() .into_iter() .map(near_primitives::action::delegate::NonDelegateAction::try_from) .collect::<Result<_, _>>() .expect("Internal error: can not convert the action to non delegate action (delegate action can not be delegated again)."); let signature = match near_ledger::sign_message_nep366_delegate_action( &borsh::to_vec(&delegate_action) .wrap_err("Delegate action is not expected to fail on serialization")?, seed_phrase_hd_path.clone(), ) { Ok(signature) => { near_crypto::Signature::from_parts(near_crypto::KeyType::ED25519, &signature) .wrap_err("Signature is not expected to fail on deserialization")? } Err(NEARLedgerError::APDUExchangeError(msg)) if msg.contains(SW_BUFFER_OVERFLOW) => { return Err(color_eyre::Report::msg(ERR_OVERFLOW_MEMO)); } Err(near_ledger_error) => { return Err(color_eyre::Report::msg(format!( "Error occurred while signing the transaction: {near_ledger_error:?}" ))); } }; let signed_delegate_action = SignedDelegateAction { delegate_action, signature, }; return Ok(Self { network_config: previous_context.network_config, global_context: previous_context.global_context, signed_transaction_or_signed_delegate_action: signed_delegate_action.into(), on_before_sending_transaction_callback: previous_context .on_before_sending_transaction_callback, on_after_sending_transaction_callback: previous_context .on_after_sending_transaction_callback, }); } let signature = match near_ledger::sign_transaction( &borsh::to_vec(&unsigned_transaction) .wrap_err("Transaction is not expected to fail on serialization")?, seed_phrase_hd_path.clone(), ) { Ok(signature) => { near_crypto::Signature::from_parts(near_crypto::KeyType::ED25519, &signature) .wrap_err("Signature is not expected to fail on deserialization")? } Err(NEARLedgerError::APDUExchangeError(msg)) if msg.contains(SW_BUFFER_OVERFLOW) => { return Err(color_eyre::Report::msg(ERR_OVERFLOW_MEMO)); } Err(near_ledger_error) => { return Err(color_eyre::Report::msg(format!( "Error occurred while signing the transaction: {near_ledger_error:?}" ))); } }; let mut signed_transaction = near_primitives::transaction::SignedTransaction::new( signature.clone(), unsigned_transaction, ); tracing::info!( parent: &tracing::Span::none(), "Your transaction was signed successfully.{}", crate::common::indent_payload(&format!( "\nPublic key: {}\nSignature: {}\n ", scope.signer_public_key, signature )) ); (previous_context.on_after_signing_callback)( &mut signed_transaction, &previous_context.network_config, )?; Ok(Self { network_config: previous_context.network_config, global_context: previous_context.global_context, signed_transaction_or_signed_delegate_action: signed_transaction.into(), on_before_sending_transaction_callback: previous_context .on_before_sending_transaction_callback, on_after_sending_transaction_callback: previous_context .on_after_sending_transaction_callback, }) } } impl From<SignLedgerContext> for super::SubmitContext { fn from(item: SignLedgerContext) -> Self { Self { network_config: item.network_config, global_context: item.global_context, signed_transaction_or_signed_delegate_action: item .signed_transaction_or_signed_delegate_action, on_before_sending_transaction_callback: item.on_before_sending_transaction_callback, on_after_sending_transaction_callback: item.on_after_sending_transaction_callback, } } } impl interactive_clap::FromCli for SignLedger { type FromCliContext = crate::commands::TransactionContext; type FromCliError = color_eyre::eyre::Error; fn from_cli( optional_clap_variant: Option<<SignLedger as interactive_clap::ToCli>::CliVariant>, context: Self::FromCliContext, ) -> interactive_clap::ResultFromCli< <Self as interactive_clap::ToCli>::CliVariant, Self::FromCliError, > where Self: Sized + interactive_clap::ToCli, { let mut clap_variant = optional_clap_variant.unwrap_or_default(); if clap_variant.seed_phrase_hd_path.is_none() { clap_variant.seed_phrase_hd_path = match Self::input_seed_phrase_hd_path(&context) { Ok(Some(seed_phrase_hd_path)) => Some(seed_phrase_hd_path), Ok(None) => return interactive_clap::ResultFromCli::Cancel(Some(clap_variant)), Err(err) => return interactive_clap::ResultFromCli::Err(Some(clap_variant), err), }; } let seed_phrase_hd_path = clap_variant .seed_phrase_hd_path .clone() .expect("Unexpected error"); if let crate::Verbosity::Quiet = context.global_context.verbosity { println!("Opening the NEAR application... Please approve opening the application"); } tracing::info!( parent: &tracing::Span::none(), "Opening the NEAR application... Please approve opening the application" ); if let Err(err) = near_ledger::open_near_application().map_err(|ledger_error| { color_eyre::Report::msg(format!("An error happened while trying to open the NEAR application on the ledger: {ledger_error:?}")) }) { return interactive_clap::ResultFromCli::Err(Some(clap_variant), err); } std::thread::sleep(std::time::Duration::from_secs(1)); if let crate::Verbosity::Quiet = context.global_context.verbosity { println!("Please allow getting the PublicKey on Ledger device (HD Path: {seed_phrase_hd_path})"); } tracing::info!( parent: &tracing::Span::none(), "Please allow getting the PublicKey on Ledger device (HD Path: {seed_phrase_hd_path})\n{}", crate::common::indent_payload(" ") ); let public_key = match near_ledger::get_public_key(seed_phrase_hd_path.clone().into()) .map_err(|near_ledger_error| { color_eyre::Report::msg(format!( "An error occurred while trying to get PublicKey from Ledger device: {near_ledger_error:?}" )) }) { Ok(public_key) => public_key, Err(err) => return interactive_clap::ResultFromCli::Err(Some(clap_variant), err), }; let signer_public_key: crate::types::public_key::PublicKey = near_crypto::PublicKey::ED25519(near_crypto::ED25519PublicKey::from( public_key.to_bytes(), )) .into(); if clap_variant.nonce.is_none() { clap_variant.nonce = match Self::input_nonce(&context) { Ok(optional_nonce) => optional_nonce, Err(err) => return interactive_clap::ResultFromCli::Err(Some(clap_variant), err), }; } let nonce = clap_variant.nonce; if clap_variant.block_hash.is_none() { clap_variant.block_hash = match Self::input_block_hash(&context) { Ok(optional_block_hash) => optional_block_hash, Err(err) => return interactive_clap::ResultFromCli::Err(Some(clap_variant), err), }; } let block_hash = clap_variant.block_hash; let new_context_scope = InteractiveClapContextScopeForSignLedger { signer_public_key, seed_phrase_hd_path, nonce, block_hash, block_height: clap_variant.block_height, meta_transaction_valid_for: clap_variant.meta_transaction_valid_for, }; let output_context = match SignLedgerContext::from_previous_context(context, &new_context_scope) { Ok(new_context) => new_context, Err(err) => return interactive_clap::ResultFromCli::Err(Some(clap_variant), err), }; match super::Submit::from_cli(clap_variant.submit.take(), output_context.into()) { interactive_clap::ResultFromCli::Ok(submit) => { clap_variant.submit = Some(submit); interactive_clap::ResultFromCli::Ok(clap_variant) } interactive_clap::ResultFromCli::Cancel(optional_submit) => { clap_variant.submit = optional_submit; interactive_clap::ResultFromCli::Cancel(Some(clap_variant)) } interactive_clap::ResultFromCli::Back => interactive_clap::ResultFromCli::Back, interactive_clap::ResultFromCli::Err(optional_submit, err) => { clap_variant.submit = optional_submit; interactive_clap::ResultFromCli::Err(Some(clap_variant), err) } } } } impl SignLedger { pub fn input_seed_phrase_hd_path( _context: &crate::commands::TransactionContext, ) -> color_eyre::eyre::Result<Option<crate::types::slip10::BIP32Path>> { input_seed_phrase_hd_path() } fn input_nonce( context: &crate::commands::TransactionContext, ) -> color_eyre::eyre::Result<Option<u64>> { if context.global_context.offline { return Ok(Some( CustomType::<u64>::new("Enter a nonce for the access key:").prompt()?, )); } Ok(None) } fn input_block_hash( context: &crate::commands::TransactionContext, ) -> color_eyre::eyre::Result<Option<crate::types::crypto_hash::CryptoHash>> { if context.global_context.offline { return Ok(Some( CustomType::<crate::types::crypto_hash::CryptoHash>::new( "Enter recent block hash:", ) .prompt()?, )); } Ok(None) } } pub fn input_seed_phrase_hd_path( ) -> color_eyre::eyre::Result<Option<crate::types::slip10::BIP32Path>> { Ok(Some( CustomType::new("Enter seed phrase HD Path (if you're not sure, leave blank for default):") .with_starting_input("44'/397'/0'/0'/1'") .prompt()?, )) }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/transaction_signature_options/send/mod.rs
src/transaction_signature_options/send/mod.rs
use color_eyre::owo_colors::OwoColorize; use tracing_indicatif::span_ext::IndicatifSpanExt; use crate::common::JsonRpcClientExt; #[derive(Debug, Clone, interactive_clap_derive::InteractiveClap)] #[interactive_clap(input_context = super::SubmitContext)] #[interactive_clap(output_context = SendContext)] pub struct Send; #[derive(Debug, Clone)] pub struct SendContext; impl SendContext { #[tracing::instrument(name = "Sending transaction ...", skip_all)] pub fn from_previous_context( previous_context: super::SubmitContext, _scope: &<Send as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { tracing::info!(target: "near_teach_me", "Sending transaction ..."); let storage_message = (previous_context.on_before_sending_transaction_callback)( &previous_context.signed_transaction_or_signed_delegate_action, &previous_context.network_config, ) .map_err(color_eyre::Report::msg)?; match previous_context.signed_transaction_or_signed_delegate_action { super::SignedTransactionOrSignedDelegateAction::SignedTransaction( signed_transaction, ) => { let transaction_info = sending_signed_transaction( &previous_context.network_config, &signed_transaction, )?; crate::common::print_transaction_status( &transaction_info, &previous_context.network_config, previous_context.global_context.verbosity, )?; (previous_context.on_after_sending_transaction_callback)( &transaction_info, &previous_context.network_config, ) .map_err(color_eyre::Report::msg)?; } super::SignedTransactionOrSignedDelegateAction::SignedDelegateAction( signed_delegate_action, ) => { match sending_delegate_action( signed_delegate_action, previous_context.network_config .meta_transaction_relayer_url .expect("Internal error: Meta-transaction relayer URL must be Some() at this point"), ){ Ok(relayer_response) => { if relayer_response.status().is_success() { let response_text = relayer_response.text().map_err(color_eyre::Report::msg)?; eprintln!("\nRelayer Response text: {response_text}"); } else { eprintln!( "\nRequest failed with status code: {}", relayer_response.status() ); } } Err(report) => return Err(color_eyre::Report::msg(report)), }; } } if let crate::Verbosity::Interactive | crate::Verbosity::TeachMe = previous_context.global_context.verbosity { tracing_indicatif::suspend_tracing_indicatif(|| eprintln!("{storage_message}")); } Ok(Self) } } #[tracing::instrument(name = "Broadcasting transaction via RPC", skip_all)] pub fn sending_signed_transaction( network_config: &crate::config::NetworkConfig, signed_transaction: &near_primitives::transaction::SignedTransaction, ) -> color_eyre::Result<near_primitives::views::FinalExecutionOutcomeView> { tracing::Span::current().pb_set_message(network_config.rpc_url.as_str()); tracing::info!(target: "near_teach_me", "Broadcasting transaction via RPC {}", network_config.rpc_url.as_str()); let retries_number = 5; let mut retries = (1..=retries_number).rev(); let transaction_info = loop { let request = near_jsonrpc_client::methods::broadcast_tx_commit::RpcBroadcastTxCommitRequest { signed_transaction: signed_transaction.clone(), }; tracing::info!( target: "near_teach_me", parent: &tracing::Span::none(), "I am making HTTP call to NEAR JSON RPC to broadcast a transaction, learn more https://docs.near.org/api/rpc/transactions#send-tx" ); let transaction_info_result = network_config .json_rpc_client() .blocking_call(request) .inspect(crate::common::teach_me_call_response); match transaction_info_result { Ok(response) => { break response; } Err(ref err) => match crate::common::rpc_transaction_error(err) { Ok(message) => { if let Some(retries_left) = retries.next() { sleep_after_error( format!("{} (Previous attempt failed with error: `{}`. Will retry {} more times)", network_config.rpc_url, message.red(), retries_left) ); } else { return Err(color_eyre::eyre::eyre!(err.to_string())); } } Err(report) => return Err(color_eyre::Report::msg(report)), }, }; }; Ok(transaction_info) } #[tracing::instrument( name = "Waiting 5 seconds before broadcasting transaction via RPC", skip_all )] pub fn sleep_after_error(additional_message_for_name: String) { tracing::Span::current().pb_set_message(&additional_message_for_name); tracing::info!(target: "near_teach_me", "Waiting 5 seconds before broadcasting transaction via RPC {additional_message_for_name}"); std::thread::sleep(std::time::Duration::from_secs(5)); } #[tracing::instrument(name = "Broadcasting delegate action via a relayer url", skip_all)] fn sending_delegate_action( signed_delegate_action: near_primitives::action::delegate::SignedDelegateAction, meta_transaction_relayer_url: url::Url, ) -> Result<reqwest::blocking::Response, reqwest::Error> { tracing::Span::current().pb_set_message(meta_transaction_relayer_url.as_str()); tracing::info!(target: "near_teach_me", "Broadcasting delegate action via a relayer url {}", meta_transaction_relayer_url.as_str()); let client = reqwest::blocking::Client::new(); let request_payload = serde_json::json!({ "signed_delegate_action": crate::types::signed_delegate_action::SignedDelegateActionAsBase64::from( signed_delegate_action ).to_string() }); tracing::info!( target: "near_teach_me", parent: &tracing::Span::none(), "I am making HTTP call to NEAR JSON RPC to broadcast a transaction, learn more https://docs.near.org/concepts/abstraction/relayers" ); tracing::info!( target: "near_teach_me", parent: &tracing::Span::none(), "HTTP POST {}", meta_transaction_relayer_url.as_str() ); tracing::info!( target: "near_teach_me", parent: &tracing::Span::none(), "JSON Body:\n{}", crate::common::indent_payload(&format!("{request_payload:#}")) ); let response = client .post(meta_transaction_relayer_url.clone()) .json(&request_payload) .send()?; tracing::info!( target: "near_teach_me", parent: &tracing::Span::none(), "JSON RPC Response:\n{}", crate::common::indent_payload(&format!("{response:#?}")) ); Ok(response) }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/transaction_signature_options/sign_with_access_key_file/mod.rs
src/transaction_signature_options/sign_with_access_key_file/mod.rs
use color_eyre::eyre::{ContextCompat, WrapErr}; use inquire::CustomType; use near_primitives::transaction::Transaction; use near_primitives::transaction::TransactionV0; use crate::common::JsonRpcClientExt; use crate::common::RpcQueryResponseExt; #[derive(Debug, Clone, interactive_clap_derive::InteractiveClap)] #[interactive_clap(input_context = crate::commands::TransactionContext)] #[interactive_clap(output_context = SignAccessKeyFileContext)] pub struct SignAccessKeyFile { /// What is the location of the account access key file (path/to/access-key-file.json)? file_path: crate::types::path_buf::PathBuf, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] pub nonce: Option<u64>, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] pub block_hash: Option<crate::types::crypto_hash::CryptoHash>, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] pub block_height: Option<near_primitives::types::BlockHeight>, #[interactive_clap(long)] #[interactive_clap(skip_interactive_input)] meta_transaction_valid_for: Option<u64>, #[interactive_clap(subcommand)] submit: super::Submit, } #[derive(Clone)] pub struct SignAccessKeyFileContext { network_config: crate::config::NetworkConfig, global_context: crate::GlobalContext, signed_transaction_or_signed_delegate_action: super::SignedTransactionOrSignedDelegateAction, on_before_sending_transaction_callback: crate::transaction_signature_options::OnBeforeSendingTransactionCallback, on_after_sending_transaction_callback: crate::transaction_signature_options::OnAfterSendingTransactionCallback, } impl SignAccessKeyFileContext { #[tracing::instrument( name = "Signing the transaction using the account access key file ...", skip_all )] pub fn from_previous_context( previous_context: crate::commands::TransactionContext, scope: &<SignAccessKeyFile as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { tracing::info!(target: "near_teach_me", "Signing the transaction using the account access key file ..."); let network_config = previous_context.network_config.clone(); let data = std::fs::read_to_string(&scope.file_path).wrap_err("Access key file not found!")?; let account_json: super::AccountKeyPair = serde_json::from_str(&data) .wrap_err_with(|| format!("Error reading data from file: {:?}", &scope.file_path))?; let (nonce, block_hash, block_height) = if previous_context.global_context.offline { ( scope .nonce .wrap_err("Nonce is required to sign a transaction in offline mode")?, scope .block_hash .wrap_err("Block Hash is required to sign a transaction in offline mode")? .0, scope .block_height .wrap_err("Block Height is required to sign a transaction in offline mode")?, ) } else { let rpc_query_response = network_config .json_rpc_client() .blocking_call_view_access_key( &previous_context.prepopulated_transaction.signer_id, &account_json.public_key, near_primitives::types::BlockReference::latest(), ) .wrap_err_with(|| format!("Cannot sign a transaction due to an error while fetching the most recent nonce value on network <{}>", network_config.network_name) )?; ( rpc_query_response .access_key_view() .wrap_err("Error current_nonce")? .nonce + 1, rpc_query_response.block_hash, rpc_query_response.block_height, ) }; let mut unsigned_transaction = TransactionV0 { public_key: account_json.public_key.clone(), block_hash, nonce, signer_id: previous_context.prepopulated_transaction.signer_id, receiver_id: previous_context.prepopulated_transaction.receiver_id, actions: previous_context.prepopulated_transaction.actions, }; (previous_context.on_before_signing_callback)(&mut unsigned_transaction, &network_config)?; let unsigned_transaction = Transaction::V0(unsigned_transaction); let signature = account_json .private_key .sign(unsigned_transaction.get_hash_and_size().0.as_ref()); if network_config.meta_transaction_relayer_url.is_some() { let max_block_height = block_height + scope .meta_transaction_valid_for .unwrap_or(super::META_TRANSACTION_VALID_FOR_DEFAULT); let signed_delegate_action = super::get_signed_delegate_action( unsigned_transaction, &account_json.public_key, account_json.private_key, max_block_height, ); return Ok(Self { network_config: previous_context.network_config, global_context: previous_context.global_context, signed_transaction_or_signed_delegate_action: signed_delegate_action.into(), on_before_sending_transaction_callback: previous_context .on_before_sending_transaction_callback, on_after_sending_transaction_callback: previous_context .on_after_sending_transaction_callback, }); } let mut signed_transaction = near_primitives::transaction::SignedTransaction::new( signature.clone(), unsigned_transaction, ); tracing::info!( parent: &tracing::Span::none(), "Your transaction was signed successfully.{}", crate::common::indent_payload(&format!( "\nPublic key: {}\nSignature: {}\n ", account_json.public_key, signature )) ); (previous_context.on_after_signing_callback)( &mut signed_transaction, &previous_context.network_config, )?; Ok(Self { network_config: previous_context.network_config, global_context: previous_context.global_context, signed_transaction_or_signed_delegate_action: signed_transaction.into(), on_before_sending_transaction_callback: previous_context .on_before_sending_transaction_callback, on_after_sending_transaction_callback: previous_context .on_after_sending_transaction_callback, }) } } impl From<SignAccessKeyFileContext> for super::SubmitContext { fn from(item: SignAccessKeyFileContext) -> Self { Self { network_config: item.network_config, global_context: item.global_context, signed_transaction_or_signed_delegate_action: item .signed_transaction_or_signed_delegate_action, on_before_sending_transaction_callback: item.on_before_sending_transaction_callback, on_after_sending_transaction_callback: item.on_after_sending_transaction_callback, } } } impl SignAccessKeyFile { fn input_nonce( context: &crate::commands::TransactionContext, ) -> color_eyre::eyre::Result<Option<u64>> { if context.global_context.offline { return Ok(Some( CustomType::<u64>::new("Enter a nonce for the access key:").prompt()?, )); } Ok(None) } fn input_block_hash( context: &crate::commands::TransactionContext, ) -> color_eyre::eyre::Result<Option<crate::types::crypto_hash::CryptoHash>> { if context.global_context.offline { return Ok(Some( CustomType::<crate::types::crypto_hash::CryptoHash>::new( "Enter recent block hash:", ) .prompt()?, )); } Ok(None) } fn input_block_height( context: &crate::commands::TransactionContext, ) -> color_eyre::eyre::Result<Option<near_primitives::types::BlockHeight>> { if context.global_context.offline { return Ok(Some( CustomType::<near_primitives::types::BlockHeight>::new( "Enter recent block height:", ) .prompt()?, )); } Ok(None) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/js_command_match/mod.rs
src/js_command_match/mod.rs
mod constants; mod account; mod contract; mod deprecated; mod keys; mod transactions; #[derive(Debug, Clone, clap::Parser)] /// Legacy CLI commands are only supported at best-effort pub enum JsCmd { #[clap(alias("create"))] CreateAccount(self::account::create::CreateAccountArgs), #[clap(alias("delete"))] DeleteAccount(self::account::delete::DeleteAccountArgs), #[clap(alias("import-account"))] Login(self::account::login::LoginArgs), State(self::account::state::StateArgs), Call(self::contract::call::CallArgs), Deploy(self::contract::deploy::DeployArgs), #[clap(alias("storage"))] ViewState(self::contract::storage::ViewStateArgs), View(self::contract::view::ViewArgs), AddKey(self::keys::add::AddKeyArgs), DeleteKey(self::keys::delete::DeleteKeyArgs), #[clap(alias("keys"))] ListKeys(self::keys::list::KeysArgs), #[clap(alias("send-near"))] Send(self::transactions::send::SendArgs), TxStatus(self::transactions::status::TxStatusArgs), Validators(self::deprecated::ValidatorsArgs), #[clap(alias("validator-stake"))] Stake(self::deprecated::StakeArgs), } impl JsCmd { pub fn rust_command_generation(&self) -> Vec<String> { let network = std::env::var("NEAR_NETWORK") .or_else(|_| std::env::var("NEAR_ENV")) .unwrap_or_else(|_| "testnet".to_owned()); match self { Self::CreateAccount(args) => args.to_cli_args(network), Self::DeleteAccount(args) => args.to_cli_args(network), Self::Login(args) => args.to_cli_args(network), Self::State(args) => args.to_cli_args(network), Self::Call(args) => args.to_cli_args(network), Self::Deploy(args) => args.to_cli_args(network), Self::ViewState(args) => args.to_cli_args(network), Self::View(args) => args.to_cli_args(network), Self::AddKey(args) => args.to_cli_args(network), Self::DeleteKey(args) => args.to_cli_args(network), Self::ListKeys(args) => args.to_cli_args(network), Self::Send(args) => args.to_cli_args(network), Self::TxStatus(args) => args.to_cli_args(network), Self::Validators(args) => args.to_cli_args(network), Self::Stake(args) => args.to_cli_args(network), } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/js_command_match/constants.rs
src/js_command_match/constants.rs
// Accounts pub const USE_ACCOUNT_ALIASES: [&str; 6] = [ "masterAccount", "master-account", "useAccount", "use-account", "accountId", "account-id", ]; // Contracts pub const CONTRACT_ID_ALIASES: [&str; 2] = ["contractId", "contract-id"]; pub const METHOD_NAMES_ALIASES: [&str; 2] = ["methodNames", "method-names"]; // Keys pub const PUBLIC_KEY_ALIASES: [&str; 2] = ["publicKey", "public-key"]; pub const SEED_PHRASE_ALIASES: [&str; 2] = ["seedPhrase", "seed-phrase"]; // Ledger pub const LEDGER_PATH_ALIASES: [&str; 2] = ["ledgerPath", "ledger-path"]; pub const DEFAULT_SEED_PHRASE_PATH: &str = "44'/397'/0'/0'/1'"; pub const SIGN_WITH_LEDGER_ALIASES: [&str; 4] = [ "signWithLedger", "sign-with-ledger", "useLedgerKey", "use-ledger-key", ]; pub const USE_LEDGER_PK_ALIASES: [&str; 4] = [ "useLedgerPK", "use-ledger-pk", "newLedgerKey", "new-ledger-key", ]; pub const PK_LEDGER_PATH_ALIASES: [&str; 2] = ["pkLedgerPath", "pk-ledger-path"]; // Balance and faucet pub const INITIAL_BALANCE_ALIASES: [&str; 2] = ["initialBalance", "initial-balance"]; pub const USE_FAUCET_ALIASES: [&str; 2] = ["useFaucet", "use-faucet"]; // SETTINGS pub const NETWORK_ID_ALIASES: [&str; 2] = ["networkId", "network-id"]; pub const BLOCK_ID_ALIASES: [&str; 2] = ["blockId", "block-id"]; // Deploy pub const WASM_FILE_ALIASES: [&str; 2] = ["wasmFile", "wasm-file"]; pub const INIT_FUNCTION_ALIASES: [&str; 2] = ["initFunction", "init-function"]; pub const INIT_ARGS_ALIASES: [&str; 2] = ["initArgs", "init-args"]; pub const INIT_GAS_ALIASES: [&str; 2] = ["initGas", "init-gas"]; pub const INIT_DEPOSIT_ALIASES: [&str; 2] = ["initDeposit", "init-deposit"];
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/js_command_match/deprecated.rs
src/js_command_match/deprecated.rs
use color_eyre::owo_colors::OwoColorize; #[derive(Debug, Clone, clap::Parser)] /// This is a legacy `validators` command. Once you run it with the specified arguments, new syntax command will be suggested. pub struct ValidatorsArgs { #[clap(allow_hyphen_values = true, num_args = 0..)] _unknown_args: Vec<String>, } #[derive(Debug, Clone, clap::Parser)] pub struct StakeArgs { #[clap(allow_hyphen_values = true, num_args = 0..)] _unknown_args: Vec<String>, } const DEPRECATED: &str = "The command you tried to run has been moved into its own CLI extension called near-validator.\nPlease, follow the installation instructions here: https://github.com/near-cli-rs/near-validator-cli-rs/blob/master/README.md"; impl ValidatorsArgs { pub fn to_cli_args(&self, _network_config: String) -> Vec<String> { eprintln!("\n{}\n", DEPRECATED.to_string().yellow()); vec!["near-validator".to_string()] } } impl StakeArgs { pub fn to_cli_args(&self, _network_config: String) -> Vec<String> { eprintln!("\n{}\n", DEPRECATED.to_string().yellow()); vec!["near-validator".to_string()] } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/js_command_match/account/login.rs
src/js_command_match/account/login.rs
use crate::js_command_match::constants::NETWORK_ID_ALIASES; #[derive(Debug, Clone, clap::Parser)] /// This is a legacy `legacy` command. Once you run it with the specified arguments, new syntax command will be suggested. pub struct LoginArgs { #[clap(long, aliases = NETWORK_ID_ALIASES)] network_id: Option<String>, } impl LoginArgs { pub fn to_cli_args(&self, network_config: String) -> Vec<String> { let network_id = self.network_id.clone().unwrap_or(network_config); let command = vec![ "account".to_string(), "import-account".to_string(), "using-web-wallet".to_string(), "network-config".to_string(), network_id, ]; command } } #[cfg(test)] mod tests { use super::super::super::JsCmd; use super::*; use clap::Parser; #[test] fn login() { for (input, expected_output) in [ ( "near import-account".to_string(), "account import-account using-web-wallet network-config testnet".to_string(), ), ( "near login".to_string(), "account import-account using-web-wallet network-config testnet".to_string(), ), ( format!("near login --{} testnet", NETWORK_ID_ALIASES[0]), "account import-account using-web-wallet network-config testnet".to_string(), ), ( format!("near login --{} mainnet", NETWORK_ID_ALIASES[1]), "account import-account using-web-wallet network-config mainnet".to_string(), ), ] { let input_cmd = shell_words::split(&input).expect("Input command must be a valid shell command"); let JsCmd::Login(login_args) = JsCmd::parse_from(&input_cmd) else { panic!( "Login command was expected, but something else was parsed out from {input}" ); }; assert_eq!( shell_words::join(LoginArgs::to_cli_args(&login_args, "testnet".to_string())), expected_output ); } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/js_command_match/account/state.rs
src/js_command_match/account/state.rs
use crate::js_command_match::constants::NETWORK_ID_ALIASES; #[derive(Debug, Clone, clap::Parser)] pub struct StateArgs { account_id: String, #[clap(long, aliases = NETWORK_ID_ALIASES)] network_id: Option<String>, } impl StateArgs { pub fn to_cli_args(&self, network_config: String) -> Vec<String> { let network_id = self.network_id.clone().unwrap_or(network_config); let command = vec![ "account".to_string(), "view-account-summary".to_string(), self.account_id.to_owned(), "network-config".to_string(), network_id, "now".to_string(), ]; command } } #[cfg(test)] mod tests { use super::super::super::JsCmd; use super::*; use clap::Parser; #[test] fn state() { for (input, expected_output) in [ ( "near state contract.testnet".to_string(), "account view-account-summary contract.testnet network-config testnet now" .to_string(), ), ( format!( "near state contract.testnet --{} testnet", NETWORK_ID_ALIASES[0] ), "account view-account-summary contract.testnet network-config testnet now" .to_string(), ), ( format!( "near state contract.testnet --{} mainnet", NETWORK_ID_ALIASES[1] ), "account view-account-summary contract.testnet network-config mainnet now" .to_string(), ), ] { let input_cmd = shell_words::split(&input).expect("Input command must be a valid shell command"); let JsCmd::State(state_args) = JsCmd::parse_from(&input_cmd) else { panic!( "State command was expected, but something else was parsed out from {input}" ); }; assert_eq!( shell_words::join(StateArgs::to_cli_args(&state_args, "testnet".to_string())), expected_output ); } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/js_command_match/account/mod.rs
src/js_command_match/account/mod.rs
pub mod create; pub mod delete; pub mod login; pub mod state;
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/js_command_match/account/create.rs
src/js_command_match/account/create.rs
use crate::js_command_match::constants::{ DEFAULT_SEED_PHRASE_PATH, INITIAL_BALANCE_ALIASES, LEDGER_PATH_ALIASES, NETWORK_ID_ALIASES, PK_LEDGER_PATH_ALIASES, PUBLIC_KEY_ALIASES, SEED_PHRASE_ALIASES, SIGN_WITH_LEDGER_ALIASES, USE_ACCOUNT_ALIASES, USE_FAUCET_ALIASES, USE_LEDGER_PK_ALIASES, }; #[derive(Debug, Clone, clap::Parser)] pub struct CreateAccountArgs { new_account_id: String, #[clap(long, aliases = USE_FAUCET_ALIASES, default_value_t = false)] use_faucet: bool, #[clap(long, aliases = USE_ACCOUNT_ALIASES, conflicts_with = "use_faucet")] use_account: Option<String>, #[clap(long, aliases = INITIAL_BALANCE_ALIASES, default_value = "1")] initial_balance: String, #[clap(long, aliases = PUBLIC_KEY_ALIASES)] public_key: Option<String>, #[clap(long, aliases = SEED_PHRASE_ALIASES, conflicts_with = "public_key")] seed_phrase: Option<String>, #[clap(long, aliases = SIGN_WITH_LEDGER_ALIASES, default_value_t = false, conflicts_with="use_faucet")] sign_with_ledger: bool, #[clap(long, aliases = LEDGER_PATH_ALIASES, default_value = DEFAULT_SEED_PHRASE_PATH)] ledger_path: String, #[clap(long, aliases = USE_LEDGER_PK_ALIASES, default_value_t = false, conflicts_with = "public_key")] use_ledger_pk: bool, #[clap(long, aliases = PK_LEDGER_PATH_ALIASES, default_value = DEFAULT_SEED_PHRASE_PATH)] pk_ledger_path: String, #[clap(long, aliases = NETWORK_ID_ALIASES)] network_id: Option<String>, } impl CreateAccountArgs { pub fn to_cli_args(&self, network_config: String) -> Vec<String> { let network_id = self.network_id.clone().unwrap_or(network_config); let mut command = vec!["account".to_string(), "create-account".to_string()]; if self.use_faucet { command.push("sponsor-by-faucet-service".to_string()); command.push(self.new_account_id.to_owned()); } else { command.push("fund-myself".to_string()); command.push(self.new_account_id.to_owned()); command.push(format!("{} NEAR", self.initial_balance)); } if self.use_ledger_pk { command.push("use-ledger".to_string()); command.push("--seed-phrase-hd-path".to_string()); command.push(self.pk_ledger_path.to_owned()); } else if let Some(seed_phrase) = &self.seed_phrase { command.push("use-manually-provided-seed-phrase".to_string()); command.push(seed_phrase.to_string()); } else if let Some(public_key) = &self.public_key { command.push("use-manually-provided-public-key".to_string()); command.push(public_key.to_string()); } else { command.push("autogenerate-new-keypair".to_string()); command.push("save-to-keychain".to_string()); } if !self.use_faucet { command.push("sign-as".to_string()); command.push( self.use_account .to_owned() .expect("Valid master account must be provided"), ); }; command.push("network-config".to_string()); command.push(network_id); if self.use_faucet { command.push("create".to_string()); } else { if self.sign_with_ledger { command.push("sign-with-ledger".to_string()); command.push("--seed-phrase-hd-path".to_string()); command.push(self.ledger_path.to_owned()); } else { command.push("sign-with-keychain".to_string()); } command.push("send".to_string()); } command } } #[cfg(test)] mod tests { use super::super::super::JsCmd; use super::*; use clap::Parser; #[test] fn create_account() { for (input, expected_output) in [ ( format!("near create-account bob.testnet --{}", USE_FAUCET_ALIASES[0]), "account create-account sponsor-by-faucet-service bob.testnet autogenerate-new-keypair save-to-keychain network-config testnet create" ), ( format!("near create bob.testnet --{}", USE_FAUCET_ALIASES[0]), "account create-account sponsor-by-faucet-service bob.testnet autogenerate-new-keypair save-to-keychain network-config testnet create" ), ( format!("near create bob.testnet --{}", USE_FAUCET_ALIASES[1]), "account create-account sponsor-by-faucet-service bob.testnet autogenerate-new-keypair save-to-keychain network-config testnet create" ), ( format!("near create bob.testnet --{} alice.testnet", USE_ACCOUNT_ALIASES[0]), "account create-account fund-myself bob.testnet '1 NEAR' autogenerate-new-keypair save-to-keychain sign-as alice.testnet network-config testnet sign-with-keychain send" ), ( format!("near create bob.testnet --{} alice.testnet", USE_ACCOUNT_ALIASES[1]), "account create-account fund-myself bob.testnet '1 NEAR' autogenerate-new-keypair save-to-keychain sign-as alice.testnet network-config testnet sign-with-keychain send" ), ( format!("near create bob.testnet --{} alice.testnet", USE_ACCOUNT_ALIASES[2]), "account create-account fund-myself bob.testnet '1 NEAR' autogenerate-new-keypair save-to-keychain sign-as alice.testnet network-config testnet sign-with-keychain send" ), ( format!("near create bob.testnet --{} alice.testnet", USE_ACCOUNT_ALIASES[3]), "account create-account fund-myself bob.testnet '1 NEAR' autogenerate-new-keypair save-to-keychain sign-as alice.testnet network-config testnet sign-with-keychain send" ), ( format!("near create bob.testnet --{} alice.testnet", USE_ACCOUNT_ALIASES[4]), "account create-account fund-myself bob.testnet '1 NEAR' autogenerate-new-keypair save-to-keychain sign-as alice.testnet network-config testnet sign-with-keychain send" ), ( format!("near create bob.testnet --{} alice.testnet", USE_ACCOUNT_ALIASES[5]), "account create-account fund-myself bob.testnet '1 NEAR' autogenerate-new-keypair save-to-keychain sign-as alice.testnet network-config testnet sign-with-keychain send" ), ( format!("near create bob.testnet --useAccount alice.testnet --{} 0.1", INITIAL_BALANCE_ALIASES[0]), "account create-account fund-myself bob.testnet '0.1 NEAR' autogenerate-new-keypair save-to-keychain sign-as alice.testnet network-config testnet sign-with-keychain send" ), ( format!("near create bob.testnet --useAccount alice.testnet --{} 0.1", INITIAL_BALANCE_ALIASES[1]), "account create-account fund-myself bob.testnet '0.1 NEAR' autogenerate-new-keypair save-to-keychain sign-as alice.testnet network-config testnet sign-with-keychain send" ), ( format!("near create bob.testnet --useAccount alice.testnet --{} 78MziB9aTNsu19MHHVrfWy762S5mAqXgCB6Vgvrv9uGV --initialBalance 0.1", PUBLIC_KEY_ALIASES[0]), "account create-account fund-myself bob.testnet '0.1 NEAR' use-manually-provided-public-key 78MziB9aTNsu19MHHVrfWy762S5mAqXgCB6Vgvrv9uGV sign-as alice.testnet network-config testnet sign-with-keychain send" ), ( format!("near create bob.testnet --useAccount alice.testnet --{} 78MziB9aTNsu19MHHVrfWy762S5mAqXgCB6Vgvrv9uGV --initialBalance 0.1", PUBLIC_KEY_ALIASES[1]), "account create-account fund-myself bob.testnet '0.1 NEAR' use-manually-provided-public-key 78MziB9aTNsu19MHHVrfWy762S5mAqXgCB6Vgvrv9uGV sign-as alice.testnet network-config testnet sign-with-keychain send" ), ( format!("near create bob.testnet --{} 'crisp clump stay mean dynamic become fashion mail bike disorder chronic sight' --useFaucet", SEED_PHRASE_ALIASES[0]), "account create-account sponsor-by-faucet-service bob.testnet use-manually-provided-seed-phrase 'crisp clump stay mean dynamic become fashion mail bike disorder chronic sight' network-config testnet create" ), ( format!("near create bob.testnet --{} 'crisp clump stay mean dynamic become fashion mail bike disorder chronic sight' --useFaucet", SEED_PHRASE_ALIASES[1]), "account create-account sponsor-by-faucet-service bob.testnet use-manually-provided-seed-phrase 'crisp clump stay mean dynamic become fashion mail bike disorder chronic sight' network-config testnet create" ), ( format!("near create bob.testnet --useAccount alice.testnet --{} --networkId testnet", SIGN_WITH_LEDGER_ALIASES[0]), "account create-account fund-myself bob.testnet '1 NEAR' autogenerate-new-keypair save-to-keychain sign-as alice.testnet network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' send" ), ( format!("near create bob.testnet --useAccount alice.testnet --{} --networkId testnet", SIGN_WITH_LEDGER_ALIASES[1]), "account create-account fund-myself bob.testnet '1 NEAR' autogenerate-new-keypair save-to-keychain sign-as alice.testnet network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' send" ), ( format!("near create bob.testnet --useAccount alice.testnet --{} --networkId testnet", SIGN_WITH_LEDGER_ALIASES[2]), "account create-account fund-myself bob.testnet '1 NEAR' autogenerate-new-keypair save-to-keychain sign-as alice.testnet network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' send" ), ( format!("near create bob.testnet --useAccount alice.testnet --{} --networkId testnet", SIGN_WITH_LEDGER_ALIASES[3]), "account create-account fund-myself bob.testnet '1 NEAR' autogenerate-new-keypair save-to-keychain sign-as alice.testnet network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' send" ), ( format!("near create bob.testnet --useAccount alice.testnet --signWithLedger --{} \"44'/397'/0'/0'/2'\"", LEDGER_PATH_ALIASES[0]), "account create-account fund-myself bob.testnet '1 NEAR' autogenerate-new-keypair save-to-keychain sign-as alice.testnet network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/2'\\''' send" ), ( format!("near create bob.testnet --useAccount alice.testnet --signWithLedger --{} \"44'/397'/0'/0'/2'\"", LEDGER_PATH_ALIASES[1]), "account create-account fund-myself bob.testnet '1 NEAR' autogenerate-new-keypair save-to-keychain sign-as alice.testnet network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/2'\\''' send" ), ( format!("near create bob.testnet --{} --useFaucet", USE_LEDGER_PK_ALIASES[0]), "account create-account sponsor-by-faucet-service bob.testnet use-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' network-config testnet create" ), ( format!("near create bob.testnet --{} --useFaucet", USE_LEDGER_PK_ALIASES[1]), "account create-account sponsor-by-faucet-service bob.testnet use-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' network-config testnet create" ), ( format!("near create bob.testnet --{} --useFaucet", USE_LEDGER_PK_ALIASES[2]), "account create-account sponsor-by-faucet-service bob.testnet use-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' network-config testnet create" ), ( format!("near create bob.testnet --{} --useFaucet", USE_LEDGER_PK_ALIASES[3]), "account create-account sponsor-by-faucet-service bob.testnet use-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' network-config testnet create" ), ( format!("near create bob.testnet --useLedgerPK --{} \"44'/397'/0'/0'/2'\" --useFaucet", PK_LEDGER_PATH_ALIASES[0]), "account create-account sponsor-by-faucet-service bob.testnet use-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/2'\\''' network-config testnet create" ), ( format!("near create bob.testnet --useLedgerPK --{} \"44'/397'/0'/0'/2'\" --useFaucet", PK_LEDGER_PATH_ALIASES[1]), "account create-account sponsor-by-faucet-service bob.testnet use-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/2'\\''' network-config testnet create" ), ( format!("near create bob.near --useAccount alice.near --signWithLedger --ledgerPath \"44'/397'/0'/0'/2'\" --{} mainnet", NETWORK_ID_ALIASES[0]), "account create-account fund-myself bob.near '1 NEAR' autogenerate-new-keypair save-to-keychain sign-as alice.near network-config mainnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/2'\\''' send" ), ( format!("near create bob.near --useAccount alice.near --signWithLedger --ledgerPath \"44'/397'/0'/0'/2'\" --{} mainnet", NETWORK_ID_ALIASES[1]), "account create-account fund-myself bob.near '1 NEAR' autogenerate-new-keypair save-to-keychain sign-as alice.near network-config mainnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/2'\\''' send" ) ] { let input_cmd = shell_words::split(&input).expect("Input command must be a valid shell command"); let JsCmd::CreateAccount(create_account_args) = JsCmd::parse_from(&input_cmd) else { panic!("CreateAccount command was expected, but something else was parsed out from {input}"); }; assert_eq!( shell_words::join(CreateAccountArgs::to_cli_args(&create_account_args, "testnet".to_string())), expected_output ); } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/js_command_match/account/delete.rs
src/js_command_match/account/delete.rs
use crate::js_command_match::constants::{ DEFAULT_SEED_PHRASE_PATH, LEDGER_PATH_ALIASES, NETWORK_ID_ALIASES, SIGN_WITH_LEDGER_ALIASES, }; #[derive(Debug, Clone, clap::Parser)] pub struct DeleteAccountArgs { account_id: String, beneficiary_id: String, #[clap(long, aliases = SIGN_WITH_LEDGER_ALIASES, default_value_t = false)] sign_with_ledger: bool, #[clap(long, aliases = LEDGER_PATH_ALIASES, default_value = DEFAULT_SEED_PHRASE_PATH)] ledger_path: String, #[clap(long, aliases = NETWORK_ID_ALIASES)] network_id: Option<String>, #[clap(long, default_value_t = false)] force: bool, } impl DeleteAccountArgs { pub fn to_cli_args(&self, network_config: String) -> Vec<String> { let network_id = self.network_id.clone().unwrap_or(network_config); let mut command = vec![ "account".to_string(), "delete-account".to_string(), self.account_id.to_owned(), "beneficiary".to_string(), self.beneficiary_id.to_owned(), ]; command.push("network-config".to_string()); command.push(network_id); if self.sign_with_ledger { command.push("sign-with-ledger".to_string()); command.push("--seed-phrase-hd-path".to_string()); command.push(self.ledger_path.to_owned()); } else { command.push("sign-with-keychain".to_string()); } if self.force { command.push("send".to_string()); } command } } #[cfg(test)] mod tests { use super::super::super::JsCmd; use super::*; use clap::Parser; #[test] fn delete_account() { for (input, expected_output) in [ ( "near delete bob.testnet alice.testnet --force".to_string(), "account delete-account bob.testnet beneficiary alice.testnet network-config testnet sign-with-keychain send".to_string() ), ( "near delete-account bob.testnet alice.testnet --force".to_string(), "account delete-account bob.testnet beneficiary alice.testnet network-config testnet sign-with-keychain send".to_string() ), ( format!("near delete-account bob.testnet alice.testnet --{} --force", SIGN_WITH_LEDGER_ALIASES[0]), "account delete-account bob.testnet beneficiary alice.testnet network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' send".to_string() ), ( format!("near delete-account bob.testnet alice.testnet --{} --force", SIGN_WITH_LEDGER_ALIASES[1]), "account delete-account bob.testnet beneficiary alice.testnet network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' send".to_string() ), ( format!("near delete-account bob.testnet alice.testnet --{} --force", SIGN_WITH_LEDGER_ALIASES[2]), "account delete-account bob.testnet beneficiary alice.testnet network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' send".to_string() ), ( format!("near delete-account bob.testnet alice.testnet --{} --force", SIGN_WITH_LEDGER_ALIASES[3]), "account delete-account bob.testnet beneficiary alice.testnet network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' send".to_string() ), ( format!("near delete-account bob.testnet alice.testnet --signWithLedger --{} \"44'/397'/0'/0'/2'\" --force", LEDGER_PATH_ALIASES[0]), "account delete-account bob.testnet beneficiary alice.testnet network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/2'\\''' send".to_string() ), ( format!("near delete-account bob.testnet alice.testnet --signWithLedger --{} \"44'/397'/0'/0'/2'\" --force", LEDGER_PATH_ALIASES[1]), "account delete-account bob.testnet beneficiary alice.testnet network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/2'\\''' send".to_string() ), ( format!("near delete-account bob.testnet alice.testnet --signWithLedger --{} mainnet --force", NETWORK_ID_ALIASES[0]), "account delete-account bob.testnet beneficiary alice.testnet network-config mainnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' send".to_string() ), ( format!("near delete-account bob.testnet alice.testnet --signWithLedger --{} mainnet --force", NETWORK_ID_ALIASES[1]), "account delete-account bob.testnet beneficiary alice.testnet network-config mainnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' send".to_string() ) ] { let input_cmd = shell_words::split(&input).expect("Input command must be a valid shell command"); let JsCmd::DeleteAccount(delete_account_args) = JsCmd::parse_from(&input_cmd) else { panic!("DeleteAccount command was expected, but something else was parsed out from {input}"); }; assert_eq!( shell_words::join(DeleteAccountArgs::to_cli_args(&delete_account_args, "testnet".to_string())), expected_output ); } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/js_command_match/transactions/status.rs
src/js_command_match/transactions/status.rs
use crate::js_command_match::constants::NETWORK_ID_ALIASES; #[derive(Debug, Clone, clap::Parser)] pub struct TxStatusArgs { hash: String, #[clap(long, aliases = NETWORK_ID_ALIASES)] network_id: Option<String>, #[clap(allow_hyphen_values = true, num_args = 0..)] _unknown_args: Vec<String>, } impl TxStatusArgs { pub fn to_cli_args(&self, network_config: String) -> Vec<String> { let network_id = self.network_id.clone().unwrap_or(network_config); let command = vec![ "transaction".to_string(), "view-status".to_string(), self.hash.to_owned(), "network-config".to_string(), network_id, ]; command } } #[cfg(test)] mod tests { use super::super::super::JsCmd; use super::*; use clap::Parser; #[test] fn tx_status() { for (input, expected_output) in [ ( "near tx-status 4HxfV69Brk7fJd3NC63ti2H3QCgwiUiMAPvwNmGWbVXo".to_string(), "transaction view-status 4HxfV69Brk7fJd3NC63ti2H3QCgwiUiMAPvwNmGWbVXo network-config testnet" ), ( format!("near tx-status 4HxfV69Brk7fJd3NC63ti2H3QCgwiUiMAPvwNmGWbVXo --{} testnet", NETWORK_ID_ALIASES[0]), "transaction view-status 4HxfV69Brk7fJd3NC63ti2H3QCgwiUiMAPvwNmGWbVXo network-config testnet" ), ( format!("near tx-status 4HxfV69Brk7fJd3NC63ti2H3QCgwiUiMAPvwNmGWbVXo --{} mainnet", NETWORK_ID_ALIASES[1]), "transaction view-status 4HxfV69Brk7fJd3NC63ti2H3QCgwiUiMAPvwNmGWbVXo network-config mainnet" ), ] { let input_cmd = shell_words::split(&input).expect("Input command must be a valid shell command"); let JsCmd::TxStatus(tx_status_args) = JsCmd::parse_from(&input_cmd) else { panic!("TxStatus command was expected, but something else was parsed out from {input}"); }; assert_eq!( shell_words::join(TxStatusArgs::to_cli_args(&tx_status_args, "testnet".to_string())), expected_output ); } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/js_command_match/transactions/send.rs
src/js_command_match/transactions/send.rs
use crate::js_command_match::constants::{ DEFAULT_SEED_PHRASE_PATH, LEDGER_PATH_ALIASES, NETWORK_ID_ALIASES, SIGN_WITH_LEDGER_ALIASES, }; #[derive(Debug, Clone, clap::Parser)] pub struct SendArgs { pub sender: String, pub receiver: String, pub amount: String, #[clap(long, aliases = SIGN_WITH_LEDGER_ALIASES, default_value_t = false)] sign_with_ledger: bool, #[clap(long, aliases = LEDGER_PATH_ALIASES, default_value = DEFAULT_SEED_PHRASE_PATH)] ledger_path: String, #[clap(long, aliases = NETWORK_ID_ALIASES)] pub network_id: Option<String>, } impl SendArgs { pub fn to_cli_args(&self, network_config: String) -> Vec<String> { let network_id = self.network_id.clone().unwrap_or(network_config); let mut command = vec![ "tokens".to_string(), self.sender.to_owned(), "send-near".to_string(), self.receiver.to_owned(), format!("{} NEAR", self.amount), "network-config".to_string(), network_id, ]; if self.sign_with_ledger { command.push("sign-with-ledger".to_string()); command.push("--seed-phrase-hd-path".to_string()); command.push(self.ledger_path.to_owned()); } else { command.push("sign-with-keychain".to_string()); } command.push("send".to_string()); command } } #[cfg(test)] mod tests { use super::super::super::JsCmd; use super::*; use clap::Parser; #[test] fn send() { for (input, expected_output) in [ ( format!("near send bob.testnet alice.testnet 1 --{}", SIGN_WITH_LEDGER_ALIASES[0]), "tokens bob.testnet send-near alice.testnet '1 NEAR' network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' send" ), ( format!("near send-near bob.testnet alice.testnet 1 --{}", SIGN_WITH_LEDGER_ALIASES[0]), "tokens bob.testnet send-near alice.testnet '1 NEAR' network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' send" ), ( format!("near send-near bob.testnet alice.testnet 1 --{}", SIGN_WITH_LEDGER_ALIASES[1]), "tokens bob.testnet send-near alice.testnet '1 NEAR' network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' send" ), ( format!("near send-near bob.testnet alice.testnet 1 --{}", SIGN_WITH_LEDGER_ALIASES[2]), "tokens bob.testnet send-near alice.testnet '1 NEAR' network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' send" ), ( format!("near send-near bob.testnet alice.testnet 1 --{}", SIGN_WITH_LEDGER_ALIASES[3]), "tokens bob.testnet send-near alice.testnet '1 NEAR' network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' send" ), ( format!("near send-near bob.testnet alice.testnet 1 --signWithLedger --{} \"44'/397'/0'/0'/2'\"", LEDGER_PATH_ALIASES[0]), "tokens bob.testnet send-near alice.testnet '1 NEAR' network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/2'\\''' send" ), ( format!("near send-near bob.testnet alice.testnet 1 --signWithLedger --{} \"44'/397'/0'/0'/2'\"", LEDGER_PATH_ALIASES[1]), "tokens bob.testnet send-near alice.testnet '1 NEAR' network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/2'\\''' send" ), ( format!("near send-near bob.testnet alice.testnet 1 --{} testnet", NETWORK_ID_ALIASES[0]), "tokens bob.testnet send-near alice.testnet '1 NEAR' network-config testnet sign-with-keychain send" ), ( format!("near send-near bob.testnet alice.testnet 1 --{} mainnet", NETWORK_ID_ALIASES[1]), "tokens bob.testnet send-near alice.testnet '1 NEAR' network-config mainnet sign-with-keychain send" ), ] { let input_cmd = shell_words::split(&input).expect("Input command must be a valid shell command"); let JsCmd::Send(send_args) = JsCmd::parse_from(&input_cmd) else { panic!("Send command was expected, but something else was parsed out from {input}"); }; assert_eq!( shell_words::join(SendArgs::to_cli_args(&send_args, "testnet".to_string())), expected_output ); } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/js_command_match/transactions/mod.rs
src/js_command_match/transactions/mod.rs
pub mod send; pub mod status;
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/js_command_match/keys/list.rs
src/js_command_match/keys/list.rs
use crate::js_command_match::constants::NETWORK_ID_ALIASES; #[derive(Debug, Clone, clap::Parser)] /// This is a legacy `keys` command. Once you run it with the specified arguments, new syntax command will be suggested. pub struct KeysArgs { account_id: String, #[clap(long, aliases = NETWORK_ID_ALIASES)] network_id: Option<String>, } impl KeysArgs { pub fn to_cli_args(&self, network_config: String) -> Vec<String> { let network_id = self.network_id.clone().unwrap_or(network_config); let command = vec![ "account".to_string(), "list-keys".to_string(), self.account_id.to_owned(), "network-config".to_string(), network_id, "now".to_string(), ]; command } } #[cfg(test)] mod tests { use super::super::super::JsCmd; use super::*; use clap::Parser; #[test] fn list_keys() { for (input, expected_output) in [ ( "near keys bob.testnet".to_string(), "account list-keys bob.testnet network-config testnet now".to_string(), ), ( "near list-keys bob.testnet".to_string(), "account list-keys bob.testnet network-config testnet now".to_string(), ), ( format!( "near list-keys bob.testnet --{} testnet", NETWORK_ID_ALIASES[0] ), "account list-keys bob.testnet network-config testnet now".to_string(), ), ( format!( "near list-keys bob.testnet --{} mainnet", NETWORK_ID_ALIASES[1] ), "account list-keys bob.testnet network-config mainnet now".to_string(), ), ] { let input_cmd = shell_words::split(&input).expect("Input command must be a valid shell command"); let JsCmd::ListKeys(keys_args) = JsCmd::parse_from(&input_cmd) else { panic!( "ListKeys command was expected, but something else was parsed out from {input}" ); }; assert_eq!( shell_words::join(KeysArgs::to_cli_args(&keys_args, "testnet".to_string())), expected_output ); } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/js_command_match/keys/mod.rs
src/js_command_match/keys/mod.rs
pub mod add; pub mod delete; pub mod list;
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/js_command_match/keys/add.rs
src/js_command_match/keys/add.rs
use crate::js_command_match::constants::{ CONTRACT_ID_ALIASES, DEFAULT_SEED_PHRASE_PATH, LEDGER_PATH_ALIASES, METHOD_NAMES_ALIASES, NETWORK_ID_ALIASES, SIGN_WITH_LEDGER_ALIASES, }; #[derive(Debug, Clone, clap::Parser)] pub struct AddKeyArgs { account_id: String, public_key: String, #[clap(long, aliases = CONTRACT_ID_ALIASES)] contract_id: Option<String>, #[clap(long, aliases = METHOD_NAMES_ALIASES, requires = "contract_id", default_value="", value_delimiter = ',', num_args = 0..)] method_names: Vec<String>, #[clap(long, default_value = "0")] allowance: String, #[clap(long, aliases = SIGN_WITH_LEDGER_ALIASES, default_value_t = false)] sign_with_ledger: bool, #[clap(long, aliases = LEDGER_PATH_ALIASES, default_value = DEFAULT_SEED_PHRASE_PATH)] ledger_path: String, #[clap(long, aliases = NETWORK_ID_ALIASES)] network_id: Option<String>, } impl AddKeyArgs { pub fn to_cli_args(&self, network_config: String) -> Vec<String> { let network_id = self.network_id.clone().unwrap_or(network_config); let mut command = vec![ "account".to_string(), "add-key".to_string(), self.account_id.to_owned(), ]; if let Some(contract_id) = &self.contract_id { let allowance = if self.allowance != "0" { format!("{} NEAR", self.allowance) } else { "unlimited".to_string() }; command.push("grant-function-call-access".to_string()); command.push("--allowance".to_string()); command.push(allowance); command.push("--contract-account-id".to_string()); command.push(contract_id.to_string()); command.push("--function-names".to_string()); command.push(self.method_names.join(",")); } else { command.push("grant-full-access".to_string()); } command.push("use-manually-provided-public-key".to_string()); command.push(self.public_key.to_owned()); command.push("network-config".to_string()); command.push(network_id); if self.sign_with_ledger { command.push("sign-with-ledger".to_string()); command.push("--seed-phrase-hd-path".to_string()); command.push(self.ledger_path.to_owned()); } else { command.push("sign-with-keychain".to_string()); } command.push("send".to_string()); command } } #[cfg(test)] mod tests { use super::super::super::JsCmd; use super::*; use clap::Parser; #[test] fn add_key() { for (input, expected_output) in [ ( format!("near add-key bob.testnet ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq --{} contract.testnet", CONTRACT_ID_ALIASES[0]), "account add-key bob.testnet grant-function-call-access --allowance unlimited --contract-account-id contract.testnet --function-names '' use-manually-provided-public-key ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq network-config testnet sign-with-keychain send" ), ( format!("near add-key bob.testnet ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq --{} contract.testnet", CONTRACT_ID_ALIASES[1]), "account add-key bob.testnet grant-function-call-access --allowance unlimited --contract-account-id contract.testnet --function-names '' use-manually-provided-public-key ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq network-config testnet sign-with-keychain send" ), ( format!("near add-key bob.testnet ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq --contractId contract.testnet --{} get,set", METHOD_NAMES_ALIASES[0]), "account add-key bob.testnet grant-function-call-access --allowance unlimited --contract-account-id contract.testnet --function-names get,set use-manually-provided-public-key ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq network-config testnet sign-with-keychain send" ), ( format!("near add-key bob.testnet ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq --contractId contract.testnet --{} get,set", METHOD_NAMES_ALIASES[1]), "account add-key bob.testnet grant-function-call-access --allowance unlimited --contract-account-id contract.testnet --function-names get,set use-manually-provided-public-key ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq network-config testnet sign-with-keychain send" ), ( format!("near add-key bob.testnet ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq --contractId contract.testnet --{}", SIGN_WITH_LEDGER_ALIASES[0]), "account add-key bob.testnet grant-function-call-access --allowance unlimited --contract-account-id contract.testnet --function-names '' use-manually-provided-public-key ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' send" ), ( format!("near add-key bob.testnet ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq --contractId contract.testnet --{}", SIGN_WITH_LEDGER_ALIASES[1]), "account add-key bob.testnet grant-function-call-access --allowance unlimited --contract-account-id contract.testnet --function-names '' use-manually-provided-public-key ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' send" ), ( format!("near add-key bob.testnet ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq --contractId contract.testnet --{}", SIGN_WITH_LEDGER_ALIASES[2]), "account add-key bob.testnet grant-function-call-access --allowance unlimited --contract-account-id contract.testnet --function-names '' use-manually-provided-public-key ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' send" ), ( format!("near add-key bob.testnet ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq --contractId contract.testnet --{}", SIGN_WITH_LEDGER_ALIASES[3]), "account add-key bob.testnet grant-function-call-access --allowance unlimited --contract-account-id contract.testnet --function-names '' use-manually-provided-public-key ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' send" ), ( format!("near add-key bob.testnet ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq --contractId contract.testnet --signWithLedger --{} \"44'/397'/0'/0'/2'\"", LEDGER_PATH_ALIASES[0]), "account add-key bob.testnet grant-function-call-access --allowance unlimited --contract-account-id contract.testnet --function-names '' use-manually-provided-public-key ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/2'\\''' send" ), ( format!("near add-key bob.testnet ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq --contractId contract.testnet --signWithLedger --{} \"44'/397'/0'/0'/2'\"", LEDGER_PATH_ALIASES[1]), "account add-key bob.testnet grant-function-call-access --allowance unlimited --contract-account-id contract.testnet --function-names '' use-manually-provided-public-key ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/2'\\''' send" ), ( format!("near add-key bob.testnet ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq --{} testnet", NETWORK_ID_ALIASES[0]), "account add-key bob.testnet grant-full-access use-manually-provided-public-key ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq network-config testnet sign-with-keychain send" ), ( format!("near add-key bob.testnet ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq --{} mainnet", NETWORK_ID_ALIASES[1]), "account add-key bob.testnet grant-full-access use-manually-provided-public-key ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq network-config mainnet sign-with-keychain send" ), ] { let input_cmd = shell_words::split(&input).expect("Input command must be a valid shell command"); let JsCmd::AddKey(add_key_args) = JsCmd::parse_from(&input_cmd) else { panic!("AddKey command was expected, but something else was parsed out from {input}"); }; assert_eq!( shell_words::join(AddKeyArgs::to_cli_args(&add_key_args, "testnet".to_string())), expected_output ); } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/js_command_match/keys/delete.rs
src/js_command_match/keys/delete.rs
use crate::js_command_match::constants::{ DEFAULT_SEED_PHRASE_PATH, LEDGER_PATH_ALIASES, NETWORK_ID_ALIASES, SIGN_WITH_LEDGER_ALIASES, }; #[derive(Debug, Clone, clap::Parser)] /// This is a legacy `delete-key` command. Once you run it with the specified arguments, new syntax command will be suggested. pub struct DeleteKeyArgs { account_id: String, access_key: String, #[clap(long, aliases = SIGN_WITH_LEDGER_ALIASES, default_value_t = false)] sign_with_ledger: bool, #[clap(long, aliases = LEDGER_PATH_ALIASES, default_value = DEFAULT_SEED_PHRASE_PATH)] ledger_path: String, #[clap(long, aliases = NETWORK_ID_ALIASES)] network_id: Option<String>, } impl DeleteKeyArgs { pub fn to_cli_args(&self, network_config: String) -> Vec<String> { let network_id = self.network_id.clone().unwrap_or(network_config); let mut command = vec![ "account".to_string(), "delete-keys".to_string(), self.account_id.to_owned(), "public-keys".to_string(), self.access_key.to_owned(), "network-config".to_string(), network_id, ]; if self.sign_with_ledger { command.push("sign-with-ledger".to_string()); command.push("--seed-phrase-hd-path".to_string()); command.push(self.ledger_path.to_owned()); } else { command.push("sign-with-keychain".to_string()); } command.push("send".to_string()); command } } #[cfg(test)] mod tests { use super::super::super::JsCmd; use super::*; use clap::Parser; #[test] fn delete_key() { for (input, expected_output) in [ ( "near delete-key bob.testnet ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq".to_string(), "account delete-keys bob.testnet public-keys ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq network-config testnet sign-with-keychain send".to_string() ), ( format!("near delete-key bob.testnet ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq --{}", SIGN_WITH_LEDGER_ALIASES[0]), "account delete-keys bob.testnet public-keys ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' send".to_string() ), ( format!("near delete-key bob.testnet ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq --{}", SIGN_WITH_LEDGER_ALIASES[1]), "account delete-keys bob.testnet public-keys ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' send".to_string() ), ( format!("near delete-key bob.testnet ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq --{}", SIGN_WITH_LEDGER_ALIASES[2]), "account delete-keys bob.testnet public-keys ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' send".to_string() ), ( format!("near delete-key bob.testnet ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq --{}", SIGN_WITH_LEDGER_ALIASES[3]), "account delete-keys bob.testnet public-keys ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' send".to_string() ), ( format!("near delete-key bob.testnet ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq --signWithLedger --{} \"44'/397'/0'/0'/2'\"", LEDGER_PATH_ALIASES[0]), "account delete-keys bob.testnet public-keys ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/2'\\''' send".to_string() ), ( format!("near delete-key bob.testnet ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq --signWithLedger --{} \"44'/397'/0'/0'/2'\"", LEDGER_PATH_ALIASES[1]), "account delete-keys bob.testnet public-keys ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/2'\\''' send".to_string() ), ( format!("near delete-key bob.testnet ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq --{} testnet", NETWORK_ID_ALIASES[0]), "account delete-keys bob.testnet public-keys ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq network-config testnet sign-with-keychain send".to_string() ), ( format!("near delete-key bob.testnet ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq --{} mainnet", NETWORK_ID_ALIASES[1]), "account delete-keys bob.testnet public-keys ed25519:DReZmNmnGhpsYcCFFeYgPsJ9YCm9xH16GGujCPe3KQEq network-config mainnet sign-with-keychain send".to_string() ), ] { let input_cmd = shell_words::split(&input).expect("Input command must be a valid shell command"); let JsCmd::DeleteKey(delete_key_args) = JsCmd::parse_from(&input_cmd) else { panic!("DeleteKey command was expected, but something else was parsed out from {input}"); }; assert_eq!( shell_words::join(DeleteKeyArgs::to_cli_args(&delete_key_args, "testnet".to_string())), expected_output ); } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/js_command_match/contract/call.rs
src/js_command_match/contract/call.rs
use near_gas::NearGas; use crate::js_command_match::constants::{ DEFAULT_SEED_PHRASE_PATH, LEDGER_PATH_ALIASES, NETWORK_ID_ALIASES, SIGN_WITH_LEDGER_ALIASES, USE_ACCOUNT_ALIASES, }; #[derive(Debug, Clone, clap::Parser)] pub struct CallArgs { contract_name: String, method_name: String, #[clap(default_value = "{}")] args: String, #[clap(long, aliases = USE_ACCOUNT_ALIASES)] use_account: String, #[clap(long, aliases = SIGN_WITH_LEDGER_ALIASES, default_value_t = false)] sign_with_ledger: bool, #[clap(long, aliases = LEDGER_PATH_ALIASES, default_value = DEFAULT_SEED_PHRASE_PATH)] ledger_path: String, #[clap(long, default_value_t = 30_000_000_000_000)] gas: u64, #[clap(long, default_value = "0")] deposit: String, #[clap(long, default_value = "0", conflicts_with = "deposit", aliases = ["depositYocto"])] deposit_yocto: String, #[clap(long, default_value_t = false)] base64: bool, #[clap(long, aliases = ["privateKey"])] private_key: Option<String>, #[clap(long, aliases = NETWORK_ID_ALIASES)] network_id: Option<String>, } impl CallArgs { pub fn to_cli_args(&self, network_config: String) -> Vec<String> { let network_id = self.network_id.clone().unwrap_or(network_config); let mut command = vec![ "contract".to_string(), "call-function".to_string(), "as-transaction".to_string(), self.contract_name.to_owned(), self.method_name.to_owned(), ]; if self.base64 { command.push("base64-args".to_string()); } else { command.push("json-args".to_string()); }; command.push(self.args.to_owned()); command.push("prepaid-gas".to_string()); command.push(format!("{} Tgas", NearGas::from_gas(self.gas).as_tgas())); command.push("attached-deposit".to_string()); if self.deposit_yocto != "0" { command.push(format!("{} yoctonear", self.deposit_yocto)); } else { command.push(format!("{} NEAR", self.deposit)); } command.push("sign-as".to_string()); command.push(self.use_account.to_owned()); command.push("network-config".to_string()); command.push(network_id); if self.sign_with_ledger { command.push("sign-with-ledger".to_string()); command.push("--seed-phrase-hd-path".to_string()); command.push(self.ledger_path.to_owned()); } else if let Some(private_key) = &self.private_key { command.push("sign-with-plaintext-private-key".to_string()); command.push(private_key.to_string()); } else { command.push("sign-with-keychain".to_string()); } command.push("send".to_string()); command } } #[cfg(test)] mod tests { use super::super::super::JsCmd; use super::*; use clap::Parser; #[test] fn call() { let json_args = "{\"player_guess\": \"tail\"}"; let base64_args = "eyJwbGF5ZXJfZ3Vlc3MiOiAidGFpbCJ9"; for (input, expected_output) in [ ( format!("near call contract.testnet flip_coin '{json_args}' --{} bob.testnet", USE_ACCOUNT_ALIASES[0]), format!("contract call-function as-transaction contract.testnet flip_coin json-args '{json_args}' prepaid-gas '30 Tgas' attached-deposit '0 NEAR' sign-as bob.testnet network-config testnet sign-with-keychain send") ), ( format!("near call contract.testnet flip_coin '{json_args}' --{} bob.testnet", USE_ACCOUNT_ALIASES[1]), format!("contract call-function as-transaction contract.testnet flip_coin json-args '{json_args}' prepaid-gas '30 Tgas' attached-deposit '0 NEAR' sign-as bob.testnet network-config testnet sign-with-keychain send") ), ( format!("near call contract.testnet flip_coin '{json_args}' --{} bob.testnet", USE_ACCOUNT_ALIASES[2]), format!("contract call-function as-transaction contract.testnet flip_coin json-args '{json_args}' prepaid-gas '30 Tgas' attached-deposit '0 NEAR' sign-as bob.testnet network-config testnet sign-with-keychain send") ), ( format!("near call contract.testnet flip_coin '{json_args}' --{} bob.testnet", USE_ACCOUNT_ALIASES[3]), format!("contract call-function as-transaction contract.testnet flip_coin json-args '{json_args}' prepaid-gas '30 Tgas' attached-deposit '0 NEAR' sign-as bob.testnet network-config testnet sign-with-keychain send") ), ( format!("near call contract.testnet flip_coin '{json_args}' --{} bob.testnet", USE_ACCOUNT_ALIASES[4]), format!("contract call-function as-transaction contract.testnet flip_coin json-args '{json_args}' prepaid-gas '30 Tgas' attached-deposit '0 NEAR' sign-as bob.testnet network-config testnet sign-with-keychain send") ), ( format!("near call contract.testnet flip_coin '{json_args}' --{} bob.testnet", USE_ACCOUNT_ALIASES[5]), format!("contract call-function as-transaction contract.testnet flip_coin json-args '{json_args}' prepaid-gas '30 Tgas' attached-deposit '0 NEAR' sign-as bob.testnet network-config testnet sign-with-keychain send") ), ( format!("near call contract.testnet flip_coin {base64_args} --useAccount bob.testnet --base64"), format!("contract call-function as-transaction contract.testnet flip_coin base64-args {base64_args} prepaid-gas '30 Tgas' attached-deposit '0 NEAR' sign-as bob.testnet network-config testnet sign-with-keychain send") ), ( format!("near call contract.testnet flip_coin '{json_args}' --useAccount bob.testnet --{}", SIGN_WITH_LEDGER_ALIASES[0]), format!("contract call-function as-transaction contract.testnet flip_coin json-args '{json_args}' prepaid-gas '30 Tgas' attached-deposit '0 NEAR' sign-as bob.testnet network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' send") ), ( format!("near call contract.testnet flip_coin '{json_args}' --useAccount bob.testnet --{}", SIGN_WITH_LEDGER_ALIASES[1]), format!("contract call-function as-transaction contract.testnet flip_coin json-args '{json_args}' prepaid-gas '30 Tgas' attached-deposit '0 NEAR' sign-as bob.testnet network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' send") ), ( format!("near call contract.testnet flip_coin '{json_args}' --useAccount bob.testnet --{}", SIGN_WITH_LEDGER_ALIASES[2]), format!("contract call-function as-transaction contract.testnet flip_coin json-args '{json_args}' prepaid-gas '30 Tgas' attached-deposit '0 NEAR' sign-as bob.testnet network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' send") ), ( format!("near call contract.testnet flip_coin '{json_args}' --useAccount bob.testnet --{}", SIGN_WITH_LEDGER_ALIASES[3]), format!("contract call-function as-transaction contract.testnet flip_coin json-args '{json_args}' prepaid-gas '30 Tgas' attached-deposit '0 NEAR' sign-as bob.testnet network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/1'\\''' send") ), ( format!("near call contract.testnet flip_coin '{json_args}' --useAccount bob.testnet --signWithLedger --{} \"44'/397'/0'/0'/2'\"", LEDGER_PATH_ALIASES[0]), format!("contract call-function as-transaction contract.testnet flip_coin json-args '{json_args}' prepaid-gas '30 Tgas' attached-deposit '0 NEAR' sign-as bob.testnet network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/2'\\''' send") ), ( format!("near call contract.testnet flip_coin '{json_args}' --useAccount bob.testnet --signWithLedger --{} \"44'/397'/0'/0'/2'\"", LEDGER_PATH_ALIASES[1]), format!("contract call-function as-transaction contract.testnet flip_coin json-args '{json_args}' prepaid-gas '30 Tgas' attached-deposit '0 NEAR' sign-as bob.testnet network-config testnet sign-with-ledger --seed-phrase-hd-path '44'\\''/397'\\''/0'\\''/0'\\''/2'\\''' send") ), ( format!("near call contract.testnet flip_coin '{json_args}' --useAccount bob.testnet --{} mainnet", NETWORK_ID_ALIASES[0]), format!("contract call-function as-transaction contract.testnet flip_coin json-args '{json_args}' prepaid-gas '30 Tgas' attached-deposit '0 NEAR' sign-as bob.testnet network-config mainnet sign-with-keychain send") ), ( format!("near call contract.testnet flip_coin '{json_args}' --useAccount bob.testnet --{} mainnet", NETWORK_ID_ALIASES[1]), format!("contract call-function as-transaction contract.testnet flip_coin json-args '{json_args}' prepaid-gas '30 Tgas' attached-deposit '0 NEAR' sign-as bob.testnet network-config mainnet sign-with-keychain send") ), ] { let input_cmd = shell_words::split(&input).expect("Input command must be a valid shell command"); let JsCmd::Call(call_args) = JsCmd::parse_from(&input_cmd) else { panic!("Call command was expected, but something else was parsed out from {input}"); }; assert_eq!( shell_words::join(CallArgs::to_cli_args(&call_args, "testnet".to_string())), expected_output ); } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/js_command_match/contract/view.rs
src/js_command_match/contract/view.rs
use crate::js_command_match::constants::NETWORK_ID_ALIASES; #[derive(Debug, Clone, clap::Parser)] /// This is a legacy `view` command. Once you run it with the specified arguments, new syntax command will be suggested. pub struct ViewArgs { contract_name: String, method_name: String, #[clap(default_value = "{}")] args: String, #[clap(long, aliases = NETWORK_ID_ALIASES)] network_id: Option<String>, } impl ViewArgs { pub fn to_cli_args(&self, network_config: String) -> Vec<String> { let network_id = self.network_id.clone().unwrap_or(network_config); let command = vec![ "contract".to_string(), "call-function".to_string(), "as-read-only".to_string(), self.contract_name.to_owned(), self.method_name.to_owned(), "json-args".to_string(), self.args.to_owned(), "network-config".to_string(), network_id, "now".to_string(), ]; command } } #[cfg(test)] mod tests { use super::super::super::JsCmd; use super::*; use clap::Parser; #[test] fn view() { let args = "{\"account_id\": \"bob.testnet\"}"; for (input, expected_output) in [ ( format!("near view counter.near-examples.testnet get '{args}'"), format!("contract call-function as-read-only counter.near-examples.testnet get json-args '{args}' network-config testnet now") ), ( format!("near view counter.near-examples.testnet get '{args}' --{} testnet", NETWORK_ID_ALIASES[0]), format!("contract call-function as-read-only counter.near-examples.testnet get json-args '{args}' network-config testnet now") ), ( format!("near view counter.near-examples.testnet get '{args}' --{} mainnet", NETWORK_ID_ALIASES[1]), format!("contract call-function as-read-only counter.near-examples.testnet get json-args '{args}' network-config mainnet now") ), ] { let input_cmd = shell_words::split(&input).expect("Input command must be a valid shell command"); let JsCmd::View(view_args) = JsCmd::parse_from(&input_cmd) else { panic!("View command was expected, but something else was parsed out from {input}"); }; assert_eq!( shell_words::join(ViewArgs::to_cli_args(&view_args, "testnet".to_string())), expected_output ); } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/js_command_match/contract/storage.rs
src/js_command_match/contract/storage.rs
use crate::js_command_match::constants::{BLOCK_ID_ALIASES, NETWORK_ID_ALIASES}; #[derive(Debug, Clone, clap::Parser)] pub struct ViewStateArgs { account_id: String, #[clap(long)] prefix: Option<String>, #[clap(long, default_value_t = false)] utf8: bool, #[clap(long, aliases = BLOCK_ID_ALIASES)] block_id: Option<String>, #[clap(long, conflicts_with = "block_id")] finality: Option<String>, #[clap(long, aliases = NETWORK_ID_ALIASES)] network_id: Option<String>, } impl ViewStateArgs { pub fn to_cli_args(&self, network_config: String) -> Vec<String> { let network_id = self.network_id.clone().unwrap_or(network_config); let mut command = vec![ "contract".to_string(), "view-storage".to_string(), self.account_id.to_owned(), ]; let output_format = if self.utf8 { "as-text" } else { "as-json" }; if let Some(prefix) = &self.prefix { let prefix_type = match near_primitives::serialize::from_base64(&prefix[..]) { Ok(_) => "keys-start-with-bytes-as-base64".to_string(), Err(_) => "keys-start-with-string".to_string(), }; command.push(prefix_type); command.push(prefix.to_string()); } else { command.push("all".to_string()); } command.push(output_format.to_owned()); command.push("network-config".to_string()); command.push(network_id); if self.finality.is_some() { command.push("now".to_string()); } else if let Some(block_id) = &self.block_id { match block_id.parse::<i32>() { Ok(_) => { command.push("at-block-height".to_string()); } Err(_) => { command.push("at-block-hash".to_string()); } } command.push(block_id.to_string()); } command } } #[cfg(test)] mod tests { use super::super::super::JsCmd; use super::*; use clap::Parser; #[test] fn view_state() { for (input, expected_output) in [ ( format!("near storage counter.near-examples.testnet --prefix U1RBVEU= --{} 167860267", BLOCK_ID_ALIASES[0]), "contract view-storage counter.near-examples.testnet keys-start-with-bytes-as-base64 'U1RBVEU=' as-json network-config testnet at-block-height 167860267" ), ( format!("near view-state counter.near-examples.testnet --prefix U1RBVEU= --{} 167860267", BLOCK_ID_ALIASES[0]), "contract view-storage counter.near-examples.testnet keys-start-with-bytes-as-base64 'U1RBVEU=' as-json network-config testnet at-block-height 167860267" ), ( format!("near view-state counter.near-examples.testnet --prefix U1RBVEU= --{} 167860267", BLOCK_ID_ALIASES[1]), "contract view-storage counter.near-examples.testnet keys-start-with-bytes-as-base64 'U1RBVEU=' as-json network-config testnet at-block-height 167860267" ), ( format!("near view-state counter.near-examples.testnet --prefix STATE --utf8 --finality final --{} mainnet", NETWORK_ID_ALIASES[0]), "contract view-storage counter.near-examples.testnet keys-start-with-string STATE as-text network-config mainnet now" ), ( format!("near view-state counter.near-examples.testnet --prefix STATE --utf8 --finality final --{} mainnet", NETWORK_ID_ALIASES[1]), "contract view-storage counter.near-examples.testnet keys-start-with-string STATE as-text network-config mainnet now" ), ] { let input_cmd = shell_words::split(&input).expect("Input command must be a valid shell command"); let JsCmd::ViewState(view_state_args) = JsCmd::parse_from(&input_cmd) else { panic!("ViewState command was expected, but something else was parsed out from {input}"); }; assert_eq!( shell_words::join(ViewStateArgs::to_cli_args(&view_state_args, "testnet".to_string())), expected_output ); } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/js_command_match/contract/deploy.rs
src/js_command_match/contract/deploy.rs
use near_gas::NearGas; use crate::js_command_match::constants::{ INIT_ARGS_ALIASES, INIT_DEPOSIT_ALIASES, INIT_FUNCTION_ALIASES, INIT_GAS_ALIASES, NETWORK_ID_ALIASES, WASM_FILE_ALIASES, }; #[derive(Debug, Clone, clap::Parser)] pub struct DeployArgs { account_id: String, #[clap(required_unless_present = "wasm_file")] wasm_file_path: Option<String>, #[clap(long, aliases = WASM_FILE_ALIASES )] wasm_file: Option<String>, #[clap(long, aliases = INIT_FUNCTION_ALIASES)] init_function: Option<String>, #[clap(long, aliases = INIT_ARGS_ALIASES, default_value = "{}")] init_args: String, #[clap(long, aliases = INIT_GAS_ALIASES, default_value_t = 30_000_000_000_000)] init_gas: u64, #[clap(long, aliases = INIT_DEPOSIT_ALIASES, default_value = "0")] init_deposit: String, #[clap(long, aliases = NETWORK_ID_ALIASES)] network_id: Option<String>, } impl DeployArgs { pub fn to_cli_args(&self, network_config: String) -> Vec<String> { let network_id = self.network_id.clone().unwrap_or(network_config); let mut command = vec!["contract".to_string(), "deploy".to_string()]; command.push(self.account_id.to_owned()); let wasm_file = self .wasm_file_path .to_owned() .or(self.wasm_file.to_owned()) .unwrap(); command.push("use-file".to_string()); command.push(wasm_file.to_owned()); if let Some(init_function) = &self.init_function { command.push("with-init-call".to_string()); command.push(init_function.to_string()); command.push("json-args".to_string()); command.push(self.init_args.to_owned()); command.push("prepaid-gas".to_string()); command.push(format!( "{} Tgas", NearGas::from_gas(self.init_gas).as_tgas() )); command.push("attached-deposit".to_string()); command.push(format!("{} NEAR", self.init_deposit)); } else { command.push("without-init-call".to_string()); } command.push("network-config".to_string()); command.push(network_id); command.push("sign-with-keychain".to_string()); command.push("send".to_owned()); command } } #[cfg(test)] mod tests { use super::super::super::JsCmd; use super::*; use clap::Parser; #[test] fn deploy() { let args = "{\"owner_id\":\"contract.testnet\",\"total_supply\":\"1000000\"}"; for (input, expected_output) in [ ( "near deploy contract.testnet build/hello_near.wasm".to_string(), "contract deploy contract.testnet use-file build/hello_near.wasm without-init-call network-config testnet sign-with-keychain send".to_string(), ), ( format!("near deploy contract.testnet --{} build/hello_near.wasm", WASM_FILE_ALIASES[0]), "contract deploy contract.testnet use-file build/hello_near.wasm without-init-call network-config testnet sign-with-keychain send".to_string(), ), ( format!("near deploy contract.testnet --{} build/hello_near.wasm", WASM_FILE_ALIASES[1]), "contract deploy contract.testnet use-file build/hello_near.wasm without-init-call network-config testnet sign-with-keychain send".to_string(), ), ( format!("near deploy contract.testnet build/hello_near.wasm --{} new --initArgs '{args}'", INIT_FUNCTION_ALIASES[0]), format!("contract deploy contract.testnet use-file build/hello_near.wasm with-init-call new json-args '{args}' prepaid-gas '30 Tgas' attached-deposit '0 NEAR' network-config testnet sign-with-keychain send") ), ( format!("near deploy contract.testnet build/hello_near.wasm --{} new --initArgs '{args}'", INIT_FUNCTION_ALIASES[1]), format!("contract deploy contract.testnet use-file build/hello_near.wasm with-init-call new json-args '{args}' prepaid-gas '30 Tgas' attached-deposit '0 NEAR' network-config testnet sign-with-keychain send") ), ( format!("near deploy contract.testnet build/hello_near.wasm --initFunction new --{} '{args}'", INIT_ARGS_ALIASES[0]), format!("contract deploy contract.testnet use-file build/hello_near.wasm with-init-call new json-args '{args}' prepaid-gas '30 Tgas' attached-deposit '0 NEAR' network-config testnet sign-with-keychain send") ), ( format!("near deploy contract.testnet build/hello_near.wasm --initFunction new --{} '{args}'", INIT_ARGS_ALIASES[1]), format!("contract deploy contract.testnet use-file build/hello_near.wasm with-init-call new json-args '{args}' prepaid-gas '30 Tgas' attached-deposit '0 NEAR' network-config testnet sign-with-keychain send") ), ( format!("near deploy contract.testnet build/hello_near.wasm --initFunction new --initArgs '{args}' --{} 60000000000000", INIT_GAS_ALIASES[0]), format!("contract deploy contract.testnet use-file build/hello_near.wasm with-init-call new json-args '{args}' prepaid-gas '60 Tgas' attached-deposit '0 NEAR' network-config testnet sign-with-keychain send") ), ( format!("near deploy contract.testnet build/hello_near.wasm --initFunction new --initArgs '{args}' --{} 60000000000000", INIT_GAS_ALIASES[1]), format!("contract deploy contract.testnet use-file build/hello_near.wasm with-init-call new json-args '{args}' prepaid-gas '60 Tgas' attached-deposit '0 NEAR' network-config testnet sign-with-keychain send") ), ( format!("near deploy contract.testnet build/hello_near.wasm --initFunction new --initArgs '{args}' --initGas 60000000000000 --{} 1", INIT_DEPOSIT_ALIASES[0]), format!("contract deploy contract.testnet use-file build/hello_near.wasm with-init-call new json-args '{args}' prepaid-gas '60 Tgas' attached-deposit '1 NEAR' network-config testnet sign-with-keychain send") ), ( format!("near deploy contract.testnet build/hello_near.wasm --initFunction new --initArgs '{args}' --initGas 60000000000000 --{} 1", INIT_DEPOSIT_ALIASES[1]), format!("contract deploy contract.testnet use-file build/hello_near.wasm with-init-call new json-args '{args}' prepaid-gas '60 Tgas' attached-deposit '1 NEAR' network-config testnet sign-with-keychain send") ), ( format!("near deploy contract.testnet build/hello_near.wasm --{} testnet", NETWORK_ID_ALIASES[0]), "contract deploy contract.testnet use-file build/hello_near.wasm without-init-call network-config testnet sign-with-keychain send".to_string(), ), ( format!("near deploy contract.testnet build/hello_near.wasm --{} mainnet", NETWORK_ID_ALIASES[1]), "contract deploy contract.testnet use-file build/hello_near.wasm without-init-call network-config mainnet sign-with-keychain send".to_string(), ), ] { let input_cmd = shell_words::split(&input).expect("Input command must be a valid shell command"); let JsCmd::Deploy(deploy_args) = JsCmd::parse_from(&input_cmd) else { panic!("Deploy command was expected, but something else was parsed out from {input}"); }; assert_eq!( shell_words::join(DeployArgs::to_cli_args(&deploy_args, "testnet".to_string())), expected_output ); } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/js_command_match/contract/mod.rs
src/js_command_match/contract/mod.rs
pub mod call; pub mod deploy; pub mod storage; pub mod view;
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/mod.rs
src/commands/mod.rs
#![allow(clippy::enum_variant_names, clippy::large_enum_variant)] use strum::{EnumDiscriminants, EnumIter, EnumMessage}; pub mod account; mod config; pub mod contract; pub mod message; mod staking; mod tokens; pub mod transaction; #[cfg(feature = "self-update")] pub mod extensions; #[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = crate::GlobalContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] #[interactive_clap(disable_back)] #[non_exhaustive] /// What are you up to? (select one of the options with the up-down arrows on your keyboard and press Enter) pub enum TopLevelCommand { #[strum_discriminants(strum(message = "account - Manage accounts"))] /// View account summary, create subaccount, delete account, list keys, add key, delete key, import account Account(self::account::AccountCommands), #[strum_discriminants(strum( message = "tokens - Manage token assets such as NEAR, FT, NFT" ))] /// Use this for token actions: send or view balances of NEAR, FT, or NFT Tokens(self::tokens::TokensCommands), #[strum_discriminants(strum( message = "staking - Manage staking: view, add and withdraw stake" ))] /// Use this for manage staking: view, add and withdraw stake Staking(self::staking::Staking), #[strum_discriminants(strum( message = "contract - Manage smart-contracts: deploy code, call functions" ))] /// Use this for contract actions: call function, deploy, download wasm, inspect storage Contract(self::contract::ContractCommands), #[strum_discriminants(strum(message = "transaction - Operate transactions"))] /// Use this to construct transactions or view a transaction status. Transaction(self::transaction::TransactionCommands), #[strum_discriminants(strum(message = "message - Sign an arbitrary message (NEP-413)"))] /// Sign an arbitrary message (NEP-413) Message(self::message::MessageCommand), #[strum_discriminants(strum( message = "config - Manage connections in a configuration file (config.toml)" ))] /// Use this to manage connections in a configuration file (config.toml). Config(self::config::ConfigCommands), #[cfg(feature = "self-update")] #[strum_discriminants(strum(message = "extension - Manage near CLI and extensions"))] /// Use this to manage near CLI and extensions Extensions(self::extensions::ExtensionsCommands), } pub type OnBeforeSigningCallback = std::sync::Arc< dyn Fn( &mut near_primitives::transaction::TransactionV0, &crate::config::NetworkConfig, ) -> crate::CliResult, >; pub type OnAfterSigningCallback = std::sync::Arc< dyn Fn( &mut near_primitives::transaction::SignedTransaction, &crate::config::NetworkConfig, ) -> crate::CliResult, >; pub type GetPrepopulatedTransactionAfterGettingNetworkCallback = std::sync::Arc< dyn Fn(&crate::config::NetworkConfig) -> color_eyre::eyre::Result<PrepopulatedTransaction>, >; #[derive(Debug, Clone)] pub struct PrepopulatedTransaction { pub signer_id: near_primitives::types::AccountId, pub receiver_id: near_primitives::types::AccountId, pub actions: Vec<near_primitives::transaction::Action>, } impl From<near_primitives::transaction::TransactionV0> for PrepopulatedTransaction { fn from(value: near_primitives::transaction::TransactionV0) -> Self { Self { signer_id: value.signer_id, receiver_id: value.receiver_id, actions: value.actions, } } } impl From<near_primitives::transaction::Transaction> for PrepopulatedTransaction { fn from(value: near_primitives::transaction::Transaction) -> Self { Self { signer_id: value.signer_id().clone(), receiver_id: value.receiver_id().clone(), actions: value.take_actions(), } } } #[derive(Clone)] pub struct ActionContext { pub global_context: crate::GlobalContext, pub interacting_with_account_ids: Vec<near_primitives::types::AccountId>, pub get_prepopulated_transaction_after_getting_network_callback: GetPrepopulatedTransactionAfterGettingNetworkCallback, pub on_before_signing_callback: OnBeforeSigningCallback, pub on_before_sending_transaction_callback: crate::transaction_signature_options::OnBeforeSendingTransactionCallback, pub on_after_sending_transaction_callback: crate::transaction_signature_options::OnAfterSendingTransactionCallback, } #[derive(Clone)] pub struct TransactionContext { pub global_context: crate::GlobalContext, pub network_config: crate::config::NetworkConfig, pub prepopulated_transaction: PrepopulatedTransaction, pub on_before_signing_callback: OnBeforeSigningCallback, pub on_after_signing_callback: OnAfterSigningCallback, pub on_before_sending_transaction_callback: crate::transaction_signature_options::OnBeforeSendingTransactionCallback, pub on_after_sending_transaction_callback: crate::transaction_signature_options::OnAfterSendingTransactionCallback, }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/mod.rs
src/commands/transaction/mod.rs
#![allow(clippy::enum_variant_names, clippy::large_enum_variant)] use strum::{EnumDiscriminants, EnumIter, EnumMessage}; pub mod construct_transaction; mod print_transaction; mod reconstruct_transaction; pub mod send_meta_transaction; pub mod send_signed_transaction; pub mod sign_transaction; mod view_status; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = crate::GlobalContext)] pub struct TransactionCommands { #[interactive_clap(subcommand)] transaction_actions: TransactionActions, } #[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = crate::GlobalContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] #[non_exhaustive] /// Сhoose action for transaction: pub enum TransactionActions { #[strum_discriminants(strum( message = "view-status - View a transaction status" ))] /// Execute function (contract method) ViewStatus(self::view_status::TransactionInfo), #[strum_discriminants(strum( message = "reconstruct-transaction - Use any existing transaction from the chain to construct NEAR CLI command (helpful tool for re-submitting similar transactions)" ))] /// Use any existing transaction from the chain to construct NEAR CLI command (helpful tool for re-submitting similar transactions) ReconstructTransaction(self::reconstruct_transaction::TransactionInfo), #[strum_discriminants(strum( message = "construct-transaction - Construct a new transaction" ))] /// Construct a new transaction ConstructTransaction(self::construct_transaction::ConstructTransaction), #[strum_discriminants(strum( message = "sign-transaction - Sign previously prepared unsigned transaction" ))] /// Sign previously prepared unsigned transaction SignTransaction(self::sign_transaction::SignTransaction), #[strum_discriminants(strum( message = "print-transaction - Print all fields of previously prepared transaction without modification" ))] /// Print previously prepared unsigned transaction without modification PrintTransaction(self::print_transaction::PrintTransactionCommands), #[strum_discriminants(strum( message = "send-signed-transaction - Send a signed transaction" ))] /// Send a signed transaction SendSignedTransaction(self::send_signed_transaction::SignedTransaction), #[strum_discriminants(strum( message = "send-meta-transaction - Act as a relayer to send a signed delegate action (meta-transaction)" ))] /// Act as a relayer to send a signed delegate action (meta-transaction) SendMetaTransaction(self::send_meta_transaction::SignedMetaTransaction), }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/send_signed_transaction/mod.rs
src/commands/transaction/send_signed_transaction/mod.rs
use color_eyre::eyre::WrapErr; use strum::{EnumDiscriminants, EnumIter, EnumMessage}; mod network; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = crate::GlobalContext)] pub struct SignedTransaction { #[interactive_clap(subcommand)] /// Select the base64 signed transaction input method signed_transaction_type: SignedTransactionType, } #[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = crate::GlobalContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Select the Base64 signed transaction input method: pub enum SignedTransactionType { #[strum_discriminants(strum( message = "base64-signed-transaction - Base64-encoded string (e.g. e30=)" ))] /// Base64-encoded string (e.g. e30=) Base64SignedTransaction(Base64SignedTransaction), #[strum_discriminants(strum( message = "file-with-base64-signed-transaction - Read base64-encoded string from file (e.g. reusable JSON or binary data)" ))] /// Read base64-encoded string from file (e.g. reusable JSON or binary data) FileWithBase64SignedTransaction(FileWithBase64SignedTransaction), } #[derive(Debug, Clone)] pub struct SignedTransactionContext { global_context: crate::GlobalContext, signed_transaction: near_primitives::transaction::SignedTransaction, } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = Base64SignedTransactionContext)] pub struct Base64SignedTransaction { /// Enter a signed transaction as base64-encoded string: signed_action: crate::types::signed_transaction::SignedTransactionAsBase64, #[interactive_clap(named_arg)] /// Select network network_config: self::network::Network, } #[derive(Debug, Clone)] pub struct Base64SignedTransactionContext(SignedTransactionContext); impl Base64SignedTransactionContext { pub fn from_previous_context( previous_context: crate::GlobalContext, scope: &<Base64SignedTransaction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self(SignedTransactionContext { global_context: previous_context, signed_transaction: scope.signed_action.inner.clone(), })) } } impl From<Base64SignedTransactionContext> for SignedTransactionContext { fn from(item: Base64SignedTransactionContext) -> Self { item.0 } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = FileWithBase64SignedTransactionContext)] pub struct FileWithBase64SignedTransaction { /// Enter the path to the file with the transaction as a string in base64 encoding: file_path: crate::types::path_buf::PathBuf, #[interactive_clap(named_arg)] /// Select network network_config: self::network::Network, } #[derive(Debug, Clone)] pub struct FileWithBase64SignedTransactionContext(SignedTransactionContext); #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct FileSignedTransaction { #[serde(rename = "signed_transaction_as_base64")] pub signed_transaction: near_primitives::transaction::SignedTransaction, } impl FileWithBase64SignedTransactionContext { pub fn from_previous_context( previous_context: crate::GlobalContext, scope: &<FileWithBase64SignedTransaction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let data = std::fs::read_to_string(&scope.file_path) .wrap_err_with(|| format!("File {:?} not found!", &scope.file_path))?; let signed_transaction = serde_json::from_str::<FileSignedTransaction>(&data) .wrap_err_with(|| format!("Error reading data from file: {:?}", &scope.file_path))? .signed_transaction; Ok(Self(SignedTransactionContext { global_context: previous_context, signed_transaction, })) } } impl From<FileWithBase64SignedTransactionContext> for SignedTransactionContext { fn from(item: FileWithBase64SignedTransactionContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/send_signed_transaction/network/mod.rs
src/commands/transaction/send_signed_transaction/network/mod.rs
use color_eyre::eyre::ContextCompat; use strum::{EnumDiscriminants, EnumIter, EnumMessage}; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::SignedTransactionContext)] #[interactive_clap(output_context = NetworkContext)] pub struct Network { /// What is the name of the network? #[interactive_clap(skip_default_input_arg)] network_name: String, #[interactive_clap(subcommand)] pub submit: Submit, } #[derive(Debug, Clone)] pub struct NetworkContext { global_context: crate::GlobalContext, signed_transaction: near_primitives::transaction::SignedTransaction, network_config: crate::config::NetworkConfig, } impl NetworkContext { pub fn from_previous_context( previous_context: super::SignedTransactionContext, scope: &<Network as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let network_config = previous_context .global_context .config .network_connection .get(&scope.network_name) .wrap_err("Failed to get network config!")? .clone(); Ok(Self { global_context: previous_context.global_context, signed_transaction: previous_context.signed_transaction, network_config, }) } } impl Network { fn input_network_name( context: &super::SignedTransactionContext, ) -> color_eyre::eyre::Result<Option<String>> { crate::common::input_network_name( &context.global_context.config, &[context.signed_transaction.transaction.receiver_id().clone()], ) } } #[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = NetworkContext)] #[interactive_clap(output_context = SubmitContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// How would you like to proceed? pub enum Submit { #[strum_discriminants(strum(message = "send - Send the transaction to the network"))] Send, } #[derive(Debug, Clone)] pub struct SubmitContext; impl SubmitContext { #[tracing::instrument(name = "Sending transaction ...", skip_all)] pub fn from_previous_context( previous_context: NetworkContext, _scope: &<Submit as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> crate::CliResult { tracing::info!(target: "near_teach_me", "Sending transaction ..."); let transaction_info = crate::transaction_signature_options::send::sending_signed_transaction( &previous_context.network_config, &previous_context.signed_transaction, )?; crate::common::print_transaction_status( &transaction_info, &previous_context.network_config, previous_context.global_context.verbosity, ) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/send_meta_transaction/mod.rs
src/commands/transaction/send_meta_transaction/mod.rs
use color_eyre::eyre::WrapErr; use strum::{EnumDiscriminants, EnumIter, EnumMessage}; mod sign_as; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = crate::GlobalContext)] pub struct SignedMetaTransaction { #[interactive_clap(subcommand)] /// Select the base64 signed meta-transaction input method signed_meta_transaction_type: SignedMetaTransactionType, } #[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = crate::GlobalContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Select the Base64 signed meta-transaction input method: pub enum SignedMetaTransactionType { #[strum_discriminants(strum( message = "base64-signed-meta-transaction - Base64-encoded string (e.g. e30=)" ))] /// Base64-encoded string (e.g. e30=) Base64SignedMetaTransaction(Base64SignedMetaTransaction), #[strum_discriminants(strum( message = "file-with-base64-signed-meta-transaction - Read base64-encoded string from file (e.g. reusable JSON or binary data)" ))] /// Read base64-encoded string from file (e.g. reusable JSON or binary data) FileWithBase64SignedMetaTransaction(FileWithBase64SignedMetaTransaction), } #[derive(Debug, Clone)] pub struct SignedMetaTransactionContext { global_context: crate::GlobalContext, signed_delegate_action: near_primitives::action::delegate::SignedDelegateAction, } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = Base64SignedMetaTransactionContext)] pub struct Base64SignedMetaTransaction { /// Enter a signed delegate action as base64-encoded string: signed_delegate_action: crate::types::signed_delegate_action::SignedDelegateActionAsBase64, #[interactive_clap(named_arg)] /// What is the relayer account ID? sign_as: self::sign_as::RelayerAccountId, } #[derive(Debug, Clone)] pub struct Base64SignedMetaTransactionContext(SignedMetaTransactionContext); impl Base64SignedMetaTransactionContext { pub fn from_previous_context( previous_context: crate::GlobalContext, scope: &<Base64SignedMetaTransaction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self(SignedMetaTransactionContext { global_context: previous_context, signed_delegate_action: scope.signed_delegate_action.clone().into(), })) } } impl From<Base64SignedMetaTransactionContext> for SignedMetaTransactionContext { fn from(item: Base64SignedMetaTransactionContext) -> Self { item.0 } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = FileWithBase64SignedMetaTransactionContext)] pub struct FileWithBase64SignedMetaTransaction { /// Enter the path to the file with the meta-transaction as a string in base64 encoding: file_path: crate::types::path_buf::PathBuf, #[interactive_clap(named_arg)] /// What is the relayer account ID? sign_as: self::sign_as::RelayerAccountId, } #[derive(Debug, Clone)] pub struct FileWithBase64SignedMetaTransactionContext(SignedMetaTransactionContext); #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct FileSignedMetaTransaction { #[serde(rename = "signed_delegate_action_as_base64")] pub signed_delegate_action: crate::types::signed_delegate_action::SignedDelegateActionAsBase64, } impl FileWithBase64SignedMetaTransactionContext { pub fn from_previous_context( previous_context: crate::GlobalContext, scope: &<FileWithBase64SignedMetaTransaction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let data = std::fs::read_to_string(&scope.file_path) .wrap_err_with(|| format!("File {:?} not found!", &scope.file_path))?; let signed_delegate_action = serde_json::from_str::<FileSignedMetaTransaction>(&data) .wrap_err_with(|| format!("Error reading data from file: {:?}", &scope.file_path))? .signed_delegate_action; Ok(Self(SignedMetaTransactionContext { global_context: previous_context, signed_delegate_action: signed_delegate_action.into(), })) } } impl From<FileWithBase64SignedMetaTransactionContext> for SignedMetaTransactionContext { fn from(item: FileWithBase64SignedMetaTransactionContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/send_meta_transaction/sign_as/mod.rs
src/commands/transaction/send_meta_transaction/sign_as/mod.rs
use inquire::Select; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::SignedMetaTransactionContext)] #[interactive_clap(output_context = RelayerAccountIdContext)] pub struct RelayerAccountId { #[interactive_clap(skip_default_input_arg)] /// What is the relayer account ID? relayer_account_id: crate::types::account_id::AccountId, #[interactive_clap(named_arg)] /// Select network network_config: crate::network_for_transaction::NetworkForTransactionArgs, } #[derive(Clone)] pub struct RelayerAccountIdContext(crate::commands::ActionContext); impl RelayerAccountIdContext { pub fn from_previous_context( previous_context: super::SignedMetaTransactionContext, scope: &<RelayerAccountId as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let get_prepopulated_transaction_after_getting_network_callback: crate::commands::GetPrepopulatedTransactionAfterGettingNetworkCallback = std::sync::Arc::new({ let signer_id: near_primitives::types::AccountId = scope.relayer_account_id.clone().into(); let signed_delegate_action = previous_context.signed_delegate_action.clone(); move |_network_config| { let actions = vec![signed_delegate_action.clone().into()]; Ok(crate::commands::PrepopulatedTransaction { signer_id: signer_id.clone(), receiver_id: signed_delegate_action.delegate_action.sender_id.clone(), actions, }) } }); let on_before_signing_callback: crate::commands::OnBeforeSigningCallback = std::sync::Arc::new({ move |prepopulated_unsigned_transaction, _network_config| { prepopulated_unsigned_transaction.actions = vec![near_primitives::transaction::Action::Delegate(Box::new( previous_context.signed_delegate_action.clone(), ))]; Ok(()) } }); Ok(Self(crate::commands::ActionContext { global_context: previous_context.global_context, interacting_with_account_ids: vec![scope.relayer_account_id.clone().into()], get_prepopulated_transaction_after_getting_network_callback, on_before_signing_callback, on_before_sending_transaction_callback: std::sync::Arc::new( |_signed_transaction, _network_config| Ok(String::new()), ), on_after_sending_transaction_callback: std::sync::Arc::new( |_outcome, _network_config| Ok(()), ), })) } } impl From<RelayerAccountIdContext> for crate::commands::ActionContext { fn from(item: RelayerAccountIdContext) -> Self { item.0 } } impl RelayerAccountId { fn input_relayer_account_id( context: &super::SignedMetaTransactionContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { loop { let relayer_account_id = if let Some(account_id) = crate::common::input_signer_account_id_from_used_account_list( &context.global_context.config.credentials_home_dir, "What is the relayer account ID?", )? { account_id } else { return Ok(None); }; if context.global_context.offline { return Ok(Some(relayer_account_id)); } if !crate::common::is_account_exist( &context.global_context.config.network_connection, relayer_account_id.clone().into(), )? { eprintln!( "\nThe account <{relayer_account_id}> does not exist on [{}] networks.", context.global_context.config.network_names().join(", ") ); #[derive(strum_macros::Display)] enum ConfirmOptions { #[strum(to_string = "Yes, I want to enter a new account name.")] Yes, #[strum(to_string = "No, I want to use this account name.")] No, } let select_choose_input = Select::new( "Do you want to enter another relayer account id?", vec![ConfirmOptions::Yes, ConfirmOptions::No], ) .prompt()?; if let ConfirmOptions::No = select_choose_input { return Ok(Some(relayer_account_id)); } } else { return Ok(Some(relayer_account_id)); } } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/mod.rs
src/commands/transaction/construct_transaction/mod.rs
pub mod add_action_1; pub mod add_action_2; pub mod add_action_3; pub mod add_action_last; pub mod skip_action; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = crate::GlobalContext)] #[interactive_clap(output_context = ConstructTransactionContext)] pub struct ConstructTransaction { #[interactive_clap(skip_default_input_arg)] /// What is the sender account ID? pub sender_account_id: crate::types::account_id::AccountId, #[interactive_clap(skip_default_input_arg)] /// What is the receiver account ID? pub receiver_account_id: crate::types::account_id::AccountId, #[interactive_clap(subcommand)] pub next_actions: self::add_action_1::NextAction, } #[derive(Debug, Clone)] pub struct ConstructTransactionContext { pub global_context: crate::GlobalContext, pub signer_account_id: near_primitives::types::AccountId, pub receiver_account_id: near_primitives::types::AccountId, pub actions: Vec<near_primitives::transaction::Action>, } impl ConstructTransactionContext { pub fn from_previous_context( previous_context: crate::GlobalContext, scope: &<ConstructTransaction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self { global_context: previous_context, signer_account_id: scope.sender_account_id.clone().into(), receiver_account_id: scope.receiver_account_id.clone().into(), actions: vec![], }) } } impl ConstructTransaction { pub fn input_sender_account_id( context: &crate::GlobalContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { crate::common::input_signer_account_id_from_used_account_list( &context.config.credentials_home_dir, "What is the sender account ID?", ) } pub fn input_receiver_account_id( context: &crate::GlobalContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { crate::common::input_non_signer_account_id_from_used_account_list( &context.config.credentials_home_dir, "What is the receiver account ID?", ) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_2/mod.rs
src/commands/transaction/construct_transaction/add_action_2/mod.rs
#![allow(clippy::enum_variant_names, clippy::large_enum_variant)] use strum::{EnumDiscriminants, EnumIter, EnumMessage}; mod add_action; #[derive(Debug, Clone, EnumDiscriminants, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::ConstructTransactionContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Select an action that you want to add to the action: pub enum NextAction { #[strum_discriminants(strum(message = "add-action - Select a new action"))] /// Choose next action AddAction(self::add_action::AddAction), #[strum_discriminants(strum(message = "skip - Skip adding a new action"))] /// Go to transaction signing Skip(super::skip_action::SkipAction), }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_2/add_action/mod.rs
src/commands/transaction/construct_transaction/add_action_2/add_action/mod.rs
use strum::{EnumDiscriminants, EnumIter, EnumMessage}; mod add_key; mod call_function; mod create_account; mod delete_account; mod delete_key; mod deploy_contract; mod deploy_global_contract; mod stake; mod transfer; mod use_global_contract; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::super::ConstructTransactionContext)] pub struct AddAction { #[interactive_clap(subcommand)] action: ActionSubcommand, } #[derive(Debug, Clone, EnumDiscriminants, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::super::ConstructTransactionContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Select an action that you want to add to the action: pub enum ActionSubcommand { #[strum_discriminants(strum( message = "transfer - The transfer is carried out in NEAR tokens" ))] /// Specify data for transfer tokens Transfer(self::transfer::TransferAction), #[strum_discriminants(strum( message = "function-call - Execute function (contract method)" ))] /// Specify data to call the function FunctionCall(self::call_function::FunctionCallAction), #[strum_discriminants(strum(message = "stake - Stake NEAR Tokens"))] /// Specify data to stake NEAR Tokens Stake(self::stake::StakeAction), #[strum_discriminants(strum(message = "create-account - Create a new sub-account"))] /// Specify data to create a sub-account CreateAccount(self::create_account::CreateAccountAction), #[strum_discriminants(strum(message = "delete-account - Delete an account"))] /// Specify data to delete an account DeleteAccount(self::delete_account::DeleteAccountAction), #[strum_discriminants(strum( message = "add-key - Add an access key to an account" ))] /// Specify the data to add an access key to the account AddKey(self::add_key::AddKeyAction), #[strum_discriminants(strum( message = "delete-key - Delete an access key from an account" ))] /// Specify the data to delete the access key to the account DeleteKey(self::delete_key::DeleteKeyAction), #[strum_discriminants(strum(message = "deploy - Add a new contract code"))] /// Specify the details to deploy the contract code DeployContract(self::deploy_contract::DeployContractAction), #[strum_discriminants(strum( message = "deploy-global-contract - Add a new global contract code" ))] /// Specify the details to deploy the global contract code DeployGlobalContract(self::deploy_global_contract::DeployGlobalContractAction), #[strum_discriminants(strum( message = "use-global-contract - Use a global contract to re-use the pre-deployed on-chain code" ))] /// Specify the details to use the global contract UseGlobalContract(self::use_global_contract::UseGlobalContractAction), }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_2/add_action/transfer/mod.rs
src/commands/transaction/construct_transaction/add_action_2/add_action/transfer/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = TransferActionContext)] pub struct TransferAction { /// How many NEAR Tokens do you want to transfer? (example: 10 NEAR or 0.5 NEAR or 10000 yoctonear) amount_in_near: crate::types::near_token::NearToken, #[interactive_clap(subcommand)] next_action: super::super::super::add_action_3::NextAction, } #[derive(Debug, Clone)] pub struct TransferActionContext(super::super::super::ConstructTransactionContext); impl TransferActionContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, scope: &<TransferAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let action = near_primitives::transaction::Action::Transfer( near_primitives::transaction::TransferAction { deposit: scope.amount_in_near.into(), }, ); let mut actions = previous_context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, })) } } impl From<TransferActionContext> for super::super::super::ConstructTransactionContext { fn from(item: TransferActionContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_2/add_action/delete_key/mod.rs
src/commands/transaction/construct_transaction/add_action_2/add_action/delete_key/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = DeleteKeyActionContext)] pub struct DeleteKeyAction { /// Enter the public key You wish to delete: public_key: crate::types::public_key::PublicKey, #[interactive_clap(subcommand)] next_action: super::super::super::add_action_3::NextAction, } #[derive(Debug, Clone)] pub struct DeleteKeyActionContext(super::super::super::ConstructTransactionContext); impl DeleteKeyActionContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, scope: &<DeleteKeyAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let action = near_primitives::transaction::Action::DeleteKey(Box::new( near_primitives::transaction::DeleteKeyAction { public_key: scope.public_key.clone().into(), }, )); let mut actions = previous_context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, })) } } impl From<DeleteKeyActionContext> for super::super::super::ConstructTransactionContext { fn from(item: DeleteKeyActionContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_2/add_action/create_account/mod.rs
src/commands/transaction/construct_transaction/add_action_2/add_action/create_account/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = CreateAccountActionContext)] pub struct CreateAccountAction { #[interactive_clap(subcommand)] next_action: super::super::super::add_action_3::NextAction, } #[derive(Debug, Clone)] pub struct CreateAccountActionContext(super::super::super::ConstructTransactionContext); impl CreateAccountActionContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, _scope: &<CreateAccountAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let action = near_primitives::transaction::Action::CreateAccount( near_primitives::transaction::CreateAccountAction {}, ); let mut actions = previous_context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, })) } } impl From<CreateAccountActionContext> for super::super::super::ConstructTransactionContext { fn from(item: CreateAccountActionContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_2/add_action/deploy_contract/mod.rs
src/commands/transaction/construct_transaction/add_action_2/add_action/deploy_contract/mod.rs
use color_eyre::eyre::Context; pub mod initialize_mode; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::super::super::ConstructTransactionContext)] pub struct DeployContractAction { #[interactive_clap(named_arg)] /// Specify a path to wasm file use_file: ContractFile, } #[derive(Debug, Clone, interactive_clap_derive::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = ContractFileContext)] pub struct ContractFile { /// What is the file location of the contract? pub file_path: crate::types::path_buf::PathBuf, #[interactive_clap(subcommand)] initialize: self::initialize_mode::InitializeMode, } #[derive(Debug, Clone)] pub struct ContractFileContext(super::super::super::ConstructTransactionContext); impl ContractFileContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, scope: &<ContractFile as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let code = std::fs::read(&scope.file_path).wrap_err_with(|| { format!("Failed to open or read the file: {:?}.", &scope.file_path.0,) })?; let action = near_primitives::transaction::Action::DeployContract( near_primitives::transaction::DeployContractAction { code }, ); let mut actions = previous_context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, })) } } impl From<ContractFileContext> for super::super::super::ConstructTransactionContext { fn from(item: ContractFileContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_2/add_action/deploy_contract/initialize_mode/mod.rs
src/commands/transaction/construct_transaction/add_action_2/add_action/deploy_contract/initialize_mode/mod.rs
use strum::{EnumDiscriminants, EnumIter, EnumMessage}; #[derive(Debug, Clone, EnumDiscriminants, interactive_clap_derive::InteractiveClap)] #[interactive_clap(context = super::super::super::super::ConstructTransactionContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Select the need for initialization: pub enum InitializeMode { /// Add an initialize #[strum_discriminants(strum(message = "with-init-call - Add an initialize"))] WithInitCall(super::super::call_function::FunctionCallAction), /// Don't add an initialize #[strum_discriminants(strum(message = "without-init-call - Don't add an initialize"))] WithoutInitCall(NoInitialize), } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::super::super::super::ConstructTransactionContext)] pub struct NoInitialize { #[interactive_clap(subcommand)] next_action: super::super::super::super::add_action_3::NextAction, }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_2/add_action/delete_account/mod.rs
src/commands/transaction/construct_transaction/add_action_2/add_action/delete_account/mod.rs
use color_eyre::owo_colors::OwoColorize; use inquire::Select; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = DeleteAccountActionContext)] pub struct DeleteAccountAction { #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] /// Enter the beneficiary ID to delete this account ID: beneficiary_id: crate::types::account_id::AccountId, #[interactive_clap(subcommand)] next_action: super::super::super::add_action_3::NextAction, } #[derive(Debug, Clone)] pub struct DeleteAccountActionContext(super::super::super::ConstructTransactionContext); impl DeleteAccountActionContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, scope: &<DeleteAccountAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let beneficiary_id: near_primitives::types::AccountId = scope.beneficiary_id.clone().into(); let action = near_primitives::transaction::Action::DeleteAccount( near_primitives::transaction::DeleteAccountAction { beneficiary_id }, ); let mut actions = previous_context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, })) } } impl From<DeleteAccountActionContext> for super::super::super::ConstructTransactionContext { fn from(item: DeleteAccountActionContext) -> Self { item.0 } } impl DeleteAccountAction { pub fn input_beneficiary_id( context: &super::super::super::ConstructTransactionContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { loop { let beneficiary_account_id = if let Some(account_id) = crate::common::input_non_signer_account_id_from_used_account_list( &context.global_context.config.credentials_home_dir, "What is the beneficiary account ID?", )? { account_id } else { return Ok(None); }; if beneficiary_account_id.0 == context.signer_account_id { eprintln!("{}", "You have selected a beneficiary account ID that will now be deleted. This will result in the loss of your funds. So make your choice again.".red()); continue; } if context.global_context.offline { return Ok(Some(beneficiary_account_id)); } #[derive(derive_more::Display)] enum ConfirmOptions { #[display("Yes, I want to check if account <{account_id}> exists. (It is free of charge, and only requires Internet access)")] Yes { account_id: crate::types::account_id::AccountId, }, #[display("No, I know this account exists and want to continue.")] No, } let select_choose_input = Select::new("\nDo you want to check the existence of the specified account so that you don't lose tokens?", vec![ConfirmOptions::Yes{account_id: beneficiary_account_id.clone()}, ConfirmOptions::No], ) .prompt()?; if let ConfirmOptions::Yes { account_id } = select_choose_input { if crate::common::find_network_where_account_exist( &context.global_context, account_id.clone().into(), )? .is_none() { eprintln!( "\nHeads up! You will lose remaining NEAR tokens on the account you delete if you specify the account <{}> as the beneficiary as it does not exist on [{}] networks.", account_id, context.global_context.config.network_names().join(", ") ); if !crate::common::ask_if_different_account_id_wanted()? { return Ok(Some(account_id)); } } else { return Ok(Some(account_id)); }; } else { return Ok(Some(beneficiary_account_id)); }; } } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_2/add_action/add_key/mod.rs
src/commands/transaction/construct_transaction/add_action_2/add_action/add_key/mod.rs
use strum::{EnumDiscriminants, EnumIter, EnumMessage}; mod access_key_type; mod use_manually_provided_seed_phrase; mod use_public_key; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::super::super::ConstructTransactionContext)] pub struct AddKeyAction { #[interactive_clap(subcommand)] permission: AccessKeyPermission, } #[derive(Debug, Clone, EnumDiscriminants, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::super::super::ConstructTransactionContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Select a permission that you want to add to the access key: pub enum AccessKeyPermission { #[strum_discriminants(strum( message = "grant-full-access - A permission with full access" ))] /// Provide data for a full access key GrantFullAccess(self::access_key_type::FullAccessType), #[strum_discriminants(strum( message = "grant-function-call-access - A permission with function call" ))] /// Provide data for a function-call access key GrantFunctionCallAccess(self::access_key_type::FunctionCallType), } #[derive(Debug, Clone, EnumDiscriminants, interactive_clap::InteractiveClap)] #[interactive_clap(context = self::access_key_type::AccessKeyPermissionContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Add an access key for this account: pub enum AccessKeyMode { #[strum_discriminants(strum( message = "use-manually-provided-seed-prase - Use the provided seed phrase manually" ))] /// Use the provided seed phrase manually UseManuallyProvidedSeedPhrase( self::use_manually_provided_seed_phrase::AddAccessWithSeedPhraseAction, ), #[strum_discriminants(strum( message = "use-manually-provided-public-key - Use the provided public key manually" ))] /// Use the provided public key manually UseManuallyProvidedPublicKey(self::use_public_key::AddAccessKeyAction), }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_2/add_action/add_key/access_key_type/mod.rs
src/commands/transaction/construct_transaction/add_action_2/add_action/add_key/access_key_type/mod.rs
use std::str::FromStr; use inquire::{CustomType, Select, Text}; #[derive(Debug, Clone)] pub struct AccessKeyPermissionContext { pub global_context: crate::GlobalContext, pub signer_account_id: near_primitives::types::AccountId, pub receiver_account_id: near_primitives::types::AccountId, pub actions: Vec<near_primitives::transaction::Action>, pub access_key_permission: near_primitives::account::AccessKeyPermission, } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = FullAccessTypeContext)] pub struct FullAccessType { #[interactive_clap(subcommand)] access_key_mode: super::AccessKeyMode, } #[derive(Debug, Clone)] pub struct FullAccessTypeContext(AccessKeyPermissionContext); impl FullAccessTypeContext { pub fn from_previous_context( previous_context: super::super::super::super::ConstructTransactionContext, _scope: &<FullAccessType as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self(AccessKeyPermissionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions: previous_context.actions, access_key_permission: near_primitives::account::AccessKeyPermission::FullAccess, })) } } impl From<FullAccessTypeContext> for AccessKeyPermissionContext { fn from(item: FullAccessTypeContext) -> Self { item.0 } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = FunctionCallTypeContext)] pub struct FunctionCallType { #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] allowance: crate::types::near_allowance::NearAllowance, #[interactive_clap(long)] /// Enter the contract account ID that this access key can be used to sign call function transactions for: contract_account_id: crate::types::account_id::AccountId, #[interactive_clap(long)] #[interactive_clap(skip_default_input_arg)] function_names: crate::types::vec_string::VecString, #[interactive_clap(subcommand)] access_key_mode: super::AccessKeyMode, } #[derive(Debug, Clone)] pub struct FunctionCallTypeContext(AccessKeyPermissionContext); impl FunctionCallTypeContext { pub fn from_previous_context( previous_context: super::super::super::super::ConstructTransactionContext, scope: &<FunctionCallType as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let access_key_permission = near_primitives::account::AccessKeyPermission::FunctionCall( near_primitives::account::FunctionCallPermission { allowance: scope.allowance.optional_near_token().map(Into::into), receiver_id: scope.contract_account_id.to_string(), method_names: scope.function_names.clone().into(), }, ); Ok(Self(AccessKeyPermissionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions: previous_context.actions, access_key_permission, })) } } impl From<FunctionCallTypeContext> for AccessKeyPermissionContext { fn from(item: FunctionCallTypeContext) -> Self { item.0 } } impl FunctionCallType { pub fn input_function_names( _context: &super::super::super::super::ConstructTransactionContext, ) -> color_eyre::eyre::Result<Option<crate::types::vec_string::VecString>> { #[derive(strum_macros::Display)] enum ConfirmOptions { #[strum( to_string = "Yes, I want to input a list of function names that can be called when transaction is signed by this access key" )] Yes, #[strum(to_string = "No, I allow it to call any functions on the specified contract")] No, } let select_choose_input = Select::new( "Would you like the access key to be valid exclusively for calling specific functions on the contract?", vec![ConfirmOptions::Yes, ConfirmOptions::No], ) .prompt()?; if let ConfirmOptions::Yes = select_choose_input { let mut input_function_names = Text::new("Enter a comma-separated list of function names that will be allowed to be called in a transaction signed by this access key:") .prompt()?; if input_function_names.contains('\"') { input_function_names.clear() }; if input_function_names.is_empty() { Ok(Some(crate::types::vec_string::VecString(vec![]))) } else { Ok(Some(crate::types::vec_string::VecString::from_str( &input_function_names, )?)) } } else { Ok(Some(crate::types::vec_string::VecString(vec![]))) } } pub fn input_allowance( _context: &super::super::super::super::ConstructTransactionContext, ) -> color_eyre::eyre::Result<Option<crate::types::near_allowance::NearAllowance>> { let allowance_near_balance: crate::types::near_allowance::NearAllowance = CustomType::new("Enter the allowance, a budget this access key can use to pay for transaction fees (example: 10 NEAR or 0.5 NEAR or 10000 yoctonear):") .with_starting_input("unlimited") .prompt()?; Ok(Some(allowance_near_balance)) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_2/add_action/add_key/use_manually_provided_seed_phrase/mod.rs
src/commands/transaction/construct_transaction/add_action_2/add_action/add_key/use_manually_provided_seed_phrase/mod.rs
use std::str::FromStr; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::access_key_type::AccessKeyPermissionContext)] #[interactive_clap(output_context = AddAccessWithSeedPhraseActionContext)] pub struct AddAccessWithSeedPhraseAction { /// Enter the seed_phrase: master_seed_phrase: String, #[interactive_clap(subcommand)] next_action: super::super::super::super::add_action_3::NextAction, } #[derive(Debug, Clone)] pub struct AddAccessWithSeedPhraseActionContext( super::super::super::super::ConstructTransactionContext, ); impl AddAccessWithSeedPhraseActionContext { pub fn from_previous_context( previous_context: super::access_key_type::AccessKeyPermissionContext, scope: &<AddAccessWithSeedPhraseAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let seed_phrase_hd_path_default = slipped10::BIP32Path::from_str("m/44'/397'/0'").unwrap(); let public_key = crate::common::get_public_key_from_seed_phrase( seed_phrase_hd_path_default, &scope.master_seed_phrase, )?; let access_key = near_primitives::account::AccessKey { nonce: 0, permission: previous_context.access_key_permission, }; let action = near_primitives::transaction::Action::AddKey(Box::new( near_primitives::transaction::AddKeyAction { public_key, access_key, }, )); let mut actions = previous_context.actions; actions.push(action); Ok(Self( super::super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, }, )) } } impl From<AddAccessWithSeedPhraseActionContext> for super::super::super::super::ConstructTransactionContext { fn from(item: AddAccessWithSeedPhraseActionContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_2/add_action/add_key/use_public_key/mod.rs
src/commands/transaction/construct_transaction/add_action_2/add_action/add_key/use_public_key/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::access_key_type::AccessKeyPermissionContext)] #[interactive_clap(output_context = AddAccessKeyActionContext)] pub struct AddAccessKeyAction { /// Enter the public key: public_key: crate::types::public_key::PublicKey, #[interactive_clap(subcommand)] next_action: super::super::super::super::add_action_3::NextAction, } #[derive(Debug, Clone)] pub struct AddAccessKeyActionContext(super::super::super::super::ConstructTransactionContext); impl AddAccessKeyActionContext { pub fn from_previous_context( previous_context: super::access_key_type::AccessKeyPermissionContext, scope: &<AddAccessKeyAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let access_key = near_primitives::account::AccessKey { nonce: 0, permission: previous_context.access_key_permission, }; let action = near_primitives::transaction::Action::AddKey(Box::new( near_primitives::transaction::AddKeyAction { public_key: scope.public_key.clone().into(), access_key, }, )); let mut actions = previous_context.actions; actions.push(action); Ok(Self( super::super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, }, )) } } impl From<AddAccessKeyActionContext> for super::super::super::super::ConstructTransactionContext { fn from(item: AddAccessKeyActionContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_2/add_action/stake/mod.rs
src/commands/transaction/construct_transaction/add_action_2/add_action/stake/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = StakeActionContext)] pub struct StakeAction { /// Enter the amount to stake: (example: 10000NEAR) stake_amount: crate::types::near_token::NearToken, /// Enter the public key of the validator key pair used on your NEAR node (see validator_key.json): public_key: crate::types::public_key::PublicKey, #[interactive_clap(subcommand)] next_action: super::super::super::add_action_3::NextAction, } #[derive(Debug, Clone)] pub struct StakeActionContext(super::super::super::ConstructTransactionContext); impl StakeActionContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, scope: &<StakeAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let action = near_primitives::transaction::Action::Stake(Box::new( near_primitives::transaction::StakeAction { stake: scope.stake_amount.into(), public_key: scope.public_key.clone().into(), }, )); let mut actions = previous_context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, })) } } impl From<StakeActionContext> for super::super::super::ConstructTransactionContext { fn from(item: StakeActionContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_2/add_action/deploy_global_contract/mod.rs
src/commands/transaction/construct_transaction/add_action_2/add_action/deploy_global_contract/mod.rs
use color_eyre::eyre::Context; use strum::{EnumDiscriminants, EnumIter, EnumMessage}; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = DeployGlobalContractActionContext)] pub struct DeployGlobalContractAction { /// What is the file location of the contract? pub file_path: crate::types::path_buf::PathBuf, #[interactive_clap(subcommand)] mode: DeployGlobalMode, } #[derive(Debug, Clone)] pub struct DeployGlobalContractActionContext { pub context: super::super::super::ConstructTransactionContext, pub code: Vec<u8>, } impl DeployGlobalContractActionContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, scope: &<DeployGlobalContractAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let code = std::fs::read(&scope.file_path).wrap_err_with(|| { format!("Failed to open or read the file: {:?}.", &scope.file_path.0,) })?; Ok(Self { context: previous_context, code, }) } } #[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = DeployGlobalContractActionContext)] #[interactive_clap(output_context = DeployGlobalModeContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] #[non_exhaustive] /// Choose a global contract deploy mode: pub enum DeployGlobalMode { #[strum_discriminants(strum( message = "as-global-hash - Deploy code as a global contract code hash (immutable)" ))] /// Deploy code as a global contract code hash (immutable) AsGlobalHash(NextCommand), #[strum_discriminants(strum( message = "as-global-account-id - Deploy code as a global contract account ID (mutable)" ))] /// Deploy code as a global contract account ID (mutable) AsGlobalAccountId(NextCommand), } #[derive(Debug, Clone)] pub struct DeployGlobalModeContext(super::super::super::ConstructTransactionContext); impl DeployGlobalModeContext { pub fn from_previous_context( previous_context: DeployGlobalContractActionContext, scope: &<DeployGlobalMode as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let action = near_primitives::transaction::Action::DeployGlobalContract( near_primitives::action::DeployGlobalContractAction { code: previous_context.code.into(), deploy_mode: match scope { DeployGlobalModeDiscriminants::AsGlobalHash => { near_primitives::action::GlobalContractDeployMode::CodeHash } DeployGlobalModeDiscriminants::AsGlobalAccountId => { near_primitives::action::GlobalContractDeployMode::AccountId } }, }, ); let mut actions = previous_context.context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.context.global_context, signer_account_id: previous_context.context.signer_account_id, receiver_account_id: previous_context.context.receiver_account_id, actions, })) } } impl From<DeployGlobalModeContext> for super::super::super::ConstructTransactionContext { fn from(item: DeployGlobalModeContext) -> Self { item.0 } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = DeployGlobalModeContext)] pub struct NextCommand { #[interactive_clap(subcommand)] next_action: super::super::super::add_action_3::NextAction, }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_2/add_action/use_global_contract/mod.rs
src/commands/transaction/construct_transaction/add_action_2/add_action/use_global_contract/mod.rs
use strum::{EnumDiscriminants, EnumIter, EnumMessage}; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::super::super::ConstructTransactionContext)] pub struct UseGlobalContractAction { #[interactive_clap(subcommand)] mode: UseGlobalActionMode, } #[derive(Debug, EnumDiscriminants, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::super::super::ConstructTransactionContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] #[non_exhaustive] /// Choose a global contract deploy mode: pub enum UseGlobalActionMode { #[strum_discriminants(strum( message = "use-global-hash - Use a global contract code hash pre-deployed on-chain (immutable)" ))] /// Use a global contract code hash (immutable) UseGlobalHash(UseHashAction), #[strum_discriminants(strum( message = "use-global-account-id - Use a global contract account ID pre-deployed on-chain (mutable)" ))] /// Use a global contract account ID (mutable) UseGlobalAccountId(UseAccountIdAction), } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = UseHashActionContext)] pub struct UseHashAction { /// What is the hash of the global contract? pub hash: crate::types::crypto_hash::CryptoHash, #[interactive_clap(subcommand)] initialize: super::deploy_contract::initialize_mode::InitializeMode, } #[derive(Debug, Clone)] pub struct UseHashActionContext(super::super::super::ConstructTransactionContext); impl UseHashActionContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, scope: &<UseHashAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let action = near_primitives::transaction::Action::UseGlobalContract(Box::new( near_primitives::action::UseGlobalContractAction { contract_identifier: near_primitives::action::GlobalContractIdentifier::CodeHash( scope.hash.into(), ), }, )); let mut actions = previous_context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, })) } } impl From<UseHashActionContext> for super::super::super::ConstructTransactionContext { fn from(item: UseHashActionContext) -> Self { item.0 } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = UseAccountIdActionContext)] pub struct UseAccountIdAction { #[interactive_clap(skip_default_input_arg)] /// What is the account ID of the global contract? pub account_id: crate::types::account_id::AccountId, #[interactive_clap(subcommand)] initialize: super::deploy_contract::initialize_mode::InitializeMode, } impl UseAccountIdAction { pub fn input_account_id( context: &super::super::super::ConstructTransactionContext, ) -> color_eyre::eyre::Result<Option<crate::types::account_id::AccountId>> { crate::common::input_non_signer_account_id_from_used_account_list( &context.global_context.config.credentials_home_dir, "What is the account ID of the global contract?", ) } } #[derive(Debug, Clone)] pub struct UseAccountIdActionContext(super::super::super::ConstructTransactionContext); impl UseAccountIdActionContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, scope: &<UseAccountIdAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let action = near_primitives::transaction::Action::UseGlobalContract(Box::new( near_primitives::action::UseGlobalContractAction { contract_identifier: near_primitives::action::GlobalContractIdentifier::AccountId( scope.account_id.clone().into(), ), }, )); let mut actions = previous_context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, })) } } impl From<UseAccountIdActionContext> for super::super::super::ConstructTransactionContext { fn from(item: UseAccountIdActionContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_2/add_action/call_function/mod.rs
src/commands/transaction/construct_transaction/add_action_2/add_action/call_function/mod.rs
use inquire::CustomType; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = FunctionCallActionContext)] pub struct FunctionCallAction { #[interactive_clap(skip_default_input_arg)] /// What is the name of the function? function_name: String, #[interactive_clap(value_enum)] #[interactive_clap(skip_default_input_arg)] /// How do you want to pass the function call arguments? function_args_type: crate::commands::contract::call_function::call_function_args_type::FunctionArgsType, /// Enter the arguments to this function: function_args: String, #[interactive_clap(named_arg)] /// Enter gas for function call prepaid_gas: PrepaidGas, } #[derive(Debug, Clone)] pub struct FunctionCallActionContext { global_context: crate::GlobalContext, signer_account_id: near_primitives::types::AccountId, receiver_account_id: near_primitives::types::AccountId, actions: Vec<near_primitives::transaction::Action>, function_name: String, function_args: Vec<u8>, } impl FunctionCallActionContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, scope: &<FunctionCallAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let function_args = crate::commands::contract::call_function::call_function_args_type::function_args( scope.function_args.clone(), scope.function_args_type.clone(), )?; Ok(Self { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions: previous_context.actions, function_name: scope.function_name.clone(), function_args, }) } } impl FunctionCallAction { fn input_function_args_type( _context: &super::super::super::ConstructTransactionContext, ) -> color_eyre::eyre::Result< Option<crate::commands::contract::call_function::call_function_args_type::FunctionArgsType>, > { crate::commands::contract::call_function::call_function_args_type::input_function_args_type( ) } fn input_function_name( context: &super::super::super::ConstructTransactionContext, ) -> color_eyre::eyre::Result<Option<String>> { crate::commands::contract::call_function::input_call_function_name( &context.global_context, &context.receiver_account_id, ) } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = FunctionCallActionContext)] #[interactive_clap(output_context = PrepaidGasContext)] pub struct PrepaidGas { #[interactive_clap(skip_default_input_arg)] /// Enter gas for function call: gas: crate::common::NearGas, #[interactive_clap(named_arg)] /// Enter deposit for a function call attached_deposit: Deposit, } #[derive(Debug, Clone)] pub struct PrepaidGasContext { global_context: crate::GlobalContext, signer_account_id: near_primitives::types::AccountId, receiver_account_id: near_primitives::types::AccountId, actions: Vec<near_primitives::transaction::Action>, function_name: String, function_args: Vec<u8>, gas: crate::common::NearGas, } impl PrepaidGasContext { pub fn from_previous_context( previous_context: FunctionCallActionContext, scope: &<PrepaidGas as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { Ok(Self { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions: previous_context.actions, function_name: previous_context.function_name, function_args: previous_context.function_args, gas: scope.gas, }) } } impl PrepaidGas { fn input_gas( _context: &FunctionCallActionContext, ) -> color_eyre::eyre::Result<Option<crate::common::NearGas>> { Ok(Some( CustomType::new("Enter gas for function call:") .with_starting_input("100 TeraGas") .with_validator(move |gas: &crate::common::NearGas| { if gas > &near_gas::NearGas::from_tgas(300) { Ok(inquire::validator::Validation::Invalid( inquire::validator::ErrorMessage::Custom( "You need to enter a value of no more than 300 TeraGas".to_string(), ), )) } else { Ok(inquire::validator::Validation::Valid) } }) .prompt()?, )) } } #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = PrepaidGasContext)] #[interactive_clap(output_context = DepositContext)] pub struct Deposit { #[interactive_clap(skip_default_input_arg)] /// Enter deposit for a function call: deposit: crate::types::near_token::NearToken, #[interactive_clap(subcommand)] next_action: super::super::super::add_action_3::NextAction, } #[derive(Debug, Clone)] pub struct DepositContext(super::super::super::ConstructTransactionContext); impl DepositContext { pub fn from_previous_context( previous_context: PrepaidGasContext, scope: &<Deposit as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let action = near_primitives::transaction::Action::FunctionCall(Box::new( near_primitives::transaction::FunctionCallAction { method_name: previous_context.function_name, args: previous_context.function_args, gas: near_primitives::gas::Gas::from_gas(previous_context.gas.as_gas()), deposit: scope.deposit.into(), }, )); let mut actions = previous_context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, })) } } impl From<DepositContext> for super::super::super::ConstructTransactionContext { fn from(item: DepositContext) -> Self { item.0 } } impl Deposit { fn input_deposit( _context: &PrepaidGasContext, ) -> color_eyre::eyre::Result<Option<crate::types::near_token::NearToken>> { Ok(Some( CustomType::new("Enter deposit for a function call (example: 10 NEAR or 0.5 near or 10000 yoctonear):") .with_starting_input("0 NEAR") .prompt()? )) } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_3/mod.rs
src/commands/transaction/construct_transaction/add_action_3/mod.rs
use strum::{EnumDiscriminants, EnumIter, EnumMessage}; mod add_action; #[derive(Debug, Clone, EnumDiscriminants, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::ConstructTransactionContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Select an action that you want to add to the action: pub enum NextAction { #[strum_discriminants(strum(message = "add-action - Select a new action"))] /// Choose next action AddAction(self::add_action::AddAction), #[strum_discriminants(strum(message = "skip - Skip adding a new action"))] /// Go to transaction signing Skip(super::skip_action::SkipAction), }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_3/add_action/mod.rs
src/commands/transaction/construct_transaction/add_action_3/add_action/mod.rs
use strum::{EnumDiscriminants, EnumIter, EnumMessage}; mod add_key; mod call_function; mod create_account; mod delete_account; mod delete_key; mod deploy_contract; mod deploy_global_contract; mod stake; mod transfer; mod use_global_contract; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::super::ConstructTransactionContext)] pub struct AddAction { #[interactive_clap(subcommand)] action: ActionSubcommand, } #[derive(Debug, Clone, EnumDiscriminants, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::super::ConstructTransactionContext)] #[strum_discriminants(derive(EnumMessage, EnumIter))] /// Select an action that you want to add to the action: pub enum ActionSubcommand { #[strum_discriminants(strum( message = "transfer - The transfer is carried out in NEAR tokens" ))] /// Specify data for transfer tokens Transfer(self::transfer::TransferAction), #[strum_discriminants(strum( message = "function-call - Execute function (contract method)" ))] /// Specify data to call the function FunctionCall(self::call_function::FunctionCallAction), #[strum_discriminants(strum(message = "stake - Stake NEAR Tokens"))] /// Specify data to stake NEAR Tokens Stake(self::stake::StakeAction), #[strum_discriminants(strum(message = "create-account - Create a new sub-account"))] /// Specify data to create a sub-account CreateAccount(self::create_account::CreateAccountAction), #[strum_discriminants(strum(message = "delete-account - Delete an account"))] /// Specify data to delete an account DeleteAccount(self::delete_account::DeleteAccountAction), #[strum_discriminants(strum( message = "add-key - Add an access key to an account" ))] /// Specify the data to add an access key to the account AddKey(self::add_key::AddKeyAction), #[strum_discriminants(strum( message = "delete-key - Delete an access key from an account" ))] /// Specify the data to delete the access key to the account DeleteKey(self::delete_key::DeleteKeyAction), #[strum_discriminants(strum(message = "deploy - Add a new contract code"))] /// Specify the details to deploy the contract code DeployContract(self::deploy_contract::DeployContractAction), #[strum_discriminants(strum( message = "deploy-global-contract - Add a new global contract code" ))] /// Specify the details to deploy the global contract code DeployGlobalContract(self::deploy_global_contract::DeployGlobalContractAction), #[strum_discriminants(strum( message = "use-global-contract - Use a global contract to re-use the pre-deployed on-chain code" ))] /// Specify the details to use the global contract UseGlobalContract(self::use_global_contract::UseGlobalContractAction), }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_3/add_action/transfer/mod.rs
src/commands/transaction/construct_transaction/add_action_3/add_action/transfer/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = TransferActionContext)] pub struct TransferAction { /// How many NEAR Tokens do you want to transfer? (example: 10 NEAR or 0.5 NEAR or 10000 yoctonear) amount_in_near: crate::types::near_token::NearToken, #[interactive_clap(subcommand)] next_action: super::super::super::add_action_last::NextAction, } #[derive(Debug, Clone)] pub struct TransferActionContext(super::super::super::ConstructTransactionContext); impl TransferActionContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, scope: &<TransferAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let action = near_primitives::transaction::Action::Transfer( near_primitives::transaction::TransferAction { deposit: scope.amount_in_near.into(), }, ); let mut actions = previous_context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, })) } } impl From<TransferActionContext> for super::super::super::ConstructTransactionContext { fn from(item: TransferActionContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_3/add_action/delete_key/mod.rs
src/commands/transaction/construct_transaction/add_action_3/add_action/delete_key/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = DeleteKeyActionContext)] pub struct DeleteKeyAction { /// Enter the public key You wish to delete: public_key: crate::types::public_key::PublicKey, #[interactive_clap(subcommand)] next_action: super::super::super::add_action_last::NextAction, } #[derive(Debug, Clone)] pub struct DeleteKeyActionContext(super::super::super::ConstructTransactionContext); impl DeleteKeyActionContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, scope: &<DeleteKeyAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let action = near_primitives::transaction::Action::DeleteKey(Box::new( near_primitives::transaction::DeleteKeyAction { public_key: scope.public_key.clone().into(), }, )); let mut actions = previous_context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, })) } } impl From<DeleteKeyActionContext> for super::super::super::ConstructTransactionContext { fn from(item: DeleteKeyActionContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_3/add_action/create_account/mod.rs
src/commands/transaction/construct_transaction/add_action_3/add_action/create_account/mod.rs
#[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = CreateAccountActionContext)] pub struct CreateAccountAction { #[interactive_clap(subcommand)] next_action: super::super::super::add_action_last::NextAction, } #[derive(Debug, Clone)] pub struct CreateAccountActionContext(super::super::super::ConstructTransactionContext); impl CreateAccountActionContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, _scope: &<CreateAccountAction as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let action = near_primitives::transaction::Action::CreateAccount( near_primitives::transaction::CreateAccountAction {}, ); let mut actions = previous_context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, })) } } impl From<CreateAccountActionContext> for super::super::super::ConstructTransactionContext { fn from(item: CreateAccountActionContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false
near/near-cli-rs
https://github.com/near/near-cli-rs/blob/c9cda7bcb76d513c212e347a76ddacdb941ed755/src/commands/transaction/construct_transaction/add_action_3/add_action/deploy_contract/mod.rs
src/commands/transaction/construct_transaction/add_action_3/add_action/deploy_contract/mod.rs
use color_eyre::eyre::Context; pub mod initialize_mode; #[derive(Debug, Clone, interactive_clap::InteractiveClap)] #[interactive_clap(context = super::super::super::ConstructTransactionContext)] pub struct DeployContractAction { #[interactive_clap(named_arg)] /// Specify a path to wasm file use_file: ContractFile, } #[derive(Debug, Clone, interactive_clap_derive::InteractiveClap)] #[interactive_clap(input_context = super::super::super::ConstructTransactionContext)] #[interactive_clap(output_context = ContractFileContext)] pub struct ContractFile { /// What is the file location of the contract? pub file_path: crate::types::path_buf::PathBuf, #[interactive_clap(subcommand)] initialize: self::initialize_mode::InitializeMode, } #[derive(Debug, Clone)] pub struct ContractFileContext(super::super::super::ConstructTransactionContext); impl ContractFileContext { pub fn from_previous_context( previous_context: super::super::super::ConstructTransactionContext, scope: &<ContractFile as interactive_clap::ToInteractiveClapContextScope>::InteractiveClapContextScope, ) -> color_eyre::eyre::Result<Self> { let code = std::fs::read(&scope.file_path).wrap_err_with(|| { format!("Failed to open or read the file: {:?}.", &scope.file_path.0,) })?; let action = near_primitives::transaction::Action::DeployContract( near_primitives::transaction::DeployContractAction { code }, ); let mut actions = previous_context.actions; actions.push(action); Ok(Self(super::super::super::ConstructTransactionContext { global_context: previous_context.global_context, signer_account_id: previous_context.signer_account_id, receiver_account_id: previous_context.receiver_account_id, actions, })) } } impl From<ContractFileContext> for super::super::super::ConstructTransactionContext { fn from(item: ContractFileContext) -> Self { item.0 } }
rust
Apache-2.0
c9cda7bcb76d513c212e347a76ddacdb941ed755
2026-01-04T20:23:22.593044Z
false