Skip to content

Instantly share code, notes, and snippets.

@NiklasRosenstein
Last active April 13, 2018 13:47
Show Gist options
  • Save NiklasRosenstein/6581356 to your computer and use it in GitHub Desktop.
Save NiklasRosenstein/6581356 to your computer and use it in GitHub Desktop.
#c4dpytask #medium How can you load a texture and assign it to a plane with image dimensions? (you need a LoadDialog, BaseBitmap and Oplane)
# @rosensteinn #c4dpytask #medium How can you load a texture and assign
# it to a plane with image dimensions? (you need a LoadDialog, BaseBitmap
# and Oplane)
import c4d
def main():
# Poll the user for a filename. We specify that the file-type may be
# an image only.
filename = c4d.storage.LoadDialog(c4d.FILESELECTTYPE_IMAGES)
# If the filename is empty, the user cancelled the dialog and does
# not want to proceed.
if not filename:
return
# Load the image into a bitmap.
bitmap = c4d.bitmaps.BaseBitmap()
result, ismovie = bitmap.InitWith(filename)
# We should abort if the image was not loaded correctly.
if result != c4d.IMAGERESULT_OK:
# And tell the user what happened!
c4d.gui.MessageDialog("The image could not be loaded, we're sorry about this!")
return
# If we come this far, the image was loaded successfully.
# We now need to obtain its dimensions in order to set the
# size of the plane which we'll create later.
width, height = bitmap.GetSize()
# Now create a Plane-Object and set its dimensions.
plane = c4d.BaseObject(c4d.Oplane)
plane[c4d.PRIM_PLANE_WIDTH] = width
plane[c4d.PRIM_PLANE_HEIGHT] = height
# Great! Now we need to insert the plane into the scene and tell the
# undo system about that!
doc.InsertObject(plane)
doc.AddUndo(c4d.UNDOTYPE_NEW, plane)
# Next step is to create a material with the image in the color
# channel! 1. The material
mat = c4d.BaseMaterial(c4d.Mmaterial)
# 2. The bitmap shader.
shader = c4d.BaseShader(c4d.Xbitmap)
shader[c4d.BITMAPSHADER_FILENAME] = filename
# 3. Add the shader to the material.
mat.InsertShader(shader) # 3a) insert
mat[c4d.MATERIAL_COLOR_SHADER] = shader # 3b) link
# 4. Insert the material into the document. (Remember that undo stuff
# from above?)
doc.InsertMaterial(mat)
doc.AddUndo(c4d.UNDOTYPE_NEW, mat)
# The last thing to do is to create a Texture Tag which references the
# material in UVW projection mode!
# Note: Since we've added the plane in this step, we do not need to add
# an undo for the tag. The tag will be removed with the plane when an
# undo was made!
texture_tag = plane.MakeTag(c4d.Ttexture)
texture_tag[c4d.TEXTURETAG_MATERIAL] = mat
texture_tag[c4d.TEXTURETAG_PROJECTION] = c4d.TEXTURETAG_PROJECTION_UVW
# Last but not least, tell Cinema to update the UI and the viewport.
c4d.EventAdd()
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment