示例#1
0
def get_sheets_authentication():
    """
    Gets the json authentication file from amazon s3 and saves it on the local machine at the filepath
    :param client: The name of the client for the sheet
    :param filepath: The filepath where the authentication json will be saved
    :return: Returns the filepath to the local copy of the authentication file
    """
    # TODO - change this to read the ENV Variable once that's more stable/consistant.
    USER_GLOBALS = load_json(
        os.path.join(os.path.expanduser('~\Documents'), 'cglumberjack',
                     'user_globals.json'))
    GLOBALS = load_json(USER_GLOBALS['globals'])
    filepath = GLOBALS['sync']['syncthing']['sheets_config_path']
    if filepath.endswith('.json'):
        url = GLOBALS['sync']['syncthing']['sync_thing_url']
        r = requests.get(url, allow_redirects=True)
        with open(filepath, 'w+') as f:
            f.write(r.content)
        return filepath
    else:
        print(
            'ERROR in sheets_config_path globals, %s does not match client.json format'
            % filepath)


# if __name__ == '__main__':
#     # sheet = authorize_sheets('LONE_COCONUT_SYNC_THING', 'C:\\Users\\Molta\\Desktop\\client.json')
#     # k = does_id_exist('2SB5KDS-FHJ5MEH-RJKY2QR-FLJ6S3R-4KQHBCW-2YZCRJJ-LULS7LQ-NUGWDAB', sheet)
#     # print k
#     # l = does_name_exist('DESKTOP-CEDFLDG', sheet)
#     # print l
示例#2
0
def authorize_sheets():
    """
    Authorizes api calls to the google sheet
    :param filepath: Path to the sheets json authentication file
    :param sheet_name: Title of the sheet being accessed
    :return: A google sheet object
    """
    import gspread
    scope = [
        'https://www.googleapis.com/auth/spreadsheets',
        'https://www.googleapis.com/auth/spreadsheets',
        'https://www.googleapis.com/auth/drive'
    ]
    user_globals = load_json(
        os.path.join(os.path.expanduser(r'~\Documents'), 'cglumberjack',
                     'user_globals.json'))
    globals_ = load_json(user_globals['globals'])
    sheet_name = globals_['sync']['syncthing']['sheets_name']
    client_file = globals_['sync']['syncthing']['sheets_config_path']
    creds = ServiceAccountCredentials.from_json_keyfile_name(
        client_file, scope)
    client = gspread.authorize(creds)
    sheet = client.open(sheet_name).sheet1

    return sheet
示例#3
0
def get_user_globals():
    # do they have an env variable
    try:
        user_globals_path = os.getenv('cgl_user_globals')
        if os.path.exists(user_globals_path):
            return load_json(user_globals_path)
    except TypeError:
        print('No cgl_user_globals ENV variable found. Assuming location.')
        return load_json(
            os.path.join(os.path.expanduser('~\\Documents'), 'cglumberjack',
                         'user_globals.json'))
示例#4
0
 def __init__(self, company=None, project=None, proj_management=None):
     self.user_config = os.path.join(os.path.expanduser('~'), 'Documents',
                                     'cglumberjack', 'user_globals.json')
     print self.user_config
     if not os.path.exists(self.user_config):
         logging.info('User Config Not Found: %s' % self.user_config)
         return
     user_globals = load_json(self.user_config)
     if not os.path.exists(user_globals['globals']):
         logging.info('No Globals Found at %s' % self.globals)
         return
     self.globals = load_json(user_globals['globals'])
     print self.globals
     Configuration.LOADED_CONFIG['app'] = self.globals
