FreeCAD: Workbench Refactor

This commit is contained in:
Mark Voltov 2024-04-14 18:54:47 +00:00 committed by Igor Brylyov
parent 037827669a
commit a58dcdafb1
386 changed files with 997 additions and 64533 deletions

2
.gitmodules vendored
View file

@ -1,3 +1,3 @@
[submodule "insertion_vector_predicate/assembly"] [submodule "simulation/insertion_vector_predicate/assembly"]
path = insertion_vector_predicate/assembly path = insertion_vector_predicate/assembly
url = https://github.com/yunshengtian/Assemble-Them-All url = https://github.com/yunshengtian/Assemble-Them-All

View file

@ -1,5 +1,7 @@
# Фреймворк Робосборщик # Фреймворк Робосборщик
Фреймворк Робосборщик (Robossembler Framework) предназначен для автоматизации разработки управляющих программ для роботов-манипуляторов, их отладки в виртуальных средах и оценки производительности. Фреймворк Робосборщик (Robossembler Framework) предназначен для автоматизации разработки управляющих программ для роботов-манипуляторов, их отладки в виртуальных средах и оценки производительности.
Фреймворк состоит из следующих функциональных модулей Фреймворк состоит из следующих функциональных модулей

View file

@ -1,26 +0,0 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
**/node_modules
server/public/
**/computed/

File diff suppressed because it is too large Load diff

View file

@ -1,45 +0,0 @@
{
"name": "express-typescript",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"build": "npx tsc",
"start": "npx tsc && node --experimental-specifier-resolution=node dist/server.js",
"dev": "nodemon --exec ts-node --esm --transpileOnly ./src/server.ts"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/compression": "^1.7.2",
"@types/cors": "^2.8.13",
"@types/express": "^4.17.17",
"@types/express-fileupload": "^1.4.1",
"@types/mongoose": "^5.11.97",
"@types/node": "^17.0.45",
"typescript": "^4.9.5"
},
"dependencies": {
"body-parser": "^1.20.2",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"compression": "^1.7.4",
"concurrently": "^8.0.1",
"cors": "^2.8.5",
"decompress": "^4.2.1",
"express": "^4.18.2",
"express-cross": "^1.0.0",
"express-fileupload": "^1.4.0",
"first-di": "^1.0.11",
"form-data": "^4.0.0",
"lodash": "^4.17.21",
"morgan": "^1.10.0",
"multer": "^1.4.5-lts.1",
"node-stream-zip": "^1.15.0",
"nodemon": "^2.0.22",
"shelljs": "^0.8.5",
"ts-node": "^10.9.1"
}
}

View file

@ -1,71 +0,0 @@
import express from "express";
import compression from "compression";
import cors from "cors";
import { Routes } from "./core/interfaces/router";
import bodyParser from "body-parser";
import fileUpload from "express-fileupload";
import { DevEnv } from "./core/env/env";
import path from 'path';
import { locator } from "./core/di/register_di";
export const dirname = path.resolve();
const corsOptions = {
origin: process.env.CORS_ALLOW_ORIGIN || '*',
methods: ['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization']
};
export class App {
public app: express.Application;
public port: string | number;
public env: string;
constructor(routes: Routes[], port) {
this.app = express();
this.port = port;
this.env = process.env.NODE_ENV || "development";
this.initializeMiddleware();
this.initializeRoutes(routes);
this.loadAppDependencies();
}
public listen() {
this.app.listen(this.port, () => {
console.info(`=================================`);
console.info(`======= ENV: ${this.env} =======`);
console.info(`🚀 App listening on the port ${this.port}`);
console.info(`=================================`);
});
}
public getServer() {
return this.app;
}
private initializeMiddleware() {
this.app.use(
cors(corsOptions)
);
this.app.use(compression());
this.app.use(express.json());
this.app.use(express.urlencoded({ extended: true }));
this.app.use(bodyParser.json());
this.app.use(bodyParser.urlencoded({ extended: true }));
this.app.use(express.static(dirname + '/public/'));
this.app.use(fileUpload({
createParentPath: true
}));
}
private initializeRoutes(routes: Routes[]) {
routes.forEach((route) => {
this.app.use("/", route.router);
});
}
loadAppDependencies() {
locator(new DevEnv());
}
}

View file

@ -1,28 +0,0 @@
import { override } from "first-di";
import { Env } from "../env/env";
import { AssemblyController } from "../../features/assembly_create/assembly_create_controller";
import { AssemblyPreviewsController } from "../../features/assembly_previews/assembly_previews_controller";
import { EntityRepository } from "../repository/entity_repository";
import { ZipRepository } from "../repository/zip_repository";
import { ComputeRepository } from "../repository/compute_repository";
export const locator = (env: Env) => {
// override(Env, env)
registerController(env)
registerRepository(env)
};
const registerRepository = (env:Env) => {
override(ZipRepository, ZipRepository);
override(EntityRepository, EntityRepository);
override(ComputeRepository,ComputeRepository);
}
const registerController = (env: Env) => {
override(AssemblyController,AssemblyController)
override(AssemblyPreviewsController, AssemblyPreviewsController)
}

View file

@ -1,10 +0,0 @@
export class HttpException extends Error {
public status: number;
public message: string;
constructor(status: number, message: string) {
super(message);
this.status = status;
this.message = message;
}
}

View file

@ -1,191 +0,0 @@
interface MemoOptions<F extends Fn, S extends unknown[] = unknown[]> {
serialize?: (...args: Parameters<F>) => S;
}
interface MemoAsyncOptions<F extends Fn> extends MemoOptions<F> {
external?: {
get: (args: Parameters<F>) => Promise<Awaited<ReturnType<F>> | undefined | null>;
set: (args: Parameters<F>, value: Awaited<ReturnType<F>>) => Promise<void>;
remove: (args: Parameters<F>) => Promise<void>;
clear: () => Promise<void>;
};
}
type Fn = (...params: any[]) => any;
type AsyncFn = (...params: any[]) => Promise<any>;
interface MemoFunc<F extends Fn> {
(...args: Parameters<F>): ReturnType<F>;
get(...args: Parameters<F>): ReturnType<F>;
raw(...args: Parameters<F>): ReturnType<F>;
clear(...args: Parameters<F> | []): void | Promise<void>;
}
export const enum State {
Empty,
Ok,
Waiting,
Error
}
export interface Node<T extends Fn> {
state: State;
value: ReturnType<T> | undefined;
error: unknown;
primitive: Map<any, Node<T>>;
reference: WeakMap<any, Node<T>>;
callbacks?: Set<{ res: (value: ReturnType<T>) => void; rej: (error: unknown) => void }>;
}
function makeNode<T extends Fn>(): Node<T> {
return {
state: State.Empty,
value: undefined,
error: undefined,
primitive: new Map(),
reference: new WeakMap()
};
}
function clearNode<T extends Fn>(node: Node<T> | undefined) {
if (node) {
node.state = State.Empty;
node.value = undefined;
node.error = undefined;
node.primitive = new Map();
node.reference = new WeakMap();
}
}
function isPrimitiveType(value: unknown) {
return (typeof value !== 'object' && typeof value !== 'function') || value === null;
}
function walkBase<T extends Fn, P extends any[] = Parameters<T>>(
node: Node<T>,
args: P,
hooks: { makeNode: () => Node<T> | undefined }
): Node<T> | undefined {
let cur = node;
for (const arg of args) {
if (isPrimitiveType(arg)) {
if (cur.primitive.has(arg)) {
cur = cur.primitive.get(arg)!;
} else {
const newNode = hooks.makeNode();
if (newNode) {
cur.primitive.set(arg, newNode);
cur = newNode;
} else {
return undefined;
}
}
} else {
if (cur.reference.has(arg)) {
cur = cur.reference.get(arg)!;
} else {
const newNode = hooks.makeNode();
if (newNode) {
cur.reference.set(arg, newNode);
cur = newNode;
} else {
return undefined;
}
}
}
}
return cur;
}
function walkAndCreate<T extends Fn, P extends any[] = Parameters<T>>(
node: Node<T>,
args: P
) {
return walkBase(node, args, { makeNode })!;
}
function walkOrBreak<T extends Fn, P extends any[] = Parameters<T>>(node: Node<T>, args: P) {
return walkBase(node, args, { makeNode: () => undefined });
}
export function memoAsync<F extends AsyncFn>(
fn: F,
options: MemoAsyncOptions<F> = {}
): MemoFunc<F> {
const root = makeNode<F>();
const memoFunc = async function (...args: Parameters<F>) {
const path = options.serialize ? options.serialize(...args) : args;
const cur = walkAndCreate<F, any[]>(root, path);
if (cur.state === State.Ok) {
return cur.value;
} else if (cur.state === State.Error) {
throw cur.error;
} else if (cur.state === State.Waiting) {
return new Promise((res, rej) => {
if (!cur.callbacks) {
cur.callbacks = new Set();
}
cur.callbacks!.add({ res, rej });
});
} else {
try {
cur.state = State.Waiting;
const external = options.external ? await options.external.get(args) : undefined;
const value = external !== undefined && external !== null ? external : await fn(...args);
cur.state = State.Ok;
cur.value = value;
if (options.external) {
await options.external.set(args, value);
}
for (const callback of cur.callbacks ?? []) {
callback.res(value);
}
return value;
} catch (error) {
cur.state = State.Error;
cur.error = error;
for (const callback of cur.callbacks ?? []) {
callback.rej(error);
}
throw error;
}
}
} as MemoFunc<F>;
memoFunc.get = (...args) => {
return memoFunc(...args);
};
memoFunc.raw = (...args) => {
return fn(...args) as ReturnType<F>;
};
memoFunc.clear = async (...args) => {
if (args.length === 0) {
clearNode(root);
if (options.external) {
await options.external.clear();
}
} else {
const cur = walkOrBreak<F>(root, args as Parameters<F>);
clearNode(cur);
if (options.external) {
await options.external.remove(args as Parameters<F>);
}
}
};
return memoFunc;
}

View file

@ -1,6 +0,0 @@
import { Router } from "express";
export interface Routes {
path?: string;
router: Router;
}

View file

@ -1,25 +0,0 @@
import { HttpException } from '../exceptions/HttpException';
import { plainToClass } from 'class-transformer';
import { validate, ValidationError } from 'class-validator';
import { RequestHandler } from 'express';
const validationMiddleware = (
type: any,
value = 'body',
skipMissingProperties = false,
whitelist = true,
forbidNonWhitelisted = true,
): RequestHandler => {
return (req, res, next) => {
validate(plainToClass(type, req[value]), { skipMissingProperties, whitelist, forbidNonWhitelisted }).then((errors: ValidationError[]) => {
if (errors.length > 0) {
const message = errors.map((error: ValidationError) => Object.values(error.constraints)).join(', ');
next(new HttpException(400, message));
} else {
next();
}
});
};
};
export default validationMiddleware;

View file

@ -1,76 +0,0 @@
import { reflection } from 'first-di';
import "reflect-metadata";
import { promises as fs } from 'fs';
import { async } from 'node-stream-zip';
import * as cp from 'child_process';
import path from 'path';
async function exec(cmd: string, opts: (cp.ExecOptions & { trim?: boolean }) = {}): Promise<string> {
return new Promise((c, e) => {
cp.exec(cmd, { env: process.env, ...opts }, (err, stdout) => err ? e(err) : c(opts.trim ? stdout.trim() : stdout));
});
}
@reflection
export class ComputeRepository {
public computedAdjaxedMatrix = async (outPath: string, cadEntity: string, entityId: string) => {
const envPath = '/home/idontsudo/t/framework/asp-review-app/server/computed/geometric_feasibility_predicate/env.json'
const computedScript = '/home/idontsudo/t/framework/asp-review-app/server/computed/geometric_feasibility_predicate/main.py'
const computedComand = 'freecadcmd'
const env = JSON.parse((await fs.readFile(envPath)).toString())
env['cadFilePath'] = cadEntity
env['outPath'] = outPath
await fs.writeFile(envPath, JSON.stringify(env))
// console.log(this._computedPath(computedScript))
exec(computedComand + ' ' + computedScript, { cwd: this._computedPath(computedScript) }).then((data) => {
console.log(data)
})
this.cadGeneration(cadEntity, entityId, outPath)
// if (stderr) {
// console.log(stderr)
// }
// console.log(stdout)
};
public computedWriteStability = async (assemblyFolder: string, buildNumber: string, id: string) => {
const computedScript = '/home/idontsudo/t/framework/cad_stability_input/main.py'
const computedComand = 'freecad'
const envPath = '/home/idontsudo/t/framework/cad_stability_input/env.json'
const env = JSON.parse((await fs.readFile(envPath)).toString())
env.assemblyFolder = assemblyFolder
env['projectId'] = id
env['buildNumber'] = buildNumber
env['assemblyFolder'] = assemblyFolder
env['resultURL'] = 'http://localhost:3002/assembly/stabilty/create/?id=' + id + '&' + 'buildNumber=' + buildNumber
await fs.writeFile(envPath, JSON.stringify(env))
await exec(computedComand + ' ' + computedScript, { cwd: this._computedPath(computedScript) })
}
private _computedPath(f: string) {
const file = path.basename(f);
const absolutPath = path.resolve(f)
return absolutPath.replace(file, '')
}
public cadGeneration = async (cadEntity, entity: string, outPath: string,) => {
const computedScript = '/home/idontsudo/t/framework/cad_generation/main.py'
const computedComand = 'freecad'
const envPath = '/home/idontsudo/t/framework/cad_generation/env.json'
const env = JSON.parse((await fs.readFile(envPath)).toString())
env.doc = cadEntity
env.projectId = entity
env.resultURL = "http://localhost:3002/assembly/save/out"
await fs.writeFile(envPath, JSON.stringify(env))
// /stabilty/create
exec(computedComand + ' ' + computedScript, { cwd: this._computedPath(computedScript) }).then((data) => {
console.log(data)
})
}
}

View file

@ -1,87 +0,0 @@
import { promises as fs } from 'fs';
import { dirname } from '../../app';
import fsSync from "fs";
import { autowired, reflection } from 'first-di';
import "reflect-metadata";
import { ComputeRepository } from './compute_repository';
import { ZipRepository } from './zip_repository';
@reflection
export class EntityRepository {
@autowired()
private readonly computedRepository: ComputeRepository;
@autowired()
private readonly zipRepository: ZipRepository;
private path: String = dirname + '/public/'
private getFileName(file: String) {
return file.slice(0, file.indexOf('.'))
}
public async getDir(path) {
return this._fullPath(await fs.readdir(path + ''), duplicatedDelete(this.path, path))
}
public isExistDirPath(path: String): boolean {
return fsSync.existsSync(path + '')
}
public async saveRootEntity(buffer: Buffer, name: string) {
const filePath = this.path + this.getFileName(name) + '/'
if (this.isExistDirPath(filePath)) {
await fs.rm(filePath, { recursive: true })
}
await fs.mkdir(filePath);
await fs.writeFile(filePath + name, buffer);
this.computedRepository.computedAdjaxedMatrix(filePath, filePath + name, this.getFileName(name))
}
public async getAllRootEntity() {
return await fs.readdir('' + this.path)
}
public async getEntityStorage(entity: string): Promise<String[]> | undefined {
return this._fullPath(await fs.readdir(this.path + entity), entity + '/')
}
private _fullPath(folderPath, helpElement = '') {
return folderPath.map((el) => this.path + helpElement + el)
}
public async readJson<T>(path) {
return JSON.parse((await fs.readFile(path)).toString())
}
public async saveGeration(data: Buffer, id: String) {
const rootFolderPath = '' + this.path + id + '/'
console.log(rootFolderPath)
this.zipRepository.archive(rootFolderPath, data)
}
public computedStability(id: string, buildNumber: string) {
const assemblyFolder = this.path + id + '/generation/'
this.computedRepository.computedWriteStability(assemblyFolder, buildNumber, id)
}
public async saveStability(zip: Buffer, id:string, buildNumber:string) {
const filePath = await this.zipRepository.archive(this.path as string, zip)
// const buildNumber = data['buildNumber']
const assemblyFolder = this.path + id + '/generation/stability/'
if (!this.isExistDirPath(assemblyFolder)) {
await fs.mkdir(assemblyFolder);
}
await this.zipRepository.archive(assemblyFolder as string, zip, buildNumber)
fs.rmdir(filePath + '/', { recursive: true})
}
}
function duplicatedDelete(strChild: String, strMain: String) {
let result = ''
for (let i = 0; i < strMain.length; i++) {
if (!(strMain[i] === strChild[i])) {
result += strMain[i]
}
}
return result
}

View file

@ -1,13 +0,0 @@
import StreamZip from 'node-stream-zip';
import { promises as fs } from 'fs';
import decompress from 'decompress'
export class ZipRepository {
public async archive(outhPath: string, zipFile: Buffer, name='generation') {
const entry = outhPath + 'archive.zip'
await fs.writeFile(entry, zipFile)
await decompress(entry, outhPath + name);
fs.rm(entry)
return outhPath + name
}
}

View file

@ -1,5 +0,0 @@
import { AssemblyRoute } from "../../features/assembly_create/assembly_create_route";
import { AssemblyPreviewsRoute } from "../../features/assembly_previews/assembly_previews_route";
export const routes = [new AssemblyRoute(), new AssemblyPreviewsRoute()];

View file

@ -1,101 +0,0 @@
import { NextFunction, Request, Response } from "express";
import { autowired } from "first-di";
import { async } from "node-stream-zip";
import { EntityRepository } from "../../core/repository/entity_repository";
import { IFile } from "./model/zip_files_model";
export class AssemblyController {
@autowired()
private readonly entityRepository: EntityRepository;
public createRootEntity = (
req: Request,
res: Response,
next: NextFunction
) => {
const file = req.files;
const cadFile = file["freecad"] as IFile;
this.entityRepository.saveRootEntity(cadFile.data, cadFile.name);
res.status(200).json("ok");
return;
};
public getAllAssembly = (
req: Request,
res: Response,
next: NextFunction
): void => { };
public createAssembly = (
req: Request,
res: Response,
next: NextFunction
): void => {
try {
const file = req.files.freecad as IFile;
const buffer = file.data as Buffer;
this.entityRepository.saveRootEntity(file.data, file.name);
res.sendStatus(200);
} catch (error) {
next(error);
}
};
public test = (req: Request,
res: Response,
next: NextFunction) => {
try {
const file = req.files;
const generation = file["zip"] as IFile;
const id = 'cubes';
this.entityRepository.saveGeration(generation.data, id)
res.sendStatus(200);
} catch (error) {
next(error);
}
}
public stabilityComputed = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
// const file = req.files;
console.log(req.body)
const id = req.body.id;
// console.log(req.query.id)
const buildNumber = req.body.buildNumber;
console.log(buildNumber)
console.log(id)
// const generation = file["zip"] as IFile;
// const id = 'cubes';
await this.entityRepository.computedStability(id, buildNumber)
res.sendStatus(200);
} catch (error) {
next(error);
}
}
public stabilityCreate = (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const files = req.files;
const zip = files['zip'] as IFile
const query = req.query as any
this.entityRepository.saveStability(zip.data, query.id, query.buildNumber)
res.sendStatus(200);
} catch (error) {
next(error);
}
}
}

View file

@ -1,46 +0,0 @@
import express, { Router } from "express";
import { Routes } from "../../core/interfaces/router";
import { autowired } from "first-di";
import { AssemblyController } from "./assembly_create_controller";
import validationMiddleware from "../../core/middlewares/ValidationMiddleware";
import { CadFilesModel } from "./model/zip_files_model";
export class AssemblyRoute implements Routes {
public path = "/assembly";
public router = Router();
@autowired()
private readonly assemblyController: AssemblyController;
constructor() {
this.initializeRoutes();
}
private initializeRoutes() {
this.router.post(
`${this.path}`,
validationMiddleware(CadFilesModel, "files"),
this.assemblyController.createAssembly
);
this.router.post(
`${this.path}/save/out`,
// validationMiddleware(CadFilesModel, "files"),
this.assemblyController.test
);
this.router.get(`${this.path}`, this.assemblyController.getAllAssembly);
this.router.post(
`${this.path}/create`,
this.assemblyController.createRootEntity
);
this.router.post(
`${this.path}/stability/write/computed`,
this.assemblyController.stabilityComputed
);
this.router.post(
`${this.path}/stabilty/create/`,
this.assemblyController.stabilityCreate
);
}
}

View file

@ -1,23 +0,0 @@
import { IsArray, IsObject } from "class-validator";
export interface IFile {
name: string,
data: Buffer,
size: Number,
encoding: string,
tempFilePath: string,
truncated: Boolean,
mimetype: string,
md5: string,
}
interface ICadFileModel {
freecad: IFile;
}
export class CadFilesModel implements ICadFileModel {
@IsObject()
public freecad: IFile;
}

View file

@ -1,156 +0,0 @@
import { NextFunction, Request, Response } from "express";
import { autowired } from "first-di";
import { EntityRepository } from "../../core/repository/entity_repository";
import { port } from "../../server";
import { memoAsync } from "../../core/helper/memorization";
export class AssemblyPreviewsController {
@autowired()
private readonly entityRepository: EntityRepository;
public getAllAssembly = async (
req: Request,
res: Response,
next: NextFunction
): Promise<void> => {
try {
res.send(await this.entityRepository.getAllRootEntity());
} catch (error) {
next(error);
}
};
public getAssemblySubsequenceById = async (
req: Request,
res: Response,
next: NextFunction
): Promise<void> => {
try {
const entity = await this.entityRepository.getEntityStorage(
req.params.id
);
const aspUsage = Number(req.query.count) - 1;
if (entity === undefined) {
res.status(404).json("entity not found");
return;
}
res.json(
await this._assemblyCompute(
aspUsage,
entity,
this.entityRepository,
req.hostname,
req.params.id
)
);
} catch (error) {
next(error);
}
};
public getAssemblyInsertionSequenceById = async (
req: Request,
res: Response,
next: NextFunction
) => {
const entity = await this.entityRepository.getEntityStorage(req.params.id);
const aspUsage = Number(req.query.count);
const assemblyFolder = entity.find((el) => {
return el.match("assembly");
});
const asmCountFolder = "0000" + aspUsage;
const assemblyDirPath = assemblyFolder + "/" + asmCountFolder;
if (!this.entityRepository.isExistDirPath(assemblyDirPath)) {
return res.status(400).json({ error: "bad request" });
}
const assemblyProcessDir = await this.entityRepository.getDir(
assemblyDirPath + "/process/"
);
const firstObj = assemblyProcessDir.find((el) => {
return el.match("1.obj");
});
const zeroObj = await assemblyProcessDir.find((el) => {
return el.match("0.obj");
});
const insertions = await this.entityRepository.readJson(
assemblyDirPath + "/" + "insertion_path.json"
);
if (
insertions === undefined ||
zeroObj === undefined ||
firstObj === undefined
) {
res.status(400).json({ error: "bad" });
return;
}
res.json({
offset: aspUsage,
count: 4,
parent: `http://${req.hostname}:${port}/${
req.params.id
}/assembly/${asmCountFolder}/${0}.obj`,
child: `http://${req.hostname}:${port}/${
req.params.id
}/assembly/${asmCountFolder}/${1}.obj`,
insertions: insertions,
});
return;
};
private async _assemblyCompute(
id: number,
entityFolder: Array<String>,
repository: EntityRepository,
host: string,
entity: string
) {
const assemblySequence = entityFolder.find((el) => {
return el.match("step-structure.json");
});
const assembly: Array<String> = await repository.readJson<Array<String>>(
assemblySequence
);
if (id == 0) {
return {
assembly: [
`http://${host}:${port}/${entity}/sdf/meshes/${assembly[id]}.obj`,
],
offset: 1,
count: assemblySequence.length,
};
} else {
const assemblyIndexed = assembly
.map((_item, index) => {
if (index <= id) {
return index;
}
})
.filter((el) => el != undefined);
return {
assembly: assemblyIndexed.map((el) => {
return `http://${host}:${port}/${entity}/sdf/meshes/${assembly[el]}.obj`;
}),
count: assemblyIndexed.length,
offset: assembly.length,
};
}
}
}

View file

@ -1,29 +0,0 @@
import express, { Router } from 'express';
import { Routes } from '../../core/interfaces/router';
import { autowired } from 'first-di';
// import { AssemblyController } from './assembly_create_controller';
import path from 'path';
import { dirname } from '../../app';
import validationMiddleware from '../../core/middlewares/ValidationMiddleware';
import { AssemblyPreviewsController } from './assembly_previews_controller';
// import { CadFilesModel } from './model/zip_files_model';
export class AssemblyPreviewsRoute implements Routes {
public path = '/assembly/preview/';
public router = Router();
@autowired()
private readonly assemblyPreviewsController: AssemblyPreviewsController;
constructor() {
this.initializeRoutes();
}
private initializeRoutes() {
this.router.get(`${this.path}`, this.assemblyPreviewsController.getAllAssembly);
// this.router.get(`${this.path}`)
this.router.get(`${this.path}subsequence/:id`, this.assemblyPreviewsController.getAssemblySubsequenceById)
this.router.get(`${this.path}insertion_sequence/:id`, this.assemblyPreviewsController.getAssemblyInsertionSequenceById)
// this.router.post(`${this.path}`, validationMiddleware(CadFilesModel, 'files'), this.assemblyController.createAssembly)
// this.router.get(`${this.path}`, this.assemblyController.getAllAssembly)
}
}

