mirror of
https://github.com/qwerfd2/OverRide-Server.git
synced 2026-10-05 13:27:57 +03:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
37be201756 | ||
|
|
771cc41d06 | ||
|
|
4b08430cf4 | ||
|
|
b190479d88 | ||
|
|
481c9ceab7 | ||
|
|
e3d7acfbf8 | ||
|
|
e42b987ecb | ||
|
|
0ea9684736 | ||
|
|
c6fe6dd7d6 | ||
|
|
964486fda0 |
@@ -1,12 +1,544 @@
|
||||
# OverRide-Server
|
||||
This is the server & package repo of a OverRapid mod that I made a while back. Open to all since the dev abandoned the game and is no longer adding new content.
|
||||
|
||||
这是Project OverRide的服务器和包体仓库。Project OverRide是一个基于OverRapid的模组,由于原开发者长期未更新内容,现公开。
|
||||
|
||||
<details>
|
||||
<summary>English</summary>
|
||||
<br>
|
||||
|
||||
## Why OverRide
|
||||
|
||||
This mod brings comprehensive feature updates, content, and bug fixes to the base game.
|
||||
|
||||
This non-exaustive list describes some of those.
|
||||
|
||||
- Added 14 removed songs (Lag train, rainshower, happy?, cancer, chaotic, after white, overprocess, unfactual factory, euphoric planet, dawn, sudden noise, night ocean fantasy, Metatron rebirth, hymn for U).
|
||||
|
||||
- Support for all 32 Arcane charts.
|
||||
|
||||
- Added 3 removed BGAs (xmas17, cosmic, decryptor).
|
||||
|
||||
- Added 2 removed Companions (doge, xmas17).
|
||||
|
||||
- Added 1 removed Gear (xmas17).
|
||||
|
||||
- Improved localization for all languages, and the game is localized to Simplified Chinese. (by improve, I mean that most image-based texts are changed to code based for better resolution and easier update. Korean and Japanese is mostly done by Google Translate, which is not ideal)
|
||||
|
||||
- Ability to connect to server directly (without proxy software)
|
||||
|
||||
- iOS, Android, and PC support.
|
||||
|
||||
- "Invisible Note" and speed up/down (0.8x - 1.2x) playstyle
|
||||
|
||||
- Added 10 achievements from season challenge 1.
|
||||
|
||||
- Added removed BGE for Outer Space.
|
||||
|
||||
- Officially supports project OverWrite (Missed charts for old songs) and save optimization.
|
||||
|
||||
- Added Hadron Kollider 4kpro (converted from 6k, very hard), and BGE support for all difficulties for H1V3.
|
||||
|
||||
- Revamped song unlock mechanism. Packs can be unlocked via RP and more songs are added to the level-up mechanism.
|
||||
|
||||
- Optimized and refactored game logic, removed redundant code, and optimized client and server assets.
|
||||
|
||||
- Added ability to restore save file via UID input at name prompt. Removed social OAUTH function.
|
||||
|
||||
- Supports download all charts and offsets via freeplay console.
|
||||
|
||||
- All functionality except leaderboard, download, ratings ranking, and PVP works offline. (must be connected at least once)
|
||||
|
||||
- Remade login client user flow. User need to create username first before downloading files.
|
||||
|
||||
- Ability to disable account creation, and ban user from server.
|
||||
|
||||
- Removed source code compilation and song encryption.
|
||||
|
||||
- Fixed multiple issues with TKR skin and allow detailed opacity customization through settings - BGA Opacity, and expanded the applicable song for Lanota BGE.
|
||||
|
||||
- TKR theme has been improved - switch over and check it out!
|
||||
|
||||
- Added Render The Over Stage theme (old application theme) that supports all modern features.
|
||||
|
||||
- Built in full fanmade chart support. Import on server, play on client solo or multiplayer immediately.
|
||||
|
||||
- General bug fixes.
|
||||
|
||||
## The Server
|
||||
|
||||
Simply get the code, download the asset, place the asset, edit `config.py`'s host and port, and run.
|
||||
Download the code and asset, unzip the asset in the server root directory.
|
||||
|
||||
## The Client
|
||||
## The Asset
|
||||
|
||||
Simply download the client, install/sideload, and run. Follow the UI to enter the `http(s)://HOST:PORT/`, and click continue.
|
||||
There are three folders of assets that you must set up before the server is functional.
|
||||
|
||||
Note. The package released carries the same security level as the official packages, from the official stores. Don't snoop around, but certainly have fun!
|
||||
They are all placed under the server root directory.
|
||||
|
||||
`OverRapid`: Contains music, chart, BGA, and config files. They are stable, and incremental.
|
||||
|
||||
`OverRide`: Skeleton folder for fanmade content. Typically, you don't need to mess with it.
|
||||
|
||||
`Resource`: Contains basic assets, such as images, movies, and transition audios. This is volatile, and the content inside can shift around as version progress.
|
||||
|
||||
Below are the Google Drive and Baidu Drive link to a folder, containing two zip files.
|
||||
|
||||
Download and unzip some or all of them to the root directory.
|
||||
|
||||
If this is your first time setting the server up, download both zip files.
|
||||
|
||||
If you are here for an upgrade, only download the `Resources` `素材包2` pack, delete the original `Resources` folder, and overwrite any conflicting files.
|
||||
|
||||
V8 Asset: [Google Drive](https://drive.google.com/drive/folders/1jR37N2wi6M1l0Eq1QeO-UkVtXPd-vkJt?usp=sharing) [Baidu Drive](https://pan.baidu.com/s/1jhzKBP3zP0dnfgcsLS1xGQ Code: AAAA)
|
||||
|
||||
After this, follow the Manual.
|
||||
|
||||
## Manual
|
||||
|
||||
<details>
|
||||
<summary>Click to expand</summary>
|
||||
<br>
|
||||
|
||||
### Preface
|
||||
|
||||
Please join QQ group (511974777) or use the issues section to report server and client issues.
|
||||
|
||||
### Server Setup and Connection
|
||||
|
||||
Download the server and respective platform's installation package from the group files/github release.
|
||||
|
||||
Unzip the server to your PC or MAC (referred to as the machine) and install the application package to your mobile device (referred to as the device). ~~Linux users should help themselves lol~~
|
||||
|
||||
Android package has been renamed and icon replaced to allow better distinction with the official client. You need jailbroken devices and tools such as trollstore to install on iOS.
|
||||
|
||||
Install ```python``` and ```pip``` on your machine. To install ```pip``` on MAC, you can use
|
||||
|
||||
```
|
||||
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
|
||||
python3 get-pip.py
|
||||
```
|
||||
|
||||
Note that MAC uses ```python3```. Code examples in this document will use the default of Windows, which is ```python```. After the installation, install dependencies using ```pip install requirements.txt```
|
||||
|
||||
After it is installed, make sure your machine and device are under the same subnetwork, such as wifi. Open ``cmd`` on PC and type ``ipconfig``. Open ``terminal`` on MAC and type ``ifconfig``.
|
||||
|
||||
Use the output to find the machine's subnet IPV4. Open ```config.py``` inside the server folder and change the IP address to the one you just got. Change the port as you please.
|
||||
|
||||
Open cmd in the server directory and type ```python metadata.py```. This will generate the up-to-date metadata file. Then, run ```python 5002.py```. Wait a moment. Once the server started, Open the app on your device.
|
||||
|
||||
In the Connection UI, enter the server's ```http://ip:port/``` according to the specification.
|
||||
|
||||
Click OK, and enter a username, or an existing 24-digit ```UID``` (covered in the "Advanced" section).
|
||||
|
||||
Download all the resources and enter the game.
|
||||
|
||||
### Advanced
|
||||
|
||||
#### Log in using ```UID```:
|
||||
|
||||
Use if you have registered before and would like to set up a new device with it.
|
||||
|
||||
Go to the settings page on your old device. Click the "Account" text under the "Account Settings" header 4 times. Your ```UID``` will be displayed and can be saved via screenshot. Go to the new device, enter the ```UID``` on the username page, and click OK.
|
||||
|
||||
You can also find the ```UID``` by opening ```player.db``` using ```DB Browser```.
|
||||
|
||||
#### Adding currency
|
||||
|
||||
Currently, the game grants unlimited currency. In case that was changed in the future, you can issue a redemption code in the database with the following `item`: `[{"item": "rp", "value": "99999"}]`.
|
||||
|
||||
#### Disable registration
|
||||
|
||||
Set ```REGISTRATION``` in ```config.py``` to ```False```. Account can only be restored via UID after this is turned off.
|
||||
|
||||
#### Ban user
|
||||
|
||||
Open ```player.db``` using ```DB Browser``` and go to the specific player. change the ```banned``` value. 0 means not banned. 1 means the user cannot change their nickname nor submit scores to leaderboard. If the value is a string, the user will be prompted the string as the reason of their ban, and the client will close after the the text prompt is shown (after intro video is done).
|
||||
|
||||
#### Reset leaderboard
|
||||
|
||||
clear the ```rank``` table of the database.
|
||||
|
||||
|
||||
</details>
|
||||
|
||||
## Fanmade
|
||||
|
||||
`OverRide` uses `BMS` charting specification. Audio playbacks are overwritten (keysound will not work, and the sound files specified within the chart file is ignored). Channel 0, 1, 2 are the left 3 lanes, 3, 4 are scratch lanes for left and right, and 5, 6, 7 are the right 3 lanes. Speed changes can be specified using BMS's built in `bpm` channel, horizontal white lines are defined in channel 9.
|
||||
|
||||
Chart reversals require special flag `0B` and `0C` - the effect is enabled for two songs (`miserable` and `tkr`) on the official listing, and all charts on the fanmade listing.
|
||||
|
||||
Two ways to make charts:
|
||||
|
||||
1. Use OSU! Mania to make 8k or 6k charts and convert the ```.osu``` file to ```.bms```. The conversion tool is in the group file. Note: Use text editor to remove negative value ```TimingPoint``` from the ```.osu``` charts, or the tool will report error. After conversion, use a text editor to replace all ```ZZ``` to ```01```. After that, open the ```.bms``` chart with ```pBMsc``` to fix and modify. The chart should not contain non-01 value.
|
||||
|
||||
2. Use Malody to make 8k or 6k charts and convert the file to ```.osu```, then convert to `bms`. [code](https://github.com/Jakads/malody2osu)
|
||||
|
||||
// I will leave the actual charting to the professionals
|
||||
|
||||
You should have a ```mp3``` file and ```bms``` charts.
|
||||
|
||||
Make a ```id``` string for the song. Don't worry about collisions, as ```importer``` can address these. Find a thumbnail and name it ```id.jpg/png```.
|
||||
Rename the charts to ```id_difficulty.bms```. Supported difficulties are ```EL,EX,PR,LPR,EL4,EX4,PR4```
|
||||
|
||||
Place charts to ```note``` folder. Place the thumbnail to ```thumbs``` folder. Place the music to ```music``` folder.
|
||||
|
||||
That's it for files. Next, let's modify ```manifest.json```.
|
||||
|
||||
```
|
||||
[
|
||||
{
|
||||
"id": 1, // Ignore
|
||||
"title": "Music Name", // Music title
|
||||
"artist": "Music Artist", //Musician
|
||||
"isJapanese": false, //Use Japanese display mode
|
||||
"bpm": 167, //bpm number
|
||||
"sync_6k": "0/0/0/-1400", //Chart offset values. 6k: EL,EX,LPR,PR. 4k: EL,EX,PR.
|
||||
"sync_4k": "0/0/0",
|
||||
"diff_6k": "0/0/0/18", // Chart difficulty。If not charted, use 0.
|
||||
"diff_4k": "0/0/0",
|
||||
"charter_6k": "-/-/-/charterA", //Charter information
|
||||
"charter_4k": "-/-/-",
|
||||
"mp3": "song", //Song ID.
|
||||
"preview": "-1/-1", //Start time of 2 music previews, in seconds.
|
||||
"bga": "-1400/24/3559" // Delete this line if no BGA is available
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
If you wish to make BGA, see section below. If not, delete the ```bga``` field.
|
||||
|
||||
That's it for the manifest. Select all files and folders, and compress to ```zip```. See "Adding Charts" section for chart importing.
|
||||
|
||||
#### Importer File Checking
|
||||
|
||||
`importer` will conduct basic check for the zip file. If the check is passed, only the necessary files will be copied to the server. 5 checks are conducted:
|
||||
|
||||
0. At least one chart should be defined in config.
|
||||
|
||||
Example: `diff_6k` and `diff_4k` not all zeroes.
|
||||
|
||||
1. A correctly named jpg or png should be in the thumbs folder.
|
||||
|
||||
Example: If the song ID is ```test```, a ```test.jpg``` or ```test.png``` should exist.
|
||||
|
||||
2. The correctly named mp3 should be in the music folder.
|
||||
|
||||
Example: If the song ID is ```test```, a ```test.mp3``` should exist.
|
||||
|
||||
3. If the manifest contains bga section, the bga zip file should be in the bga folder.
|
||||
|
||||
Example: If the song ID is ```test``` and has a ```bga``` section in manifest, a ```test.zip``` should exist.
|
||||
|
||||
4. If the manifest does not have bga, there should not be a bga zip file in the bga folder.
|
||||
|
||||
Example: If song ID ```test``` does not have ```bga``` section in manifest, ```test.zip``` should not exist. Note: Did you forget to add the bga to manifest?
|
||||
|
||||
5. All difficulties specified in the manifest should have a corresponding note file in the note folder.
|
||||
|
||||
Example: Song ID is ```test``` and manifest specifies multiple non-zero difficulties. All charts should exist.
|
||||
|
||||
### Making BGA
|
||||
|
||||
Download the MP4 from YouTube or other platforms. 360p is enough.
|
||||
|
||||
Put the video in the folder from the archive. Remember to ```pip install opencv-python```
|
||||
|
||||
Open ```cmd``` in the directory and type ```python v2b.py```
|
||||
|
||||
Follow the instructions. ```fps``` are typically 15 or 24. After the frames are extracted, go to the output folder and remove the black frame at the start and end to save some space.
|
||||
|
||||
ZIP all the images and fill the ```bga``` section of the manifest.
|
||||
|
||||
The 1st number is the millisecond offset. The 2nd number is the frame rate. The 3rd number is the frame number of the last frame.
|
||||
|
||||
Add the zip archive to the bga directory.
|
||||
|
||||
### Addendium for OverRide
|
||||
|
||||
In addition to the respective github repo, the tooling is also available in the `tools` folder. There is also this minimal client-server setup for fanmade charting specifically [Fanmade Server](https://github.com/qwerfd2/OverRapid-Fanmade-Server/)
|
||||
|
||||
That project is technically separate from Project OverRide, since that one is specifically designed for fanmade and carries some merit for that purpose (minimal server and client asset, essential assets are local, server only used for fanmade assets delivery, no official content), although it still requires a server to be set up (flask, not starlette).
|
||||
|
||||
Note: Although the fanmade chart package format is the exact same, the `importer.py` from the fanmade repo is NOT COMPATIBLE with Project OverRide. Project OverRide requires several additional considerations during implementation (collision with official listing and local assets, asset cleanup, compatibility with official manifest format), which means that although the tooling does the same thing, they way they achieved it is very different.
|
||||
|
||||
When importing a chart, you do not need to worry about:
|
||||
|
||||
1. The `mp3` value colliding with the official listing - everything is stored in either a different location or uses a different format;
|
||||
|
||||
2. Residual local assets if a fanmade song is deleted server-side - music, chart, and bga are automatically deleted if the manifest change is detected;
|
||||
|
||||
Note that the game client never had a way to customize per-song sync offset. That is done exclusively server-side, via `OverRide/playmanifest.json`.
|
||||
|
||||
`CNG`/`ARC`/`BRK` Difficulty is not supported for fanmade charts.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>中文</summary>
|
||||
<br>
|
||||
|
||||
## 为什么要OverRide
|
||||
|
||||
这个魔改带来了全新功能更新,内容,和bug修复。
|
||||
如下是不全面的列表,描述了一些功能。
|
||||
|
||||
- 添加14首移除曲目 (Lag train, rainshower, happy?, cancer, chaotic, after white, overprocess, unfactual factory, euphoric planet, dawn, sudden noise, night ocean fantasy, Metatron rebirth, hymn for U)。
|
||||
|
||||
- 支持全部32个Arcane谱面。
|
||||
|
||||
- 添加3个移除的BGA (xmas17, cosmic, decryptor)。
|
||||
|
||||
- 添加2个移除的头像 (doge, xmas17)。
|
||||
|
||||
- 添加1个移除的皮肤 (xmas17)。
|
||||
|
||||
- 优化所有语言的本地化,支持简体中文。(优化是指把原版的文字图片替换成了代码,以获得清晰度并降低修改难度。日语和韩语是用Google翻译的 - 不是很理想)
|
||||
|
||||
- 可以直连私服,不需要中继软件。
|
||||
|
||||
- iOS, 安卓, 和 PC 支持。
|
||||
|
||||
- "隐形音符" 和加减速 (0.8x - 1.2x) 玩法。
|
||||
|
||||
- 添加了10个来自季节挑战的。。。挑战。
|
||||
|
||||
- 添加了 Outer Space 的BGE.
|
||||
|
||||
- 官方支持 Project OverWrite 和存档优化功能。
|
||||
|
||||
- 添加了Hadron Kollider的4k难度(超难),和H1V3的全难度特效支持。
|
||||
|
||||
- 重做解歌系统。曲包可用RP解锁,玩家等级解锁添加更多曲目。
|
||||
|
||||
- 优化游戏逻辑,删除无用代码,优化服务器和安装包资源。
|
||||
|
||||
- 支持通过UID恢复存档。移除社交媒体OAUTH功能。
|
||||
|
||||
- 支持通过FP控制台下载所有谱面和偏移值。
|
||||
|
||||
- 除了分数排行榜,文件下载,评级排行榜,和PVP,所有功能离线均可用。(必须先联网下载全部数据)
|
||||
|
||||
- 重做客户端登录流程。用户需要先起名才能下载资源。
|
||||
|
||||
- 可以关闭账号注册功能,也可以封禁用户。
|
||||
|
||||
- 移除歌曲文件加密和源码编译。
|
||||
|
||||
- 修复TKR皮肤的若干问题,透明度可通过BGA透明度自定义,调整Lanota BGE受用的曲目。
|
||||
|
||||
- TKR重制-快切换过去看看吧!
|
||||
|
||||
- 添加Render The Over Stage主题(老版本主题),支持全部新功能。
|
||||
|
||||
- 内置完备的自制谱支持。服务器导入,立刻在客户端单机或多人游玩。
|
||||
|
||||
- 修复Bug。
|
||||
|
||||
## 服务器
|
||||
|
||||
下载所有代码和资源,把资源解压到服务器根目录。
|
||||
|
||||
## 资源
|
||||
|
||||
在服务器可用前,有三个需要配置的文件夹。
|
||||
|
||||
都位于根目录下。
|
||||
|
||||
|
||||
`OverRapid`: 包括音乐,谱面,BGA,和配置文件。稳定,可以版本更新。
|
||||
|
||||
`OverRide`: 自制内容的初始文件夹。不需要担心。
|
||||
|
||||
`Resource`: 包括基础素材,比如图像,视频,和音频。不稳定,可能出现很多变化。
|
||||
|
||||
如下Google Drive和百度网盘链接指向一个文件夹,包括两个zip文档。
|
||||
|
||||
根据需求,下载一个或全部并解压到服务器根目录。
|
||||
|
||||
如果这是你第一次配置服务器,全部下载。
|
||||
|
||||
如果你是来这里更新的,那么可以仅下载`Resources` `素材包2`。把老的`Resources`文件夹删掉,覆盖任何冲突内容。
|
||||
|
||||
V8 资源: [Google Drive](https://drive.google.com/drive/folders/1jR37N2wi6M1l0Eq1QeO-UkVtXPd-vkJt?usp=sharing) [Baidu Drive](https://pan.baidu.com/s/1jhzKBP3zP0dnfgcsLS1xGQ Code: AAAA)
|
||||
|
||||
之后,跟随使用手册配置。
|
||||
|
||||
## 使用手册
|
||||
|
||||
<details>
|
||||
<summary>点击放大</summary>
|
||||
<br>
|
||||
|
||||
### 前言
|
||||
|
||||
如有错漏敬请加群(511974777)联系。欢迎使用Github Issues汇报服务器及客户端错误。
|
||||
|
||||
### 搭建服务器和连接
|
||||
|
||||
|
||||
群文件或Github Release下载服务器,下载对应平台的安装包。
|
||||
|
||||
PC 或 MAC(统称主机)解压服务器,~~linux 自己去搞(~~
|
||||
|
||||
设备安装下载好的安装包。 Android 已修改包名和图标,不会和官方冲突。iOS 需要 trollstore 之类的 jailbroken 工具。
|
||||
|
||||
主机安装 ```python```,安装 ```pip```。MAC 安装 ```pip``` 可使用
|
||||
|
||||
```
|
||||
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
|
||||
python3 get-pip.py
|
||||
```
|
||||
|
||||
注意 MAC 默认为 ```python3```。往后的示例默认用 windows 的默认,即 ```python```。安装完成后 ```pip install requirements.txt```
|
||||
|
||||
安装完成后,设备和主机确认在同一子网下,例如 wifi。
|
||||
|
||||
PC 打开 ```cmd``` 输入 ```ipconfig```。MAC 打开 ```terminal``` 输入 ```ifconfig```。进而找到本机的子网 IPV4。
|
||||
主机打开服务器文件夹的 ```config.py``` 修改 IP 地址。Port 也可以更改。
|
||||
|
||||
服务器文件夹内 ```cmd``` 输入 ```python metadata.py``` 生成最新metadata文件。然后执行 ```python 5002.py```,等一小会。跑起来之后,设备打开程序.
|
||||
|
||||
接下来的连接窗口,按照格式输入服务器的 ```http://ip:port/```
|
||||
|
||||
点击 OK,输入用户名或已有的 24 位 ```UID```(高级操作章节)。下载资源,进入游戏。
|
||||
|
||||
### 高级操作
|
||||
|
||||
#### 使用 ```UID``` 登录:
|
||||
|
||||
你之前注册过账号,并想用这个账号在新设备上玩。
|
||||
|
||||
进入老设备的设置页面。点击 账号设置 下的标题文字 账号 4 次。```UID``` 将显示,可以截屏保存。在新的设备上的登陆界面输入 ```UID```,点击确认。
|
||||
|
||||
你也可以用```DB Browser```打开```player.db```来寻找```UID```。
|
||||
|
||||
#### 添加货币
|
||||
|
||||
目前,游戏给予无限货币。若以后发生改变,可以使用兑换码机制来添加货币。在数据库添加一个兑换码,`item`为`[{"item": "rp", "value": "99999"}]`。
|
||||
|
||||
#### 关闭注册
|
||||
|
||||
把```config.py```里的```REGISTRATION```设成```False```。如果关闭,只能通过UID恢复已有账号来开始游戏。
|
||||
|
||||
#### 封禁用户
|
||||
|
||||
用```DB Browser```打开```player.db```。找到该用户。修改```banned```数值。0代表不封禁。1代表禁止昵称修改并禁止排行榜分数上传。如果数值是字符串,玩家在开场视频结束后将被提示封禁,该字符串将显示给玩家,作为封禁理由。客户端将会关闭。
|
||||
|
||||
#### 重置排行榜
|
||||
|
||||
清除```rank```数据库表。
|
||||
|
||||
</details>
|
||||
|
||||
## 自制
|
||||
|
||||
```OverRide``` 使用 ```BMS``` 谱面格式。音频播放不可用(按键音不可用,谱面文件内的音频被无视)。0, 1, 2 轨为左侧 3 轨,3, 4 为左右划键,5, 6, 7 为右侧 3 轨。变速可在谱面内通过`BPM`轨设定,水平白线通过9轨设定。
|
||||
|
||||
谱面倒退可以通过 ```0B``` 和 ```0C``` 来指定 - 官方列表只有两首可以使用(`miserable` 和 `tkr`),自制没有限制。
|
||||
|
||||
目前的两个制谱方式:
|
||||
|
||||
1. 通过 OSU! Mania 制 8k/6k 谱并将 ```.osu``` 文件转至 ```.bms```。转码工具在群文件里。注意事项:提前用文本编辑器删除负值 ```TimingPoint```,否则工具会报错。转码后用文本编辑器将所有 ```ZZ``` 变成 01. 之后用 ```pBMsc``` 打开 ```bms``` 进行修改修复并保存。谱面内不应出现非 01 的值。
|
||||
|
||||
2. 通过 Malody 制 8k/6k 谱并将谱面转至 ```.osu```, 再使用上述方法转至 `bms`. [代码](https://github.com/Jakads/malody2osu)
|
||||
|
||||
//具体制谱思路让专业的来写(
|
||||
|
||||
现在,你应该有歌曲的 ```mp3``` 音乐文件,和 ```bms``` 谱面。
|
||||
|
||||
给歌曲定个 ```id``` 字符串。不用担心和别人重名,如果使用 ```importer``` 导入会自动解决。找到歌曲的封面并重命名为 歌曲 ```id.jpg/png```.
|
||||
将谱面重命名为 ```id_难度.bms```,支持的难度为 ```EL,EX,PR,LPR,EL4,EX4,PR4```.
|
||||
谱面放到 ```note``` 文件夹。歌曲封面放到 ```thumbs```。音乐文件放到 ```music```。不要放无关的文件。至此,文件安放完毕。接下来要修改 ```manifest.json```.
|
||||
|
||||
```
|
||||
[
|
||||
{
|
||||
"id": 1, // 无视
|
||||
"title": "Music Name", // 曲名
|
||||
"artist": "Music Artist", //曲师
|
||||
"isJapanese": false, //是否用日语模式显示
|
||||
"bpm": 167, //bpm 数字
|
||||
"sync_6k": "0/0/0/-1400", //谱面偏移值. 6k: EL,EX,LPR,PR. 4k: EL,EX,PR.
|
||||
"sync_4k": "0/0/0",
|
||||
"diff_6k": "0/0/0/18", // 谱面难度。如果没有谱面填 0.
|
||||
"diff_4k": "0/0/0",
|
||||
"charter_6k": "-/-/-/charterA", //谱师信息
|
||||
"charter_4k": "-/-/-",
|
||||
"mp3": "song", //歌曲 ID。
|
||||
"preview": "-1/-1", //两段音乐 preview 开始时间,以秒计
|
||||
"bga": "-1400/24/3559" //如曲目没有BGA删除此行
|
||||
}
|
||||
]
|
||||
|
||||
```
|
||||
|
||||
如果想做 BGA 可以参考下方。如果不想做必须删除 ```bga``` 行。
|
||||
|
||||
至此,```manifest``` 编辑完成。全选所有文件夹和 ```manifest.json```,压缩成 ```zip```。
|
||||
|
||||
导入可以参考“添加谱面”章节。
|
||||
|
||||
### Importer 文件检查
|
||||
|
||||
|
||||
```importer``` 会对包体进行基本检查。如果检查通过,只会将需要的文件拷贝到服务器里。总共检查 5 项内容:
|
||||
|
||||
0. 配置文件中至少要有一个谱面难度。
|
||||
|
||||
举例:`diff_4k`和`diff_6k`不能全是0.
|
||||
|
||||
1. 至少一个正确命名的 jpg 或 png 图片应该在 thumbs 文件夹里。
|
||||
|
||||
举例:如果歌曲 ID:```test```,```test.jpg``` 或者 ```test.png``` 应该存在。
|
||||
|
||||
2. 正确命名的 MP3 文件应该在 music 文件夹里。
|
||||
|
||||
举例:如果歌曲 ID:```test```,```test.mp3``` 应该存在。
|
||||
|
||||
3. 如果 manifest 里有 bga,则 bga 压缩包应该在 bga 文件夹里。
|
||||
|
||||
举例:如果歌曲 ID:```test``` 且 manifest 里有 ```bga``` 行,```test.zip``` 应该存在。
|
||||
|
||||
4. 如果 manifest 里没有 ```bga``` 而 ```bga``` 文件夹里存在 ```bga``` 压缩包。虽然不会出现错误程序也会提示。
|
||||
|
||||
举例:歌曲 ID:```test``` 且 manifest 里没有 ```bga``` 行,而 ```test.zip``` 存在。是不是忘写进 manifest 了?
|
||||
|
||||
5. 写进 manifest 的谱面难度应该都在 note 文件夹里。
|
||||
|
||||
举例:歌曲 ID:```test``` 且 manifest 里写明有多个非 0 难度,而 ```note``` 里缺少谱面。
|
||||
|
||||
|
||||
### 制作 BGA
|
||||
|
||||
油管或者其他平台下载视频 MP4 文件。清晰度只要是 360p 以上就行。
|
||||
|
||||
将视频文件放到解压的文件夹里。记得 ```pip install opencv-python```
|
||||
|
||||
文件夹内 ```cmd``` 输入 ```python v2b.py```
|
||||
|
||||
根据提示操作,一般 ```fps``` 为 15 或 24. 完成后进入文件夹,删除黑屏的帧来节省空间。
|
||||
|
||||
所有图片压 zip 包,填写 manifest 里的 ```bga```。
|
||||
|
||||
第一个数字为毫秒偏移。第二个数字为帧率。第三个数字为最后一帧的数字。将压好的 zip 包放到 ```bga``` 文件夹里。
|
||||
|
||||
|
||||
### OverRide附加内容
|
||||
|
||||
上面描述的工具既可以在他们自己的仓库下载,也可以在本仓库的`tools`文件夹找到。还有一个更袖珍的客户端-服务器方案,专为自制谱设计。[自制服务器](https://github.com/qwerfd2/OverRapid-Fanmade-Server/)
|
||||
|
||||
这个项目之所以和OverRide区分开,是因为它专为自制设计,有些独有的优势(最小化客户端和服务器资源,必要资源内置无需下载,服务器仅用作自制文件运输,无官方内容),尽管这个方案仍需要一个服务器(`flask`而不是`starlette`)
|
||||
|
||||
提示:尽管自制导入的文件完全一样,自制服务器的`importer.py`不可和此项目的`importer.py`混用。在这里,有一些特殊的考量(和官方列表和文件的冲突,资源清理,列表兼容),导致具体实施完全不同。
|
||||
|
||||
在导入时,不需要担心:
|
||||
|
||||
1. `mp3`和官方重叠 - 所有文件和配置都要么存在不同的地方,要么使用了不同的格式;
|
||||
|
||||
2. 服务器删曲后本地资源留存 - 当列表变化到达本地,音乐,谱面,和bga将被自动删除;
|
||||
|
||||
注意,客户端从没有具体谱面偏移调整保存的能力 - 这是服务器端功能,需要通过修改`OverRide/playmanifest.json`来实现。
|
||||
|
||||
自制不支持 `CNG`/`ARC`/`BRK` 难度。
|
||||
|
||||
</details>
|
||||
|
||||
+15
-12
@@ -2,6 +2,7 @@ from starlette.applications import Starlette
|
||||
from starlette.responses import FileResponse, Response, JSONResponse
|
||||
from starlette.routing import Route
|
||||
from starlette.requests import Request
|
||||
import contextlib
|
||||
import os
|
||||
import databases
|
||||
import sqlalchemy
|
||||
@@ -85,7 +86,7 @@ async def set_player_data(user_id, data_field, new_data):
|
||||
# ------------ CDN -------------
|
||||
|
||||
root_folder = os.path.dirname(os.path.abspath(__file__))
|
||||
allowed_folders = ["OverRapid", "Resources"]
|
||||
allowed_folders = ["OverRapid", "Resources", "OverRide"]
|
||||
|
||||
async def serve_file(request):
|
||||
path = request.path_params['path']
|
||||
@@ -154,14 +155,12 @@ async def api_function(request: Request):
|
||||
try:
|
||||
score = float(content_dict.get("score", ""))
|
||||
except ValueError:
|
||||
print("parse failed")
|
||||
return JSONResponse({"dummy": False}, status_code=400)
|
||||
print(player_info['rating'])
|
||||
|
||||
if player_info['rating'] is not None:
|
||||
await set_player_data(user_id, "rating", score)
|
||||
return JSONResponse({"dummy": True})
|
||||
else:
|
||||
print("else failed")
|
||||
return JSONResponse({"dummy": False}, status_code=400)
|
||||
|
||||
elif name == "rename":
|
||||
@@ -291,7 +290,8 @@ async def pvp_function(request: Request):
|
||||
lobby_data = {
|
||||
"data": {
|
||||
"mp3": data.get("mp3", ""),
|
||||
"diff": data.get("diff", "")
|
||||
"diff": data.get("diff", ""),
|
||||
"fm": data.get("fm", False),
|
||||
},
|
||||
"timestamp": int(time.time()),
|
||||
"players": {
|
||||
@@ -383,6 +383,9 @@ async def pvp_function(request: Request):
|
||||
return JSONResponse(lobby["match"])
|
||||
else:
|
||||
return JSONResponse({})
|
||||
|
||||
else:
|
||||
return JSONResponse({})
|
||||
|
||||
routes = [
|
||||
Route("/Api", api_function, methods=["POST"]),
|
||||
@@ -391,16 +394,16 @@ routes = [
|
||||
|
||||
routes.append(Route("/{path:path}", serve_file))
|
||||
|
||||
app = Starlette(debug=DEBUG, routes=routes)
|
||||
|
||||
@app.on_event("startup")
|
||||
async def startup():
|
||||
@contextlib.asynccontextmanager
|
||||
async def lifespan(app: Starlette):
|
||||
await database.connect()
|
||||
await init_db()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
await database.disconnect()
|
||||
|
||||
@app.on_event("shutdown")
|
||||
async def shutdown():
|
||||
await database.disconnect()
|
||||
app = Starlette(debug=DEBUG, routes=routes, lifespan=lifespan)
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
@@ -0,0 +1,368 @@
|
||||
import os
|
||||
import zipfile
|
||||
import json
|
||||
import shutil
|
||||
import hashlib
|
||||
from PIL import Image
|
||||
|
||||
def calculate_md5_and_size(file_path):
|
||||
md5_hash = hashlib.md5()
|
||||
file_size = 0
|
||||
|
||||
with open(file_path, "rb") as file:
|
||||
for byte_block in iter(lambda: file.read(4096), b""):
|
||||
md5_hash.update(byte_block)
|
||||
file_size += len(byte_block)
|
||||
|
||||
return md5_hash.hexdigest(), file_size
|
||||
|
||||
def process_folder(folder_path):
|
||||
md5_checksum_dict = {}
|
||||
size_dict = {}
|
||||
|
||||
for root, dirs, files in os.walk(folder_path):
|
||||
for file_name in files:
|
||||
file_path = os.path.join(root, file_name)
|
||||
relative_path = os.path.relpath(file_path, folder_path)
|
||||
|
||||
md5_checksum, file_size = calculate_md5_and_size(file_path)
|
||||
|
||||
md5_checksum_dict[relative_path.replace("\\", "/")] = md5_checksum
|
||||
size_dict[relative_path.replace("\\", "/")] = file_size
|
||||
|
||||
return md5_checksum_dict, size_dict
|
||||
|
||||
def write_to_file(file_name, data):
|
||||
with open(file_name, "w") as file:
|
||||
file.write(json.dumps(data, separators=(',', ':')))
|
||||
|
||||
def get_unique_song_file(existing_songs, song_file):
|
||||
counter = 1
|
||||
unique_song_file = song_file
|
||||
while unique_song_file in existing_songs:
|
||||
unique_song_file = f"{song_file}{counter}"
|
||||
counter += 1
|
||||
return unique_song_file
|
||||
|
||||
def get_chart_list(dir, manifest):
|
||||
chart_6k = manifest.get("diff_6k").split('/')
|
||||
chart_4k = manifest.get("diff_4k").split('/')
|
||||
dir_list = []
|
||||
all_chart = chart_6k + chart_4k
|
||||
diff_table = ["_EL.bms", "_EX.bms", "_LPR.bms", "_PR.bms", "_EL4.bms", "_EX4.bms", "_PR4.bms"]
|
||||
for i in range(len(all_chart)):
|
||||
if all_chart[i] != "0":
|
||||
path = os.path.join(dir, "note", manifest.get("mp3") + diff_table[i])
|
||||
dir_list.append(path)
|
||||
return dir_list
|
||||
|
||||
def deleteChart(song_id):
|
||||
|
||||
# Find the song manifest to remove.
|
||||
|
||||
playmanifest_path = "OverRide/playmanifest.json"
|
||||
with open(playmanifest_path, 'r', encoding="utf-8") as f:
|
||||
playmanifest = json.load(f)
|
||||
|
||||
manifest_to_remove = None
|
||||
for manifest in playmanifest:
|
||||
if manifest[0].get("id") == song_id:
|
||||
manifest_to_remove = manifest
|
||||
break
|
||||
|
||||
# We now have the manifest to remove, which is aquired after looping through the main manifest.
|
||||
|
||||
if manifest_to_remove is None:
|
||||
print("That song ID not found. 没有找到此歌曲ID。")
|
||||
return
|
||||
|
||||
# Confirm with the user one last time by printing out some useful data.
|
||||
|
||||
song_title = manifest_to_remove[0].get("title")
|
||||
diff_str = manifest_to_remove[0].get("diff_6k") + "/" + manifest_to_remove[0].get("diff_4k")
|
||||
charter = manifest_to_remove[0].get("charter_6k") + "/" + manifest_to_remove[0].get("charter_4k")
|
||||
print(f"Are you sure you want to delete the song '{song_title}', difficulty '{diff_str}', charted by '{charter}'?")
|
||||
print(f"你确定要删除这首歌吗?名为 '{song_title}',难度 '{diff_str}',谱师为 '{charter}'?")
|
||||
confirm = input("(y/n): ")
|
||||
if confirm.lower() != 'y':
|
||||
print("Deletion cancelled. 删除终止。")
|
||||
return
|
||||
|
||||
song_name = manifest_to_remove[0].get("mp3")
|
||||
|
||||
# Remove everything but the chart.
|
||||
|
||||
paths_to_check = [
|
||||
(os.path.join("OverRide", "bga", f"{song_name}.zip"), False),
|
||||
(os.path.join("OverRide", "music", f"{song_name}"), False),
|
||||
(os.path.join("Resources", "data_fm", f"{song_name}.jpg"), False),
|
||||
(os.path.join("Resources", "data_fm", f"255{song_name}.jpg"), False),
|
||||
]
|
||||
|
||||
for path, _ in paths_to_check:
|
||||
if os.path.exists(path):
|
||||
os.remove(path)
|
||||
|
||||
# Remove charts
|
||||
|
||||
charts = get_chart_list(os.path.join("OverRide"), manifest_to_remove[0])
|
||||
|
||||
for chart in charts:
|
||||
chart = chart.replace(".bms", "")
|
||||
if os.path.exists(chart):
|
||||
os.remove(chart)
|
||||
|
||||
# Remove the charts from the zip.
|
||||
|
||||
note_zip_path = os.path.join("OverRide", "Note.zip")
|
||||
if os.path.exists(note_zip_path):
|
||||
temp_zip_path = os.path.join("OverRide", "temp_Note.zip")
|
||||
with zipfile.ZipFile(note_zip_path, 'r') as note_zip:
|
||||
with zipfile.ZipFile(temp_zip_path, 'w') as temp_zip:
|
||||
for item in note_zip.infolist():
|
||||
check_name = "offlineNote_" + song_name + "_"
|
||||
file_name = item.filename
|
||||
if not file_name.startswith(check_name):
|
||||
# write file
|
||||
temp_zip.writestr(item, note_zip.read(item.filename))
|
||||
|
||||
os.remove(note_zip_path)
|
||||
os.rename(temp_zip_path, note_zip_path)
|
||||
|
||||
# Remove the manifest, and refresh the metadata.
|
||||
|
||||
playmanifest.remove(manifest_to_remove)
|
||||
with open(playmanifest_path, 'w', encoding="utf-8") as f:
|
||||
json.dump(playmanifest, f, indent=4)
|
||||
|
||||
# Correct the main sync and metadata.
|
||||
update_metadata()
|
||||
print("Song has been deleted from the server. 歌曲已从服务器删除。")
|
||||
|
||||
def importChart(name):
|
||||
|
||||
# Create a temp directory for unzipping the provided zip file.
|
||||
|
||||
extract_to = "_temp"
|
||||
if os.path.exists(extract_to):
|
||||
shutil.rmtree(extract_to)
|
||||
os.makedirs(extract_to)
|
||||
|
||||
if not os.path.isfile(name):
|
||||
print(f"Error: The file '{name}' does not exist.")
|
||||
return
|
||||
|
||||
# Safely opens the zip file.
|
||||
|
||||
try:
|
||||
with zipfile.ZipFile(name, 'r') as zip_ref:
|
||||
zip_ref.extractall(extract_to)
|
||||
except zipfile.BadZipFile:
|
||||
print(f"Error: '{name}' is not a valid zip file.")
|
||||
return
|
||||
except PermissionError:
|
||||
print(f"Error: Permission denied. Check your permissions for '{extract_to}'.")
|
||||
return
|
||||
except Exception as e:
|
||||
print(f"An unexpected error occurred when unzipping: {e}")
|
||||
return
|
||||
|
||||
# Safely read the song manifest
|
||||
|
||||
manifest_path = os.path.join(extract_to, "manifest.json")
|
||||
|
||||
if not os.path.isfile(manifest_path):
|
||||
print(f"Error: The file '{manifest_path}' does not exist.")
|
||||
return
|
||||
try:
|
||||
with open(manifest_path, 'r', encoding='utf-8') as f:
|
||||
manifest = json.load(f)
|
||||
except Exception as e:
|
||||
print(f"JSON parse failed for manifest failed: {e}")
|
||||
return
|
||||
|
||||
for song in manifest:
|
||||
song_file = song.get("mp3")
|
||||
|
||||
# get list of charts
|
||||
|
||||
charts = get_chart_list(extract_to, song)
|
||||
|
||||
# Sanity check everything
|
||||
# (0): at least one chart should be present in the config.
|
||||
|
||||
standard_check = True
|
||||
reason_fail = ""
|
||||
|
||||
if charts == []:
|
||||
standard_check = False
|
||||
reason_fail += "\nNo charts found in the chart config this song (all zeroes). "
|
||||
|
||||
bga_data = song.get("bga")
|
||||
|
||||
# (1): either the jpg and png version of the thumbnail should exist.
|
||||
|
||||
img1_path = os.path.join(os.path.join(extract_to, "thumbs"), f"{song_file}.jpg")
|
||||
img2_path = os.path.join(os.path.join(extract_to, "thumbs"), f"{song_file}.png")
|
||||
is_png = False
|
||||
|
||||
if os.path.exists(img1_path) == False:
|
||||
if os.path.exists(img2_path) == False:
|
||||
standard_check = False
|
||||
reason_fail += "\nSong thumbnail (music_name.jpg or music_name.png) is missing from the thumbs folder. "
|
||||
else:
|
||||
is_png = True
|
||||
|
||||
# (2): The correct mp3 file should be there.
|
||||
|
||||
song_path = os.path.join(os.path.join(extract_to, "music"), f"{song_file}.mp3")
|
||||
|
||||
if os.path.exists(song_path) == False:
|
||||
standard_check = False
|
||||
reason_fail += "\nMusic file (music_name.mp3) is missing from the Music folder. "
|
||||
|
||||
# (3): If bga data is present, bga file should be there.
|
||||
|
||||
bga_path = os.path.join(os.path.join(extract_to, "bga"), f"{song_file}.zip")
|
||||
|
||||
if bga_data != None and os.path.exists(bga_path) == False:
|
||||
standard_check = False
|
||||
reason_fail += "\nSince manifest specified BGA, there should be a music_name.zip in the bga folder. "
|
||||
|
||||
# (4): If bga data is not present but there is a song_name.zip in bga folder.
|
||||
|
||||
if bga_data == None and os.path.exists(bga_path):
|
||||
standard_check = False
|
||||
reason_fail += "\nManifest did not specify BGA, but there is a music_name.zip in the bga folder. While this is not a breaking issue, if you wish to use the BGA please specify it in the manifest. "
|
||||
|
||||
# (5): All the charts specified in the manifest should exist
|
||||
|
||||
for chart in charts:
|
||||
if os.path.exists(chart) == False:
|
||||
standard_check = False
|
||||
reason_fail += "\nA chart that is specified in manifest is missing from the note folder: " + chart + ". "
|
||||
|
||||
# That is it!
|
||||
|
||||
if standard_check == False:
|
||||
print("The song contains issues and is not imported. 此曲目存在问题,没有导入。")
|
||||
print("The reasons are as follows. 原因如下。")
|
||||
print(reason_fail)
|
||||
shutil.rmtree(extract_to)
|
||||
continue
|
||||
|
||||
playmanifest_path = "OverRide/playmanifest.json"
|
||||
with open(playmanifest_path, 'r', encoding="utf-8") as f:
|
||||
playmanifest = json.load(f)
|
||||
|
||||
existing_song_files = [item[0].get("mp3") for item in playmanifest]
|
||||
unique_song_file = get_unique_song_file(existing_song_files, song_file)
|
||||
|
||||
# Copy bga zip file if bga is specified
|
||||
|
||||
if bga_data != None:
|
||||
new_bga_name = unique_song_file + ".zip"
|
||||
new_bga_path = os.path.join("OverRide", "bga", new_bga_name)
|
||||
os.makedirs(os.path.dirname(new_bga_path), exist_ok=True)
|
||||
shutil.move(bga_path, new_bga_path)
|
||||
|
||||
# Copy music file
|
||||
|
||||
new_song_name = unique_song_file
|
||||
new_song_path = os.path.join("OverRide", "Music", new_song_name)
|
||||
os.makedirs(os.path.dirname(new_song_path), exist_ok=True)
|
||||
shutil.move(song_path, new_song_path)
|
||||
|
||||
# Copy the thumbnails
|
||||
|
||||
new_img_name = unique_song_file + ".jpg"
|
||||
new_img_path = os.path.join("Resources", "data_fm", new_img_name)
|
||||
os.makedirs(os.path.dirname(new_img_path), exist_ok=True)
|
||||
|
||||
if is_png:
|
||||
with Image.open(img2_path) as img:
|
||||
rgb_img = img.convert("RGB")
|
||||
rgb_img.save(new_img_path, "JPEG")
|
||||
else:
|
||||
shutil.move(img1_path, new_img_path)
|
||||
|
||||
# Save a resized 255x255 version of the image
|
||||
resized_img_name = "255" + unique_song_file + ".jpg"
|
||||
resized_img_path = os.path.join("Resources", "data_fm", resized_img_name)
|
||||
|
||||
with Image.open(new_img_path) as img:
|
||||
img = img.resize((255, 255), Image.Resampling.LANCZOS)
|
||||
img.save(resized_img_path, "JPEG")
|
||||
|
||||
# Copy all the charts
|
||||
|
||||
for chart in charts:
|
||||
new_chart_name = os.path.basename(chart).replace(".bms", "")
|
||||
new_chart_name = new_chart_name.replace(song_file, unique_song_file)
|
||||
new_chart_path = os.path.join("OverRide", "Note", new_chart_name)
|
||||
os.makedirs(os.path.dirname(new_chart_path), exist_ok=True)
|
||||
shutil.copy(chart, new_chart_path)
|
||||
|
||||
# Add charts to zip
|
||||
|
||||
note_zip_path = os.path.join("OverRide", "Note.zip")
|
||||
new_charts = []
|
||||
for chart in charts:
|
||||
new_chart_name = chart.replace(song_file, f"offlineNote_{unique_song_file}")
|
||||
new_chart_name = new_chart_name.replace(".bms", "")
|
||||
os.rename(chart, new_chart_name)
|
||||
new_charts.append(new_chart_name)
|
||||
|
||||
with zipfile.ZipFile(note_zip_path, 'a') as note_zip:
|
||||
for chart in new_charts:
|
||||
note_zip.write(chart, arcname=os.path.basename(chart))
|
||||
|
||||
# Merge the manifest
|
||||
|
||||
if playmanifest:
|
||||
last_id = playmanifest[-1][0].get("id", 0)
|
||||
else:
|
||||
last_id = 0
|
||||
|
||||
song["id"] = last_id + 1
|
||||
song["mp3"] = unique_song_file
|
||||
|
||||
playmanifest.append([song])
|
||||
with open(playmanifest_path, 'w', encoding="utf-8") as f:
|
||||
json.dump(playmanifest, f, indent=4)
|
||||
|
||||
print(f"Song added: 歌曲已添加:{unique_song_file}")
|
||||
|
||||
# Refresh the metadata and we are done!
|
||||
update_metadata()
|
||||
shutil.rmtree(extract_to)
|
||||
|
||||
|
||||
def update_metadata():
|
||||
resources_folder = "Resources"
|
||||
|
||||
md5_checksum_dict, size_dict = process_folder(resources_folder)
|
||||
|
||||
md5_file_name = "OverRapid/Md5ListChecksum.json"
|
||||
size_file_name = "OverRapid/SizeList.json"
|
||||
|
||||
write_to_file(md5_file_name, md5_checksum_dict)
|
||||
write_to_file(size_file_name, size_dict)
|
||||
|
||||
print(f"MD5 and size checksums saved.")
|
||||
|
||||
def main():
|
||||
print("Override Concierge - 您的Override管家")
|
||||
print("For music import, simply enter the zip file's path. For music deletion, simply enter its SID as displayed in-game.")
|
||||
print("曲目导入请输入zip文件的目录。曲目删除请输入游戏内显示的SID。")
|
||||
user_input = input("Input 输入: ")
|
||||
|
||||
if user_input.isdigit():
|
||||
deleteChart(int(user_input))
|
||||
elif not user_input.endswith(".zip"):
|
||||
print("The file is not zip. 文件不是zip。")
|
||||
else:
|
||||
importChart(user_input)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,48 @@
|
||||
import os
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
def calculate_md5_and_size(file_path):
|
||||
md5_hash = hashlib.md5()
|
||||
file_size = 0
|
||||
|
||||
with open(file_path, "rb") as file:
|
||||
for byte_block in iter(lambda: file.read(4096), b""):
|
||||
md5_hash.update(byte_block)
|
||||
file_size += len(byte_block)
|
||||
|
||||
return md5_hash.hexdigest(), file_size
|
||||
|
||||
def process_folder(folder_path):
|
||||
md5_checksum_dict = {}
|
||||
size_dict = {}
|
||||
|
||||
for root, dirs, files in os.walk(folder_path):
|
||||
for file_name in files:
|
||||
file_path = os.path.join(root, file_name)
|
||||
relative_path = os.path.relpath(file_path, folder_path)
|
||||
|
||||
md5_checksum, file_size = calculate_md5_and_size(file_path)
|
||||
|
||||
md5_checksum_dict[relative_path.replace("\\", "/")] = md5_checksum
|
||||
size_dict[relative_path.replace("\\", "/")] = file_size
|
||||
|
||||
return md5_checksum_dict, size_dict
|
||||
|
||||
def write_to_file(file_name, data):
|
||||
with open(file_name, "w") as file:
|
||||
file.write(json.dumps(data, separators=(',', ':')))
|
||||
|
||||
if __name__ == "__main__":
|
||||
resources_folder = "Resources"
|
||||
|
||||
md5_checksum_dict, size_dict = process_folder(resources_folder)
|
||||
|
||||
md5_file_name = "OverRapid/Md5ListChecksum.json"
|
||||
size_file_name = "OverRapid/SizeList.json"
|
||||
|
||||
write_to_file(md5_file_name, md5_checksum_dict)
|
||||
write_to_file(size_file_name, size_dict)
|
||||
|
||||
print(f"MD5 checksums saved to {md5_file_name}")
|
||||
print(f"File sizes saved to {size_file_name}")
|
||||
@@ -0,0 +1,4 @@
|
||||
databases==0.9.0
|
||||
SQLAlchemy==2.0.37
|
||||
starlette==0.50.0
|
||||
uvicorn==0.40.0
|
||||
@@ -0,0 +1,55 @@
|
||||
import cv2
|
||||
import os
|
||||
|
||||
video_file = input("Enter the name of the video file: 输入视频文件名称 ")
|
||||
|
||||
if not os.path.isfile(video_file) or not video_file.endswith('.mp4'):
|
||||
print("The file does not exist or is not an MP4 file. 文件不存在或不是mp4")
|
||||
exit()
|
||||
|
||||
id_string = input("Enter an ID string: 输入命名用ID")
|
||||
frame_rate = float(input("Enter the frame rate: 输入帧率"))
|
||||
|
||||
output_dir = input("Enter the output directory: 输入保存文件夹目录")
|
||||
|
||||
if not os.path.exists(output_dir):
|
||||
os.makedirs(output_dir)
|
||||
|
||||
cap = cv2.VideoCapture(video_file)
|
||||
|
||||
video_frame_rate = cap.get(cv2.CAP_PROP_FPS)
|
||||
|
||||
if frame_rate > video_frame_rate:
|
||||
frame_rate = video_frame_rate
|
||||
|
||||
original_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
||||
original_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
||||
|
||||
desired_width = 480
|
||||
desired_height = 270
|
||||
|
||||
interval = int(video_frame_rate / frame_rate)
|
||||
|
||||
frame_count = 0
|
||||
saved_count = 0
|
||||
|
||||
while cap.isOpened():
|
||||
ret, frame = cap.read()
|
||||
|
||||
if not ret:
|
||||
break
|
||||
|
||||
if frame.shape[1] != desired_width or frame.shape[0] != desired_height:
|
||||
frame = cv2.resize(frame, (desired_width, desired_height))
|
||||
|
||||
if frame_count % interval == 0:
|
||||
output_path = os.path.join(output_dir, f"{id_string}_{saved_count + 1}.jpg")
|
||||
cv2.imwrite(output_path, frame)
|
||||
saved_count += 1
|
||||
|
||||
frame_count += 1
|
||||
|
||||
cap.release()
|
||||
|
||||
print(f"Extracted {saved_count} frames and saved to {output_dir}.")
|
||||
print(f"已提取 {saved_count} 帧并保存到了 {output_dir}.")
|
||||
Binary file not shown.
@@ -0,0 +1,18 @@
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"title": "Music Name",
|
||||
"artist": "Music Artist",
|
||||
"isJapanese": false,
|
||||
"bpm": 167,
|
||||
"sync_6k": "0/0/0/-1400",
|
||||
"sync_4k": "0/0/0",
|
||||
"diff_6k": "0/0/0/18",
|
||||
"diff_4k": "0/0/0",
|
||||
"charter_6k": "-/-/-/charterA",
|
||||
"charter_4k": "-/-/-",
|
||||
"mp3": "song",
|
||||
"preview": "-1/-1",
|
||||
"bga": "-1400/24/3559"
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1 @@
|
||||
This is a test placeholder file
|
||||
@@ -0,0 +1 @@
|
||||
This is a test placeholder file
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.0 KiB |
Binary file not shown.
@@ -0,0 +1,439 @@
|
||||
import os
|
||||
import json
|
||||
import sys
|
||||
import zipfile
|
||||
from shutil import rmtree
|
||||
from msvcrt import getch
|
||||
import ctypes
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
|
||||
lastfile = "N/A"
|
||||
version = "Final"
|
||||
date = "November 5th, 2019"
|
||||
|
||||
try:
|
||||
ctypes.windll.kernel32.SetConsoleTitleW(f"Malody to osu!mania Converter v{version}") #https://stackoverflow.com/questions/7387276
|
||||
|
||||
if getattr(sys, 'frozen', False):
|
||||
os.chdir(os.path.dirname(sys.executable))
|
||||
#https://codeday.me/ko/qa/20190316/78831.html
|
||||
|
||||
print(f"Malody to osu!mania Converter v{version}")
|
||||
print(date)
|
||||
print("by Jakads\n\n")
|
||||
|
||||
def choose():
|
||||
choice = getch().decode()
|
||||
while choice not in 'yYnN':
|
||||
choice = getch().decode()
|
||||
|
||||
if choice in 'nN':
|
||||
return 0
|
||||
|
||||
else:
|
||||
return 1
|
||||
|
||||
"""
|
||||
if len(sys.argv) > 1 and sys.argv[1] == '--:update': #added ":" to disallow user to view this message by dragging in files
|
||||
#checks the first condition first so it will not give IndexError
|
||||
if os.path.isfile(sys.argv[2]):
|
||||
os.remove(sys.argv[2])
|
||||
else:
|
||||
print(f'[X] Failed to remove the temporary batch file({sys.argv[2]}). Please remove it manually. This message is not supposed to be shown.\n')
|
||||
print(f"[O] Successfully updated to v{version}! :D\n[!] Would you like to check out the changelog? (Y/N)\n")
|
||||
if choose():
|
||||
webbrowser.open('https://github.com/jakads/Malody-to-Osumania#changelog')
|
||||
del sys.argv[1], sys.argv[1] #Deleting second element twice actually deletes second and third
|
||||
|
||||
print("(i) Checking for new updates . . .")
|
||||
try:
|
||||
latest = requests.get('https://github.com/jakads/Malody-to-Osumania/raw/master/version.txt')
|
||||
latest.raise_for_status()
|
||||
print(f"\n(i) Latest Version = v{latest.text}")
|
||||
|
||||
if latest.text != version:
|
||||
print("\n[!] New update is available! Would you like to download? (Y/N)")
|
||||
if not choose():
|
||||
print("(i) Skipping the update.\n\n")
|
||||
|
||||
else:
|
||||
print("(i) Downloading . . .")
|
||||
exe = requests.get("https://github.com/jakads/Malody-to-Osumania/raw/master/convert.exe", stream=True)
|
||||
exe.raise_for_status()
|
||||
total = int(exe.headers.get('content-length'))
|
||||
progress = tqdm(total=total, unit='B', unit_scale=True, unit_divisor=1024, ncols=80) #https://github.com/tqdm/tqdm/wiki/How-to-make-a-great-Progress-Bar
|
||||
rand=''.join(random.choice(string.ascii_letters + string.digits) for i in range(16)) #https://pynative.com/python-generate-random-string/
|
||||
filename=os.path.basename(sys.executable)
|
||||
with open(f"{rand}.exe", 'wb') as f: #https://stackoverflow.com/questions/37573483
|
||||
for chunk in exe.iter_content(chunk_size=8192):
|
||||
if chunk:
|
||||
progress.update(8192)
|
||||
f.write(chunk)
|
||||
with open(f'{rand}.bat', 'w', encoding='utf-8') as f:
|
||||
f.write('\n'.join(['@echo off',
|
||||
'echo (i) Restarting . . .',
|
||||
"echo (i) All the files you've dragged in will be converted very soon!",
|
||||
'timeout /t 5 /nobreak >nul',
|
||||
f'del "{filename}"',
|
||||
f'rename {rand}.exe "{filename}"',
|
||||
'cls',
|
||||
'"{0}" --:update {1}.bat {2}'.format(filename, rand, ' '.join(f'"{file}\"' for file in sys.argv[1:]) if len(sys.argv)>1 else '')])) #https://stackoverflow.com/questions/12007686
|
||||
os.startfile(f'{rand}.bat')
|
||||
sys.exit()
|
||||
|
||||
else:
|
||||
print("\n[O] Your program is as good as new! We're good to go.\n\n")
|
||||
except Exception as e:
|
||||
print("\n[!] Error while connecting:", e)
|
||||
print("\n[!] Connection to GitHub failed. Will just continue...\n\n")
|
||||
"""
|
||||
|
||||
def recursive_file_gen(mydir):
|
||||
for root, dirs, files in os.walk(mydir):
|
||||
for file in files:
|
||||
yield os.path.join(root, file)
|
||||
#https://stackoverflow.com/questions/2865278
|
||||
|
||||
def convert(i, bgtmp, soundtmp):
|
||||
lastfile = f'{i} (Crashed while reading)'
|
||||
|
||||
try:
|
||||
with open(f'{i}',encoding='utf-8') as mc:
|
||||
mcFile = json.loads(mc.read())
|
||||
mcFile['meta']['mode']
|
||||
except:
|
||||
print(f"[!] FileWarning: {os.path.basename(i)} is not a valid .mc file. Ignoring...")
|
||||
return 1
|
||||
|
||||
if not mcFile['meta']['mode'] == 0:
|
||||
print(f"[!] KeyWarning: {os.path.basename(i)} is not a Key difficulty. Ignoring...")
|
||||
return 1
|
||||
|
||||
ms = lambda beats, bpm, offset: 1000*(60/bpm)*beats+offset
|
||||
beat = lambda beat: beat[0] + beat[1]/beat[2] #beats = [measure, nth beat, divisor]
|
||||
col = lambda column, keys: int(512*(2*column+1)/(2*keys))
|
||||
|
||||
SVMap = False
|
||||
|
||||
line = mcFile['time']
|
||||
meta = mcFile['meta']
|
||||
note = mcFile['note']
|
||||
if 'effect' in mcFile and len(mcFile['effect'])>0:
|
||||
sv = mcFile['effect']
|
||||
SVMap = True
|
||||
soundnote = {}
|
||||
|
||||
keys = meta["mode_ext"]["column"]
|
||||
|
||||
for x in note:
|
||||
if x.get('type',0):
|
||||
soundnote = x
|
||||
|
||||
bpm = [line[0]['bpm']]
|
||||
bpmoffset = [-soundnote.get('offset',0)]
|
||||
|
||||
if len(line)>1:
|
||||
j=0
|
||||
lastbeat=line[0]['beat']
|
||||
for x in line[1:]:
|
||||
bpm.append(x['bpm'])
|
||||
bpmoffset.append(ms(beat(x['beat'])-beat(lastbeat),line[j]['bpm'],bpmoffset[j]))
|
||||
j+=1
|
||||
lastbeat=x['beat']
|
||||
|
||||
global title, artist #I know using global is a bad practice but c'mon
|
||||
title = meta["song"]["title"]
|
||||
artist = meta["song"]["artist"]
|
||||
|
||||
preview = meta.get('preview',-1)
|
||||
titleorg = meta['song'].get('titleorg',title)
|
||||
artistorg = meta['song'].get('artistorg',artist)
|
||||
|
||||
background = meta["background"]
|
||||
if not background=="": bgtmp.append(f'{os.path.dirname(i)}\\{background}')
|
||||
sound = soundnote["sound"]
|
||||
if not sound=="": soundtmp.append(f'{os.path.dirname(i)}\\{sound}')
|
||||
creator = meta["creator"]
|
||||
version = meta["version"]
|
||||
|
||||
lastfile = f'{i} (Crashed while converting)'
|
||||
|
||||
with open(f'{os.path.splitext(i)[0]}.osu',mode='w',encoding='utf-8') as osu:
|
||||
osuformat = ['osu file format v14',
|
||||
'',
|
||||
'[General]',
|
||||
f'AudioFilename: {sound}',
|
||||
'AudioLeadIn: 0',
|
||||
f'PreviewTime: {preview}',
|
||||
'Countdown: 0',
|
||||
'SampleSet: Soft',
|
||||
'StackLeniency: 0.7',
|
||||
'Mode: 3',
|
||||
'LetterboxInBreaks: 0',
|
||||
'SpecialStyle: 0',
|
||||
'WidescreenStoryboard: 0',
|
||||
'',
|
||||
'[Editor]',
|
||||
'DistanceSpacing: 1.2',
|
||||
'BeatDivisor: 4',
|
||||
'GridSize: 8',
|
||||
'TimelineZoom: 2.4',
|
||||
'',
|
||||
'[Metadata]',
|
||||
f'Title:{title}',
|
||||
f'TitleUnicode:{titleorg}',
|
||||
f'Artist:{artist}',
|
||||
f'ArtistUnicode:{artistorg}',
|
||||
f'Creator:{creator}',
|
||||
f'Version:{version}',
|
||||
'Source:Malody',
|
||||
'Tags:Malody Convert by Jakads',
|
||||
'BeatmapID:0',
|
||||
'BeatmapSetID:-1',
|
||||
'',
|
||||
'[Difficulty]',
|
||||
'HPDrainRate:8',
|
||||
f'CircleSize:{keys}',
|
||||
'OverallDifficulty:8',
|
||||
'ApproachRate:5',
|
||||
'SliderMultiplier:1.4',
|
||||
'SliderTickRate:1',
|
||||
'',
|
||||
'[Events]',
|
||||
'//Background and Video events',
|
||||
f'0,0,\"{background}\",0,0',
|
||||
'',
|
||||
'[TimingPoints]\n']
|
||||
osu.write('\n'.join(osuformat))
|
||||
#https://thrillfighter.tistory.com/310
|
||||
|
||||
bpmcount = len(bpm)
|
||||
for x in range(bpmcount):
|
||||
osu.write(f'{bpmoffset[x]},{60000/bpm[x]},{int(line[x].get("sign",4))},1,0,0,1,0\n')
|
||||
|
||||
if SVMap:
|
||||
for n in sv:
|
||||
j=0
|
||||
|
||||
for b in line:
|
||||
if beat(b['beat']) > beat(n['beat']):
|
||||
j+=1
|
||||
else:
|
||||
continue
|
||||
|
||||
j=bpmcount-j-1
|
||||
|
||||
if int(ms(beat(n["beat"]), bpm[j], bpmoffset[j])) >= bpmoffset[0]:
|
||||
osu.write(f'{ms(beat(n["beat"])-beat(line[j]["beat"]), bpm[j], bpmoffset[j])},-{100/abs(n["scroll"]) if n["scroll"]!=0 else "1E+308"},{int(line[j].get("sign",4))},1,0,0,0,0\n')
|
||||
|
||||
osu.write('\n\n[HitObjects]')
|
||||
|
||||
for n in note:
|
||||
if not n.get('type',0) == 0:
|
||||
continue
|
||||
|
||||
j=0
|
||||
k=0
|
||||
|
||||
for b in line:
|
||||
if beat(b['beat']) > beat(n['beat']):
|
||||
j+=1
|
||||
else:
|
||||
continue
|
||||
|
||||
if not n.get('endbeat') == None:
|
||||
for b in line:
|
||||
if beat(b['beat']) > beat(n['endbeat']):
|
||||
k+=1
|
||||
else:
|
||||
continue
|
||||
|
||||
j=bpmcount-j-1
|
||||
k=bpmcount-k-1
|
||||
|
||||
if int(ms(beat(n["beat"]), bpm[j], bpmoffset[j])) >= 0:
|
||||
osu.write(f'\n{col(n["column"], keys)},192,{int(ms(beat(n["beat"])-beat(line[j]["beat"]), bpm[j], bpmoffset[j]))}')
|
||||
|
||||
if n.get('endbeat') == None: #Regular Note
|
||||
osu.write(',1,0,0:0:0:')
|
||||
else: #Long Note
|
||||
osu.write(f',128,0,{int(ms(beat(n["endbeat"])-beat(line[k]["beat"]), bpm[k], bpmoffset[k]))}:0:0:0:')
|
||||
|
||||
if n.get('sound') == None:
|
||||
osu.write('0:')
|
||||
else: #Hitsound Note
|
||||
osu.write('{0}:{1}'.format(n['vol'],n['sound'].replace('"','')))
|
||||
return 0
|
||||
|
||||
def compress(compressname, name, bglist, soundlist):
|
||||
osz = zipfile.ZipFile(f'{compressname}.osz','w')
|
||||
|
||||
for i in name:
|
||||
lastfile = f'{i} (Crashed while compressing)'
|
||||
osz.write(f'{os.path.splitext(i)[0]}.osu', f'{os.path.basename(i)}.osu')
|
||||
os.remove(f'{os.path.splitext(i)[0]}.osu')
|
||||
print(f'[O] Compressed: {os.path.splitext(i)[0]}.osu')
|
||||
if not len(bglist)==0:
|
||||
for i in bglist:
|
||||
lastfile = f'{i} (Crashed while compressing)'
|
||||
if os.path.isfile(i):
|
||||
osz.write(i, os.path.basename(i))
|
||||
print(f'[O] Compressed: {os.path.basename(i)}')
|
||||
else:
|
||||
print(f'[!] {os.path.basename(i)} is not found and thus not compressed.')
|
||||
if not len(soundlist)==0:
|
||||
for i in soundlist:
|
||||
lastfile = f'{i} (Crashed while compressing)'
|
||||
if os.path.isfile(i):
|
||||
osz.write(i, os.path.basename(i))
|
||||
print(f'[O] Compressed: {os.path.basename(i)}\n')
|
||||
else:
|
||||
print(f'[!] {os.path.basename(i)} is not found and thus not compressed.')
|
||||
osz.close()
|
||||
oszname.append(f'{compressname}.osz')
|
||||
|
||||
if len(sys.argv)<=1:
|
||||
print("(i) Drag .mc or .mcz/.zip files into this program to convert them to .osu or .osz!")
|
||||
print("(i) Press any key to exit.")
|
||||
getch()
|
||||
sys.exit()
|
||||
|
||||
MCDragged = False
|
||||
MCValid = False
|
||||
ZIPDragged = False
|
||||
#FolderDragged = False
|
||||
mcname = []
|
||||
zipname = []
|
||||
foldername = []
|
||||
oszname = []
|
||||
|
||||
mctmp = []
|
||||
print('(i) Checking file validity . . .\n')
|
||||
for x in sys.argv[1:]:
|
||||
lastfile = f'{x} (Crashed while checking)'
|
||||
isMCZ = False
|
||||
if os.path.isdir(x):
|
||||
#zipname.append(os.path.splitext(x)[0])
|
||||
#FolderDragged = True
|
||||
print(f"[!] FileWarning: {os.path.basename(x)} is a directory, not a file. Ignoring...")
|
||||
elif not os.path.isfile(x):
|
||||
print(f"[!] FileWarning: {os.path.basename(x)} is not found. You normally aren't supposed to see this message. Ignoring...")
|
||||
elif os.path.splitext(x)[1].lower() == ".mc":
|
||||
mctmp.append(x)
|
||||
MCDragged = True
|
||||
elif os.path.splitext(x)[1].lower() in [".mcz", ".zip"]:
|
||||
if os.path.splitext(x)[1].lower() == ".mcz":
|
||||
isMCZ = True
|
||||
os.rename(x, f'{os.path.splitext(x)[0]}.zip')
|
||||
x = f'{os.path.splitext(x)[0]}.zip'
|
||||
mcz = zipfile.ZipFile(x)
|
||||
mcz.extractall(os.path.splitext(x)[0])
|
||||
mcz.close()
|
||||
if isMCZ:
|
||||
os.rename(x, f'{os.path.splitext(x)[0]}.mcz')
|
||||
zipname.append(os.path.splitext(x)[0])
|
||||
ZIPDragged = True
|
||||
else:
|
||||
print(f"[!] FileWarning: The file type of {os.path.basename(x)} is not supported. Ignoring...")
|
||||
|
||||
if MCDragged:
|
||||
mcname.append(mctmp)
|
||||
|
||||
if not MCDragged and not ZIPDragged:
|
||||
#print("\n[X] FILEERROR: None of the files you've dragged in are supported. This program only accepts .mc, .mcz, .zip files, or folders with them.")
|
||||
print("\n[X] FILEERROR: None of the files you've dragged in are supported. This program only accepts .mc, .mcz, or .zip files.")
|
||||
print("(i) Press any key to exit.")
|
||||
getch()
|
||||
sys.exit()
|
||||
|
||||
title = ""
|
||||
artist = ""
|
||||
mctitle = ""
|
||||
mcartist = ""
|
||||
bglist = []
|
||||
soundlist = []
|
||||
|
||||
print("\n\n(i) Converting . . .\n")
|
||||
|
||||
#Converting to .osu (dragged .mc files)
|
||||
if MCDragged:
|
||||
bgtmp = []
|
||||
soundtmp = []
|
||||
for i in mcname[0][:]: #https://stackoverflow.com/questions/7210578
|
||||
if not convert(i, bgtmp, soundtmp):
|
||||
print(f'[O] Converted: {os.path.basename(i)}')
|
||||
MCValid = True
|
||||
else:
|
||||
mcname[0].remove(i)
|
||||
mctitle = title
|
||||
mcartist = artist
|
||||
bglist.append(bgtmp)
|
||||
soundlist.append(soundtmp)
|
||||
|
||||
|
||||
#Converting to .osu (dragged .mcz/.zip files)
|
||||
if ZIPDragged:
|
||||
for folder in zipname:
|
||||
print(f'\n\n(i) Converting {os.path.basename(folder)} . . .\n')
|
||||
c=0
|
||||
bgtmp = []
|
||||
soundtmp = []
|
||||
mctmp = []
|
||||
filelist = list(recursive_file_gen(folder))
|
||||
for files in filelist:
|
||||
if os.path.splitext(files)[1] == ".mc":
|
||||
if not convert(files, bgtmp, soundtmp):
|
||||
print(f'[O] Converted: {os.path.basename(files)}')
|
||||
c+=1
|
||||
MCValid = True
|
||||
mctmp.append(files)
|
||||
if c>0:
|
||||
foldername.append(folder)
|
||||
bglist.append(bgtmp)
|
||||
soundlist.append(soundtmp)
|
||||
mcname.append(mctmp)
|
||||
|
||||
if not MCValid:
|
||||
print("\n[X] FILEERROR: None of the files you've dragged are supported.")
|
||||
print("(i) Press any key to exit.")
|
||||
getch()
|
||||
sys.exit()
|
||||
|
||||
print('\n\n(i) All the supported .mc files have been converted to .osu!\n(i) Either close the program now and move the files manually,\n(i) or press Enter to compress all into .osz.')
|
||||
getch()
|
||||
|
||||
print('\n\n\n(i) Compressing . . .\n')
|
||||
#Compress to .osz (dragged .mc files as single mapset)
|
||||
if MCDragged:
|
||||
compress(f'{mcartist} - {mctitle}', mcname[0], set(bglist[0]), set(soundlist[0]))
|
||||
|
||||
if ZIPDragged:
|
||||
i = 1 if MCDragged else 0
|
||||
for folder in zipname:
|
||||
print(f'\n(i) Compressing {os.path.basename(folder)} . . .\n')
|
||||
compress(f'{os.path.basename(folder)}', mcname[i], set(bglist[i]), set(soundlist[i]))
|
||||
i+=1
|
||||
rmtree(folder)
|
||||
|
||||
print('\n(i) The following .osz files have been created! Run the files to add the maps to osu! automatically.\n')
|
||||
for i in oszname:
|
||||
print(f'* {i}')
|
||||
print('\n(i) Press any key to exit.')
|
||||
getch()
|
||||
|
||||
except Exception as e:
|
||||
print(f'\n\n\n[X] FATAL ERROR : {repr(e)}\n')
|
||||
traceback.print_exc()
|
||||
crashlog = f'CrashLog_{datetime.now().strftime("%Y%m%d%H%M%S")}.log'
|
||||
with open(crashlog,mode='w',encoding='utf-8') as crash:
|
||||
crash.write('lol rip xd\n\n')
|
||||
crash.write(f"Target File: {lastfile}\n")
|
||||
crash.write("If you would like to tell the dev about this issue, please attach the file above if available (and the whole folder too if possible) with this crash report.\n")
|
||||
crash.write('DO NOT EDIT ANYTHING WRITTEN HERE.\n\n')
|
||||
crash.write(traceback.format_exc())
|
||||
print(f'\n[X] The crash log has been saved as {crashlog}.')
|
||||
print('[X] Please tell the dev about this!')
|
||||
print('(i) Press any key to exit.')
|
||||
getch()
|
||||
exit()
|
||||
@@ -0,0 +1,2 @@
|
||||
**/__pycache__/
|
||||
**/input/
|
||||
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
@@ -0,0 +1,117 @@
|
||||
# o!m2bms
|
||||
|
||||
[Original Repo](https://github.com/mashimycota/om2bms)
|
||||
|
||||
Program that converts osu!mania maps to BMS maps. (**currently only supports 2k to 8k**)
|
||||
|
||||
Supports fully keysounded maps and bpm changes.
|
||||
|
||||
**If you come across any Errors, please report them in the issues!**
|
||||
|
||||
## Installation
|
||||
|
||||
Written on Python 3.6+.
|
||||
You can download the required libraries by running:
|
||||
```
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
Requires an instance of ffmpeg in your system PATH. Here's an [ffmpeg installtion tutorial](https://phoenixnap.com/kb/ffmpeg-windows) if you don't have it already. (To check it if works, type `ffmpeg` in your terminal, and it should not return an error)
|
||||
|
||||
|
||||
Set the default output directory by running,
|
||||
|
||||
```
|
||||
python om2bms_osz.py -sdo [OUTPUT DIRECTORY]
|
||||
```
|
||||
|
||||
or go to `default_outdir.ini` and paste the path to a subdirectory in a BMS songfolder directory.
|
||||
|
||||
## Running
|
||||
Run
|
||||
|
||||
```
|
||||
python om2bms_osz.py -i sample_osz_file.osz
|
||||
```
|
||||
|
||||
to convert all 2k-8k files in `sample_osz_file.osz` and output them to `[OUTPUT DIRECTORY]/sample_osz_file`
|
||||
|
||||
To convert individual .osu files run
|
||||
|
||||
```
|
||||
python om2bms_osu.py -i sample_osu_file.osu
|
||||
```
|
||||
|
||||
#### Batch Converting
|
||||
|
||||
Run
|
||||
```
|
||||
python commandUI.py
|
||||
```
|
||||
To access the Command Line User Interface that allows some settings customisation and batch conversion of `.osz` files that are in the input folder (not compatible with single `.osu` files for now)
|
||||
|
||||
(I personally think always converting `.osz` files is best anyway)
|
||||
|
||||
|
||||
### To view help, run
|
||||
|
||||
```
|
||||
python om2bms_osz.py -h
|
||||
```
|
||||
|
||||
```
|
||||
python om2bms_osu.py -h
|
||||
```
|
||||
|
||||
## Key Mapping
|
||||
(note: I will make images for this section in the future | will also make the layouts customizable)
|
||||
|
||||
|
||||
Lets define the columns like this = `|1|2|3|4|5|6|7|8|`.
|
||||
|
||||
If a column is used for the key count in question, it will have it's corresponding number inside it.
|
||||
|
||||
### 2k
|
||||
`|1| | | |5| | | |` (so 1k + scratch with controller)
|
||||
|
||||
### 3k
|
||||
`| | | |4|5|6| | |`
|
||||
|
||||
### 4k
|
||||
`| | |3|4| |6|7| |`
|
||||
|
||||
### 5k
|
||||
`| |2|3|4|5|6| | |`
|
||||
|
||||
### 6k
|
||||
`|1|2|3|4|5|6| | |` (so 5k + scratch if controller)
|
||||
|
||||
## To-do List
|
||||
|
||||
- [ ] Slider Velocity
|
||||
- [ ] Difficulty calculation when converting
|
||||
- [x] *Background Videos* **(Needs to find fix for offset)**
|
||||
- [x] Persistent settings file for UI
|
||||
- [x] Support other keycounts then just 7k and 8k **(Supports 2k - 8k)**
|
||||
- [ ] Improved background image resize/processing when converting
|
||||
- [x] Adapt to be used without command line, aka a general run function for the arguments (necessary for GUI and improving command line UI)
|
||||
- [ ] Make GUI
|
||||
- [ ] Drag-and-drop for GUI
|
||||
- [ ] Change output file format from `.bms` to `.bmson` (will allow easier feature implementation). Not to be done for a while. Will require big rewrite.
|
||||
|
||||
## Notes
|
||||
|
||||
- Tested with LR2
|
||||
- Does not currently support SV changes
|
||||
- Uses first timing point to estimate the first measure
|
||||
- Assumes timing points are always the start of a new measure
|
||||
- If there are >1 hitsounds played in one note, only plays the hitsound with the highest bit
|
||||
|
||||
[.osu file documentation](https://osu.ppy.sh/help/wiki/osu!_File_Formats/Osu_(file_format)).
|
||||
|
||||
[BMS file documentation](https://hitkey.nekokan.dyndns.info/cmds.htm).
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the GPLv3 license, refer to LICENSE for details.
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
import om2bms_osz
|
||||
import os
|
||||
import json
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
clear = lambda: os.system("cls")
|
||||
|
||||
end = False
|
||||
curr_page = "main"
|
||||
|
||||
# curr_opts = {
|
||||
# "in_file": "input",
|
||||
# "set_default_out": open("./default_outdir.ini", "r").read().strip(),
|
||||
# "hitsound": None,
|
||||
# "bg": True,
|
||||
# "video": True,
|
||||
# "offset": -235,
|
||||
# "judge": 2
|
||||
# }
|
||||
if not os.path.exists("./settings.json"):
|
||||
# incase someone for some reason deletes the settings file
|
||||
default_settings = {
|
||||
"in_file": "input",
|
||||
"set_default_out": "output",
|
||||
"hitsound": None,
|
||||
"bg": True,
|
||||
"video": True,
|
||||
"offset": -235,
|
||||
"judge": 2
|
||||
}
|
||||
json.dump({"custom":default_settings, "default": default_settings}, open("./settings.json", "w"))
|
||||
|
||||
curr_opts = json.load(open("./settings.json", "r"))["custom"]
|
||||
|
||||
|
||||
if not os.path.isdir(curr_opts["in_file"]):
|
||||
os.mkdir(curr_opts["in_file"])
|
||||
print(f"The missing input directory \"{curr_opts['in_file']}\" has been created. You can put your .osz files in there to convert.")
|
||||
input("Press ENTER to continue...")
|
||||
|
||||
|
||||
while not end:
|
||||
# updates options with whatever changes were made in previous iteration
|
||||
settings_file = json.load(open("./settings.json", "r"))
|
||||
settings_file["custom"] = curr_opts
|
||||
json.dump(settings_file, open("./settings.json", "w"))
|
||||
|
||||
# ugly format that shows the value of every setting at the beginning of each loop
|
||||
main_page_options = """Input Folder: {}\t\t Output Folder: {}\t\t\t Use Hitsounds: {}
|
||||
Background Image: {}\t\t Default Map Offset: {}ms\t\t Judgement: {}
|
||||
Background Video: {}""".format(curr_opts["in_file"], curr_opts["set_default_out"], "False" if curr_opts["hitsound"] is None else curr_opts["hitsound"],
|
||||
curr_opts["bg"], curr_opts["offset"], curr_opts["judge"], curr_opts["video"])
|
||||
|
||||
|
||||
clear()
|
||||
print("\n")
|
||||
print(main_page_options)
|
||||
print()
|
||||
|
||||
# initial page display
|
||||
print("="*20 + "OPTIONS" + "="*20)
|
||||
if curr_page == "main":
|
||||
print("(1) Run Converter")
|
||||
print("(2) Edit Settings")
|
||||
print("(3) List Files To Convert")
|
||||
print("(4) Exit Program")
|
||||
elif curr_page == "settings":
|
||||
print("(1) Change Input Folder \t\t (2) Change Output Folder")
|
||||
print("(3) Toggle hitsounds \t\t\t (4) Toggle Convert Background Image")
|
||||
print("(5) Change Offset\t\t\t (6) Change Map Judgement")
|
||||
print("(7) Toggle Convert Background Video")
|
||||
print("\n(RESET): Reset these settings back to the system defaults")
|
||||
print("\n(0) Back to main page")
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
print("")
|
||||
option = input("Choose option number: ").lower().strip()
|
||||
|
||||
if curr_page == "main": # functionality for each option of main page
|
||||
if option == "1":
|
||||
# input_dir_scan = list(os.scandir(curr_opts["in_file"]))
|
||||
|
||||
for file in os.scandir(curr_opts["in_file"]): # we loop across the path of every .osz file and convert them
|
||||
if file.is_file() and file.path.endswith(".osz"):
|
||||
curr_opts["in_file"] = file.path
|
||||
om2bms_osz.convert(**curr_opts)
|
||||
|
||||
print("\nConversion Complete\n")
|
||||
end = True
|
||||
elif option == "2":
|
||||
curr_page = "settings"
|
||||
clear()
|
||||
elif option == "3": # we just iterate over and display the filename of all .osz files in input file
|
||||
for file in os.scandir(curr_opts["in_file"]):
|
||||
if file.is_file() and file.path.endswith(".osz"):
|
||||
print(os.path.basename(file.path))
|
||||
input("(Enter to clear)")
|
||||
elif option == "4":
|
||||
end = True
|
||||
else:
|
||||
input("ERROR: That option number does not exist!")
|
||||
|
||||
elif curr_page == "settings": # functionality for each option of settings page
|
||||
if option == "1":
|
||||
new_input = input("Enter new input folder: ").strip()
|
||||
if new_input:
|
||||
curr_opts["in_file"] = new_input
|
||||
else:
|
||||
input("ERROR: the input folder must be a none empty name.")
|
||||
elif option == "2":
|
||||
new_output = input("Enter new output folder: ").strip()
|
||||
if new_output:
|
||||
curr_opts["set_default_out"] = new_output
|
||||
else:
|
||||
input("ERROR: the output folder must be a none empty name.")
|
||||
elif option == "3":
|
||||
curr_opts["hitsound"] = not curr_opts["hitsound"]
|
||||
elif option == "4":
|
||||
curr_opts["bg"] = not curr_opts["bg"]
|
||||
elif option == "5":
|
||||
new_offset = input("Enter a new Offset (ms): ").strip()
|
||||
if all([num in map(str, range(10)) for num in (new_offset[1:] if new_offset[0] == "-" else new_offset)]):
|
||||
curr_opts["offset"] = int(new_offset)
|
||||
else:
|
||||
input("ERROR: you must enter a whole number for the offset!")
|
||||
elif option == "6":
|
||||
new_judgement = input("Enter a number for the map judgement: ").strip()
|
||||
if all([num in map(str, range(10)) for num in new_judgement]):
|
||||
curr_opts["judge"] = int(new_judgement)
|
||||
else:
|
||||
input("ERROR: Judgement number must be a positive whole number!")
|
||||
elif option == "7":
|
||||
curr_opts["video"] = not curr_opts["video"]
|
||||
elif option == "reset":
|
||||
settings_file = json.load(open("./settings.json", "r"))
|
||||
curr_opts = settings_file["default"]
|
||||
# will update the "settings.json" on next iteration of the while loop
|
||||
|
||||
elif option == "0":
|
||||
curr_page = "main"
|
||||
else:
|
||||
input("ERROR: That option number does not exist!")
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
output
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,351 @@
|
||||
from typing import Union, List, Tuple, Dict
|
||||
|
||||
from om2bms.exceptions import BMSHitSoundException
|
||||
|
||||
|
||||
class OsuMania:
|
||||
"""Class containing information from .osu file"""
|
||||
|
||||
def __init__(self):
|
||||
# general
|
||||
self.audio_filename = None
|
||||
self.audio_lead_in = None
|
||||
self.video_filename = None
|
||||
self.video_start_time = None
|
||||
self.special_style = None # o!m scrollkey y/n
|
||||
self.sample_set = None
|
||||
# metadata
|
||||
self.title = None
|
||||
self.title_unicode = None
|
||||
self.artist = None
|
||||
self.artist_unicode = None
|
||||
self.creator = None
|
||||
self.version = None
|
||||
self.source = None
|
||||
self.beatmap_id = None
|
||||
self.stagebg = None
|
||||
|
||||
self.key_count = None # originally circle size
|
||||
self.od = None
|
||||
|
||||
self.float_bpm = []
|
||||
self.timing_points = []
|
||||
self.hit_objects = []
|
||||
self.sample_objects = []
|
||||
self.objects = []
|
||||
self.sample_filenames = []
|
||||
self.filename_to_sample = {}
|
||||
|
||||
self.noninherited_tp = []
|
||||
|
||||
self.hitsounds = {}
|
||||
self.hitsound_names = []
|
||||
|
||||
def parse_float_bpm(self, bpm: float):
|
||||
"""
|
||||
Parse float bpm into (INDEX, BPM)
|
||||
"""
|
||||
for e in self.float_bpm:
|
||||
if e[1] == bpm:
|
||||
return
|
||||
self.float_bpm.append((get_current_hs_count(len(self.float_bpm) + 1), bpm))
|
||||
|
||||
|
||||
class OsuTimingPoint:
|
||||
"""Contains information for a particular timing point"""
|
||||
def __init__(self):
|
||||
self.time = None
|
||||
self.ms_per_beat = None
|
||||
self.meter = None
|
||||
self.sample_set = None
|
||||
self.sample_index = None
|
||||
self.volume = None # not supported in lr2
|
||||
self.inherited = None
|
||||
self.kiai_mode = None # not needed
|
||||
|
||||
self.ms_per_measure = None
|
||||
|
||||
self.sort_type = 0 # for sorting
|
||||
|
||||
def __repr__(self):
|
||||
return str(self.time) + "ms at " + str(self.ms_per_beat) + "ms_per_beat"
|
||||
|
||||
def __eq__(self, other):
|
||||
return self.ms_per_beat == other.ms_per_beat and self.meter == other.meter and \
|
||||
self.sample_set == other.sample_set and self.sample_index == other.sample_index
|
||||
|
||||
|
||||
class SoundEvent:
|
||||
"""Just to contain build_filename"""
|
||||
_hit_sound_key = {
|
||||
0: "none",
|
||||
1: "normal",
|
||||
2: "whistle",
|
||||
4: "finish",
|
||||
8: "clap"}
|
||||
_sample_set_key = {
|
||||
1: "normal",
|
||||
2: "soft",
|
||||
3: "drum"}
|
||||
|
||||
def __init__(self):
|
||||
self.index = None
|
||||
|
||||
self.sort_type = 1 # for sorting
|
||||
|
||||
def build_filename(self, custom_index: int, sample_set: int, hitsound: int) -> str:
|
||||
"""
|
||||
filename = {sample set}-hit{sound}{index}.wav
|
||||
"""
|
||||
index = "" if custom_index == 1 else str(custom_index)
|
||||
return str(HitSound._sample_set_key[sample_set]) + "-hit" + str(HitSound._hit_sound_key[hitsound]) \
|
||||
+ index + ".wav"
|
||||
|
||||
def get_info(self):
|
||||
"""
|
||||
For list iterating purposes
|
||||
"""
|
||||
return (self.index, self)
|
||||
|
||||
|
||||
class OsuBGSoundEvent(SoundEvent):
|
||||
"""
|
||||
For when sample plays in the background that is not the audiofile
|
||||
"""
|
||||
def __init__(self, time, filename, sample_num):
|
||||
super().__init__()
|
||||
self.time = time
|
||||
self.filename = filename
|
||||
self.index = get_current_hs_count(sample_num)
|
||||
|
||||
def __str__(self):
|
||||
return self.filename
|
||||
|
||||
|
||||
class HitSound(SoundEvent):
|
||||
"""
|
||||
hit_sound key
|
||||
"""
|
||||
def __init__(self, hitsound: int, tp: Union[OsuTimingPoint, None], sample_set: int, custom_index:
|
||||
int, filename: str, sample_num: int):
|
||||
super().__init__()
|
||||
self.timing_point = tp
|
||||
self.hitsound = hitsound
|
||||
self.sample_set = sample_set
|
||||
self.custom_index = custom_index if custom_index != 0 else self.timing_point.sample_index
|
||||
self.filename = filename if filename != "" else self.build_filename(self.custom_index, self.sample_set,
|
||||
self.hitsound)
|
||||
self.addition_set = self.sample_set # needed?
|
||||
self.index = get_current_hs_count(sample_num)
|
||||
|
||||
def __str__(self):
|
||||
return self.filename
|
||||
|
||||
|
||||
class OsuHitObject:
|
||||
"""
|
||||
Hitobject class
|
||||
|
||||
mania_column:
|
||||
scroll = 0
|
||||
key1 = 1
|
||||
key2 = 2
|
||||
...
|
||||
key7 = 7
|
||||
"""
|
||||
def __init__(self):
|
||||
self.time = None
|
||||
self.time_value = None
|
||||
self.new_combo = False
|
||||
|
||||
self.hit_sound = None
|
||||
self.mania_column = None
|
||||
|
||||
self.timing_point = None
|
||||
|
||||
self.sort_type = 1 # for sorting
|
||||
|
||||
|
||||
class OsuManiaNote(OsuHitObject):
|
||||
"""Single o!m note"""
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
def get_type_value(self):
|
||||
"""
|
||||
Returns type value of note
|
||||
"""
|
||||
return 5 if self.new_combo else 1
|
||||
|
||||
def __str__(self):
|
||||
return "NOTE: t=" + str(self.time) + "|c=" + str(self.mania_column)
|
||||
|
||||
def __repr__(self):
|
||||
return "NOTE: t=" + str(self.time) + "|c=" + str(self.mania_column)
|
||||
|
||||
|
||||
class OsuManiaLongNote(OsuHitObject):
|
||||
"""o!m noodle"""
|
||||
def __init__(self, end_time=None):
|
||||
super().__init__()
|
||||
self.end_time = end_time
|
||||
|
||||
def get_type_value(self):
|
||||
"""
|
||||
Returns type value of note
|
||||
"""
|
||||
return 132 if self.new_combo else 128
|
||||
|
||||
def __str__(self):
|
||||
return "LN: t=" + str(self.time) + "|t2=" + str(self.end_time) + "|c=" + str(self.mania_column)
|
||||
|
||||
def __repr__(self):
|
||||
return "LN: t=" + str(self.time) + "|t2=" + str(self.end_time) + "|c=" + str(self.mania_column)
|
||||
|
||||
|
||||
class BMSMeasure:
|
||||
"""
|
||||
Contains info for all lines in the same measure
|
||||
"""
|
||||
_hit_sounds = True
|
||||
|
||||
def __init__(self, measure_number: str):
|
||||
self.measure_number = measure_number
|
||||
self.lines = []
|
||||
|
||||
def __str__(self):
|
||||
"""
|
||||
Returns in format XXXYY:NN
|
||||
"""
|
||||
ret = ""
|
||||
for line in self.lines:
|
||||
ret += ("#" + str(self.measure_number) + str(line.channel) + ":" + str(line.data) + "\n")
|
||||
return str(ret)
|
||||
|
||||
def create_data_line(self, channel: str, bits: int,
|
||||
locations: List[Tuple[List[int], Union[OsuHitObject, OsuBGSoundEvent, str]]]):
|
||||
"""
|
||||
Wrapper for creating data_line
|
||||
"""
|
||||
chars = {}
|
||||
locations_ = []
|
||||
for e in locations:
|
||||
locations_.append(e[0])
|
||||
if isinstance(e[1], OsuHitObject):
|
||||
if e[1].hit_sound is not None and BMSMeasure._hit_sounds:
|
||||
chars[e[0]] = e[1].hit_sound.index
|
||||
if chars[e[0]] == "":
|
||||
chars[e[0]] = "ZZ"
|
||||
else:
|
||||
chars[e[0]] = "ZZ"
|
||||
elif isinstance(e[1], OsuBGSoundEvent):
|
||||
chars[e[0]] = e[1].index
|
||||
else:
|
||||
chars[e[0]] = e[1]
|
||||
self.lines.append(BMSMainDataLine(channel, bits, chars, locations_, self.measure_number))
|
||||
|
||||
def create_measure_length_change(self, num_of_beats):
|
||||
"""
|
||||
Channel 2 measure length change
|
||||
"""
|
||||
# beats_over_four = float(num_of_beats / 4)
|
||||
self.lines.append(BMSMainDataLine("02", 1, {0: str(num_of_beats)}, [0], self.measure_number))
|
||||
|
||||
def create_bpm_change_line(self, bpm: int):
|
||||
"""
|
||||
Channel 3 bpm change (ints only), 01 - FF(255)
|
||||
"""
|
||||
self.lines.append(BMSMainDataLine("03", 1, {0: str(hex(bpm))[2:4].upper().zfill(2)}, [0], self.measure_number))
|
||||
|
||||
def create_bpm_extended_change_line(self, bpm: Union[int, float], float_bpm_arr):
|
||||
"""
|
||||
Channel 8 bpm change. Takes real number.
|
||||
"""
|
||||
tup = (None, None)
|
||||
for e in float_bpm_arr:
|
||||
if e[1] == bpm:
|
||||
tup = e
|
||||
self.lines.append(BMSMainDataLine("08", 1, {0: str(tup[0])}, [0], self.measure_number))
|
||||
|
||||
|
||||
class BMSMainDataLine:
|
||||
"""
|
||||
Single line within the
|
||||
"""
|
||||
def __init__(self, channel: str, bits: int, chars: Dict[int, str], locations: List[int], measure_number: str):
|
||||
self.channel = channel
|
||||
self.data = self._build_data(bits, chars, locations)
|
||||
self.measure_number = measure_number
|
||||
|
||||
def _build_data(self, bits: int, chars: Dict[int, str], locations: List[int]) -> str:
|
||||
"""
|
||||
Builds the components of line
|
||||
"""
|
||||
ret = ""
|
||||
location_index = 0
|
||||
for i in range(bits):
|
||||
if i == locations[location_index]:
|
||||
ret += chars[i]
|
||||
if not location_index >= len(locations) - 1:
|
||||
location_index += 1
|
||||
else:
|
||||
ret += "00"
|
||||
return ret
|
||||
|
||||
def __str__(self):
|
||||
"""
|
||||
Returns in format XXXYY:NN
|
||||
"""
|
||||
ret = "#" + str(self.measure_number) + str(self.channel) + ":" + str(self.data) + "\n"
|
||||
return str(ret)
|
||||
|
||||
|
||||
def get_current_hs_count(sample_num: int) -> str:
|
||||
"""
|
||||
Returns the HitSound instance's base36 hitsound identifier.
|
||||
"""
|
||||
def base36encode(number, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ') -> str:
|
||||
"""Converts an integer to a base36 string.
|
||||
Adapted from Wikipedia.
|
||||
"""
|
||||
base36 = ''
|
||||
if 0 <= number < len(alphabet):
|
||||
return alphabet[number]
|
||||
while number != 0:
|
||||
number, i = divmod(number, len(alphabet))
|
||||
base36 = alphabet[i] + base36
|
||||
return base36
|
||||
|
||||
ret = base36encode(sample_num)
|
||||
if len(ret) == 1:
|
||||
ret = "0" + ret
|
||||
elif len(ret) > 2 or ret == "ZZ":
|
||||
# raise BMSHitSoundException("Too many hitsounds.")
|
||||
print("Too many hitsounds - continuing")
|
||||
return ""
|
||||
return ret
|
||||
|
||||
|
||||
def calculate_bpm(timing_point: OsuTimingPoint) -> Union[int, float]:
|
||||
"""
|
||||
Calculates bpm and rounds if decimals 1-4 are 0 or 9
|
||||
"""
|
||||
def get_nth_decimal(number, n):
|
||||
"""
|
||||
Returns nth decimal of number
|
||||
"""
|
||||
return int(number * (10 ** n)) % 10
|
||||
|
||||
bpm_float = 1 / ((timing_point.ms_per_beat / 1000) / 60)
|
||||
ncount = count = 0
|
||||
for i in range(1, 5):
|
||||
if get_nth_decimal(bpm_float, i) == 0:
|
||||
count += 1
|
||||
elif get_nth_decimal(bpm_float, i) == 9:
|
||||
ncount += 1
|
||||
if count == 4:
|
||||
return int(bpm_float)
|
||||
elif ncount == 4:
|
||||
return round(bpm_float)
|
||||
else:
|
||||
return int(bpm_float * (10 ** 4)) / 10000
|
||||
@@ -0,0 +1,23 @@
|
||||
"""
|
||||
For exceptions
|
||||
"""
|
||||
|
||||
|
||||
class OsuParseException(Exception):
|
||||
"""Excpetion class for osu parsing excpetions"""
|
||||
pass
|
||||
|
||||
|
||||
class OsuGameTypeException(Exception):
|
||||
"""For non-osumania maps """
|
||||
pass
|
||||
|
||||
|
||||
class BMSHitSoundException(Exception):
|
||||
"""When there are too many sound files (~1293)"""
|
||||
pass
|
||||
|
||||
|
||||
class BMSMaxMeasuresException(Exception):
|
||||
"""BMS files only support up to 999 measures."""
|
||||
pass
|
||||
@@ -0,0 +1,107 @@
|
||||
from PIL import Image, ImageFilter, ImageEnhance, ImageOps, ImageFont, ImageDraw
|
||||
import os
|
||||
from pydub import AudioSegment
|
||||
from om2bms.data_structures import OsuTimingPoint
|
||||
|
||||
def appratio(t: int,b: int, val: float) -> int:
|
||||
"""
|
||||
calculates a fixed ratio with t and b to then convert val according to that ratio.
|
||||
"""
|
||||
return int((t/b)*val)
|
||||
|
||||
def cut_save_preview_audio(path_to_audio: str, preview_time: int, timing_points: list[OsuTimingPoint]) -> None:
|
||||
"""
|
||||
Retrives a segment of an audio file and saves as preview_{filename}.mp3
|
||||
"""
|
||||
|
||||
filename = os.path.basename(path_to_audio)
|
||||
extention = filename.split(".")[-1]
|
||||
file_dir = os.path.dirname(path_to_audio)
|
||||
audio = AudioSegment.from_file(path_to_audio, format=extention)
|
||||
segment_length = 20000 # in milliseconds
|
||||
interval = [0,0]
|
||||
|
||||
if preview_time >= 0: # if there was already a preview starting point defined in the osu map
|
||||
preview_time_end = preview_time + segment_length
|
||||
|
||||
if len(audio) < preview_time_end:
|
||||
interval = [preview_time, len(audio)]
|
||||
else:
|
||||
interval = [preview_time, preview_time_end]
|
||||
|
||||
elif timing_points != [] and any([tp.kiai_mode for tp in timing_points]): # if no defined preview point, take first kiai section
|
||||
i = 0
|
||||
while not timing_points[i].kiai_mode:
|
||||
i += 1
|
||||
|
||||
start = timing_points[i].time
|
||||
end = start + segment_length
|
||||
|
||||
if end > len(audio):
|
||||
end = len(audio)
|
||||
|
||||
interval = [start, end]
|
||||
|
||||
else: # if neither of the above, take default preview point that starts at 40% of the song
|
||||
start = int(len(audio)*0.4)
|
||||
end = len(audio) if (start+segment_length) > len(audio) else start + segment_length
|
||||
interval = [start, end]
|
||||
|
||||
preview_audio = audio[interval[0]:interval[1]]
|
||||
new_filename = "preview_"+filename
|
||||
|
||||
preview_audio.export(os.path.join(file_dir, new_filename), format=extention)
|
||||
|
||||
|
||||
def size_bg_thumbnail(path_to_image: str, creator: str, beatmapid: str, thumbnail_size = (1000, 750)) -> None:
|
||||
"""
|
||||
Resizes image to 700x700. Add black borders if image is widescreen.
|
||||
"""
|
||||
|
||||
source_image = Image.open(path_to_image).convert("RGB")
|
||||
background = source_image
|
||||
(sw, sh) = source_image.size
|
||||
thumbnail_w, thumbnail_h = thumbnail_size
|
||||
|
||||
thumbnail_aspect = round(thumbnail_w/thumbnail_h, 3)
|
||||
source_aspect = round(sw/sh, 3)
|
||||
# print(thumbnail_aspect, source_aspect)
|
||||
|
||||
if thumbnail_aspect == source_aspect or source_aspect < 1.333:
|
||||
# if it's already the desired aspect, we'll only resize it and do no more processing on it.
|
||||
background.thumbnail((thumbnail_w, thumbnail_h))
|
||||
# background.show()
|
||||
background.save(path_to_image)
|
||||
background.close()
|
||||
else:
|
||||
# if it's not the desired aspect ratio, we fit it to an image with that aspect ratio (we also add text to the image in this case)
|
||||
|
||||
zoomed_w, zoomed_h = round((sw/sh)*thumbnail_w), thumbnail_h
|
||||
# print(w, zoomed_w, h, zoomed_h)
|
||||
background.resize((zoomed_h, zoomed_w)) # resizes to h=700 aspect ratio
|
||||
background = ImageEnhance.Brightness(background).enhance(0.5) # dims image to 40% brightness
|
||||
background = background.filter(ImageFilter.GaussianBlur(6)) # blurs image
|
||||
background = ImageOps.fit(background, thumbnail_size) # fits/crops background image to the desired size
|
||||
|
||||
source_image.thumbnail(thumbnail_size) # resizes source image
|
||||
paste_start_y = (thumbnail_h-source_image.height) // 2
|
||||
background.paste(source_image, (0, paste_start_y)) # places source image centered into the background
|
||||
|
||||
curr_path = os.path.dirname(__file__) #because of some weird fucking path issue that the code is too dumb to understand (I spent an hour finding out this was the issue)
|
||||
font = ImageFont.truetype(os.path.join(curr_path, "allerregular.ttf"), appratio(22,700,thumbnail_w))
|
||||
draw = ImageDraw.Draw(background)
|
||||
|
||||
# mapper
|
||||
text_offset = appratio(10,700, thumbnail_w)
|
||||
draw.text((text_offset ,paste_start_y-text_offset), "mapped by "+creator, (255,255,255), anchor="lb", font=font)
|
||||
# map uid
|
||||
draw.text((thumbnail_w-text_offset, paste_start_y + source_image.height + text_offset), "uid: /"+str(beatmapid), anchor="rt", font=font)
|
||||
|
||||
|
||||
|
||||
# background.show()
|
||||
|
||||
background.save(path_to_image)
|
||||
background.close()
|
||||
|
||||
# black_background_thumbnail("./lol.jpg", "Thor", "236", (700, 525))
|
||||
@@ -0,0 +1,534 @@
|
||||
import codecs
|
||||
import os
|
||||
import re
|
||||
|
||||
from typing import Union, List, Tuple, Dict
|
||||
from fractions import Fraction
|
||||
from math import gcd
|
||||
from functools import reduce
|
||||
|
||||
# import om2bms.image_resizer
|
||||
from om2bms.data_structures import OsuMania
|
||||
from om2bms.data_structures import OsuTimingPoint
|
||||
from om2bms.data_structures import OsuManiaNote
|
||||
from om2bms.data_structures import OsuManiaLongNote
|
||||
from om2bms.data_structures import OsuBGSoundEvent
|
||||
from om2bms.data_structures import BMSMeasure
|
||||
from om2bms.data_structures import calculate_bpm
|
||||
from om2bms.osu import OsuBeatmapReader
|
||||
from om2bms.exceptions import OsuGameTypeException
|
||||
from om2bms.exceptions import OsuParseException
|
||||
from om2bms.exceptions import BMSMaxMeasuresException
|
||||
|
||||
|
||||
class OsuManiaToBMSParser:
|
||||
"""
|
||||
in_file: path to osu file to convert
|
||||
out_dir: directory to output the converted bms file
|
||||
filename: the name to print to console when converting
|
||||
"""
|
||||
_ms_to_inverse_note_values = {}
|
||||
_mania_note_to_channel = {
|
||||
0: 16,
|
||||
1: 11,
|
||||
2: 12,
|
||||
3: 13,
|
||||
4: 14,
|
||||
5: 15,
|
||||
6: 18,
|
||||
7: 19
|
||||
}
|
||||
_mania_ln_to_channel = {
|
||||
0: 56,
|
||||
1: 51,
|
||||
2: 52,
|
||||
3: 53,
|
||||
4: 54,
|
||||
5: 55,
|
||||
6: 58,
|
||||
7: 59
|
||||
}
|
||||
_convertion_options = {}
|
||||
_out_file = None
|
||||
|
||||
def __init__(self, in_file, out_dir, filename):
|
||||
self.reset()
|
||||
self.bg_filename = None
|
||||
self.audio_filepath = None
|
||||
self.failed = False
|
||||
try:
|
||||
self.beatmap = OsuBeatmapReader(in_file)
|
||||
except OsuGameTypeException:
|
||||
self.failed = True
|
||||
return
|
||||
except OsuParseException as e:
|
||||
self.failed = True
|
||||
print(e)
|
||||
return
|
||||
print("\tConverting " + filename)
|
||||
|
||||
self.beatmap = self.beatmap.get_parsed_beatmap()
|
||||
|
||||
bms_filename = self.beatmap.title + " " + self.beatmap.version + ".bms"
|
||||
bms_filename = re.sub('[\\/:"*?<>|]+', "", bms_filename)
|
||||
output = os.path.join(out_dir, bms_filename)
|
||||
OsuManiaToBMSParser._out_file = codecs.open(output, "w", "shiftjis", errors="replace")
|
||||
|
||||
self.write_buffer(self.create_header())
|
||||
music_start_param = self.music_start_time(self.beatmap)
|
||||
self.get_next_measure(music_start_param[0], music_start_param[1], self.beatmap)
|
||||
|
||||
OsuManiaToBMSParser._out_file.close()
|
||||
|
||||
file = os.path.dirname(in_file)
|
||||
if OsuManiaToBMSParser._convertion_options["BG"] and self.beatmap.stagebg is not None and \
|
||||
os.path.isfile(os.path.join(file, self.beatmap.stagebg)):
|
||||
# om2bms.image_resizer.black_background_thumbnail(os.path.join(file, self.beatmap.stagebg))
|
||||
self.bg_filename = os.path.join(file, self.beatmap.stagebg)
|
||||
|
||||
if self.beatmap.audio_filename is not None and os.path.isfile(os.path.join(file, self.beatmap.audio_filename)):
|
||||
self.audio_filepath = os.path.join(file, self.beatmap.audio_filename)
|
||||
|
||||
if self.beatmap.video_filename is not None and os.path.isfile(os.path.join(file, self.beatmap.video_filename)):
|
||||
self.video_filename = os.path.join(file, self.beatmap.video_filename)
|
||||
|
||||
def get_bg(self):
|
||||
"""
|
||||
Returns bg filename
|
||||
"""
|
||||
return self.bg_filename
|
||||
|
||||
def get_audio_path(self):
|
||||
"""
|
||||
Returns path to map audio
|
||||
"""
|
||||
return self.audio_filepath
|
||||
|
||||
def get_video_name(self):
|
||||
"""
|
||||
Returns filename to map video
|
||||
"""
|
||||
return self.video_filename
|
||||
|
||||
def reset(self):
|
||||
"""
|
||||
Resets class variables
|
||||
"""
|
||||
OsuManiaToBMSParser._out_file = None
|
||||
OsuBeatmapReader._latest_tp_index = 0
|
||||
OsuBeatmapReader._latest_noninherited_tp_index = 0
|
||||
OsuBeatmapReader._sample_index = 1
|
||||
BMSMeasure._hit_sounds = OsuManiaToBMSParser._convertion_options["HITSOUND"]
|
||||
|
||||
def write_buffer(self, buffer: Union[BMSMeasure, List[str]]):
|
||||
"""
|
||||
Writes to file. \n between each element in buffer if list
|
||||
"""
|
||||
if buffer is None:
|
||||
return
|
||||
elif isinstance(buffer, BMSMeasure):
|
||||
for line in buffer.lines:
|
||||
OsuManiaToBMSParser._out_file.write(str(line))
|
||||
else:
|
||||
for line in buffer:
|
||||
OsuManiaToBMSParser._out_file.write(line)
|
||||
OsuManiaToBMSParser._out_file.write("\n")
|
||||
OsuManiaToBMSParser._out_file.write("\n")
|
||||
|
||||
def expansion_wrapper(self, n, ms_per_measure) -> Fraction:
|
||||
"""
|
||||
Approximates n, where 0 < n < 1, to p/q where q=2^i or 3 * 2^i up to q=192.
|
||||
"""
|
||||
def expander(n, ms_per_measure, meter, end):
|
||||
"""
|
||||
Generalized expander for non upper number of 3 or 4 measures.
|
||||
"""
|
||||
def within_offset(num, sum__, offset):
|
||||
"""
|
||||
return true if within
|
||||
"""
|
||||
return int(ms_per_measure * num) - 1 < ms_per_measure * (sum__ + offset) < int(ms_per_measure * num) + 2
|
||||
done = False
|
||||
denominator = meter
|
||||
sum_ = Fraction(1, meter)
|
||||
while sum_ + Fraction(1, denominator) < n:
|
||||
sum_ += Fraction(1, denominator)
|
||||
iterations = 0
|
||||
while iterations < 6:
|
||||
if within_offset(n, sum_, 0) or round(n, 5) == round(float(sum_), 5):
|
||||
done = True
|
||||
break
|
||||
if float(sum_) > n:
|
||||
sum_ -= Fraction(1, denominator)
|
||||
denominator *= 2
|
||||
elif float(sum_) < n:
|
||||
sum_ += Fraction(1, denominator)
|
||||
denominator *= 2
|
||||
iterations += 1
|
||||
# pad with maxs
|
||||
while not done:
|
||||
if within_offset(n, sum_, 0):
|
||||
break
|
||||
prev_error = abs(n - sum_)
|
||||
if sum_ > n:
|
||||
if within_offset(n, sum_, -Fraction(1, end)):
|
||||
sum_ -= Fraction(1, end)
|
||||
break
|
||||
elif abs(n - (prev_error - Fraction(1, end))) > sum_ - Fraction(1, end):
|
||||
break
|
||||
sum_ -= Fraction(1, end)
|
||||
elif sum_ < n:
|
||||
if within_offset(n, sum_, Fraction(1, end)):
|
||||
sum_ += Fraction(1, end)
|
||||
break
|
||||
elif abs(n - (prev_error + Fraction(1, end))) < sum_ - Fraction(1, end):
|
||||
break
|
||||
sum_ += Fraction(1, end)
|
||||
return (abs(n - sum_), sum_)
|
||||
|
||||
error2 = expander(n, ms_per_measure, 4, 128)
|
||||
error3 = expander(n, ms_per_measure, 3, 192)
|
||||
error = error2 if error2[0] < error3[0] else error3
|
||||
time_value = error[1]
|
||||
if time_value == 1:
|
||||
return Fraction(0, 1)
|
||||
if time_value != 0:
|
||||
self.add_to_mtnv(time_value * ms_per_measure, time_value)
|
||||
return error[1]
|
||||
|
||||
def music_start_time(self, beatmap: OsuMania):
|
||||
"""
|
||||
Returns the measure offset and ms of first measure. Calls BMSMeasure and BMSMainDataLine on the BGM start line.
|
||||
"""
|
||||
first_object = beatmap.objects[0]
|
||||
first_timing = beatmap.timing_points[0]
|
||||
ms_per_measure = first_timing.meter * first_timing.ms_per_beat
|
||||
use_obj = False
|
||||
if first_object.time < first_timing.time:
|
||||
start_time = first_object.time
|
||||
use_obj = True
|
||||
else:
|
||||
start_time = first_timing.time
|
||||
# find first obj on down beat
|
||||
if use_obj:
|
||||
i = 0
|
||||
while beatmap.objects[i].time < first_timing.time:
|
||||
i += 1
|
||||
start_time = beatmap.objects[i].time
|
||||
while start_time - ms_per_measure > 0:
|
||||
start_time -= ms_per_measure
|
||||
# start_time_offset is the time from 0 ms to the first obj
|
||||
start_time_offset = ms_per_measure - start_time if start_time > 0 else abs(start_time)
|
||||
|
||||
start_time_offset += OsuManiaToBMSParser._convertion_options["OFFSET"]
|
||||
|
||||
mus_start_at_001 = True if first_object.time + ms_per_measure < ms_per_measure else False
|
||||
|
||||
sto_fraction = start_time_offset / ms_per_measure
|
||||
time_value_ratio = self.expansion_wrapper(sto_fraction, ms_per_measure)
|
||||
if time_value_ratio == 0 and mus_start_at_001:
|
||||
bms_measure = BMSMeasure("001")
|
||||
measure_start = 1
|
||||
bms_measure.create_data_line("01", time_value_ratio.denominator, [(time_value_ratio.numerator, "01")])
|
||||
else:
|
||||
if mus_start_at_001:
|
||||
bms_measure = BMSMeasure("001")
|
||||
measure_start = 1
|
||||
else:
|
||||
bms_measure = BMSMeasure("000")
|
||||
if time_value_ratio == 0:
|
||||
measure_start = 0
|
||||
else:
|
||||
measure_start = 1
|
||||
bms_measure.create_data_line("01", time_value_ratio.denominator, [(time_value_ratio.numerator, "01")])
|
||||
|
||||
measure_offset = measure_start
|
||||
if beatmap.objects[0].time > start_time:
|
||||
while not start_time >= beatmap.objects[0].time:
|
||||
start_time += ms_per_measure
|
||||
measure_offset += 1
|
||||
else:
|
||||
measure_offset = 0 if measure_start == 0 else 1
|
||||
|
||||
if first_timing.meter != 4:
|
||||
if bms_measure.measure_number == "000":
|
||||
bms_measure.create_measure_length_change(first_timing.meter / 4)
|
||||
elif bms_measure.measure_number == "001":
|
||||
bms_measure0 = BMSMeasure("000")
|
||||
bms_measure0.create_measure_length_change(first_timing.meter / 4)
|
||||
self.write_buffer(bms_measure0)
|
||||
bms_measure.create_measure_length_change(first_timing.meter / 4)
|
||||
self.write_buffer(bms_measure)
|
||||
if first_timing.meter != 4:
|
||||
for i in range(1, measure_offset):
|
||||
bms_measure = BMSMeasure(str(i).zfill(3))
|
||||
bms_measure.create_measure_length_change(first_timing.meter / 4)
|
||||
self.write_buffer(bms_measure)
|
||||
|
||||
first_measure_time = int(start_time)
|
||||
if first_object.time < first_measure_time - 1:
|
||||
measure_offset -= 1
|
||||
first_measure_time -= ms_per_measure
|
||||
if time_value_ratio == 0 and not mus_start_at_001:
|
||||
while not self.within_2_ms(start_time, measure_offset * ms_per_measure):
|
||||
measure_offset += 1
|
||||
|
||||
self.initialize_mtnv()
|
||||
return (measure_offset, first_measure_time)
|
||||
|
||||
def get_next_measure(self, starting_measure: int, starting_ms: int, beatmap: OsuMania):
|
||||
"""
|
||||
Retrieves information for each measure.
|
||||
"""
|
||||
def add_to_measure(current_measure_, hitobjj_):
|
||||
"""
|
||||
Adds hitobj to measure
|
||||
"""
|
||||
if isinstance(hitobjj_, OsuManiaNote):
|
||||
column = hitobjj_.mania_column
|
||||
bmscolumn = OsuManiaToBMSParser._mania_note_to_channel[column]
|
||||
if bmscolumn not in current_measure_:
|
||||
current_measure_[OsuManiaToBMSParser._mania_note_to_channel[column]] = [hitobjj_]
|
||||
else:
|
||||
current_measure_[OsuManiaToBMSParser._mania_note_to_channel[column]].append(hitobjj_)
|
||||
elif isinstance(hitobjj_, OsuManiaLongNote):
|
||||
column = hitobjj_.mania_column
|
||||
bmscolumn = OsuManiaToBMSParser._mania_ln_to_channel[column]
|
||||
if bmscolumn not in current_measure_:
|
||||
current_measure_[OsuManiaToBMSParser._mania_ln_to_channel[column]] = [hitobjj_]
|
||||
else:
|
||||
current_measure_[OsuManiaToBMSParser._mania_ln_to_channel[column]].append(hitobjj_)
|
||||
elif isinstance(hitobjj_, OsuBGSoundEvent):
|
||||
column = 1
|
||||
if column not in current_measure_:
|
||||
current_measure_[column] = [hitobjj_]
|
||||
else:
|
||||
current_measure_[column].append(hitobjj_)
|
||||
elif isinstance(hitobjj_, OsuTimingPoint):
|
||||
if 0 not in current_measure_:
|
||||
current_measure_[0] = [hitobjj_]
|
||||
else:
|
||||
current_measure_[0] = [hitobjj_]
|
||||
|
||||
current_measure = {}
|
||||
|
||||
current_time_in_ms = starting_ms
|
||||
truncate_measure = False
|
||||
first_timing = beatmap.noninherited_tp[0]
|
||||
ms_per_measure = first_timing.ms_per_beat * first_timing.meter
|
||||
measure_number = starting_measure
|
||||
most_recent_tp = first_timing
|
||||
i = 0
|
||||
while i < len(beatmap.objects):
|
||||
hitobj = beatmap.objects[i]
|
||||
|
||||
if hitobj.time < int(current_time_in_ms + ms_per_measure) - 1 and not truncate_measure:
|
||||
if not isinstance(hitobj, OsuTimingPoint):
|
||||
add_to_measure(current_measure, hitobj)
|
||||
elif isinstance(hitobj, OsuTimingPoint) and self.within_2_ms(current_time_in_ms, hitobj.time):
|
||||
most_recent_tp = hitobj
|
||||
ms_per_measure = hitobj.ms_per_beat * hitobj.meter
|
||||
current_time_in_ms = hitobj.time
|
||||
add_to_measure(current_measure, hitobj)
|
||||
else:
|
||||
truncate_measure = True
|
||||
else: # hitobj.starttime >= current_time_in_ms + ms_per_measure:
|
||||
if truncate_measure:
|
||||
if hitobj.time - current_time_in_ms < 0:
|
||||
truncation_frac = (hitobj.time - (current_time_in_ms - ms_per_measure)) / ms_per_measure
|
||||
else:
|
||||
truncation_frac = (hitobj.time - current_time_in_ms) / ms_per_measure
|
||||
truncation_float = float(self.expansion_wrapper(truncation_frac, ms_per_measure))
|
||||
bmsmeasure = self.create_measure(current_measure, most_recent_tp, current_time_in_ms,
|
||||
str(measure_number).zfill(3),
|
||||
truncation_float)
|
||||
truncate_measure = False
|
||||
self.write_buffer(bmsmeasure)
|
||||
self.initialize_mtnv()
|
||||
measure_number += 1
|
||||
most_recent_tp = hitobj
|
||||
ms_per_measure = hitobj.ms_per_beat * hitobj.meter
|
||||
current_time_in_ms = hitobj.time
|
||||
current_measure = {}
|
||||
add_to_measure(current_measure, hitobj)
|
||||
|
||||
i += 1
|
||||
continue
|
||||
else:
|
||||
bmsmeasure = self.create_measure(current_measure, most_recent_tp, current_time_in_ms,
|
||||
str(measure_number).zfill(3), 0)
|
||||
|
||||
self.write_buffer(bmsmeasure)
|
||||
|
||||
# move to next measure with hitnotes
|
||||
while not self.within_2_ms(current_time_in_ms, hitobj.time):
|
||||
measure_number += 1
|
||||
current_time_in_ms += ms_per_measure
|
||||
|
||||
if hitobj.time < int(current_time_in_ms + ms_per_measure) - 1:
|
||||
if isinstance(hitobj, OsuTimingPoint) and not self.within_2_ms(current_time_in_ms, hitobj.time):
|
||||
truncate_measure = True
|
||||
elif isinstance(hitobj, OsuTimingPoint) and self.within_2_ms(current_time_in_ms, hitobj.time):
|
||||
most_recent_tp = hitobj
|
||||
self.initialize_mtnv()
|
||||
ms_per_measure = hitobj.ms_per_beat * hitobj.meter
|
||||
current_time_in_ms = hitobj.time
|
||||
current_measure = {}
|
||||
add_to_measure(current_measure, hitobj)
|
||||
break
|
||||
|
||||
if measure_number > 999:
|
||||
raise BMSMaxMeasuresException("Exceeded 999 measures")
|
||||
|
||||
if not truncate_measure:
|
||||
i += 1
|
||||
|
||||
# for the last measure (outside loop)
|
||||
bmsmeasure = self.create_measure(current_measure, most_recent_tp, current_time_in_ms,
|
||||
str(measure_number).zfill(3), 0)
|
||||
self.write_buffer(bmsmeasure)
|
||||
|
||||
def initialize_mtnv(self) -> None:
|
||||
"""
|
||||
Reset _ms_to_inverse_note_values (bpm changes)
|
||||
"""
|
||||
OsuManiaToBMSParser._ms_to_inverse_note_values = {}
|
||||
|
||||
def add_to_mtnv(self, key: int, value: Fraction):
|
||||
"""
|
||||
Wrapper to add into mtnv
|
||||
"""
|
||||
OsuManiaToBMSParser._ms_to_inverse_note_values[key] = value
|
||||
OsuManiaToBMSParser._ms_to_inverse_note_values[key - 1] = value
|
||||
OsuManiaToBMSParser._ms_to_inverse_note_values[key + 1] = value
|
||||
|
||||
def within_2_ms(self, base, n) -> bool:
|
||||
"""
|
||||
True if n is close enough to base
|
||||
"""
|
||||
return base - 2 <= n <= base + 2
|
||||
|
||||
def create_measure(self, current_measure, timing_point: OsuTimingPoint, measure_start: float,
|
||||
measure_number: str, measure_truncation: float):
|
||||
"""
|
||||
Creates a BMSMeasure containing linedata
|
||||
"""
|
||||
def get_numerator_with_gcd(fraction, gcd_) -> int:
|
||||
"""
|
||||
Returns numerator of fraction with denom of gcd
|
||||
"""
|
||||
if fraction[1] == gcd_:
|
||||
return fraction[0]
|
||||
elif fraction[1] < gcd_:
|
||||
fraction[0] *= 2
|
||||
fraction[1] *= 2
|
||||
return get_numerator_with_gcd(fraction, gcd_)
|
||||
else: # fraction[1] > gcd: (switch from
|
||||
if fraction[1] % 3 == 0:
|
||||
fraction[0] //= 3
|
||||
fraction[1] //= 3
|
||||
else:
|
||||
fraction[0] //= 4
|
||||
fraction[0] *= 3
|
||||
fraction[1] //= 4
|
||||
fraction[1] *= 3
|
||||
return get_numerator_with_gcd(fraction, gcd_)
|
||||
|
||||
# if the measure is empty skip
|
||||
if len(current_measure) == 0:
|
||||
return
|
||||
|
||||
bms_measure = BMSMeasure(measure_number)
|
||||
if timing_point.meter != 4:
|
||||
bms_measure.create_measure_length_change(timing_point.meter / 4)
|
||||
self.initialize_mtnv()
|
||||
elif measure_truncation != 0:
|
||||
bms_measure.create_measure_length_change(measure_truncation)
|
||||
ms_per_measure = timing_point.meter * timing_point.ms_per_beat
|
||||
|
||||
if len(current_measure) != 0:
|
||||
for key in sorted(current_measure.keys()):
|
||||
# get notes from column/key and put them into a line
|
||||
denoms = []
|
||||
locations = [] # temp
|
||||
locations_ = [] # to be passed into bmsmaindataline
|
||||
for note in current_measure[key]:
|
||||
# if first_note:
|
||||
time_value_ms = round(abs(measure_start - note.time), 5)
|
||||
if self.within_2_ms(time_value_ms, 0):
|
||||
time_value_ratio = Fraction(0, 1)
|
||||
elif int(time_value_ms) in OsuManiaToBMSParser._ms_to_inverse_note_values:
|
||||
time_value_ratio = OsuManiaToBMSParser._ms_to_inverse_note_values[int(time_value_ms)]
|
||||
else:
|
||||
time_value_ratio = self.expansion_wrapper(time_value_ms / ms_per_measure, ms_per_measure)
|
||||
denoms.append(time_value_ratio.denominator)
|
||||
locations.append(([time_value_ratio.numerator, time_value_ratio.denominator], note))
|
||||
|
||||
if key == 0 and not current_measure[key][0].inherited:
|
||||
new_bpm = calculate_bpm(current_measure[key][0])
|
||||
if new_bpm <= 255 and isinstance(new_bpm, int):
|
||||
bms_measure.create_bpm_change_line(new_bpm)
|
||||
else:
|
||||
bms_measure.create_bpm_extended_change_line(new_bpm, self.beatmap.float_bpm)
|
||||
elif key == 1:
|
||||
locations_ = sorted(locations, key=lambda x: x[0])
|
||||
for i in range(len(locations)):
|
||||
bms_measure.create_data_line(str(key).zfill(2), locations_[i][0][1],
|
||||
[(locations_[i][0][0], locations_[i][1])])
|
||||
else:
|
||||
# make all denomaintors = to gcd
|
||||
gcd_ = reduce(lambda a, b: a * b // gcd(a, b), denoms)
|
||||
for list_ in locations:
|
||||
locations_.append((get_numerator_with_gcd(list_[0], gcd_), list_[1]))
|
||||
bms_measure.create_data_line(str(key).zfill(2), gcd_, sorted(locations_, key=lambda x: x[0]))
|
||||
|
||||
return bms_measure
|
||||
|
||||
def create_header(self) -> List[str]:
|
||||
"""
|
||||
Makes everything before maindata field
|
||||
"""
|
||||
# HEADER FIELD
|
||||
buffer = list([""])
|
||||
buffer.append("*---------------------- HEADER FIELD")
|
||||
buffer.append("")
|
||||
buffer.append("#PLAYER 1")
|
||||
buffer.append("#GENRE " + self.beatmap.creator)
|
||||
buffer.append("#TITLE " + self.beatmap.title_unicode)
|
||||
if str(self.beatmap.key_count) + "k" not in self.beatmap.version.lower(): # addes [nk] prefix to the diff name
|
||||
diff_key_count = "[" + str(self.beatmap.key_count) + "K] "
|
||||
buffer.append("#SUBTITLE " + diff_key_count + self.beatmap.version)
|
||||
else:
|
||||
buffer.append("#SUBTITLE " + self.beatmap.version)
|
||||
buffer.append("#ARTIST " + self.beatmap.artist_unicode)
|
||||
# buffer.append("#SUBARTIST " + beatmap.artist)
|
||||
buffer.append("#BPM " + str(int(calculate_bpm(self.beatmap.timing_points[0]))))
|
||||
buffer.append("#PLAYLEVEL " + "0") # initially 5
|
||||
buffer.append("#RANK " + str(OsuManiaToBMSParser._convertion_options["JUDGE"]))
|
||||
buffer.append("")
|
||||
for hs in self.beatmap.hitsound_names:
|
||||
buffer.append("#WAV" + hs[0] + " " + str(hs[1]))
|
||||
buffer.append("")
|
||||
if self.beatmap.audio_filename is not None: # is for preview audio
|
||||
buffer.append("#PREVIEW " + "preview_" + self.beatmap.audio_filename)
|
||||
if self.beatmap.video_filename is not None and OsuManiaToBMSParser._convertion_options["VIDEO"]: #TODO add to _conversion_options so that it isn't added by default => adding to cmd UI also
|
||||
buffer.append("#VIDEOFILE " + self.beatmap.video_filename)
|
||||
if self.beatmap.stagebg is not None and OsuManiaToBMSParser._convertion_options["BG"]:
|
||||
buffer.append("#BMP01 " + self.beatmap.stagebg)
|
||||
buffer.append("#STAGEFILE " + self.beatmap.stagebg) # allows you to preview the map bg in song select
|
||||
buffer.append("")
|
||||
if len(self.beatmap.float_bpm) > 0:
|
||||
for e in self.beatmap.float_bpm:
|
||||
buffer.append("#BPM" + str(e[0]) + " " + str(e[1]))
|
||||
buffer.append("")
|
||||
# BGM FIELD
|
||||
buffer.append("*---------------------- EXPANSION FIELD")
|
||||
buffer.append("")
|
||||
|
||||
buffer.append("*---------------------- MAIN DATA FIELD")
|
||||
buffer.append("")
|
||||
buffer.append("")
|
||||
if self.beatmap.stagebg is not None and OsuManiaToBMSParser._convertion_options["BG"]:
|
||||
buffer.append("#00004:01")
|
||||
|
||||
return buffer
|
||||
@@ -0,0 +1,399 @@
|
||||
import copy
|
||||
import codecs
|
||||
|
||||
from om2bms.data_structures import OsuMania
|
||||
from om2bms.data_structures import OsuTimingPoint
|
||||
from om2bms.data_structures import OsuBGSoundEvent
|
||||
from om2bms.data_structures import HitSound
|
||||
from om2bms.data_structures import OsuManiaNote
|
||||
from om2bms.data_structures import OsuManiaLongNote
|
||||
from om2bms.data_structures import calculate_bpm
|
||||
from om2bms.exceptions import OsuGameTypeException
|
||||
from om2bms.exceptions import OsuParseException
|
||||
|
||||
|
||||
class OsuBeatmapReader:
|
||||
"""Parses information from .osu file to OsuMania class. """
|
||||
_latest_tp_index = 0
|
||||
_latest_noninherited_tp_index = 0
|
||||
_sample_index = 1
|
||||
|
||||
def __init__(self, input_file):
|
||||
self.osumania_beatmap = OsuMania()
|
||||
self.parse(input_file, self.osumania_beatmap)
|
||||
|
||||
def get_parsed_beatmap(self):
|
||||
"""
|
||||
Returns the parsed beatmap.
|
||||
"""
|
||||
return self.osumania_beatmap
|
||||
|
||||
def parse(self, input_file, osumania_beatmap):
|
||||
"""
|
||||
Parses beatmap
|
||||
"""
|
||||
def header_hitobjects(line, beatmap):
|
||||
"""
|
||||
Parses header HitObjects
|
||||
"""
|
||||
def decode_bits(num: int) -> int:
|
||||
"""
|
||||
For when sample_set plays > 1 hitsound at the same time. Take only the largest
|
||||
"""
|
||||
if num > 8:
|
||||
return 8
|
||||
elif num > 4:
|
||||
return 4
|
||||
elif num > 2:
|
||||
return 2
|
||||
else:
|
||||
return 1
|
||||
ln_buffer = None
|
||||
type_ln = False
|
||||
line_separated = parse_symbol_separated(line, ',')
|
||||
if len(line_separated) < 4:
|
||||
OsuParseException("HitObject Error: Invalid Syntax")
|
||||
hit_object_type = line_separated[3]
|
||||
hit_object_arg = parse_symbol_separated(line_separated[-1], ':')
|
||||
|
||||
hit_object = None
|
||||
if hit_object_type == "1" or hit_object_type == "5": # single note
|
||||
hit_object = OsuManiaNote()
|
||||
if hit_object_type == "5":
|
||||
hit_object.new_combo = True
|
||||
elif hit_object_type == "2" or hit_object_type == "6": # o!std slider
|
||||
return
|
||||
elif hit_object_type == "8" or hit_object_type == "12": # o!std spinner
|
||||
return
|
||||
elif hit_object_type == "132" or hit_object_type == "128": # o!m longnote
|
||||
type_ln = True
|
||||
hit_object = OsuManiaLongNote(int(hit_object_arg[0]))
|
||||
ln_buffer = OsuManiaLongNote(int(hit_object_arg[0]))
|
||||
if hit_object_type == "128":
|
||||
hit_object.new_combo = True
|
||||
else:
|
||||
raise OsuParseException("HitObject Error: type " + hit_object_type + " not found in " + line)
|
||||
|
||||
#! This is where the column conversion will be done for lower key counts.
|
||||
# column index = floor(x*y/512) = floor(x/512/y)
|
||||
# x = index * 512/y
|
||||
lt7keys = {
|
||||
6: {0:0, 1:1, 2:2,
|
||||
3:3, 4:4, 5:5},
|
||||
|
||||
5: {0:1, 1:2, 2:3,
|
||||
3:4, 4:5},
|
||||
|
||||
4: {0:2, 1:3,
|
||||
2:5, 3:6},
|
||||
|
||||
3: {0:3, 1:4, 2:5},
|
||||
2: {0:0, 2:4},
|
||||
}
|
||||
if beatmap.key_count == 7:
|
||||
hit_object.mania_column = (int(line_separated[0]) // (512 // beatmap.key_count)) + 1 \
|
||||
if line_separated[0] != "0" else 0
|
||||
elif beatmap.key_count in range(2, 9):
|
||||
hit_object.mania_column = (int(line_separated[0]) // (512 // beatmap.key_count))
|
||||
if beatmap.key_count != 8:
|
||||
# uses dictionary to redefine which column it's in depending on keycount
|
||||
hit_object.mania_column = lt7keys[beatmap.key_count][hit_object.mania_column]
|
||||
|
||||
hit_object.hit_sound = int(line_separated[4])
|
||||
hit_object.time = int(line_separated[2])
|
||||
|
||||
if OsuBeatmapReader._latest_tp_index < len(beatmap.timing_points) - 1 and \
|
||||
beatmap.timing_points[OsuBeatmapReader._latest_tp_index + 1].time <= hit_object.time:
|
||||
OsuBeatmapReader._latest_tp_index += 1
|
||||
|
||||
hitsound_int = int(line_separated[4]) if int(line_separated[4]) in [0, 1, 2, 4, 8] else \
|
||||
decode_bits(int(line_separated[4]))
|
||||
timing_point = beatmap.timing_points[OsuBeatmapReader._latest_tp_index]
|
||||
if type_ln:
|
||||
filename = "" if len(hit_object_arg) < 5 else hit_object_arg[5].strip()
|
||||
sample_set = int(hit_object_arg[1])
|
||||
else:
|
||||
filename = "" if len(hit_object_arg) < 4 else hit_object_arg[4].strip()
|
||||
sample_set = int(hit_object_arg[0])
|
||||
|
||||
if filename == "" and hitsound_int == 0:
|
||||
hitsound = None
|
||||
else:
|
||||
if sample_set == 0:
|
||||
sample_set = timing_point.sample_set
|
||||
custom_index = int(hit_object_arg[3]) if type_ln else int(hit_object_arg[2])
|
||||
hs_id = (hitsound_int, sample_set, custom_index, filename)
|
||||
if hs_id not in beatmap.hitsounds:
|
||||
hitsound = HitSound(hitsound_int, timing_point, sample_set, custom_index, filename, OsuBeatmapReader._sample_index)
|
||||
OsuBeatmapReader._sample_index += 1
|
||||
beatmap.hitsounds[hs_id] = hitsound
|
||||
beatmap.hitsound_names.append(hitsound.get_info())
|
||||
else:
|
||||
hitsound = beatmap.hitsounds[hs_id]
|
||||
|
||||
hit_object.hit_sound = hitsound
|
||||
hit_object.timing_point = timing_point
|
||||
beatmap.hit_objects.append(hit_object)
|
||||
if ln_buffer is not None:
|
||||
ln_buffer.time = hit_object.end_time
|
||||
ln_buffer.end_time = hit_object.end_time
|
||||
ln_buffer.mania_column = hit_object.mania_column
|
||||
beatmap.hit_objects.append(ln_buffer)
|
||||
|
||||
def header_timingpoints(line, beatmap):
|
||||
"""
|
||||
Parses header TimingPoints:
|
||||
"""
|
||||
def get_ms_per_beat(ms, _beatmap):
|
||||
"""
|
||||
Takes care of negative values found in Timing Points
|
||||
"""
|
||||
if ms >= 0:
|
||||
return ms
|
||||
else:
|
||||
for _tp in reversed(_beatmap.timing_points):
|
||||
if not _tp.inherited:
|
||||
return (abs(ms) / 100) * _tp.ms_per_beat
|
||||
raise OsuParseException("Non inherited BPM not found. Timing points are broken")
|
||||
|
||||
line_separated = parse_symbol_separated(line, ',')
|
||||
if len(line_separated) != 8:
|
||||
raise OsuParseException("TimingPoint Error: Invalid Syntax")
|
||||
tp = OsuTimingPoint()
|
||||
tp.time = int(float(line_separated[0]))
|
||||
tp.inherited = True if int(line_separated[6]) == 0 else False
|
||||
tp.meter = int(line_separated[2])
|
||||
tp.sample_set = int(line_separated[3])
|
||||
tp.sample_index = int(line_separated[4])
|
||||
tp.volume = int(line_separated[5])
|
||||
tp.kiai_mode = False if line_separated[7] == 0 else True
|
||||
# delete previous tp if new tp causes old tp to last only a few ms
|
||||
if len(beatmap.timing_points) > 0 and tp.time <= beatmap.timing_points[-1].time + 2 and not tp.inherited:
|
||||
del beatmap.timing_points[-1]
|
||||
if tp.inherited:
|
||||
tp.ms_per_beat = get_ms_per_beat(float(line_separated[1]), beatmap)
|
||||
prev_tp = beatmap.timing_points[-1]
|
||||
if len(beatmap.timing_points) > 0 and tp.time <= prev_tp.time + 1 and \
|
||||
tp.sample_set != prev_tp.sample_set and tp.sample_index != prev_tp.sample_index:
|
||||
del beatmap.timing_points[-1]
|
||||
else:
|
||||
tp.ms_per_beat = float(line_separated[1])
|
||||
bpm = calculate_bpm(tp)
|
||||
if isinstance(bpm, float) or bpm > 255:
|
||||
beatmap.parse_float_bpm(bpm)
|
||||
if len(beatmap.timing_points) > 0 and tp.time <= beatmap.noninherited_tp[-1].time + 1:
|
||||
del beatmap.noninherited_tp[-1]
|
||||
beatmap.noninherited_tp.append(tp)
|
||||
beatmap.timing_points.append(tp)
|
||||
|
||||
def header_events(line, beatmap):
|
||||
"""
|
||||
Parses header Events
|
||||
"""
|
||||
line_separated = parse_symbol_separated(line, ',')
|
||||
if len(line_separated) < 1:
|
||||
OsuParseException("Events Error: Invalid Syntax")
|
||||
event = {}
|
||||
if line_separated[0] == "Sample":
|
||||
if len(line_separated) != 5:
|
||||
raise OsuParseException("Events Error: Invalid Syntax")
|
||||
time = int(line_separated[1])
|
||||
filename = str(line_separated[3][1:-1])
|
||||
if filename not in beatmap.filename_to_sample.keys():
|
||||
beatmap.sample_filenames.append(filename)
|
||||
sample = OsuBGSoundEvent(time, filename, OsuBeatmapReader._sample_index)
|
||||
OsuBeatmapReader._sample_index += 1
|
||||
beatmap.filename_to_sample[filename] = sample
|
||||
beatmap.sample_objects.append(sample)
|
||||
beatmap.hitsound_names.append(sample.get_info())
|
||||
else:
|
||||
sample = beatmap.filename_to_sample[filename]
|
||||
new_sample = copy.deepcopy(sample)
|
||||
new_sample.time = time
|
||||
beatmap.sample_objects.append(new_sample)
|
||||
|
||||
elif line_separated[0] == "Video":
|
||||
if len(line_separated) != 3:
|
||||
OsuParseException("Events Error: Invalid Syntax")
|
||||
else:
|
||||
beatmap.video_start_time = int(line_separated[1])
|
||||
beatmap.video_filename = line_separated[2].strip("\n").strip("\r")[1:-1]
|
||||
|
||||
elif len(line_separated) <= 5 and line_separated[0] == "0":
|
||||
temp = line_separated[2]
|
||||
temp = temp.replace('"', '').strip()
|
||||
sep = temp.split('.')
|
||||
if len(sep) == 2:
|
||||
beatmap.stagebg = sep[0] + "." + sep[1]
|
||||
|
||||
def header_difficulty(line, beatmap):
|
||||
"""
|
||||
Parses the header Difficulty
|
||||
"""
|
||||
line_property = get_line_property(line)
|
||||
if line_property[0] == "CircleSize":
|
||||
keycount = int(line_property[1])
|
||||
if keycount in range(2,9):
|
||||
beatmap.key_count = keycount
|
||||
else:
|
||||
raise OsuParseException("Only 2k-8k files are supported!")
|
||||
elif line_property[0] == "HPDrainRate":
|
||||
pass
|
||||
elif line_property[0] == "OverallDifficulty":
|
||||
beatmap.od = float(line_property[1])
|
||||
elif line_property[0] == "ApproachRate":
|
||||
pass
|
||||
else:
|
||||
OsuParseException("Attribute Error: " + line_property[0] + " not found")
|
||||
|
||||
def header_general(line, beatmap):
|
||||
"""
|
||||
Parses the header General
|
||||
"""
|
||||
line_property = get_line_property(line)
|
||||
if line_property[0] == "AudioFilename":
|
||||
audio_filename = line_property[1].strip()
|
||||
beatmap.audio_filename = audio_filename
|
||||
audio = HitSound(0, None, 0, 1, audio_filename, OsuBeatmapReader._sample_index)
|
||||
OsuBeatmapReader._sample_index += 1
|
||||
beatmap.hitsound_names.append(audio.get_info())
|
||||
elif line_property[0] == "AudioLeadIn":
|
||||
beatmap.audio_lead_in = int(line_property[1])
|
||||
elif line_property[0] == "PreviewTime":
|
||||
beatmap.preview_time = int(line_property[1])
|
||||
elif line_property[0] == "Countdown":
|
||||
pass
|
||||
elif line_property[0] == "SampleSet":
|
||||
beatmap.sample_set = str(line_property[1])
|
||||
pass
|
||||
elif line_property[0] == "StackLeniency":
|
||||
pass
|
||||
elif line_property[0] == "Mode":
|
||||
if not int(line_property[1]) == 3:
|
||||
raise OsuGameTypeException("Beatmap is not an o!m beatmap!")
|
||||
elif line_property[0] == "LetterboxInBreaks":
|
||||
pass
|
||||
elif line_property[0] == "SpecialStyle":
|
||||
if line_property[1] == 1:
|
||||
beatmap.special_style = True
|
||||
elif line_property[0] == "WidescreenStoryboard":
|
||||
pass
|
||||
|
||||
def header_metadata(line, beatmap):
|
||||
"""
|
||||
Parses the header Metadata
|
||||
"""
|
||||
line_property = get_line_property(line)
|
||||
if line_property[0] == "Title":
|
||||
beatmap.title = line_property[1].strip().replace("/", "").replace("\\", "")
|
||||
elif line_property[0] == "TitleUnicode":
|
||||
try:
|
||||
beatmap.title_unicode = line_property[1].strip().encode("shiftjis")
|
||||
beatmap.title_unicode = line_property[1].strip()
|
||||
except UnicodeEncodeError:
|
||||
beatmap.title_unicode = beatmap.title
|
||||
elif line_property[0] == "Artist":
|
||||
beatmap.artist = line_property[1].strip()
|
||||
elif line_property[0] == "ArtistUnicode":
|
||||
try:
|
||||
beatmap.artist_unicode = line_property[1].strip().encode("shiftjis")
|
||||
beatmap.artist_unicode = line_property[1].strip()
|
||||
except UnicodeEncodeError:
|
||||
beatmap.artist_unicode = beatmap.artist
|
||||
elif line_property[0] == "Creator":
|
||||
beatmap.creator = line_property[1].strip()
|
||||
elif line_property[0] == "Version":
|
||||
beatmap.version = line_property[1].strip()
|
||||
elif line_property[0] == "Source":
|
||||
beatmap.source = line_property[1].strip()
|
||||
elif line_property[0] == "Tags":
|
||||
pass
|
||||
elif line_property[0] == "BeatmapID":
|
||||
beatmap.beatmap_id = line_property[1].strip()
|
||||
elif line_property[0] == "BeatmapSetID":
|
||||
pass
|
||||
|
||||
def is_empty(line):
|
||||
"""
|
||||
Returns True iff line is empty
|
||||
"""
|
||||
return len(line.strip()) == 0
|
||||
|
||||
def is_comment(line):
|
||||
"""
|
||||
Returns True iff line is a comment line
|
||||
"""
|
||||
return len(line) >= 2 and line[0:1] == "//"
|
||||
|
||||
def is_section_header(line):
|
||||
"""
|
||||
Return True iff line is section header.
|
||||
"""
|
||||
return len(line) >= 2 and line[0] == '[' and line[-2] == ']'
|
||||
|
||||
def get_section(line):
|
||||
"""
|
||||
Return section header
|
||||
"""
|
||||
return line[1:-2]
|
||||
|
||||
def get_line_property(line):
|
||||
"""
|
||||
Returns tuple of (Attribute, Value)
|
||||
"""
|
||||
split = line.split(":")
|
||||
return (split[0], split[1])
|
||||
|
||||
def parse_symbol_separated(line, symbol):
|
||||
"""
|
||||
Returns list of elements in line separated by symbol.
|
||||
"""
|
||||
return line.split(symbol)
|
||||
|
||||
file = codecs.open(input_file, 'r', "utf-8")
|
||||
section = "FileFormat"
|
||||
for line in file.readlines():
|
||||
if is_empty(line) or is_comment(line):
|
||||
continue
|
||||
elif is_section_header(line):
|
||||
section = get_section(line)
|
||||
continue
|
||||
if line[0] == '[':
|
||||
section = line[1:-3]
|
||||
continue
|
||||
if section == "FileFormat":
|
||||
continue
|
||||
elif section == "General":
|
||||
header_general(line, osumania_beatmap)
|
||||
elif section == "Editor":
|
||||
continue
|
||||
elif section == "Metadata":
|
||||
header_metadata(line, osumania_beatmap)
|
||||
elif section == "Difficulty":
|
||||
header_difficulty(line, osumania_beatmap)
|
||||
elif section == "Events":
|
||||
header_events(line, osumania_beatmap)
|
||||
elif section == "TimingPoints":
|
||||
header_timingpoints(line, osumania_beatmap)
|
||||
elif section == "Colours":
|
||||
continue
|
||||
elif section == "HitObjects":
|
||||
header_hitobjects(line, osumania_beatmap)
|
||||
else:
|
||||
OsuParseException("Header Error: " + section + " not found")
|
||||
|
||||
osumania_beatmap.objects = sorted(osumania_beatmap.hit_objects +
|
||||
osumania_beatmap.sample_objects +
|
||||
osumania_beatmap.noninherited_tp,
|
||||
key=lambda x: (x.time, x.sort_type))
|
||||
|
||||
# for i in range(len(osumania_beatmap.objects)):
|
||||
# if isinstance(osumania_beatmap.objects[i], OsuTimingPoint):
|
||||
# j = i
|
||||
# while osumania_beatmap.objects[j].time == osumania_beatmap.objects[i].time:
|
||||
# j -= 1
|
||||
# j += 1
|
||||
# osumania_beatmap.objects[j], osumania_beatmap.objects[i], = \
|
||||
# osumania_beatmap.objects[i], osumania_beatmap.objects[j]
|
||||
|
||||
file.close()
|
||||
@@ -0,0 +1,55 @@
|
||||
import os
|
||||
|
||||
from argparse import ArgumentParser
|
||||
|
||||
import om2bms.om_to_bms
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
parser = ArgumentParser(description='Convert a .osu osu!mania file to a BMS file. '
|
||||
'Outputs to directory of om2bms.py',
|
||||
add_help=True,
|
||||
allow_abbrev=True)
|
||||
|
||||
parser.add_argument('-i', '--in_file',
|
||||
action='store',
|
||||
help='Path to file to be converted.',
|
||||
type=str)
|
||||
|
||||
parser.add_argument('-hs', '--hitsound',
|
||||
action='store_false',
|
||||
default=False,
|
||||
help='Disables hitsounds.')
|
||||
|
||||
parser.add_argument('-b', '--bg',
|
||||
action='store_false',
|
||||
default=True,
|
||||
help='Disables background conversion.')
|
||||
|
||||
parser.add_argument('-o', '--offset',
|
||||
default=0,
|
||||
type=int,
|
||||
help="Adjusts music start time by [offset] ms.")
|
||||
|
||||
parser.add_argument('-j', '--judge',
|
||||
default=2,
|
||||
type=int,
|
||||
help="Judge difficulty. Defaults to EASY. "
|
||||
"(3: EASY), (2: NORMAL), (1: HARD), (0: VERY HARD)")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
cwd = os.getcwd()
|
||||
|
||||
om2bms.om_to_bms.OsuManiaToBMSParser._convertion_options = {
|
||||
"HITSOUND": args.hitsound,
|
||||
"VIDEO": False,
|
||||
"BG": args.bg,
|
||||
"OFFSET": args.offset,
|
||||
"JUDGE": args.judge
|
||||
}
|
||||
convert = om2bms.om_to_bms.OsuManiaToBMSParser(
|
||||
args.in_file, os.getcwd(), args.in_file)
|
||||
print("Done")
|
||||
exit(0)
|
||||
@@ -0,0 +1,233 @@
|
||||
import zipfile
|
||||
import os
|
||||
import json
|
||||
import shutil
|
||||
|
||||
from argparse import ArgumentParser
|
||||
from om2bms.exceptions import BMSMaxMeasuresException
|
||||
from om2bms.extra_file_processing import size_bg_thumbnail, cut_save_preview_audio
|
||||
from types import SimpleNamespace
|
||||
|
||||
import om2bms.om_to_bms
|
||||
import multiprocessing
|
||||
|
||||
def convert(in_file: str, set_default_out: str = None, hitsound: bool = None, bg: bool = True, video: bool = True, foldername: str = None, offset: int = -235, judge: int = 2):
|
||||
|
||||
args = SimpleNamespace(**{ # Allows simpler use of the paramaters
|
||||
"in_file": in_file,
|
||||
"set_default_out": set_default_out,
|
||||
"hitsound": hitsound,
|
||||
"bg": bg,
|
||||
"video": video,
|
||||
"foldername": foldername,
|
||||
"offset": offset,
|
||||
"judge": judge
|
||||
})
|
||||
|
||||
cwd = os.getcwd()
|
||||
|
||||
cfg_file = os.path.join(cwd, 'settings.json')
|
||||
if not os.path.exists(cfg_file):
|
||||
default_settings = {
|
||||
"in_file": "input",
|
||||
"set_default_out": "output",
|
||||
"hitsound": None,
|
||||
"bg": True,
|
||||
"video": True,
|
||||
"offset": -235,
|
||||
"judge": 2
|
||||
}
|
||||
json.dump({"custom":default_settings, "default": default_settings}, open(cfg_file, "w"))
|
||||
|
||||
# I know this whole if statement is weird, but I don't want to risk breaking anything any more
|
||||
if args.set_default_out is not None and args.set_default_out:
|
||||
# modifies output dir in json settings
|
||||
settings_obj = json.load(open(cfg_file, "r"))
|
||||
settings_obj["custom"]["set_default_out"] = args.set_default_out.strip()
|
||||
json.dump(settings_obj, open(cfg_file, "w"))
|
||||
|
||||
outdir = args.set_default_out.strip()
|
||||
else:
|
||||
outdir = json.load(open(cfg_file, "r"))["custom"]["set_default_out"]
|
||||
|
||||
if args.in_file is None:
|
||||
exit(0)
|
||||
|
||||
if args.foldername is None:
|
||||
foldername = os.path.basename(args.in_file)[:-4]
|
||||
out_foldername = foldername
|
||||
else:
|
||||
out_foldername = args.foldername
|
||||
|
||||
unzip_dir = os.path.join(cwd, "unzip_dir")
|
||||
if not os.path.isdir(unzip_dir):
|
||||
os.makedirs(unzip_dir)
|
||||
try:
|
||||
if not os.path.isdir(unzip_dir):
|
||||
os.makedirs(unzip_dir)
|
||||
|
||||
filename = os.path.basename(args.in_file)
|
||||
shutil.copy2(args.in_file, unzip_dir)
|
||||
|
||||
osz_dir = os.path.join(unzip_dir, filename)
|
||||
|
||||
base = os.path.splitext(osz_dir)[0]
|
||||
os.rename(osz_dir, base + ".zip")
|
||||
osz_file_dir = base + ".zip"
|
||||
|
||||
print("Unzipping...")
|
||||
with zipfile.ZipFile(osz_file_dir, 'r') as zipf:
|
||||
zipf.extractall(unzip_dir)
|
||||
|
||||
output_file_dir = os.path.join(outdir, out_foldername)
|
||||
print("Output directory is " + output_file_dir)
|
||||
|
||||
if not os.path.isdir(output_file_dir):
|
||||
os.makedirs(output_file_dir)
|
||||
|
||||
processes = []
|
||||
manager = multiprocessing.Manager()
|
||||
bg_list = manager.list()
|
||||
audio_list = manager.list()
|
||||
for file in os.listdir(unzip_dir):
|
||||
if file.endswith(".osu"):
|
||||
filedir = os.path.join(unzip_dir, file)
|
||||
p = multiprocessing.Process(target=start_convertion,
|
||||
args=(filedir, output_file_dir, file, args, bg_list, audio_list))
|
||||
processes.append(p)
|
||||
|
||||
|
||||
for p in processes:
|
||||
p.start()
|
||||
|
||||
for p in processes:
|
||||
p.join()
|
||||
|
||||
if args.bg:
|
||||
print("Converting BG...")
|
||||
convert_bg_list(bg_list)
|
||||
|
||||
print("Snipping preview audio...")
|
||||
make_preview_audio(audio_list)
|
||||
|
||||
# move files to output directory
|
||||
for f in os.listdir(unzip_dir):
|
||||
if not os.path.isdir(os.path.join(unzip_dir, f)):
|
||||
if not f.split(".")[-1] == "zip" and not f.split(".")[-1] == "osu":
|
||||
full_path = os.path.join(unzip_dir, f)
|
||||
try:
|
||||
shutil.copy2(full_path, output_file_dir)
|
||||
except PermissionError as e:
|
||||
print(e)
|
||||
continue
|
||||
|
||||
print("Done")
|
||||
# exit(0)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
exit(1)
|
||||
finally:
|
||||
shutil.rmtree(unzip_dir)
|
||||
|
||||
def start_convertion(filedir_, output_file_dir_, file_, args, bg_list_, audio_list_):
|
||||
"""
|
||||
Returns bg filename
|
||||
"""
|
||||
try:
|
||||
om2bms.om_to_bms.OsuManiaToBMSParser._convertion_options = {
|
||||
"HITSOUND": None if args.hitsound == False else args.hitsound,
|
||||
"BG": args.bg,
|
||||
"VIDEO": args.video,
|
||||
"OFFSET": args.offset,
|
||||
"JUDGE": args.judge
|
||||
}
|
||||
|
||||
converted_file = om2bms.om_to_bms.OsuManiaToBMSParser(filedir_, output_file_dir_, file_)
|
||||
if not converted_file.failed:
|
||||
if args.bg:
|
||||
bg_list_.append((converted_file.get_bg(), converted_file.beatmap.creator, converted_file.beatmap.beatmap_id))
|
||||
|
||||
audio_list_.append((converted_file.get_audio_path(), converted_file.beatmap.preview_time, converted_file.beatmap.timing_points))
|
||||
|
||||
|
||||
except BMSMaxMeasuresException as e:
|
||||
print(e)
|
||||
|
||||
def make_preview_audio(audio_list_) -> None:
|
||||
"""
|
||||
Creates a second audio file that we will use in the om2bms preview section
|
||||
(From osu map, uses either PreviewTime + 20s, first kiai section + 20s, 40% song + 20s)
|
||||
"""
|
||||
|
||||
seen = []
|
||||
for audio_info in audio_list_:
|
||||
audio_path, map_preview_time, map_timing_poins = audio_info
|
||||
if audio_path is not None and audio_path not in seen:
|
||||
cut_save_preview_audio(audio_path, map_preview_time, map_timing_poins)
|
||||
seen.append(audio_path)
|
||||
|
||||
def convert_bg_list(bg_list_) -> None:
|
||||
"""
|
||||
Converts all images in img_list
|
||||
"""
|
||||
seen = []
|
||||
for bg_info in bg_list_:
|
||||
bg, creator, beatmapid = bg_info
|
||||
if bg is not None and bg not in seen:
|
||||
size_bg_thumbnail(bg, creator, beatmapid)
|
||||
seen.append(bg)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
parser = ArgumentParser(description='Convert all .osu osu!mania files in a .osz to BMS files',
|
||||
add_help=True,
|
||||
allow_abbrev=True)
|
||||
|
||||
parser.add_argument('-i', '--in_file',
|
||||
action='store',
|
||||
default=None,
|
||||
help='Path to .osz to be converted.',
|
||||
type=str)
|
||||
|
||||
parser.add_argument('-sdo', '--set_default_out',
|
||||
action='store',
|
||||
default=None,
|
||||
help='Sets the default output directory',
|
||||
type=str)
|
||||
|
||||
parser.add_argument('-hs', '--hitsound',
|
||||
action='store_false',
|
||||
default=None,
|
||||
help='Disables hitsounds.')
|
||||
|
||||
parser.add_argument('-b', '--bg',
|
||||
action='store_false',
|
||||
default=True,
|
||||
help='Disables background image conversion.')
|
||||
|
||||
parser.add_argument("-v", "--video",
|
||||
action="store_false",
|
||||
default=True,
|
||||
help="Disables video conversion.")
|
||||
|
||||
parser.add_argument('-f', '--foldername',
|
||||
action='store',
|
||||
default=None,
|
||||
help='Directory name to store output files in output path. '
|
||||
'Default value is the .osz filename')
|
||||
|
||||
parser.add_argument('-o', '--offset',
|
||||
default=-235,
|
||||
type=int,
|
||||
help="Adjusts music start time by [offset] ms.")
|
||||
|
||||
parser.add_argument('-j', '--judge',
|
||||
default=2,
|
||||
type=int,
|
||||
help="Judge difficulty. Defaults to EASY. "
|
||||
"(3: EASY), (2: NORMAL), (1: HARD), (0: VERY HARD)")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
convert(**vars(args)) # because this function takes actual arguments instead of kwargs
|
||||
@@ -0,0 +1 @@
|
||||
holds no info, it's just so that ./output/ uploads to github
|
||||
@@ -0,0 +1,2 @@
|
||||
pillow
|
||||
pydub
|
||||
@@ -0,0 +1 @@
|
||||
{"custom": {"in_file": "input", "set_default_out": "output", "hitsound": null, "bg": true, "video": true, "offset": -235, "judge": 2}, "default": {"in_file": "input", "set_default_out": "output", "hitsound": null, "bg": true, "video": true, "offset": -235, "judge": 2}}
|
||||
@@ -0,0 +1,5 @@
|
||||
bga maker: instruction in main readme. Just follow the prompt.
|
||||
|
||||
malody to osu: open .mcz as zip, drag .mc chart file on to convert.exe. An osu file will be saved in the directory.
|
||||
|
||||
osu to bms: run `python osu.py -i *input .osu file path*`. A .bms file will be saved in the directory. Note the name of the file might change as it is defined internally in the input file.
|
||||
Reference in New Issue
Block a user