Jump to content
  • entries
    944
  • comments
    5,899
  • views
    929,660

The Asset Loader Class


Josh

3,248 views

 Share

In Turbo (Leadwerks 5) all asset types have a list of asset loader objects for loading different file formats. There are a number of built-in loaders for different file formats, but you can add your own by deriving the AssetLoader class or creating a script-based loader. Another new feature is that any scripts in the "Scripts/Start" folder get run when your game starts. Put those together, and you can add support for a new model or texture file format just by dropping a script in your project.

The following script can be used to add support for loading RAW image files as a model heightmap.

function LoadModelRaw(stream, asset, flags)
	
	--Calculate and verify heightmap size - expects 2 bytes per terrain point, power-of-two sized
	local datasize = stream:GetSize()
	local pointsize = 2
	local points = datasize / pointsize
	if points * pointsize ~= datasize then return nil end
	local size = math.sqrt(points)
	if size * size ~= points then return nil end
	if math.pow(2, math.log(size) / math.log(2)) ~= size then return nil end

	--Create model
	local modelbase = ModelBase(asset)
	modelbase.model = CreateModel(nil)
	local mesh = modelbase.model:AddMesh()

	--Build mesh from height data
	local x,y,height,v
	local textureScale = 4
	local terrainHeight = 100
	for x = 1, size do
		for y = 1, size do
			height = stream:ReadUShort() / 65536
			v = mesh.AddVertex(x,height * terrainHeight,y, 0,1,0, x/textureScale, y/textureScale, 0,0, 1,1,1,1)
			if x > 1 and y > 1 then
				mesh:AddTriangle(v, v - size - 1, v - size)
				mesh:AddTriangle(v, v - 1, v - size - 1)
			end
		end
	end

	--Finalize the mesh
	mesh:UpdateBounds()
	mesh:UpdateNormals()
	mesh:UpdateTangents()
	mesh:Lock()

	--Finalize the model
	modelbase.model:UpdateBounds()
	modelbase.model:SetShape(CreateShape(mesh))
	
	return true
end

AddModelLoader(LoadModelRaw)

Loading a heightmap is just like loading any other model file:

auto model = LoadModel(world,"Models/Terrain/island.r16");

This will provide a temporary solution for terrain until the full system is finished.

  • Like 4
 Share

3 Comments


Recommended Comments

Neat. Is there a specific entry function for the start scripts, or just it just "import" the script into memory?

Link to comment
Guest
Add a comment...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...