Skip to content

Commit

Permalink
Use arcstr::ArcStr in block names, UI, and raytracing.
Browse files Browse the repository at this point in the history
Benefits:
* Evaluating blocks or cloning no longer clones display names.
* `ui` doesn't need a lazy-allocated `Arc<str>`; closer to no_std.
* Text raytracer no longer allocates for its name slices.
  It also implements grapheme cluster splitting, because that happened
  to be easy.
  • Loading branch information
kpreid committed Oct 15, 2023
1 parent e56bfe3 commit 52f20a9
Show file tree
Hide file tree
Showing 24 changed files with 166 additions and 118 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@
- All functions using `usize` to identify a coordinate axis now use `math::Axis` instead.
`Face6::axis_number()` and `Face7::axis_number()` are now called `axis()`.

- In block names and universe member names, `Cow<'static, str>` and `Arc<str>` have been replaced with `arcstr::ArcStr`.
This type allows both refcounting and static literal strings.

- The following functions have changed signature to use the new type `math::Gridgid`:
- `math::GridAab::transform()`
- `math::GridMatrix::decompose()`
Expand Down
14 changes: 12 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ thiserror = "1.0.40"
# The library crates do not require Tokio.
tokio = { version = "1.28.0", default-features = false }
trycmd = "0.14.1" # keep in sync with `snapbox`
unicode-segmentation = { version = "1.10.1", default-features = false }
wasm-bindgen-futures = "0.4.34"
# Note: "expose_ids" feature is not needed globally but is enabled to avoid compiling two versions
wgpu = { version = "0.17.0", features = ["expose-ids"] }
Expand Down
4 changes: 2 additions & 2 deletions all-is-cubes-desktop/src/terminal.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
//! Rendering as terminal text. Why not? Turn cubes into rectangles.
use std::borrow::Cow;
use std::sync::mpsc::{self, TrySendError};
use std::time::{Duration, Instant};

use anyhow::Context;
use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers, MouseEvent, MouseEventKind};
use tui::layout::Rect;

