def test_read_obj(self):
     v, _, n, f, _, _ = igl.read_obj(self.test_path + "face.obj")
     self.assertTrue(type(v) == type(f) == type(n) == np.ndarray)
     self.assertTrue(v.shape == (25905, 3) and n.shape == (0, 0) and f.shape == (51712, 3))
     self.assertTrue(v.dtype == np.float64)
     v, _, n, f, _, _ = igl.read_obj(self.test_path + "face.obj", dtype="float32")
     self.assertTrue(v.shape == (25905, 3) and n.shape == (0, 0) and f.shape == (51712, 3))
     self.assertTrue(v.dtype == np.float32)
     self.assertTrue(v.flags.c_contiguous)
     self.assertTrue(f.flags.c_contiguous)
     self.assertTrue(n.flags.c_contiguous)
Пример #2
0
def read_model(obj_path, feat_path):
    m = {}
    m["vertices"], _, m["normals"], m["face_indices"], _, m["normal_indices"] = igl.read_obj(obj_path)
            
    with open(feat_path) as fi:
        m["features"] = yaml.load(fi, Loader=Loader)
    return m
Пример #3
0
import timeit

# captialized
if __name__ == "__main__":
    # argparse
    parser = argparse.ArgumentParser(description="cubic stylization")
    parser.add_argument("mesh", help="path to target mesh")
    parser.add_argument("--plambda",
                        help="parameter to control cubeness",
                        type=float,
                        default=0.2)
    opt = parser.parse_args()
    print(opt)
    filename = opt.mesh
    # load mesh
    V, _, _, F, _, _ = igl.read_obj(filename)
    # init optim context
    ctx = Context()
    # normalize mesh
    V = normalize(V)
    U = np.array(V)
    # set a constrained point
    ctx.set_constrain(V, F)
    ctx.set_parameters(V, F)
    ctx.set_lambda(opt.plambda)
    # optim loop
    maxIter = 1000
    stopRelativeDeltaV = 1e-3
    start = timeit.default_timer()
    for iter in range(0, maxIter):
        ctx.optim_step(V, U)
Пример #4
0
def rotate_ribbon(omega, skipped_frames, dt):
    with open(input_json) as f:
        input_data = json.load(f)
        handles = [0, 3] # handle vertices

        rest_mesh_path = file_prefix + input_data['rest_mesh']
        rest_pos, _, _, faces, _, _ = igl.read_obj(rest_mesh_path)
        cur_vel = np.zeros(rest_pos.shape)
        np.savetxt(file_prefix + input_data['current_velocity'], cur_vel)

        # save rest mesh
        cur_pos = rest_pos
        mesh_path = output_folder + '/mesh/mesh_0.obj'
        igl.write_obj(mesh_path, rest_pos, faces)

        #save init vel
        vel_path = output_folder + '/velocity/vel_0.txt'
        np.savetxt(vel_path, cur_vel)

        kp = 0.1
        kd = 2 * math.sqrt(kp)
        fmin = -0.01
        fmax = 0.01
        
        for i in range(250):    
            cur_time  = i  * dt * skipped_frames
            print('iter: ', i)
            theta = omega * cur_time
            ref_theta = omega * (i * dt * skipped_frames + dt)
            # generate force file
            clampedDOFs = np.zeros((len(handles), 4))
            for j in range(len(handles)):
                vid = handles[j]
                r = np.linalg.norm(rest_pos[vid])
                clampedDOFs[j][0] = vid
                clampedDOFs[j][2] = r * math.sin(ref_theta)
                clampedDOFs[j][3] = r * math.cos(ref_theta)
                print('clamped dofs on vertex:', vid, clampedDOFs[j])
            save_clamped_dofs(file_prefix + input_data['clamped_DOFs'], clampedDOFs)

            cur_data = input_data

            cur_data['cur_mesh'] = '/ribbon_dynamic/mesh/mesh_' + str(i) + '.obj'
            cur_data['curedge_DOFs'] = '/ribbon_dynamic/mesh/edgedofs_' + str(i) + 'txt'
            cur_data['current_velocity'] = '/ribbon_dynamic/velocity/vel_' + str(i) + '.txt'
            cur_data['clamped_DOFs'] = '/ribbon_dynamic/mesh/clampedDOFs_' + str(i) + '.txt'

            #save clamped dofs
            save_clamped_dofs(file_prefix + cur_data['clamped_DOFs'], clampedDOFs)

            with open(cur_json, 'w') as json_file:
                json.dump(cur_data, json_file, indent = 4, sort_keys=True)

            args = [exe_path, '--input', cur_json, '--output', file_prefix, '--numSteps', str(4), '--timeStep', str(0.005)]
            subprocess.check_call(args)

            # save files
            cur_pos, _, _, faces, _, _ = igl.read_obj(file_prefix + 'mesh_simulated.obj')
            mesh_path = output_folder + '/mesh/mesh_' + str(i+1) + '.obj'
            igl.write_obj(mesh_path, cur_pos, faces)

            #save vel
            cur_vel = np.loadtxt(file_prefix + 'vel_simulated.txt')
            vel_path = output_folder + '/velocity/vel_' + str(i+1) + '.txt'
            np.savetxt(vel_path, cur_vel)

            #save edge dofs
            cur_edgedofs = np.loadtxt(file_prefix + 'edgedofs_simulated.txt')
            edge_path = output_folder + '/mesh/edgedofs_' + str(i+1) + 'txt'
            np.savetxt(edge_path, cur_edgedofs)
