MD3 Loading code with normals

BlitzMax Forums/BlitzMax Programming/MD3 Loading code with normals

JoshK(Posted 2007) [#1]
I tested it in my engine and it seems to work. Gmax forum moderators have posted a .3ds import script and a new .md3 export script in the GMax forum, and it appears to be okay for use if you export .md3 files:
	Method Load:TMesh(stream:TStream)
		If stream.ReadString(4)<>"IDP3" Return Null
		If stream.ReadInt()<>15 Return Null
		
		mesh:TMesh=CreateMesh()
		
		name$=stream.ReadString(64)
		flags=stream.ReadInt()
		numFrames=stream.ReadInt()
		numTags=stream.ReadInt()
		numSurfaces=stream.ReadInt()
		numSkins=stream.ReadInt()
		offsetFrames=stream.ReadInt()
		offsetTags=stream.ReadInt()
		offsetSurfaces=stream.ReadInt()
		offsetEnd=stream.ReadInt()
		
		Notify numSurfaces
		
		'Load surfaces
		stream.seek offsetSurfaces
		For surface=1 To numSurfaces
		
			surf:TSurface=CreateSurface(mesh)
		
			offsetStart=stream.pos()
			ident=stream.ReadInt()
			name$=stream.ReadString(64)
			flags=stream.ReadInt()
			numFrames=stream.ReadInt()
			numShaders=stream.ReadInt()
			numVertices=stream.ReadInt()
			numTriangles=stream.ReadInt()
			offsetTriangles=stream.ReadInt()
			offsetShaders=stream.ReadInt()
			offsetTexcoords=stream.ReadInt()
			offsetVertices=stream.ReadInt()
			offsetEnd=stream.ReadInt()
			
			'Vertices
			stream.seek offsetVertices+offsetStart
			For vertex=0 To numVertices-1 
				x#=Float(ReadSignedShort(stream))/64.0
				z#=Float(ReadSignedShort(stream))/64.0
				y#=Float(ReadSignedShort(stream))/64.0
				lng#=Float(stream.ReadByte())/256.0*360.0
				lat#=Float(stream.ReadByte())/256.0*360.0
				nx#=Cos(lat)*Sin(lng)
				nz#=Sin(lat)*Sin(lng)
				ny#=Cos(lng)
				Normalize nx,ny,nz
				nx=VectorX()
				ny=VectorY()
				vz=VectorZ()
				surf.addvertex x,y,z,nx,ny,nz
			Next
			
			'TexCoords
			stream.seek offsetTexcoords+offsetStart
			For v=0 To numVertices-1
				u0#=stream.ReadFloat()
				v0#=stream.ReadFloat()
				VertexTexCoords surf,v,u0,v0
			Next
			
			'Triangles
			stream.seek offsetTriangles+offsetStart
			For triangle=0 To numTriangles-1
				a=stream.ReadInt()
				b=stream.ReadInt()
				c=stream.ReadInt()
				AddTriangle surf,a,b,c
			Next

			stream.seek offsetend+offsetStart
		Next
		
		Return mesh
	EndMethod
	
	Function ReadSignedShort:Int(stream:TStream)
		Local result:Int
		result=stream.readshort()
		If result>32767 result=result-65535
		Return result
	EndFunction