def add_err_material(obj): mat = bpy.data.materials.new("ERROR MATERIAL") mat.diffuse_color = mathutils.Color((0, 0, 1)) mat.specular_color = mathutils.Color((1, 1, 1)) mat.diffuse_intensity = 1 add_material(obj, mat) return mat
def __init__(self, scene): self.autoClear = True world = scene.world if world: self.ambient_color = world.ambient_color self.clear_color = world.horizon_color else: self.ambient_color = mathutils.Color((0.2, 0.2, 0.3)) self.clear_color = mathutils.Color((0.0, 0.0, 0.0)) self.gravity = scene.gravity if world and world.mist_settings.use_mist: if world.fogMode == eFOGMODE_LINEAR: self.fogMode = FOGMODE_LINEAR elif world.fogMode == eFOGMODE_EXP: self.fogMode = FOGMODE_EXP elif world.fogMode == eFOGMODE_EXP2: self.fogMode = FOGMODE_EXP2 self.fogColor = world.horizon_color self.fogStart = world.mist_settings.start self.fogEnd = world.mist_settings.depth self.fogDensity = world.fogDensity else: self.fogMode = FOGMODE_NONE Logger.log('Python World class constructor completed')
def execute(self, context): vps = context.active_object.data.vertex_paint_settings a = mu.Color((vps.color.r, vps.color.g, vps.color.b)) b = mu.Color((vps.swap.r, vps.swap.g, vps.swap.b)) vps.color = b vps.swap = a return {'FINISHED'}
def sample(self, point, normal, face, layer=None): if face == -1: return mathutils.Color((0, 0, 0)) obj = self.obj mesh = self.mesh colors = self.layer.data if layer is not None: colors = mesh.vertex_colors[layer].data poly = mesh.polygons[face] vert_a = mesh.vertices[poly.vertices[0]].co vert_b = mesh.vertices[poly.vertices[1]].co vert_c = mesh.vertices[poly.vertices[2]].co color_a = colors[poly.loop_indices[0]].color color_b = colors[poly.loop_indices[1]].color color_c = colors[poly.loop_indices[2]].color total_area = poly.area area_a = mathutils.geometry.area_tri(point, vert_b, vert_c) area_b = mathutils.geometry.area_tri(point, vert_a, vert_c) area_c = mathutils.geometry.area_tri(point, vert_a, vert_b) r = (color_a.r * area_a + color_b.r * area_b + color_c.r * area_c) / total_area g = (color_a.g * area_a + color_b.g * area_b + color_c.g * area_c) / total_area b = (color_a.b * area_a + color_b.b * area_b + color_c.b * area_c) / total_area return mathutils.Color((r, g, b))
def add_vcolor(mesh, representation, layerID): """copies vertex colors (layer `layerID`) from the representation to the blender mesh""" vx_layer = mesh.vertex_colors.new("v_color_" + str(layerID)) # some really recent, unstable versions of blender 2.79 have alpha support in vertex colors. # detect this and react accordingly (or an exception will be raised) try: vx_layer.data[0].color = (1, 0, 0, 0) alpha_support = True except: alpha_support = False vx_layer_a = mesh.vertex_colors.new("v_color_alpha_" + str(layerID)) # alpimg = bpy.data.images.new(mesh.name+'_vcol_alpha_'+str(layerID), 256, 256) # XCX image method buggy -> disabled if alpha_support: for num, com in enumerate(representation.loops): if com.VColors[layerID] is not None: vx_layer.data[num].color = com.VColors[layerID] else: for num, com in enumerate(representation.loops): if com.VColors[layerID] is not None: vx_layer.data[num].color = mathutils.Color( com.VColors[layerID][:3]) vx_layer_a.data[num].color = mathutils.Color( (com.VColors[layerID][3], ) * 3)
def _save_poly(self): colors = self.layer.colors.data colors[self.poly_index].color = mathutils.Color(self.color) if self.layer.alpha: a = self.alpha self.layer.alpha.data[self.poly_index].color = mathutils.Color( (a, a, a))
def execute(self, context): ob = context.active_object me = ob.data mate = ob.active_material active_slot = context.texture_slot active_tex = context.texture tex_name = common.remove_serial_number(active_tex.name) target_slots = [] if self.is_all: for slot in mate.texture_slots: if not slot: continue name = common.remove_serial_number(slot.texture.name) if name in ['_ShadowColor', '_RimColor', '_OutlineColor']: target_slots.append(slot) else: target_slots.append(active_slot) for slot in mate.texture_slots: if not slot: continue name = common.remove_serial_number(slot.texture.name) if name == '_MainTex': img = slot.texture.image if img: if len(img.pixels): break else: img = me.uv_textures.active.data[0].image sample_count = 10 img_width, img_height, img_channel = img.size[0], img.size[1], img.channels bm = bmesh.new() bm.from_mesh(me) uv_lay = bm.loops.layers.uv.active uvs = [l[uv_lay].uv[:] for f in bm.faces if f.material_index == ob.active_material_index for l in f.loops] bm.free() average_color = mathutils.Color([0, 0, 0]) seek_interval = len(uvs) / sample_count for sample_index in range(sample_count): uv_index = int(seek_interval * sample_index) x, y = uvs[uv_index] x, y = int(x * img_width), int(y * img_height) pixel_index = ((y * img_width) + x) * img_channel color = mathutils.Color(img.pixels[pixel_index:pixel_index+3]) average_color += color average_color /= sample_count average_color.s *= self.saturation_multi average_color.v *= self.value_multi for slot in target_slots: slot.color = average_color[:3] common.set_texture_color(slot) return {'FINISHED'}
def export_light(object, scene, file_handler): light_type_items = { 'POINT': 0, 'SUN': 1, 'SPOT': 2, 'HEMI': 3, 'AREA': 0 } light_type = light_type_items[object.data.type] file_handler.write("{") Export_babylon.write_string(file_handler, "name", object.name, True) Export_babylon.write_string(file_handler, "id", object.name) Export_babylon.write_float(file_handler, "type", light_type) if light_type == 0: Export_babylon.write_vector(file_handler, "position", object.location) elif light_type == 1: direction = Export_babylon.getDirection(object.matrix_world) Export_babylon.write_vector(file_handler, "position", object.location) Export_babylon.write_vector(file_handler, "direction", direction) elif light_type == 2: Export_babylon.write_vector(file_handler, "position", object.location) direction = Export_babylon.getDirection(object.matrix_world) Export_babylon.write_vector(file_handler, "direction", direction) Export_babylon.write_float(file_handler, "angle", object.data.spot_size) Export_babylon.write_float(file_handler, "exponent", object.data.spot_blend * 2) else: matrix_world = object.matrix_world.copy() matrix_world.translation = mathutils.Vector((0, 0, 0)) direction = mathutils.Vector((0, 0, -1)) * matrix_world Export_babylon.write_vector(file_handler, "direction", -direction) Export_babylon.write_color(file_handler, "groundColor", mathutils.Color((0, 0, 0))) Export_babylon.write_float(file_handler, "intensity", object.data.energy) if object.data.use_diffuse: Export_babylon.write_color(file_handler, "diffuse", object.data.color) else: Export_babylon.write_color(file_handler, "diffuse", mathutils.Color((0, 0, 0))) if object.data.use_specular: Export_babylon.write_color(file_handler, "specular", object.data.color) else: Export_babylon.write_color(file_handler, "specular", mathutils.Color((0, 0, 0))) file_handler.write("}")
def charge_material(self, pname, mname, element): """Return charge material""" pmat = bpy.data.materials.new(pname) mmat = bpy.data.materials.new(mname) pmat.diffuse_color = mathutils.Color(self.chargepluscolor) mmat.diffuse_color = mathutils.Color(self.chargeminuscolor) return pmat, mmat
def save_materials(filepath, mats): file = open(filepath, "w", encoding="utf8", newline="\n") file.write('<?xml version="1.0" encoding="UTF-8"?>\n') file.write('<!-- Automatically exported from Blender v{} using the bouge exporter by Lucas Beyer -->\n'.format(bpy.app.version_string)) for mat in mats: bmat = common.BougeMaterial(mat.name) # Default phong light model values. dc = mat.diffuse_color sc = mat.specular_color di = mat.diffuse_intensity si = mat.specular_intensity #si = mat.specular_hardness bmat.setprop('uMaterialAmbient', __col2str(mathutils.Color((0.2, 0.2, 0.2)))) bmat.setprop('uMaterialDiffuse', __col2str(mathutils.Color((dc.r * di, dc.g * di, dc.b * di)))) #bmat.setprop('specular', __col2str(mathutils.Color((sc.r * si, sc.g * si, sc.b * si)))) #bmat.setprop('shininess', str(mat.specular_hardness)) bmat.setprop('uMaterialSpecular', __col2str(mathutils.Color((sc.r * si, sc.g * si, sc.b * si)), mat.specular_hardness)) # Texture maps for tex, i in zip(mat.texture_slots.values(), range(len(mat.texture_slots))): # Weird thing is that there are always the slots, it's just that # if there is no texture in the slot, it's None if not tex: continue if tex.texture_coords != 'UV': print("Warning: skipping texture {} because it doesn't use UV texture coordinates!".format(tex.name)) continue # Note that Arkana-FTS only supports png images! # I anticipate keeping the correct file path won't do. Some users # will pack the texture with absolute path and some with relative. # - Relative, it's all fine, keep the path. # - Absolute, just use the filename and put it in a 'textures' subdir. img = tex.texture.image if img.file_format != 'PNG': print("Warning: texture {} is not in png format! Trying to convert but that may fail!".format(tex.name)) imgfile = img.filepath[2:] if img.filepath[:2] == "//" else os.path.join('textures', os.path.basename(img.filepath)) imgfile_png = os.path.join(os.path.dirname(imgfile), os.path.splitext(os.path.basename(imgfile))[0] + '.png') bmat.setprop('uTexture' + (str(i) if i else ''), imgfile_png) # And now save the packed (or even just loaded?) image to disk. old_filepath = img.filepath old_format = img.file_format img.file_format = 'PNG' img.filepath = os.path.join(os.path.dirname(filepath), imgfile_png) img.save() img.filepath = old_filepath img.file_format = old_format bmat.writeXML(file) file.close()
def reset_gradient_props(obj): setattr(obj, 'blend_type', 'DIRECTIONAL') setattr(obj, 'blend_method', 'REPLACE') setattr(obj, 'blend_falloff', 'LINEAR') setattr(obj, 'bias', 0) setattr(obj, 'scale', 1) setattr(obj, 'mirror', False) setattr(obj, 'color_a', mu.Color((0, 0, 0))) setattr(obj, 'alpha_a', 1) setattr(obj, 'color_b', mu.Color((1, 1, 1))) setattr(obj, 'alpha_b', 1)
def gradient_to_kwargs(obj): g = {} if 'Gradient' in obj: d = obj['Gradient'] g['blend_type'] = d['blend_type'] g['blend_method'] = d['blend_method'] g['color_a'] = mathutils.Color(d['color_a']) g['color_b'] = mathutils.Color(d['color_b']) g['alpha_a'] = d['alpha_a'] g['alpha_b'] = d['alpha_b'] return g
def _save_samples(self): colors = self.colors.data if self.alpha: alpha = self.alpha.data else: alpha = None for sample in self._samples: colors[sample.poly_index].color = mathutils.Color(sample.color) if alpha: a = sample.alpha alpha[sample.poly_index].color = mathutils.Color((a, a, a))
def __init__(self): self.shader = BL_Shader() self.blending = (0,0) self.alpha = float() self.hardness = int() self.emit = float() self.ambient = float() self.specularAlpha = float() self.specularIntensity = float() self.diffuseIntensity = float() self.specularColor = mathutils.Color() self.diffuseColor = mathutils.Color() self.textures = BL_Texture()
def __init__(self): context = bpy.context aux_objects = list(context.selected_objects) aux_objects.remove(context.active_object) ref = aux_objects[0] if 'Gradient' in ref: d = ref['Gradient'] self.blend_type = d['blend_type'] self.blend_method = d['blend_method'] self.color_a = mathutils.Color(d['color_a']) self.color_b = mathutils.Color(d['color_b']) self.alpha_a = d['alpha_a'] self.alpha_b = d['alpha_b']
def to_sdl(cls, b_prop_group, sdlconsole, res_name): albedo_vec = b_prop_group.albedo albedo = mathutils.Color((albedo_vec[0], albedo_vec[1], albedo_vec[2])) f0_vec = b_prop_group.f0 f0 = mathutils.Color((f0_vec[0], f0_vec[1], f0_vec[2])) command = psdl.materialcmd.AbradedTranslucentCreator() command.set_data_name(res_name) command.set_albedo(albedo) command.set_f0(f0) command.set_ior_outer(b_prop_group.ior) command.set_roughness(MicrofacetProperty.get_roughness(b_prop_group)) return command.to_sdl(sdlconsole)
def __init__(self): self.KX_MIST_QUADRATIC = int() self.KX_MIST_LINEAR = int() self.KX_MIST_INV_QUADRATIC = int() self.mistEnable = bool() self.mistStart = float() self.mistDistance = float() self.mistIntensity = float() self.mistType = None self.mistColor = mathutils.Color() self.horizonColor = mathutils.Color() self.zenithColor = mathutils.Color() self.ambientColor = mathutils.Color() self.exposure = float() self.range = float()
def execute(self, context): activeObject = context.active_object selectedObjects = context.selected_objects activeNode = activeObject.vray.Node activeAttrIndex = activeNode.user_attributes_selected activeAttrCount = len(activeNode.user_attributes) if not activeAttrIndex >= 0 or not activeAttrCount: return {'CANCELLED'} activeAttribute = activeNode.user_attributes[activeAttrIndex] attrName = activeAttribute.name attrType = activeAttribute.value_type attrValueName = gUserAttributeTypeToValue[attrType] activeAttrValue = getattr(activeAttribute, attrValueName) selectionFilter = lambda x: hasattr(x, 'vray') and hasattr(x.vray, 'Node') and x != activeObject for ob in filter(selectionFilter, selectedObjects): Node = ob.vray.Node attr = None if attrName in Node.user_attributes: attr = Node.user_attributes[attrName] # NOTE: Type could be changed attr.value_type = attrType else: attr = Node.user_attributes.add() attr.name = attrName attr.value_type = attrType if not activeNode.user_attributes_rnd_use: setattr(attr, attrValueName, activeAttrValue) else: if activeAttribute.value_type == '3': attr.value_string = activeAttribute.value_string else: newValue = None if activeAttribute.value_type == '0': newValue = random.randrange(activeNode.user_attributes_int_rnd_min, activeNode.user_attributes_int_rnd_max) elif activeAttribute.value_type == '1': random.random() randFloat = random.random() randRange = activeNode.user_attributes_float_rnd_max - activeNode.user_attributes_float_rnd_min newValue = activeNode.user_attributes_float_rnd_min + randFloat * randRange elif activeAttribute.value_type == '2': random.random() randR = random.random() random.random() randG = random.random() random.random() randB = random.random() newValue = mathutils.Color((randR, randG, randB)) setattr(attr, attrValueName, newValue) return {'FINISHED'}
def execute(self, context): objects = context.selected_objects if not objects: self.report({'ERROR'}, 'No objects selected') return {'CANCELLED'} xr_data = context.scene.xray self.seed = xr_data.materials_colorize_random_seed self.power = xr_data.materials_colorize_color_power materials = set() for obj in objects: for slot in obj.material_slots: materials.add(slot.material) for mat in materials: if not mat: continue data = bytearray(mat.name, 'utf8') data.append(self.seed) hsh = zlib.crc32(data) color = mathutils.Color() color.hsv = ((hsh & 0xFF) / 0xFF, (((hsh >> 8) & 3) / 3 * 0.5 + 0.5) * self.power, ((hsh >> 2) & 1) * (0.5 * self.power) + 0.5) color = [color.r, color.g, color.b] if version_utils.IS_28: color.append(1.0) # alpha mat.diffuse_color = color return {'FINISHED'}
def translate_diffuse_bsdf_node(this_node, sdlconsole, res_name): command = psdl.materialcmd.MatteOpaqueCreator() command.set_data_name(res_name) color_socket = this_node.inputs.get("Color") if color_socket.is_linked: result = translate_node(color_socket.links[0].from_node, sdlconsole, res_name) if result.sdl_resource_identifier is not None: command.set_albedo_image(result.sdl_resource_identifier) else: print("warning: material %s's albedo image is invalid" % res_name) sdlconsole.queue_command(command) return TranslateResult(command) # TODO: color has 4 components, currently parsing 3 only color = color_socket.default_value # TODO: handle roughness & normal sockets albedo = mathutils.Color((color[0], color[1], color[2])) command.set_albedo_color(albedo) sdlconsole.queue_command(command) return TranslateResult(command)
def makeCone(self, li): #object geometric parameters params = self.strToVect(' '.join(li[1:3])) myName = 'Cone' + '_' + str(li[3]) #if object is dynamic create an entry in the movables dictionary if int(li[3]) > 0: self.movables[myName] = numpy.empty(0) my_Cone = bpy.ops.mesh.primitive_cone_add(vertices=40, radius1=params[0], radius2=0, depth=params[1], location=self.strToVect(' '.join(li[6:9]), rotation=self.quatToEul(self.strToVect(' '.join(li[9:13]))))) ob = bpy.context.object ob.name = myName ob.show_name = True me = ob.data me.name = myName + '_' + 'Mesh' #assign a random color to the primitive col = mathutils.Color((random.random(), random.random(), random.random())) mat = self.makeMaterial('random color' + str(random.random()), col, 1) self.setMaterial(ob, mat) return ob
def makeSphere(self, li): #object geometric parameters params = self.strToVect(' '.join(li[1])) myName = 'Sphere' + '_' + str(li[2]) #if object is dynamic create an entry in the movables dictionary if int(li[2]) > 0: self.movables[myName] = numpy.empty(0) my_Sphere = bpy.ops.mesh.primitive_uv_sphere_add(size=params[0], location=self.strToVect(' '.join(li[5:8]))) ob = bpy.context.object ob.name = myName ob.show_name = True me = ob.data me.name = myName + '_' + 'Mesh' #assign a random color to the primitive col = mathutils.Color((random.random(), random.random(), random.random())) mat = self.makeMaterial('random color' + str(random.random()), col, 1) self.setMaterial(ob, mat) return ob
def createPreview(objects, export_path, modelname, render_resolution=256, opengl=False): """Creates a thumbnail of the given objects. Args: objects(list of bpy.types.Object): list of objects for the thumbnail export_path(str): folder to export image to modelname(str): name of model (used as file name) render_resolution(int): side length of resulting image in pixels (Default value = 256) opengl(bool): whether to use opengl rendering or not (Default value = False) Returns: """ log("Creating thumbnail of model: "+modelname, "INFO") # render presets bpy.context.scene.render.image_settings.file_format = 'PNG' bpy.context.scene.render.resolution_x = render_resolution bpy.context.scene.render.resolution_y = render_resolution bpy.context.scene.render.resolution_percentage = 100 # hide everything that is not supposed to show for ob in bpy.data.objects: if not (ob in objects): ob.hide_render = True ob.hide = True # render the preview if opengl: # use the viewport representation to create preview bpy.ops.view3d.view_selected() bpy.ops.render.opengl(view_context=True) else: # use real rendering # create camera bpy.ops.object.camera_add(view_align=True) cam = bpy.context.scene.objects.active bpy.data.cameras[cam.data.name].type = 'ORTHO' bpy.data.scenes[0].camera = cam # set camera as active camera sUtils.selectObjects(objects, True, 0) bpy.ops.view3d.camera_to_view_selected() # create light bpy.ops.object.lamp_add(type='SUN', radius=1) light = bpy.context.scene.objects.active light.matrix_world = cam.matrix_world # set background oldcolor = bpy.data.worlds[0].horizon_color.copy() bpy.data.worlds[0].horizon_color = mathutils.Color((1.0, 1.0, 1.0)) bpy.ops.render.render() bpy.data.worlds[0].horizon_color = oldcolor sUtils.selectObjects([cam, light], True, 0) bpy.ops.object.delete() # safe render and reset the scene log("Saving model preview to: " + os.path.join(export_path, modelname + '.png'), "INFO") bpy.data.images['Render Result'].save_render(os.path.join(export_path, modelname + '.png')) # make all objects visible again for ob in bpy.data.objects: ob.hide_render = False ob.hide = False
def makeStlMesh(self, li): """Function to read an .stl mesh from the file and instantiate it on the scene""" myName = 'My_Mesh' + '_' + str(li[1]) #if object is dynamic create an entry in the movables dictionary if int(li[1]) > 0: self.movables[myName] = numpy.empty(0) my_mesh = bpy.ops.import_mesh.stl(filepath=li[0]) ob = bpy.context.selected_objects[0] ob.location = self.strToVect(' '.join(li[4:7])) ob.rotation_euler = self.quatToEul(self.strToVect(' '.join(li[7:11]))) ob.name = myName ob.show_name = True me = ob.data me.name = myName + '_' + 'Mesh' #assign a random color to the primitive col = mathutils.Color((random.random(), random.random(), random.random())) mat = self.makeMaterial('random color' + str(random.random()), col, 1) self.setMaterial(ob, mat) return ob
def light_colors_obj(obj, use_normals=False, color_layer='', select='POLYGON'): light_all = False select = select.lower() lights = [] for l in cc.utils.traverse(bpy.context.scene.objects): if (l.type == 'LAMP' and not l.hide_render): lights.append(l) final = cc.colors.layer(obj) temp = cc.colors.new(obj, '_Temp') base = cc.colors.layer(obj, color_layer) if final.name == base.name: light_all = True for i, s in enumerate(base.itersamples()): s.color = mathutils.Color((1, 1, 1)) for i, s in enumerate(temp.itersamples()): if light_all or s.is_selected(select): s.color *= 0 for light in lights: center = light.matrix_world * mathutils.Vector((0, 0, 0)) radius = light.data.distance lcolor = light.data.color * light.data.energy for i, s in enumerate(temp.itersamples()): if not light_all and not s.is_selected(select): continue vert = obj.matrix_world * s.vertex.co if use_normals: light_dir = (vert - center).normalized() normal = s.vertex.normal n_dot_l = 1 - normal.dot(light_dir) else: n_dot_l = 1 distance = cc.utils.magnitude(vert - center) atten = 1 - min(distance / radius, 1) color = lcolor.copy() color.v *= atten * n_dot_l rcolor = base.samples[i].color s.color.r += color.r * rcolor.r s.color.g += color.g * rcolor.g s.color.b += color.b * rcolor.b for i, s in enumerate(final.itersamples()): if light_all or s.is_selected(select): s.color = temp.samples[i].color temp.destroy()
def get_golden_angle_colour(i): """Return the golden angle colour from an integer number of steps.""" c = mathutils.Color() h = divmod(111.25 / 360 * i, 1)[1] c.hsv = h, 1, 1 return list(c)
def hex_to_color(val): try: val = str(val).lower() except ValueError: return mathutils.Color((1, 0, 1)) if val == '0': val = '000000' if len(val) == 3: val = val[2] + val[2] + val[1] + val[1] + val[0] + val[0] try: t = struct.unpack('BBB', bytes.fromhex(val)) except ValueError: return mathutils.Color((1, 0, 1)) else: return mathutils.Color((t[0] / 255.0, t[1] / 255.0, t[2] / 255.0))
def sample_color(context, event, ray_max=1000.0): result = cc.utils.find(context, event, 10000) if result is not None: obj, origin, target = result if obj.data.vertex_colors.active: with cc.colors.Sampler(obj) as sampler: return sampler.raycast(origin, target) return mu.Color((0, 0, 0))
def read_vertex_data(file, FVF_FLAGS, compressed): """read PKG vertex data into a tuple""" vnorm = mathutils.Vector((1, 1, 1)) vuv = (0, 0) vcolor = mathutils.Color((1, 1, 1)) if FVF_FLAGS.has_flag("D3DFVF_NORMAL"): vnorm = bin.read_cfloat3(file) if compressed else bin.read_float3(file) if FVF_FLAGS.has_flag("D3DFVF_DIFFUSE"): c4d = bin.read_color4d(file) vcolor = mathutils.Color((c4d[0], c4d[1], c4d[2])) if FVF_FLAGS.has_flag("D3DFVF_SPECULAR"): c4d = bin.read_color4d(file) vcolor = mathutils.Color((c4d[0], c4d[1], c4d[2])) if FVF_FLAGS.has_flag("D3DFVF_TEX1"): vuv = bin.read_cfloat2(file) if compressed else bin.read_float2(file) return (vnorm, vuv, vcolor)
def highLight(self, frame): """Colour the nodes in the interface to reflect the output""" hue, sat, val = self.resultLog[frame] self.bpyNode.use_custom_color = True c = mathutils.Color() c.hsv = hue, sat, val self.bpyNode.color = c self.bpyNode.keyframe_insert("color")