Example #1
0
def generate_tooltip(mdata):
    col_w = 40
    if type(mdata['parameters']) == list:
        mparams = utils.params_to_dict(mdata['parameters'])
    else:
        mparams = mdata['parameters']
    t = ''
    t = writeblock(t, mdata['name'], width=col_w)
    t += '\n'

    t = writeblockm(t, mdata, key='description', pretext='', width=col_w)
    if mdata['description'] != '':
        t += '\n'

    bools = (('rig', None), ('animated', None), ('manifold', 'non-manifold'),
             ('scene', None), ('simulation', None), ('uv', None))
    for b in bools:
        if mparams.get(b[0]):
            mdata['tags'].append(b[0])
        elif b[1] != None:
            mdata['tags'].append(b[1])

    bools_data = ('adult', )
    for b in bools_data:
        if mdata.get(b) and mdata[b]:
            mdata['tags'].append(b)
    t = writeblockm(t,
                    mparams,
                    key='designer',
                    pretext='designer',
                    width=col_w)
    t = writeblockm(t,
                    mparams,
                    key='manufacturer',
                    pretext='manufacturer',
                    width=col_w)
    t = writeblockm(t,
                    mparams,
                    key='designCollection',
                    pretext='design collection',
                    width=col_w)

    # t = writeblockm(t, mparams, key='engines', pretext='engine', width = col_w)
    # t = writeblockm(t, mparams, key='model_style', pretext='style', width = col_w)
    # t = writeblockm(t, mparams, key='material_style', pretext='style', width = col_w)
    # t = writeblockm(t, mdata, key='tags', width = col_w)
    # t = writeblockm(t, mparams, key='condition', pretext='condition', width = col_w)
    # t = writeblockm(t, mparams, key='productionLevel', pretext='production level', width = col_w)
    if has(mdata, 'purePbr'):
        t = writeblockm(t, mparams, key='pbrType', pretext='pbr', width=col_w)

    t = writeblockm(t,
                    mparams,
                    key='designYear',
                    pretext='design year',
                    width=col_w)

    if has(mparams, 'dimensionX'):
        t += 'size: %s, %s, %s\n' % (fmt_length(
            mparams['dimensionX']), fmt_length(
                mparams['dimensionY']), fmt_length(mparams['dimensionZ']))
    if has(mparams, 'faceCount'):
        t += 'face count: %s, render: %s\n' % (mparams['faceCount'],
                                               mparams['faceCountRender'])

    # t = writeblockm(t, mparams, key='meshPolyType', pretext='mesh type', width = col_w)
    # t = writeblockm(t, mparams, key='objectCount', pretext='nubmber of objects', width = col_w)

    # t = writeblockm(t, mparams, key='materials', width = col_w)
    # t = writeblockm(t, mparams, key='modifiers', width = col_w)
    # t = writeblockm(t, mparams, key='shaders', width = col_w)

    if has(mparams, 'textureSizeMeters'):
        t += 'texture size: %s\n' % fmt_length(mparams['textureSizeMeters'])

    if has(mparams,
           'textureResolutionMax') and mparams['textureResolutionMax'] > 0:
        if mparams['textureResolutionMin'] == mparams['textureResolutionMax']:
            t = writeblockm(t,
                            mparams,
                            key='textureResolutionMin',
                            pretext='texture resolution',
                            width=col_w)
        else:
            t += 'tex resolution: %i - %i\n' % (
                mparams['textureResolutionMin'],
                mparams['textureResolutionMax'])

    if has(mparams, 'thumbnailScale'):
        t = writeblockm(t,
                        mparams,
                        key='thumbnailScale',
                        pretext='preview scale',
                        width=col_w)

    # t += 'uv: %s\n' % mdata['uv']
    # t += '\n'
    t = writeblockm(t, mdata, key='license', width=col_w)

    # generator is for both upload preview and search, this is only after search
    # if mdata.get('versionNumber'):
    #     # t = writeblockm(t, mdata, key='versionNumber', pretext='version', width = col_w)
    #     a_id = mdata['author'].get('id')
    #     if a_id != None:
    #         adata = bpy.context.window_manager['bkit authors'].get(str(a_id))
    #         if adata != None:
    #             t += generate_author_textblock(adata)

    # t += '\n'
    if len(t.split('\n')) < 6:
        t += '\n'
        t += get_random_tip(mdata)
        t += '\n'
    return t