示例#5
0
 def edit_globals_paths(self):
     globals = read_write.load_json(self.globals_path)
     # change the stuff
     globals["paths"]["code_root"] = self.default_code_root
     globals["paths"]["root"] = self.default_root
     globals["paths"]["cgl_tools"] = os.path.join(self.default_root,
                                                  '_config', 'cgl_tools')
     # TODO this shouldn't be used
     globals["paths"]["globals"] = os.path.join(self.default_root,
                                                '_config', 'globals.json')
     # TODO this should be a env_variable
     globals["paths"]["user_globals"] = self.default_user_globals
     globals["sync"]["syncthing"]["sheets_config_path"] = os.path.join(
         self.default_root, '_config', 'client.json')
     # TODO this should exist
     globals["account_info"]["globals_path"] = os.path.join(
         self.default_root, '_config', 'globals.json')
     # TODO - This shouldn't exist
     globals["cg_lumberjack_dir"] = os.path.join(self.default_root,
                                                 '_config')
     # TODO - it'd be nice to double check all the sofwtare paths and see if there are newer versions on disk, this will help a ton.
     globals_dir = os.path.dirname(globals["paths"]["globals"])
     if not os.path.exists(globals_dir):
         os.makedirs(globals_dir)
     print 'Saving Globals To: %s' % globals["paths"]["globals"]
     read_write.save_json(globals["paths"]["globals"], globals)
示例#6
0
 def load_globals(self):
     globals_line_edit = self.widget_dict['globals']['line_edit']
     if globals_line_edit.text():
         globals_ = globals_line_edit.text()
         self.global_config = read_write.load_json(globals_)
         # self.globals_tree_widget.load_dictionary(self.global_config)
         # self.globals_tree_widget.show()
     return self.global_config
def write_anim(outFile=None):
    from cgl.plugins.blender.alchemy import scene_object, PathObject, import_file
    from cgl.core.utils.read_write import load_json, save_json
    import bpy
    from pathlib import Path

    if outFile == None:
        outFile = scene_object().copy(ext='json').path_root
    data = {}

    data = load_json(outFile)

    valid_rigs = []

    for obj in bpy.data.objects:

        if 'proxy' in obj.name:
            animation_data = obj.animation_data
            if animation_data:
                action = animation_data.action
                if action:
                    valid_rigs.append(obj)

    for obj in valid_rigs:
        name = obj.name.split('_proxy')[0]
        print('___________' + name)
        #            blender_transform = np.array(obj.matrix_world).tolist()
        blender_transform = [
            obj.matrix_world.to_translation().x,
            obj.matrix_world.to_translation().y,
            obj.matrix_world.to_translation().z,
            obj.matrix_world.to_euler().x,
            obj.matrix_world.to_euler().y,
            obj.matrix_world.to_euler().z,
            obj.matrix_world.to_scale().x,
            obj.matrix_world.to_scale().y,
            obj.matrix_world.to_scale().z
        ]
        libraryPath = bpy.path.abspath(
            obj.proxy_collection.instance_collection.library.filepath)
        filename = Path(bpy.path.abspath(libraryPath)).__str__()
        libObject = PathObject(filename)

    sourcePath = alc.scene_object()

    data[name] = {
        'name': libObject.asset,
        'source_path': libObject.path,
        'blender_transform': blender_transform,
        'blender_action': obj.animation_data.action.name,
        'blender_action_path': sourcePath.path
    }

    save_json(outFile, data)

    print(data)
    return (outFile)
