我目前正在为 Blender 开发一个导出脚本,但是我觉得我的问题通常更多地基于 Python,所以我在这里发布了它。
一位朋友在 java 中为 .obj 文件创建了一个转换程序,将它们转换为自定义的二进制文件格式。但是,我想跳过该过程并直接从 Blender 导出二进制文件。
该文件包含文本、整数和浮点数,使用 utf-8、utf-16 和 utf-32 格式。
到目前为止,我已将所有数据导出为标准文本文件,因此我只需要以适当的编码/格式输出它。这是他在 Java 中使用的代码,用于以不同的编码将数据写入文件:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class StreamConverter {
//---------------------------------------------------
public static void buffer_write_string(DataOutputStream out,String text) throws IOException{
byte[] bytes = text.getBytes();
for(int i =0;i<text.length();i++){
buffer_write_u8(out,bytes[i]);
}
}
public static void buffer_write_u32(DataOutputStream out,int i) throws IOException{
ByteBuffer b = ByteBuffer.allocate(4);
b.order(ByteOrder.LITTLE_ENDIAN);
b.putInt(i);
out.write(b.array());
}
public static void buffer_write_u16(DataOutputStream out,int i) throws IOException{
out.write((byte) i);
out.write((byte) (i >> 8));
}
public static void buffer_write_s16(DataOutputStream out,int i) throws IOException{
out.write((byte) i);
out.write((byte) (i >> 8));
}
public static void buffer_write_s32(DataOutputStream out,int i) throws IOException{
ByteBuffer b = ByteBuffer.allocate(4);
b.order(ByteOrder.LITTLE_ENDIAN);
b.putInt(i);
out.write(b.array());
}
public static void buffer_write_u8(DataOutputStream out,int i) throws IOException{
out.writeByte((byte) i);
}
public static void buffer_write_s8(DataOutputStream out,int i) throws IOException{
out.writeByte((byte) i);
}
public static void buffer_write_f64(DataOutputStream out,double i) throws IOException{
ByteBuffer b = ByteBuffer.allocate(8);
b.order(ByteOrder.LITTLE_ENDIAN);
b.putDouble(i);
out.write(b.array());
}
public static void buffer_write_f32(DataOutputStream out,float i) throws IOException{
ByteBuffer b = ByteBuffer.allocate(4);
b.order(ByteOrder.LITTLE_ENDIAN);
b.putFloat(i);
out.write(b.array());
}
}
我不知道如何做到这一点是 Python,我正在尝试这个,看看我是否至少可以让整数正确输出,但没有运气。
def write_u8(file, num):
enum = num.encode('utf-8')
file.write(enum)
def write_u16(file, num):
enum = num.encode('utf-16')
file.write(enum)
def write_u32(file, num):
enum = num.encode('utf-32')
file.write(enum)
示例用法:
write_u32(file, u'%i' % (vertex_count))
也试过这个:
counts = bytes([vertex_count,tex_count,normal_count])
file.write(counts)
我对整个二进制/编码的事情有点迷茫,我已经阅读了 Python 文档,但它没有帮助。
任何指向教程或示例的链接都会很棒!