Example #2
0
def timer_update():
    # this makes a first search after opening blender. showing latest assets.
    global first_time
    preferences = bpy.context.preferences.addons['blenderkit'].preferences
    if first_time:  # first time
        first_time = False
        if preferences.show_on_start or preferences.first_run:
            # TODO here it should check if there are some results, and only open assetbar if this is the case, not search.
            #if bpy.context.scene.get('search results') is None:
            search()
            preferences.first_run = False
        if preferences.tips_on_start:
            ui.get_largest_3dview()
            ui.update_ui_size(ui.active_area, ui.active_region)
            ui.add_report(text='BlenderKit Tip: ' + random.choice(rtips),
                          timeout=12,
                          color=colors.GREEN)

    check_clipboard()

    global search_threads
    # don't do anything while dragging - this could switch asset during drag, and make results list length different,
    # causing a lot of throuble.
    if len(search_threads) == 0 or bpy.context.scene.blenderkitUI.dragging:
        return 1
    for thread in search_threads:
        # TODO this doesn't check all processes when one gets removed,
        # but most of the time only one is running anyway
        if not thread[0].is_alive():
            search_threads.remove(thread)  #
            icons_dir = thread[1]
            scene = bpy.context.scene
            # these 2 lines should update the previews enum and set the first result as active.
            s = bpy.context.scene
            asset_type = thread[2]
            if asset_type == 'model':
                props = scene.blenderkit_models
                json_filepath = os.path.join(icons_dir,
                                             'model_searchresult.json')
                search_name = 'bkit model search'
            if asset_type == 'scene':
                props = scene.blenderkit_scene
                json_filepath = os.path.join(icons_dir,
                                             'scene_searchresult.json')
                search_name = 'bkit scene search'
            if asset_type == 'material':
                props = scene.blenderkit_mat
                json_filepath = os.path.join(icons_dir,
                                             'material_searchresult.json')
                search_name = 'bkit material search'
            if asset_type == 'brush':
                props = scene.blenderkit_brush
                json_filepath = os.path.join(icons_dir,
                                             'brush_searchresult.json')
                search_name = 'bkit brush search'

            s[search_name] = []

            global reports
            if reports != '':
                props.report = str(reports)
                return .2
            with open(json_filepath, 'r') as data_file:
                rdata = json.load(data_file)

            result_field = []
            ok, error = check_errors(rdata)
            if ok:
                bpy.ops.object.run_assetbar_fix_context()
                for r in rdata['results']:
                    # TODO remove this fix when filesSize is fixed.
                    # this is a temporary fix for too big numbers from the server.
                    try:
                        r['filesSize'] = int(r['filesSize'] / 1024)
                    except:
                        utils.p('asset with no files-size')
                    if r['assetType'] == asset_type:
                        if len(r['files']) > 0:
                            furl = None
                            tname = None
                            allthumbs = []
                            durl, tname = None, None
                            for f in r['files']:
                                if f['fileType'] == 'thumbnail':
                                    tname = paths.extract_filename_from_url(
                                        f['fileThumbnailLarge'])
                                    small_tname = paths.extract_filename_from_url(
                                        f['fileThumbnail'])
                                    allthumbs.append(
                                        tname
                                    )  # TODO just first thumb is used now.

                                tdict = {}
                                for i, t in enumerate(allthumbs):
                                    tdict['thumbnail_%i'] = t
                                if f['fileType'] == 'blend':
                                    durl = f['downloadUrl'].split('?')[0]
                                    # fname = paths.extract_filename_from_url(f['filePath'])
                            if durl and tname:

                                tooltip = generate_tooltip(r)
                                #for some reason, the id was still int on some occurances. investigate this.
                                r['author']['id'] = str(r['author']['id'])

                                asset_data = {
                                    'thumbnail': tname,
                                    'thumbnail_small': small_tname,
                                    # 'thumbnails':allthumbs,
                                    'download_url': durl,
                                    'id': r['id'],
                                    'asset_base_id': r['assetBaseId'],
                                    'name': r['name'],
                                    'asset_type': r['assetType'],
                                    'tooltip': tooltip,
                                    'tags': r['tags'],
                                    'can_download': r.get('canDownload', True),
                                    'verification_status':
                                    r['verificationStatus'],
                                    'author_id': r['author']['id'],
                                    # 'author': r['author']['firstName'] + ' ' + r['author']['lastName']
                                    # 'description': r['description'],
                                }
                                asset_data['downloaded'] = 0

                                # parse extra params needed for blender here
                                params = utils.params_to_dict(r['parameters'])

                                if asset_type == 'model':
                                    if params.get('boundBoxMinX') != None:
                                        bbox = {
                                            'bbox_min':
                                            (float(params['boundBoxMinX']),
                                             float(params['boundBoxMinY']),
                                             float(params['boundBoxMinZ'])),
                                            'bbox_max':
                                            (float(params['boundBoxMaxX']),
                                             float(params['boundBoxMaxY']),
                                             float(params['boundBoxMaxZ']))
                                        }

                                    else:
                                        bbox = {
                                            'bbox_min': (-.5, -.5, 0),
                                            'bbox_max': (.5, .5, 1)
                                        }
                                    asset_data.update(bbox)
                                if asset_type == 'material':
                                    asset_data[
                                        'texture_size_meters'] = params.get(
                                            'textureSizeMeters', 1.0)

                                asset_data.update(tdict)
                                if r['assetBaseId'] in scene.get(
                                        'assets used', {}).keys():
                                    asset_data['downloaded'] = 100

                                result_field.append(asset_data)

                                # results = rdata['results']
                s[search_name] = result_field
                s['search results'] = result_field
                s[search_name + ' orig'] = rdata
                s['search results orig'] = rdata
                load_previews()
                ui_props = bpy.context.scene.blenderkitUI
                if len(result_field) < ui_props.scrolloffset:
                    ui_props.scrolloffset = 0
                props.is_searching = False
                props.search_error = False
                props.report = 'Found %i results. ' % (
                    s['search results orig']['count'])
                if len(s['search results']) == 0:
                    tasks_queue.add_task(
                        (ui.add_report, ('No matching results found.', )))

            # (rdata['next'])
            # if rdata['next'] != None:
            # search(False, get_next = True)
            else:
                print('error', error)
                props.report = error
                props.search_error = True

            # print('finished search thread')
            mt('preview loading finished')
    return .3