def read_relationship(filepath, obj_a=None, obj_b=None, bones=False):
    """reads the relationship matrix from filepath

    Args:
        filepath ([type]): [description]
        obj_a ([type], optional): [description]. Defaults to None.
        obj_b ([type], optional): [description]. Defaults to None.
        bones (bool, optional): [description]. Defaults to False.
    """
    obj_a, obj_b = get_selection_order(obj_a, obj_b, bones)

    print(obj_a, obj_b)

    if bones is False:

        obj_a_mat = obj_a.matrix_world
        obj_b_mat = obj_b.matrix_world

    else:

        obj_a_mat = obj_a.bone.matrix_local
        obj_obj_b_mat = obj_b.bone.matrix_local

    identity = Matrix((([1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0,
                                                                   1])))
    matrix = load_json(filepath)
    current = '{} {}'.format(obj_a.name, obj_b.name)

    c = matrix[current]

    difference = unflatten(matrix[current])

    if bones is False:

        obj_a.matrix_world = obj_b.matrix_world @ difference
        print(obj_b.matrix_world)

    else:

        new_matrix = obj_a.matrix @ difference

    print(obj_a.name, obj_b.name)
    print('DIFFERENCE')
    print(difference)

    print(obj_a.name)
    print(obj_a.matrix)

    print(obj_b.name)
    print(obj_b.matrix)

    print('NEW MATRIX')
    print(new_matrix)

    obj_b.matrix = new_matrix

    reset_modifiers(obj_b)
示例#9
0
 def load_globals_template(self):
     code_root_line_edit = self.widget_dict['code_root']['line_edit']
     if code_root_line_edit.text():
         globals_ = os.path.join(code_root_line_edit.text(), 'cgl', 'cfg',
                                 'globals_template.json')
         self.global_config = read_write.load_json(globals_)
         # elf.globals_tree_widget.load_dictionary(self.global_config)
         # self.globals_tree_widget.show()
         return self.global_config
     else:
         print 'Code Root Not Defined'
         return None
示例#10
0
def read_materials(path_object=None):
    """

    :type path_object: object
    """
    from cgl.plugins.blender import alchemy as alc
    from cgl.core.utils.read_write import load_json
    """
    Reads the materials on the shdr task from defined from a json file
    :return:
    """
    import bpy
    if path_object is None:
        path_object = alc.scene_object()

    shaders = path_object.copy(task='shd',
                               user='******',
                               set_proper_filename=True).latest_version()
    outFile = shaders.copy(ext='json').path_root

    data = load_json(outFile)

    for obj in data.keys():
        object = bpy.data.objects[obj]
        # data = object.data
        index = 0

        for material in data[obj].keys():

            if material not in bpy.data.materials:
                alc.import_file(shaders.path_root,
                                collection_name=material,
                                type='MATERIAL',
                                linked=False)

            if material not in object.data.materials:
                object.data.materials.append(bpy.data.materials[material])

            face_list = data[obj][material]

            for face in face_list:
                object.data.polygons[face].select = True

            bpy.ops.object.mode_set(mode='EDIT')
            bpy.context.tool_settings.mesh_select_mode = [False, False, True]
            object.active_material_index = index
            bpy.ops.object.material_slot_assign()
            bpy.ops.mesh.select_all(action='DESELECT')
            bpy.ops.object.mode_set(mode='OBJECT')
            index += 1
def save_relationship(filepath, obj_a=None, obj_b=None, bones=False):
    if bones is False:
        obj_a, obj_b = get_selection_order(obj_a, obj_b, bones)
        obj_a_mat = obj_a.matrix
        obj_b_mat = obj_b.matrix

    else:
        obj_a, obj_b = get_selection_order(obj_a, obj_b, bones)
        obj_a_mat = obj_a.matrix
        obj_b_mat = obj_b.matrix
        obj_a_mat_world = obj_a.matrix
        obj_b_mat_world = obj_b.matrix
        difference_local = obj_b_mat_world.inverted() @ obj_a_mat_world

    difference = obj_b_mat.inverted() @ obj_a_mat

    if bones:
        print('difference world')
        print(obj_a_mat_world)
        print(obj_b_mat_world)
        difference = obj_a_mat_world.inverted() @ obj_b_mat_world

    print('difference')
    print(difference)

    data = {}
    data.update({'{} {}'.format(obj_a.name, obj_b.name): flatten(difference)})
    data.update({
        '{} {}'.format(obj_b.name, obj_a.name):
        flatten(difference.inverted())
    })

    updated_json = data
    if isfile(filepath):
        print('file_ existis')
        current_json = load_json(filepath)
        print(current_json)
    else:
        current_json = {}

    if current_json:
        updated_json = {**data, **current_json}
        print('file updated')
        print(updated_json)

    save_json(filepath, updated_json)
示例#12
0
def parent_linked_environment_assets(library):
    import os
    env = library
    bpy.ops.file.make_paths_absolute()
    env_path = alc.PathObject(env.filepath)
    env_layout = env_path.copy(ext='json').path_root
    asset_collection = create_collection('env')

    if os.path.isfile(env_layout):
        data = load_json(env_layout)
        env_object_collection = create_environment_objects_collection(
            env_path.asset)

        for i in data:
            name = data[i]['name']
            print(44444444444)
            print(env_object_collection)
            move_to_collection(i, env_object_collection)
        print(env_path.asset)
        move_to_collection(env_path.asset, bpy.data.collections['env'])
示例#13
0
def remove_linked_environment_dependencies(library):
    env = library
    bpy.ops.file.make_paths_absolute()
    env_path = alc.PathObject(env.filepath)
    env_layout = env_path.copy(ext='msd').path_root

    data = load_json(env_layout)

    for i in data:
        print(i)
        name = data[i]['name']

        if i in bpy.data.objects:
            obj = bpy.data.objects[i]
            unlink_asset(obj)
    try:
        env_asset_collection = bpy.data.collections['{}_assets'.format(env_path.asset)]
        bpy.data.collections.remove(env_asset_collection)
    except KeyError:
        pass
示例#14
0
    def __init__(self,
                 parent=None,
                 company='',
                 config_dict=None,
                 root=r"C:\CGLUMBERJACK\COMPANIES"):
        QtWidgets.QDialog.__init__(self, parent)
        self.app_config = config_dict
        self.proj_management_label = QtWidgets.QLabel('Project Management')
        self.contents = {}
        self.company = company
        self.global_config = {}
        self.root = root
        self.user_name = self.get_user_name()
        self.api_key = ''
        self.api_script = ''
        self.api_user = ''
        self.project_management = ''
        self.api_server = ''
        self.setWindowTitle('Create Globals')

        layout = QtWidgets.QVBoxLayout(self)
        self.project_management_label = QtWidgets.QLabel('Project Management:')
        self.project_management_label.setProperty('class', 'ultra_title')
        self.proj_management_label = QtWidgets.QLabel('Software:')
        self.proj_management_combo = QtWidgets.QComboBox()
        self.proj_management_combo.addItems(
            ['lumbermill', 'ftrack', 'shotgun'])
        # self.red_palette, self.green_palette, self.black_palette = define_palettes()

        self.user_email_label = QtWidgets.QLabel('User Email:')
        self.user_email_line_edit = QtWidgets.QLineEdit()
        self.user_name_label = QtWidgets.QLabel('User Name:')
        self.user_name_line_edit = QtWidgets.QLineEdit()
        self.user_name_line_edit.setText(self.user_name)
        self.globals_label = QtWidgets.QLabel('Globals')
        self.globals_label.setProperty('class', 'ultra_title')
        self.paths_label = QtWidgets.QLabel('Paths')
        self.paths_label.setProperty('class', 'ultra_title')

        self.server_label = QtWidgets.QLabel('server url:')
        self.api_key_label = QtWidgets.QLabel('api key:')
        self.api_user_label = QtWidgets.QLabel('api user:'******'api script:')
        self.root_label = QtWidgets.QLabel('Production Root:')
        self.server_line_edit = QtWidgets.QLineEdit()
        self.api_key_line_edit = QtWidgets.QLineEdit()
        self.api_user_line_edit = QtWidgets.QLineEdit()
        self.api_script_line_edit = QtWidgets.QLineEdit()

        self.choose_folder_button = QtWidgets.QToolButton()
        self.choose_folder_button.setText('...')
        self.choose_root = QtWidgets.QToolButton()
        self.choose_root.setText('...')
        self.choose_code_root_button = QtWidgets.QToolButton()
        self.choose_code_root_button.setText('...')

        self.proj_man_grid = QtWidgets.QGridLayout()
        self.proj_man_grid.addWidget(self.proj_management_label, 0, 0)
        self.proj_man_grid.addWidget(self.proj_management_combo, 0, 1)
        self.proj_man_grid.addWidget(self.api_key_label, 1, 0)
        self.proj_man_grid.addWidget(self.api_key_line_edit, 1, 1)
        self.proj_man_grid.addWidget(self.api_user_label, 2, 0)
        self.proj_man_grid.addWidget(self.api_user_line_edit, 2, 1)
        self.proj_man_grid.addWidget(self.server_label, 3, 0)
        self.proj_man_grid.addWidget(self.server_line_edit, 3, 1)
        self.proj_man_grid.addWidget(self.api_script_label, 4, 0)
        self.proj_man_grid.addWidget(self.api_script_line_edit, 4, 1)
        self.proj_man_grid.addWidget(self.user_name_label, 5, 0)
        self.proj_man_grid.addWidget(self.user_name_line_edit, 5, 1)
        self.proj_man_grid.addWidget(self.user_email_label, 6, 0)
        self.proj_man_grid.addWidget(self.user_email_line_edit, 6, 1)

        self.cancel_button = QtWidgets.QPushButton('Cancel')
        self.ok_button = QtWidgets.QPushButton('Ok')
        self.button = ''
        self.ok_button.setEnabled(False)
        self.create_globals_button = QtWidgets.QPushButton('Create Globals')
        self.create_globals_button.setEnabled(False)

        # self.project_management = self.app_config['account_info']['project_management']

        button_layout = QtWidgets.QHBoxLayout()
        button_layout.addStretch(1)
        button_layout.addWidget(self.cancel_button)
        button_layout.addWidget(self.create_globals_button)
        button_layout.addWidget(self.ok_button)

        # self.globals_tree_widget = DictionaryTreeWidget({})
        this = __file__.split('cglumberjack')[0]
        if not self.app_config:
            dialog = QuickSync()
            dialog.exec_()
            globals_path = dialog.globals_path
            cgl_tools_path = dialog.cgl_tools_path
            if globals_path:
                dict_ = read_write.load_json(globals_path)
                self.inherited_globals = True
            else:
                self.inherited_globals = False
                this = __file__.split('cglumberjack')[0]
                dict_ = read_write.load_json(
                    os.path.join(this, 'cglumberjack', 'cgl', 'cfg',
                                 'globals_template.json'))
        self.proj_man_dict = dict_['project_management']
        self.path_item_widget = PathItemWidget(paths_dict=dict_['paths'],
                                               hide_on_find=True)

        if self.path_item_widget.widget_dict['root']['line_edit'].text():
            self.show_project_management_basics()
        else:
            self.hide_project_management_basics()
        self.widget_dict = self.path_item_widget.widget_dict

        layout.addWidget(self.globals_label)
        layout.addWidget(self.path_item_widget)
        layout.addWidget(self.project_management_label)
        layout.addLayout(self.proj_man_grid)
        # layout.addWidget(self.globals_tree_widget)
        # layout.addWidget(QHLine())
        layout.addLayout(button_layout)
        layout.addStretch(1)

        # self.user_globals_line_edit.setEnabled(False)
        self.proj_management_combo.currentIndexChanged.connect(
            self.on_pm_changed)
        self.path_item_widget.line_edit_changed.connect(
            self.on_line_edits_changed)
        self.ok_button.clicked.connect(self.on_ok_clicked)
        self.ok_button.hide()
        self.cancel_button.clicked.connect(self.cancel_clicked)
        self.create_globals_button.clicked.connect(
            self.on_create_globals_clicked)
        self.path_item_widget.root_set.connect(self.on_root_line_edit_set)
        self.user_email_line_edit.textChanged.connect(
            self.check_ok_to_create_globals)
        self.user_name_line_edit.textChanged.connect(
            self.check_ok_to_create_globals)
        self.proj_management_combo.currentIndexChanged.connect(
            self.check_ok_to_create_globals)
        self.get_input()

        self.hide_api_info()
        self.set_proj_man()
        self.check_user_config()
        # self.globals_tree_widget.hide()
        self.on_globals_changed()
        self.set_some_stuff()
