def main(): # file location on computer fopen = open("C:\L4212G.asc") points = [] lineNb = 0 rowNb = 0.0 first = fopen.readline() size = int(first[13:]) for line in fopen: if lineNb > 6: ptnum = 0.0 posz = rowNb / float(size -1) * size line = line[1:] for i in line.split(" "): posx = ptnum / float(size - 1) * size posy = float(i) pos = c4d.Vector(posx, posy, posz) c4d.StatusSetBar((lineNb/30)) points.append(pos) ptnum += 1 rowNb += 1 lineNb += 1 poly = c4d.PolygonObject(len(points),0) poly.SetAllPoints(points) doc.InsertObject(poly) c4d.StatusClear() fopen.close
def connect(lst_poly, nom=None): """connecte tous les polys entre eux et renvoie un polygon object avec l'axe au centre à la base du batiment ATTENTION lancer la commande OPTIMIZE APRES""" pts = [] polys = [] pos = 0 for poly in lst_poly: mg = poly.GetMg() pts += [p * mg for p in poly.GetAllPoints()] polys += [refCPoly(p, pos) for p in poly.GetAllPolygons()] pos += poly.GetPointCount() res = c4d.PolygonObject(len(pts), len(polys)) res.SetAllPoints(pts) for i, p in enumerate(polys): res.SetPolygon(i, p) res.Message(c4d.MSG_UPDATE) centre = res.GetMp() rad = res.GetRad() centre.y -= rad.y pts = [p - centre for p in pts] res.SetAllPoints(pts) mg = res.GetMg() mg.off = centre res.SetMg(mg) if nom: res.SetName(nom) res.Message(c4d.MSG_UPDATE) return res
def connectSupprim(lst_obj,name,doc,bc =False): """bc est si on veut stocker les egid sous forme de basecontainer""" nb_pts = 0 nb_poly = 0 #BaseContainer pour stocker en etiquette l'EGID #en valeur un ss-conteneur stocke en 0 l'id du premier poly #et en 1 le nombre de polygones du batiment #ATTENTION de bien fusionner par noEGID avant pour ne pas avoir deux poly #avec le meme no if bc : #premier container qui contient en 0 le nombre de batiment ... bc_egid = c4d.BaseContainer() #et en 1 le sous-container contenant tous les container pour chaque bâtiment sub_bc1 = c4d.BaseContainer() for i,obj in enumerate(lst_obj): if bc: egid = int(obj.GetName()) ss_bc = c4d.BaseContainer() ss_bc[0] = nb_poly ss_bc[1] = obj.GetPolygonCount() ss_bc[2] = egid sub_bc1.SetContainer(i, ss_bc) nb_pts+=obj.GetPointCount() nb_poly+=obj.GetPolygonCount() res = c4d.PolygonObject(nb_pts,nb_poly) #on lui colle le baseContainer avec les no EGID if bc : #en 0 le nombre de bâtiemnt bc_egid[0] = len(lst_obj) #en 1 le sous bc_egid.SetContainer(1, sub_bc1) res[ID_EGID_BC] = bc_egid res.SetName(name) id_pt_dprt=0 id_poly_dprt =0 for obj in lst_obj: for i,pt in enumerate(obj.GetAllPoints()): res.SetPoint(i+id_pt_dprt,pt) for i,poly in enumerate(obj.GetAllPolygons()): poly.a += id_pt_dprt poly.b += id_pt_dprt poly.c += id_pt_dprt poly.d += id_pt_dprt res.SetPolygon(i+id_poly_dprt,poly) id_pt_dprt+=obj.GetPointCount() id_poly_dprt += obj.GetPolygonCount() obj.Remove() res.Message(c4d.MSG_UPDATE) doc.InsertObject(res) doc.AddUndo(c4d.UNDOTYPE_NEW,res) return res
def main(): doc = c4d.documents.GetActiveDocument() objs = doc.GetActiveObjects(c4d.GETACTIVEOBJECTFLAGS_SELECTIONORDER) if not len(objs) == 2: c4d.gui.MessageDialog(TXT_PB_SELECTION) return obj_pts, mnt = objs if not obj_pts.CheckType(c4d.Opoint): c4d.gui.MessageDialog(TXT_NOT_POINTSOBJECT) return if not mnt.CheckType(c4d.Opolygon): c4d.gui.MessageDialog(TXT_NOT_POLYGON) return rep = c4d.gui.QuestionDialog( f"""Les points de "{obj_pts.GetName()}" seront copiés et projetés sur "{mnt.GetName()}"\nVoulez-vous continuer ?""" ) if not rep: return obj_points_clone = obj_pts.GetClone() pointsOnSurface(obj_points_clone, mnt) #suppression des polygones de l'objet mg = obj_points_clone.GetMg() pts = [p * mg for p in obj_points_clone.GetAllPoints()] new_obj_pts = c4d.PolygonObject(len(pts), 0) new_obj_pts.SetAllPoints(pts) new_obj_pts.Message(c4d.MSG_UPDATE) new_obj_pts.SetName(SUFFIXE_OBJ_POINT + obj_pts.GetName()) multi_inst = c4d.BaseObject(c4d.Oinstance) multi_inst[ c4d. INSTANCEOBJECT_RENDERINSTANCE_MODE] = c4d.INSTANCEOBJECT_RENDERINSTANCE_MODE_MULTIINSTANCE multi_inst[c4d.INSTANCEOBJECT_MULTIPOSITIONINPUT] = new_obj_pts multi_inst.InsertUnder(new_obj_pts) #arbre source #TODO : spliter pas variante (ici je prends uniquement la première) fn = '/Users/donzeo/Library/Preferences/MAXON/Maxon Cinema 4D R23_2FE1299C/plugins/SITG_C4D/__arbres_2018__.c4d' sources = getArbresSourcesFromFile(fn) if sources: source = sources[0] source.InsertUnder(new_obj_pts) source.SetName("objet de référence") multi_inst[c4d.INSTANCEOBJECT_LINK] = source doc.InsertObject(new_obj_pts) c4d.EventAdd()
def GenerateMeshFromMatrices(_matrices, _size=1, _quad=True): # QUAD MESH if _quad: verticesPerFace = 4 baseVertices = CreateRectangleVertices(_size) # TRIANGLE MESH else: verticesPerFace = 3 baseVertices = CreateTriangleVertices(_size) # Setup List Counts matrixCount = len(_matrices) faceCount = matrixCount vertexCount = faceCount * verticesPerFace # Setup Mesh Lists mesh = c4d.PolygonObject(vertexCount, faceCount) vertices = [None] * vertexCount faces = [None] * faceCount # Iterate through the matrices and transform the vertices accordingly for i, m in enumerate(_matrices): cnt = i * verticesPerFace if _quad: vertices[cnt:cnt + 4] = TransformVertices(baseVertices, m) faces[i] = c4d.CPolygon(cnt + 0, cnt + 1, cnt + 2, cnt + 3) else: vertices[cnt:cnt + 3] = TransformVertices(baseVertices, m) faces[i] = c4d.CPolygon(cnt + 0, cnt + 1, cnt + 2) # Translate the matrix of the mesh object to the centroid of the vertices centroid = Centroid(vertices) mesh.SetAbsPos(centroid) # Translate the vertices back to their original positions vertices = [v - centroid for v in vertices] # Set the mesh vertices mesh.SetAllPoints(vertices) # Set the mesh faces for i, f in enumerate(faces): mesh.SetPolygon(i, f) # Update the object mesh.Message(c4d.MSG_UPDATE) return mesh
def FixUpEmptyNulls(self, op): while op: # Add empty polygon objects to any null nodes with no children, so # that they are exported by the COLLADA exporter correctly. if nullTypeName in op.GetTypeName(): if len(op.GetChildren()) == 0: polyOp = c4d.PolygonObject(0, 0) polyOp.SetName(polygonName) polyOp.InsertUnder(op) self.polyCounter += 1 # Recurse thru the hierarchy self.FixUpEmptyNulls(op.GetDown()) op = op.GetNext()
def main(): doc.StartUndo() points = [] s = doc.GetSelection() for x in s: mat = x.GetMg() pos = mat.off posx = pos[0] posy = pos[1] posz = pos[2] pos = c4d.Vector(posx, posy, posz) points.append(pos) poly = c4d.PolygonObject(len(points),0) poly.SetAllPoints(points) doc.InsertObject(poly) doc.AddUndo(c4d.UNDOTYPE_NEW, poly) doc.EndUndo() c4d.EventAdd()
def main(): doc = c4d.documents.GetActiveDocument() # Get active Cinema 4D document doc.StartUndo() # Start recording undos try: # Try to execute following script points = [] # Initialize empty list for points selection = doc.GetActiveObjects( c4d.GETACTIVEOBJECTFLAGS_SELECTIONORDER ) # Get active object selection (selection order enabled) for obj in selection: # Loop through selection mat = obj.GetMg() # Get object's matrix pos = mat.off # Get object's position points.append(pos) # Add point to points list poly = c4d.PolygonObject(len(points), 0) # Initialize polygon object poly.SetAllPoints(points) # Set all points to polygon object doc.InsertObject(poly) # Insert polygon object to document doc.AddUndo(c4d.UNDOTYPE_NEW, poly) # Add undo command for adding new polygon object except: # If something went wrong pass # Do nothing doc.EndUndo() # Stop recording undos c4d.EventAdd() # Refresh Cinema 4D
def multipatch(self, shp): pts = [ c4d.Vector(x, z, y) - self.centre for (x, y), z in zip(shp.points, shp.z) ] nb_pts = len(pts) polys = [] id_pt = 0 n = 0 for p1, p2 in zip(shp.parts[:-1], shp.parts[1:]): nb_cotes = p2 - p1 #Triangles if nb_cotes == 3: poly = c4d.CPolygon(id_pt + n, id_pt + n + 1, id_pt + n + 2) polys.append(poly) #Quadrangles elif nb_cotes == 4: poly = c4d.CPolygon(id_pt + n, id_pt + n + 1, id_pt + n + 2, id_pt + n + 3) polys.append(poly) #Autres else: print 'attention ngons!' pass n += nb_cotes res = c4d.PolygonObject(nb_pts, len(polys)) #TODO : tag phong ! res.SetAllPoints(pts) for i, poly in enumerate(polys): res.SetPolygon(i, poly) res.Message(c4d.MSG_UPDATE) res.InsertUnder(self.geoms)
def polygonObjectFromPoints(pts): polyo = c4d.PolygonObject(len(pts), 0) polyo.SetAllPoints(pts) polyo.Message(c4d.MSG_UPDATE) return polyo
def create_point_object(points): res = c4d.PolygonObject(len(points), 0) res.SetAllPoints(points) res.Message(c4d.MSG_UPDATE) return res
def convert_primitive(self, prim, gltf, materials): # Helper functions def float2bytes(f): int_value = int(math.fabs(f * 32000.0)) high_byte = int(int_value / 256) low_byte = int_value - 256 * high_byte if f < 0: high_byte = 255 - high_byte low_byte = 255 - low_byte return (low_byte, high_byte) # Normals tag. (Contains 12 WORDs per polygon, enumerated like the following: ax,ay,az,bx,by,bz,cx,cy,cz,dx,dy,dz. # The value is the Real value of the normal vector component multiplied by 32000.0.) def set_normals(normal_tag, polygon, normal_a, normal_b, normal_c, normal_d): normal_list = [normal_a, normal_b, normal_c, normal_d] normal_buffer = normal_tag.GetLowlevelDataAddressW() vector_size = 6 component_size = 2 for v in range(4): normal = normal_list[v] component = [normal.x, normal.y, normal.z] for c in range(3): low_byte, high_byte = float2bytes(component[c]) normal_buffer[normal_tag.GetDataSize() * polygon + v * vector_size + c * component_size + 0] = chr(low_byte) normal_buffer[normal_tag.GetDataSize() * polygon + v * vector_size + c * component_size + 1] = chr(high_byte) def parse_normals(): normal = [] if 'NORMAL' in prim.attributes: normal = BinaryData.get_data_from_accessor( gltf, prim.attributes['NORMAL']) if normal: normaltag = c4d.NormalTag(nb_poly) for polyidx in range(nb_poly): poly = c4d_mesh.GetPolygon(polyidx) normal_a = self.switch_handedness_v3( self.list_to_vec3(normal[poly.a])) normal_b = self.switch_handedness_v3( self.list_to_vec3(normal[poly.b])) normal_c = self.switch_handedness_v3( self.list_to_vec3(normal[poly.c])) normal_d = c4d.Vector(0.0, 0.0, 0.0) set_normals(normaltag, polyidx, normal_a, normal_b, normal_c, normal_d) c4d_mesh.InsertTag(normaltag) # A Phong tag is needed to make C4D use the Normal Tag (seems to be done for Collada) phong = c4d.BaseTag(5612) c4d_mesh.InsertTag(phong) def parse_texcoords(index, c4d_mesh): texcoord_key = 'TEXCOORD_{}'.format(index) if texcoord_key in prim.attributes: uvs = BinaryData.get_data_from_accessor( gltf, prim.attributes[texcoord_key]) if uvs: uvtag = c4d.UVWTag(nb_poly) uvtag.SetName(texcoord_key) for i in range(0, nb_poly): poly = c4d_mesh.GetPolygon(i) aa = (uvs[poly.a][0], uvs[poly.a][1], 0.0) bb = (uvs[poly.b][0], uvs[poly.b][1], 0.0) cc = (uvs[poly.c][0], uvs[poly.c][1], 0.0) uvtag.SetSlow(i, aa, bb, cc, (0.0, 0.0, 0.0)) c4d_mesh.InsertTag(uvtag) def parse_vertex_colors(index, c4d_mesh): colors = [] color_key = 'COLOR_{}'.format(index) colortag = None if color_key in prim.attributes: colors = BinaryData.get_data_from_accessor( gltf, prim.attributes[color_key]) if colors: nb_verts = len(verts) colortag = c4d.VertexColorTag(nb_verts) colortag.SetPerPointMode(True) colortag.SetName(color_key) vtx_color_data = colortag.GetDataAddressW() has_alpha = len(colors[0]) > 3 for i in range(nb_verts): c4d.VertexColorTag.SetPoint( vtx_color_data, None, None, i, c4d.Vector4d(colors[i][0], colors[i][1], colors[i][2], colors[i][3] if has_alpha else 1.0)) c4d_mesh.InsertTag(colortag) self.has_vertex_colors = True return colortag def parse_tangents(): tangent = [] if 'TANGENT' in prim.attributes: tangent = BinaryData.get_data_from_accessor( gltf, prim.attributes['TANGENT']) if tangent: tangentTag = c4d.TangentTag(nb_poly) for polyidx in range(0, nb_poly): poly = c4d_mesh.GetPolygon(polyidx) normal_a = self.switch_handedness_v3( self.list_to_vec3(tangent[poly.a])) normal_b = self.switch_handedness_v3( self.list_to_vec3(tangent[poly.b])) normal_c = self.switch_handedness_v3( self.list_to_vec3(tangent[poly.c])) normal_d = c4d.Vector(0.0, 0.0, 0.0) set_normals(tangentTag, polyidx, normal_a, normal_b, normal_c, normal_d) c4d_mesh.InsertTag(tangentTag) vertex = BinaryData.get_data_from_accessor(gltf, prim.attributes['POSITION']) nb_vertices = len(vertex) # Vertices are stored under the form # [(1.0, 0.0, 0.0), (0.0, 0.0, 0.0) ...] verts = [] for i in range(len(vertex)): vect = c4d.Vector(vertex[i][0], vertex[i][1], vertex[i][2]) verts.append(self.switch_handedness_v3(vect)) indices = BinaryData.get_data_from_accessor(gltf, prim.indices) nb_poly = len(indices) / 3 c4d_mesh = c4d.PolygonObject(nb_vertices, nb_poly) c4d_mesh.SetAllPoints(verts) # Indices are stored like [(0,), (1,), (2,)] current_poly = 0 for i in range(0, len(indices), 3): poly = c4d.CPolygon( indices[i + 2][0], indices[i + 1][0], indices[i][0]) # indice list is like [(0,), (1,), (2,)] c4d_mesh.SetPolygon(current_poly, poly) current_poly += 1 parse_normals() # TANGENTS (Commented for now, "Tag not in sync" error popup in c4d) # parse_tangents() for texcoord_index in range(10): parse_texcoords(texcoord_index, c4d_mesh) mat = materials[prim.material] # Only parse COLORS_0 colortag = parse_vertex_colors(0, c4d_mesh) self.make_vertex_colors_layer(mat, colortag) # Enable vertex colors for material if not gltf.data.materials[prim.material].double_sided: mat.SetParameter(c4d.TEXTURETAG_SIDE, c4d.SIDE_FRONT, c4d.DESCFLAGS_SET_NONE) mattag = c4d.TextureTag() mattag.SetParameter(c4d.TEXTURETAG_MATERIAL, mat, c4d.DESCFLAGS_SET_NONE) mattag.SetParameter(c4d.TEXTURETAG_PROJECTION, c4d.TEXTURETAG_PROJECTION_UVW, c4d.DESCFLAGS_GET_NONE) c4d_mesh.InsertTag(mattag) c4d_mesh.SetDirty(c4d.DIRTYFLAGS_ALL) return c4d_mesh
def terrainFromASC(fn): """Attention le doc doit être en mètres""" name = os.path.basename(fn).split('.')[0] nb = 0 header = {} #lecture de l'entête pour savoir si on a 5 ou 6 lignes ( il y a des fichiers qui n'ont pas la ligne nodata) #ou encore 7 lignes commes qgis avec valeurs différentes pour dx, dy with open(fn, 'r') as file: while 1: s = file.readline() split = s.split() #si la première partie de split commence par un chiffre ou par le signe moins on break if re.match(r'^[0-9]', split[0]) or re.match(r'^-', split[0]): break k, v = split #print k,v header[k.lower( )] = v #QGIS met le NODATA_value en partie en majuscule !!! nb += 1 ncols = int(header['ncols']) nrows = int(header['nrows']) xcorner = float(header['xllcorner']) ycorner = float(header['yllcorner']) #on teste si on a une valeur cellsize if header.get('cellsize', None): cellsize = float(header['cellsize']) dx = cellsize dy = cellsize #sinon on récupère dx et dy else: dx = float(header['dx']) dy = float(header['dy']) nodata = 0. if nb == 6 or nb == 7: try: nodata = float(header['nodata_value']) except: nodata = 0. #lecture des altitudes with open(fn, 'r') as file: #on saute l'entête for i in xrange(nb): file.readline() nb_pts = ncols * nrows nb_poly = (ncols - 1) * (nrows - 1) poly = c4d.PolygonObject(nb_pts, nb_poly) poly.SetName(name) origine = c4d.Vector(xcorner, 0, ycorner + nrows * dy) pos = c4d.Vector(0) i = 0 for r in xrange(nrows): for val in file.readline().split(): y = float(val) if y == nodata: y = 0.0 pos.y = y poly.SetPoint(i, pos) pos.x += dx i += 1 pos.x = 0 pos.z -= dy polygonise(poly, nrows, ncols) insert_geotag(poly, origine) poly.Message(c4d.MSG_UPDATE) return poly