Example #3
0
 def create_asset_data(rdata, asset_type):
     for r in rdata['results']:
         if r['assetType'] == asset_type and len(r['files']) > 0:
             furl = None
             tname = None
             allthumbs = []
             durl, tname = None, None
             for f in r['files']:
                 if f['fileType'] == 'thumbnail':
                     tname = paths.extract_filename_from_url(
                         f['fileThumbnailLarge'])
                     small_tname = paths.extract_filename_from_url(
                         f['fileThumbnail'])
                     allthumbs.append(
                         tname)  # TODO just first thumb is used now.
                 tdict = {}
                 for i, t in enumerate(allthumbs):
                     tdict['thumbnail_%i'] = t
                 if f['fileType'] == 'blend':
                     durl = f['downloadUrl'].split('?')[0]
                     # fname = paths.extract_filename_from_url(f['filePath'])
             if durl and tname:
                 tooltip = blenderkit.search.generate_tooltip(r)
                 r['author']['id'] = str(r['author']['id'])
                 asset_data = {
                     'thumbnail': tname,
                     'thumbnail_small': small_tname,
                     # 'thumbnails':allthumbs,
                     'download_url': durl,
                     'id': r['id'],
                     'asset_base_id': r['assetBaseId'],
                     'name': r['name'],
                     'asset_type': r['assetType'],
                     'tooltip': tooltip,
                     'tags': r['tags'],
                     'can_download': r.get('canDownload', True),
                     'verification_status': r['verificationStatus'],
                     'author_id': r['author']['id'],
                     # 'author': r['author']['firstName'] + ' ' + r['author']['lastName']
                     # 'description': r['description'],
                 }
                 asset_data['downloaded'] = 0
                 # parse extra params needed for blender here
                 params = utils.params_to_dict(r['parameters'])
                 if asset_type == 'model':
                     if params.get('boundBoxMinX') != None:
                         bbox = {
                             'bbox_min': (float(params['boundBoxMinX']),
                                          float(params['boundBoxMinY']),
                                          float(params['boundBoxMinZ'])),
                             'bbox_max': (float(params['boundBoxMaxX']),
                                          float(params['boundBoxMaxY']),
                                          float(params['boundBoxMaxZ']))
                         }
                     else:
                         bbox = {
                             'bbox_min': (-.5, -.5, 0),
                             'bbox_max': (.5, .5, 1)
                         }
                     asset_data.update(bbox)
                 if asset_type == 'material':
                     asset_data['texture_size_meters'] = params.get(
                         'textureSizeMeters', 1.0)
                 asset_data.update(tdict)
         r.update(asset_data)
