🔥 测试错误内容

This commit is contained in:
远野千束 2024-08-28 10:52:17 +08:00
parent 989dbae873
commit 8ba6ee805a
26 changed files with 4075 additions and 5 deletions

View File

@ -31,7 +31,8 @@ jobs:
- name: Test with pytest
run: |
pdm run pytest --junitxml=report/report.xml
pdm run pytest --junitxml=report/report.xml.
0
- name: Archive Pytest test report
uses: actions/upload-artifact@v3

8
.gitignore vendored
View File

@ -5,4 +5,10 @@
.pdm-build
.pdm-python
pdm.lock
.pdm-build/
.pdm-build/
# node.js
node_modules/
docs/.vitepress/dist
docs/.vitepress/cache

View File

@ -1,2 +1,14 @@
# mcpe
MinecraftParticleEffect
# More Basic Change Particle - 更多基础变换粒子
A Minecraft particle production library
## 介绍
该库用于一些Minecraft粒子特效的计算和制作集成了常用的numpysympyscipy等科学计算库
## 文档
[MBCP docs](https://mbcp.liteyuki.icu)
## 示例
- [【特效红石音乐】童话镇~「总有一条蜿蜒在童话镇里...」](https://www.bilibili.com/video/BV1xE4m1d72j)
- [【特效红石音乐】使一颗心免于哀伤 If I Can Stop One Heart From Breaking「崩坏星穹铁道 EP」](https://www.bilibili.com/video/BV1B1421t7i3)

View File

@ -0,0 +1,28 @@
import { defineConfig } from 'vitepress'
// https://vitepress.dev/reference/site-config
export default defineConfig({
title: "MBCP docs",
description: "MBCP library docs",
themeConfig: {
// https://vitepress.dev/reference/default-theme-config
nav: [
{ text: 'Home', link: '/' },
{ text: 'Examples', link: '/markdown-examples' }
],
sidebar: [
{
text: 'Examples',
items: [
{ text: 'Markdown Examples', link: '/markdown-examples' },
{ text: 'Runtime API Examples', link: '/api-examples' }
]
}
],
socialLinks: [
{ icon: 'github', link: 'https://github.com/vuejs/vitepress' }
]
}
})

49
docs/api-examples.md Normal file
View File

@ -0,0 +1,49 @@
---
outline: deep
---
# Runtime API Examples
This page demonstrates usage of some of the runtime APIs provided by VitePress.
The main `useData()` API can be used to access site, theme, and page data for the current page. It works in both `.md` and `.vue` files:
```md
<script setup>
import { useData } from 'vitepress'
const { theme, page, frontmatter } = useData()
</script>
## Results
### Theme Data
<pre>{{ theme }}</pre>
### Page Data
<pre>{{ page }}</pre>
### Page Frontmatter
<pre>{{ frontmatter }}</pre>
```
<script setup>
import { useData } from 'vitepress'
const { site, theme, page, frontmatter } = useData()
</script>
## Results
### Theme Data
<pre>{{ theme }}</pre>
### Page Data
<pre>{{ page }}</pre>
### Page Frontmatter
<pre>{{ frontmatter }}</pre>
## More
Check out the documentation for the [full list of runtime APIs](https://vitepress.dev/reference/runtime-api#usedata).

7
docs/api/indedx.md Normal file
View File

@ -0,0 +1,7 @@
---
title: mbcp.\n\ninit\n\n
order: 1
icon: laptop-code
category: API
---

303
docs/api/mp_math/angle.md Normal file
View File

@ -0,0 +1,303 @@
---
title: mbcp.mp\nmath.angle
order: 1
icon: laptop-code
category: API
---
### ***class*** `AnyAngle`
### &emsp; ***def*** `__init__(self, value: float, is_radian: bool) -> None`
&emsp;任意角度。
Args:
value: 角度或弧度值
is_radian: 是否为弧度,默认为否
<details>
<summary>源代码</summary>
```python
def __init__(self, value: float, is_radian: bool=False):
"""
任意角度。
Args:
value: 角度或弧度值
is_radian: 是否为弧度,默认为否
"""
if is_radian:
self.radian = value
else:
self.radian = value * PI / 180
```
</details>
### &emsp; ***@property***
### &emsp; ***def*** `complementary(self: Any) -> 'AnyAngle'`
&emsp;余角两角的和为90°。
Returns:
余角
<details>
<summary>源代码</summary>
```python
@property
def complementary(self) -> 'AnyAngle':
"""
余角两角的和为90°。
Returns:
余角
"""
return AnyAngle(PI / 2 - self.minimum_positive.radian, is_radian=True)
```
</details>
### &emsp; ***@property***
### &emsp; ***def*** `supplementary(self: Any) -> 'AnyAngle'`
&emsp;补角两角的和为180°。
Returns:
补角
<details>
<summary>源代码</summary>
```python
@property
def supplementary(self) -> 'AnyAngle':
"""
补角两角的和为180°。
Returns:
补角
"""
return AnyAngle(PI - self.minimum_positive.radian, is_radian=True)
```
</details>
### &emsp; ***@property***
### &emsp; ***def*** `degree(self: Any) -> float`
&emsp;角度。
Returns:
弧度
<details>
<summary>源代码</summary>
```python
@property
def degree(self) -> float:
"""
角度。
Returns:
弧度
"""
return self.radian * 180 / PI
```
</details>
### &emsp; ***@property***
### &emsp; ***def*** `minimum_positive(self: Any) -> 'AnyAngle'`
&emsp;最小正角。
Returns:
最小正角度
<details>
<summary>源代码</summary>
```python
@property
def minimum_positive(self) -> 'AnyAngle':
"""
最小正角。
Returns:
最小正角度
"""
return AnyAngle(self.radian % (2 * PI))
```
</details>
### &emsp; ***@property***
### &emsp; ***def*** `maximum_negative(self: Any) -> 'AnyAngle'`
&emsp;最大负角。
Returns:
最大负角度
<details>
<summary>源代码</summary>
```python
@property
def maximum_negative(self) -> 'AnyAngle':
"""
最大负角。
Returns:
最大负角度
"""
return AnyAngle(-self.radian % (2 * PI), is_radian=True)
```
</details>
### &emsp; ***@property***
### &emsp; ***def*** `sin(self: Any) -> float`
&emsp;正弦值。
Returns:
正弦值
<details>
<summary>源代码</summary>
```python
@property
def sin(self) -> float:
"""
正弦值。
Returns:
正弦值
"""
return math.sin(self.radian)
```
</details>
### &emsp; ***@property***
### &emsp; ***def*** `cos(self: Any) -> float`
&emsp;余弦值。
Returns:
余弦值
<details>
<summary>源代码</summary>
```python
@property
def cos(self) -> float:
"""
余弦值。
Returns:
余弦值
"""
return math.cos(self.radian)
```
</details>
### &emsp; ***@property***
### &emsp; ***def*** `tan(self: Any) -> float`
&emsp;正切值。
Returns:
正切值
<details>
<summary>源代码</summary>
```python
@property
def tan(self) -> float:
"""
正切值。
Returns:
正切值
"""
return math.tan(self.radian)
```
</details>
### &emsp; ***@property***
### &emsp; ***def*** `cot(self: Any) -> float`
&emsp;余切值。
Returns:
余切值
<details>
<summary>源代码</summary>
```python
@property
def cot(self) -> float:
"""
余切值。
Returns:
余切值
"""
return 1 / math.tan(self.radian)
```
</details>
### &emsp; ***@property***
### &emsp; ***def*** `sec(self: Any) -> float`
&emsp;正割值。
Returns:
正割值
<details>
<summary>源代码</summary>
```python
@property
def sec(self) -> float:
"""
正割值。
Returns:
正割值
"""
return 1 / math.cos(self.radian)
```
</details>
### &emsp; ***@property***
### &emsp; ***def*** `csc(self: Any) -> float`
&emsp;余割值。
Returns:
余割值
<details>
<summary>源代码</summary>
```python
@property
def csc(self) -> float:
"""
余割值。
Returns:
余割值
"""
return 1 / math.sin(self.radian)
```
</details>

31
docs/api/mp_math/const.md Normal file
View File

@ -0,0 +1,31 @@
---
title: mbcp.mp\nmath.const
order: 1
icon: laptop-code
category: API
---
### ***var*** `PI = math.pi`
### ***var*** `E = math.e`
### ***var*** `GOLDEN_RATIO = (1 + math.sqrt(5)) / 2`
### ***var*** `GAMMA = 0.5772156649015329`
### ***var*** `EPSILON = 0.0001`
### ***var*** `APPROX = 0.001`

View File

@ -0,0 +1,145 @@
---
title: mbcp.mp\nmath.equation
order: 1
icon: laptop-code
category: API
---
### ***def*** `get_partial_derivative_func(func: MultiVarsFunc, var: int | tuple[int, ...], epsilon: Number) -> MultiVarsFunc`
求N元函数一阶偏导函数。这玩意不太稳定慎用。
Args:
func: 函数
var: 变量位置,可为整数(一阶偏导)或整数元组(高阶偏导)
epsilon: 偏移量
Returns:
偏导函数
Raises:
ValueError: 无效变量类型
<details>
<summary>源代码</summary>
```python
def get_partial_derivative_func(func: MultiVarsFunc, var: int | tuple[int, ...], epsilon: Number=EPSILON) -> MultiVarsFunc:
"""
求N元函数一阶偏导函数。这玩意不太稳定慎用。
Args:
func: 函数
var: 变量位置,可为整数(一阶偏导)或整数元组(高阶偏导)
epsilon: 偏移量
Returns:
偏导函数
Raises:
ValueError: 无效变量类型
"""
if isinstance(var, int):
def partial_derivative_func(*args: Var) -> Var:
args_list_plus = list(args)
args_list_plus[var] += epsilon
args_list_minus = list(args)
args_list_minus[var] -= epsilon
return (func(*args_list_plus) - func(*args_list_minus)) / (2 * epsilon)
return partial_derivative_func
elif isinstance(var, tuple):
def high_order_partial_derivative_func(*args: Var) -> Var:
result_func = func
for v in var:
result_func = get_partial_derivative_func(result_func, v, epsilon)
return result_func(*args)
return high_order_partial_derivative_func
else:
raise ValueError('Invalid var type')
```
</details>
### ***def*** `partial_derivative_func() -> Var`
<details>
<summary>源代码</summary>
```python
def partial_derivative_func(*args: Var) -> Var:
args_list_plus = list(args)
args_list_plus[var] += epsilon
args_list_minus = list(args)
args_list_minus[var] -= epsilon
return (func(*args_list_plus) - func(*args_list_minus)) / (2 * epsilon)
```
</details>
### ***def*** `high_order_partial_derivative_func() -> Var`
<details>
<summary>源代码</summary>
```python
def high_order_partial_derivative_func(*args: Var) -> Var:
result_func = func
for v in var:
result_func = get_partial_derivative_func(result_func, v, epsilon)
return result_func(*args)
```
</details>
### ***class*** `CurveEquation`
### &emsp; ***def*** `__init__(self, x_func: OneVarFunc, y_func: OneVarFunc, z_func: OneVarFunc) -> None`
&emsp;曲线方程。
:param x_func:
:param y_func:
:param z_func:
<details>
<summary>源代码</summary>
```python
def __init__(self, x_func: OneVarFunc, y_func: OneVarFunc, z_func: OneVarFunc):
"""
曲线方程。
:param x_func:
:param y_func:
:param z_func:
"""
self.x_func = x_func
self.y_func = y_func
self.z_func = z_func
```
</details>
### ***var*** `args_list_plus = list(args)`
### ***var*** `args_list_minus = list(args)`
### ***var*** `result_func = func`
### ***var*** `result_func = get_partial_derivative_func(result_func, v, epsilon)`

View File

@ -0,0 +1,7 @@
---
title: mbcp.mp\nmath.\n\ninit\n\n
order: 1
icon: laptop-code
category: API
---

489
docs/api/mp_math/line.md Normal file
View File

@ -0,0 +1,489 @@
---
title: mbcp.mp\nmath.line
order: 1
icon: laptop-code
category: API
---
### ***class*** `Line3`
### &emsp; ***def*** `__init__(self, point: 'Point3', direction: 'Vector3') -> None`
&emsp;三维空间中的直线。由一个点和一个方向向量确定。
Args:
point: 直线上的一点
direction: 直线的方向向量
<details>
<summary>源代码</summary>
```python
def __init__(self, point: 'Point3', direction: 'Vector3'):
"""
三维空间中的直线。由一个点和一个方向向量确定。
Args:
point: 直线上的一点
direction: 直线的方向向量
"""
self.point = point
self.direction = direction
```
</details>
### &emsp; ***def*** `approx(self, other: 'Line3', epsilon: float) -> bool`
&emsp;判断两条直线是否近似相等。
Args:
other: 另一条直线
epsilon: 误差
Returns:
是否近似相等
<details>
<summary>源代码</summary>
```python
def approx(self, other: 'Line3', epsilon: float=APPROX) -> bool:
"""
判断两条直线是否近似相等。
Args:
other: 另一条直线
epsilon: 误差
Returns:
是否近似相等
"""
return self.is_approx_parallel(other, epsilon) and (self.point - other.point).is_approx_parallel(self.direction, epsilon)
```
</details>
### &emsp; ***def*** `cal_angle(self, other: 'Line3') -> 'AnyAngle'`
&emsp;计算直线和直线之间的夹角。
Args:
other: 另一条直线
Returns:
夹角弧度
Raises:
TypeError: 不支持的类型
<details>
<summary>源代码</summary>
```python
def cal_angle(self, other: 'Line3') -> 'AnyAngle':
"""
计算直线和直线之间的夹角。
Args:
other: 另一条直线
Returns:
夹角弧度
Raises:
TypeError: 不支持的类型
"""
return self.direction.cal_angle(other.direction)
```
</details>
### &emsp; ***def*** `cal_distance(self, other: 'Line3 | Point3') -> float`
&emsp;计算直线和直线或点之间的距离。
Args:
other: 平行直线或点
Returns:
距离
Raises:
TypeError: 不支持的类型
<details>
<summary>源代码</summary>
```python
def cal_distance(self, other: 'Line3 | Point3') -> float:
"""
计算直线和直线或点之间的距离。
Args:
other: 平行直线或点
Returns:
距离
Raises:
TypeError: 不支持的类型
"""
if isinstance(other, Line3):
if self == other:
return 0
elif self.is_parallel(other):
return (other.point - self.point).cross(self.direction).length / self.direction.length
elif not self.is_coplanar(other):
return abs(self.direction.cross(other.direction) @ (self.point - other.point) / self.direction.cross(other.direction).length)
else:
return 0
elif isinstance(other, Point3):
return (other - self.point).cross(self.direction).length / self.direction.length
else:
raise TypeError('Unsupported type.')
```
</details>
### &emsp; ***def*** `cal_intersection(self, other: 'Line3') -> 'Point3'`
&emsp;计算两条直线的交点。
Args:
other: 另一条直线
Returns:
交点
Raises:
ValueError: 直线平行
ValueError: 直线不共面
<details>
<summary>源代码</summary>
```python
def cal_intersection(self, other: 'Line3') -> 'Point3':
"""
计算两条直线的交点。
Args:
other: 另一条直线
Returns:
交点
Raises:
ValueError: 直线平行
ValueError: 直线不共面
"""
if self.is_parallel(other):
raise ValueError('Lines are parallel and do not intersect.')
if not self.is_coplanar(other):
raise ValueError('Lines are not coplanar and do not intersect.')
return self.point + self.direction.cross(other.direction) @ other.direction.cross(self.point - other.point) / self.direction.cross(other.direction).length ** 2 * self.direction
```
</details>
### &emsp; ***def*** `cal_perpendicular(self, point: 'Point3') -> 'Line3'`
&emsp;计算直线经过指定点p的垂线。
Args:
point: 指定点
Returns:
垂线
<details>
<summary>源代码</summary>
```python
def cal_perpendicular(self, point: 'Point3') -> 'Line3':
"""
计算直线经过指定点p的垂线。
Args:
point: 指定点
Returns:
垂线
"""
return Line3(point, self.direction.cross(point - self.point))
```
</details>
### &emsp; ***def*** `get_point(self, t: RealNumber) -> 'Point3'`
&emsp;获取直线上的点。同一条直线但起始点和方向向量不同则同一个t对应的点不同。
Args:
t: 参数t
Returns:
<details>
<summary>源代码</summary>
```python
def get_point(self, t: RealNumber) -> 'Point3':
"""
获取直线上的点。同一条直线但起始点和方向向量不同则同一个t对应的点不同。
Args:
t: 参数t
Returns:
"""
return self.point + t * self.direction
```
</details>
### &emsp; ***def*** `get_parametric_equations(self) -> tuple[OneSingleVarFunc, OneSingleVarFunc, OneSingleVarFunc]`
&emsp;获取直线的参数方程。
Returns:
x(t), y(t), z(t)
<details>
<summary>源代码</summary>
```python
def get_parametric_equations(self) -> tuple[OneSingleVarFunc, OneSingleVarFunc, OneSingleVarFunc]:
"""
获取直线的参数方程。
Returns:
x(t), y(t), z(t)
"""
return (lambda t: self.point.x + self.direction.x * t, lambda t: self.point.y + self.direction.y * t, lambda t: self.point.z + self.direction.z * t)
```
</details>
### &emsp; ***def*** `is_approx_parallel(self, other: 'Line3', epsilon: float) -> bool`
&emsp;判断两条直线是否近似平行。
Args:
other: 另一条直线
epsilon: 误差
Returns:
是否近似平行
<details>
<summary>源代码</summary>
```python
def is_approx_parallel(self, other: 'Line3', epsilon: float=1e-06) -> bool:
"""
判断两条直线是否近似平行。
Args:
other: 另一条直线
epsilon: 误差
Returns:
是否近似平行
"""
return self.direction.is_approx_parallel(other.direction, epsilon)
```
</details>
### &emsp; ***def*** `is_parallel(self, other: 'Line3') -> bool`
&emsp;判断两条直线是否平行。
Args:
other: 另一条直线
Returns:
是否平行
<details>
<summary>源代码</summary>
```python
def is_parallel(self, other: 'Line3') -> bool:
"""
判断两条直线是否平行。
Args:
other: 另一条直线
Returns:
是否平行
"""
return self.direction.is_parallel(other.direction)
```
</details>
### &emsp; ***def*** `is_collinear(self, other: 'Line3') -> bool`
&emsp;判断两条直线是否共线。
Args:
other: 另一条直线
Returns:
是否共线
<details>
<summary>源代码</summary>
```python
def is_collinear(self, other: 'Line3') -> bool:
"""
判断两条直线是否共线。
Args:
other: 另一条直线
Returns:
是否共线
"""
return self.is_parallel(other) and (self.point - other.point).is_parallel(self.direction)
```
</details>
### &emsp; ***def*** `is_point_on(self, point: 'Point3') -> bool`
&emsp;判断点是否在直线上。
Args:
point: 点
Returns:
是否在直线上
<details>
<summary>源代码</summary>
```python
def is_point_on(self, point: 'Point3') -> bool:
"""
判断点是否在直线上。
Args:
point: 点
Returns:
是否在直线上
"""
return (point - self.point).is_parallel(self.direction)
```
</details>
### &emsp; ***def*** `is_coplanar(self, other: 'Line3') -> bool`
&emsp;判断两条直线是否共面。
充要条件两直线方向向量的叉乘与两直线上任意一点的向量的点积为0。
Args:
other: 另一条直线
Returns:
是否共面
<details>
<summary>源代码</summary>
```python
def is_coplanar(self, other: 'Line3') -> bool:
"""
判断两条直线是否共面。
充要条件两直线方向向量的叉乘与两直线上任意一点的向量的点积为0。
Args:
other: 另一条直线
Returns:
是否共面
"""
return self.direction.cross(other.direction) @ (self.point - other.point) == 0
```
</details>
### &emsp; ***def*** `simplify(self) -> None`
&emsp;简化直线方程,等价相等。
自体简化,不返回值。
按照可行性一次对x y z 化 0 处理,并对向量单位化
<details>
<summary>源代码</summary>
```python
def simplify(self):
"""
简化直线方程,等价相等。
自体简化,不返回值。
按照可行性一次对x y z 化 0 处理,并对向量单位化
"""
self.direction.normalize()
if self.direction.x == 0:
self.point.x = 0
if self.direction.y == 0:
self.point.y = 0
if self.direction.z == 0:
self.point.z = 0
```
</details>
### &emsp; ***@classmethod***
### &emsp; ***def*** `from_two_points(cls: Any, p1: 'Point3', p2: 'Point3') -> 'Line3'`
&emsp;工厂函数 由两点构造直线。
Args:
p1: 点1
p2: 点2
Returns:
直线
<details>
<summary>源代码</summary>
```python
@classmethod
def from_two_points(cls, p1: 'Point3', p2: 'Point3') -> 'Line3':
"""
工厂函数 由两点构造直线。
Args:
p1: 点1
p2: 点2
Returns:
直线
"""
direction = p2 - p1
return cls(p1, direction)
```
</details>
### ***var*** `direction = p2 - p1`
### ***var*** `s = 'Line3: '`

View File

@ -0,0 +1,15 @@
---
title: mbcp.mp\nmath.mp\nmath\ntyping
order: 1
icon: laptop-code
category: API
---
### ***var*** `SingleVar = TypeVar('SingleVar', bound=Number)`
### ***var*** `ArrayVar = TypeVar('ArrayVar', bound=Iterable[Number])`

552
docs/api/mp_math/plane.md Normal file
View File

@ -0,0 +1,552 @@
---
title: mbcp.mp\nmath.plane
order: 1
icon: laptop-code
category: API
---
### ***class*** `Plane3`
### &emsp; ***def*** `__init__(self, a: float, b: float, c: float, d: float) -> None`
&emsp;平面方程ax + by + cz + d = 0
Args:
a:
b:
c:
d:
<details>
<summary>源代码</summary>
```python
def __init__(self, a: float, b: float, c: float, d: float):
"""
平面方程ax + by + cz + d = 0
Args:
a:
b:
c:
d:
"""
self.a = a
self.b = b
self.c = c
self.d = d
```
</details>
### &emsp; ***def*** `approx(self, other: 'Plane3', epsilon: float) -> bool`
&emsp;判断两个平面是否近似相等。
Args:
other:
epsilon:
Returns:
是否近似相等
<details>
<summary>源代码</summary>
```python
def approx(self, other: 'Plane3', epsilon: float=APPROX) -> bool:
"""
判断两个平面是否近似相等。
Args:
other:
epsilon:
Returns:
是否近似相等
"""
if self.a != 0:
k = other.a / self.a
return approx(other.b, self.b * k) and approx(other.c, self.c * k) and approx(other.d, self.d * k)
elif self.b != 0:
k = other.b / self.b
return approx(other.a, self.a * k) and approx(other.c, self.c * k) and approx(other.d, self.d * k)
elif self.c != 0:
k = other.c / self.c
return approx(other.a, self.a * k) and approx(other.b, self.b * k) and approx(other.d, self.d * k)
else:
return False
```
</details>
### &emsp; ***def*** `cal_angle(self, other: 'Line3 | Plane3') -> 'AnyAngle'`
&emsp;计算平面与平面之间的夹角。
Args:
other: 另一个平面
Returns:
夹角弧度
Raises:
TypeError: 不支持的类型
<details>
<summary>源代码</summary>
```python
def cal_angle(self, other: 'Line3 | Plane3') -> 'AnyAngle':
"""
计算平面与平面之间的夹角。
Args:
other: 另一个平面
Returns:
夹角弧度
Raises:
TypeError: 不支持的类型
"""
if isinstance(other, Line3):
return self.normal.cal_angle(other.direction).complementary
elif isinstance(other, Plane3):
return AnyAngle(math.acos(self.normal @ other.normal / (self.normal.length * other.normal.length)), is_radian=True)
else:
raise TypeError(f'Unsupported type: {type(other)}')
```
</details>
### &emsp; ***def*** `cal_distance(self, other: 'Plane3 | Point3') -> float`
&emsp;计算平面与平面或点之间的距离。
Args:
other: 另一个平面或点
Returns:
距离
Raises:
TypeError: 不支持的类型
<details>
<summary>源代码</summary>
```python
def cal_distance(self, other: 'Plane3 | Point3') -> float:
"""
计算平面与平面或点之间的距离。
Args:
other: 另一个平面或点
Returns:
距离
Raises:
TypeError: 不支持的类型
"""
if isinstance(other, Plane3):
return 0
elif isinstance(other, Point3):
return abs(self.a * other.x + self.b * other.y + self.c * other.z + self.d) / (self.a ** 2 + self.b ** 2 + self.c ** 2) ** 0.5
else:
raise TypeError(f'Unsupported type: {type(other)}')
```
</details>
### &emsp; ***def*** `cal_intersection_line3(self, other: 'Plane3') -> 'Line3'`
&emsp;计算两平面的交线。该方法有问题,待修复。
Args:
other: 另一个平面
Returns:
交线
Raises:
<details>
<summary>源代码</summary>
```python
def cal_intersection_line3(self, other: 'Plane3') -> 'Line3':
"""
计算两平面的交线。该方法有问题,待修复。
Args:
other: 另一个平面
Returns:
交线
Raises:
"""
if self.normal.is_parallel(other.normal):
raise ValueError('Planes are parallel and have no intersection.')
direction = self.normal.cross(other.normal)
x, y, z = (0, 0, 0)
if self.a != 0 and other.a != 0:
A = np.array([[self.b, self.c], [other.b, other.c]])
B = np.array([-self.d, -other.d])
y, z = np.linalg.solve(A, B)
elif self.b != 0 and other.b != 0:
A = np.array([[self.a, self.c], [other.a, other.c]])
B = np.array([-self.d, -other.d])
x, z = np.linalg.solve(A, B)
elif self.c != 0 and other.c != 0:
A = np.array([[self.a, self.b], [other.a, other.b]])
B = np.array([-self.d, -other.d])
x, y = np.linalg.solve(A, B)
return Line3(Point3(x, y, z), direction)
```
</details>
### &emsp; ***def*** `cal_intersection_point3(self, other: 'Line3') -> 'Point3'`
&emsp;计算平面与直线的交点。
Args:
other: 不与平面平行或在平面上的直线
Returns:
交点
Raises:
ValueError: 平面与直线平行或重合
<details>
<summary>源代码</summary>
```python
def cal_intersection_point3(self, other: 'Line3') -> 'Point3':
"""
计算平面与直线的交点。
Args:
other: 不与平面平行或在平面上的直线
Returns:
交点
Raises:
ValueError: 平面与直线平行或重合
"""
if self.normal @ other.direction == 0:
raise ValueError('The plane and the line are parallel or coincident.')
x, y, z = other.get_parametric_equations()
t = -(self.a * other.point.x + self.b * other.point.y + self.c * other.point.z + self.d) / (self.a * other.direction.x + self.b * other.direction.y + self.c * other.direction.z)
return Point3(x(t), y(t), z(t))
```
</details>
### &emsp; ***def*** `cal_parallel_plane3(self, point: 'Point3') -> 'Plane3'`
&emsp;计算平行于该平面且过指定点的平面。
Args:
point: 指定点
Returns:
平面
<details>
<summary>源代码</summary>
```python
def cal_parallel_plane3(self, point: 'Point3') -> 'Plane3':
"""
计算平行于该平面且过指定点的平面。
Args:
point: 指定点
Returns:
平面
"""
return Plane3.from_point_and_normal(point, self.normal)
```
</details>
### &emsp; ***def*** `is_parallel(self, other: 'Plane3') -> bool`
&emsp;判断两个平面是否平行。
Args:
other: 另一个平面
Returns:
是否平行
<details>
<summary>源代码</summary>
```python
def is_parallel(self, other: 'Plane3') -> bool:
"""
判断两个平面是否平行。
Args:
other: 另一个平面
Returns:
是否平行
"""
return self.normal.is_parallel(other.normal)
```
</details>
### &emsp; ***@property***
### &emsp; ***def*** `normal(self: Any) -> 'Vector3'`
&emsp;平面的法向量。
Returns:
法向量
<details>
<summary>源代码</summary>
```python
@property
def normal(self) -> 'Vector3':
"""
平面的法向量。
Returns:
法向量
"""
return Vector3(self.a, self.b, self.c)
```
</details>
### &emsp; ***@classmethod***
### &emsp; ***def*** `from_point_and_normal(cls: Any, point: 'Point3', normal: 'Vector3') -> 'Plane3'`
&emsp;工厂函数 由点和法向量构造平面(点法式构造)。
Args:
point: 平面上的一点
normal: 法向量
Returns:
平面
<details>
<summary>源代码</summary>
```python
@classmethod
def from_point_and_normal(cls, point: 'Point3', normal: 'Vector3') -> 'Plane3':
"""
工厂函数 由点和法向量构造平面(点法式构造)。
Args:
point: 平面上的一点
normal: 法向量
Returns:
平面
"""
a, b, c = (normal.x, normal.y, normal.z)
d = -a * point.x - b * point.y - c * point.z
return cls(a, b, c, d)
```
</details>
### &emsp; ***@classmethod***
### &emsp; ***def*** `from_three_points(cls: Any, p1: 'Point3', p2: 'Point3', p3: 'Point3') -> 'Plane3'`
&emsp;工厂函数 由三点构造平面。
Args:
p1: 点1
p2: 点2
p3: 点3
Returns:
平面
<details>
<summary>源代码</summary>
```python
@classmethod
def from_three_points(cls, p1: 'Point3', p2: 'Point3', p3: 'Point3') -> 'Plane3':
"""
工厂函数 由三点构造平面。
Args:
p1: 点1
p2: 点2
p3: 点3
Returns:
平面
"""
v1 = p2 - p1
v2 = p3 - p1
normal = v1.cross(v2)
return cls.from_point_and_normal(p1, normal)
```
</details>
### &emsp; ***@classmethod***
### &emsp; ***def*** `from_two_lines(cls: Any, l1: 'Line3', l2: 'Line3') -> 'Plane3'`
&emsp;工厂函数 由两直线构造平面。
Args:
l1: 直线1
l2: 直线2
Returns:
平面
<details>
<summary>源代码</summary>
```python
@classmethod
def from_two_lines(cls, l1: 'Line3', l2: 'Line3') -> 'Plane3':
"""
工厂函数 由两直线构造平面。
Args:
l1: 直线1
l2: 直线2
Returns:
平面
"""
v1 = l1.direction
v2 = l2.point - l1.point
if v2 == zero_vector3:
v2 = l2.get_point(1) - l1.point
return cls.from_point_and_normal(l1.point, v1.cross(v2))
```
</details>
### &emsp; ***@classmethod***
### &emsp; ***def*** `from_point_and_line(cls: Any, point: 'Point3', line: 'Line3') -> 'Plane3'`
&emsp;工厂函数 由点和直线构造平面。
Args:
point: 面上一点
line: 面上直线,不包含点
Returns:
平面
<details>
<summary>源代码</summary>
```python
@classmethod
def from_point_and_line(cls, point: 'Point3', line: 'Line3') -> 'Plane3':
"""
工厂函数 由点和直线构造平面。
Args:
point: 面上一点
line: 面上直线,不包含点
Returns:
平面
"""
return cls.from_point_and_normal(point, line.direction)
```
</details>
### ***var*** `direction = self.normal.cross(other.normal)`
### ***var*** `t = -(self.a * other.point.x + self.b * other.point.y + self.c * other.point.z + self.d) / (self.a * other.direction.x + self.b * other.direction.y + self.c * other.direction.z)`
### ***var*** `d = -a * point.x - b * point.y - c * point.z`
### ***var*** `v1 = p2 - p1`
### ***var*** `v2 = p3 - p1`
### ***var*** `normal = v1.cross(v2)`
### ***var*** `v1 = l1.direction`
### ***var*** `v2 = l2.point - l1.point`
### ***var*** `s = 'Plane3: '`
### ***var*** `k = other.a / self.a`
### ***var*** `A = np.array([[self.b, self.c], [other.b, other.c]])`
### ***var*** `B = np.array([-self.d, -other.d])`
### ***var*** `v2 = l2.get_point(1) - l1.point`
### ***var*** `k = other.b / self.b`
### ***var*** `A = np.array([[self.a, self.c], [other.a, other.c]])`
### ***var*** `B = np.array([-self.d, -other.d])`
### ***var*** `k = other.c / self.c`
### ***var*** `A = np.array([[self.a, self.b], [other.a, other.b]])`
### ***var*** `B = np.array([-self.d, -other.d])`

75
docs/api/mp_math/point.md Normal file
View File

@ -0,0 +1,75 @@
---
title: mbcp.mp\nmath.point
order: 1
icon: laptop-code
category: API
---
### ***class*** `Point3`
### &emsp; ***def*** `__init__(self, x: float, y: float, z: float) -> None`
&emsp;笛卡尔坐标系中的点。
Args:
x: x 坐标
y: y 坐标
z: z 坐标
<details>
<summary>源代码</summary>
```python
def __init__(self, x: float, y: float, z: float):
"""
笛卡尔坐标系中的点。
Args:
x: x 坐标
y: y 坐标
z: z 坐标
"""
self.x = x
self.y = y
self.z = z
```
</details>
### &emsp; ***def*** `approx(self, other: 'Point3', epsilon: float) -> bool`
&emsp;判断两个点是否近似相等。
Args:
other:
epsilon:
Returns:
是否近似相等
<details>
<summary>源代码</summary>
```python
def approx(self, other: 'Point3', epsilon: float=APPROX) -> bool:
"""
判断两个点是否近似相等。
Args:
other:
epsilon:
Returns:
是否近似相等
"""
return all([abs(self.x - other.x) < epsilon, abs(self.y - other.y) < epsilon, abs(self.z - other.z) < epsilon])
```
</details>

View File

@ -0,0 +1,40 @@
---
title: mbcp.mp\nmath.segment
order: 1
icon: laptop-code
category: API
---
### ***class*** `Segment3`
### &emsp; ***def*** `__init__(self, p1: 'Point3', p2: 'Point3') -> None`
&emsp;三维空间中的线段。
:param p1:
:param p2:
<details>
<summary>源代码</summary>
```python
def __init__(self, p1: 'Point3', p2: 'Point3'):
"""
三维空间中的线段。
:param p1:
:param p2:
"""
self.p1 = p1
self.p2 = p2
'方向向量'
self.direction = self.p2 - self.p1
'长度'
self.length = self.direction.length
'中心点'
self.midpoint = Point3((self.p1.x + self.p2.x) / 2, (self.p1.y + self.p2.y) / 2, (self.p1.z + self.p2.z) / 2)
```
</details>

194
docs/api/mp_math/utils.md Normal file
View File

@ -0,0 +1,194 @@
---
title: mbcp.mp\nmath.utils
order: 1
icon: laptop-code
category: API
---
### ***def*** `clamp(x: float, min_: float, max_: float) -> float`
区间截断函数。
Args:
x:
min_:
max_:
Returns:
限制后的值
<details>
<summary>源代码</summary>
```python
def clamp(x: float, min_: float, max_: float) -> float:
"""
区间截断函数。
Args:
x:
min_:
max_:
Returns:
限制后的值
"""
return max(min(x, max_), min_)
```
</details>
### ***def*** `approx(x: float, y: float, epsilon: float) -> bool`
判断两个数是否近似相等。或包装一个实数用于判断是否近似于0。
Args:
x:
y:
epsilon:
Returns:
是否近似相等
<details>
<summary>源代码</summary>
```python
def approx(x: float, y: float=0.0, epsilon: float=APPROX) -> bool:
"""
判断两个数是否近似相等。或包装一个实数用于判断是否近似于0。
Args:
x:
y:
epsilon:
Returns:
是否近似相等
"""
return abs(x - y) < epsilon
```
</details>
### ***def*** `sign(x: float, only_neg: bool) -> str`
获取数的符号。
Args:
x: 数
only_neg: 是否只返回负数的符号
Returns:
符号 + - ""
<details>
<summary>源代码</summary>
```python
def sign(x: float, only_neg: bool=False) -> str:
"""获取数的符号。
Args:
x: 数
only_neg: 是否只返回负数的符号
Returns:
符号 + - ""
"""
if x > 0:
return '+' if not only_neg else ''
elif x < 0:
return '-'
else:
return ''
```
</details>
### ***def*** `sign_format(x: float, only_neg: bool) -> str`
格式化符号数
-1 -> -1
1 -> +1
0 -> ""
Args:
x: 数
only_neg: 是否只返回负数的符号
Returns:
符号 + - ""
<details>
<summary>源代码</summary>
```python
def sign_format(x: float, only_neg: bool=False) -> str:
"""格式化符号数
-1 -> -1
1 -> +1
0 -> ""
Args:
x: 数
only_neg: 是否只返回负数的符号
Returns:
符号 + - ""
"""
if x > 0:
return f'+{x}' if not only_neg else f'{x}'
elif x < 0:
return f'-{abs(x)}'
else:
return ''
```
</details>
### ***class*** `Approx`
用于近似比较对象
已实现对象 实数 Vector3 Point3 Plane3 Line3
### &emsp; ***def*** `__init__(self, value: RealNumber) -> None`
&emsp;
<details>
<summary>源代码</summary>
```python
def __init__(self, value: RealNumber):
self.value = value
```
</details>
### &emsp; ***def*** `raise_type_error(self, other: Any) -> None`
&emsp;
<details>
<summary>源代码</summary>
```python
def raise_type_error(self, other):
raise TypeError(f'Unsupported type: {type(self.value)} and {type(other)}')
```
</details>

340
docs/api/mp_math/vector.md Normal file
View File

@ -0,0 +1,340 @@
---
title: mbcp.mp\nmath.vector
order: 1
icon: laptop-code
category: API
---
### ***class*** `Vector3`
### &emsp; ***def*** `__init__(self, x: float, y: float, z: float) -> None`
&emsp;3维向量
Args:
x: x轴分量
y: y轴分量
z: z轴分量
<details>
<summary>源代码</summary>
```python
def __init__(self, x: float, y: float, z: float):
"""
3维向量
Args:
x: x轴分量
y: y轴分量
z: z轴分量
"""
self.x = x
self.y = y
self.z = z
```
</details>
### &emsp; ***def*** `approx(self, other: 'Vector3', epsilon: float) -> bool`
&emsp;判断两个向量是否近似相等。
Args:
other:
epsilon:
Returns:
是否近似相等
<details>
<summary>源代码</summary>
```python
def approx(self, other: 'Vector3', epsilon: float=APPROX) -> bool:
"""
判断两个向量是否近似相等。
Args:
other:
epsilon:
Returns:
是否近似相等
"""
return all([abs(self.x - other.x) < epsilon, abs(self.y - other.y) < epsilon, abs(self.z - other.z) < epsilon])
```
</details>
### &emsp; ***def*** `cal_angle(self, other: 'Vector3') -> 'AnyAngle'`
&emsp;计算两个向量之间的夹角。
Args:
other: 另一个向量
Returns:
夹角
<details>
<summary>源代码</summary>
```python
def cal_angle(self, other: 'Vector3') -> 'AnyAngle':
"""
计算两个向量之间的夹角。
Args:
other: 另一个向量
Returns:
夹角
"""
return AnyAngle(math.acos(self @ other / (self.length * other.length)), is_radian=True)
```
</details>
### &emsp; ***def*** `cross(self, other: 'Vector3') -> 'Vector3'`
&emsp;向量积 叉乘v1 cross v2 -> v3
叉乘为0则两向量平行。
其余结果的模为平行四边形的面积。
返回如下行列式的结果:
``i j k``
``x1 y1 z1``
``x2 y2 z2``
Args:
other:
Returns:
行列式的结果
<details>
<summary>源代码</summary>
```python
def cross(self, other: 'Vector3') -> 'Vector3':
"""
向量积 叉乘v1 cross v2 -> v3
叉乘为0则两向量平行。
其余结果的模为平行四边形的面积。
返回如下行列式的结果:
``i j k``
``x1 y1 z1``
``x2 y2 z2``
Args:
other:
Returns:
行列式的结果
"""
return Vector3(self.y * other.z - self.z * other.y, self.z * other.x - self.x * other.z, self.x * other.y - self.y * other.x)
```
</details>
### &emsp; ***def*** `is_approx_parallel(self, other: 'Vector3', epsilon: float) -> bool`
&emsp;判断两个向量是否近似平行。
Args:
other: 另一个向量
epsilon: 允许的误差
Returns:
是否近似平行
<details>
<summary>源代码</summary>
```python
def is_approx_parallel(self, other: 'Vector3', epsilon: float=APPROX) -> bool:
"""
判断两个向量是否近似平行。
Args:
other: 另一个向量
epsilon: 允许的误差
Returns:
是否近似平行
"""
return self.cross(other).length < epsilon
```
</details>
### &emsp; ***def*** `is_parallel(self, other: 'Vector3') -> bool`
&emsp;判断两个向量是否平行。
Args:
other: 另一个向量
Returns:
是否平行
<details>
<summary>源代码</summary>
```python
def is_parallel(self, other: 'Vector3') -> bool:
"""
判断两个向量是否平行。
Args:
other: 另一个向量
Returns:
是否平行
"""
return self.cross(other).approx(zero_vector3)
```
</details>
### &emsp; ***def*** `normalize(self) -> None`
&emsp;将向量归一化。
自体归一化,不返回值。
<details>
<summary>源代码</summary>
```python
def normalize(self):
"""
将向量归一化。
自体归一化,不返回值。
"""
length = self.length
self.x /= length
self.y /= length
self.z /= length
```
</details>
### &emsp; ***@property***
### &emsp; ***def*** `np_array(self: Any) -> 'np.ndarray'`
&emsp;返回numpy数组
Returns:
<details>
<summary>源代码</summary>
```python
@property
def np_array(self) -> 'np.ndarray':
"""
返回numpy数组
Returns:
"""
return np.array([self.x, self.y, self.z])
```
</details>
### &emsp; ***@property***
### &emsp; ***def*** `length(self: Any) -> float`
&emsp;向量的模。
Returns:
<details>
<summary>源代码</summary>
```python
@property
def length(self) -> float:
"""
向量的模。
Returns:
"""
return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)
```
</details>
### &emsp; ***@property***
### &emsp; ***def*** `unit(self: Any) -> 'Vector3'`
&emsp;获取该向量的单位向量。
Returns:
单位向量
<details>
<summary>源代码</summary>
```python
@property
def unit(self) -> 'Vector3':
"""
获取该向量的单位向量。
Returns:
单位向量
"""
return self / self.length
```
</details>
### ***var*** `zero_vector3 = Vector3(0, 0, 0)`
### ***var*** `x_axis = Vector3(1, 0, 0)`
### ***var*** `y_axis = Vector3(0, 1, 0)`
### ***var*** `z_axis = Vector3(0, 0, 1)`
### ***var*** `length = self.length`

View File

@ -0,0 +1,7 @@
---
title: mbcp.particle.\n\ninit\n\n
order: 1
icon: laptop-code
category: API
---

View File

@ -0,0 +1,7 @@
---
title: mbcp.presets.\n\ninit\n\n
order: 1
icon: laptop-code
category: API
---

View File

@ -0,0 +1,118 @@
---
title: mbcp.presets.model.\n\ninit\n\n
order: 1
icon: laptop-code
category: API
---
### ***def*** `sphere(radius: float, density: float) -> None`
生成球体上的点集。
Args:
radius:
density:
Returns:
List[Point3]: 球体上的点集。
<details>
<summary>源代码</summary>
```python
@staticmethod
def sphere(radius: float, density: float):
"""
生成球体上的点集。
Args:
radius:
density:
Returns:
List[Point3]: 球体上的点集。
"""
area = 4 * np.pi * radius ** 2
num = int(area * density)
phi_list = np.arccos([clamp(-1 + (2.0 * _ - 1.0) / num, -1, 1) for _ in range(num)])
theta_list = np.sqrt(num * np.pi) * phi_list
x_array = radius * np.sin(phi_list) * np.cos(theta_list)
y_array = radius * np.sin(phi_list) * np.sin(theta_list)
z_array = radius * np.cos(phi_list)
return [Point3(x_array[i], y_array[i], z_array[i]) for i in range(num)]
```
</details>
### ***class*** `GeometricModels`
### &emsp; ***@staticmethod***
### &emsp; ***def*** `sphere(radius: float, density: float) -> None`
&emsp;生成球体上的点集。
Args:
radius:
density:
Returns:
List[Point3]: 球体上的点集。
<details>
<summary>源代码</summary>
```python
@staticmethod
def sphere(radius: float, density: float):
"""
生成球体上的点集。
Args:
radius:
density:
Returns:
List[Point3]: 球体上的点集。
"""
area = 4 * np.pi * radius ** 2
num = int(area * density)
phi_list = np.arccos([clamp(-1 + (2.0 * _ - 1.0) / num, -1, 1) for _ in range(num)])
theta_list = np.sqrt(num * np.pi) * phi_list
x_array = radius * np.sin(phi_list) * np.cos(theta_list)
y_array = radius * np.sin(phi_list) * np.sin(theta_list)
z_array = radius * np.cos(phi_list)
return [Point3(x_array[i], y_array[i], z_array[i]) for i in range(num)]
```
</details>
### ***var*** `area = 4 * np.pi * radius ** 2`
### ***var*** `num = int(area * density)`
### ***var*** `phi_list = np.arccos([clamp(-1 + (2.0 * _ - 1.0) / num, -1, 1) for _ in range(num)])`
### ***var*** `theta_list = np.sqrt(num * np.pi) * phi_list`
### ***var*** `x_array = radius * np.sin(phi_list) * np.cos(theta_list)`
### ***var*** `y_array = radius * np.sin(phi_list) * np.sin(theta_list)`
### ***var*** `z_array = radius * np.cos(phi_list)`

25
docs/index.md Normal file
View File

@ -0,0 +1,25 @@
---
# https://vitepress.dev/reference/default-theme-home-page
layout: home
hero:
name: "MBCP docs"
text: "More basic change particle"
tagline: 用于几何运算和粒子制作的库
actions:
- theme: brand
text: 快速开始
link: /guide
- theme: alt
text: API
link: api
features:
- title: 高可用性
details: 通过简单的接口,实现了大部分几何运算和粒子制作的需求
- title: 高集成度
details: 对<code>numpy</code><code>scipy</code><code>sumpy</code>进行了封装和集成使脚本编写像使用Geogebra一样简单
- title: 内置预设
details: 提供了大量的预设,包括常见的几何图形、粒子效果等,方便快速制作
---

85
docs/markdown-examples.md Normal file
View File

@ -0,0 +1,85 @@
# Markdown Extension Examples
This page demonstrates some of the built-in markdown extensions provided by VitePress.
## Syntax Highlighting
VitePress provides Syntax Highlighting powered by [Shiki](https://github.com/shikijs/shiki), with additional features like line-highlighting:
**Input**
````md
```js{4}
export default {
data () {
return {
msg: 'Highlighted!'
}
}
}
```
````
**Output**
```js{4}
export default {
data () {
return {
msg: 'Highlighted!'
}
}
}
```
## Custom Containers
**Input**
```md
::: info
This is an info box.
:::
::: tip
This is a tip.
:::
::: warning
This is a warning.
:::
::: danger
This is a dangerous warning.
:::
::: details
This is a details block.
:::
```
**Output**
::: info
This is an info box.
:::
::: tip
This is a tip.
:::
::: warning
This is a warning.
:::
::: danger
This is a dangerous warning.
:::
::: details
This is a details block.
:::
## More
Check out the documentation for the [full list of markdown extensions](https://vitepress.dev/guide/markdown).

352
docs/mkdoc.py Normal file
View File

@ -0,0 +1,352 @@
# -*- coding: utf-8 -*-
"""
MkDocs文档生成脚本
用法 python docs/mkdoc.py
"""
import ast
import os
import shutil
from typing import Any
from enum import Enum
from pydantic import BaseModel
NO_TYPE_ANY = "Any"
NO_TYPE_HINT = "NoTypeHint"
class DefType(Enum):
FUNCTION = "function"
METHOD = "method"
STATIC_METHOD = "staticmethod"
CLASS_METHOD = "classmethod"
PROPERTY = "property"
class FunctionInfo(BaseModel):
name: str
args: list[tuple[str, str]]
return_type: str
docstring: str
source_code: str = ""
type: DefType
"""若为类中def则有"""
is_async: bool
class AttributeInfo(BaseModel):
name: str
type: str
value: Any = None
docstring: str = ""
class ClassInfo(BaseModel):
name: str
docstring: str
methods: list[FunctionInfo]
attributes: list[AttributeInfo]
inherit: list[str]
class ModuleInfo(BaseModel):
module_path: str
"""点分割模块路径 例如 liteyuki.bot"""
functions: list[FunctionInfo]
classes: list[ClassInfo]
attributes: list[AttributeInfo]
docstring: str
def get_relative_path(base_path: str, target_path: str) -> str:
"""
获取相对路径
Args:
base_path: 基础路径
target_path: 目标路径
"""
return os.path.relpath(target_path, base_path)
def write_to_files(file_data: dict[str, str]):
"""
输出文件
Args:
file_data: 文件数据 相对路径
"""
for rp, data in file_data.items():
if not os.path.exists(os.path.dirname(rp)):
os.makedirs(os.path.dirname(rp))
with open(rp, 'w', encoding='utf-8') as f:
f.write(data)
def get_file_list(module_folder: str):
file_list = []
for root, dirs, files in os.walk(module_folder):
for file in files:
if file.endswith((".py", ".pyi")):
file_list.append(os.path.join(root, file))
return file_list
def get_module_info_normal(file_path: str, ignore_private: bool = True) -> ModuleInfo:
"""
获取函数和类
Args:
file_path: Python 文件路径
ignore_private: 忽略私有函数和类
Returns:
模块信息
"""
with open(file_path, 'r', encoding='utf-8') as file:
file_content = file.read()
tree = ast.parse(file_content)
dot_sep_module_path = file_path.replace(os.sep, '.').replace(".py", "").replace(".pyi", "")
module_docstring = ast.get_docstring(tree)
module_info = ModuleInfo(
module_path=dot_sep_module_path,
functions=[],
classes=[],
attributes=[],
docstring=module_docstring if module_docstring else ""
)
for node in ast.walk(tree):
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
# 模块函数 且不在类中 若ignore_private=True则忽略私有函数
if not any(isinstance(parent, ast.ClassDef) for parent in ast.iter_child_nodes(node)) and (not ignore_private or not node.name.startswith('_')):
# 判断第一个参数是否为self或cls后期用其他办法优化
if node.args.args:
first_arg = node.args.args[0]
if first_arg.arg in ("self", "cls"):
continue
function_docstring = ast.get_docstring(node)
func_info = FunctionInfo(
name=node.name,
args=[(arg.arg, ast.unparse(arg.annotation) if arg.annotation else NO_TYPE_ANY) for arg in node.args.args],
return_type=ast.unparse(node.returns) if node.returns else "None",
docstring=function_docstring if function_docstring else "",
type=DefType.FUNCTION,
is_async=isinstance(node, ast.AsyncFunctionDef),
source_code=ast.unparse(node)
)
module_info.functions.append(func_info)
elif isinstance(node, ast.ClassDef):
# 模块类
class_docstring = ast.get_docstring(node)
class_info = ClassInfo(
name=node.name,
docstring=class_docstring if class_docstring else "",
methods=[],
attributes=[],
inherit=[ast.unparse(base) for base in node.bases]
)
for class_node in node.body:
# methods [instance, static, class property]保留__init__方法
if isinstance(class_node, ast.FunctionDef) and (not ignore_private or not class_node.name.startswith('_') or class_node.name == "__init__"):
method_docstring = ast.get_docstring(class_node)
def_type = DefType.METHOD
if class_node.decorator_list:
if any(isinstance(decorator, ast.Name) and decorator.id == "staticmethod" for decorator in class_node.decorator_list):
def_type = DefType.STATIC_METHOD
elif any(isinstance(decorator, ast.Name) and decorator.id == "classmethod" for decorator in class_node.decorator_list):
def_type = DefType.CLASS_METHOD
elif any(isinstance(decorator, ast.Name) and decorator.id == "property" for decorator in class_node.decorator_list):
def_type = DefType.PROPERTY
class_info.methods.append(FunctionInfo(
name=class_node.name,
args=[(arg.arg, ast.unparse(arg.annotation) if arg.annotation else NO_TYPE_ANY) for arg in class_node.args.args],
return_type=ast.unparse(class_node.returns) if class_node.returns else "None",
docstring=method_docstring if method_docstring else "",
type=def_type,
is_async=isinstance(class_node, ast.AsyncFunctionDef),
source_code=ast.unparse(class_node)
))
# attributes
elif isinstance(class_node, ast.Assign):
for target in class_node.targets:
if isinstance(target, ast.Name):
class_info.attributes.append(AttributeInfo(
name=target.id,
type=ast.unparse(class_node.value)
))
module_info.classes.append(class_info)
elif isinstance(node, ast.Assign):
# 检查是否在类或函数中
if not any(isinstance(parent, (ast.ClassDef, ast.FunctionDef)) for parent in ast.iter_child_nodes(node)):
# 模块属性变量
for target in node.targets:
if isinstance(target, ast.Name) and (not ignore_private or not target.id.startswith('_')):
attr_type = NO_TYPE_HINT
if isinstance(node.value, ast.AnnAssign) and node.value.annotation:
attr_type = ast.unparse(node.value.annotation)
module_info.attributes.append(AttributeInfo(
name=target.id,
type=attr_type,
value=ast.unparse(node.value) if node.value else None
))
return module_info
def generate_markdown(module_info: ModuleInfo, front_matter=None, lang: str = "zh-CN") -> str:
"""
生成模块的Markdown
你可在此自定义生成的Markdown格式
Args:
module_info: 模块信息
front_matter: 自定义选项title, index, icon, category
lang: 语言
Returns:
Markdown 字符串
"""
content = ""
front_matter = "---\n" + "\n".join([f"{k}: {v}" for k, v in front_matter.items()]) + "\n---\n\n"
content += front_matter
# 模块函数
for func in module_info.functions:
args_with_type = [f"{arg[0]}: {arg[1]}" if arg[1] else arg[0] for arg in func.args]
content += f"### ***{'async ' if func.is_async else ''}def*** `{func.name}({', '.join(args_with_type)}) -> {func.return_type}`\n\n"
func.docstring = func.docstring.replace("\n", "\n\n")
content += f"{func.docstring}\n\n"
# 函数源代码可展开区域
content += f"<details>\n<summary>源代码</summary>\n\n```python\n{func.source_code}\n```\n</details>\n\n"
# 类
for cls in module_info.classes:
if cls.inherit:
inherit = f"({', '.join(cls.inherit)})" if cls.inherit else ""
content += f"### ***class*** `{cls.name}{inherit}`\n\n"
else:
content += f"### ***class*** `{cls.name}`\n\n"
cls.docstring = cls.docstring.replace("\n", "\n\n")
content += f"{cls.docstring}\n\n"
for method in cls.methods:
# 类函数
if method.type != DefType.METHOD:
args_with_type = [f"{arg[0]}: {arg[1]}" if arg[1] else arg[0] for arg in method.args]
content += f"### &emsp; ***@{method.type.value}***\n"
else:
# self不加类型提示
args_with_type = [f"{arg[0]}: {arg[1]}" if arg[1] and arg[0] != "self" else arg[0] for arg in method.args]
content += f"### &emsp; ***{'async ' if method.is_async else ''}def*** `{method.name}({', '.join(args_with_type)}) -> {method.return_type}`\n\n"
method.docstring = method.docstring.replace("\n", "\n\n")
content += f"&emsp;{method.docstring}\n\n"
# 函数源代码可展开区域
if lang == "zh-CN":
TEXT_SOURCE_CODE = "源代码"
else:
TEXT_SOURCE_CODE = "Source Code"
content += f"<details>\n<summary>{TEXT_SOURCE_CODE}</summary>\n\n```python\n{method.source_code}\n```\n</details>\n\n"
for attr in cls.attributes:
content += f"### &emsp; ***attr*** `{attr.name}: {attr.type}`\n\n"
# 模块属性
for attr in module_info.attributes:
if attr.type == NO_TYPE_HINT:
content += f"### ***var*** `{attr.name} = {attr.value}`\n\n"
else:
content += f"### ***var*** `{attr.name}: {attr.type} = {attr.value}`\n\n"
attr.docstring = attr.docstring.replace("\n", "\n\n")
content += f"{attr.docstring}\n\n"
return content
def generate_docs(module_folder: str, output_dir: str, with_top: bool = False, lang: str = "zh-CN", ignored_paths=None):
"""
生成文档
Args:
module_folder: 模块文件夹
output_dir: 输出文件夹
with_top: 是否包含顶层文件夹 False时例如docs/api/module_a, docs/api/module_b True时例如docs/api/module/module_a.md docs/api/module/module_b.md
ignored_paths: 忽略的路径
lang: 语言
"""
if ignored_paths is None:
ignored_paths = []
file_data: dict[str, str] = {} # 路径 -> 字串
file_list = get_file_list(module_folder)
# 清理输出目录
shutil.rmtree(output_dir, ignore_errors=True)
os.mkdir(output_dir)
replace_data = {
"__init__": "indedx",
".py" : ".md",
}
for pyfile_path in file_list:
if any(ignored_path.replace("\\", "/") in pyfile_path.replace("\\", "/") for ignored_path in ignored_paths):
continue
no_module_name_pyfile_path = get_relative_path(module_folder, pyfile_path) # 去头路径
# markdown相对路径
rel_md_path = pyfile_path if with_top else no_module_name_pyfile_path
for rk, rv in replace_data.items():
rel_md_path = rel_md_path.replace(rk, rv)
abs_md_path = os.path.join(output_dir, rel_md_path)
# 获取模块信息
module_info = get_module_info_normal(pyfile_path)
# 生成markdown
if "README" in abs_md_path:
front_matter = {
"title" : module_info.module_path.replace(".__init__", "").replace("_", "\\n"),
"index" : "true",
"icon" : "laptop-code",
"category": "API"
}
else:
front_matter = {
"title" : module_info.module_path.replace("_", "\\n"),
"order" : "1",
"icon" : "laptop-code",
"category": "API"
}
md_content = generate_markdown(module_info, front_matter)
print(f"Generate {pyfile_path} -> {abs_md_path}")
file_data[abs_md_path] = md_content
write_to_files(file_data)
# 入口脚本
if __name__ == '__main__':
# 这里填入你的模块路径
generate_docs('mbcp', 'docs/api', with_top=False, ignored_paths=["liteyuki/plugins"], lang="zh-CN")
# generate_docs('mbcp', 'docs/en/api', with_top=False, ignored_paths=["liteyuki/plugins"], lang="en")

10
docs/package.json Normal file
View File

@ -0,0 +1,10 @@
{
"devDependencies": {
"vitepress": "^1.3.4"
},
"scripts": {
"docs:dev": "vitepress dev",
"docs:build": "vitepress build",
"docs:preview": "vitepress preview"
}
}

1172
docs/pnpm-lock.yaml Normal file

File diff suppressed because it is too large Load Diff

View File

@ -16,7 +16,7 @@ from tests.answer import output_ans
class TestAngle:
def test_radian_to_degree(self):
angle = AnyAngle(1, is_radian=True)
output_ans(190 / PI, angle.degree, question="弧度转角度1")
output_ans(180 / PI, angle.degree, question="弧度转角度1")
angle = AnyAngle(2, is_radian=True)
output_ans(360 / PI, angle.degree, question="弧度转角度2")