View file

@ -1,14 +0,0 @@
import { App } from "./app";
import { routes } from "./core/routes/routes";
import "reflect-metadata";
export const port = 3002
const app = new App(routes,port);
function main() {
app.listen();
}
main();

View file

@ -1,28 +0,0 @@
{
"compileOnSave": false,
"compilerOptions": {
"target": "es2017",
"lib": ["es2017", "esnext.asynciterable"],
"typeRoots": ["node_modules/@types"],
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"module": "ESNext",
"pretty": true,
"sourceMap": true,
"declaration": true,
"outDir": "./dist",
"allowJs": true,
"noEmit": false,
"esModuleInterop": true,
"resolveJsonModule": true,
},
"ts-node": {
"esm": true,
"experimentalSpecifierResolution": "node",
},
"include": ["src/**/*.ts", "src/**/*.json", ".env"],
"exclude": ["node_modules"]
}

View file

@ -1,46 +0,0 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `yarn start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `yarn test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `yarn build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `yarn eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).

View file

@ -1,104 +0,0 @@
'use strict';
const fs = require('fs');
const path = require('path');
const paths = require('./paths');
// Make sure that including paths.js after env.js will read .env variables.
delete require.cache[require.resolve('./paths')];
const NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV) {
throw new Error(
'The NODE_ENV environment variable is required but was not specified.'
);
}
// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
const dotenvFiles = [
`${paths.dotenv}.${NODE_ENV}.local`,
// Don't include `.env.local` for `test` environment
// since normally you expect tests to produce the same
// results for everyone
NODE_ENV !== 'test' && `${paths.dotenv}.local`,
`${paths.dotenv}.${NODE_ENV}`,
paths.dotenv,
].filter(Boolean);
// Load environment variables from .env* files. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set. Variable expansion is supported in .env files.
// https://github.com/motdotla/dotenv
// https://github.com/motdotla/dotenv-expand
dotenvFiles.forEach(dotenvFile => {
if (fs.existsSync(dotenvFile)) {
require('dotenv-expand')(
require('dotenv').config({
path: dotenvFile,
})
);
}
});
// We support resolving modules according to `NODE_PATH`.
// This lets you use absolute paths in imports inside large monorepos:
// https://github.com/facebook/create-react-app/issues/253.
// It works similar to `NODE_PATH` in Node itself:
// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
// Otherwise, we risk importing Node.js core modules into an app instead of webpack shims.
// https://github.com/facebook/create-react-app/issues/1023#issuecomment-265344421
// We also resolve them to make sure all tools using them work consistently.
const appDirectory = fs.realpathSync(process.cwd());
process.env.NODE_PATH = (process.env.NODE_PATH || '')
.split(path.delimiter)
.filter(folder => folder && !path.isAbsolute(folder))
.map(folder => path.resolve(appDirectory, folder))
.join(path.delimiter);
// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
// injected into the application via DefinePlugin in webpack configuration.
const REACT_APP = /^REACT_APP_/i;
function getClientEnvironment(publicUrl) {
const raw = Object.keys(process.env)
.filter(key => REACT_APP.test(key))
.reduce(
(env, key) => {
env[key] = process.env[key];
return env;
},
{
// Useful for determining whether were running in production mode.
// Most importantly, it switches React into the correct mode.
NODE_ENV: process.env.NODE_ENV || 'development',
// Useful for resolving the correct path to static assets in `public`.
// For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
// This should only be used as an escape hatch. Normally you would put
// images into the `src` and `import` them in code to get their paths.
PUBLIC_URL: publicUrl,
// We support configuring the sockjs pathname during development.
// These settings let a developer run multiple simultaneous projects.
// They are used as the connection `hostname`, `pathname` and `port`
// in webpackHotDevClient. They are used as the `sockHost`, `sockPath`
// and `sockPort` options in webpack-dev-server.
WDS_SOCKET_HOST: process.env.WDS_SOCKET_HOST,
WDS_SOCKET_PATH: process.env.WDS_SOCKET_PATH,
WDS_SOCKET_PORT: process.env.WDS_SOCKET_PORT,
// Whether or not react-refresh is enabled.
// It is defined here so it is available in the webpackHotDevClient.
FAST_REFRESH: process.env.FAST_REFRESH !== 'false',
}
);
// Stringify all values so we can feed into webpack DefinePlugin
const stringified = {
'process.env': Object.keys(raw).reduce((env, key) => {
env[key] = JSON.stringify(raw[key]);
return env;
}, {}),
};
return { raw, stringified };
}
module.exports = getClientEnvironment;

View file

@ -1,66 +0,0 @@
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const chalk = require('react-dev-utils/chalk');
const paths = require('./paths');
// Ensure the certificate and key provided are valid and if not
// throw an easy to debug error
function validateKeyAndCerts({ cert, key, keyFile, crtFile }) {
let encrypted;
try {
// publicEncrypt will throw an error with an invalid cert
encrypted = crypto.publicEncrypt(cert, Buffer.from('test'));
} catch (err) {
throw new Error(
`The certificate "${chalk.yellow(crtFile)}" is invalid.\n${err.message}`
);
}
try {
// privateDecrypt will throw an error with an invalid key
crypto.privateDecrypt(key, encrypted);
} catch (err) {
throw new Error(
`The certificate key "${chalk.yellow(keyFile)}" is invalid.\n${
err.message
}`
);
}
}
// Read file and throw an error if it doesn't exist
function readEnvFile(file, type) {
if (!fs.existsSync(file)) {
throw new Error(
`You specified ${chalk.cyan(
type
)} in your env, but the file "${chalk.yellow(file)}" can't be found.`
);
}
return fs.readFileSync(file);
}
// Get the https config
// Return cert files if provided in env, otherwise just true or false
function getHttpsConfig() {
const { SSL_CRT_FILE, SSL_KEY_FILE, HTTPS } = process.env;
const isHttps = HTTPS === 'true';
if (isHttps && SSL_CRT_FILE && SSL_KEY_FILE) {
const crtFile = path.resolve(paths.appPath, SSL_CRT_FILE);
const keyFile = path.resolve(paths.appPath, SSL_KEY_FILE);
const config = {
cert: readEnvFile(crtFile, 'SSL_CRT_FILE'),
key: readEnvFile(keyFile, 'SSL_KEY_FILE'),
};
validateKeyAndCerts({ ...config, keyFile, crtFile });
return config;
}
return isHttps;
}
module.exports = getHttpsConfig;

View file

@ -1,29 +0,0 @@
'use strict';
const babelJest = require('babel-jest').default;
const hasJsxRuntime = (() => {
if (process.env.DISABLE_NEW_JSX_TRANSFORM === 'true') {
return false;
}
try {
require.resolve('react/jsx-runtime');
return true;
} catch (e) {
return false;
}
})();
module.exports = babelJest.createTransformer({
presets: [
[
require.resolve('babel-preset-react-app'),
{
runtime: hasJsxRuntime ? 'automatic' : 'classic',
},
],
],
babelrc: false,
configFile: false,
});

View file

@ -1,14 +0,0 @@
'use strict';
// This is a custom Jest transformer turning style imports into empty objects.
// http://facebook.github.io/jest/docs/en/webpack.html
module.exports = {
process() {
return 'module.exports = {};';
},
getCacheKey() {
// The output is always the same.
return 'cssTransform';
},
};

View file

@ -1,40 +0,0 @@
'use strict';
const path = require('path');
const camelcase = require('camelcase');
// This is a custom Jest transformer turning file imports into filenames.
// http://facebook.github.io/jest/docs/en/webpack.html
module.exports = {
process(src, filename) {
const assetFilename = JSON.stringify(path.basename(filename));
if (filename.match(/\.svg$/)) {
// Based on how SVGR generates a component name:
// https://github.com/smooth-code/svgr/blob/01b194cf967347d43d4cbe6b434404731b87cf27/packages/core/src/state.js#L6
const pascalCaseFilename = camelcase(path.parse(filename).name, {
pascalCase: true,
});
const componentName = `Svg${pascalCaseFilename}`;
return `const React = require('react');
module.exports = {
__esModule: true,
default: ${assetFilename},
ReactComponent: React.forwardRef(function ${componentName}(props, ref) {
return {
$$typeof: Symbol.for('react.element'),
type: 'svg',
ref: ref,
key: null,
props: Object.assign({}, props, {
children: ${assetFilename}
})
};
}),
};`;
}
return `module.exports = ${assetFilename};`;
},
};

View file

@ -1,134 +0,0 @@
'use strict';
const fs = require('fs');
const path = require('path');
const paths = require('./paths');
const chalk = require('react-dev-utils/chalk');
const resolve = require('resolve');
/**
* Get additional module paths based on the baseUrl of a compilerOptions object.
*
* @param {Object} options
*/
function getAdditionalModulePaths(options = {}) {
const baseUrl = options.baseUrl;
if (!baseUrl) {
return '';
}
const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
// We don't need to do anything if `baseUrl` is set to `node_modules`. This is
// the default behavior.
if (path.relative(paths.appNodeModules, baseUrlResolved) === '') {
return null;
}
// Allow the user set the `baseUrl` to `appSrc`.
if (path.relative(paths.appSrc, baseUrlResolved) === '') {
return [paths.appSrc];
}
// If the path is equal to the root directory we ignore it here.
// We don't want to allow importing from the root directly as source files are
// not transpiled outside of `src`. We do allow importing them with the
// absolute path (e.g. `src/Components/Button.js`) but we set that up with
// an alias.
if (path.relative(paths.appPath, baseUrlResolved) === '') {
return null;
}
// Otherwise, throw an error.
throw new Error(
chalk.red.bold(
"Your project's `baseUrl` can only be set to `src` or `node_modules`." +
' Create React App does not support other values at this time.'
)
);
}
/**
* Get webpack aliases based on the baseUrl of a compilerOptions object.
*
* @param {*} options
*/
function getWebpackAliases(options = {}) {
const baseUrl = options.baseUrl;
if (!baseUrl) {
return {};
}
const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
if (path.relative(paths.appPath, baseUrlResolved) === '') {
return {
src: paths.appSrc,
};
}
}
/**
* Get jest aliases based on the baseUrl of a compilerOptions object.
*
* @param {*} options
*/
function getJestAliases(options = {}) {
const baseUrl = options.baseUrl;
if (!baseUrl) {
return {};
}
const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
if (path.relative(paths.appPath, baseUrlResolved) === '') {
return {
'^src/(.*)$': '<rootDir>/src/$1',
};
}
}
function getModules() {
// Check if TypeScript is setup
const hasTsConfig = fs.existsSync(paths.appTsConfig);
const hasJsConfig = fs.existsSync(paths.appJsConfig);
if (hasTsConfig && hasJsConfig) {
throw new Error(
'You have both a tsconfig.json and a jsconfig.json. If you are using TypeScript please remove your jsconfig.json file.'
);
}
let config;
// If there's a tsconfig.json we assume it's a
// TypeScript project and set up the config
// based on tsconfig.json
if (hasTsConfig) {
const ts = require(resolve.sync('typescript', {
basedir: paths.appNodeModules,
}));
config = ts.readConfigFile(paths.appTsConfig, ts.sys.readFile).config;
// Otherwise we'll check if there is jsconfig.json
// for non TS projects.
} else if (hasJsConfig) {
config = require(paths.appJsConfig);
}
config = config || {};
const options = config.compilerOptions || {};
const additionalModulePaths = getAdditionalModulePaths(options);
return {
additionalModulePaths: additionalModulePaths,
webpackAliases: getWebpackAliases(options),
jestAliases: getJestAliases(options),
hasTsConfig,
};
}
module.exports = getModules();

View file

@ -1,77 +0,0 @@
'use strict';
const path = require('path');
const fs = require('fs');
const getPublicUrlOrPath = require('react-dev-utils/getPublicUrlOrPath');
// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebook/create-react-app/issues/637
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
// We use `PUBLIC_URL` environment variable or "homepage" field to infer
// "public path" at which the app is served.
// webpack needs to know it to put the right <script> hrefs into HTML even in
// single-page apps that may serve index.html for nested URLs like /todos/42.
// We can't use a relative path in HTML because we don't want to load something
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
const publicUrlOrPath = getPublicUrlOrPath(
process.env.NODE_ENV === 'development',
require(resolveApp('package.json')).homepage,
process.env.PUBLIC_URL
);
const buildPath = process.env.BUILD_PATH || 'build';
const moduleFileExtensions = [
'web.mjs',
'mjs',
'web.js',
'js',
'web.ts',
'ts',
'web.tsx',
'tsx',
'json',
'web.jsx',
'jsx',
];
// Resolve file paths in the same order as webpack
const resolveModule = (resolveFn, filePath) => {
const extension = moduleFileExtensions.find(extension =>
fs.existsSync(resolveFn(`${filePath}.${extension}`))
);
if (extension) {
return resolveFn(`${filePath}.${extension}`);
}
return resolveFn(`${filePath}.js`);
};
// config after eject: we're in ./config/
module.exports = {
dotenv: resolveApp('.env'),
appPath: resolveApp('.'),
appBuild: resolveApp(buildPath),
appPublic: resolveApp('public'),
appHtml: resolveApp('public/index.html'),
appIndexJs: resolveModule(resolveApp, 'src/index'),
appPackageJson: resolveApp('package.json'),
appSrc: resolveApp('src'),
appTsConfig: resolveApp('tsconfig.json'),
appJsConfig: resolveApp('jsconfig.json'),
yarnLockFile: resolveApp('yarn.lock'),
testsSetup: resolveModule(resolveApp, 'src/setupTests'),
proxySetup: resolveApp('src/setupProxy.js'),
appNodeModules: resolveApp('node_modules'),
appWebpackCache: resolveApp('node_modules/.cache'),
appTsBuildInfoFile: resolveApp('node_modules/.cache/tsconfig.tsbuildinfo'),
swSrc: resolveModule(resolveApp, 'src/service-worker'),
publicUrlOrPath,
};
module.exports.moduleFileExtensions = moduleFileExtensions;

View file

@ -1,755 +0,0 @@
'use strict';
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
const resolve = require('resolve');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InlineChunkHtmlPlugin = require('react-dev-utils/InlineChunkHtmlPlugin');
const TerserPlugin = require('terser-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const { WebpackManifestPlugin } = require('webpack-manifest-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WorkboxWebpackPlugin = require('workbox-webpack-plugin');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent');
const ESLintPlugin = require('eslint-webpack-plugin');
const paths = require('./paths');
const modules = require('./modules');
const getClientEnvironment = require('./env');
const ModuleNotFoundPlugin = require('react-dev-utils/ModuleNotFoundPlugin');
const ForkTsCheckerWebpackPlugin =
process.env.TSC_COMPILE_ON_ERROR === 'true'
? require('react-dev-utils/ForkTsCheckerWarningWebpackPlugin')
: require('react-dev-utils/ForkTsCheckerWebpackPlugin');
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
const createEnvironmentHash = require('./webpack/persistentCache/createEnvironmentHash');
// Source maps are resource heavy and can cause out of memory issue for large source files.
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
const reactRefreshRuntimeEntry = require.resolve('react-refresh/runtime');
const reactRefreshWebpackPluginRuntimeEntry = require.resolve(
'@pmmmwh/react-refresh-webpack-plugin'
);
const babelRuntimeEntry = require.resolve('babel-preset-react-app');
const babelRuntimeEntryHelpers = require.resolve(
'@babel/runtime/helpers/esm/assertThisInitialized',
{ paths: [babelRuntimeEntry] }
);
const babelRuntimeRegenerator = require.resolve('@babel/runtime/regenerator', {
paths: [babelRuntimeEntry],
});
// Some apps do not need the benefits of saving a web request, so not inlining the chunk
// makes for a smoother build process.
const shouldInlineRuntimeChunk = process.env.INLINE_RUNTIME_CHUNK !== 'false';
const emitErrorsAsWarnings = process.env.ESLINT_NO_DEV_ERRORS === 'true';
const disableESLintPlugin = process.env.DISABLE_ESLINT_PLUGIN === 'true';
const imageInlineSizeLimit = parseInt(
process.env.IMAGE_INLINE_SIZE_LIMIT || '10000'
);
// Check if TypeScript is setup
const useTypeScript = fs.existsSync(paths.appTsConfig);
// Check if Tailwind config exists
const useTailwind = fs.existsSync(
path.join(paths.appPath, 'tailwind.config.js')
);
// Get the path to the uncompiled service worker (if it exists).
const swSrc = paths.swSrc;
// style files regexes
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;
const hasJsxRuntime = (() => {
if (process.env.DISABLE_NEW_JSX_TRANSFORM === 'true') {
return false;
}
try {
require.resolve('react/jsx-runtime');
return true;
} catch (e) {
return false;
}
})();
// This is the production and development configuration.
// It is focused on developer experience, fast rebuilds, and a minimal bundle.
module.exports = function (webpackEnv) {
const isEnvDevelopment = webpackEnv === 'development';
const isEnvProduction = webpackEnv === 'production';
// Variable used for enabling profiling in Production
// passed into alias object. Uses a flag if passed into the build command
const isEnvProductionProfile =
isEnvProduction && process.argv.includes('--profile');
// We will provide `paths.publicUrlOrPath` to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
// Get environment variables to inject into our app.
const env = getClientEnvironment(paths.publicUrlOrPath.slice(0, -1));
const shouldUseReactRefresh = env.raw.FAST_REFRESH;
// common function to get style loaders
const getStyleLoaders = (cssOptions, preProcessor) => {
const loaders = [
isEnvDevelopment && require.resolve('style-loader'),
isEnvProduction && {
loader: MiniCssExtractPlugin.loader,
// css is located in `static/css`, use '../../' to locate index.html folder
// in production `paths.publicUrlOrPath` can be a relative path
options: paths.publicUrlOrPath.startsWith('.')
? { publicPath: '../../' }
: {},
},
{
loader: require.resolve('css-loader'),
options: cssOptions,
},
{
// Options for PostCSS as we reference these options twice
// Adds vendor prefixing based on your specified browser support in
// package.json
loader: require.resolve('postcss-loader'),
options: {
postcssOptions: {
// Necessary for external CSS imports to work
// https://github.com/facebook/create-react-app/issues/2677
ident: 'postcss',
config: false,
plugins: !useTailwind
? [
'postcss-flexbugs-fixes',
[
'postcss-preset-env',
{
autoprefixer: {
flexbox: 'no-2009',
},
stage: 3,
},
],
// Adds PostCSS Normalize as the reset css with default options,
// so that it honors browserslist config in package.json
// which in turn let's users customize the target behavior as per their needs.
'postcss-normalize',
]
: [
'tailwindcss',
'postcss-flexbugs-fixes',
[
'postcss-preset-env',
{
autoprefixer: {
flexbox: 'no-2009',
},
stage: 3,
},
],
],
},
sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
},
},
].filter(Boolean);
if (preProcessor) {
loaders.push(
{
loader: require.resolve('resolve-url-loader'),
options: {
sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
root: paths.appSrc,
},
},
{
loader: require.resolve(preProcessor),
options: {
sourceMap: true,
},
}
);
}
return loaders;
};
return {
target: ['browserslist'],
// Webpack noise constrained to errors and warnings
stats: 'errors-warnings',
mode: isEnvProduction ? 'production' : isEnvDevelopment && 'development',
// Stop compilation early in production
bail: isEnvProduction,
devtool: isEnvProduction
? shouldUseSourceMap
? 'source-map'
: false
: isEnvDevelopment && 'cheap-module-source-map',
// These are the "entry points" to our application.
// This means they will be the "root" imports that are included in JS bundle.
entry: paths.appIndexJs,
output: {
// The build folder.
path: paths.appBuild,
// Add /* filename */ comments to generated require()s in the output.
pathinfo: isEnvDevelopment,
// There will be one main bundle, and one file per asynchronous chunk.
// In development, it does not produce real files.
filename: isEnvProduction
? 'static/js/[name].[contenthash:8].js'
: isEnvDevelopment && 'static/js/bundle.js',
// There are also additional JS chunk files if you use code splitting.
chunkFilename: isEnvProduction
? 'static/js/[name].[contenthash:8].chunk.js'
: isEnvDevelopment && 'static/js/[name].chunk.js',
assetModuleFilename: 'static/media/[name].[hash][ext]',
// webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
// We inferred the "public path" (such as / or /my-project) from homepage.
publicPath: paths.publicUrlOrPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: isEnvProduction
? info =>
path
.relative(paths.appSrc, info.absoluteResourcePath)
.replace(/\\/g, '/')
: isEnvDevelopment &&
(info => path.resolve(info.absoluteResourcePath).replace(/\\/g, '/')),
},
cache: {
type: 'filesystem',
version: createEnvironmentHash(env.raw),
cacheDirectory: paths.appWebpackCache,
store: 'pack',
buildDependencies: {
defaultWebpack: ['webpack/lib/'],
config: [__filename],
tsconfig: [paths.appTsConfig, paths.appJsConfig].filter(f =>
fs.existsSync(f)
),
},
},
infrastructureLogging: {
level: 'none',
},
optimization: {
minimize: isEnvProduction,
minimizer: [
// This is only used in production mode
new TerserPlugin({
terserOptions: {
parse: {
// We want terser to parse ecma 8 code. However, we don't want it
// to apply any minification steps that turns valid ecma 5 code
// into invalid ecma 5 code. This is why the 'compress' and 'output'
// sections only apply transformations that are ecma 5 safe
// https://github.com/facebook/create-react-app/pull/4234
ecma: 8,
},
compress: {
ecma: 5,
warnings: false,
// Disabled because of an issue with Uglify breaking seemingly valid code:
// https://github.com/facebook/create-react-app/issues/2376
// Pending further investigation:
// https://github.com/mishoo/UglifyJS2/issues/2011
comparisons: false,
// Disabled because of an issue with Terser breaking valid code:
// https://github.com/facebook/create-react-app/issues/5250
// Pending further investigation:
// https://github.com/terser-js/terser/issues/120
inline: 2,
},
mangle: {
safari10: true,
},
// Added for profiling in devtools
keep_classnames: isEnvProductionProfile,
keep_fnames: isEnvProductionProfile,
output: {
ecma: 5,
comments: false,
// Turned on because emoji and regex is not minified properly using default
// https://github.com/facebook/create-react-app/issues/2488
ascii_only: true,
},
},
}),
// This is only used in production mode
new CssMinimizerPlugin(),
],
},
resolve: {
// This allows you to set a fallback for where webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebook/create-react-app/issues/253
modules: ['node_modules', paths.appNodeModules].concat(
modules.additionalModulePaths || []
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebook/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: paths.moduleFileExtensions
.map(ext => `.${ext}`)
.filter(ext => useTypeScript || !ext.includes('ts')),
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
// Allows for better profiling with ReactDevTools
...(isEnvProductionProfile && {
'react-dom$': 'react-dom/profiling',
'scheduler/tracing': 'scheduler/tracing-profiling',
}),
...(modules.webpackAliases || {}),
},
plugins: [
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
new ModuleScopePlugin(paths.appSrc, [
paths.appPackageJson,
reactRefreshRuntimeEntry,
reactRefreshWebpackPluginRuntimeEntry,
babelRuntimeEntry,
babelRuntimeEntryHelpers,
babelRuntimeRegenerator,
]),
],
},
module: {
strictExportPresence: true,
rules: [
// Handle node_modules packages that contain sourcemaps
shouldUseSourceMap && {
enforce: 'pre',
exclude: /@babel(?:\/|\\{1,2})runtime/,
test: /\.(js|mjs|jsx|ts|tsx|css)$/,
loader: require.resolve('source-map-loader'),
},
{
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
// TODO: Merge this config once `image/avif` is in the mime-db
// https://github.com/jshttp/mime-db
{
test: [/\.avif$/],
type: 'asset',
mimetype: 'image/avif',
parser: {
dataUrlCondition: {
maxSize: imageInlineSizeLimit,
},
},
},
// "url" loader works like "file" loader except that it embeds assets
// smaller than specified limit in bytes as data URLs to avoid requests.
// A missing `test` is equivalent to a match.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
type: 'asset',
parser: {
dataUrlCondition: {
maxSize: imageInlineSizeLimit,
},
},
},
{
test: /\.svg$/,
use: [
{
loader: require.resolve('@svgr/webpack'),
options: {
prettier: false,
svgo: false,
svgoConfig: {
plugins: [{ removeViewBox: false }],
},
titleProp: true,
ref: true,
},
},
{
loader: require.resolve('file-loader'),
options: {
name: 'static/media/[name].[hash].[ext]',
},
},
],
issuer: {
and: [/\.(ts|tsx|js|jsx|md|mdx)$/],
},
},
// Process application JS with Babel.
// The preset includes JSX, Flow, TypeScript, and some ESnext features.
{
test: /\.(js|mjs|jsx|ts|tsx)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
customize: require.resolve(
'babel-preset-react-app/webpack-overrides'
),
presets: [
[
require.resolve('babel-preset-react-app'),
{
runtime: hasJsxRuntime ? 'automatic' : 'classic',
},
],
],
plugins: [
isEnvDevelopment &&
shouldUseReactRefresh &&
require.resolve('react-refresh/babel'),
].filter(Boolean),
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true,
// See #6846 for context on why cacheCompression is disabled
cacheCompression: false,
compact: isEnvProduction,
},
},
// Process any JS outside of the app with Babel.
// Unlike the application JS, we only compile the standard ES features.
{
test: /\.(js|mjs)$/,
exclude: /@babel(?:\/|\\{1,2})runtime/,
loader: require.resolve('babel-loader'),
options: {
babelrc: false,
configFile: false,
compact: false,
presets: [
[
require.resolve('babel-preset-react-app/dependencies'),
{ helpers: true },
],
],
cacheDirectory: true,
// See #6846 for context on why cacheCompression is disabled
cacheCompression: false,
// Babel sourcemaps are needed for debugging into node_modules
// code. Without the options below, debuggers like VSCode
// show incorrect code and set breakpoints on the wrong lines.
sourceMaps: shouldUseSourceMap,
inputSourceMap: shouldUseSourceMap,
},
},
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use MiniCSSExtractPlugin to extract that CSS
// to a file, but in development "style" loader enables hot editing
// of CSS.
// By default we support CSS Modules with the extension .module.css
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
modules: {
mode: 'icss',
},
}),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
// Adds support for CSS Modules (https://github.com/css-modules/css-modules)
// using the extension .module.css
{
test: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
modules: {
mode: 'local',
getLocalIdent: getCSSModuleLocalIdent,
},
}),
},
// Opt-in support for SASS (using .scss or .sass extensions).
// By default we support SASS Modules with the
// extensions .module.scss or .module.sass
{
test: sassRegex,
exclude: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 3,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
modules: {
mode: 'icss',
},
},
'sass-loader'
),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
// Adds support for CSS Modules, but using SASS
// using the extension .module.scss or .module.sass
{
test: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 3,
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
modules: {
mode: 'local',
getLocalIdent: getCSSModuleLocalIdent,
},
},
'sass-loader'
),
},
// "file" loader makes sure those assets get served by WebpackDevServer.
// When you `import` an asset, you get its (virtual) filename.
// In production, they would get copied to the `build` folder.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
// Exclude `js` files to keep "css" loader working as it injects
// its runtime that would otherwise be processed through "file" loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/^$/, /\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
type: 'asset/resource',
},
// ** STOP ** Are you adding a new loader?
// Make sure to add the new loader(s) before the "file" loader.
],
},
].filter(Boolean),
},
plugins: [
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin(
Object.assign(
{},
{
inject: true,
template: paths.appHtml,
},
isEnvProduction
? {
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}
: undefined
)
),
// Inlines the webpack runtime script. This script is too small to warrant
// a network request.
// https://github.com/facebook/create-react-app/issues/5358
isEnvProduction &&
shouldInlineRuntimeChunk &&
new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime-.+[.]js/]),
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="icon" href="%PUBLIC_URL%/favicon.ico">
// It will be an empty string unless you specify "homepage"
// in `package.json`, in which case it will be the pathname of that URL.
new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
// This gives some necessary context to module not found errors, such as
// the requesting resource.
new ModuleNotFoundPlugin(paths.appPath),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
// It is absolutely essential that NODE_ENV is set to production
// during a production build.
// Otherwise React will be compiled in the very slow development mode.
new webpack.DefinePlugin(env.stringified),
// Experimental hot reloading for React .
// https://github.com/facebook/react/tree/main/packages/react-refresh
isEnvDevelopment &&
shouldUseReactRefresh &&
new ReactRefreshWebpackPlugin({
overlay: false,
}),
// Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this.
// See https://github.com/facebook/create-react-app/issues/240
isEnvDevelopment && new CaseSensitivePathsPlugin(),
isEnvProduction &&
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: 'static/css/[name].[contenthash:8].css',
chunkFilename: 'static/css/[name].[contenthash:8].chunk.css',
}),
// Generate an asset manifest file with the following content:
// - "files" key: Mapping of all asset filenames to their corresponding
// output file so that tools can pick it up without having to parse
// `index.html`
// - "entrypoints" key: Array of files which are included in `index.html`,
// can be used to reconstruct the HTML if necessary
new WebpackManifestPlugin({
fileName: 'asset-manifest.json',
publicPath: paths.publicUrlOrPath,
generate: (seed, files, entrypoints) => {
const manifestFiles = files.reduce((manifest, file) => {
manifest[file.name] = file.path;
return manifest;
}, seed);
const entrypointFiles = entrypoints.main.filter(
fileName => !fileName.endsWith('.map')
);
return {
files: manifestFiles,
entrypoints: entrypointFiles,
};
},
}),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin({
resourceRegExp: /^\.\/locale$/,
contextRegExp: /moment$/,
}),
// Generate a service worker script that will precache, and keep up to date,
// the HTML & assets that are part of the webpack build.
isEnvProduction &&
fs.existsSync(swSrc) &&
new WorkboxWebpackPlugin.InjectManifest({
swSrc,
dontCacheBustURLsMatching: /\.[0-9a-f]{8}\./,
exclude: [/\.map$/, /asset-manifest\.json$/, /LICENSE/],
// Bump up the default maximum size (2mb) that's precached,
// to make lazy-loading failure scenarios less likely.
// See https://github.com/cra-template/pwa/issues/13#issuecomment-722667270
maximumFileSizeToCacheInBytes: 5 * 1024 * 1024,
}),
// TypeScript type checking
useTypeScript &&
new ForkTsCheckerWebpackPlugin({
async: isEnvDevelopment,
typescript: {
typescriptPath: resolve.sync('typescript', {
basedir: paths.appNodeModules,
}),
configOverwrite: {
compilerOptions: {
sourceMap: isEnvProduction
? shouldUseSourceMap
: isEnvDevelopment,
skipLibCheck: true,
inlineSourceMap: false,
declarationMap: false,
noEmit: true,
incremental: true,
tsBuildInfoFile: paths.appTsBuildInfoFile,
},
},
context: paths.appPath,
diagnosticOptions: {
syntactic: true,
},
mode: 'write-references',
// profile: true,
},
issue: {
// This one is specifically to match during CI tests,
// as micromatch doesn't match
// '../cra-template-typescript/template/src/App.tsx'
// otherwise.
include: [
{ file: '../**/src/**/*.{ts,tsx}' },
{ file: '**/src/**/*.{ts,tsx}' },
],
exclude: [
{ file: '**/src/**/__tests__/**' },
{ file: '**/src/**/?(*.){spec|test}.*' },
{ file: '**/src/setupProxy.*' },
{ file: '**/src/setupTests.*' },
],
},
logger: {
infrastructure: 'silent',
},
}),
!disableESLintPlugin &&
new ESLintPlugin({
// Plugin options
extensions: ['js', 'mjs', 'jsx', 'ts', 'tsx'],
formatter: require.resolve('react-dev-utils/eslintFormatter'),
eslintPath: require.resolve('eslint'),
failOnError: !(isEnvDevelopment && emitErrorsAsWarnings),
context: paths.appSrc,
cache: true,
cacheLocation: path.resolve(
paths.appNodeModules,
'.cache/.eslintcache'
),
// ESLint class options
cwd: paths.appPath,
resolvePluginsRelativeTo: __dirname,
baseConfig: {
extends: [require.resolve('eslint-config-react-app/base')],
rules: {
...(!hasJsxRuntime && {
'react/react-in-jsx-scope': 'error',
}),
},
},
}),
].filter(Boolean),
// Turn off performance processing because we utilize
// our own hints via the FileSizeReporter
performance: false,
};
};

View file

@ -1,9 +0,0 @@
'use strict';
const { createHash } = require('crypto');
module.exports = env => {
const hash = createHash('md5');
hash.update(JSON.stringify(env));
return hash.digest('hex');
};

View file

@ -1,127 +0,0 @@
'use strict';
const fs = require('fs');
const evalSourceMapMiddleware = require('react-dev-utils/evalSourceMapMiddleware');
const noopServiceWorkerMiddleware = require('react-dev-utils/noopServiceWorkerMiddleware');
const ignoredFiles = require('react-dev-utils/ignoredFiles');
const redirectServedPath = require('react-dev-utils/redirectServedPathMiddleware');
const paths = require('./paths');
const getHttpsConfig = require('./getHttpsConfig');
const host = process.env.HOST || '0.0.0.0';
const sockHost = process.env.WDS_SOCKET_HOST;
const sockPath = process.env.WDS_SOCKET_PATH; // default: '/ws'
const sockPort = process.env.WDS_SOCKET_PORT;
module.exports = function (proxy, allowedHost) {
const disableFirewall =
!proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true';
return {
// WebpackDevServer 2.4.3 introduced a security fix that prevents remote
// websites from potentially accessing local content through DNS rebinding:
// https://github.com/webpack/webpack-dev-server/issues/887
// https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a
// However, it made several existing use cases such as development in cloud
// environment or subdomains in development significantly more complicated:
// https://github.com/facebook/create-react-app/issues/2271
// https://github.com/facebook/create-react-app/issues/2233
// While we're investigating better solutions, for now we will take a
// compromise. Since our WDS configuration only serves files in the `public`
// folder we won't consider accessing them a vulnerability. However, if you
// use the `proxy` feature, it gets more dangerous because it can expose
// remote code execution vulnerabilities in backends like Django and Rails.
// So we will disable the host check normally, but enable it if you have
// specified the `proxy` setting. Finally, we let you override it if you
// really know what you're doing with a special environment variable.
// Note: ["localhost", ".localhost"] will support subdomains - but we might
// want to allow setting the allowedHosts manually for more complex setups
allowedHosts: disableFirewall ? 'all' : [allowedHost],
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': '*',
'Access-Control-Allow-Headers': '*',
},
// Enable gzip compression of generated files.
compress: true,
static: {
// By default WebpackDevServer serves physical files from current directory
// in addition to all the virtual build products that it serves from memory.
// This is confusing because those files wont automatically be available in
// production build folder unless we copy them. However, copying the whole
// project directory is dangerous because we may expose sensitive files.
// Instead, we establish a convention that only files in `public` directory
// get served. Our build script will copy `public` into the `build` folder.
// In `index.html`, you can get URL of `public` folder with %PUBLIC_URL%:
// <link rel="icon" href="%PUBLIC_URL%/favicon.ico">
// In JavaScript code, you can access it with `process.env.PUBLIC_URL`.
// Note that we only recommend to use `public` folder as an escape hatch
// for files like `favicon.ico`, `manifest.json`, and libraries that are
// for some reason broken when imported through webpack. If you just want to
// use an image, put it in `src` and `import` it from JavaScript instead.
directory: paths.appPublic,
publicPath: [paths.publicUrlOrPath],
// By default files from `contentBase` will not trigger a page reload.
watch: {
// Reportedly, this avoids CPU overload on some systems.
// https://github.com/facebook/create-react-app/issues/293
// src/node_modules is not ignored to support absolute imports
// https://github.com/facebook/create-react-app/issues/1065
ignored: ignoredFiles(paths.appSrc),
},
},
client: {
webSocketURL: {
// Enable custom sockjs pathname for websocket connection to hot reloading server.
// Enable custom sockjs hostname, pathname and port for websocket connection
// to hot reloading server.
hostname: sockHost,
pathname: sockPath,
port: sockPort,
},
overlay: {
errors: true,
warnings: false,
},
},
devMiddleware: {
// It is important to tell WebpackDevServer to use the same "publicPath" path as
// we specified in the webpack config. When homepage is '.', default to serving
// from the root.
// remove last slash so user can land on `/test` instead of `/test/`
publicPath: paths.publicUrlOrPath.slice(0, -1),
},
https: getHttpsConfig(),
host,
historyApiFallback: {
// Paths with dots should still use the history fallback.
// See https://github.com/facebook/create-react-app/issues/387.
disableDotRule: true,
index: paths.publicUrlOrPath,
},
// `proxy` is run between `before` and `after` `webpack-dev-server` hooks
proxy,
onBeforeSetupMiddleware(devServer) {
// Keep `evalSourceMapMiddleware`
// middlewares before `redirectServedPath` otherwise will not have any effect
// This lets us fetch source contents from webpack for the error overlay
devServer.app.use(evalSourceMapMiddleware(devServer));
if (fs.existsSync(paths.proxySetup)) {
// This registers user provided middleware for proxy reasons
require(paths.proxySetup)(devServer.app);
}
},
onAfterSetupMiddleware(devServer) {
// Redirect to `PUBLIC_URL` or `homepage` from `package.json` if url not match
devServer.app.use(redirectServedPath(paths.publicUrlOrPath));
// This service worker file is effectively a 'no-op' that will reset any
// previous service worker registered for the same host:port combination.
// We do this in development to avoid hitting the production cache if
// it used the same host and port.
// https://github.com/facebook/create-react-app/issues/2272#issuecomment-302832432
devServer.app.use(noopServiceWorkerMiddleware(paths.publicUrlOrPath));
},
};
};

File diff suppressed because it is too large Load diff

View file

@ -1,165 +0,0 @@
{
"name": "i18next",
"version": "0.1.0",
"private": true,
"dependencies": {
"@babel/core": "^7.16.0",
"@pmmmwh/react-refresh-webpack-plugin": "^0.5.3",
"@react-three/drei": "^9.65.3",
"@svgr/webpack": "^5.5.0",
"@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^13.0.0",
"@testing-library/user-event": "^13.2.1",
"@types/jest": "^27.0.1",
"@types/node": "^16.7.13",
"@types/react": "18.0.25",
"@types/react-dom": "18.0.9",
"antd": "^5.5.2",
"babel-jest": "^27.4.2",
"babel-loader": "^8.2.3",
"babel-plugin-named-asset-import": "^0.3.8",
"babel-preset-react-app": "^10.0.1",
"bfj": "^7.0.2",
"browserslist": "^4.18.1",
"camelcase": "^6.2.1",
"case-sensitive-paths-webpack-plugin": "^2.4.0",
"css-loader": "^6.5.1",
"css-minimizer-webpack-plugin": "^3.2.0",
"dotenv": "^10.0.0",
"dotenv-expand": "^5.1.0",
"eslint": "^8.3.0",
"eslint-config-react-app": "^7.0.1",
"eslint-webpack-plugin": "^3.1.1",
"file-loader": "^6.2.0",
"fs-extra": "^10.0.0",
"html-webpack-plugin": "^5.5.0",
"i18next": "^22.4.14",
"i18next-browser-languagedetector": "^7.0.1",
"identity-obj-proxy": "^3.0.0",
"jest": "^27.4.3",
"jest-resolve": "^27.4.2",
"jest-watch-typeahead": "^1.0.0",
"localforage": "^1.10.0",
"match-sorter": "^6.3.1",
"mini-css-extract-plugin": "^2.4.5",
"mobx": "^6.9.0",
"mobx-react": "^7.6.0",
"postcss": "^8.4.4",
"postcss-flexbugs-fixes": "^5.0.2",
"postcss-loader": "^6.2.1",
"postcss-normalize": "^10.0.1",
"postcss-preset-env": "^7.0.1",
"prompts": "^2.4.2",
"react": "18.0.0",
"react-app-polyfill": "^3.0.0",
"react-dev-utils": "^12.0.1",
"react-dom": "18.0.0",
"react-i18next": "^12.2.0",
"react-refresh": "^0.11.0",
"react-router-dom": "^6.11.2",
"react-three-fiber": "^6.0.13",
"resolve": "^1.20.0",
"resolve-url-loader": "^4.0.0",
"rete": "2.0.0-beta.9",
"rete-area-plugin": "2.0.0-beta.12",
"rete-connection-plugin": "2.0.0-beta.16",
"rete-react-render-plugin": "2.0.0-beta.22",
"rete-render-utils": "2.0.0-beta.12",
"sass-loader": "^12.3.0",
"semver": "^7.3.5",
"sort-by": "^1.2.0",
"source-map-loader": "^3.0.0",
"style-loader": "^3.3.1",
"tailwindcss": "^3.0.2",
"terser-webpack-plugin": "^5.2.5",
"three": "^0.151.3",
"typescript": "^4.4.2",
"web-vitals": "^2.1.0",
"webpack": "^5.64.4",
"webpack-dev-server": "^4.6.0",
"webpack-manifest-plugin": "^4.0.2",
"workbox-webpack-plugin": "^6.4.1"
},
"scripts": {
"dev": "node scripts/start.js",
"build": "node scripts/build.js",
"test": "node scripts/test.js"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@types/three": "^0.150.1"
},
"jest": {
"roots": [
"<rootDir>/src"
],
"collectCoverageFrom": [
"src/**/*.{js,jsx,ts,tsx}",
"!src/**/*.d.ts"
],
"setupFiles": [
"react-app-polyfill/jsdom"
],
"setupFilesAfterEnv": [
"<rootDir>/src/setupTests.ts"
],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}",
"<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}"
],
"testEnvironment": "jsdom",
"transform": {
"^.+\\.(js|jsx|mjs|cjs|ts|tsx)$": "<rootDir>/config/jest/babelTransform.js",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|mjs|cjs|ts|tsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs|cjs|ts|tsx)$",
"^.+\\.module\\.(css|sass|scss)$"
],
"modulePaths": [],
"moduleNameMapper": {
"^react-native$": "react-native-web",
"^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy"
},
"moduleFileExtensions": [
"web.js",
"js",
"web.ts",
"ts",
"web.tsx",
"tsx",
"json",
"web.jsx",
"jsx",
"node"
],
"watchPlugins": [
"jest-watch-typeahead/filename",
"jest-watch-typeahead/testname"
],
"resetMocks": true
},
"babel": {
"presets": [
"react-app"
]
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

View file

@ -1,43 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div class="root" id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.4 KiB

View file

@ -1,25 +0,0 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View file

@ -1,3 +0,0 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

View file

@ -1,217 +0,0 @@
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'production';
process.env.NODE_ENV = 'production';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const path = require('path');
const chalk = require('react-dev-utils/chalk');
const fs = require('fs-extra');
const bfj = require('bfj');
const webpack = require('webpack');
const configFactory = require('../config/webpack.config');
const paths = require('../config/paths');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
const printHostingInstructions = require('react-dev-utils/printHostingInstructions');
const FileSizeReporter = require('react-dev-utils/FileSizeReporter');
const printBuildError = require('react-dev-utils/printBuildError');
const measureFileSizesBeforeBuild =
FileSizeReporter.measureFileSizesBeforeBuild;
const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
const useYarn = fs.existsSync(paths.yarnLockFile);
// These sizes are pretty large. We'll warn for bundles exceeding them.
const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;
const isInteractive = process.stdout.isTTY;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
const argv = process.argv.slice(2);
const writeStatsJson = argv.indexOf('--stats') !== -1;
// Generate configuration
const config = configFactory('production');
// We require that you explicitly set browsers and do not fall back to
// browserslist defaults.
const { checkBrowsers } = require('react-dev-utils/browsersHelper');
checkBrowsers(paths.appPath, isInteractive)
.then(() => {
// First, read the current file sizes in build directory.
// This lets us display how much they changed later.
return measureFileSizesBeforeBuild(paths.appBuild);
})
.then(previousFileSizes => {
// Remove all content but keep the directory so that
// if you're in it, you don't end up in Trash
fs.emptyDirSync(paths.appBuild);
// Merge with the public folder
copyPublicFolder();
// Start the webpack build
return build(previousFileSizes);
})
.then(
({ stats, previousFileSizes, warnings }) => {
if (warnings.length) {
console.log(chalk.yellow('Compiled with warnings.\n'));
console.log(warnings.join('\n\n'));
console.log(
'\nSearch for the ' +
chalk.underline(chalk.yellow('keywords')) +
' to learn more about each warning.'
);
console.log(
'To ignore, add ' +
chalk.cyan('// eslint-disable-next-line') +
' to the line before.\n'
);
} else {
console.log(chalk.green('Compiled successfully.\n'));
}
console.log('File sizes after gzip:\n');
printFileSizesAfterBuild(
stats,
previousFileSizes,
paths.appBuild,
WARN_AFTER_BUNDLE_GZIP_SIZE,
WARN_AFTER_CHUNK_GZIP_SIZE
);
console.log();
const appPackage = require(paths.appPackageJson);
const publicUrl = paths.publicUrlOrPath;
const publicPath = config.output.publicPath;
const buildFolder = path.relative(process.cwd(), paths.appBuild);
printHostingInstructions(
appPackage,
publicUrl,
publicPath,
buildFolder,
useYarn
);
},
err => {
const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === 'true';
if (tscCompileOnError) {
console.log(
chalk.yellow(
'Compiled with the following type errors (you may want to check these before deploying your app):\n'
)
);
printBuildError(err);
} else {
console.log(chalk.red('Failed to compile.\n'));
printBuildError(err);
process.exit(1);
}
}
)
.catch(err => {
if (err && err.message) {
console.log(err.message);
}
process.exit(1);
});
// Create the production build and print the deployment instructions.
function build(previousFileSizes) {
console.log('Creating an optimized production build...');
const compiler = webpack(config);
return new Promise((resolve, reject) => {
compiler.run((err, stats) => {
let messages;
if (err) {
if (!err.message) {
return reject(err);
}
let errMessage = err.message;
// Add additional information for postcss errors
if (Object.prototype.hasOwnProperty.call(err, 'postcssNode')) {
errMessage +=
'\nCompileError: Begins at CSS selector ' +
err['postcssNode'].selector;
}
messages = formatWebpackMessages({
errors: [errMessage],
warnings: [],
});
} else {
messages = formatWebpackMessages(
stats.toJson({ all: false, warnings: true, errors: true })
);
}
if (messages.errors.length) {
// Only keep the first error. Others are often indicative
// of the same problem, but confuse the reader with noise.
if (messages.errors.length > 1) {
messages.errors.length = 1;
}
return reject(new Error(messages.errors.join('\n\n')));
}
if (
process.env.CI &&
(typeof process.env.CI !== 'string' ||
process.env.CI.toLowerCase() !== 'false') &&
messages.warnings.length
) {
// Ignore sourcemap warnings in CI builds. See #8227 for more info.
const filteredWarnings = messages.warnings.filter(
w => !/Failed to parse source map/.test(w)
);
if (filteredWarnings.length) {
console.log(
chalk.yellow(
'\nTreating warnings as errors because process.env.CI = true.\n' +
'Most CI servers set it automatically.\n'
)
);
return reject(new Error(filteredWarnings.join('\n\n')));
}
}
const resolveArgs = {
stats,
previousFileSizes,
warnings: messages.warnings,
};
if (writeStatsJson) {
return bfj
.write(paths.appBuild + '/bundle-stats.json', stats.toJson())
.then(() => resolve(resolveArgs))
.catch(error => reject(new Error(error)));
}
return resolve(resolveArgs);
});
});
}
function copyPublicFolder() {
fs.copySync(paths.appPublic, paths.appBuild, {
dereference: true,
filter: file => file !== paths.appHtml,
});
}

View file

@ -1,154 +0,0 @@
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const fs = require('fs');
const chalk = require('react-dev-utils/chalk');
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const clearConsole = require('react-dev-utils/clearConsole');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const {
choosePort,
createCompiler,
prepareProxy,
prepareUrls,
} = require('react-dev-utils/WebpackDevServerUtils');
const openBrowser = require('react-dev-utils/openBrowser');
const semver = require('semver');
const paths = require('../config/paths');
const configFactory = require('../config/webpack.config');
const createDevServerConfig = require('../config/webpackDevServer.config');
const getClientEnvironment = require('../config/env');
const react = require(require.resolve('react', { paths: [paths.appPath] }));
const env = getClientEnvironment(paths.publicUrlOrPath.slice(0, -1));
const useYarn = fs.existsSync(paths.yarnLockFile);
const isInteractive = process.stdout.isTTY;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// Tools like Cloud9 rely on this.
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
const HOST = process.env.HOST || '0.0.0.0';
if (process.env.HOST) {
console.log(
chalk.cyan(
`Attempting to bind to HOST environment variable: ${chalk.yellow(
chalk.bold(process.env.HOST)
)}`
)
);
console.log(
`If this was unintentional, check that you haven't mistakenly set it in your shell.`
);
console.log(
`Learn more here: ${chalk.yellow('https://cra.link/advanced-config')}`
);
console.log();
}
// We require that you explicitly set browsers and do not fall back to
// browserslist defaults.
const { checkBrowsers } = require('react-dev-utils/browsersHelper');
checkBrowsers(paths.appPath, isInteractive)
.then(() => {
// We attempt to use the default port but if it is busy, we offer the user to
// run on a different port. `choosePort()` Promise resolves to the next free port.
return choosePort(HOST, DEFAULT_PORT);
})
.then(port => {
if (port == null) {
// We have not found a port.
return;
}
const config = configFactory('development');
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
const appName = require(paths.appPackageJson).name;
const useTypeScript = fs.existsSync(paths.appTsConfig);
const urls = prepareUrls(
protocol,
HOST,
port,
paths.publicUrlOrPath.slice(0, -1)
);
// Create a webpack compiler that is configured with custom messages.
const compiler = createCompiler({
appName,
config,
urls,
useYarn,
useTypeScript,
webpack,
});
// Load proxy config
const proxySetting = require(paths.appPackageJson).proxy;
const proxyConfig = prepareProxy(
proxySetting,
paths.appPublic,
paths.publicUrlOrPath
);
// Serve webpack assets generated by the compiler over a web server.
const serverConfig = {
...createDevServerConfig(proxyConfig, urls.lanUrlForConfig),
host: HOST,
port,
};
const devServer = new WebpackDevServer(serverConfig, compiler);
// Launch WebpackDevServer.
devServer.startCallback(() => {
if (isInteractive) {
clearConsole();
}
if (env.raw.FAST_REFRESH && semver.lt(react.version, '16.10.0')) {
console.log(
chalk.yellow(
`Fast Refresh requires React 16.10 or higher. You are using React ${react.version}.`
)
);
}
console.log(chalk.cyan('Starting the development server...\n'));
openBrowser(urls.localUrlForBrowser);
});
['SIGINT', 'SIGTERM'].forEach(function (sig) {
process.on(sig, function () {
devServer.close();
process.exit();
});
});
if (process.env.CI !== 'true') {
// Gracefully exit when stdin ends
process.stdin.on('end', function () {
devServer.close();
process.exit();
});
}
})
.catch(err => {
if (err && err.message) {
console.log(err.message);
}
process.exit(1);
});

View file

@ -1,52 +0,0 @@
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'test';
process.env.NODE_ENV = 'test';
process.env.PUBLIC_URL = '';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const jest = require('jest');
const execSync = require('child_process').execSync;
let argv = process.argv.slice(2);
function isInGitRepository() {
try {
execSync('git rev-parse --is-inside-work-tree', { stdio: 'ignore' });
return true;
} catch (e) {
return false;
}
}
function isInMercurialRepository() {
try {
execSync('hg --cwd . root', { stdio: 'ignore' });
return true;
} catch (e) {
return false;
}
}
// Watch unless on CI or explicitly running all tests
if (
!process.env.CI &&
argv.indexOf('--watchAll') === -1 &&
argv.indexOf('--watchAll=false') === -1
) {
// https://github.com/facebook/create-react-app/issues/5210
const hasSourceControl = isInGitRepository() || isInMercurialRepository();
argv.push(hasSourceControl ? '--watch' : '--watchAll');
}
jest.run(argv);

View file

@ -1,44 +0,0 @@
.canvas{
width: 100vw;
height: 100vh;
display: block;
}
.root{
overflow-y: hidden;
}
.centeredDiv{
width: 100vw;
display: flex;
justify-content: center;
}
.projects-container{
width: 100%;
background-color: aliceblue;
display: flex;
flex-direction: column;
justify-content: space-evenly;
align-items: center;
overflow-y:hidden;
}
.centeredContainer{
display: flex;
flex-direction: column;
align-content: center;
align-items: center;
}
label {
background-color: indigo;
color: white;
padding: 0.5rem;
font-family: sans-serif;
border-radius: 0.3rem;
cursor: pointer;
margin-top: 1rem;
}
#file-chosen{
margin-left: 0.3rem;
font-family: sans-serif;
}