Example #4
0
def parse_result(r):
    '''
    needed to generate some extra data in the result(by now)
    Parameters
    ----------
    r - search result, also called asset_data
    '''
    scene = bpy.context.scene

    # TODO remove this fix when filesSize is fixed.
    # this is a temporary fix for too big numbers from the server.
    try:
        r['filesSize'] = int(r['filesSize'] / 1024)
    except:
        utils.p('asset with no files-size')
    asset_type = r['assetType']
    if len(r['files']) > 0:

        allthumbs = []
        durl, tname = None, None
        for f in r['files']:
            if f['fileType'] == 'thumbnail':
                tname = paths.extract_filename_from_url(
                    f['fileThumbnailLarge'])
                small_tname = paths.extract_filename_from_url(
                    f['fileThumbnail'])
                allthumbs.append(tname)  # TODO just first thumb is used now.

            tdict = {}
            for i, t in enumerate(allthumbs):
                tdict['thumbnail_%i'] = t
            if f['fileType'] == 'blend':
                durl = f['downloadUrl'].split('?')[0]
                # fname = paths.extract_filename_from_url(f['filePath'])
        if durl and tname:

            tooltip = generate_tooltip(r)
            # for some reason, the id was still int on some occurances. investigate this.
            r['author']['id'] = str(r['author']['id'])

            # some helper props, but generally shouldn't be renaming/duplifiying original properties,
            # so blender's data is same as on server.
            asset_data = {
                'thumbnail': tname,
                'thumbnail_small': small_tname,
                # 'thumbnails':allthumbs,
                'download_url': durl,
                # 'id': r['id'],
                # 'asset_base_id': r['assetBaseId'],#this should stay ONLY for compatibility with older scenes
                # 'name': r['name'],
                # 'asset_type': r['assetType'], #this should stay ONLY for compatibility with older scenes
                'tooltip': tooltip,
                # 'tags': r['tags'],
                # 'can_download': r.get('canDownload', True),#this should stay ONLY for compatibility with older scenes
                # 'verification_status': r['verificationStatus'],#this should stay ONLY for compatibility with older scenes
                # 'author_id': r['author']['id'],#this should stay ONLY for compatibility with older scenes
                # 'author': r['author']['firstName'] + ' ' + r['author']['lastName']
                # 'description': r['description'],
            }
            asset_data['downloaded'] = 0

            # parse extra params needed for blender here
            params = utils.params_to_dict(r['parameters'])

            if asset_type == 'model':
                if params.get('boundBoxMinX') != None:
                    bbox = {
                        'bbox_min': (float(params['boundBoxMinX']),
                                     float(params['boundBoxMinY']),
                                     float(params['boundBoxMinZ'])),
                        'bbox_max': (float(params['boundBoxMaxX']),
                                     float(params['boundBoxMaxY']),
                                     float(params['boundBoxMaxZ']))
                    }

                else:
                    bbox = {'bbox_min': (-.5, -.5, 0), 'bbox_max': (.5, .5, 1)}
                asset_data.update(bbox)
            if asset_type == 'material':
                asset_data['texture_size_meters'] = params.get(
                    'textureSizeMeters', 1.0)

            asset_data.update(tdict)
            if r['assetBaseId'] in scene.get('assets used', {}).keys():
                asset_data['downloaded'] = 100

            # attempt to switch to use original data gradually, since the parsing as itself should become obsolete.
            asset_data.update(r)
            return asset_data