Пример #5
0
def main(args):
    with open(args.category_map_file_path, "r") as f:
        future2suncg_cat = json.load(f)

    filenames = os.listdir(args.FRONT_path)

    if not os.path.exists(args.save_path):
        os.mkdir(args.save_path)
    if not os.path.exists(os.path.join(args.save_path, "alilevel")):
        os.mkdir(os.path.join(args.save_path, "alilevel"))
    if not os.path.exists(os.path.join(args.save_path, "room")):
        os.mkdir(os.path.join(args.save_path, "room"))
    if not os.path.exists(os.path.join(args.save_path, "background")):
        os.mkdir(os.path.join(args.save_path, "background"))
    filenames = os.listdir('../../3D-FRONT')
    # # DEBUG
    # filenames = [
    #     '00f2a7e7-a994-4734-8104-8cb81560beb0.json',
    #     '0e02ee68-5940-49dd-bbdc-0e3667ec9e49.json',
    #     '4b663d06-fc0a-44ca-887a-d0bfc584a3ee.json',
    #     '1aab0a4b-760c-4489-b012-da6cefdca8a4.json',
    #     '129c9a2a-f789-4cd0-82c0-2b6d5293c45f.json',
    #     '5a4c9099-cf8f-4439-96ee-43736096617a.json',
    #     '5c0a1757-e14e-4901-a3a3-498537689821.json',
    #     '4c1b75c2-351b-4b6b-a7df-c867a2d9b3d6.json',
    #     '274ef293-2cf8-4c9a-8125-814f91d0bc83.json',
    #     '641eaf99-ec77-40a6-bef8-2ff72ef2b1d1.json',
    #     '7b2fae3d-5455-4dae-b174-7643ca83b1dc.json',
    #     '06a3196e-a2a2-4952-a5c6-034afcc18e15.json',
    #     '7e07a2a4-fead-40b8-8172-a430c150b733.json',
    #     'be5538a6-455b-486f-a46a-fd03d864587e.json'
    #     ]

    for sceneIdx, filename in tqdm(enumerate(filenames)):

        # create path to save generated models of the scene
        if not os.path.exists(
                os.path.join(args.save_path, "backgroundobj", filename[:-5])):
            os.mkdir(
                os.path.join(args.save_path, "backgroundobj", filename[:-5]))
        if not os.path.exists(
                os.path.join(args.save_path, "room", filename[:-5])):
            os.mkdir(os.path.join(args.save_path, "room", filename[:-5]))
        with open(os.path.join(args.FRONT_path, filename),
                  'r',
                  encoding='utf-8') as f:
            frontJson = json.load(f)

        suncgJson = {}

        suncgJson["origin"] = frontJson["uid"]
        suncgJson["id"] = str(sceneIdx)
        suncgJson["bbox"] = {"min": [INF, INF, INF], "max": [-INF, -INF, -INF]}
        suncgJson["up"] = [0, 1, 0]
        suncgJson["front"] = [0, 0, 1]
        suncgJson["rooms"] = []

        meshList = frontJson["mesh"]
        meshes = {}

        for mesh in meshList:
            meshes[mesh["uid"]] = mesh
            xyz = np.reshape(mesh['xyz'], (-1, 3)).astype(np.float64)
            face = np.reshape(mesh['faces'], (-1, 3))
            normal = np.reshape(mesh['normal'], (-1, 3))
            uv = np.reshape(mesh['uv'], (-1, 2))
            # if future2suncg_cat[mesh["type"]] == "Object":
            if mesh["type"] in ["Window", "Door"]:
                # With respect to components of the scene, we extract windows and doors and consider them as isolate objects
                # like other furnitures, which follows the rule of SunCG dataset.
                bgopath = os.path.join(args.save_path, "backgroundobj",
                                       filename[:-5],
                                       mesh["uid"].replace('/', 'X') + ".obj")
                trimesh.Trimesh(vertices=xyz,
                                faces=face,
                                vertex_normals=normal,
                                vertex_colors=uv).export(bgopath)
                add_new_line(bgopath)

        furnitureList = frontJson["furniture"]
        furnitures = {}
        for furniture in furnitureList:
            # We add each valid furniture models to the result and ignore others.
            if "valid" in furniture and furniture["valid"]:
                furnitures[furniture["uid"]] = furniture

        scene = frontJson["scene"]
        rooms = scene["room"]

        room_obj_cnt = 0

        for roomIdx, front_room in enumerate(rooms):
            suncg_room = {
                "id": "%d_%d" % (sceneIdx, room_obj_cnt),
                "modelId": front_room["instanceid"],
                "roomTypes": [front_room["type"]],
                "bbox": {
                    "min": [INF, INF, INF],
                    "max": [-INF, -INF, -INF]
                },
                "origin": frontJson["uid"],
                "roomId": roomIdx,
                "objList": []
            }
            if not os.path.exists(
                    os.path.join(args.save_path, "room", filename[:-5])):
                os.mkdir(os.path.join(args.save_path, "room", filename[:-5]))
            wallObjs = []
            ceilObjs = []
            floorObjs = []
            room_obj_cnt += 1

            # For each meshes in the room, we roughly split them into two category, scene and objects.
            # Each furniture in the room of 3d-future dataset is categorized as objects of SunCG dataset,
            # as well as windows and doors of 3d-future dataset. The other models of the same category
            # is merged into one model and considered as the scene of SunCG dataset.
            for childIdx, child in enumerate(front_room["children"]):
                if child["ref"] not in meshes and child[
                        "ref"] not in furnitures:
                    continue
                if child[
                        "ref"] in meshes:  # and future2suncg_cat[meshes[child["ref"]]["type"]] != "Object":
                    if future2suncg_cat[meshes[child["ref"]]
                                        ["type"]] == "Wall":
                        Objs = wallObjs
                    elif future2suncg_cat[meshes[child["ref"]]
                                          ["type"]] == "Floor":
                        Objs = floorObjs
                    elif future2suncg_cat[meshes[child["ref"]]
                                          ["type"]] == "Ceil":
                        Objs = ceilObjs
                    else:
                        # assert False
                        Objs = wallObjs

                    mesh = meshes[child["ref"]]
                    vs = np.reshape(mesh['xyz'], (-1, 3)).astype(np.float64)
                    face = np.reshape(mesh['faces'], (-1, 3))
                    normal = np.reshape(mesh['normal'], (-1, 3))
                    uv = np.reshape(mesh['uv'], (-1, 2))
                    pos = child['pos']
                    rot = child['rot']
                    scale = child['scale']
                    vs = vs.astype(np.float64) * scale
                    ref = [0, 0, 1]
                    axis = np.cross(ref, rot[1:])
                    theta = np.arccos(np.dot(ref, rot[1:])) * 2
                    if np.sum(axis) != 0 and not math.isnan(theta):
                        R = rotation_matrix(axis, theta)
                        vs = np.transpose(vs)
                        vs = np.matmul(R, vs)
                        vs = np.transpose(vs)
                    vs = vs + pos
                    Objs.append(
                        trimesh.Trimesh(vertices=vs,
                                        faces=face,
                                        vertex_normals=normal,
                                        vertex_colors=uv))

                    if meshes[child["ref"]]["type"] not in ['Window', "Door"]:
                        # If this mesh is a window or door, we collect it and process later.
                        continue
                # We create a object in the form of SunCG dataset.
                suncg_obj = {
                    "id":
                    "%d_%d" % (sceneIdx, room_obj_cnt),
                    "type":
                    "Object",
                    "modelId":
                    meshes[child["ref"]]["uid"].replace('/', 'X')
                    if child["ref"] in meshes else
                    furnitures[child["ref"]]["jid"],
                    "bbox": {
                        "min": [INF, INF, INF],
                        "max": [-INF, -INF, -INF]
                    },
                    "translate":
                    child["pos"],
                    "scale":
                    child["scale"],
                    "rotate":
                    quaternion_to_euler(child["rot"]),
                    "rotateOrder":
                    "XYZ",
                    "orient":
                    quaternion_to_euler(child["rot"])[1],
                    "coarseSemantic":
                    meshes[child["ref"]]["type"] if child["ref"] in meshes else
                    furnitures[child["ref"]]["category"],
                    "roomId":
                    roomIdx
                }
                suncg_obj['orient'] = orient33(
                    euler_to_matrix(suncg_obj['rotate'][0],
                                    suncg_obj['rotate'][1],
                                    suncg_obj['rotate'][2]))
                # convert modelId in consistent with the platform;
                if suncg_obj['modelId'] in ali_to_sk:
                    suncg_obj['modelId'] = ali_to_sk[suncg_obj['modelId']]
                if suncg_obj['modelId'] not in obj_coarse_semantic:
                    suncg_obj['inDatabase'] = False
                room_obj_cnt += 1
                obj_path = None
                if child["ref"] in meshes:
                    obj_path = os.path.join(
                        args.save_path, "backgroundobj", filename[:-5],
                        meshes[child["ref"]]["uid"].replace('/', 'X') + ".obj")
                if child["ref"] in furnitures:
                    obj_path = os.path.join(args.FUTURE_path,
                                            furnitures[child["ref"]]["jid"],
                                            "raw_model.obj")
                assert obj_path is not None
                assert os.path.exists(obj_path)

                # some .obj files are not provided by ali, so here we need to skip them;
                try:
                    v, vt, _, faces, ftc, _ = igl.read_obj(obj_path)
                except Exception as e:
                    print(e)
                    continue
                # print("???")
                # sys.stdout,sys.stderr = stdout,stderr

                # We convert the coordinate representation of 3d-future models to the form of suncg coordinate.
                pos, rot, scale = child["pos"], child["rot"], child["scale"]
                v = v.astype(np.float64) * scale
                ref = [0, 0, 1]
                axis = np.cross(ref, rot[1:])
                theta = np.arccos(np.dot(ref, rot[1:])) * 2
                if np.sum(axis) != 0 and not math.isnan(theta):
                    R = rotation_matrix(axis, theta)
                    v = np.transpose(v)
                    v = np.matmul(R, v)
                    v = np.transpose(v)
                v = v + pos
                assert v.shape[1:] == (3, )
                lb = v.min(axis=0)
                ub = v.max(axis=0)
                suncg_obj["bbox"]["min"] = list(lb)
                suncg_obj["bbox"]["max"] = list(ub)
                suncg_room["objList"].append(suncg_obj)

                suncg_room["bbox"]["min"] = Min3d(suncg_room["bbox"]["min"],
                                                  suncg_obj["bbox"]["min"])
                suncg_room["bbox"]["max"] = Max3d(suncg_room["bbox"]["max"],
                                                  suncg_obj["bbox"]["max"])

            # adding a new line is because of a bug of three.js library...
            wfcroot = os.path.join(args.save_path, "room", filename[:-5],
                                   front_room["instanceid"])
            # We merge the components of the scene into three models, including wall, floor and ceil.
            if len(wallObjs) > 0:
                tmp = trimesh.util.concatenate(wallObjs)
                tmp.vertex_normals
                tmp.export(wfcroot + "w.obj")
                add_new_line(wfcroot + "w.obj")
            if len(floorObjs) > 0:
                tmp = trimesh.util.concatenate(floorObjs)
                tmp.vertex_normals
                tmp.export(wfcroot + "f.obj")
                add_new_line(wfcroot + "f.obj")

            if len(ceilObjs) > 0:
                tmp = trimesh.util.concatenate(ceilObjs)
                tmp.vertex_normals
                tmp.export(wfcroot + "c.obj")
                add_new_line(wfcroot + "c.obj")

            # if not os.path.exists(os.path.join(args.save_path,"room_alipart",filename[:-5])):
            #     os.makedirs(os.path.join(args.save_path,"room_alipart",filename[:-5]))
            # allcwfs = wallObjs + floorObjs + ceilObjs
            # allcwfroot = os.path.join(args.save_path,"room_alipart",filename[:-5])
            # for obj in allcwfs:
            #     obj.export(allcwfroot + f'{} + ')

            suncgJson["rooms"].append(suncg_room)
            suncgJson["bbox"]["min"] = Min3d(suncgJson["bbox"]["min"],
                                             suncg_room["bbox"]["min"])
            suncgJson["bbox"]["max"] = Max3d(suncgJson["bbox"]["max"],
                                             suncg_room["bbox"]["max"])

        with open(os.path.join(args.save_path, "alilevel", filename),
                  "w") as f:
            json.dump(suncgJson, f)