View file

@ -1,10 +0,0 @@
// @ts-nocheck
import {ReactComponent as SolidSvg} from "./assets/solid.svg";
import {ReactComponent as PartSvg} from "./assets/part.svg";
export const svg = {SolidSvg, PartSvg}
export { svg as SVG };

View file

@ -1,35 +0,0 @@
export enum HttpMethod {
GET = 'GET',
POST = 'POST'
}
export enum HttpRoute {
insertionPath = '/assembly/preview/insertion_sequence/',
assemblyPreviewPath = '/assembly/preview/subsequence/',
projects = '/assembly/preview',
createProject = '/assembly/create',
ajaxMatrix = 'matrix.json'
}
export class HttpRepository {
static server = 'http://localhost:3002'
static async jsonRequest<T>(method: HttpMethod, url: string, data?: any): Promise<T> {
const reqInit = {
'body': data,
'method': method,
'headers': { 'Content-Type': 'application/json' },
}
if (data !== undefined) {
reqInit['body'] = JSON.stringify(data)
}
return (await fetch(this.server + url, reqInit)).json()
}
static async request<T>(method: HttpMethod, url: string, data?: any): Promise<T> {
const reqInit = {
'body': data,
'method': method,
}
if (data !== undefined) {
reqInit['body'] = data
}
return (await fetch(this.server + url, reqInit)).json()
}
}

View file

@ -1,89 +0,0 @@
import * as React from "react";
import { useEffect, useState } from "react";
import {
HttpMethod,
HttpRepository,
HttpRoute,
} from "../../core/repository/http_repository";
import { Button } from "antd";
import { Typography } from "antd";
import { Card } from "antd";
import { createProjectRoute } from "../create_project/create_project";
import { useNavigate } from "react-router-dom";
import { pathAjaxTopologyScreen } from "../topology_ajax_preview/topology_ajax_preview";
import { pathStabilityScreen } from "../stability_preview/stability_preview";
const { Text, Link, Title } = Typography;
function LinkCreateProjectPage() {
const navigate = useNavigate();
return (
<Link
style={{ paddingLeft: "10px" }}
onClick={() => {
navigate(createProjectRoute);
}}
>
<> add new project?</>
</Link>
);
}
export const ProjectsPath = "/";
export const ProjectScreen: React.FunctionComponent = () => {
const [projects, setProjects] = useState<Array<String>>([]);
const navigate = useNavigate();
useEffect(() => {
async function fetchData() {
setProjects(
await HttpRepository.jsonRequest<Array<String>>(
HttpMethod.GET,
HttpRoute.projects
)
);
}
fetchData();
}, []);
return (
<>
<div className="centeredDiv">
<Title>Projects</Title>
</div>
<div>
{projects.length === 0 ? (
<div className="centeredDiv">
<Text>Not found projects</Text>
<div>
<LinkCreateProjectPage />
</div>
</div>
) : (
<div></div>
)}
</div>
<div className="projects-container">
{projects.map((el) => {
return (
<>
<Card style={{ width: 300 }}>
<div>{el}</div>
<Button onClick={() => {
navigate(pathAjaxTopologyScreen + el);
}} > Preview topology ajax computed </Button>
<Button onClick={() => {
navigate(pathStabilityScreen + el);
}} > Preview stability computed </Button>
<Button> Preview insert Path </Button>
<Button>Preview assembly logical </Button>
</Card>
</>
);
})}
<div> {projects.length === 0 ? <></> : <LinkCreateProjectPage />} </div>
</div>
</>
);
};

View file

@ -1,198 +0,0 @@
import * as React from "react";
import {
DirectionalLight,
Object3D,
PerspectiveCamera,
Scene,
WebGLRenderer,
AmbientLight,
Vector3,
Group,
Quaternion,
} from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import { OBJLoader } from "three/examples/jsm/loaders/OBJLoader";
import CSS from "csstype";
import {
HttpMethod,
HttpRepository,
HttpRoute,
} from "../../core/repository/http_repository";
import { useParams } from "react-router-dom";
const canvasStyle: CSS.Properties = {
backgroundColor: "rgb(151 41 41 / 85%)",
};
export const AssemblyPreviewInsertVectorPath = "/insertion_vector/";
export interface AssemblyPreviewInsertionPathModel {
offset: number;
count: number;
parent: string;
child: string;
insertions: Insertions;
}
export interface Insertions {
time: number;
insertion_path: InsertionPath[];
status: string;
}
export interface InsertionPath {
quadrelion: number[];
xyz: number[];
euler: number[];
}
export function AssemblyPreviewInsertVector() {
const container = new Object3D();
const canvasRef = React.useRef<HTMLCanvasElement>(null);
const scene = new Scene();
const camera = new PerspectiveCamera(
80,
window.innerWidth / window.innerHeight,
0.1,
1000
);
let renderId = 1;
let assemblyCounter: undefined | Number = undefined;
let params = useParams().id;
React.useEffect(() => {
const renderer = new WebGLRenderer({
canvas: canvasRef.current as HTMLCanvasElement,
antialias: true,
alpha: true,
});
camera.position.set(2, 1, 2);
const directionalLight = new DirectionalLight(0xffffff, 0.2);
directionalLight.castShadow = true;
directionalLight.position.set(-1, 2, 4);
scene.add(directionalLight);
const ambientLight = new AmbientLight(0xffffff, 0.7);
scene.add(ambientLight);
container.position.set(0, 0, 0);
renderer.setSize(window.innerWidth, window.innerHeight);
const onResize = () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer!.setSize(window.innerWidth, window.innerHeight);
};
window.addEventListener("resize", onResize, false);
new OrbitControls(camera, renderer.domElement);
renderer!.setAnimationLoop(() => {
renderer!.render(scene, camera);
});
renderObject(1, params!);
});
async function renderObject(renderId: Number, projectId: String) {
const assemblyResponse =
await HttpRepository.jsonRequest<AssemblyPreviewInsertionPathModel>(
HttpMethod.GET,
`${HttpRoute.insertionPath}${projectId}?count=${renderId}`
);
const objectControl = (
await loadObject([assemblyResponse.child, assemblyResponse.parent])
)[1];
function assemblyAnimate(objectId: Number, coords: InsertionPath, b:boolean) {
const object = scene.getObjectById(objectId as number);
const r = 1
object?.position.set(coords.xyz[0] * r, coords.xyz[1] * r, coords.xyz[2] * r);
object?.setRotationFromQuaternion(
new Quaternion(
coords.quadrelion[0],
coords.quadrelion[1],
coords.quadrelion[2],
coords.quadrelion[3]
)
);
console.log(object?.position)
}
function timer(ms: number) {
return new Promise((res) => setTimeout(res, ms));
}
const b = true
async function load(id: Number, len: number) {
for (var i = 0; i < len; i++) {
assemblyAnimate(objectControl, assemblyResponse.insertions.insertion_path[i], b);
await timer(3);
}
}
assemblyResponse.insertions.insertion_path = assemblyResponse.insertions.insertion_path.reverse()
load(objectControl, assemblyResponse.insertions.insertion_path.length);
}
async function click() {
renderId = renderId + 1;
if (assemblyCounter === renderId) {
renderId = 1;
}
scene.clear();
renderObject(renderId, params!);
}
async function loadObject(objectList: string[]): Promise<Number[]> {
const promises: Array<Promise<Group>> = [];
objectList.forEach((e) => {
const fbxLoader = new OBJLoader();
promises.push(fbxLoader.loadAsync(e));
});
const objects = await Promise.all(promises);
const result: Array<Number> = [];
for (let i = 0; objects.length > i; i++) {
const el = objects[i];
container.add(el);
scene.add(container);
result.push(el.id);
const directionalLight = new DirectionalLight(0xffffff, 0.2);
directionalLight.castShadow = true;
directionalLight.position.set(container.position.x - 10,container.position.y - 10,container.position.z - 10);
scene.add(directionalLight);
container.position.set(0, 0, 0);
fitCameraToCenteredObject(camera, container);
}
return result;
}
function fitCameraToCenteredObject(
camera: PerspectiveCamera,
object: Object3D
) {
const dist = 20;
const vector = new Vector3();
camera.getWorldDirection(vector);
vector.multiplyScalar(dist);
vector.add(camera.position);
object.position.set(vector.x, vector.y, vector.z);
object.setRotationFromQuaternion(camera.quaternion);
}
return (
<>
<div className="loader">
<div onClick={() => click()}>next</div>
<canvas style={canvasStyle} ref={canvasRef} />
</div>
</>
);
}

View file

@ -1,141 +0,0 @@
import React, { useEffect } from "react";
import {
DirectionalLight,
Object3D,
PerspectiveCamera,
Scene,
WebGLRenderer,
AmbientLight,
Vector3,
} from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import { OBJLoader } from "three/examples/jsm/loaders/OBJLoader";
import CSS from "csstype";
import { useParams } from "react-router-dom";
import { HttpMethod, HttpRepository, HttpRoute } from "../../core/repository/http_repository";
const canvasStyle: CSS.Properties = {
backgroundColor: "rgb(151 41 41 / 85%)",
};
export interface AssemblyPreviewStructure {
assembly: string[];
offset: number;
count: number;
}
export const AssemblyPreviewSubsequencePath = "/123/";
export const AssemblyPreviewSubsequence = () => {
const container = new Object3D();
const canvasRef = React.useRef<HTMLCanvasElement>(null);
const scene = new Scene();
const camera = new PerspectiveCamera(
80,
window.innerWidth / window.innerHeight,
0.1,
1000
);
let renderId = 1;
let assemblyCounter: undefined | Number = undefined;
let params = useParams().id;
useEffect(() => {
const renderer = new WebGLRenderer({
canvas: canvasRef.current as HTMLCanvasElement,
antialias: true,
alpha: true,
});
camera.position.set(2, 1, 2);
const directionalLight = new DirectionalLight(0xffffff, 0.2);
directionalLight.castShadow = true;
directionalLight.position.set(-1, 2, 4);
scene.add(directionalLight);
const ambientLight = new AmbientLight(0xffffff, 0.7);
scene.add(ambientLight);
container.position.set(0, 0, 0);
renderer.setSize(window.innerWidth, window.innerHeight);
const onResize = () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer!.setSize(window.innerWidth, window.innerHeight);
};
window.addEventListener("resize", onResize, false);
new OrbitControls(camera, renderer.domElement);
renderer!.setAnimationLoop(() => {
renderer!.render(scene, camera);
});
renderObject(1, params!);
} );
async function renderObject(renderId: Number,projectId:string ) {
const assemblyResponse =
await HttpRepository.jsonRequest<AssemblyPreviewStructure>(
HttpMethod.GET,
`${HttpRoute.assemblyPreviewPath}${projectId}?count=${renderId}`
);
assemblyCounter = assemblyResponse.count;
loadObject(assemblyResponse.assembly);
}
async function click() {
renderId = renderId + 1;
console.log(assemblyCounter);
console.log(renderId);
if (assemblyCounter === renderId) {
renderId = 1;
}
renderObject(renderId, params!);
}
function loadObject(objectList: string[]) {
objectList.forEach((el) => {
const fbxLoader = new OBJLoader();
fbxLoader.load(
el,
(object) => {
object.scale.x = 0.3;
object.scale.y = 0.3;
object.scale.z = 0.3;
object.rotation.x = -Math.PI / 2;
object.position.y = -30;
container.add(object);
scene.add(container);
fitCameraToCenteredObject(camera, container);
},
(xhr) => {
console.log((xhr.loaded / xhr.total) * 100 + "% loaded");
},
(error) => {
console.log(error);
}
);
});
}
function fitCameraToCenteredObject(
camera: PerspectiveCamera,
object: Object3D
) {
const dist = 50;
const vector = new Vector3();
camera.getWorldDirection(vector);
vector.multiplyScalar(dist);
vector.add(camera.position);
object.position.set(vector.x, vector.y, vector.z);
object.setRotationFromQuaternion(camera.quaternion);
}
return <canvas onClick={() => click()} style={canvasStyle} ref={canvasRef} />;
};

View file

@ -1,72 +0,0 @@
import { Spin, Typography } from "antd";
import * as React from "react";
import { useNavigate } from "react-router-dom";
import {
HttpMethod,
HttpRepository,
HttpRoute,
} from "../../core/repository/http_repository";
import { pathStabilityScreen } from "../stability_preview/stability_preview";
const { Title } = Typography;
export const createProjectRoute = "/new_project";
const UploadButton = () => {
const navigate = useNavigate();
const [isLoading, setLoading] = React.useState<boolean>(false);
const handleImageChange = function (e: React.ChangeEvent<HTMLInputElement>) {
const fileList = e.target.files;
if (!fileList) return;
let file = fileList[0] as File;
uploadFile(file);
};
const uploadFile = async (file: File) => {
if (file) {
const formData = new FormData();
formData.append("freecad", file, file.name);
setLoading(true);
await HttpRepository.request(
HttpMethod.POST,
HttpRoute.createProject,
formData
);
setLoading(false);
navigate(pathStabilityScreen)
}
};
return isLoading ? (
<>
<Spin />
</>
) : (
<label htmlFor="photo">
<input
accept="*/.FCStd"
style={{ display: "none" }}
id="photo"
name="photo"
type="file"
multiple={false}
onChange={handleImageChange}
/>
Choose Cad file
</label>
);
};
export default function CreateProject() {
return (
<div className="centeredContainer">
<div className="centeredDiv">
<Title>Create new project</Title>
</div>
<div style={{ paddingTop: "10px" }}>
<UploadButton />
</div>
</div>
);
}

View file

@ -1,57 +0,0 @@
import { Button } from 'antd';
import * as React from 'react';
import { useParams } from 'react-router-dom';
import { HttpRepository, HttpMethod, HttpRoute } from '../../core/repository/http_repository';
export const pathStabilityScreen = '/stability/preview/usecase/'
interface IStabilityCheckResponce {
status: "rejected" | "fulfilled";
value: undefined | string;
index: number;
}
interface IStability {
status: boolean;
detail: string;
}
export const StabilityPreviewScreen: React.FunctionComponent = () => {
const id = useParams().id
const [stabilityResult, setStability] = React.useState<IStability[] | null>(null);
React.useEffect(() => {
const stabilityCheck = async () => {
const result = await HttpRepository.jsonRequest<Array<string>>(HttpMethod.GET, '/' + id + '/generation/step-structure.json')
const promises = []
for (let i = 0; i !== result.length; i++) {
const stabilitySubId = i + 1
promises.push(HttpRepository.jsonRequest<Array<string>>(HttpMethod.GET, '/' + id + '/generation/stability/' + stabilitySubId + '/geometry.json'))
}
const stabilityCheck = await (await Promise.allSettled(promises)).map<IStability>((element, index) => {
return {
status: element.status === 'fulfilled' ? true : false,
detail: result[index],
}
})
setStability(stabilityCheck)
};
stabilityCheck()
}, []);
return (<div>
{stabilityResult != null ? (<>
{stabilityResult.map((el, index) => {
return (<div><div>{el.detail}</div> <div>{el.status ? (<>Sucses</>) : (<><Button onClick={async () => {
await HttpRepository.jsonRequest(HttpMethod.POST, '/assembly/stability/write/computed', {
"id": id,
"buildNumber": (index + 1).toString()
})
}}>need input </Button></>)}</div> </div>)
})}
</>) : (<div>loading</div>)}
</div>);
};

View file

@ -1,48 +0,0 @@
import * as React from 'react';
import { useParams } from 'react-router-dom';
import { HttpRepository, HttpMethod, HttpRoute } from '../../core/repository/http_repository';
export const pathAjaxTopologyScreen = '/topology/adjax/usecase/'
export interface IAdjaxMatrix {
allParts: string[];
firstDetail: string;
matrix: StringMap;
matrixError: StringMap | null;
}
interface StringMap { [key: string]: string; }
export const MatrixTopologyAdjaxScreen: React.FunctionComponent = () => {
const [matrix, setMatrix] = React.useState<IAdjaxMatrix | null>(null);
const param = useParams().id
React.useEffect(() => {
async function fetchData() {
setMatrix(
await HttpRepository.jsonRequest<IAdjaxMatrix>(
HttpMethod.GET,
'/' + param + '/' + HttpRoute.ajaxMatrix
)
);
}
fetchData();
}, []);
return (<div>
{matrix === null ? (<>loaded</>) : (<>
{matrix.matrixError != null ? (<>
{Object.keys(matrix.matrixError).map((keyName, i) => {
const m = matrix.matrixError as StringMap;
return (
<div key={i}>
<div>{m[keyName]}</div>
</div>
)
})}
</>) : (<>Success</>)}
</>)}
</div>);
};

View file

@ -1,14 +0,0 @@
/// <reference types="react-scripts" />
import { resources, defaultNS } from './i18n';
declare module 'i18next' {
interface CustomTypeOptions {
defaultNS: typeof defaultNS;
resources: typeof resources['en'];
}
}
declare module "*.svg" {
import { ReactElement, SVGProps } from "react";
const content: (props: SVGProps<SVGElement>) => ReactElement;
export default content;
}

View file

@ -1,13 +0,0 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}

View file

@ -1,50 +0,0 @@
import { render } from "react-dom";
import "./App.css";
import "./index.css";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import {
AssemblyPreviewInsertVector,
AssemblyPreviewInsertVectorPath,
} from "./features/assembly_preview_insert_vector/Assembly_preview_insert_vector_screen";
import {
ProjectScreen,
ProjectsPath,
} from "./features/all_project/all_project_screen";
import {
AssemblyPreviewSubsequence,
AssemblyPreviewSubsequencePath,
} from "./features/assembly_preview_subsequence/assembly_preview_subsequence_screen";
import CreateProject, { createProjectRoute } from "./features/create_project/create_project";
import { pathAjaxTopologyScreen, MatrixTopologyAdjaxScreen } from "./features/topology_ajax_preview/topology_ajax_preview";
import { pathStabilityScreen, StabilityPreviewScreen } from "./features/stability_preview/stability_preview";
const rootElement = document.getElementById("root");
const router = createBrowserRouter([
{
path: ProjectsPath,
element: <ProjectScreen />,
},
{
path:createProjectRoute,
element:<CreateProject/>
},
{
path: AssemblyPreviewSubsequencePath + ":id",
element: <AssemblyPreviewSubsequence />,
},
{
path: AssemblyPreviewInsertVectorPath + ":id",
element: <AssemblyPreviewInsertVector />,
},
{
path: pathAjaxTopologyScreen + ":id",
element:<MatrixTopologyAdjaxScreen/>
},
{
path: pathStabilityScreen + ':id',
element:<StabilityPreviewScreen/>
}
]);
render(<RouterProvider router={router} />, rootElement);

View file

@ -1,15 +0,0 @@
import { ReportHandler } from 'web-vitals';
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;

View file

@ -1,27 +0,0 @@
{
"compilerOptions": {
"target": "ES6",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
]
}

File diff suppressed because it is too large Load diff

View file

@ -1,13 +0,0 @@
from enum import Enum
class FilesGenerator(Enum):
DETAIL = 'detail.json'
ASSEMBLY = 'assembly.json'
class FolderGenerator(Enum):
MESHES = 'meshes'
ASSETS = 'assets'
SDF = 'sdf'
ASSEMBlY = 'assembly'

View file

@ -1,86 +0,0 @@
from typing import Any, TypeVar, Type, cast
T = TypeVar("T")
def from_float(x: Any) -> float:
assert isinstance(x, (float, int)) and not isinstance(x, bool)
return float(x)
def to_float(x: Any) -> float:
assert isinstance(x, float)
return x
def to_class(c: Type[T], x: Any) -> dict:
assert isinstance(x, c)
return cast(Any, x).to_dict()
class Axis:
x: float
y: float
z: float
def __init__(self, x: float, y: float, z: float) -> None:
self.x = x
self.y = y
self.z = z
@staticmethod
def from_dict(obj: Any) -> 'Axis':
assert isinstance(obj, dict)
x = from_float(obj.get("x"))
y = from_float(obj.get("y"))
z = from_float(obj.get("z"))
return Axis(x, y, z)
def to_dict(self) -> dict:
result: dict = {}
result["x"] = to_float(self.x)
result["y"] = to_float(self.y)
result["z"] = to_float(self.z)
return result
class GeometryPart:
euler: Axis
position: Axis
rotation: Axis
center: Axis
def __init__(self, euler: Axis, position: Axis, rotation: Axis, center: Axis) -> None:
self.euler = euler
self.position = position
self.rotation = rotation
self.center = center
@staticmethod
def from_dict(obj: Any) -> 'GeometryPart':
assert isinstance(obj, dict)
euler = Axis.from_dict(obj.get("euler"))
position = Axis.from_dict(obj.get("position"))
rotation = Axis.from_dict(obj.get("rotation"))
center = Axis.from_dict(obj.get("center"))
return GeometryPart(euler, position, rotation, center)
def to_dict(self) -> dict:
result: dict = {}
result["euler"] = to_class(Axis, self.euler)
result["position"] = to_class(Axis, self.position)
result["rotation"] = to_class(Axis, self.rotation)
result["center"] = to_class(Axis, self.center)
return result
def toJson(self) -> str:
return str(self.to_dict()).replace('\'', '"')
def geometry_part_from_dict(s: Any) -> GeometryPart:
return GeometryPart.from_dict(s)
def geometry_part_to_dict(x: GeometryPart) -> Any:
return to_class(GeometryPart, x)