Example #5
0
def timer_update2():
    preferences = bpy.context.preferences.addons['blenderkit'].preferences
    if search.first_time:
        search.first_time = False
        if preferences.show_on_start:
            search()
        if preferences.tips_on_start:
            ui.get_largest_3dview()
            ui.update_ui_size(ui.active_area, ui.active_region)
            ui.add_report(text='BlenderKit Tip: ' +
                          random.choice(search.rtips),
                          timeout=12,
                          color=colors.GREEN)

    if bpy.context.window_manager.clipboard != search.last_clipboard:
        last_clipboard = bpy.context.window_manager.clipboard
        instr = 'asset_base_id:'
        if last_clipboard[:len(instr)] == instr:
            atstr = 'asset_type:'
            ati = last_clipboard.find(atstr)
            if ati > -1:
                search_props = utils.get_search_props()
                search_props.search_keywords = last_clipboard

    if len(search.search_threads
           ) == 0 or bpy.context.scene.blenderkitUI.dragging:
        return 1
    for thread in search.search_threads:
        if not thread[0].is_alive():
            search.search_threads.remove(thread)  #
            icons_dir = thread[1]
            scene = bpy.context.scene
            s = bpy.context.scene
            asset_type = thread[2]
            if asset_type == 'model':
                props = scene.blenderkit_models
                json_filepath = os.path.join(icons_dir,
                                             'model_searchresult.json')
                search_name = 'bkit model search'
            if asset_type == 'scene':
                props = scene.blenderkit_scene
                json_filepath = os.path.join(icons_dir,
                                             'scene_searchresult.json')
                search_name = 'bkit scene search'
            if asset_type == 'material':
                props = scene.blenderkit_mat
                json_filepath = os.path.join(icons_dir,
                                             'material_searchresult.json')
                search_name = 'bkit material search'
            if asset_type == 'brush':
                props = scene.blenderkit_brush
                json_filepath = os.path.join(icons_dir,
                                             'brush_searchresult.json')
                search_name = 'bkit brush search'

            s[search_name] = []

            if search.reports != '':
                props.report = str(search.reports)
                return .2
            with open(json_filepath, 'r') as data_file:
                rdata = json.load(data_file)

            result_field = []
            ok, error = search.check_errors(rdata)
            if ok:
                bpy.ops.object.run_assetbar_fix_context()
                for r in rdata['results']:
                    try:
                        r['filesSize'] = int(r['filesSize'] / 1024)
                    except:
                        utils.p('asset with no files-size')
                    if r['assetType'] == asset_type:
                        if len(r['files']) > 0:
                            tname = None
                            allthumbs = []
                            durl, tname = None, None
                            for f in r['files']:
                                if f['fileType'] == 'thumbnail':
                                    tname = paths.extract_filename_from_url(
                                        f['fileThumbnailLarge'])
                                    small_tname = paths.extract_filename_from_url(
                                        f['fileThumbnail'])
                                    allthumbs.append(tname)

                                tdict = {}
                                for i, t in enumerate(allthumbs):
                                    tdict['thumbnail_%i'] = t
                                if f['fileType'] == 'blend':
                                    durl = f['downloadUrl'].split('?')[0]
                            if durl and tname:

                                tooltip = search.generate_tooltip(r)
                                asset_data = {
                                    'thumbnail': tname,
                                    'thumbnail_small': small_tname,
                                    'download_url': durl,
                                    'id': r['id'],
                                    'asset_base_id': r['assetBaseId'],
                                    'name': r['name'],
                                    'asset_type': r['assetType'],
                                    'tooltip': tooltip,
                                    'tags': r['tags'],
                                    'can_download': r.get('canDownload', True),
                                    'verification_status':
                                    r['verificationStatus'],
                                    'author_id': str(r['author']['id'])
                                }
                                asset_data['downloaded'] = 0

                                if 'description' in r:
                                    asset_data['description'] = r[
                                        'description']
                                if 'metadata' in r:
                                    asset_data['metadata'] = r['metadata']
                                if 'sku' in r:
                                    asset_data['sku'] = r['sku']
                                if 'client' in r:
                                    asset_data['client'] = r['client']

                                params = utils.params_to_dict(r['parameters'])

                                if asset_type == 'model':
                                    if params.get('boundBoxMinX') is not None:
                                        bbox = {
                                            'bbox_min':
                                            (float(params['boundBoxMinX']),
                                             float(params['boundBoxMinY']),
                                             float(params['boundBoxMinZ'])),
                                            'bbox_max':
                                            (float(params['boundBoxMaxX']),
                                             float(params['boundBoxMaxY']),
                                             float(params['boundBoxMaxZ']))
                                        }

                                    else:
                                        bbox = {
                                            'bbox_min': (-.5, -.5, 0),
                                            'bbox_max': (.5, .5, 1)
                                        }
                                    asset_data.update(bbox)
                                if asset_type == 'material':
                                    asset_data[
                                        'texture_size_meters'] = params.get(
                                            'textureSizeMeters', 1.0)

                                asset_data.update(tdict)
                                if r['assetBaseId'] in scene.get(
                                        'assets used', {}).keys():
                                    asset_data['downloaded'] = 100

                                result_field.append(asset_data)

                s[search_name] = result_field
                s['search results'] = result_field
                s[search_name + ' orig'] = rdata
                s['search results orig'] = rdata
                search.load_previews()
                ui_props = bpy.context.scene.blenderkitUI
                if len(result_field) < ui_props.scrolloffset:
                    ui_props.scrolloffset = 0
                props.is_searching = False
                props.search_error = False
                props.report = 'Found %i results. ' % (
                    s['search results orig']['count'])
                if len(s['search results']) == 0:
                    tasks_queue.add_task(
                        (ui.add_report, ('No matching results found.', )))

            else:
                print('error', error)
                props.report = error
                props.search_error = True

            search.mt('preview loading finished')
    return .3