def read_layout(outFile=None, linked=True, append=False):
    """
    Reads layout from json file
    :param outFile: path to json file
    :param linked:
    :param append: if true the files are imported in the scene
    :return:
    """
    from cgl.plugins.blender.alchemy import scene_object, PathObject, import_file_old
    from cgl.core.utils.read_write import load_json
    import bpy
    import os
    if outFile == None:
        outFileObject = scene_object().copy(
            ext='json', task='lay', set_proper_filename=True).latest_version()
        outFile = outFileObject.path_root
    # outFile = scene_object().path_root.replace(scene_object().ext, 'json')
    if os.path.isfile(outFile):

        data = load_json(outFile)

        libraries = get_layout_libraries(data)

        print('________LIBRARIES___________')

        for i in libraries:
            pathToFile = os.path.join(scene_object().root, i)
            PathObject = PathObject(pathToFile)

            print(pathToFile)

            if PathObject.filename_base in bpy.data.libraries:
                lib = bpy.data.libraries[PathObject.filename]
                bpy.data.batch_remove(ids=([lib]))
                import_file_old(PathObject.path_root,
                                linked=False,
                                append=True)
                bpy.data.ojects[PathObject.asset].select_set(True)
                bpy.ops.object.unlink_asset()
            else:
                import_file_old(PathObject.path_root,
                                linked=False,
                                append=True)

        for p in data:
            print(p)
            data_path = data[p]['source_path']
            blender_transform = data[p]['blender_transform']

            transform_data = []
            for value in blender_transform:
                transform_data.append(float(value))

            pathToFile = os.path.join(scene_object().root, data_path)
            PathObject = PathObject(pathToFile)
            obj = bpy.data.objects.new(p, None)
            bpy.context.collection.objects.link(obj)
            obj.instance_type = 'COLLECTION'
            if PathObject.asset in bpy.data.collections:

                obj.instance_collection = bpy.data.collections[
                    PathObject.asset]

                location = (transform_data[0], transform_data[1],
                            transform_data[2])
                obj.location = location

                rotation = (transform_data[3], transform_data[4],
                            transform_data[5])
                obj.rotation_euler = rotation

                scale = (transform_data[6], transform_data[7],
                         transform_data[8])
                obj.scale = scale

                if PathObject.type in [
                        'char',
                ]:

                    if append:
                        print(
                            "___________creating proxy rig for {}____________".
                            format(PathObject.asset))
                        rig = '{}_rig'.format(PathObject.asset)
                        print(rig)
                        objects = bpy.context.view_layer.objects
                        bpy.context.view_layer.objects.active = objects[
                            PathObject.asset]
                        bpy.ops.object.proxy_make(object=rig)

                        if 'blender_action_path' in data[p]:
                            anim_path = data[p]['blender_action_path']
                            path_to_anim = os.path.join(
                                scene_object().root, anim_path)
                            print(path_to_anim)
                            alc.import_file_old(
                                path_to_anim,
                                type='ANIM',
                                collection_name=data[p]['blender_action'],
                                linked=False)

            else:
                print("__________________{} not found_____________".format(
                    PathObject.path_root))
    else:
        print("_____________NO LAYOUT FOUND__________")
示例#16
0
def get_globals():
    globals_path = get_user_globals()['globals']
    if globals_path:
        return load_json(globals_path)
    else:
        print('No user_globals found at %s' % user_config())