View file

@ -1,32 +0,0 @@
import FreeCAD as App
import uuid
import Mesh
import Part
# import PartGui
import MeshPart
class MeshPartModel:
id = None
mesh = None
def __init__(self, part) -> None:
try:
from random import randrange
self.id = 'mesh' + str(randrange(1000000))
document = App.ActiveDocument
mesh = document.addObject("Mesh::Feature", self.id)
shape = Part.getShape(part, "")
mesh.Mesh = MeshPart.meshFromShape(
Shape=shape, LinearDeflection=20, AngularDeflection=0.1, Relative=False)
mesh.Label = self.id
self.mesh = mesh
except Exception as e:
print(e)
pass
def remove(self):
try:
App.ActiveDocument.removeObject(self.mesh.Label)
except Exception as e:
print(e)

View file

@ -1,158 +0,0 @@
import json
def from_str(x):
assert isinstance(x, str)
return x
def from_none(x):
assert x is None
return x
def from_union(fs, x):
for f in fs:
try:
return f(x)
except:
pass
assert False
def to_class(c, x):
assert isinstance(x, c)
return x.to_dict()
class SdfGeometryModel:
def __init__(
self,
name,
ixx,
ixy,
ixz,
iyy,
izz,
massSDF,
posX,
posY,
posZ,
eulerX,
eulerY,
eulerZ,
iyz,
stl,
friction,
centerMassX,
centerMassY,
centerMassZ,
):
self.name = name
self.ixx = ixx
self.ixy = ixy
self.ixz = ixz
self.iyy = iyy
self.izz = izz
self.massSDF = massSDF
self.posX = posX
self.posY = posY
self.posZ = posZ
self.eulerX = eulerX
self.eulerY = eulerY
self.eulerZ = eulerZ
self.iyz = iyz
self.stl = stl
self.friction = friction
self.centerMassX = centerMassX
self.centerMassY = centerMassY
self.centerMassZ = centerMassZ
@staticmethod
def from_dict(obj):
assert isinstance(obj, dict)
name = from_union([from_str, from_none], obj.get("name"))
ixx = from_union([from_str, from_none], obj.get("ixx"))
ixy = from_union([from_str, from_none], obj.get("ixy"))
ixz = from_union([from_str, from_none], obj.get("ixz"))
iyy = from_union([from_str, from_none], obj.get("iyy"))
izz = from_union([from_str, from_none], obj.get("izz"))
massSDF = from_union([from_str, from_none], obj.get("massSDF"))
posX = from_union([from_str, from_none], obj.get("posX"))
posY = from_union([from_str, from_none], obj.get("posY"))
posZ = from_union([from_str, from_none], obj.get("posZ"))
eulerX = from_union([from_str, from_none], obj.get("eulerX"))
eulerY = from_union([from_str, from_none], obj.get("eulerY"))
eulerZ = from_union([from_str, from_none], obj.get("eulerZ"))
iyz = from_union([from_str, from_none], obj.get("iyz"))
stl = from_union([from_str, from_none], obj.get("stl"))
friction = from_union([from_str, from_none], obj.get("friction"))
centerMassX = from_union([from_str, from_none], obj.get("centerMassX"))
centerMassY = from_union([from_str, from_none], obj.get("centerMassY"))
centerMassZ = from_union([from_str, from_none], obj.get("centerMassZ"))
return SdfGeometryModel(
name,
ixx,
ixy,
ixz,
iyy,
izz,
massSDF,
posX,
posY,
posZ,
eulerX,
eulerY,
eulerZ,
iyz,
stl,
friction,
centerMassX,
centerMassY,
centerMassZ,
)
def to_dict(self):
result = {}
if self.name is not None:
result["name"] = from_union([from_str, from_none], self.name)
if self.ixx is not None:
result["ixx"] = from_union([from_str, from_none], self.ixx)
if self.ixy is not None:
result["ixy"] = from_union([from_str, from_none], self.ixy)
if self.ixz is not None:
result["ixz"] = from_union([from_str, from_none], self.ixz)
if self.iyy is not None:
result["iyy"] = from_union([from_str, from_none], self.iyy)
if self.izz is not None:
result["izz"] = from_union([from_str, from_none], self.izz)
if self.massSDF is not None:
result["massSDF"] = from_union([from_str, from_none], self.massSDF)
if self.posX is not None:
result["posX"] = from_union([from_str, from_none], self.posX)
if self.posY is not None:
result["posY"] = from_union([from_str, from_none], self.posY)
if self.posZ is not None:
result["posZ"] = from_union([from_str, from_none], self.posZ)
if self.eulerX is not None:
result["eulerX"] = from_union([from_str, from_none], self.eulerX)
if self.eulerY is not None:
result["eulerY"] = from_union([from_str, from_none], self.eulerY)
if self.eulerZ is not None:
result["eulerZ"] = from_union([from_str, from_none], self.eulerZ)
if self.iyz is not None:
result["iyz"] = from_union([from_str, from_none], self.iyz)
if self.stl is not None:
result["stl"] = from_union([from_str, from_none], self.stl)
if self.friction is not None:
result["friction"] = from_union([from_str, from_none], self.eulerZ)
if self.centerMassX is not None:
result["centerMassX"] = from_union([from_str, from_none], self.centerMassX)
if self.centerMassY is not None:
result["centerMassY"] = from_union([from_str, from_none], self.centerMassY)
if self.centerMassZ is not None:
result["centerMassZ"] = from_union([from_str, from_none], self.centerMassZ)
return result
def toJSON(self) -> str:
return str(self.to_dict()).replace("'", '"')

View file

@ -1,30 +0,0 @@
import FreeCAD as App
import Part
class SimpleCopyPartModel:
id = None
copyLink = None
label = None
part = None
def getPart(self):
return self.part
def __init__(self, part) -> None:
try:
from random import randrange
self.id = str(randrange(1000000))
childObj = part
__shape = Part.getShape(
childObj, '', needSubElement=False, refine=False)
obj = App.ActiveDocument.addObject('Part::Feature', self.id)
obj.Shape = __shape
self.part = obj
self.label = obj.Label
App.ActiveDocument.recompute()
except Exception as e:
print(e)
def remove(self):
App.ActiveDocument.removeObject(self.label)

View file

@ -1,2 +0,0 @@
# -*- coding: utf-8 -*-
# to keep this module importable

View file

@ -1,3 +0,0 @@
## cg.blender
Модули проекта Robossembler для Blender

View file

@ -1,5 +0,0 @@
# -*- coding: utf-8 -*-
"""
DESCRIPTION.
Blender modules for Robosembler project pipeline.
"""

View file

@ -1,20 +0,0 @@
## cg.blender.export
Модули экспорта для Blender
Все модули экспорта работают через декоратор `export_decorator`.
Его задача, чтоб экспорт был пообъектным, каждый объект в своем отдельном файле с именем объекта.
### fbx.py
Экспорт midpoly с оптимизированными параметрами для high end движков.
### dae.py
Экспорт lowpoly с оптимизированными параметрами для opengl-2 движков.
### stl.py
Экспорт lowpoly с оптимизированными параметрами для объекта коллизии.
### Остальные модули - DEPRECATED

View file

@ -1,56 +0,0 @@
# coding: utf-8
# Copyright (C) 2023 Ilia Kurochkin <brothermechanic@yandex.com>
#
# 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.
'''
DESCRIPTION.
Decorator for export functions.
'''
import logging
import os
import bpy
import mathutils
logger = logging.getLogger(__name__)
def export_decorator(func):
def wrapper(**kwargs):
bpy.ops.object.select_all(action='DESELECT')
# add defaults
kwargs.setdefault('global_scale', 1000)
kwargs.setdefault('axis_forward', 'Y')
kwargs.setdefault('axis_up', 'Z')
kwargs.setdefault('path', '//')
kwargs.setdefault('subdir', '')
obj = bpy.data.objects.get(kwargs['obj_name'])
# deselect all but just one object and make it active
bpy.ops.object.select_all(action='DESELECT')
obj.select_set(state=True)
bpy.context.view_layer.objects.active = obj
# clean hierarchy and transforms
obj.parent = None
# reset transforms
obj.matrix_world = mathutils.Matrix()
# construct path
filename = bpy.context.active_object.name
filepath = os.path.join(kwargs['path'],
kwargs['subdir']).replace('\\', '/')
if not os.path.isdir(filepath):
os.makedirs(filepath)
# store path
kwargs['outpath'] = os.path.join(filepath, filename)
# return export function
return func(**kwargs)
return wrapper

View file

@ -1,41 +0,0 @@
# -*- coding: utf-8 -*-
"""
DESCRIPTION.
STL mesh exporter.
Exports all objects in scene.
You can set export path and subdir.
"""
__version__ = "0.1"
import logging
import sys
import bpy
import os
logger = logging.getLogger(__name__)
def export_col_stl(path, subdir=""):
""" STL mesh exporter. Exports all objects in scene. """
for ob in bpy.context.scene.objects:
# deselect all but just one object and make it active
bpy.ops.object.select_all(action='DESELECT')
ob.select_set(state=True)
bpy.context.view_layer.objects.active = ob
filename = bpy.context.active_object.name
# create collision hull mesh
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.mesh.convex_hull()
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.modifier_add(type='DECIMATE')
bpy.context.object.modifiers["Decimate"].ratio = 0.2
# export stl
stl_path = os.path.join(path, subdir).replace('\\', '/')
if not os.path.isdir(stl_path):
os.makedirs(stl_path)
outpath = os.path.join(stl_path, filename+'.stl')
logger.debug('collision:', outpath)
bpy.ops.export_mesh.stl(filepath=outpath, check_existing=False, filter_glob='*.stl', use_selection=True, global_scale=1.0, use_scene_unit=False, ascii=False, use_mesh_modifiers=True, batch_mode='OFF', axis_forward='Y', axis_up='Z')

View file

@ -1,62 +0,0 @@
# coding: utf-8
# Copyright (C) 2023 Ilia Kurochkin <brothermechanic@yandex.com>
#
# 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.
'''
DESCRIPTION.
Collada mesh exporter.
'''
__version__ = "0.2"
import bpy
from blender.export import export_decorator
@export_decorator
def export_dae(**kwargs):
outpath = ('{}.dae'.format(kwargs['outpath']))
bpy.ops.wm.collada_export(
filepath=outpath,
check_existing=False,
apply_modifiers=True,
export_mesh_type=0,
export_mesh_type_selection='view',
export_global_forward_selection=kwargs['axis_forward'],
export_global_up_selection=kwargs['axis_up'],
apply_global_orientation=False,
selected=True,
include_children=False,
include_armatures=False,
include_shapekeys=False,
deform_bones_only=False,
include_animations=False,
include_all_actions=True,
export_animation_type_selection='sample',
sampling_rate=1,
keep_smooth_curves=False,
keep_keyframes=False,
keep_flat_curves=False,
active_uv_only=False,
use_texture_copies=True,
triangulate=True,
use_object_instantiation=True,
use_blender_profile=True,
sort_by_name=False,
export_object_transformation_type=0,
export_object_transformation_type_selection='matrix',
export_animation_transformation_type=0,
export_animation_transformation_type_selection='matrix',
open_sim=False,
limit_precision=False,
keep_bind_info=False)
return outpath

View file

@ -1,69 +0,0 @@
# coding: utf-8
# Copyright (C) 2023 Ilia Kurochkin <brothermechanic@yandex.com>
#
# 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.
'''
DESCRIPTION.
FBX mesh exporter.
'''
__version__ = "0.1"
import bpy
from blender.export import export_decorator
@export_decorator
def export_fbx(**kwargs):
outpath = ('{}.fbx'.format(kwargs['outpath']))
bpy.ops.export_scene.fbx(
filepath=outpath,
check_existing=False,
filter_glob="*.fbx",
use_selection=True,
use_visible=False,
use_active_collection=False,
global_scale=1,
apply_unit_scale=True,
apply_scale_options='FBX_SCALE_NONE',
use_space_transform=True,
bake_space_transform=False,
object_types={'MESH'},
use_mesh_modifiers=True,
use_mesh_modifiers_render=True,
mesh_smooth_type='FACE',
colors_type='SRGB',
use_subsurf=False,
use_mesh_edges=False,
use_tspace=False,
use_triangles=True,
use_custom_props=False,
add_leaf_bones=True,
primary_bone_axis='Y',
secondary_bone_axis='X',
use_armature_deform_only=False,
armature_nodetype='NULL',
bake_anim=False,
bake_anim_use_all_bones=True,
bake_anim_use_nla_strips=True,
bake_anim_use_all_actions=True,
bake_anim_force_startend_keying=True,
bake_anim_step=1,
bake_anim_simplify_factor=1,
path_mode='AUTO',
embed_textures=False,
batch_mode='OFF',
use_batch_own_dir=True,
use_metadata=True,
axis_forward='-Z',
axis_up='Y')
return outpath

View file

@ -1,36 +0,0 @@
# -*- coding: utf-8 -*-
"""
DESCRIPTION.
OBJ mesh exporter.
Exports all objects in scene.
You can set export path and subdir.
DEPRECATED
"""
__version__ = "0.2"
import logging
import bpy
import os
logger = logging.getLogger(__name__)
def export_obj(path, subdir="", filename=None):
""" OBJ mesh exporter. Exports all objects in scene. """
for ob in bpy.context.scene.objects:
# deselect all but just one object and make it active
bpy.ops.object.select_all(action='DESELECT')
ob.select_set(state=True)
bpy.context.view_layer.objects.active = ob
if not filename:
filename = bpy.context.active_object.name
if not filename.endswith('.obj'):
filename = (filename + '.obj')
# export obj
obj_path = os.path.join(path, subdir).replace('\\', '/')
if not os.path.isdir(obj_path):
os.makedirs(obj_path)
outpath = os.path.join(obj_path, filename)
logger.debug('Exporting to %s', outpath)
return bpy.ops.wm.obj_export(filepath=outpath, forward_axis='Y', up_axis='Z', global_scale=1000, apply_modifiers=True, export_selected_objects=True, export_uv=True, export_normals=True, export_colors=False, export_materials=True, export_pbr_extensions=False, path_mode='AUTO', export_triangulated_mesh=True)

View file

@ -1,40 +0,0 @@
# coding: utf-8
# Copyright (C) 2023 Ilia Kurochkin <brothermechanic@yandex.com>
#
# 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.
'''
DESCRIPTION.
PLY mesh exporter.
'''
__version__ = "0.2"
import bpy
from blender.export import export_decorator
@export_decorator
def export_ply(**kwargs):
outpath = ('{}.ply'.format(kwargs['outpath']))
bpy.ops.export_mesh.ply(filepath=outpath,
check_existing=False,
filter_glob="*.ply",
use_ascii=True,
use_selection=True,
use_mesh_modifiers=True,
use_normals=True,
use_uv_coords=True,
use_colors=True,
global_scale=kwargs['global_scale'],
axis_forward=kwargs['axis_forward'],
axis_up=kwargs['axis_up'])
return outpath

View file

@ -1,39 +0,0 @@
# coding: utf-8
# Copyright (C) 2023 Ilia Kurochkin <brothermechanic@yandex.com>
#
# 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.
'''
DESCRIPTION.
STL mesh exporter.
'''
__version__ = "0.2"
import bpy
from blender.export import export_decorator
@export_decorator
def export_stl(**kwargs):
outpath = ('{}.stl'.format(kwargs['outpath']))
bpy.ops.export_mesh.stl(filepath=outpath,
check_existing=False,
filter_glob='*.stl',
use_selection=True,
global_scale=kwargs['global_scale'],
use_scene_unit=False,
ascii=False,
use_mesh_modifiers=True,
batch_mode='OFF',
axis_forward=kwargs['axis_forward'],
axis_up=kwargs['axis_up'])
return outpath

View file

@ -1,20 +0,0 @@
## cg.blender.import_cad
Формирование Bledner сцены по данным FreeCAD сцены.
### build_blender_scene.py
- Восстанавливает из JSON словаря Bledner сцену.
- Задает имена mesh объектов на основе solid объектов.
- Импортирует локальные координаты и задает их mesh объектам.
- Импортирует FEM материалы (если они есть) и задает их mesh объектам.
### import_hierarchy.py
- Восстанавливает иерархию объектов.
### import_materials.py
- Восстанавливает материалы объектов.
### Остальные модули - DEPRECATED

View file

@ -1,6 +0,0 @@
# -*- coding: utf-8 -*-
'''
DESCRIPTION.
Generate Bledner scene from FreeCAD scene.
'''

View file

@ -1,108 +0,0 @@
# coding: utf-8
# Copyright (C) 2023 Ilia Kurochkin <brothermechanic@yandex.com>
#
# 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.
'''
DESCRIPTION.
- Build Blender scene from JSON data.
- Setup hierarchy.
- Setup materials.
- Setup LCS points.
- Apply Bledner scene transforms.
'''
__version__ = '0.2'
import collections
import logging
import random
import bpy
from blender.utils.object_transforms import apply_transforms
from blender.import_cad.import_hierarchy import (fc_placement,
hierarchy_list)
from blender.import_cad.import_materials import (assign_materials,
assign_black)
logger = logging.getLogger(__name__)
scene_scale = 0.001
blackbody_mat_name = 'Robossembler_Black_Body'
def json_to_blend(js_data):
''' Reads JSON data and creates Blender scene '''
render_collection = bpy.data.collections.new('Render')
bpy.context.scene.collection.children.link(render_collection)
fc_file = list(js_data.keys())[0]
imported_objects = collections.defaultdict(list)
for js_obj in js_data[fc_file]:
bobj = None
if js_data[fc_file][js_obj]['type'] == 'LCS':
if not js_data[fc_file][js_obj].get('Robossembler_SocketFlow'):
# TODO test
logger.info('LCS %s is not defined!', js_obj)
continue
bobj = bpy.data.objects.new(js_obj, None)
bobj.empty_display_type = 'ARROWS'
bobj.empty_display_size = round(random.uniform(0.05, 0.15), 3)
bobj.show_in_front = True
for attr in js_data[fc_file][js_obj].keys():
if 'Robossembler' not in attr:
continue
bobj[attr] = js_data[fc_file][js_obj][attr]
render_collection.objects.link(bobj)
imported_objects['objs_lcs'].append(bobj.name)
elif js_data[fc_file][js_obj]['type'] == 'PART':
if js_data[fc_file][js_obj].get('mesh'):
verts = js_data[fc_file][js_obj]['mesh'][0]
edges = []
faces = js_data[fc_file][js_obj]['mesh'][1]
# create blender object data
bmesh = bpy.data.meshes.new(name=js_obj)
bmesh.from_pydata(verts, edges, faces)
bmesh.update()
bobj = bpy.data.objects.new(js_obj, bmesh)
render_collection.objects.link(bobj)
if bobj:
fc_placement(bobj,
js_data[fc_file][js_obj]['fc_location'],
js_data[fc_file][js_obj]['fc_rotation'],
scene_scale)
if bobj.type == 'MESH':
bobj.scale = (scene_scale, scene_scale, scene_scale)
apply_transforms(bobj, scale=True)
# construct assembly hierarchy
hierarchy_objs = hierarchy_list(
bobj, js_data[fc_file][js_obj]['hierarchy'], scene_scale)
for hierarchy_obj in hierarchy_objs:
render_collection.objects.link(hierarchy_obj)
imported_objects['objs_hierarchy'].append(hierarchy_obj.name)
# one material for the whole object
if bobj.type == 'MESH':
if js_data[fc_file][js_obj].get('material'):
fem_mat = js_data[fc_file][js_obj]['material']
assign_materials(bobj, fem_mat)
imported_objects['objs_foreground'].append(bobj.name)
else:
assign_black(bobj)
imported_objects['objs_background'].append(bobj.name)
logger.info('Generated %s objects without errors',
len(sum(list(imported_objects.values()), [])))
return imported_objects

View file

@ -1,67 +0,0 @@
# coding: utf-8
# Copyright (C) 2023 Ilia Kurochkin <brothermechanic@yandex.com>
#
# 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.
#
'''
DESCRIPTION.
Import from json exported FreeCAD's asm4 coordinates as Blender's empty object.
DEPRECATED
'''
__version__ = '0.2'
import logging
import bpy
import json
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def lcs_json_importer(path_json):
''' Import json LCS as Bledner's Empty object. '''
with open(path_json) as f:
data = json.load(f)
lcs_name = data['label']
lcs_parent_name = data['parent_label']
lcs_pose = data['placement']
loc = tuple(lcs_pose['position'].values())
fori = tuple(lcs_pose['orientation'].values())
bori = (fori[3],)+fori[:3]
if not bpy.data.collections.get('Import LCS'):
lcs_collection = bpy.data.collections.new('Import LCS')
bpy.context.scene.collection.children.link(lcs_collection)
bpy.context.view_layer.active_layer_collection = \
bpy.context.view_layer.layer_collection.children['Import LCS']
else:
lcs_collection = bpy.data.collections['Import LCS']
bpy.ops.object.empty_add(
type='ARROWS', radius=0.1, align='WORLD',
location=(0, 0, 0), rotation=(0, 0, 0))
lcs_obj = bpy.context.active_object # or bpy.context.object
lcs_obj.name = lcs_name
lcs_obj.rotation_mode = 'QUATERNION'
lcs_obj.location = loc
lcs_obj.rotation_quaternion = bori
lcs_obj.rotation_mode = 'XYZ'
lcs_obj.show_in_front = True
if lcs_parent_name:
lcs_obj.parent = bpy.data.objects[lcs_parent_name]
f.close()
logger.info('Point %s imported without errors', lcs_name)
return lcs_obj

View file

@ -1,65 +0,0 @@
# coding: utf-8
# Copyright (C) 2023 Ilia Kurochkin <brothermechanic@yandex.com>
#
# 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.
'''
DESCRIPTION.
Collecting all parents and reconstruct this hierarhy in bledner.
'''
__version__ = '0.3'
import logging
import bpy
from mathutils import Vector
logger = logging.getLogger(__name__)
def fc_placement(bobj, fc_location, fc_rotation, scene_scale):
''' Prepare FreeCAD's Placement and Quaternion for Blender '''
bobj.location = Vector(fc_location) * scene_scale
m = bobj.rotation_mode
bobj.rotation_mode = 'QUATERNION'
# FreeCAD Quaternion is XYZW while Blender is WXYZ
fc_rotation.insert(0, fc_rotation.pop(3))
bobj.rotation_quaternion = fc_rotation
bobj.rotation_mode = m
return bobj
def hierarchy_list(bobj, hierarchy, scene_scale):
''' Blender object, dict, Blender World Scale factor. '''
hierarchy_objs = []
for parent_name in hierarchy.keys():
if bpy.data.objects.get(parent_name):
empty = bpy.data.objects[parent_name]
else:
empty = bpy.data.objects.new(parent_name, None)
empty.empty_display_type = 'CUBE'
empty.empty_display_size = 0.01
fc_placement(empty,
hierarchy[parent_name]['fc_location'],
hierarchy[parent_name]['fc_rotation'],
scene_scale)
empty.select_set(False)
hierarchy_objs.append(empty)
if hierarchy[parent_name]['deep_index'] == 0:
bobj.parent = empty
logger.debug('Add parent %s to object %s', bobj.parent.name, bobj.name)
for parent_name in hierarchy.keys():
parent_parenta_name = hierarchy[parent_name]['parent']
if parent_parenta_name:
bpy.data.objects[parent_name].parent = bpy.data.objects[
parent_parenta_name]
return hierarchy_objs

View file