use all_is_cubes::arcstr::literal_substr;
use all_is_cubes::camera::{self, Camera, StandardCameras, Viewport};
use all_is_cubes::euclid::{Point2D, Vector2D};
use all_is_cubes::listen::{ListenableCell, ListenableSource};
Expand Down Expand Up @@ -356,7 +356,7 @@ impl Accumulate for ColorCharacterBuf {

fn hit_nothing(&mut self) {
self.text
.add(Rgba::TRANSPARENT, &CharacterRtData(Cow::Borrowed(" ")));
.add(Rgba::TRANSPARENT, &CharacterRtData(literal_substr!(" ")));
self.override_color = true;
}

Expand Down
1 change: 0 additions & 1 deletion all-is-cubes-ui/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ futures-core = { workspace = true }
futures-task = { workspace = true }
indoc = { workspace = true }
log = { workspace = true }
once_cell = { workspace = true }

[dev-dependencies]
futures-channel = { workspace = true }
Expand Down
5 changes: 3 additions & 2 deletions all-is-cubes-ui/src/logo.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
//! Drawing the All is Cubes logo.
use alloc::{borrow::Cow, sync::Arc};
use alloc::sync::Arc;

use all_is_cubes::{
arcstr::literal,
block::Block,
content::palette,
drawing::{
Expand All @@ -22,7 +23,7 @@ pub fn logo_text() -> Arc<dyn vui::Widget> {
let background_text_block: Block = palette::LOGO_STROKE.into();

Arc::new(vui::widgets::LargeText {
text: Cow::Borrowed("All is Cubes"),
text: literal!("All is Cubes"),
font: || &FONT_9X15_BOLD,
brush: {
VoxelBrush::new([
Expand Down
4 changes: 2 additions & 2 deletions all-is-cubes-ui/src/ui_content/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ fn graphics_toggle_button(
setter: fn(&mut GraphicsOptions, bool),
) -> WidgetTree {
let icon = hud_inputs.hud_blocks.blocks[icon_key].clone();
let text_label = String::from(icon.evaluate().unwrap().attributes.display_name);
let text_label = icon.evaluate().unwrap().attributes.display_name.clone();
let button: Arc<dyn Widget> = widgets::ToggleButton::new(
hud_inputs.graphics_options.clone(),
getter,
Expand All @@ -132,7 +132,7 @@ fn graphics_toggle_button(
children: vec![LayoutTree::leaf(button), {
// TODO: extract this for general use and reconcile with pages::parts::shrink()
let text: WidgetTree = LayoutTree::leaf(Arc::new(widgets::LargeText {
text: text_label.into(),
text: text_label,
font: || &font::FONT_6X10,
brush: VoxelBrush::single(block::Block::from(palette::ALMOST_BLACK)),
text_style: TextStyle::default(),
Expand Down
6 changes: 3 additions & 3 deletions all-is-cubes-ui/src/vui/page.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use alloc::borrow::Cow;
use alloc::sync::Arc;

use all_is_cubes::arcstr::ArcStr;
use all_is_cubes::block::AIR;
use all_is_cubes::block::{Block, BlockAttributes, Resolution};
use all_is_cubes::camera;
Expand Down Expand Up @@ -182,7 +182,7 @@ pub(crate) mod parts {
)))
}

pub fn heading(text: impl Into<Cow<'static, str>>) -> WidgetTree {
pub fn heading(text: impl Into<ArcStr>) -> WidgetTree {
LayoutTree::leaf(Arc::new(widgets::LargeText {
text: text.into(),
font: || &font::FONT_9X15_BOLD,
Expand All @@ -191,7 +191,7 @@ pub(crate) mod parts {
}))
}

pub fn paragraph(text: impl Into<Cow<'static, str>>) -> WidgetTree {
pub fn paragraph(text: impl Into<ArcStr>) -> WidgetTree {
LayoutTree::leaf(Arc::new(widgets::LargeText {
text: text.into(),
font: || &font::FONT_6X10,
Expand Down
4 changes: 2 additions & 2 deletions all-is-cubes-ui/src/vui/widgets/text.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use alloc::borrow::Cow;
use alloc::sync::Arc;

use all_is_cubes::arcstr::ArcStr;
use all_is_cubes::drawing::embedded_graphics::{
mono_font::{MonoFont, MonoTextStyle},
prelude::{Dimensions, Point},
Expand All @@ -22,7 +22,7 @@ use crate::vui::{widgets, LayoutGrant, LayoutRequest, Layoutable, Widget, Widget
#[allow(clippy::exhaustive_structs)] // TODO: find a better strategy
pub struct LargeText {
/// Text to be displayed.
pub text: Cow<'static, str>,
pub text: ArcStr,
/// Font with which to draw the text.
/// Needs to be a function to be Send+Sync.
pub font: fn() -> &'static MonoFont<'static>,
Expand Down
25 changes: 12 additions & 13 deletions all-is-cubes-ui/src/vui/widgets/tooltip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ use alloc::sync::Arc;
use std::error::Error;
use std::sync::Mutex;

use once_cell::sync::Lazy;

use all_is_cubes::arcstr::{literal, ArcStr};
use all_is_cubes::block::{space_to_blocks, AnimationHint, BlockAttributes, Resolution, AIR};
use all_is_cubes::character::{Character, CharacterChange};
use all_is_cubes::drawing::embedded_graphics::{
Expand All @@ -21,8 +20,6 @@ use all_is_cubes::universe::{URef, Universe};
use crate::ui_content::hud::{HudBlocks, HudFont};
use crate::vui::{LayoutRequest, Layoutable, Widget, WidgetController, WidgetTransaction};

static EMPTY_ARC_STR: Lazy<Arc<str>> = Lazy::new(|| "".into());

#[derive(Debug)]
pub(crate) struct TooltipState {
/// Character we're reading inventory state from
Expand Down Expand Up @@ -65,7 +62,7 @@ impl TooltipState {
}
}

pub fn set_message(&mut self, text: Arc<str>) {
pub fn set_message(&mut self, text: ArcStr) {
self.dirty_inventory = false;
self.set_contents(TooltipContents::Message(text))
}
Expand All @@ -77,7 +74,7 @@ impl TooltipState {
}

/// Advances time and returns the string that should be newly written to the screen, if different than the previous call.
fn step(&mut self, hud_blocks: &HudBlocks, tick: Tick) -> Option<Arc<str>> {
fn step(&mut self, hud_blocks: &HudBlocks, tick: Tick) -> Option<ArcStr> {
if let Some(ref mut age) = self.age {
*age += tick.delta_t();
if *age > Duration::from_secs(1) {
Expand All @@ -101,8 +98,8 @@ impl TooltipState {
.icon(&hud_blocks.icons)
.evaluate()
.ok()
.map(|ev_block| ev_block.attributes.display_name.into_owned().into())
.unwrap_or_else(|| EMPTY_ARC_STR.clone());
.map(|ev_block| ev_block.attributes.display_name.clone())
.unwrap_or_else(|| literal!(""));
let new_contents = TooltipContents::InventoryItem {
source_slot: selected_slot,
text: new_text,
Expand Down Expand Up @@ -160,17 +157,19 @@ enum TooltipContents {
/// right away.
JustStartedExisting,
Blanked,
Message(Arc<str>),
Message(ArcStr),
InventoryItem {
source_slot: usize,
text: Arc<str>,
text: ArcStr,
},
}

impl TooltipContents {
fn text(&self) -> &Arc<str> {
fn text(&self) -> &ArcStr {
static EMPTY: ArcStr = literal!("");

match self {
TooltipContents::JustStartedExisting | TooltipContents::Blanked => &EMPTY_ARC_STR,
TooltipContents::JustStartedExisting | TooltipContents::Blanked => &EMPTY,
TooltipContents::Message(m) => m,
TooltipContents::InventoryItem { text, .. } => text,
}
Expand Down Expand Up @@ -275,7 +274,7 @@ impl WidgetController for TooltipController {

fn step(&mut self, tick: Tick) -> Result<WidgetTransaction, Box<dyn Error + Send + Sync>> {
// None if no update is needed
let text_update: Option<Arc<str>> = self
let text_update: Option<ArcStr> = self
.definition
.state
.try_lock()
Expand Down
8 changes: 7 additions & 1 deletion all-is-cubes/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,11 @@ harness = false
[features]
default = ["std"]
# Adds std-dependent functionality such as thread safety.
std = ["dep:once_cell", "yield-progress/sync"]
std = [
"dep:once_cell",
"arcstr/std", # not required but nicer behavior
"yield-progress/sync",
]
# Adds `impl arbitrary::Arbitrary for ...`
# Note: Not using euclid/arbitrary because it's broken
arbitrary = ["dep:arbitrary", "ordered-float/arbitrary"]
Expand All @@ -71,6 +75,7 @@ threads = ["std", "dep:rayon"]

[dependencies]
arbitrary = { workspace = true, optional = true }
arcstr = { version = "1.1.5", default-features = false, features = ["serde", "substr"] }
base64 = { workspace = true, optional = true, features = ["std"] } # used in serialization
bitflags = { workspace = true }
bytemuck = { workspace = true, features = ["derive"] }
Expand Down Expand Up @@ -105,6 +110,7 @@ re_sdk = { workspace = true, optional = true }
# rc feature needed because we are [de]serializing `Arc`s
serde = { workspace = true, optional = true, features = ["derive", "rc"] }
serde_repr = { version = "0.1.12", optional = true, default-features = false }
unicode-segmentation = { workspace = true }
yield-progress = { workspace = true }

[build-dependencies]
Expand Down
14 changes: 8 additions & 6 deletions all-is-cubes/src/block/attributes.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
//! [`BlockAttributes`] and closely related types.
use alloc::borrow::Cow;
use core::fmt;
use core::num::NonZeroU16;

use arcstr::ArcStr;

use crate::math::{Face6, GridRotation};
use crate::op::Operation;
use crate::universe::VisitRefs;
Expand All @@ -26,9 +27,10 @@ pub struct BlockAttributes {
///
/// The default value is the empty string. The empty string should be considered a
/// reasonable choice for solid-color blocks with no special features.
// ---
// TODO: Make this a refcounted type so we can make cloning O(1).
pub display_name: Cow<'static, str>,
//---
// Design note: The use of `ArcStr` allows cloning a `BlockAttributes` to be O(1)
// allocate no additional memory.
pub display_name: ArcStr,

/// Whether players' [cursors](crate::character::Cursor) target it or pass through it.
///
Expand Down Expand Up @@ -92,7 +94,7 @@ impl fmt::Debug for BlockAttributes {

impl BlockAttributes {
const DEFAULT: Self = BlockAttributes {
display_name: Cow::Borrowed(""),
display_name: arcstr::literal!(""),
selectable: true,
rotation_rule: RotationPlacementRule::Never,
tick_action: None,
Expand Down Expand Up @@ -159,7 +161,7 @@ impl Default for BlockAttributes {
impl<'a> arbitrary::Arbitrary<'a> for BlockAttributes {
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
Ok(BlockAttributes {
display_name: Cow::Owned(u.arbitrary()?),
display_name: u.arbitrary::<alloc::string::String>()?.into(),
selectable: u.arbitrary()?,
rotation_rule: u.arbitrary()?,
tick_action: None, // TODO: need Arbitrary for Block
Expand Down
7 changes: 4 additions & 3 deletions all-is-cubes/src/block/builder.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
//! Lesser-used helpers for [`BlockBuilder`].
use alloc::borrow::Cow;
use alloc::sync::Arc;
use alloc::vec::Vec;

use arcstr::ArcStr;

use crate::block::{
AnimationHint, Atom, Block, BlockAttributes, BlockCollision, BlockDef, BlockParts, BlockPtr,
Modifier, Primitive, Resolution, RotationPlacementRule, AIR,
Expand All @@ -28,7 +29,7 @@ use crate::universe::{Name, URef, Universe};
///
/// assert_eq!(block.evaluate().unwrap().color, Rgba::new(0.5, 0.5, 0., 1.));
/// assert_eq!(
/// block.evaluate().unwrap().attributes.display_name.as_ref(),
/// block.evaluate().unwrap().attributes.display_name.as_str(),
/// "BROWN",
/// );
/// ```
Expand Down Expand Up @@ -72,7 +73,7 @@ impl<C> BlockBuilder<C> {
}

/// Sets the value for [`BlockAttributes::display_name`].
pub fn display_name(mut self, value: impl Into<Cow<'static, str>>) -> Self {
pub fn display_name(mut self, value: impl Into<ArcStr>) -> Self {
self.attributes.display_name = value.into();
self
}
Expand Down
6 changes: 5 additions & 1 deletion all-is-cubes/src/block/evaluated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -595,14 +595,18 @@ pub const AIR_EVALUATED: EvaluatedBlock = EvaluatedBlock {
voxel_opacity_mask: None,
};

/// This separate item is needed to convince the compiler that `AIR_ATTRIBUTES.display_name`
/// isn't being dropped if we return `&AIR_EVALUATED`.
pub(crate) const AIR_EVALUATED_REF: &EvaluatedBlock = &AIR_EVALUATED;

pub(super) const AIR_EVALUATED_MIN: MinEval = MinEval {
attributes: AIR_ATTRIBUTES,
voxels: Evoxels::One(Evoxel::AIR),
};

/// Used only by [`AIR_EVALUATED`].
const AIR_ATTRIBUTES: BlockAttributes = BlockAttributes {
display_name: alloc::borrow::Cow::Borrowed("<air>"),
display_name: arcstr::literal!("<air>"),
selectable: false,
rotation_rule: block::RotationPlacementRule::Never,
tick_action: None,
Expand Down
Loading

0 comments on commit 52f20a9

Please sign in to comment.