Пример #6
0
def main():
    try:
        V, F, _, _ = mio.read_obj('nonexistent_file.obj')
    except FileNotFoundError:
        print('Successfully failed when nonexistent file is given')

    print('v only')
    V, F, VT, FT, VN, FN = mio.read_obj('resource/v.obj')
    print(V.shape)
    print(V)
    print(F.shape)
    print(F)
    print(VT.shape)
    print(VT)
    print(FT.shape)
    print(FT)
    print(VN.shape)
    print(VN)
    print(FN.shape)
    print(FN)

    print('v+vt')
    V, F, VT, FT, VN, FN = mio.read_obj('resource/v_vt.obj')
    print(V.shape)
    print(V)
    print(F.shape)
    print(F)
    print(VT.shape)
    print(VT)
    print(FT.shape)
    print(FT)
    print(VN.shape)
    print(VN)
    print(FN.shape)
    print(FN)

    print('v+vn')
    V, F, VT, FT, VN, FN = mio.read_obj('resource/v_vn.obj')
    print(V.shape)
    print(V)
    print(F.shape)
    print(F)
    print(VT.shape)
    print(VT)
    print(FT.shape)
    print(FT)
    print(VN.shape)
    print(VN)
    print(FN.shape)
    print(FN)

    print('v+vt+vn')
    V, F, VT, FT, VN, FN = mio.read_obj('resource/v_vt_vn.obj')
    print(V.shape)
    print(V)
    print(F.shape)
    print(F)
    print(VT.shape)
    print(VT)
    print(FT.shape)
    print(FT)
    print(VN.shape)
    print(VN)
    print(FN.shape)
    print(FN)

    print('wow_tex.obj with texture')
    mio.write_obj('wow_tex.obj', V, F, VT, FT, VN, FN, 'wow_tex.jpg')

    if IGL_FOUND:
        # On Ryzen 7 3950x
        # cython: 9.520554542541504 ms
        # igl(C++): 21.706414222717285 ms
        print('benchmark-read')
        start = time.time()
        for i in range(10):
            mio.read_obj('resource/v_vt_vn.obj')
        end = time.time()
        print('cython: {} ms'.format((end - start) * 100))
        start = time.time()
        for i in range(10):
            igl.read_obj('resource/v_vt_vn.obj')
        end = time.time()
        print('igl: {} ms'.format((end - start) * 100))

        # On Ryzen 7 3950x
        # cython: 8.391046524047852 ms
        # igl(C++): 10.899710655212402 ms
        print('benchmark-write')
        start = time.time()
        for i in range(10):
            mio.write_obj('resource/buffer.obj', V, F)
        end = time.time()
        print('cython: {} ms'.format((end - start) * 100))
        start = time.time()
        for i in range(10):
            igl.write_obj('resource/buffer.obj', V, F)
        end = time.time()
        print('igl: {} ms'.format((end - start) * 100))