@ -1,117 +0,0 @@
# coding: utf-8
# Copyright (C) 2023 Ilia Kurochkin <brothermechanic@yandex.com>
#
# 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.
__version__ = '0.3'
import logging
import bpy
from bpy_extras.node_shader_utils import PrincipledBSDFWrapper
from blender.utils.shininess_to_roughness import shiny_to_rough
logger = logging.getLogger(__name__)
blackbody_mat_name = 'Robossembler_Black_Body'
def assign_materials(bobj, fem_mat):
''' Build Blender shader from FreeCAD's FEM material '''
fem_mat_name = fem_mat['Name']
if fem_mat_name in bpy.data.materials:
# prepare for reimport
if len(bobj.material_slots) < 1:
bobj.data.materials.append(bpy.data.materials[fem_mat_name])
else:
bobj.material_slots[0].material = bpy.data.materials[fem_mat_name]
else:
if 'DiffuseColor' in fem_mat.keys():
d_col_str = fem_mat['DiffuseColor']
d_col4 = tuple(map(float, d_col_str[1:-1].split(', ')))
d_col = d_col4[:-1]
else:
d_col = (0.5, 0.5, 0.5)
if 'Father' in fem_mat.keys():
if fem_mat['Father'] == 'Metal':
me = 1
else:
me = 0
else:
me = 0
if 'Shininess' in fem_mat.keys():
shiny = float(fem_mat['Shininess'])
if shiny == 0:
rg = 0.5
else:
rg = shiny_to_rough(shiny)
else:
rg = 0.5
if 'EmissiveColor' in fem_mat.keys():
e_col_str = fem_mat['EmissiveColor']
e_col4 = tuple(map(float, e_col_str[1:-1].split(', ')))
e_col = e_col4[:-1]
else:
e_col = (0.0, 0.0, 0.0)
if 'Transparency' in fem_mat.keys():
tr_str = fem_mat['Transparency']
alpha = 1.0 - float(tr_str)
else:
alpha = 1.0
bmat = bpy.data.materials.new(name=fem_mat_name)
bmat.use_nodes = True
principled = PrincipledBSDFWrapper(bmat, is_readonly=False)
principled.base_color = d_col
principled.metallic = me
principled.roughness = rg
principled.emission_color = e_col
principled.alpha = alpha
bevel = bmat.node_tree.nodes.new(type="ShaderNodeBevel")
bevel.location = -300, -300
bevel.samples = 32
bevel.inputs[0].default_value = 0.001
principled_node = bmat.node_tree.nodes["Principled BSDF"]
bmat.node_tree.links.new(bevel.outputs['Normal'], principled_node.inputs['Normal'])
# prepare for reimport
if len(bobj.material_slots) < 1:
bobj.data.materials.append(bmat)
else:
bobj.material_slots[0].material = bmat
logger.debug('Assign %s to object %s', fem_mat_name, bobj.name)
return bobj
def assign_black(bobj):
''' Set absolute black body shader '''
fem_mat_name = blackbody_mat_name
if fem_mat_name in bpy.data.materials:
# prepare for reimport TODO
if len(bobj.material_slots) < 1:
bobj.data.materials.append(bpy.data.materials[fem_mat_name])
else:
bobj.material_slots[0].material = bpy.data.materials[fem_mat_name]
else:
bmat = bpy.data.materials.new(name=fem_mat_name)
bmat.use_nodes = True
bmat.diffuse_color = (0, 0, 0, 1)
principled = bmat.node_tree.nodes['Principled BSDF']
principled.inputs['Base Color'].default_value = (0, 0, 0, 1)
principled.inputs['Specular IOR Level'].default_value = 0.0
principled.inputs['Roughness'].default_value = 1.0
# prepare for reimport
if len(bobj.material_slots) < 1:
bobj.data.materials.append(bmat)
else:
bobj.material_slots[0].material = bmat
logger.debug('Assign %s to object %s', fem_mat_name, bobj.name)
return bobj

View file

@ -1 +0,0 @@
## Модули импорта для Blender

View file

@ -1,7 +0,0 @@
# -*- coding: utf-8 -*-
"""
DESCRIPTION.
Blender export modules.
Modules exports all objests in scene.
You can set export path and subdir.
"""

View file

@ -1,30 +0,0 @@
# -*- coding: utf-8 -*-
"""
DESCRIPTION.
OBJ mesh importer.
Import files in blender scene.
DEPRECATED
"""
__version__ = "0.2"
import logging
import bpy
import os
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def import_obj(path):
bpy.ops.object.select_all(action='DESELECT')
path = path.replace('\\', '/')
if os.path.isfile(path) and path.endswith('.obj'):
return bpy.ops.wm.obj_import(filepath=path, global_scale=0.001, clamp_size=0, forward_axis='Y', up_axis='Z')
if os.path.isdir(path):
file_list = sorted(os.listdir(path))
obj_list = [dict(name=item) for item in file_list if item.endswith('.obj')]
return bpy.ops.wm.obj_import(directory=path, files=obj_list, global_scale=0.001, clamp_size=0, forward_axis='Y', up_axis='Z')
return logger.info("Path must be a directory or *.obj file!")

View file

@ -1,34 +0,0 @@
## cg.blender.processing
Пакетная обработка всех объектов сцены в Blender
### highpoly_setup.py
- Обработка геометрии, тесселированной во FreeCAD
- Проверка и исправление на сдвоенную геометрию
- Проверка и назначение нормалей точек
- Проверка и назначение острых граней
### restruct_hierarchy_by_lcs.py
- Перестроение иерархии сцены на основе LCS координат и последовательности деталей
- Определение отдельных сборок деталей
- Определение имен сборок деталей
- Определение координат шарниров
- Универсальный алгоритм
### midpoly_setup.py
- Генерация объекта из коллекции объектов
### lowpoly_setup.py
- Генерация замкнутой поверхности из составного объекта
- Ретопология замкнутой поверхности
- Исправление артефактов на замкнутой поверхности
- Назначение нормалей точек замкнутой поверхности
- Назначение острых граней замкнутой поверхности
### uv_setup.py
- Генерация и упаковка развертки 3д объекта

View file

@ -1,5 +0,0 @@
# coding: utf-8
'''
DESCRIPTION.
Mesh processing for asset creation pipeline.
'''

View file

@ -1,69 +0,0 @@
# coding: utf-8
# Copyright (C) 2023 Ilia Kurochkin <brothermechanic@yandex.com>
#
# 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.
'''
DESCRIPTION.
Generte object from collection of objects.
'''
# DEPRECATED
__version__ = '0.1'
import logging
import bpy
import math
from blender.utils.object_relations import parenting
from blender.utils.collection_tools import remove_collections_with_objects
from blender.utils.mesh_tools import collect_less_volume_objs
logger = logging.getLogger(__name__)
def hightpoly_collections_to_midpoly(collection_name, part_names, **cg_config):
''' Convert part's collecttions to single objects. '''
logger.info('Midpoly objects creation launched...')
midpoly_obj_names = []
for part_name in part_names:
midpoly_name = '_'.join((part_name, cg_config['midpoly']))
midpoly_mesh = bpy.data.meshes.new(midpoly_name)
midpoly_obj = bpy.data.objects.new(midpoly_name, midpoly_mesh)
bpy.context.view_layer.update()
if bpy.data.objects[part_name].parent:
root_locator = bpy.data.objects[part_name].parent
else:
root_locator = bpy.data.objects[part_name]
midpoly_obj.matrix_world = root_locator.matrix_world.copy()
parenting(root_locator, midpoly_obj)
midpoly_parts_col = bpy.data.collections[collection_name]
midpoly_parts_col.objects.link(midpoly_obj)
for col in midpoly_parts_col.children:
# only for current part
if part_name not in col.name:
continue
bpy.ops.object.select_all(action='DESELECT')
exclude_objs = collect_less_volume_objs(col.objects, min_volume=2.0e-06)
for obj in col.objects:
if obj not in exclude_objs:
obj.select_set(state=True)
midpoly_obj.select_set(state=True)
bpy.context.view_layer.objects.active = midpoly_obj
bpy.ops.object.join()
bpy.ops.object.shade_smooth(use_auto_smooth=True)
break
midpoly_obj_names.append(midpoly_name)
midpoly_parts_col.name = cg_config['midpoly_col_name']
for col in midpoly_parts_col.children:
remove_collections_with_objects(col)
logger.info('Setup of %s midpoly meshes is finished!', len(part_names))
return midpoly_obj_names

View file

@ -1,74 +0,0 @@
# coding: utf-8
# Copyright (C) 2023 Ilia Kurochkin <brothermechanic@yandex.com>
#
# 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.
'''
DESCRIPTION.
Mesh processing for original tesselated assets for render.
'''
__version__ = '0.3'
import logging
import bpy
import math
logger = logging.getLogger(__name__)
def setup_meshes(obj_names, cleanup=False, sharpness=False, shading=False):
''' Setup raw meshes list after importing '''
logger.info('Render assets setup launched...')
fixed_obj_names = []
for obj_name in obj_names:
if not bpy.data.objects.get(obj_name):
continue
obj = bpy.data.objects[obj_name]
bpy.ops.object.select_all(action='DESELECT')
obj.select_set(state=True)
bpy.context.view_layer.objects.active = obj
if cleanup:
# remove doubles
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.mesh.remove_doubles(threshold=0.00001)
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.mesh.select_mode(type='FACE')
bpy.ops.mesh.select_interior_faces()
bpy.ops.mesh.delete(type='FACE')
bpy.ops.object.mode_set(mode='OBJECT')
if sharpness:
# set shaps and unwrap
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.mesh.select_mode(type='EDGE')
bpy.ops.mesh.edges_select_sharp(sharpness=math.radians(12))
bpy.ops.mesh.mark_sharp()
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.uv.smart_project()
bpy.ops.object.mode_set(mode='OBJECT')
if shading:
# fix shading TODO
bpy.ops.object.shade_smooth()
bpy.context.view_layer.objects.active.data.use_auto_smooth = 1
bpy.context.view_layer.objects.active.modifiers.new(type='DECIMATE', name='decimate')
bpy.context.view_layer.objects.active.modifiers['decimate'].decimate_type = 'DISSOLVE'
bpy.context.view_layer.objects.active.modifiers['decimate'].angle_limit = 0.00872665
bpy.context.object.modifiers['decimate'].show_expanded = 0
bpy.context.view_layer.objects.active.modifiers.new(type='TRIANGULATE', name='triangulate')
bpy.context.object.modifiers['triangulate'].keep_custom_normals = 1
bpy.context.object.modifiers['triangulate'].show_expanded = 0
fixed_obj_names.append(obj_name)
return logger.info('Setup of %s meshes is finished!', len(fixed_obj_names))

View file

@ -1,268 +0,0 @@
# coding: utf-8
# Copyright (C) 2023 Ilia Kurochkin <brothermechanic@yandex.com>
#
# 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.
'''
DESCRIPTION.
Reorganization and restructuring of assembly structure.
'''
__version__ = '0.3'
import logging
import bpy
import mathutils
from blender.utils.object_relations import (parenting,
unparenting)
from blender.utils.object_transforms import round_transforms
from blender.utils.collection_tools import unlink_from_collections
logger = logging.getLogger(__name__)
def hierarchy_assembly(lcs_names, parts_sequence):
''' Hierarchy by LCS and Parts Assembling Sequence. '''
# collect scene hierarchy start info
main_locators = [obj for obj in bpy.data.objects if not obj.parent]
lcs_inlet_objects = []
lcs_outlet_objects = []
for lcs_name in lcs_names:
lcs_obj = bpy.data.objects[lcs_name]
if (lcs_obj.get('Robossembler_SocketFlow') == 'inlet'
and lcs_obj.get('Robossembler_DefaultOrigin')
):
lcs_inlet_objects.append(lcs_obj)
else:
lcs_outlet_objects.append(lcs_obj)
if not lcs_inlet_objects:
raise Exception('No LCS Inlet objects found!')
# get main_locator
main_locator = None
for locator in main_locators:
if set(lcs_inlet_objects + lcs_outlet_objects).issubset(
locator.children_recursive
):
main_locator = locator
if not main_locator:
# TODO need checking
return logger.error('CAD root locator should be parent of all LCS!')
# check parts_sequence objects in scene
for part in parts_sequence:
if not bpy.data.objects.get(part):
return logger.error('%s part object not found!', part)
# create root lcs by parts sequence
first_part_obj = bpy.data.objects[parts_sequence[0]]
root_lcs = None
for lcs_inlet in first_part_obj.children:
# drop non lcs objs
if lcs_inlet.name not in lcs_names:
continue
# drop non DefaultOrigins
lcs_obj = bpy.data.objects[lcs_name]
if not (lcs_obj.get('Robossembler_SocketFlow') == 'inlet'
and lcs_obj.get('Robossembler_DefaultOrigin')
):
continue
root_lcs_name = 'root'
root_lcs = bpy.data.objects.new(root_lcs_name, None)
root_lcs.empty_display_type = 'ARROWS'
root_lcs.empty_display_size = 0.15
root_lcs.show_in_front = True
root_lcs.location = lcs_inlet.location
root_lcs.rotation_euler = lcs_inlet.rotation_euler
root_lcs.parent = lcs_inlet.parent
bpy.context.scene.collection.objects.link(root_lcs)
logger.info('Root Inlet LCS object created!')
unparenting(root_lcs)
round_transforms(root_lcs)
parenting(root_lcs, main_locator)
# retree_by lcs
for lcs_inlet_obj in lcs_inlet_objects:
# lcs inlet as main parent
parent_locator = lcs_inlet_obj.parent
if not parent_locator:
raise Exception('LCS %s should have a parent!', lcs_inlet_obj.name)
unparenting(lcs_inlet_obj)
round_transforms(lcs_inlet_obj)
if parent_locator:
if parent_locator.parent:
unparenting(parent_locator)
parenting(lcs_inlet_obj, parent_locator)
parenting(root_lcs, lcs_inlet_obj)
# lcs outlet parent to lcs inlet
for lcs_outlet_obj in lcs_inlet_obj.children_recursive:
if lcs_outlet_obj.name not in lcs_names:
continue
unparenting(lcs_outlet_obj)
round_transforms(lcs_outlet_obj)
parenting(lcs_inlet_obj, lcs_outlet_obj)
# reset transforms for root_lcs
root_lcs.matrix_world = mathutils.Matrix()
# lcs collections
part_names = []
for lcs_inlet_obj in root_lcs.children:
# remove unmarked parts
if lcs_inlet_obj not in lcs_inlet_objects:
for obj in lcs_inlet_obj.children_recursive:
bpy.data.objects.remove(obj, do_unlink=True)
bpy.data.objects.remove(lcs_inlet_obj, do_unlink=True)
continue
# collect part names
part_name = None
for locator in lcs_inlet_obj.children:
if locator in lcs_outlet_objects:
continue
part_name = locator.name
part_names.append(part_name)
# pack parts to collections
part_col = bpy.data.collections.new(f'{part_name}')
bpy.data.collections['Render'].children.link(part_col)
for obj in lcs_inlet_obj.children_recursive:
unlink_from_collections(obj)
part_col.objects.link(obj)
unlink_from_collections(lcs_inlet_obj)
part_col.objects.link(lcs_inlet_obj)
# TODO DEPRECATED
"""
# parts assembling
for idx, part_name in enumerate(parts_sequence):
# TODO clones for clones
if part_name not in part_names:
continue
lcs_inlet_obj = bpy.data.objects[part_name].parent
constraint = lcs_inlet_obj.constraints.new(type='COPY_TRANSFORMS')
# drop first_part_obj
if idx == 0:
constraint.target = root_lcs
continue
# if asm pair exists
part_before = bpy.data.objects.get(parts_sequence[idx - 1])
if part_before:
lcs_outlet_objs = [
lcs_out
for lcs_out in part_before.parent.children
if lcs_out in lcs_outlet_objects]
if lcs_outlet_objs:
constraint.target = lcs_outlet_objs[0]
else:
constraint.target = root_lcs
constraint.enabled = False
# for reset transforms when exporting
for lcs in lcs_outlet_objects:
constraint = lcs.constraints.new(type='COPY_TRANSFORMS')
constraint.target = root_lcs
constraint.enabled = False
"""
logger.info('Restructuring assembly pipeline finished!')
return part_names
def hierarchy_separated_parts(lcs_names):
''' Restructuring pipeline as separated parts. '''
# collect scene hierarchy start info
lcs_inlet_objects = []
lcs_outlet_objects = []
for lcs_name in lcs_names:
lcs_obj = bpy.data.objects[lcs_name]
if (lcs_obj.get('Robossembler_SocketFlow') == 'inlet'
and lcs_obj.get('Robossembler_DefaultOrigin')
):
lcs_inlet_objects.append(lcs_obj)
else:
lcs_outlet_objects.append(lcs_obj)
if not lcs_inlet_objects:
raise Exception('No LCS Inlet objects found!')
# retree_by lcs
part_names = []
for lcs_inlet_obj in lcs_inlet_objects:
# lcs inlet as main parent
parent_locator = lcs_inlet_obj.parent
if not parent_locator:
raise Exception('LCS %s should have a parent!', lcs_inlet_obj.name)
unparenting(lcs_inlet_obj)
round_transforms(lcs_inlet_obj)
if parent_locator:
if parent_locator.parent:
unparenting(parent_locator)
parenting(lcs_inlet_obj, parent_locator)
# lcs outlet parent to lcs inlet
for lcs_outlet_obj in lcs_inlet_obj.children_recursive:
if lcs_outlet_obj.name not in lcs_names:
continue
unparenting(lcs_outlet_obj)
round_transforms(lcs_outlet_obj)
parenting(lcs_inlet_obj, lcs_outlet_obj)
# reset transforms for inlet_lcs
lcs_inlet_obj.matrix_world = mathutils.Matrix()
# pack parts to collections
part_name = None
for locator in lcs_inlet_obj.children:
if locator not in lcs_outlet_objects:
part_name = locator.name
part_names.append(part_name)
part_col = bpy.data.collections.new(f'{part_name}')
bpy.data.collections['Render'].children.link(part_col)
for obj in lcs_inlet_obj.children_recursive:
unlink_from_collections(obj)
part_col.objects.link(obj)
unlink_from_collections(lcs_inlet_obj)
part_col.objects.link(lcs_inlet_obj)
# remove unmarked objects
marked_objs = sum(
[lcs_inlet_obj.children_recursive for lcs_inlet_obj in lcs_inlet_objects],
[])
parts_col_objs = bpy.data.collections['Render'].objects
unmarked_objs = list(set(parts_col_objs) - set(marked_objs))
if unmarked_objs:
removed_objs = list(map(bpy.data.objects.remove, unmarked_objs))
logger.info('%s unmarked objects removed!', len(removed_objs))
logger.info('Restructuring pipeline as separated parts finished!')
return part_names
def hierarchy_mono_part():
''' Restructuring pipeline as single part. '''
# collect scene hierarchy start info
main_locators = [obj for obj in bpy.data.objects if not obj.parent]
# pack parts to collections
part_names = []
for main_locator in main_locators:
part_name = main_locator.name
part_names.append(part_name)
part_col = bpy.data.collections.new(f'{part_name}')
bpy.data.collections['Render'].children.link(part_col)
for obj in main_locator.children_recursive:
unlink_from_collections(obj)
part_col.objects.link(obj)
unlink_from_collections(main_locator)
part_col.objects.link(main_locator)
logger.info('Restructuring pipeline as single part finished!')
return part_names

View file

@ -1,64 +0,0 @@
# coding: utf-8
# Copyright (C) 2023 Ilia Kurochkin <brothermechanic@yandex.com>
#
# 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.
'''
DESCRIPTION.
UV unwrapping and UV packing processing.
'''
__version__ = '0.1'
import logging
import math
import bpy
logger = logging.getLogger(__name__)
def uv_unwrap(obj_names, angle_limit=30):
''' UV unwrapping and UV packing processing '''
for obj_name in obj_names:
obj = bpy.data.objects[obj_name]
bpy.ops.object.select_all(action='DESELECT')
obj.select_set(True)
bpy.context.view_layer.objects.active = obj
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='SELECT')
# unwrapping
bpy.ops.uv.smart_project(angle_limit=math.radians(angle_limit))
# packing
bpy.ops.uv.pack_islands(udim_source='CLOSEST_UDIM',
rotate=True,
rotate_method='ANY',
scale=True,
merge_overlap=False,
margin_method='ADD',
margin=(1 / 256),
pin=False,
pin_method='LOCKED',
shape_method='CONCAVE')
bpy.ops.uv.pack_islands(udim_source='CLOSEST_UDIM',
rotate=True,
rotate_method='ANY',
scale=True,
merge_overlap=False,
margin_method='ADD',
margin=(1 / 256),
pin=False,
pin_method='LOCKED',
shape_method='CONCAVE')
bpy.ops.object.mode_set(mode='OBJECT')
obj.select_set(False)
return logger.info('UV setup of %s lowpoly meshes is finished!', len(obj_names))

View file

@ -1,133 +0,0 @@
# coding: utf-8
# Copyright (C) 2023 Ilia Kurochkin <brothermechanic@yandex.com>
#
# 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.
'''
DESCRIPTION.
Retopology visual assets for simulation pipeline.
'''
__version__ = '0.3'
import logging
import bpy
import math
from blender.utils.generative_modifiers import shell_remesher
from blender.utils.object_converter import mesh_to_mesh
from blender.utils.object_relations import parenting
from blender.utils.mesh_tools import select_peaks, select_stratched_edges
logger = logging.getLogger(__name__)
def parts_to_shells(part_names, **cg_config):
''' Create lowpoly shells from parts collections. '''
logger.info('Lowpoly shells creation launched...')
lowpoly_col = bpy.data.collections.new(cg_config['lowpoly_col_name'])
bpy.context.scene.collection.children.link(lowpoly_col)
for part_name in part_names:
# generate lowpoly objects from part collections
lowpoly_name = '{}_{}'.format(part_name, cg_config['lowpoly'])
lowpoly_mesh = bpy.data.meshes.new(lowpoly_name)
lowpoly_obj = bpy.data.objects.new(lowpoly_name, lowpoly_mesh)
bpy.context.view_layer.update()
lowpoly_col.objects.link(lowpoly_obj)
if bpy.data.objects[part_name].parent:
root_locator = bpy.data.objects[part_name].parent
else:
root_locator = bpy.data.objects[part_name]
lowpoly_obj.matrix_world = root_locator.matrix_world.copy()
parenting(root_locator, lowpoly_obj)
part_col = bpy.data.collections[
'{}_{}'.format(part_name, cg_config['hightpoly'])]
shell_remesher(lowpoly_obj, 'remesh_nodes', 'robossembler')
lowpoly_obj.modifiers['remesh_nodes']['Input_0'] = part_col
remesh_voxel = lowpoly_obj.modifiers.new('remesh_voxel', type='REMESH')
remesh_voxel.mode = 'VOXEL'
remesh_voxel.voxel_size = 0.001
remesh_sharp = lowpoly_obj.modifiers.new('remesh_sharp', type='REMESH')
remesh_sharp.mode = 'SHARP'
remesh_sharp.octree_depth = 7
decimate = lowpoly_obj.modifiers.new('decimate', type='DECIMATE')
decimate.decimate_type = 'COLLAPSE'
decimate.ratio = 0.1
# apply all modifiers to mesh
parenting(root_locator, mesh_to_mesh(lowpoly_obj))
# fix non_manifold shape
for lowpoly_obj in lowpoly_col.objects:
bpy.ops.object.select_all(action='DESELECT')
lowpoly_obj.select_set(state=True)
bpy.context.view_layer.objects.active = lowpoly_obj
bpy.ops.object.mode_set(mode='EDIT')
# pass 1
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.mesh.select_mode(use_extend=False, use_expand=False, type='VERT')
select_peaks(lowpoly_obj.data)
bpy.ops.mesh.select_non_manifold()
bpy.ops.mesh.dissolve_mode(use_verts=True, use_boundary_tear=False)
bpy.ops.mesh.delete(type='VERT')
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.mesh.quads_convert_to_tris(quad_method='BEAUTY', ngon_method='BEAUTY')
# pass 2
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.mesh.select_mode(use_extend=False, use_expand=False, type='VERT')
select_peaks(lowpoly_obj.data)
bpy.ops.mesh.select_non_manifold()
bpy.ops.mesh.dissolve_mode(use_verts=True, use_boundary_tear=False)
bpy.ops.mesh.delete(type='VERT')
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.mesh.quads_convert_to_tris(quad_method='BEAUTY', ngon_method='BEAUTY')
# pass 3
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.mesh.select_mode(use_extend=False, use_expand=False, type='VERT')
select_peaks(lowpoly_obj.data)
bpy.ops.mesh.select_non_manifold()
bpy.ops.mesh.dissolve_mode(use_verts=True, use_boundary_tear=False)
bpy.ops.mesh.delete(type='VERT')
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.mesh.quads_convert_to_tris(quad_method='BEAUTY', ngon_method='BEAUTY')
# pass 4
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.mesh.select_mode(use_extend=False, use_expand=False, type='VERT')
select_peaks(lowpoly_obj.data)
bpy.ops.mesh.select_non_manifold()
bpy.ops.mesh.dissolve_mode(use_verts=True, use_boundary_tear=False)
bpy.ops.mesh.delete(type='VERT')
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.mesh.quads_convert_to_tris(quad_method='BEAUTY', ngon_method='BEAUTY')
# pass 5
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.mesh.select_mode(type='EDGE')
select_stratched_edges(lowpoly_obj.data)
bpy.ops.mesh.dissolve_mode(use_verts=True)
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.mesh.quads_convert_to_tris(quad_method='BEAUTY', ngon_method='BEAUTY')
bpy.ops.mesh.normals_make_consistent()
# final
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.mesh.select_mode(type='FACE')
bpy.ops.object.mode_set(mode='OBJECT')
# shading
bpy.ops.object.shade_smooth(use_auto_smooth=True)
lowpoly_obj.data.auto_smooth_angle = math.radians(10)
lowpoly_obj.modifiers.new(type='WEIGHTED_NORMAL', name='WeightedNormal')
lowpoly_obj.modifiers['WeightedNormal'].keep_sharp = True
bpy.ops.object.modifier_apply(modifier="WeightedNormal")
logger.info('Generation of %s lowpoly shells is finished!', len(lowpoly_col.objects))
return [obj.name for obj in lowpoly_col.objects]

