Skip to content

World access and player control

Lesson 7.8

The C++ wrappers return Expected<> values and own snapshots for you. This lesson reads the world in bulk and controls players; the C lesson has the same calls in plain C.

The world

clight::Level lv(level);
cl_raycast_opts o = CL_RAYCAST_OPTS_INIT;
o.blocks = CL_RAY_BLOCKS_VISUAL;                 // glass and bars let the ray through
auto hit = lv.raycast(eye, far_point, &o);       // Expected<cl_raycast_hit>
if (hit && hit->type == CL_HIT_BLOCK) { /* hit->block_pos, hit->state, hit->face */ }

auto states = lv.get_blocks({x - 8, y - 4, z - 8}, {x + 8, y + 4, z + 8});   // Expected<std::vector<cl_block_state>>
clight::Snapshot snap = lv.snapshot({x - 8, y - 4, z - 8}, {x + 8, y + 4, z + 8});  // released by the last copy
cl_block_state s = snap.get({x, y, z});

auto light = lv.light({x, y + 1, z});            // Expected<cl_light_info>

Properties and facts are C functions on any thread: cl_block_state_property, cl_block_state_with, cl_block_get_info, cl_block_sound_type. Containers: lv.container_size(pos), container_get, container_set; block entity data: lv.block_entity_get(pos) (SNBT). Subscribe to level.block_changed to keep caches fresh.

Players

clight::Entity p(player);
cl_movement_modifier m = CL_MOVEMENT_MODIFIER_INIT;
m.id = CL_STR("broken_leg");
m.speed_mult = 0.6F;
m.can_sprint = false;
p.add_movement_modifier(&m);
auto mv = p.movement();                          // Expected<cl_movement_state>
p.set_part_visible(CL_PART_LEFT_ARM, false);
p.lock_slot(40, true, false);
p.set_natural_regen(false);

Exercise

Write a function that returns how many blocks of a snapshot are air.

Show a solution
size_t air_count(const clight::Snapshot& snap) {
    auto all = snap.copy(0);
    if (!all) return 0;
    cl_block_info info{};
    size_t n = 0;
    for (cl_block_state s : *all)
        if (cl_block_get_info(s, &info) == CL_OK && info.is_air) ++n;
    return n;
}

Recap: Level::raycast, get_blocks, snapshot and light read the world, the cl_block_* functions describe states, and the Entity player functions change movement, parts, slots, input and food. Guides: World Access, Player Control.