aboutsummaryrefslogtreecommitdiff
path: root/codegen
diff options
context:
space:
mode:
authormat <27899617+mat-1@users.noreply.github.com>2022-10-02 12:29:47 -0500
committerGitHub <noreply@github.com>2022-10-02 12:29:47 -0500
commitc9b4dccd7eaeed68ce96cf5167916417d0baa6a7 (patch)
tree0b381ee72a1486ccb22fe22158b5d7d3edaf3f99 /codegen
parentaa78491ee09ec0c6879e6edde349ca67cf809daf (diff)
downloadazalea-drasl-c9b4dccd7eaeed68ce96cf5167916417d0baa6a7.tar.xz
All block shapes & collisions (#22)
* start adding shapes * add more collision stuff * DiscreteCubeMerger * more mergers * start adding BitSetDiscreteVoxelShape::join * i love rust :smiley: :smiley: :smiley: * r * IT COMPILES???? * fix warning * fix error * fix more clippy issues * add box_shape * more shape stuff * make DiscreteVoxelShape an enum * Update shape.rs * also make VoxelShape an enum * implement BitSet::clear * add more missing things * it compiles W * start block shape codegen * optimize shape codegen * make az-block/blocks.rs look better (broken) * almost new block macro * make the codegen not generate 'type' * try to fix * work more on the blocks macro * wait it compiles * fix clippy issues * shapes codegen works * well it's almost working * simplify some shape codegen * enum type names are correct * W it compiles * cargo check no longer warns * fix some clippy issues * start making it so the shape impl is on BlockStates * insane code * new impl compiles * fix wrong find_bits + TESTS PASS! * add a test for slab collision * fix clippy issues * ok rust * fix error that happens when on stairs * add test for top slabs * start adding join_is_not_empty * add more to join_is_not_empty * top slabs still don't work!! * x..=0 doesn't work in rust :smiley: :smiley: :smiley: :smiley: :smiley: :smiley: :smiley: :smiley: :smiley: :smiley: :smiley: :smiley: :smiley: :smiley: * remove comment since i added more useful names * remove some printlns * fix walls in some configurations erroring * fix some warnings * change comment to \`\`\`ignore instead of \`\`\`no_run * players are .6 wide not .8 * fix clippy's complaints * i missed one clippy warning
Diffstat (limited to 'codegen')
-rw-r--r--codegen/README.md6
-rw-r--r--codegen/genblocks.py7
-rw-r--r--codegen/lib/code/blocks.py155
-rw-r--r--codegen/lib/code/shapes.py110
-rw-r--r--codegen/lib/code/utils.py14
-rw-r--r--codegen/lib/extract.py24
6 files changed, 245 insertions, 71 deletions
diff --git a/codegen/README.md b/codegen/README.md
index fa00b63f..e2cb0fcd 100644
--- a/codegen/README.md
+++ b/codegen/README.md
@@ -2,6 +2,12 @@ Tools for automatically generating code to help with updating Minecraft versions
The directory name doesn't start with `azalea-` because it's not a Rust crate.
+## Requirements
+
+- Python 3.8+
+- Java 17+
+- Gradle
+
## Usage
Generate packet:\
diff --git a/codegen/genblocks.py b/codegen/genblocks.py
index fe5eddd1..6b802771 100644
--- a/codegen/genblocks.py
+++ b/codegen/genblocks.py
@@ -1,4 +1,5 @@
import lib.code.version
+import lib.code.shapes
import lib.code.packet
import lib.code.blocks
import lib.code.utils
@@ -8,7 +9,8 @@ import lib.utils
version_id = lib.code.version.get_version_id()
-lib.extract.get_generator_mod_data(version_id, 'blockCollisionShapes')
+shape_datas = lib.extract.get_generator_mod_data(
+ version_id, 'blockCollisionShapes')
mappings = lib.download.get_mappings_for_version(version_id)
block_states_burger = lib.extract.get_block_states_burger(version_id)
@@ -18,6 +20,9 @@ block_states_report = lib.extract.get_block_states_report(version_id)
lib.code.blocks.generate_blocks(
block_states_burger, block_states_report, ordered_blocks, mappings)
+lib.code.shapes.generate_block_shapes(
+ shape_datas['blocks'], shape_datas['shapes'], block_states_report, block_states_burger, mappings)
+
lib.code.utils.fmt()
print('Done!')
diff --git a/codegen/lib/code/blocks.py b/codegen/lib/code/blocks.py
index 7dc85137..c32a3bbc 100644
--- a/codegen/lib/code/blocks.py
+++ b/codegen/lib/code/blocks.py
@@ -1,6 +1,7 @@
-from typing import Optional
-from lib.utils import to_snake_case, upper_first_letter, get_dir_location, to_camel_case
+from lib.utils import get_dir_location, to_camel_case
+from lib.code.utils import clean_property_name
from ..mappings import Mappings
+from typing import Optional
import re
BLOCKS_RS_DIR = get_dir_location('../azalea-block/src/blocks.rs')
@@ -19,49 +20,6 @@ def generate_blocks(blocks_burger: dict, blocks_report: dict, ordered_blocks: li
new_make_block_states_macro_code = []
new_make_block_states_macro_code.append('make_block_states! {')
- def get_property_struct_name(property: Optional[dict], block_data_burger: dict, property_variants: list[str]) -> str:
- # these are hardcoded because otherwise they cause conflicts
- # some names inspired by https://github.com/feather-rs/feather/blob/main/feather/blocks/src/generated/table.rs
- if property_variants == ['north', 'east', 'south', 'west', 'up', 'down']:
- return 'FacingCubic'
- if property_variants == ['north', 'south', 'west', 'east']:
- return 'FacingCardinal'
- if property_variants == ['top', 'bottom']:
- return 'TopBottom'
- if property_variants == ['north_south', 'east_west', 'ascending_east', 'ascending_west', 'ascending_north', 'ascending_south']:
- return 'RailShape'
- if property_variants == ['straight', 'inner_left', 'inner_right', 'outer_left', 'outer_right']:
- return 'StairShape'
- if property_variants == ['normal', 'sticky']:
- return 'PistonType'
- if property_variants == ['x', 'z']:
- return 'AxisXZ'
- if property_variants == ['single', 'left', 'right']:
- return 'ChestType'
- if property_variants == ['compare', 'subtract']:
- return 'ComparatorType'
-
- if property is None:
- return ''.join(map(to_camel_case, property_variants))
-
- property_name = None
- for class_name in [block_data_burger['class']] + block_data_burger['super']:
- property_name = mappings.get_field(
- class_name, property['field_name'])
- if property_name:
- break
- assert property_name
- property_name = to_camel_case(property_name.lower())
- if property['type'] == 'int':
- property_name = to_camel_case(
- block_data_burger['text_id']) + property_name
-
- # if property_variants == ['none', 'low', 'tall']:
-
- if property_variants == ['up', 'side', 'none']:
- property_name = 'Wire' + to_camel_case(property_name)
-
- return property_name
# Find properties
properties = {}
@@ -87,7 +45,7 @@ def generate_blocks(blocks_burger: dict, blocks_report: dict, ordered_blocks: li
'Warning: The reports have states for a block, but Burger doesn\'t!', block_data_burger)
property_struct_name = get_property_struct_name(
- property_burger, block_data_burger, property_variants)
+ property_burger, block_data_burger, property_variants, mappings)
if property_struct_name in properties:
if not properties[property_struct_name] == property_variants:
@@ -99,14 +57,7 @@ def generate_blocks(blocks_burger: dict, blocks_report: dict, ordered_blocks: li
block_properties[property_struct_name] = property_variants
- # if the name ends with _<number>, remove that part
- ending = property_name.split('_')[-1]
- if ending.isdigit():
- property_name = property_name[:-(len(ending) + 1)]
-
- # `type` is a reserved keyword, so we use kind instead ¯\_(ツ)_/¯
- if property_name == 'type':
- property_name = 'kind'
+ property_name = clean_property_name(property_name)
property_struct_names_to_names[property_struct_name] = property_name
properties.update(block_properties)
@@ -120,15 +71,20 @@ def generate_blocks(blocks_burger: dict, blocks_report: dict, ordered_blocks: li
# Ceiling,
# },
property_name = property_struct_names_to_names[property_struct_name]
- new_make_block_states_macro_code.append(
- f' "{property_name}" => {property_struct_name} {{')
- for variant in property_variants:
- new_make_block_states_macro_code.append(
- f' {to_camel_case(variant)},')
+ # if the only variants are true and false, we can just make it a normal boolean
+ if property_variants == ['true', 'false']:
+ property_shape_code = 'bool'
+ else:
+ property_shape_code = f'{property_struct_name} {{\n'
+ for variant in property_variants:
+ property_shape_code += f' {to_camel_case(variant)},\n'
+ property_shape_code += ' }'
new_make_block_states_macro_code.append(
- f' }},')
+ f' "{property_name}" => {property_shape_code},')
+
+
new_make_block_states_macro_code.append(' },')
# Block codegen
@@ -145,9 +101,8 @@ def generate_blocks(blocks_burger: dict, blocks_report: dict, ordered_blocks: li
if state.get('default'):
default_property_variants = state.get('properties', {})
- # TODO: use burger to generate the blockbehavior
- new_make_block_states_macro_code.append(
- f' {block_id} => BlockBehavior::default(), {{')
+
+ properties_code = '{'
for property_name in list(block_data_report.get('properties', {}).keys()):
property_burger = None
for property in block_data_burger.get('states', []):
@@ -159,11 +114,33 @@ def generate_blocks(blocks_burger: dict, blocks_report: dict, ordered_blocks: li
property_variants = block_data_report['properties'][property_name]
property_struct_name = get_property_struct_name(
- property_burger, block_data_burger, property_variants)
+ property_burger, block_data_burger, property_variants, mappings)
+
+ is_boolean_property = property_variants == ['true', 'false']
+
+ if is_boolean_property:
+ # if it's a boolean, keep the type lowercase
+ # (so it's either `true` or `false`)
+ property_default_type = property_default
+ else:
+ property_default_type = f'{property_struct_name}::{to_camel_case(property_default)}'
+
assert property_default is not None
- new_make_block_states_macro_code.append(
- f' {property_struct_name}={to_camel_case(property_default)},')
- new_make_block_states_macro_code.append(' },')
+
+ property_name = clean_property_name(property_name)
+ this_property_code = f'{property_name}: {property_default_type}'
+
+ properties_code += f'\n {this_property_code},'
+ # if there's nothing inside the properties, keep it in one line
+ if properties_code == '{':
+ properties_code += '}'
+ else:
+ properties_code += '\n }'
+
+ # TODO: use burger to generate the blockbehavior
+ new_make_block_states_macro_code.append(
+ f' {block_id} => BlockBehavior::default(), {properties_code},')
+
new_make_block_states_macro_code.append(' }')
new_make_block_states_macro_code.append('}')
@@ -185,3 +162,47 @@ def generate_blocks(blocks_burger: dict, blocks_report: dict, ordered_blocks: li
with open(BLOCKS_RS_DIR, 'w') as f:
f.write('\n'.join(new_code))
+
+def get_property_struct_name(property: Optional[dict], block_data_burger: dict, property_variants: list[str], mappings: Mappings) -> str:
+ # these are hardcoded because otherwise they cause conflicts
+ # some names inspired by https://github.com/feather-rs/feather/blob/main/feather/blocks/src/generated/table.rs
+ if property_variants == ['north', 'east', 'south', 'west', 'up', 'down']:
+ return 'FacingCubic'
+ if property_variants == ['north', 'south', 'west', 'east']:
+ return 'FacingCardinal'
+ if property_variants == ['top', 'bottom']:
+ return 'TopBottom'
+ if property_variants == ['north_south', 'east_west', 'ascending_east', 'ascending_west', 'ascending_north', 'ascending_south']:
+ return 'RailShape'
+ if property_variants == ['straight', 'inner_left', 'inner_right', 'outer_left', 'outer_right']:
+ return 'StairShape'
+ if property_variants == ['normal', 'sticky']:
+ return 'PistonType'
+ if property_variants == ['x', 'z']:
+ return 'AxisXZ'
+ if property_variants == ['single', 'left', 'right']:
+ return 'ChestType'
+ if property_variants == ['compare', 'subtract']:
+ return 'ComparatorType'
+
+ if property is None:
+ return ''.join(map(to_camel_case, property_variants))
+
+ property_name = None
+ for class_name in [block_data_burger['class']] + block_data_burger['super']:
+ property_name = mappings.get_field(
+ class_name, property['field_name'])
+ if property_name:
+ break
+ assert property_name
+ property_name = to_camel_case(property_name.lower())
+ if property['type'] == 'int':
+ property_name = to_camel_case(
+ block_data_burger['text_id']) + property_name
+
+ # if property_variants == ['none', 'low', 'tall']:
+
+ if property_variants == ['up', 'side', 'none']:
+ property_name = 'Wire' + to_camel_case(property_name)
+
+ return property_name
diff --git a/codegen/lib/code/shapes.py b/codegen/lib/code/shapes.py
new file mode 100644
index 00000000..e65e4028
--- /dev/null
+++ b/codegen/lib/code/shapes.py
@@ -0,0 +1,110 @@
+from lib.utils import get_dir_location, to_camel_case
+from lib.code.utils import clean_property_name
+from .blocks import get_property_struct_name
+from ..mappings import Mappings
+
+COLLISION_BLOCKS_RS_DIR = get_dir_location(
+ '../azalea-physics/src/collision/blocks.rs')
+
+
+def generate_block_shapes(blocks: dict, shapes: dict, block_states_report, block_datas_burger, mappings: Mappings):
+ code = generate_block_shapes_code(blocks, shapes, block_states_report, block_datas_burger, mappings)
+ with open(COLLISION_BLOCKS_RS_DIR, 'w') as f:
+ f.write(code)
+
+
+def generate_block_shapes_code(blocks: dict, shapes: dict, block_states_report, block_datas_burger, mappings: Mappings):
+ # look at downloads/generator-mod-*/blockCollisionShapes.json for format of blocks and shapes
+
+ generated_shape_code = ''
+ # we make several lazy_static! blocks so it doesn't complain about
+ # recursion and hopefully the compiler can paralleize it?
+ generated_shape_code += 'lazy_static! {'
+ for i, (shape_id, shape) in enumerate(sorted(shapes.items(), key=lambda shape: int(shape[0]))):
+ if i > 0 and i % 10 == 0:
+ generated_shape_code += '}\nlazy_static! {'
+ generated_shape_code += generate_code_for_shape(shape_id, shape)
+ generated_shape_code += '}'
+
+ # BlockState::PurpurStairs_NorthTopStraightTrue => &SHAPE24,
+ generated_match_inner_code = ''
+ shape_ids_to_variants = {}
+ for block_id, shape_ids in blocks.items():
+ if isinstance(shape_ids, int):
+ shape_ids = [shape_ids]
+ block_report_data = block_states_report['minecraft:' + block_id]
+ block_data_burger = block_datas_burger[block_id]
+
+ for possible_state, shape_id in zip(block_report_data['states'], shape_ids):
+ variant_values = []
+ for value in tuple(possible_state.get('properties', {}).values()):
+ variant_values.append(to_camel_case(value))
+
+ if variant_values == []:
+ variant_name = to_camel_case(block_id)
+ else:
+ variant_name = f'{to_camel_case(block_id)}_{"".join(variant_values)}'
+
+ if shape_id not in shape_ids_to_variants:
+ shape_ids_to_variants[shape_id] = []
+ shape_ids_to_variants[shape_id].append(f'BlockState::{variant_name}')
+ # shape 1 is the most common so we have a _ => &SHAPE1 at the end
+ del shape_ids_to_variants[1]
+ for shape_id, variants in shape_ids_to_variants.items():
+ generated_match_inner_code += f'{"|".join(variants)} => &SHAPE{shape_id},\n'
+
+
+ return f'''
+//! Autogenerated block collisions for every block
+
+// This file is generated from codegen/lib/code/block_shapes.py. If you want to
+// modify it, change that file.
+
+#![allow(clippy::explicit_auto_deref)]
+
+use super::VoxelShape;
+use crate::collision::{{self, Shapes}};
+use azalea_block::*;
+use lazy_static::lazy_static;
+
+trait BlockWithShape {{
+ fn shape(&self) -> &'static VoxelShape;
+}}
+
+{generated_shape_code}
+
+impl BlockWithShape for BlockState {{
+ fn shape(&self) -> &'static VoxelShape {{
+ match self {{
+ {generated_match_inner_code}_ => &SHAPE1
+ }}
+ }}
+}}
+'''
+
+
+def generate_code_for_shape(shape_id: str, parts: list[list[float]]):
+ def make_arguments(part: list[float]):
+ return ', '.join(map(lambda n: str(n).rstrip('0'), part))
+ code = ''
+ code += f'static ref SHAPE{shape_id}: VoxelShape = '
+ steps = []
+ if parts == []:
+ steps.append('collision::empty_shape()')
+ else:
+ steps.append(f'collision::box_shape({make_arguments(parts[0])})')
+ for part in parts[1:]:
+ steps.append(
+ f'Shapes::or(s, collision::box_shape({make_arguments(part)}))')
+
+ if len(steps) == 1:
+ code += steps[0]
+ else:
+ code += '{\n'
+ for step in steps[:-1]:
+ code += f' let s = {step};\n'
+ code += f' {steps[-1]}\n'
+ code += '};\n'
+ return code
+
+
diff --git a/codegen/lib/code/utils.py b/codegen/lib/code/utils.py
index e4671488..d91e0634 100644
--- a/codegen/lib/code/utils.py
+++ b/codegen/lib/code/utils.py
@@ -147,3 +147,17 @@ def write_packet_file(state, packet_name_snake_case, code):
def fmt():
os.system(f'cd {get_dir_location("..")} && cargo fmt')
+
+
+def clean_property_name(property_name):
+ # if the name ends with _<number>, remove that part
+ ending = property_name.split('_')[-1]
+ if ending.isdigit():
+ property_name = property_name[:-(len(ending) + 1)]
+
+ # `type` is a reserved keyword, so we use kind instead ¯\_(ツ)_/¯
+ if property_name == 'type':
+ property_name = 'kind'
+
+ return property_name
+
diff --git a/codegen/lib/extract.py b/codegen/lib/extract.py
index 75e4908b..5d49ac62 100644
--- a/codegen/lib/extract.py
+++ b/codegen/lib/extract.py
@@ -123,9 +123,27 @@ def get_generator_mod_data(version_id: str, category: str):
with open(get_dir_location(f'{generator_mod_dir}/src/main/resources/fabric.mod.json'), 'w') as f:
json.dump(fabric_mod_json, f, indent=2)
- os.system(
- f'cd {generator_mod_dir} && gradlew runServer'
- )
+ try: os.system(f'cd {generator_mod_dir} && chmod u+x ./gradlew')
+ except: pass
+
+ # set the server port to something other than 25565 so it doesn't
+ # conflict with anything else that's running
+ try: os.makedirs(get_dir_location(f'{generator_mod_dir}/run'))
+ except: pass
+ with open(get_dir_location(f'{generator_mod_dir}/run/server.properties'), 'w') as f:
+ f.write('server-port=56553')
+
+ # make sure we have perms to run this file
+ # (on windows it fails but keeps running)
+ os.system(f'cd {generator_mod_dir} && chmod u+x ./gradlew')
+ try:
+ subprocess.run(
+ [f'cd {generator_mod_dir} && ./gradlew runServer'],
+ check=True,
+ shell=True
+ )
+ except Exception as e:
+ os.system(f'cd {generator_mod_dir} && gradlew runServer')
if os.path.exists(target_dir):
os.unlink(target_dir)