View file

@ -1,674 +0,0 @@
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>.

View file

@ -1,207 +0,0 @@
'''
Copyright (C) 2019-2023 Dancing Fortune Software All Rights Reserved
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 <http://www.gnu.org/licenses/>.
'''
bl_info = {
'name': 'Bake Wrangler',
'description': 'Bake Wrangler aims to improve all baking tasks with a node based interface and provides additional bake passes',
'author': 'DFS',
'version': (1, 5, 'b11'),
'blender': (3, 6, 0),
'location': 'Editor Type > Bake Node Editor',
"warning": "Beta Version",
'doc_url': 'https://bake-wrangler.readthedocs.io',
"tracker_url": "https://blenderartists.org/t/bake-wrangler-node-based-baking-tool-set/",
"support": "COMMUNITY",
'category': 'Baking'}
import bpy
from . import nodes
from . import status_bar
# Preferences
class BakeWrangler_Preferences(bpy.types.AddonPreferences):
bl_idname = __package__
def update_icon(self, context):
if not self.show_icon:
status_bar.status_bar_icon.disable_bw_icon()
else:
status_bar.status_bar_icon.ensure_bw_icon()
# Message prefs
show_icon: bpy.props.BoolProperty(name="Show BW Icon in Status Bar", description="Shows an icon that changes color based on baking state and can be clicked on to bring up the log", default=True, update=update_icon)
text_msgs: bpy.props.BoolProperty(name="Messages to Text editor", description="Write messages to a text block in addition to the console", default=True)
clear_msgs: bpy.props.BoolProperty(name="Clear Old Messages", description="Clear the text block before each new bake", default=True)
wind_msgs: bpy.props.BoolProperty(name="Open Text in new Window", description="A new window will be opened displaying the text block each time a new bake is started", default=False)
wind_close: bpy.props.BoolProperty(name="Auto Close Text Window", description="Close the text window on successful bake completion", default=False)
# Node prefs
show_node_prefs: bpy.props.BoolProperty(name="Node Defaults", description="Default general node options", default=False)
def_filter_mesh: bpy.props.BoolProperty(name="Meshes", description="Show mesh type objects", default=True)
def_filter_curve: bpy.props.BoolProperty(name="Curves", description="Show curve type objects", default=True)
def_filter_surface: bpy.props.BoolProperty(name="Surfaces", description="Show surface type objects", default=True)
def_filter_meta: bpy.props.BoolProperty(name="Metas", description="Show meta type objects", default=True)
def_filter_font: bpy.props.BoolProperty(name="Fonts", description="Show font type objects", default=True)
def_filter_light: bpy.props.BoolProperty(name="Lights", description="Show light type objects", default=True)
def_filter_collection: bpy.props.BoolProperty(name="Collections", description="Toggle only collections", default=False)
def_show_adv: bpy.props.BoolProperty(name="Expand Advanced Settings", description="Expand advanced settings on node creation instead of starting with them collapsed", default=False)
invert_bakemod: bpy.props.BoolProperty(name="Invert Selected in Bake Modifiers", description="Inverts the selection method used by the Bake Modifiers option from ignoring viewport hidden modifiers to baking them", default=False)
# Render prefs
show_render_prefs: bpy.props.BoolProperty(name="Render Defaults", description="Default settings for rendering options", default=False)
def_samples: bpy.props.IntProperty(name="Default Bake Samples", description="The number of samples per pixel that new Pass nodes will be set to when created", default=1, min=1)
def_xres: bpy.props.IntProperty(name="Default Bake X Resolution", description="The X resolution new Pass nodes will be set to when created", default=1024, min=1, subtype='PIXEL')
def_yres: bpy.props.IntProperty(name="Default Bake Y Resolution", description="The Y resolution new Pass nodes will be set to when created", default=1024, min=1, subtype='PIXEL')
def_device: bpy.props.EnumProperty(name="Default Device", description="The render device new Pass nodes will be set to when created", items=nodes.node_tree.BakeWrangler_PassSettings.cycles_devices, default='CPU')
def_raydist: bpy.props.FloatProperty(name="Default Ray Distance", description="The ray distance that new Mesh nodes will use when created", default=0.01, step=1, min=0.0, unit='LENGTH')
def_max_ray_dist: bpy.props.FloatProperty(name="Default Max Ray Dist", description="The max ray distance that new Mesh nodes will use when created", default=0.0, step=1, min=0.0, unit='LENGTH')
def_margin: bpy.props.IntProperty(name="Default Margin", description="The margin that new Mesh nodes will use when created", default=0, min=0, subtype='PIXEL')
def_mask_margin: bpy.props.IntProperty(name="Default Mask Margin", description="The mask margin that new Mesh nodes will use when created", default=0, min=0, subtype='PIXEL')
ignore_vis: bpy.props.BoolProperty(name="Objects Always Visible", description="Enable to ignore the visibility of selected objects when baking, making them visible regardless of settings in blender", default=False)
# Ouput prefs
show_output_prefs: bpy.props.BoolProperty(name="Output Defaults", description="Default settings for output options", default=False)
def_format: bpy.props.EnumProperty(name="Default Output Format", description="The format new Output nodes will use when created", items=nodes.node_tree.BakeWrangler_OutputSettings.img_format, default='PNG')
def_xout: bpy.props.IntProperty(name="Default Output X Resolution", description="The X resolution new Output nodes will be set to when created", default=1024, min=1, subtype='PIXEL')
def_yout: bpy.props.IntProperty(name="Default Output Y Resolution", description="The Y resolution new Output nodes will be set to when created", default=1024, min=1, subtype='PIXEL')
def_outpath: bpy.props.StringProperty(name="Default Output Path", description="The path new Output nodes will use when created", default="", subtype='DIR_PATH')
def_outname: bpy.props.StringProperty(name="Default Output Name", description="The name new Output nodes will use when created", default="Image", subtype='FILE_NAME')
make_dirs: bpy.props.BoolProperty(name="Create Paths", description="If selected path doesn't exist, try to create it", default=False)
auto_open: bpy.props.BoolProperty(name="Auto open bakes", description="Automatically open the baked image in blender if it isn't already open", default=True)
save_packed: bpy.props.BoolProperty(name="Save packed images", description="Prior to baking, save any packed images with changes or they will not apply during the bake", default=False)
save_images: bpy.props.BoolProperty(name="Save unpacked images", description="Prior to baking, save any unpacked images with changes or they will not apply during the bake", default=False)
img_non_color: bpy.props.EnumProperty(name="Non-Color", description="Color space to use as non-color when alternative color spaces are in use", items=nodes.node_tree.BakeWrangler_OutputSettings.img_color_spaces)
# Performance prefs
fact_start: bpy.props.BoolProperty(name="Disable Add-ons", description="Disable add-ons in the background baking instance (faster load times and some 3rd party add-ons can crash the process)", default=True)
retrys: bpy.props.IntProperty(name="Retries", description="On bake failure retry this many times", default=0)
# Dev prefs
debug: bpy.props.BoolProperty(name="Debug", description="Enable additional debugging output", default=False)
def draw(self, context):
layout = self.layout
colprefs = layout.column(align=False)
coltext = colprefs.column(align=False)
coltext.prop(self, "show_icon")
coltext.prop(self, "text_msgs")
if self.text_msgs:
box = coltext.box()
box.prop(self, "clear_msgs")
box.prop(self, "wind_msgs")
row = box.row(align=True)
row.label(icon='THREE_DOTS')
row.prop(self, "wind_close")
if self.wind_msgs:
row.enabled = True
else:
row.enabled = False
# Node prefs
box = colprefs.box()
if not self.show_node_prefs:
box.prop(self, "show_node_prefs", icon="DISCLOSURE_TRI_RIGHT", emboss=False)
else:
box.prop(self, "show_node_prefs", icon="DISCLOSURE_TRI_DOWN", emboss=False)
col = box.column(align=False)
row = col.row(align=True)
row.alignment = 'LEFT'
row.label(text="Filter:")
row1 = row.row(align=True)
row1.alignment = 'LEFT'
row1.prop(self, "def_filter_mesh", text="", icon='MESH_DATA')
row1.prop(self, "def_filter_curve", text="", icon='CURVE_DATA')
row1.prop(self, "def_filter_surface", text="", icon='SURFACE_DATA')
row1.prop(self, "def_filter_meta", text="", icon='META_DATA')
row1.prop(self, "def_filter_font", text="", icon='FONT_DATA')
row1.prop(self, "def_filter_light", text="", icon='LIGHT_DATA')
if self.def_filter_collection:
row1.enabled = False
row2 = row.row(align=False)
row2.alignment = 'LEFT'
row2.prop(self, "def_filter_collection", text="", icon='GROUP')
col.prop(self, "def_show_adv")
col.prop(self, "invert_bakemod")
# Render prefs
box = colprefs.box()
if not self.show_render_prefs:
box.prop(self, "show_render_prefs", icon="DISCLOSURE_TRI_RIGHT", emboss=False)
else:
box.prop(self, "show_render_prefs", icon="DISCLOSURE_TRI_DOWN", emboss=False)
col = box.column(align=False)
col.prop(self, "def_samples", text="Samples")
col1 = col.column(align=True)
col1.prop(self, "def_xres", text="X")
col1.prop(self, "def_yres", text="Y")
col.prop(self, "def_device", text="Device")
col.prop(self, "def_margin", text="Margin")
col.prop(self, "def_mask_margin", text="Mask Margin")
col.prop(self, "def_raydist", text="Ray Distance")
col.prop(self, "def_max_ray_dist", text="Max Ray Dist")
col.prop(self, "ignore_vis")
# Output prefs
box = colprefs.box()
if not self.show_output_prefs:
box.prop(self, "show_output_prefs", icon="DISCLOSURE_TRI_RIGHT", emboss=False)
else:
box.prop(self, "show_output_prefs", icon="DISCLOSURE_TRI_DOWN", emboss=False)
col = box.column(align=False)
col.prop(self, "def_format", text="Format")
col1 = col.column(align=True)
col1.prop(self, "def_xout", text="X")
col1.prop(self, "def_yout", text="Y")
col2 = col.column(align=True)
col2.prop(self, "def_outpath", text="Image Path")
col2.prop(self, "def_outname", text="Image Name")
col.prop(self, "make_dirs")
col.prop(self, "auto_open")
# Dev prefs
col = colprefs.column(align=True)
col.prop(self, "fact_start")
col.prop(self, "save_packed")
col.prop(self, "save_images")
col.prop(self, "retrys")
if 'Non-Color' not in bpy.types.ColorManagedInputColorspaceSettings.bl_rna.properties['name'].enum_items.keys():
col.prop(self, "img_non_color")
col.prop(self, "debug")
def register():
from bpy.utils import register_class
register_class(BakeWrangler_Preferences)
# Add status property to the window manager
bpy.types.WindowManager.bw_status = bpy.props.IntProperty(name="Bake Wrangler Status", default=0)
bpy.types.WindowManager.bw_lastlog = bpy.props.StringProperty(name="Bake Wangler Log", default="")
bpy.types.WindowManager.bw_lastfile = bpy.props.StringProperty(name="Bake Wangler Temp Blend", default="")
nodes.register()
status_bar.register()
def unregister():
from bpy.utils import unregister_class
nodes.unregister()
status_bar.unregister()
unregister_class(BakeWrangler_Preferences)
# Remove status property from window manager
delattr(bpy.types.WindowManager, 'bw_status')

File diff suppressed because it is too large Load diff

View file

@ -1,162 +0,0 @@
import numpy as np
# Main loop over image broken into segments. Will try to calculate pixel values outside of
# the masked area using the preconfigured weighting system.
def worker(hunk, shm_pixels, shm_mask, shm_bools, shm_margin, margin, limit, hit_target):
np_pixels = np.ndarray(shm_pixels[1], dtype=shm_pixels[2], buffer=shm_pixels[0].buf)
np_mask = np.ndarray(shm_mask[1], dtype=shm_mask[2], buffer=shm_mask[0].buf)
np_bools = np.ndarray(shm_bools[1], dtype=shm_bools[2], buffer=shm_bools[0].buf)
margins_bool = np.ndarray(shm_margin[1], dtype=shm_margin[2], buffer=shm_margin[0].buf)
hit_stub = np.zeros((0,3))
lim = len(margins_bool) if not limit else limit
for multi_index in hunk:
# Index ranges to create local view of arrays centred on pixel
view_idx = [multi_index[0],
multi_index[0]+(margin*2)+1,
multi_index[1],
multi_index[1]+(margin*2)+1]
bool_view = np_bools[view_idx[0]:view_idx[1],view_idx[2]:view_idx[3]]
hit_max = np.count_nonzero(bool_view) # Count number of non alpha pixels in view
if hit_max:
pixel_view = np_pixels[view_idx[0]:view_idx[1],view_idx[2]:view_idx[3]] # Get view of pixel data
hit_targ = hit_max if hit_max < hit_target else hit_target
hits = hit_stub
iteration = 0
# Majority of time cost is here due to arrays being copied in every case
while hits.shape[0] < hit_targ and iteration < lim:
sub_bool = bool_view[margins_bool[iteration]]
if np.count_nonzero(sub_bool):
sub_pixel = pixel_view[margins_bool[iteration]]
hits = np.append(hits, sub_pixel[sub_bool,:3], axis=0) if hits.shape[0] else sub_pixel[sub_bool,:3]
iteration += 1
# Get average of selected pixels colour and write value
if hits.shape[0] >= hit_target:
np_pixels[multi_index[0]+margin, multi_index[1]+margin,:3] = hits.sum(0) / hits.shape[0]
np_mask[multi_index[0]+margin, multi_index[1]+margin] = 1.0
# Simply writes pixels to a bpy.image. This is to keep bpy outside of the main working loop
def write_back(image, pixels):
import bpy
image.pixels.foreach_set(pixels.ravel())
image.update()
# Create numpy arrays of the image and mask as well as set up a weighting system for sampling
# pixels within the margin step area
def set_up(image, mask, margin):
import bpy
# Load numpy array from input image and mask
w, h = image.size
np_pixels = np.zeros((w, h, 4), 'f')
np_mask = np.zeros((w, h, 4), 'f')
image.pixels.foreach_get(np_pixels.ravel())
mask.pixels.foreach_get(np_mask.ravel())
# Create a weighting system for pixel samples within the margin area
px_offsets = np.array(np.meshgrid(np.arange(0,margin*2+1), np.arange(0,margin*2+1)))
px_offsets = np.moveaxis(px_offsets, 0, -1) # Change to X by Y by 2
px_offsets = np.absolute(px_offsets - [margin,margin])
# Manhattan distance array
#px_manhat = px_offsets.sum(2)
# Euclid distances
px_euclid = np.sqrt(np.power(px_offsets[:,:,0],2) + np.power(px_offsets[:,:,1],2))
px_euclid_c = np.int_(np.ceil(px_euclid))
px_euclid_r = np.int_(np.round(px_euclid))
# Bool arrays for each weight level starting at 1
margins_bool = []
for i in range(1,margin+1):
margins_bool.append(px_euclid_r == i)
# Expand pixel data by margin size by copying the start onto the end to hopefully make iteration faster
# (negative array indexes work, but you can't exceed array bounds)
np_pixels = np.vstack((np_pixels, np_pixels[0:margin,:,:])) # Add <margin> rows from the bottom to the top
np_pixels = np.vstack((np_pixels[h-margin:h,:,:], np_pixels)) # Add <margin> rows from old top to the new top
np_pixels = np.hstack((np_pixels, np_pixels[:,0:margin,:])) # Add <margin> cols from left to right
np_pixels = np.hstack((np_pixels[:,w-margin:w,:], np_pixels)) # Add <margin> cols from old right to new right
# Do same for mask
np_mask = np.vstack((np_mask, np_mask[0:margin,:,:])) # Add <margin> rows from the bottom to the top
np_mask = np.vstack((np_mask[h-margin:h,:,:], np_mask)) # Add <margin> rows from old top to the new top
np_mask = np.hstack((np_mask, np_mask[:,0:margin,:])) # Add <margin> cols from left to right
np_mask = np.hstack((np_mask[:,w-margin:w,:], np_mask)) # Add <margin> cols from old right to new right
# Reduce mask values to just reds to save space
np_mask = np_mask[...,0].copy()
np_bool = np_mask > 0.9
return np_pixels, np_mask, np_bool, np.asarray(margins_bool), w, h, margin
# Takes all the outputs from the setup routine (not called from within to avoid interacting with
# bpy in the subprocesses). Creates shared memory versions of the data and spawns a bunch of
# processes to work on smaller hunks of pixels in parallel.
def add_margin(pixels, mask, bools, margins, w, h, margin_step, margin, hit_target):
import concurrent.futures
from multiprocessing.managers import SharedMemoryManager
m_step = margin_step if margin >= margin_step or margin == -1 else margin
with SharedMemoryManager() as smm:
# Create shared memory versions of these arrays for the processes to share
shm_pixels = smm.SharedMemory(size=pixels.nbytes)
shm_mask = smm.SharedMemory(size=mask.nbytes)
shm_bools = smm.SharedMemory(size=bools.nbytes)
shm_margin = smm.SharedMemory(size=margins.nbytes)
np_pixels = np.ndarray(pixels.shape, dtype=pixels.dtype, buffer=shm_pixels.buf)
np_pixels[:] = pixels[:]
del pixels
np_mask = np.ndarray(mask.shape, dtype=mask.dtype, buffer=shm_mask.buf)
np_mask[:] = mask[:]
del mask
np_bools = np.ndarray(bools.shape, dtype=bools.dtype, buffer=shm_bools.buf)
np_bools[:] = bools[:]
del bools
margins_bool = np.ndarray(margins.shape, dtype=margins.dtype, buffer=shm_margin.buf)
margins_bool[:] = margins
del margins
# Split work into smaller hunks to split between cpu cores
import os
cpus = os.cpu_count() * 2
mask_where = np.argwhere(np_bools[margin_step:w+margin_step,margin_step:h+margin_step] == False)
hunks = np.array_split(mask_where, cpus)
# Do the processing in parallel
with concurrent.futures.ProcessPoolExecutor() as executor:
futures = []
limit = 0
# Negative margin indicates complete fill is wanted
if margin == -1:
# Simply keep processing hunks until they come back empty
while len(hunks[0]) > 0:
for i in hunks:
futures.append(executor.submit(worker, i, [shm_pixels, np_pixels.shape, np_pixels.dtype], [shm_mask, np_mask.shape, np_mask.dtype], [shm_bools, np_bools.shape, np_bools.dtype], [shm_margin, margins_bool.shape, margins_bool.dtype], m_step, limit, hit_target))
# Wait for this steps hunks to finish, then calculate the next set
concurrent.futures.wait(futures)
np_bools[:] = np_mask > 0.9
mask_where = np.argwhere(np_bools[margin_step:w+margin_step,margin_step:h+margin_step] == False)
hunks = np.array_split(mask_where, cpus)
# Check the margin actually has a size before doing anything
elif margin > 0:
# Work out how many steps are needed and if a last sub step size pass will be needed at the end
steps = int(margin / m_step)
lasts = margin % m_step
if lasts: steps += 1
# Process all hunks for each step in parallel
for step in range(steps):
# If the margin step didn't fit evenly a last sub sized step will be done to fill it
if lasts and step == steps-1:
limit = lasts
for i in hunks:
futures.append(executor.submit(worker, i, [shm_pixels, np_pixels.shape, np_pixels.dtype], [shm_mask, np_mask.shape, np_mask.dtype], [shm_bools, np_bools.shape, np_bools.dtype], [shm_margin, margins_bool.shape, margins_bool.dtype], m_step, limit, hit_target))
# Wait for this steps hunks to finish, then calculate the next set if there are more steps
concurrent.futures.wait(futures)
if step < steps-1:
np_bools[:] = np_mask > 0.9
mask_where = np.argwhere(np_bools[margin_step:w+margin_step,margin_step:h+margin_step] == False)
hunks = np.array_split(mask_where, cpus)
# Copy pixels from shared memory before the smm exits
output_px = np_pixels[margin_step:w+margin_step,margin_step:h+margin_step].copy()
return output_px
if __name__ == '__main__':
pass

View file

@ -1,17 +0,0 @@
from . import node_tree
from . import node_msgbus
from . import node_panel
from . import node_update
def register():
node_tree.register()
node_msgbus.register()
node_panel.register()
node_update.register()
def unregister():
node_tree.unregister()
node_msgbus.unregister()
node_panel.unregister()
node_update.unregister()

View file

