### Profiling with Flamegraph Source: https://github.com/azalea-rs/azalea/blob/main/CONTRIBUTING.md Instructions for setting up and running flamegraph for profiling. Ensure frame pointers are enabled during the build and run the example before starting the flamegraph collection. ```sh cargo install flamegraph RUSTFLAGS="-C force-frame-pointers=yes" cargo r -r --example testbot # wait a few seconds so chunks being loaded doesn't affect the flamegraph, and # then run this in a separate window: flamegraph -p $(pidof testbot) --deterministic # wait about 15 seconds, then ctrl+c, and view the flamegraph.svg ``` -------------------------------- ### Install and Run Fuzz Target Source: https://github.com/azalea-rs/azalea/blob/main/azalea-protocol/fuzz/README.md Install cargo-fuzz and run a specific fuzz target like 'clientbound_game'. Adjust memory limits as needed. The '-s none' flag can improve performance but may catch fewer bugs. ```sh cargo install cargo-fuzz cargo fuzz run clientbound_game -s none -- -rss_limit_mb=4096 -malloc_limit_mb=1024 ``` -------------------------------- ### Log Chat Messages with Azalea Bot Source: https://github.com/azalea-rs/azalea/blob/main/azalea/README.md This example shows how to create a bot that logs chat messages and counts them. It uses Azalea's event handling to process chat events and a shared state to maintain the message count. ```rust //! A bot that logs chat messages and the number that we've received to the console. use std::sync::Arc; use azalea::prelude::*; use parking_lot::Mutex; #[tokio::main] async fn main() -> AppExit { let account = Account::offline("bot"); // or Account::microsoft("example@example.com").await.unwrap(); ClientBuilder::new() .set_handler(handle) .start(account, "localhost") .await } #[derive(Default, Clone, Component)] pub struct State { /// An example field that stores the number of messages that've been /// received by the client so far. /// /// The state gets cloned whenever the handler is called, so to have all /// the clones point to the same data and have it be mutable, we use an /// Arc>. pub messages_received: Arc> } async fn handle(bot: Client, event: Event, state: State) -> eyre::Result<()> { match event { Event::Chat(m) => { let mut messages_received = state.messages_received.lock(); *messages_received += 1; println!("#{messages_received}: {}", m.message().to_ansi()); // messages_received gets implicitly unlocked here because it's dropped } _ => {} } Ok(()) } ``` -------------------------------- ### Get Minecraft Translation String Source: https://github.com/azalea-rs/azalea/blob/main/azalea-language/README.md Use this function to retrieve the translated string for a given Minecraft translation key. Returns None if the key is not found. ```rust assert_eq!(azalea_language::get("translation.test.none"), Some("Hello, world!")); ``` -------------------------------- ### Remove Generics from Rust Code String Source: https://github.com/azalea-rs/azalea/blob/main/docs-rs/trait-tags.html A helper function to recursively remove generic type parameters from a Rust code string. For example, it transforms 'Vec' into 'Vec'. ```javascript function removeGenerics(str) { const newStr = str.replace(/<[^<>]*>/g, ''); if (newStr !== str) { return removeGenerics(newStr); } return newStr; } ``` -------------------------------- ### Build Documentation with Docs.rs Extensions Source: https://github.com/azalea-rs/azalea/blob/main/docs-rs/README.md Use this command to build documentation locally with custom extensions enabled. Ensure you replace `` with your actual package name. ```bash RUSTDOCFLAGS="--html-after-content docs-rs/trait-tags.html --html-after-content docs-rs/arborium-header.html --cfg docsrs_dep" RUSTFLAGS="--cfg docsrs_dep" cargo doc --no-deps --package ``` -------------------------------- ### Register and Execute a Literal Command Source: https://github.com/azalea-rs/azalea/blob/main/azalea-brigadier/README.md Demonstrates how to register a simple literal command and execute it using the CommandDispatcher. Requires importing necessary traits from azalea_brigadier::prelude. ```rust use azalea_brigadier::prelude::*; use std::sync::Arc; #[derive(Debug, PartialEq)] struct CommandSource {} let mut subject = CommandDispatcher::new(); subject.register(literal("foo").executes(|_| 42)); assert_eq!( subject .execute("foo", Arc::new(CommandSource {})) .unwrap(), 42 ); ``` -------------------------------- ### Enable Trace Logging and Pipe to File Source: https://github.com/azalea-rs/azalea/blob/main/azalea/README.md Set RUST_LOG to 'trace' for maximum logging detail, especially for packet parsing issues. Pipe output to 'azalea.log' to manage large log files on Linux. ```bash RUST_LOG=trace NO_COLOR=1 cargo run &> azalea.log ``` -------------------------------- ### Enable Full Backtraces Source: https://github.com/azalea-rs/azalea/blob/main/azalea/README.md Run your code with the RUST_BACKTRACE=1 environment variable to enable full backtraces. This is crucial for diagnosing crashes and understanding the call stack. ```bash RUST_BACKTRACE=1 cargo run ``` -------------------------------- ### Generate New Packet Source: https://github.com/azalea-rs/azalea/blob/main/codegen/README.md Use this command to create a new packet file. Specify the packet ID, direction (clientbound/serverbound), and the protocol state (game, handshake, login, status). The script generates a file in the appropriate directory, but manual adjustments to the code are usually necessary. ```bash python newpacket.py [packet id] [clientbound or serverbound] [game/handshake/login/status] ``` -------------------------------- ### Import Azalea and Swarm Preludes Source: https://github.com/azalea-rs/azalea/blob/main/azalea/README.md When using swarms, ensure you import both the main Azalea prelude and the swarm prelude to access necessary functionalities. ```rust use azalea::prelude::*; use azalea::swarm::prelude::*; ``` -------------------------------- ### Perform Authentication with Cache Source: https://github.com/azalea-rs/azalea/blob/main/azalea-auth/README.md Authenticates a user using their email and optionally a cache file. The default cache location is `~/.minecraft/azalea-auth.json`. Ensure the `tokio` runtime is available for async operations. ```rust use std::path::PathBuf; #[tokio::main] async fn main() { let cache_file = PathBuf::from("example_cache.json"); let auth_result = azalea_auth::auth( "example@example.com", azalea_auth::AuthOpts { cache_file: Some(cache_file), ..Default::default() }, ) .await .unwrap(); println!("{auth_result:?}"); } ``` -------------------------------- ### Add Azalea to Project (Latest Stable Release) Source: https://github.com/azalea-rs/azalea/blob/main/azalea/README.md Use this command to add the latest stable release of Azalea to your project's Cargo.toml. ```bash cargo add azalea ``` -------------------------------- ### Configure Cargo.toml for Faster Debug Builds Source: https://github.com/azalea-rs/azalea/blob/main/azalea/README.md Add this configuration to your Cargo.toml file to optimize performance in debug mode. This enables level 1 optimization for the entire project and level 3 for packages. ```toml [profile.dev] opt-level = 1 [profile.dev.package.""] opt-level = 3 ``` -------------------------------- ### Optimize Debug Builds in Cargo.toml Source: https://github.com/azalea-rs/azalea/blob/main/azalea/src/_docs/performance.md Add these lines to your Cargo.toml to achieve near-release mode performance with faster incremental compile times in debug mode. For maximum performance, still use release mode when a short feedback loop isn't critical. ```toml [profile.dev] opt-level = 1 [profile.dev.package."*"] opt-level = 3 ``` -------------------------------- ### Create BlockState from CobblestoneWall Source: https://github.com/azalea-rs/azalea/blob/main/azalea-block/README.md Instantiates a `BlockState` for a CobblestoneWall with specific properties. This is how blocks are stored in the world. ```rust # use azalea_block::BlockState; let block_state: BlockState = azalea_block::blocks::CobblestoneWall { east: azalea_block::properties::WallEast::Low, north: azalea_block::properties::WallNorth::Low, south: azalea_block::properties::WallSouth::Low, west: azalea_block::properties::WallWest::Low, up: false, waterlogged: false, } .into(); ``` -------------------------------- ### Enable LTO in Cargo.toml Source: https://github.com/azalea-rs/azalea/blob/main/azalea/src/_docs/performance.md Enable Link Time Optimization (LTO) for release builds in your Cargo.toml file. This can significantly improve performance in certain scenarios but will increase compile times. ```toml [profile.release] lto = true ``` -------------------------------- ### Enable Deadlock Detection with parking_lot Source: https://github.com/azalea-rs/azalea/blob/main/azalea/README.md Enable the 'deadlock_detection' feature for the 'parking_lot' crate and include the provided code snippet to print a backtrace upon deadlock detection. ```rust #[cfg(feature = "deadlock_detection")] use parking_lot::deadlock; #[cfg(feature = "deadlock_detection")] use std::thread; #[cfg(feature = "deadlock_detection")] fn main() { thread::spawn(|| { let _lock = lock_manager.get_lock("some_lock").unwrap(); // do something }); // Check for deadlocks every 10 seconds loop { let deadlocks = deadlock::check_for_deadlocks(); if deadlocks.is_empty() { println!("No deadlocks detected."); } else { println!("{}\n", deadlocks); panic!("Deadlock detected!"); } thread::sleep(std::time::Duration::from_secs(10)); } } ``` -------------------------------- ### Add Azalea to Project (Latest Bleeding-Edge) Source: https://github.com/azalea-rs/azalea/blob/main/azalea/README.md Use this command to add the latest bleeding-edge version of Azalea to your project's Cargo.toml. ```bash cargo add azalea --git=https://github.com/azalea-rs/azalea ``` -------------------------------- ### Set Logging Level for Debugging Source: https://github.com/azalea-rs/azalea/blob/main/codegen/README.md To aid in debugging, set the RUST_LOG environment variable. 'debug' provides general logs, while 'trace' offers more detailed packet information, including the first few hundred bytes of each received packet, which is typically more useful for diagnosing crashes. ```bash export RUST_LOG=trace ``` -------------------------------- ### Update to New Minecraft Version Source: https://github.com/azalea-rs/azalea/blob/main/codegen/README.md Run this script to automate updates for a new Minecraft version. It handles packet updates, README modifications, protocol version changes, and generation of various game data like blocks, shapes, registries, and entity metadata. Manual review of changes and code type-checking are essential after execution. ```bash python migrate.py [new version] ``` -------------------------------- ### Available Fuzz Targets Source: https://github.com/azalea-rs/azalea/blob/main/azalea-protocol/fuzz/README.md Lists the available fuzz targets for different protocol states and directions. These can be used with the 'cargo fuzz run' command. ```sh # other valid targets: # {clientbound,serverbound}_{config,game,handshake,login,status} ``` -------------------------------- ### Enable Debug Logging in Azalea Source: https://github.com/azalea-rs/azalea/blob/main/azalea/README.md Set the RUST_LOG environment variable to 'debug' to increase logging verbosity. This is useful for observing detailed information during runtime. ```bash RUST_LOG=debug cargo run ``` -------------------------------- ### Set Client View Distance Source: https://github.com/azalea-rs/azalea/blob/main/azalea/src/_docs/performance.md Reduce the number of stored chunks and entities, and decrease received packets by setting a lower view distance. This is done within the `Event::Init` handler by calling `bot.set_client_information`. ```rust azalea::Event::Init => bot.set_client_information(ClientInformation { view_distance: 2, ..Default::default() })? ``` -------------------------------- ### CSS for Bevy Trait Tags Source: https://github.com/azalea-rs/azalea/blob/main/docs-rs/trait-tags.html CSS rules for styling the Bevy trait tags and their container. This includes layout, appearance, and specific color schemes for different trait types like Component, Resource, and Asset. ```css .bevy-tag-container { padding: 0.5rem 0; display: flex; flex-wrap: wrap; gap: 0.5rem; } .bevy-tag { display: flex; align-items: center; width: fit-content; height: 1.5rem; padding: 0 0.5rem; border-radius: 0.75rem; font-size: 1rem; font-weight: normal; color: white; } .bevy-tag { background-color: var(--tag-color); } .component-tag, .immutable-component-tag { --tag-color: oklch(50% 27% 80); } .resource-tag { --tag-color: oklch(50% 27% 110); } .asset-tag { --tag-color: oklch(50% 27% 0); } .event-tag { --tag-color: oklch(50% 27% 310); } .message-tag { --tag-color: oklch(50% 27% 190); } .plugin-tag, .plugingroup-tag { --tag-color: oklch(50% 27% 50); } .schedulelabel-tag, .systemset-tag { --tag-color: oklch(50% 27% 270); } .systemparam-tag { --tag-color: oklch(50% 27% 240); } .relationship-tag, .relationshiptarget-tag { --tag-color: oklch(50% 27% 150); } ``` -------------------------------- ### Bevy Trait Tagging Logic Source: https://github.com/azalea-rs/azalea/blob/main/docs-rs/trait-tags.html This JavaScript code adds tags to Bevy documentation pages. It identifies implemented traits and displays them as clickable tags, with special handling for immutable components. This extension is intended to be passed to rustdoc using the `--html-after-content` flag. ```javascript const bevyTraits = [ 'Plugin', 'PluginGroup', 'Component', 'Resource', 'Asset', 'Event', 'Message', 'ScheduleLabel', 'SystemSet', 'SystemParam', 'Relationship', 'RelationshipTarget' ]; const implementedBevyTraits = findImplementedBevyTraits(document); if (implementedBevyTraits.size > 0) { const heading = document.body.querySelector(".main-heading h1"); const tagContainer = document.createElement('div'); tagContainer.className = 'bevy-tag-container'; heading.appendChild(tagContainer); const associatedTypeHeader = document.querySelectorAll(".trait-impl.associatedtype .code-header"); const isImmutable = [...associatedTypeHeader].some(el => el.innerText.includes('type Mutability = Immutable')); for (let [tagName, href] of implementedBevyTraits) { if (tagName == 'Component' & isImmutable) { tagName = 'Immutable Component'; } tagContainer.appendChild(createBevyTag(tagName, href)); } } ``` -------------------------------- ### Convert Minecraft JSON to ANSI Terminal Text Source: https://github.com/azalea-rs/azalea/blob/main/azalea-chat/README.md Converts a Minecraft formatted text JSON into colored text that can be printed to the terminal using ANSI escape codes. Requires `azalea_chat` and `serde_json`. ```rust // convert a Minecraft formatted text JSON into colored text that can be printed to the terminal. use azalea_chat::FormattedText; use serde_json::Value; use serde::Deserialize; let j: Value = serde_json::from_str( r#"{"text": "hello","color": "red","bold": true}""# ) .unwrap(); let text = FormattedText::deserialize(&j).unwrap(); assert_eq!( text.to_ansi(), "\u{1b}[1m\u{1b}[38;2;255;85;85mhello\u{1b}[m" ); ``` -------------------------------- ### Convert BlockState to Box Source: https://github.com/azalea-rs/azalea/blob/main/azalea-block/README.md Converts a `BlockState` into a boxed trait object implementing `BlockTrait`. This allows for dynamic dispatch and access to block behavior information. ```rust # use azalea_block::{BlockTrait, BlockState}; # let block_state = BlockState::from(azalea_registry::builtin::BlockKind::Jukebox); let block = Box::::from(block_state); ``` -------------------------------- ### Create BlockState from BlockKind Source: https://github.com/azalea-rs/azalea/blob/main/azalea-block/README.md Converts a `BlockKind` enum variant into a `BlockState` using its default state. Useful for creating a basic block representation. ```rust # use azalea_block::BlockState; # use azalea_registry::builtin::BlockKind; let block_state: BlockState = BlockKind::Jukebox.into(); ``` -------------------------------- ### Find Implemented Bevy Traits Source: https://github.com/azalea-rs/azalea/blob/main/docs-rs/trait-tags.html This JavaScript function identifies traits implemented by the current type by parsing trait implementation headers. It returns a Map of trait names and their corresponding documentation links, filtering for known Bevy traits. ```javascript function findImplementedBevyTraits(doc) { const implementedTraits = new Map(); const allTraitHeaders = doc.body.querySelectorAll( '#trait-implementations-list .impl .code-header, #blanket-implementations-list .impl .code-header' ); for (const header of allTraitHeaders) { const traitName = removeGenerics(header.innerText).split(' ')[1].trim(); const traitLinkEl = [...header.children].find(el => el.getAttribute('href')?.includes(`trait.${traitName}.html`)); const href = traitLinkEl?.getAttribute('href'); implementedTraits.set(traitName, href); } const implementedBevyTraits = new Map( [...implementedTraits].filter(([traitName, _]) => bevyTraits.find((x) => x == traitName)) ); return implementedBevyTraits; } ``` -------------------------------- ### Disable Packet Events with Cargo Source: https://github.com/azalea-rs/azalea/blob/main/azalea/src/_docs/performance.md To reduce overhead, disable default Azalea features and re-enable specific ones, excluding `packet-event`. This command adds Azalea to your project with these configurations. ```sh cargo add azalea --no-default-features --features=log,online-mode,serde ``` -------------------------------- ### Create Bevy Tag Element Source: https://github.com/azalea-rs/azalea/blob/main/docs-rs/trait-tags.html This JavaScript function creates an anchor element for a Bevy trait tag. It sets the href attribute if provided and applies CSS classes based on the tag name for styling. ```javascript function createBevyTag(tagName, href) { const el = document.createElement('a'); const kebabCaseName = tagName.toLowerCase().replace(' ', '-'); if (href) { el.setAttribute('href', href); } el.innerText = tagName; el.className = `bevy-tag ${kebabCaseName}-tag`; return el; } ``` -------------------------------- ### Filter ECS Entities for Minecraft Entities Source: https://github.com/azalea-rs/azalea/blob/main/azalea/README.md To specifically target entities that are part of the Minecraft world within the Bevy ECS, use `With` as a filter. ```rust With ``` -------------------------------- ### Downcast BlockTrait to Specific Block Type Source: https://github.com/azalea-rs/azalea/blob/main/azalea-block/README.md Attempts to downcast a boxed `BlockTrait` to a specific block type, such as `Jukebox`. This is useful for accessing block-specific fields and methods. ```rust # use azalea_block::{BlockTrait, BlockState}; # let block_state: BlockState = azalea_registry::builtin::BlockKind::Jukebox.into(); if let Some(jukebox) = Box::::from(block_state).downcast_ref::() { // ... } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.