Пример #7
0
def main(args):
    with open(args.category_map_file_path, "r") as f:
        future2suncg_cat = json.load(f)

    filenames = os.listdir(args.FRONT_path)

    if not os.path.exists(args.save_path):
        os.mkdir(args.save_path)
    if not os.path.exists(os.path.join(args.save_path, "alilevel")):
        os.mkdir(os.path.join(args.save_path, "alilevel"))
    if not os.path.exists(os.path.join(args.save_path, "room")):
        os.mkdir(os.path.join(args.save_path, "room"))
    if not os.path.exists(os.path.join(args.save_path, "background")):
        os.mkdir(os.path.join(args.save_path, "background"))
    filenames = os.listdir('../../3D-FRONT')
    filenames = [
        '00a4ff0c-ec69-4202-9420-cc8536ffffe0.json',
        # '0e02ee68-5940-49dd-bbdc-0e3667ec9e49.json',
        # '4b663d06-fc0a-44ca-887a-d0bfc584a3ee.json',
        # '1aab0a4b-760c-4489-b012-da6cefdca8a4.json',
        # '129c9a2a-f789-4cd0-82c0-2b6d5293c45f.json',
        # '5a4c9099-cf8f-4439-96ee-43736096617a.json',
        # '5c0a1757-e14e-4901-a3a3-498537689821.json',
        # '4c1b75c2-351b-4b6b-a7df-c867a2d9b3d6.json',
        # '274ef293-2cf8-4c9a-8125-814f91d0bc83.json',
        # '641eaf99-ec77-40a6-bef8-2ff72ef2b1d1.json',
        # '7b2fae3d-5455-4dae-b174-7643ca83b1dc.json',
        # '06a3196e-a2a2-4952-a5c6-034afcc18e15.json',
        # '7e07a2a4-fead-40b8-8172-a430c150b733.json',
        # 'be5538a6-455b-486f-a46a-fd03d864587e.json'
    ]
    filenames = os.listdir('../../3D-FRONT')[277:]

    for sceneIdx, filename in tqdm(enumerate(filenames)):

        if not os.path.exists(
                os.path.join(args.save_path, "backgroundobj", filename[:-5])):
            os.mkdir(
                os.path.join(args.save_path, "backgroundobj", filename[:-5]))
        if not os.path.exists(
                os.path.join(args.save_path, "room", filename[:-5])):
            os.mkdir(os.path.join(args.save_path, "room", filename[:-5]))
        with open(os.path.join(args.FRONT_path, filename),
                  'r',
                  encoding='utf-8') as f:
            # 打开3D-FRONT每个json文件
            frontJson = json.load(f)

        suncgJson = {}

        suncgJson["origin"] = frontJson["uid"]
        suncgJson["id"] = str(sceneIdx)
        suncgJson["bbox"] = {"min": [INF, INF, INF], "max": [-INF, -INF, -INF]}
        suncgJson["up"] = [0, 1, 0]
        suncgJson["front"] = [0, 0, 1]
        suncgJson["rooms"] = []

        meshList = frontJson["mesh"]
        meshes = {}

        for mesh in meshList:
            meshes[mesh["uid"]] = mesh
            xyz = np.reshape(mesh['xyz'], (-1, 3)).astype(np.float64)
            face = np.reshape(mesh['faces'], (-1, 3))
            # if future2suncg_cat[mesh["type"]] == "Object":
            if mesh["type"] in ["Window", "Door"]:
                bgopath = os.path.join(args.save_path, "backgroundobj",
                                       filename[:-5],
                                       mesh["uid"].replace('/', 'X') + ".obj")
                trimesh.Trimesh(xyz, face).export(bgopath)
                add_new_line(bgopath)

        furnitureList = frontJson["furniture"]
        furnitures = {}
        for furniture in furnitureList:
            if "valid" in furniture and furniture["valid"]:
                furnitures[furniture["uid"]] = furniture

        scene = frontJson["scene"]
        rooms = scene["room"]

        room_obj_cnt = 0

        for roomIdx, front_room in enumerate(rooms):
            suncg_room = {
                "id": "%d_%d" % (sceneIdx, room_obj_cnt),
                "modelId": front_room["instanceid"],
                "roomTypes": [front_room["type"]],
                "bbox": {
                    "min": [INF, INF, INF],
                    "max": [-INF, -INF, -INF]
                },
                "origin": frontJson["uid"],
                "roomId": roomIdx,
                "objList": []
            }
            if not os.path.exists(
                    os.path.join(args.save_path, "room", filename[:-5])):
                os.mkdir(os.path.join(args.save_path, "room", filename[:-5]))
            wallObjs = []
            ceilObjs = []
            floorObjs = []
            room_obj_cnt += 1
            for childIdx, child in enumerate(front_room["children"]):
                if child["ref"] not in meshes and child[
                        "ref"] not in furnitures:
                    continue
                if child[
                        "ref"] in meshes:  # and future2suncg_cat[meshes[child["ref"]]["type"]] != "Object":
                    if future2suncg_cat[meshes[child["ref"]]
                                        ["type"]] == "Wall":
                        Objs = wallObjs
                    elif future2suncg_cat[meshes[child["ref"]]
                                          ["type"]] == "Floor":
                        Objs = floorObjs
                    elif future2suncg_cat[meshes[child["ref"]]
                                          ["type"]] == "Ceil":
                        Objs = ceilObjs
                    else:
                        # assert False
                        Objs = wallObjs

                    mesh = meshes[child["ref"]]
                    vs = np.reshape(mesh["xyz"], (-1, 3))
                    faces = np.reshape(mesh["faces"], (-1, 3))
                    pos = child['pos']
                    rot = child['rot']
                    scale = child['scale']
                    vs = vs.astype(np.float64) * scale
                    ref = [0, 0, 1]
                    axis = np.cross(ref, rot[1:])
                    theta = np.arccos(np.dot(ref, rot[1:])) * 2
                    if np.sum(axis) != 0 and not math.isnan(theta):
                        R = rotation_matrix(axis, theta)
                        vs = np.transpose(vs)
                        vs = np.matmul(R, vs)
                        vs = np.transpose(vs)
                    vs = vs + pos
                    Objs.append(trimesh.Trimesh(vs, faces))
                    # keep windows and door in both wall meshes and suncg objects;
                    if meshes[child["ref"]]["type"] not in ['Window', "Door"]:
                        continue
                suncg_obj = {
                    "id":
                    "%d_%d" % (sceneIdx, room_obj_cnt),
                    "type":
                    "Object",
                    "modelId":
                    meshes[child["ref"]]["uid"].replace('/', 'X')
                    if child["ref"] in meshes else
                    furnitures[child["ref"]]["jid"],
                    "bbox": {
                        "min": [INF, INF, INF],
                        "max": [-INF, -INF, -INF]
                    },
                    "translate":
                    child["pos"],
                    "scale":
                    child["scale"],
                    "rotate":
                    quaternion_to_euler(child["rot"]),
                    "rotateOrder":
                    "XYZ",
                    "orient":
                    quaternion_to_euler(child["rot"])[1],
                    "coarseSemantic":
                    meshes[child["ref"]]["type"] if child["ref"] in meshes else
                    furnitures[child["ref"]]["category"],
                    "roomId":
                    roomIdx
                }
                # convert modelId in consistent with the platform;
                if suncg_obj['modelId'] in ali_to_sk:
                    suncg_obj['modelId'] = ali_to_sk[suncg_obj['modelId']]
                room_obj_cnt += 1
                obj_path = None
                if child["ref"] in meshes:
                    obj_path = os.path.join(
                        args.save_path, "backgroundobj", filename[:-5],
                        meshes[child["ref"]]["uid"].replace('/', 'X') + ".obj")
                if child["ref"] in furnitures:
                    obj_path = os.path.join(args.FUTURE_path,
                                            furnitures[child["ref"]]["jid"],
                                            "raw_model.obj")
                assert obj_path is not None
                assert os.path.exists(obj_path)

                # 屏蔽warning信息,下面的方法好像屏蔽不了,日
                # stdout,stderr= sys.stdout,sys.stderr
                # with open('/dev/null',"w+") as null:
                #     sys.stdout,sys.stderr = null,null
                # some .obj files are not provided by ali, so here we need to skip them;
                try:
                    v, vt, _, faces, ftc, _ = igl.read_obj(obj_path)
                except Exception as e:
                    print(e)
                    continue
                # print("???")
                # sys.stdout,sys.stderr = stdout,stderr

                pos, rot, scale = child["pos"], child["rot"], child["scale"]
                v = v.astype(np.float64) * scale
                ref = [0, 0, 1]
                axis = np.cross(ref, rot[1:])
                theta = np.arccos(np.dot(ref, rot[1:])) * 2
                if np.sum(axis) != 0 and not math.isnan(theta):
                    R = rotation_matrix(axis, theta)
                    v = np.transpose(v)
                    v = np.matmul(R, v)
                    v = np.transpose(v)
                v = v + pos
                assert v.shape[1:] == (3, )
                lb = v.min(axis=0)
                ub = v.max(axis=0)
                suncg_obj["bbox"]["min"] = list(lb)
                suncg_obj["bbox"]["max"] = list(ub)
                suncg_room["objList"].append(suncg_obj)

                suncg_room["bbox"]["min"] = Min3d(suncg_room["bbox"]["min"],
                                                  suncg_obj["bbox"]["min"])
                suncg_room["bbox"]["max"] = Max3d(suncg_room["bbox"]["max"],
                                                  suncg_obj["bbox"]["max"])

            # adding a new line is because of a bug of three.js library...
            wfcroot = os.path.join(args.save_path, "room", filename[:-5],
                                   front_room["instanceid"])
            if len(wallObjs) > 0:
                trimesh.util.concatenate(wallObjs).export(wfcroot + "w.obj")
                add_new_line(wfcroot + "w.obj")

            if len(floorObjs) > 0:
                trimesh.util.concatenate(floorObjs).export(wfcroot + "f.obj")
                add_new_line(wfcroot + "f.obj")

            if len(ceilObjs) > 0:
                trimesh.util.concatenate(ceilObjs).export(wfcroot + "c.obj")
                add_new_line(wfcroot + "c.obj")

            suncgJson["rooms"].append(suncg_room)
            suncgJson["bbox"]["min"] = Min3d(suncgJson["bbox"]["min"],
                                             suncg_room["bbox"]["min"])
            suncgJson["bbox"]["max"] = Max3d(suncgJson["bbox"]["max"],
                                             suncg_room["bbox"]["max"])

        with open(os.path.join(args.save_path, "alilevel", filename),
                  "w") as f:
            json.dump(suncgJson, f)
Пример #8
0
            room_id = r['instanceid']
            meshes = []
            if not os.path.exists(args.save_path + '/' + m[:-5] + '/' +
                                  room_id):
                os.mkdir(args.save_path + '/' + m[:-5] + '/' + room_id)
            children = r['children']
            number = 1
            for c in children:

                ref = c['ref']
                type = 'f'
                try:
                    idx = model_uid.index(ref)
                    if os.path.exists(args.future_path + '/' + model_jid[idx]):
                        v, vt, _, faces, ftc, _ = igl.read_obj(
                            args.future_path + '/' + model_jid[idx] +
                            '/raw_model.obj')
                        # bbox = np.max(v, axis=0) - np.min(v, axis=0)
                        # s = bbox / model_bbox[idx]
                        # v = v / s
                except:
                    try:
                        idx = mesh_uid.index(ref)
                    except:
                        continue
                    v = mesh_xyz[idx]
                    faces = mesh_faces[idx]
                    type = 'm'

                pos = c['pos']
                rot = c['rot']