@ -1,370 +0,0 @@
from bl_operators.presets import AddPresetBase
from bl_ui.utils import PresetPanel
from bpy.types import Panel, Menu, Operator
import bpy
# Helper functions and data for exporting meshes
# Classes to manage FBX preset panel/menu
class BW_PT_PresetsFBX(PresetPanel, Panel):
bl_label = 'FBX Presets'
preset_subdir = 'bake_wrangler\export.fbx'
preset_operator = 'script.execute_preset'
preset_add_operator = 'bake_wrangler.add_preset_fbx'
class BW_MT_PresetsFBX(Menu):
bl_label = 'FBX Presets'
preset_subdir = 'bake_wrangler\export.fbx'
preset_operator = 'script.execute_preset'
draw = Menu.draw_preset
class BW_OT_AddPresetFBX(AddPresetBase, Operator):
'''Add new FBX preset'''
bl_idname = 'bake_wrangler.add_preset_fbx'
bl_label = 'Add FBX preset'
preset_menu = 'BW_MT_PresetsFBX'
# Common variable used for all preset values
preset_defines = [
'node = bpy.context.active_node.FBX',
]
# Properties to store in the preset
preset_values = []
for key in bpy.ops.export_scene.fbx.get_rna_type().properties.keys()[2:]:
preset_values.append("node." + key)
# Directory to store the presets
preset_subdir = 'bake_wrangler\export.fbx'
#Helper functions and data
export_supported = {
'FBX': [BW_PT_PresetsFBX, 'export_scene.fbx', None],
}
exporters = {}
def get_exporters():
presets_enum = []
for key, val in exporters.items():
if key == 'FBX':
presets_enum.append(('FBX', "FBX", "Export to FBX"))
return tuple(presets_enum)
def draw_presets(preset, layout):
exporters[preset][0].draw_menu(layout)
def draw_properties(node, preset, layout):
props = getattr(node, preset)
#for prop in props.rna_type.properties.keys():
# if prop not in ["rna_type", "name"]:
# layout.prop(props, prop)
# Go the road to hell and have custom layouts for each format mostly stolen from their panels
# instead of just displaying all the properties and letting god sort them out
if preset == 'FBX':
# Main section
layout.use_property_decorate = False
row = layout.row(align=True)
row.prop(props, "path_mode")
sub = row.row(align=True)
sub.enabled = (props.path_mode == 'COPY')
sub.prop(props, "embed_textures", text="", icon='PACKAGE' if props.embed_textures else 'UGLYPACKAGE')
box = layout.box()
if not node.show_pt_1:
box.prop(node, "show_pt_1", icon="DISCLOSURE_TRI_RIGHT", emboss=False, text="Include")
else:
box.prop(node, "show_pt_1", icon="DISCLOSURE_TRI_DOWN", emboss=False, text="Include")
box.use_property_split = True
box.column().prop(props, "object_types")
box.prop(props, "use_custom_props")
box = layout.box()
if not node.show_pt_2:
box.prop(node, "show_pt_2", icon="DISCLOSURE_TRI_RIGHT", emboss=False, text="Transform")
else:
box.prop(node, "show_pt_2", icon="DISCLOSURE_TRI_DOWN", emboss=False, text="Transform")
box.use_property_split = True
box.prop(props, "global_scale")
box.prop(props, "apply_scale_options")
box.prop(props, "axis_forward")
box.prop(props, "axis_up")
box.prop(props, "apply_unit_scale")
box.prop(props, "use_space_transform")
row = box.row()
row.prop(props, "bake_space_transform")
row.label(text="", icon='ERROR')
box = layout.box()
if not node.show_pt_3:
box.prop(node, "show_pt_3", icon="DISCLOSURE_TRI_RIGHT", emboss=False, text="Geometry")
else:
box.prop(node, "show_pt_3", icon="DISCLOSURE_TRI_DOWN", emboss=False, text="Geometry")
box.use_property_split = True
box.prop(props, "mesh_smooth_type")
box.prop(props, "use_subsurf")
box.prop(props, "use_mesh_modifiers")
box.prop(props, "use_mesh_edges")
sub = box.row()
sub.prop(props, "use_tspace")
box = layout.box()
if not node.show_pt_4:
box.prop(node, "show_pt_4", icon="DISCLOSURE_TRI_RIGHT", emboss=False, text="Armature")
else:
box.prop(node, "show_pt_4", icon="DISCLOSURE_TRI_DOWN", emboss=False, text="Armature")
box.use_property_split = True
box.prop(props, "primary_bone_axis")
box.prop(props, "secondary_bone_axis")
box.prop(props, "armature_nodetype")
box.prop(props, "use_armature_deform_only")
box.prop(props, "add_leaf_bones")
box = layout.box()
hed = box.row()
if not node.show_pt_5:
hed.prop(node, "show_pt_5", icon="DISCLOSURE_TRI_RIGHT", emboss=False, text="")
hed.prop(props, "bake_anim", text="")
hed.prop(node, "show_pt_5", icon="NONE", emboss=False, text="Bake Animation")
else:
hed.prop(node, "show_pt_5", icon="DISCLOSURE_TRI_DOWN", emboss=False, text="")
hed.prop(props, "bake_anim", text="")
hed.prop(node, "show_pt_5", icon="NONE", emboss=False, text="Bake Animation")
box.use_property_split = True
col = box.column()
col.enabled = props.bake_anim
col.prop(props, "bake_anim_use_all_bones")
col.prop(props, "bake_anim_use_nla_strips")
col.prop(props, "bake_anim_use_all_actions")
col.prop(props, "bake_anim_force_startend_keying")
col.prop(props, "bake_anim_step")
col.prop(props, "bake_anim_simplify_factor")
# Creates a property group from an operators properties
def prop_grp_from_op(opName, grpName):
oppath, opnm = opName.split(".")
op = getattr(bpy.ops, oppath, None)
if op is None:
return op
op = getattr(op, opnm, None)
if op is None:
return op
props = op.get_rna_type()
props = props.properties
grp_props = {'__annotations__' : {}}
for prop in props:
if prop.identifier in ["rna_type", "filepath"]:
continue
if prop.type == 'BOOLEAN':
grp_props['__annotations__'][prop.identifier] = bpy.props.BoolProperty(
name=prop.name,
description=prop.description,
default=prop.default,
subtype=prop.subtype)
elif prop.type == 'ENUM':
eitems = []
eopts = set()
ende =prop.default
if prop.is_enum_flag:
eopts = set({'ENUM_FLAG'})
ende = prop.default_flag
for key in prop.enum_items.keys():
eitems.append((key, prop.enum_items[key].name, prop.enum_items[key].description))
grp_props['__annotations__'][prop.identifier] = bpy.props.EnumProperty(
items=tuple(eitems),
name=prop.name,
description=prop.description,
options=eopts,
default=ende)
elif prop.type == 'STRING':
grp_props['__annotations__'][prop.identifier] = bpy.props.StringProperty(
name=prop.name,
description=prop.description,
default=prop.default,
maxlen=prop.length_max,
subtype=prop.subtype)
elif prop.type == 'POINTER':
grp_props['__annotations__'][prop.identifier] = bpy.props.PointerProperty(
type=getattr(bpy.types, prop.fixed_type.name),
name=prop.name,
description=prop.description)
elif prop.type == 'FLOAT':
grp_props['__annotations__'][prop.identifier] = bpy.props.FloatProperty(
name=prop.name,
description=prop.description,
default=prop.default,
min=prop.hard_min,
max=prop.hard_max,
soft_min=prop.soft_min,
soft_max=prop.soft_max,
step=prop.step,
precision=prop.precision,
subtype=prop.subtype,
unit=prop.unit)
else:
print("Unknown type: %s on %s" % (prop.type, prop.identifier))
# Create and return prop group class from the props
return type(grpName, tuple([bpy.types.PropertyGroup]), grp_props)
# Node to export baked models in some format
class BakeWrangler_Output_Export_Mesh(Node, BakeWrangler_Tree_Node):
'''Node to export baked models to the selected format'''
bl_label = 'Output Export Mesh'
# Makes sure there is always one empty input socket at the bottom by adding and removing sockets
def update_inputs(self):
BakeWrangler_Tree_Node.update_inputs(self, 'BakeWrangler_Socket_Mesh', "Mesh")
# Check node settings are valid to bake. Returns true/false, plus error message(s).
def validate(self, is_primary=False):
valid = [True]
# Validate inputs
has_valid_input = False
for input in self.inputs:
if not is_primary:
has_valid_input = True
break
else:
input_valid = get_input(input).validate()
valid[0] = input_valid.pop(0)
if valid[0]:
has_valid_input = True
valid += input_valid
errs = len(valid)
if not has_valid_input and errs < 2:
valid[0] = False
valid.append([_print("Input error", node=self, ret=True), ": No valid inputs connected"])
# Validate file path
self.get_full_path(bpy.context)
if not os.path.isdir(os.path.abspath(self.out_path)):
# Try creating the path if enabled in prefs
if _prefs("make_dirs") and not os.path.exists(os.path.abspath(self.out_path)):
try:
os.makedirs(os.path.abspath(self.out_path))
except OSError as err:
valid[0] = False
valid.append([_print("Path error", node=self, ret=True), ": Trying to create path at '%s'" % (err.strerror)])
return valid
else:
valid[0] = False
valid.append([_print("Path error", node=self, ret=True), ": Invalid path '%s'" % (os.path.abspath(self.out_path))])
return valid
# Check if there is read/write access to the file/directory
file_path = os.path.join(os.path.abspath(self.out_path), self.name_with_ext())
if os.path.exists(file_path):
if os.path.isfile(file_path):
# It exists so try to open it r/w
try:
file = open(file_path, "a")
except OSError as err:
valid[0] = False
valid.append([_print("File error", node=self, ret=True), ": Trying to open file at '%s'" % (err.strerror)])
else:
# It exists but isn't a file
valid[0] = False
valid.append([_print("File error", node=self, ret=True), ": File exists but isn't a regular file '%s'" % (file_path)])
else:
# See if it can be created
try:
file = open(file_path, "a")
except OSError as err:
valid[0] = False
valid.append([_print("File error", node=self, ret=True), ": %s trying to create file at '%s'" % (err.strerror, file_path)])
else:
file.close()
os.remove(file_path)
# Validated
return valid
# Get full path, removing any relative references
def get_full_path(self, context):
cwd = os.path.dirname(bpy.data.filepath)
self.out_path = os.path.normpath(os.path.join(cwd, bpy.path.abspath(self.disp_path)))
# Deal with any path components that may be in the filename
def update_filename(self, context):
fullpath = os.path.normpath(bpy.path.abspath(self.out_name))
path, name = os.path.split(fullpath)
if path:
self.disp_path = self.out_name[:-len(name)]
if name and self.out_name != name:
self.out_name = name
# Return the file name with the correct extension and suffix
def name_with_ext(self, suffix=""):
return self.out_name + suffix + self.exporter.lower()
def get_exporters(self, context):
return node_mexport.get_exporters()
# Core settings
disp_path: bpy.props.StringProperty(name="Output Path", description="Path to save mesh in", default="", subtype='DIR_PATH', update=get_full_path)
out_path: bpy.props.StringProperty(name="Output Path", description="Path to save mesh in", default="", subtype='DIR_PATH')
out_name: bpy.props.StringProperty(name="Output File", description="File prefix to save mesh as", default="Mesh", subtype='FILE_PATH', update=update_filename)
exporter: bpy.props.EnumProperty(name="Format", description="Export file format", items=get_exporters)
show_pt_1: bpy.props.BoolProperty(default=True)
show_pt_2: bpy.props.BoolProperty(default=False)
show_pt_3: bpy.props.BoolProperty(default=False)
show_pt_4: bpy.props.BoolProperty(default=False)
show_pt_5: bpy.props.BoolProperty(default=False)
def init(self, context):
super().init(context)
# Sockets IN
self.inputs.new('BakeWrangler_Socket_Mesh', "Mesh")
# Sockets OUT
self.outputs.new('BakeWrangler_Socket_Bake', "Bake")
# Prefs
self.disp_path = _prefs("def_meshpath")
self.out_name = _prefs("def_meshname")
def draw_buttons(self, context, layout):
colnode = layout.column(align=False)
colpath = colnode.column(align=True)
colpath.prop(self, "disp_path", text="")
colpath.prop(self, "out_name", text="")
colpath.prop(self, "exporter")
def draw_buttons_ext(self, context, layout):
node_mexport.draw_presets(self.exporter, layout.row())
col = layout.column()
node_mexport.draw_properties(self, self.exporter, col)
# Classes to register
classes = (
BW_PT_PresetsFBX,
BW_MT_PresetsFBX,
BW_OT_AddPresetFBX,
)
def register():
from bpy.utils import register_class
for cls in classes:
register_class(cls)
for exp in export_supported.keys():
if getattr(bpy.ops, exp[1], None) is not None:
prop_grp = prop_grp_from_op(export_supported[exp][1], "BW_PropGrp" + exp)
exporters[exp] = [export_supported[exp][0], export_supported[exp][1], prop_grp]
register_class(prop_grp)
from .node_tree import BakeWrangler_Output_Export_Mesh
setattr(BakeWrangler_Output_Export_Mesh, exp, bpy.props.PointerProperty(type=prop_grp))
def unregister():
from bpy.utils import unregister_class
for cls in reversed(classes):
unregister_class(cls)
for exp in exporters.keys():
unregister_class(exporters[exp][2])
exporters = {}
if __name__ == "__main__":
register()

View file

@ -1,114 +0,0 @@
import bpy
from .node_tree import _prefs, _print, BW_TREE_VERSION
# Msgbus will call this when the loaded node tree changes. Checks on tree version etc can be done
def BakeWrangler_Msgbus_NodeTreeChange(*args):
debug = _prefs('debug')
if debug: _print("Node Tree Changed")
wm = bpy.context.window_manager
ar = bpy.context.area
if debug: _print("Context Area: %s" % (ar))
# First find all the open node editors that belong to BW
spaces = []
for window in wm.windows:
for area in window.screen.areas:
if area.ui_type == 'BakeWrangler_Tree':
if len(area.spaces) > 0:
for spc in area.spaces:
if spc.type == 'NODE_EDITOR' and hasattr(spc, 'node_tree'):
if debug: _print("Node editor found: %s" % (spc))
spaces.append(spc)
break
for space in spaces:
tree = space.node_tree
# Init a new tree
if tree and not tree.initialised:
if debug: _print("New/Uninitialized node tree active")
tree.use_fake_user = True
# Give tree a nice name
'''if tree.name.startswith("NodeTree"):
num = 0
for nodes in bpy.data.node_groups:
if nodes.name.startswith("Bake Recipe"):
if num == 0:
num = 1
splt = nodes.name.split('.')
if len(splt) > 1 and splt[1].isnumeric:
num = int(splt[1]) + 1
if num == 0:
name = "Bake Recipe"
else:
name = "Bake Recipe.%03d" % (num)
tree.name = tree.name.replace("NodeTree", name, 1)'''
# Add initial basic node set up
if len(tree.nodes) == 0:
bake_mesh = tree.nodes.new('BakeWrangler_Bake_Mesh')
bake_pass = tree.nodes.new('BakeWrangler_Bake_Pass')
output_img = tree.nodes.new('BakeWrangler_Output_Image_Path')
global_mesh_set = tree.nodes.new('BakeWrangler_MeshSettings')
global_mesh_set.pinned = True
global_pass_set = tree.nodes.new('BakeWrangler_PassSettings')
global_pass_set.pinned = True
global_outp_set = tree.nodes.new('BakeWrangler_OutputSettings')
global_outp_set.pinned = True
global_samp_set = tree.nodes.new('BakeWrangler_SampleSettings')
global_samp_set.pinned = True
bake_mesh.location[0] -= 300
output_img.location[0] += 200
global_mesh_set.location[0] -= 300
global_mesh_set.location[1] += 210
global_pass_set.location[0] += 100
global_pass_set.location[1] += 210
global_outp_set.location[0] += 280
global_outp_set.location[1] += 210
global_samp_set.location[0] -= 80
global_samp_set.location[1] += 210
tree.links.new(bake_pass.inputs[1], bake_mesh.outputs[0])
tree.links.new(output_img.inputs[2], bake_pass.outputs[0])
output_img.inputs[2].valid = True
tree.tree_version = BW_TREE_VERSION
tree.initialised = True
if debug: _print("Tree initialized")
# Reregister message bus subscription
bw_subscriber = object()
from bpy.app.handlers import persistent
@persistent
def BakeWrangler_Hook_Post_Load(dummy):
BakeWrangler_Msgbus_Subscribe(bw_subscriber)
# Subscribe to message bus
def BakeWrangler_Msgbus_Subscribe(owner, sub=True):
if owner is not None:
bpy.msgbus.clear_by_owner(owner)
if sub:
subscribe_to = bpy.types.SpaceNodeEditor, "node_tree"
bpy.msgbus.subscribe_rna(key=subscribe_to,
owner=owner,
args=(1,2),
notify=BakeWrangler_Msgbus_NodeTreeChange)
def register():
BakeWrangler_Msgbus_Subscribe(bw_subscriber)
bpy.app.handlers.load_post.append(BakeWrangler_Hook_Post_Load)
def unregister():
hook_index = None
for idx in range(len(bpy.app.handlers.load_post)):
if bpy.app.handlers.load_post[idx] == BakeWrangler_Hook_Post_Load:
hook_index = idx
if hook_index != None:
bpy.app.handlers.load_post.pop(hook_index)
BakeWrangler_Msgbus_Subscribe(bw_subscriber, False)
if __name__ == "__main__":
register()

View file

@ -1,299 +0,0 @@
import bpy
from .node_tree import _prefs, _print, BW_TREE_VERSION, BakeWrangler_Operator
# Panel displaying info about recipe version and containing update button
class BakeWrangler_RecipeInfo(bpy.types.Panel):
'''Panel in node editor to show recipe information'''
bl_label = "Recipe Info"
bl_idname = "OBJECT_PT_BW_RecipeInfo"
bl_space_type = 'NODE_EDITOR'
bl_region_type = 'UI'
bl_context = "area"
bl_category = "Bake Wrangler"
@classmethod
def poll(cls, context):
# Only display if the edited tree is of the correct type
return (context.area and context.area.ui_type == 'BakeWrangler_Tree')
def draw(self, context):
tree = context.space_data.node_tree
layout = self.layout
if tree is None:
layout.label(text="No recipe loaded")
return
tree_ver = getattr(tree, "tree_version", 0)
curr_ver = BW_TREE_VERSION
nodes = len(tree.nodes)
col = layout.column()
op = col.operator("bake_wrangler.show_log", icon='TEXT')
op.tree = tree.name
col.label(text="Recipe version: " + str(tree_ver))
col.label(text="Add-on version: " + str(curr_ver))
col.label(text="Nodes: " + str(nodes))
if tree_ver != curr_ver:
row = col.row()
if tree_ver > curr_ver:
row.label(text="Status: Add-on requires update")
else:
row.label(text="Status: Recipe requires update")
op_row = col.row()
if tree_ver >= 5:
op = op_row.operator("bake_wrangler_op.update_recipe", icon='FILE_REFRESH', text="Update Recipe")
op.tree = tree.name
else:
op_row.operator("bake_wrangler_op.update_recipe", icon='CANCEL', text="Update Unavailable")
op_row.enabled = False
# Panel for automatic cage management tasks
class BakeWrangler_AutoCages(bpy.types.Panel):
'''Panel in node editor to manage automatic cages'''
bl_label = "Auto Cages"
bl_idname = "OBJECT_PT_BW_AutoCages"
bl_space_type = 'NODE_EDITOR'
bl_region_type = 'UI'
bl_context = "area"
bl_category = "Bake Wrangler"
@classmethod
def poll(cls, context):
# Only display if the edited tree is of the correct type
return (context.area and context.area.ui_type == 'BakeWrangler_Tree')
def draw(self, context):
tree = context.space_data.node_tree
layout = self.layout
if tree is None:
layout.label(text="No recipe loaded")
return
col = layout.column()
op = col.operator("bake_wrangler.auto_cage_create")
op.tree = tree.name
op = col.operator("bake_wrangler.auto_cage_update")
op.tree = tree.name
op = col.operator("bake_wrangler.auto_cage_remove")
op.tree = tree.name
# Show log file
class BakeWrangler_Operator_ShowLog(BakeWrangler_Operator, bpy.types.Operator):
'''Show last log created by this recipe'''
bl_idname = "bake_wrangler.show_log"
bl_label = "Show Log"
bl_options = {"REGISTER"}
# Called either after invoke from UI or directly from script
def execute(self, context):
return {'FINISHED'}
# Called from button press, set modifier key states
def invoke(self, context, event):
tree = bpy.data.node_groups[self.tree]
if tree.last_log:
bpy.ops.screen.area_dupli('INVOKE_DEFAULT')
open_ed = bpy.context.window_manager.windows[len(bpy.context.window_manager.windows) - 1].screen.areas[0]
open_ed.type = 'TEXT_EDITOR'
log = bpy.data.texts.load(tree.last_log)
open_ed.spaces[0].text = log
open_ed.spaces[0].show_line_numbers = False
open_ed.spaces[0].show_syntax_highlight = False
return {'FINISHED'}
else:
self.report({'WARNING'}, "No log file set")
return {'CANCELLED'}
# Generate auto cages
class BakeWrangler_Operator_AutoCageCreate(BakeWrangler_Operator, bpy.types.Operator):
'''Create cages in current scene for objects in recipe that don't have a cage set.\nShift-Click to exclude hidden objects'''
bl_idname = "bake_wrangler.auto_cage_create"
bl_label = "Generate Cages"
bl_options = {"REGISTER", "UNDO"}
# Called either after invoke from UI or directly from script
def execute(self, context):
return {'FINISHED'}
# Called from button press, set modifier key states
def invoke(self, context, event):
mod_shift = event.shift
objs = get_auto_caged(bpy.data.node_groups[self.tree], mod_shift, context)
if len(objs):
# Check if cage collection exists and create it if needed
if 'BW Cages' not in bpy.data.collections.keys():
bpy.data.collections.new('BW Cages')
# Check if cage collection is in current scene and link if needed
if 'BW Cages' not in context.scene.collection.children.keys():
context.scene.collection.children.link(bpy.data.collections['BW Cages'])
bw_cages = bpy.data.collections['BW Cages'].objects
# Create and link cages to the collection for all objects
for obj in objs:
if not obj[0].bw_auto_cage:
generate_auto_cage(obj[0], obj[1], obj[2], context)
if obj[0].bw_auto_cage not in bw_cages.values():
bw_cages.link(obj[0].bw_auto_cage)
return {'FINISHED'}
else:
self.report({'WARNING'}, "No objects with auto cages found")
return {'CANCELLED'}
# Update auto cages
class BakeWrangler_Operator_AutoCageUpdate(BakeWrangler_Operator, bpy.types.Operator):
'''Update cages in current scene for objects in recipe. Overwrites user changes if 'bw_cage' modifier has been removed.\nShift-Click to exclude hidden objects'''
bl_idname = "bake_wrangler.auto_cage_update"
bl_label = "Update Cages"
bl_options = {"REGISTER", "UNDO"}
# Called either after invoke from UI or directly from script
def execute(self, context):
return {'FINISHED'}
# Called from button press, set modifier key states
def invoke(self, context, event):
mod_shift = event.shift
objs = get_auto_caged(bpy.data.node_groups[self.tree], mod_shift, context)
if len(objs):
for obj in objs:
if obj[0].bw_auto_cage:
cage = obj[0].bw_auto_cage
# If the modifier is still on the object just change it instead of making a new object
if "bw_cage" in cage.modifiers:
cage.modifiers["bw_cage"].strength = obj[1]
cage.data.auto_smooth_angle = obj[2]
elif 'BW Cages' in bpy.data.collections.keys():
bpy.data.collections['BW Cages'].objects.unlink(cage)
generate_auto_cage(obj[0], obj[1], obj[2], context)
return {'FINISHED'}
else:
self.report({'WARNING'}, "No objects with auto cages found")
return {'CANCELLED'}
# Remove auto cages
class BakeWrangler_Operator_AutoCageRemove(BakeWrangler_Operator, bpy.types.Operator):
'''Remove cages in current scene for objects in recipe.\nShift-Click to exclude hidden objects'''
bl_idname = "bake_wrangler.auto_cage_remove"
bl_label = "Remove Cages"
bl_options = {"REGISTER", "UNDO"}
# Called either after invoke from UI or directly from script
def execute(self, context):
return {'FINISHED'}
# Called from button press, set modifier key states
def invoke(self, context, event):
mod_shift = event.shift
if 'BW Cages' in bpy.data.collections.keys():
bw_cages = bpy.data.collections['BW Cages'].objects
objs = context.scene.collection.all_objects
for obj in objs:
if obj.bw_auto_cage and (not mod_shift or obj.visible_get()):
bw_cages.unlink(obj.bw_auto_cage)
obj.bw_auto_cage = None
if 'BW Cages' in context.scene.collection.children:
context.scene.collection.children.unlink(bw_cages.id_data)
return {'FINISHED'}
else:
self.report({'WARNING'}, "No objects with auto cages found")
return {'CANCELLED'}
# Return a list of objects that would get a cage auto generated
def get_auto_caged(tree, vis, context):
nodes = tree.nodes
objs = []
for node in nodes:
if node.bl_idname == 'BakeWrangler_Output_Image_Path':
objs += node.get_unique_objects('TARGET', for_auto_cage=True)
# Get a list of all objects in the scene and cull it down to only visible ones
vl_objs = context.scene.collection.all_objects.values()
if vis:
vl_vis = []
for obj in vl_objs:
if obj.visible_get() and obj not in vl_vis:
vl_vis.append(obj)
vl_objs = vl_vis
# Return a list of unique objects that are in the scene and visible and would have a cage
objs_prune = []
for obj in objs:
if obj not in objs_prune and obj[0] in vl_objs:
objs_prune.append(obj)
return objs_prune
# Create an auto cage for the given mesh
def generate_auto_cage(mesh, cage_exp, smooth, context):
# Create a copy of the base mesh with modifiers applied to use a the base cage
cage = mesh.copy()
cage.data = mesh.data.copy()
cage.name = mesh.name + '.cage'
cage.name = mesh.name + '.cage'
cage.data.materials.clear()
cage.data.polygons.foreach_set('material_index', [0] * len(cage.data.polygons))
cage.display_type = 'WIRE'
if cage not in bpy.data.collections['BW Cages'].objects.values():
bpy.data.collections['BW Cages'].objects.link(cage)
if len(cage.modifiers):
prev_active = bpy.context.view_layer.objects.active
bpy.context.view_layer.objects.active = cage
for mod in cage.modifiers:
if mod.show_render:
try:
bpy.ops.object.modifier_apply(modifier=mod.name)
except:
_print("Error applying modifier '%s' to object '%s'" % (mod.name, mesh.name))
bpy.ops.object.modifier_remove(modifier=mod.name)
else:
bpy.ops.object.modifier_remove(modifier=mod.name)
bpy.context.view_layer.objects.active = prev_active
# Expand cage on normals
cage_disp = cage.modifiers.new("bw_cage", 'DISPLACE')
cage_disp.strength = cage_exp
cage_disp.direction = 'NORMAL'
cage_disp.mid_level = 0.0
cage_disp.show_in_editmode = True
cage_disp.show_on_cage = True
cage_disp.show_expanded = False
# Smooth normals and clear sharps
cage.data.use_auto_smooth = True
cage.data.auto_smooth_angle = smooth
for poly in cage.data.polygons:
poly.use_smooth = True
for edge in cage.data.edges:
edge.use_edge_sharp = False
# Link cage via property on mesh
mesh.bw_auto_cage = cage
# Classes to register
classes = (
BakeWrangler_RecipeInfo,
BakeWrangler_AutoCages,
BakeWrangler_Operator_ShowLog,
BakeWrangler_Operator_AutoCageCreate,
BakeWrangler_Operator_AutoCageUpdate,
BakeWrangler_Operator_AutoCageRemove,
)
def register():
# Add pointer to generated cage
bpy.types.Object.bw_auto_cage = bpy.props.PointerProperty(name="Cage", description="Bake Wrangler auto generated cage", type=bpy.types.Object)
from bpy.utils import register_class
for cls in classes:
register_class(cls)
def unregister():
from bpy.utils import unregister_class
for cls in reversed(classes):
unregister_class(cls)
if __name__ == "__main__":
register()

Some files were not shown because too many files have changed in this diff Show more