2
0
mirror of https://github.com/rehlds/rehlds.git synced 2024-12-27 23:25:45 +03:00

Initial commit

This commit is contained in:
dreamstalker 2015-05-04 22:25:41 +04:00
parent c404ae1bbf
commit 7326bee095
423 changed files with 113935 additions and 0 deletions

16
.gitignore vendored Normal file
View File

@ -0,0 +1,16 @@
**/build
**/.gradle
.idea
*.iml
**/msvc/Debug*
**/msvc/Release*
**/msvc/*.sdf
**/msvc/*.opensdf
**/msvc/*.user
**/msvc/*.suo
**/msvc/ipch
rehlds/version/appversion.h
rehlds/msvc/PublishPath*.txt
rehlds/_rehldsTestImg
publish

44
build.gradle Normal file
View File

@ -0,0 +1,44 @@
import versioning.GitVersioner
import versioning.RehldsVersionInfo
apply plugin: 'maven-publish'
apply from: 'shared.gradle'
group = 'rehlds'
def gitInfo = GitVersioner.versionForDir(project.rootDir)
if (!gitInfo) {
throw new RuntimeException('Running outside git repository')
}
RehldsVersionInfo versionInfo
if (gitInfo.tag && gitInfo.tag[0] == 'v') {
def m = gitInfo.tag =~ /^v(\d+)\.(\d+)(\.(\d+))?$/
if (!m.find()) {
throw new RuntimeException("Invalid git version tag name ${gitInfo.tag}")
}
versionInfo = new RehldsVersionInfo(
majorVersion: m.group(1) as int,
minorVersion: m.group(2) as int,
maintenanceVersion: m.group(4) ? (m.group(4) as int) : null,
lastCommitDate: gitInfo.lastCommitDate
)
} else {
versionInfo = new RehldsVersionInfo(
majorVersion: project.majorVersion as int,
minorVersion: project.minorVersion as int,
suffix: 'SNAPSHOT',
lastCommitDate: gitInfo.lastCommitDate
)
}
project.ext.rehldsVersionInfo = versionInfo
project.version = versionInfo.asMavenVersion()
apply from: 'publish.gradle'
task wrapper(type: Wrapper) {
gradleVersion = '2.4-rc-2'
}

37
buildSrc/build.gradle Normal file
View File

@ -0,0 +1,37 @@
apply plugin: 'groovy'
repositories {
//mavenLocal()
mavenCentral()
maven {
url 'http://nexus.rehlds.org/nexus/content/repositories/rehlds-releases/'
}
maven {
url 'http://nexus.rehlds.org/nexus/content/repositories/rehlds-snapshots/'
}
}
configurations {
rehlds_it_image
}
dependencies {
compile gradleApi()
compile localGroovy()
compile 'commons-io:commons-io:2.4'
compile 'commons-lang:commons-lang:2.6'
compile 'joda-time:joda-time:2.7'
compile 'org.doomedsociety.gradlecpp:gradle-cpp-plugin:1.1'
compile 'org.eclipse.jgit:org.eclipse.jgit:3.7.0.201502260915-r'
compile 'org.apache.velocity:velocity:1.7'
}
buildscript {
configurations {
rehlds_it_image
}
}

View File

@ -0,0 +1,58 @@
package dirsync.builder
import dirsync.model.tree.DirectoryNode
import dirsync.model.tree.FileNode
import groovy.transform.CompileStatic
class FileSystemTreeBuilder {
@CompileStatic
private static FileNode<File> buildNodeForFile(File file, DirectoryNode<File> parent) {
if (parent.getChildren(file.name)) {
throw new RuntimeException("Parent dir ${parent.name} already contains child node ${file.name}");
}
return new FileNode(
name: file.name,
lastModifiedDate: file.lastModified(),
data: file,
parent: parent,
size: file.size()
);
}
@CompileStatic
private static DirectoryNode<File> buildNodeForDirectoryRecursive(File dir, DirectoryNode<File> parent) {
if (!dir.isDirectory()) {
throw new RuntimeException("File ${dir.absolutePath} is not a directory")
}
if (parent != null && parent.getChildren(dir.name)) {
throw new RuntimeException("Parent dir ${parent.name} already contains child node ${dir.name}");
}
DirectoryNode<File> thisNode = new DirectoryNode(
name: dir.name,
lastModifiedDate: dir.lastModified(),
data: dir,
parent: parent
);
dir.eachFile { File f ->
if (f.isDirectory()) {
thisNode.childNodes[f.name] = buildNodeForDirectoryRecursive(f, thisNode)
} else {
thisNode.childNodes[f.name] = buildNodeForFile(f, thisNode)
}
}
return thisNode;
}
static DirectoryNode<File> buildFileSystemTree(File rootDir) {
def root = buildNodeForDirectoryRecursive(rootDir, null);
PostBuildPass.doPostBuild(root)
return root
}
}

View File

@ -0,0 +1,60 @@
package dirsync.builder
import dirsync.model.tree.DirectoryNode
import dirsync.model.tree.FileNode
class FileTreeMerger {
private static <T> void mergeContentsRecursive(DirectoryNode<T> newParent, DirectoryNode<T> toMerge) {
toMerge.childNodes.each { cn ->
def node = cn.value
def existingNode = newParent.childNodes[node.name]
if (existingNode) {
if (!(existingNode instanceof DirectoryNode) || !(node instanceof DirectoryNode))
throw new RuntimeException("Failed to merge non-directory nodes ${node.fullPath}")
def existingDirNode = existingNode as DirectoryNode<T>
def dirNode = node as DirectoryNode<T>
existingDirNode.lastModifiedDate = Math.max(existingDirNode.lastModifiedDate, dirNode.lastModifiedDate)
mergeContentsRecursive(existingDirNode, dirNode)
} else {
if (node instanceof DirectoryNode) {
def dirNode = node as DirectoryNode<T>
def newNode = new DirectoryNode<T>(
name: dirNode.name,
data: dirNode.data,
parent: newParent,
lastModifiedDate: dirNode.lastModifiedDate
)
newParent.childNodes[node.name] = newNode
mergeContentsRecursive(newNode, dirNode)
} else {
FileNode<T> fileNode = node as FileNode<T>
FileNode<T> newNode = new FileNode<T>(
name: fileNode.name,
data: fileNode.data,
parent: newParent,
lastModifiedDate: fileNode.lastModifiedDate,
size: fileNode.size
)
newParent.childNodes[node.name] = newNode
}
}
}
}
public static <T> DirectoryNode<T> mergeTrees(DirectoryNode<T> tree1, DirectoryNode<T> tree2) {
DirectoryNode<T> newRoot = new DirectoryNode<T>(
name: tree1.name ?: tree2.name
)
mergeContentsRecursive(newRoot, tree1)
mergeContentsRecursive(newRoot, tree2)
PostBuildPass.doPostBuild(newRoot)
return newRoot
}
}

View File

@ -0,0 +1,22 @@
package dirsync.builder
import dirsync.model.tree.DirectoryNode
class PostBuildPass {
private static <T> void postProcessRecursive(DirectoryNode<T> dir) {
dir.childNodes.each { cne ->
def childNode = cne.value
childNode.fullPath = dir.fullPath ? dir.fullPath + '/' + childNode.name : childNode.name
if (childNode instanceof DirectoryNode) {
def childDirNode = childNode as DirectoryNode<T>
postProcessRecursive(childDirNode)
}
}
}
static <T> void doPostBuild(DirectoryNode<T> root) {
root.fullPath = ''
postProcessRecursive(root)
}
}

View File

@ -0,0 +1,53 @@
package dirsync.builder
import dirsync.model.tree.DirectoryNode
import dirsync.model.tree.FileNode
import dirsync.model.tree.ZipData
import java.util.zip.ZipFile
class ZipTreeBuilder {
static DirectoryNode<ZipData> buildForZipArchive(String zipArchive, ZipFile zf) {
DirectoryNode<ZipData> root = new DirectoryNode<>()
zf.entries().each { ze ->
def path = ze.name.replace('\\', '/')
if (path.endsWith('/'))
path = path.substring(0, path.length() - 1)
def parentPath = path.contains('/') ? path.substring(0, path.lastIndexOf('/')) : ''
def childPath = path.contains('/') ? path.substring(path.lastIndexOf('/') + 1) : path
def parentNode = (DirectoryNode<ZipData>) root.getByPath(parentPath)
if (parentNode == null)
throw new RuntimeException("Error reading ${zipArchive}: could not find parent path ${parentPath} for path ${path}")
def childNode = parentNode.getChildren(childPath)
if (childNode)
throw new RuntimeException("Error reading ${zipArchive}: duplicate path ${path}")
if (ze.directory) {
childNode = new DirectoryNode<ZipData>(
name: childPath,
lastModifiedDate: ze.time,
data: new ZipData(zipEntryName: ze.name, zipArchiveName: zipArchive),
parent: parentNode
);
} else {
childNode = new FileNode<ZipData>(
name: childPath,
lastModifiedDate: ze.time,
data: new ZipData(zipEntryName: ze.name, zipArchiveName: zipArchive),
parent: parentNode,
size: ze.size
);
}
parentNode.childNodes[childPath] = childNode
//println '' + ze.directory + ' ' + ze.name + ' ' + parentPath + ' ' + childPath
}
PostBuildPass.doPostBuild(root)
return root
}
}

View File

@ -0,0 +1,97 @@
package dirsync.merger
import dirsync.model.synccmd.AbstractSyncCmd
import dirsync.model.synccmd.CopyDirCmd
import dirsync.model.synccmd.CopyFileCmd
import dirsync.model.synccmd.DeleteDirCmd
import dirsync.model.synccmd.DeleteFileCmd
import dirsync.model.synccmd.ReplaceFileCmd
import dirsync.model.tree.DirectoryNode
import dirsync.model.tree.FileNode
import groovy.transform.TypeChecked
@TypeChecked
class FileTreeComparator {
private static <T, U> void mergeDirsRecursive(DirectoryNode<T> left, DirectoryNode<U> right, List<AbstractSyncCmd<T, U>> diffs) {
// left => right
left.childNodes.each { le ->
def leftNode = le.value
def rightNode = right.childNodes[leftNode.name]
if (rightNode == null) {
switch (leftNode) {
case DirectoryNode:
def leftDirNode = leftNode as DirectoryNode<T>
diffs << new CopyDirCmd<>(src: leftDirNode, dstParentDir: right)
break
case FileNode:
def leftFileNode = leftNode as FileNode<T>
diffs << new CopyFileCmd<>(src: leftFileNode, dstDir: right)
break
default:
throw new RuntimeException("Invalid node class ${leftNode.class.name}")
}
return
}
if (rightNode.class != leftNode.class) {
throw new RuntimeException("node classes mismatch: ${leftNode.class.name} != ${rightNode.class.name}")
}
switch (rightNode) {
case DirectoryNode:
def leftDirNode = leftNode as DirectoryNode<T>
def rightDirNode = rightNode as DirectoryNode<U>
mergeDirsRecursive(leftDirNode, rightDirNode, diffs)
break
case FileNode:
def leftFileNode = leftNode as FileNode<T>
def rightFileNode = rightNode as FileNode<T>
if (leftFileNode.size != rightFileNode.size || leftFileNode.lastModifiedDate != rightFileNode.lastModifiedDate) {
diffs << new ReplaceFileCmd<>(src: leftFileNode, dst: rightFileNode)
}
break
default:
throw new RuntimeException("Invalid node class ${rightNode.class.name}")
}
} // ~left => right
//right => left
right.childNodes.each { re ->
def rightNode = re.value
def leftNode = left.childNodes[rightNode.name]
if (leftNode != null) {
return //already processed in left => right
}
switch (rightNode) {
case DirectoryNode:
def rightDirNode = rightNode as DirectoryNode<U>
diffs << new DeleteDirCmd<>(dirNode: rightDirNode)
break
case FileNode:
def rightFileNode = rightNode as FileNode<T>
diffs << new DeleteFileCmd<>(node: rightFileNode)
break
default:
throw new RuntimeException("Invalid node class ${rightNode.class.name}")
}
} // ~right => left
}
static <T, U> List<AbstractSyncCmd<T, U>> mergeTrees(DirectoryNode<T> leftRoot, DirectoryNode<U> rightRoot) {
List<AbstractSyncCmd<T, U>> res = []
mergeDirsRecursive(leftRoot, rightRoot, res)
return res
}
}

View File

@ -0,0 +1,103 @@
package dirsync.merger
import dirsync.model.synccmd.AbstractSyncCmd
import dirsync.model.synccmd.CopyDirCmd
import dirsync.model.synccmd.CopyFileCmd
import dirsync.model.synccmd.DeleteDirCmd
import dirsync.model.synccmd.DeleteFileCmd
import dirsync.model.synccmd.ReplaceFileCmd
import dirsync.model.tree.DirectoryNode
import dirsync.model.tree.FileNode
import dirsync.model.tree.TreePhysMapper
import groovy.transform.TypeChecked
import org.apache.commons.io.IOUtils
@TypeChecked
public class FileTreeDiffApplier {
static <T, U> void copyDirRecursive(DirectoryNode<T> src, TreePhysMapper<T> srcMapper, TreePhysMapper<U> dstMapper) {
dstMapper.createDirectory(src.fullPath)
src.childNodes.each { ce ->
def childNode = ce.value
def childPath = childNode.fullPath
switch (childNode) {
case FileNode:
srcMapper.fileContent(childNode.data).withStream { InputStream inStream ->
dstMapper.createFile(childPath).withStream { OutputStream outStream ->
IOUtils.copy(inStream, outStream)
}
dstMapper.setFileLastUpdatedDate(childPath, childNode.lastModifiedDate)
}
break;
case DirectoryNode:
copyDirRecursive(childNode as DirectoryNode<T>, srcMapper, dstMapper)
break;
default:
throw new RuntimeException("Invalid node class: ${childNode.class.name}")
}
}
}
static <T, U> void handleCopyFile(CopyFileCmd<T, U> fileCopy, TreePhysMapper<T> srcMapper, TreePhysMapper<U> dstMapper) {
def dstPath = fileCopy.dstDir.fullPath ? fileCopy.dstDir.fullPath + '/' + fileCopy.src.name : fileCopy.src.name
srcMapper.fileContent(fileCopy.src.data).withStream { InputStream inStream ->
dstMapper.createFile(dstPath).withStream { OutputStream outStream ->
IOUtils.copy(inStream, outStream)
}
dstMapper.setFileLastUpdatedDate(dstPath, fileCopy.src.lastModifiedDate)
}
}
static <T, U> void handleDeleteDir(DeleteDirCmd<T, U> delDir, TreePhysMapper<T> srcMapper, TreePhysMapper<U> dstMapper) {
dstMapper.removeDirectory(delDir.dirNode.fullPath)
}
static <T, U> void handleDeleteFile(DeleteFileCmd<T, U> delFile, TreePhysMapper<T> srcMapper, TreePhysMapper<U> dstMapper) {
dstMapper.removeFile(delFile.node.fullPath)
}
static <T, U> void handleReplaceFile(ReplaceFileCmd<T, U> replaceFile, TreePhysMapper<T> srcMapper, TreePhysMapper<U> dstMapper) {
dstMapper.removeFile(replaceFile.dst.fullPath)
srcMapper.fileContent(replaceFile.src.data).withStream { InputStream inStream ->
dstMapper.createFile(replaceFile.dst.fullPath).withStream { OutputStream outStream ->
IOUtils.copy(inStream, outStream)
}
dstMapper.setFileLastUpdatedDate(replaceFile.dst.fullPath, replaceFile.src.lastModifiedDate)
}
}
static <T, U> void applyDiffs(List<AbstractSyncCmd<T, U>> diffs, TreePhysMapper<T> srcMapper, TreePhysMapper<U> dstMapper) {
diffs.each { diff ->
switch (diff) {
case CopyDirCmd:
def copyDir = diff as CopyDirCmd<T, U>
copyDirRecursive(copyDir.src, srcMapper, dstMapper)
break
case CopyFileCmd:
handleCopyFile(diff as CopyFileCmd<T, U>, srcMapper, dstMapper)
break
case DeleteDirCmd:
handleDeleteDir(diff as DeleteDirCmd<T, U>, srcMapper, dstMapper)
break
case DeleteFileCmd:
handleDeleteFile(diff as DeleteFileCmd<T, U>, srcMapper, dstMapper)
break
case ReplaceFileCmd:
handleReplaceFile(diff as ReplaceFileCmd<T, U>, srcMapper, dstMapper)
break
default:
throw new RuntimeException("Invalid diff command ${diff.class.name}")
}
}
}
}

View File

@ -0,0 +1,4 @@
package dirsync.model.synccmd
class AbstractSyncCmd<T, U> {
}

View File

@ -0,0 +1,8 @@
package dirsync.model.synccmd
import dirsync.model.tree.DirectoryNode
class CopyDirCmd<T, U> extends AbstractSyncCmd<T, U> {
DirectoryNode<T> src
DirectoryNode<U> dstParentDir
}

View File

@ -0,0 +1,9 @@
package dirsync.model.synccmd
import dirsync.model.tree.DirectoryNode
import dirsync.model.tree.FileNode
class CopyFileCmd<T, U> extends AbstractSyncCmd<T, U> {
FileNode<T> src
DirectoryNode<U> dstDir
}

View File

@ -0,0 +1,7 @@
package dirsync.model.synccmd
import dirsync.model.tree.DirectoryNode
class DeleteDirCmd<T, U> extends AbstractSyncCmd<T, U> {
DirectoryNode<U> dirNode
}

View File

@ -0,0 +1,7 @@
package dirsync.model.synccmd
import dirsync.model.tree.FileNode
class DeleteFileCmd<T, U> extends AbstractSyncCmd<T, U> {
FileNode<U> node
}

View File

@ -0,0 +1,8 @@
package dirsync.model.synccmd
import dirsync.model.tree.FileNode
class ReplaceFileCmd<T, U> extends AbstractSyncCmd<T, U> {
FileNode<T> src
FileNode<U> dst
}

View File

@ -0,0 +1,27 @@
package dirsync.model.tree
import groovy.transform.CompileStatic
@CompileStatic
abstract class AbstractFileTreeNode<T> {
DirectoryNode<T> parent
String name
String fullPath
long lastModifiedDate
T data
boolean equals(o) {
if (this.is(o)) return true
if (getClass() != o.class) return false
AbstractFileTreeNode that = (AbstractFileTreeNode) o
if (name != that.name) return false
return true
}
int hashCode() {
return (name != null ? name.hashCode() : 0)
}
}

View File

@ -0,0 +1,42 @@
package dirsync.model.tree
import groovy.transform.CompileStatic
@CompileStatic
class DirectoryNode<T> extends AbstractFileTreeNode<T> {
Map<String, AbstractFileTreeNode<T>> childNodes = new HashMap<>()
AbstractFileTreeNode<T> getChildren(String name) {
return childNodes[name];
}
AbstractFileTreeNode<T> getChildren(String[] names, int idx) {
if (idx == names.length)
return this
AbstractFileTreeNode<T> c = childNodes[names[idx]]
if (c == null)
return null
if (c instanceof DirectoryNode) {
def d = (DirectoryNode<T>) c;
return d.getChildren(names, idx + 1)
}
return null;
}
AbstractFileTreeNode<T> getByPath(String path) {
path = path.replace('\\', '/')
if (path.endsWith('/'))
path = path.substring(0, path.length() - 1)
if (path.empty) {
return this
}
String[] components = path.split('/')
return getChildren(components, 0)
}
}

View File

@ -0,0 +1,50 @@
package dirsync.model.tree
class FSMapper extends TreePhysMapper<File> {
final File root
FSMapper(File root) {
this.root = root
}
@Override
InputStream fileContent(File file) {
return file.newDataInputStream()
}
@Override
void createDirectory(String dir) {
def target = new File(root, dir)
if (!target.mkdirs()) {
throw new RuntimeException("Failed to create directory ${target.absolutePath}")
}
}
@Override
void removeDirectory(String dir) {
def target = new File(root, dir)
if (!target.deleteDir()) {
throw new RuntimeException("Failed to delete directory ${target.absolutePath}")
}
}
@Override
void removeFile(String path) {
def target = new File(root, path)
if (!target.delete()) {
throw new RuntimeException("Failed to delete file ${target.absolutePath}")
}
}
@Override
OutputStream createFile(String path) {
def target = new File(root, path)
return target.newOutputStream()
}
@Override
void setFileLastUpdatedDate(String path, long date) {
def target = new File(root, path)
target.setLastModified(date)
}
}

View File

@ -0,0 +1,8 @@
package dirsync.model.tree
import groovy.transform.CompileStatic
@CompileStatic
class FileNode<T> extends AbstractFileTreeNode<T> {
long size
}

View File

@ -0,0 +1,11 @@
package dirsync.model.tree
abstract class TreePhysMapper<T> {
abstract InputStream fileContent(T file)
abstract void createDirectory(String dir)
abstract void removeDirectory(String dir)
abstract void removeFile(String path)
abstract OutputStream createFile(String path)
abstract void setFileLastUpdatedDate(String path, long date)
}

View File

@ -0,0 +1,9 @@
package dirsync.model.tree
import groovy.transform.CompileStatic
@CompileStatic
class ZipData {
String zipEntryName
String zipArchiveName
}

View File

@ -0,0 +1,72 @@
package dirsync.model.tree
import dirsync.builder.FileTreeMerger
import dirsync.builder.ZipTreeBuilder
import sun.reflect.generics.reflectiveObjects.NotImplementedException
import java.util.zip.ZipFile
public class ZipTreeMapper extends TreePhysMapper<ZipData> implements Closeable {
Map<String, ZipFile> zipArchives = [:]
void addZipArchive(String zipArchive) {
zipArchives[zipArchive] = new ZipFile(zipArchive)
}
DirectoryNode<ZipData> buildFileTree() {
def root = new DirectoryNode<ZipData>()
zipArchives.each { ze ->
def zipTree = ZipTreeBuilder.buildForZipArchive(ze.key, ze.value)
root = FileTreeMerger.mergeTrees(root, zipTree)
}
return root
}
@Override
void close() throws IOException {
zipArchives.each { ze ->
try { ze.value.close() } catch (Exception ignored) { }
}
}
@Override
InputStream fileContent(ZipData file) {
def archive = zipArchives[file.zipArchiveName]
if (!archive) {
throw new RuntimeException("Archive ${file.zipArchiveName} is not loaded");
}
def zipEntry = archive.getEntry(file.zipEntryName)
if (!zipEntry) {
throw new RuntimeException("File ${file.zipEntryName} not found in archive ${file.zipArchiveName}");
}
return archive.getInputStream(zipEntry)
}
@Override
void createDirectory(String dir) {
throw new NotImplementedException()
}
@Override
void removeDirectory(String dir) {
throw new NotImplementedException()
}
@Override
void removeFile(String path) {
throw new NotImplementedException()
}
@Override
OutputStream createFile(String path) {
throw new NotImplementedException()
}
@Override
void setFileLastUpdatedDate(String path, long date) {
throw new NotImplementedException()
}
}

View File

@ -0,0 +1,19 @@
package gradlecpp
import org.gradle.api.Project
import org.gradle.nativeplatform.NativeBinarySpec
class CppUnitTestExtension {
Project _project
CppUnitTestExtension(Project p) {
_project = p
}
void eachTestExecutable(Closure action) {
_project.binaries.each { NativeBinarySpec bin ->
if (!bin.hasProperty('cppUnitTestsExecutable')) return
action(bin)
}
}
}

View File

@ -0,0 +1,242 @@
package gradlecpp
import gradlecpp.teamcity.TeamCityIntegration
import org.gradle.api.Action
import org.gradle.api.GradleException
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.internal.project.AbstractProject
import org.gradle.model.internal.core.DirectNodeModelAction
import org.gradle.model.internal.core.ModelActionRole
import org.gradle.model.internal.core.ModelPath
import org.gradle.model.internal.core.ModelReference
import org.gradle.model.internal.core.MutableModelNode
import org.gradle.model.internal.core.rule.describe.ModelRuleDescriptor
import org.gradle.model.internal.core.rule.describe.SimpleModelRuleDescriptor
import org.gradle.model.internal.registry.ModelRegistry
import org.gradle.nativeplatform.NativeBinarySpec
import org.gradle.nativeplatform.NativeLibrarySpec
import org.gradle.nativeplatform.internal.AbstractNativeBinarySpec
import org.doomedsociety.gradlecpp.GradleCppUtils
class CppUnitTestPlugin implements Plugin<Project> {
private static class TestExecStatus {
boolean successful
int exitCode
String output
long durationMsec
String cmdLine
String execDir
}
static void onBinariesCreated(Project p, String desc, Closure action) {
ModelRegistry mr = (p as AbstractProject).getModelRegistry()
def modelPath = ModelPath.path("binaries")
ModelRuleDescriptor ruleDescriptor = new SimpleModelRuleDescriptor(desc);
mr.configure(ModelActionRole.Finalize, DirectNodeModelAction.of(ModelReference.of(modelPath), ruleDescriptor, new Action<MutableModelNode>() {
@Override
void execute(MutableModelNode node) {
action()
}
}))
}
@Override
void apply(Project project) {
project.extensions.create('cppUnitTest', CppUnitTestExtension, project)
onBinariesCreated(project, 'CppUnitTestPlugin::AttachUnitTest', {
processCppUnitTests(project)
})
}
/**
* Attaches test tasks to C/C++ libraries build tasks
*/
static void processCppUnitTests(Project p) {
//println "processCppUnitTests::afterEvaluate on ${p.name}: project type is ${p.projectType}"
p.binaries.all { NativeBinarySpec bin ->
if (!(bin.component instanceof NativeLibrarySpec)) {
return
}
def testComponentName = bin.component.name + '_tests'
Collection<NativeBinarySpec> testCandidates = p.binaries.matching { it.component.name == testComponentName && bin.buildType == it.buildType && bin.flavor == it.flavor }
if (testCandidates.size() > 1) {
throw new GradleException("Found >1 test candidates for library ${bin.component.name} in project ${p}: ${testCandidates}")
} else if (!testCandidates.empty) {
def testBinary = testCandidates.first()
GradleCppUtils.onTasksCreated(p, 'CppUnitTestPlugin::AttachUnitTestTask', {
attachTestTaskToCppLibrary(bin, testBinary)
})
String testTaskName = bin.namingScheme.getTaskName('unitTest')
bin.ext.cppUnitTestTask = testTaskName
} else {
throw new GradleException("No tests found for library ${bin.component.name} in project ${p}")
}
}
}
static TestExecStatus runTestExecutable(NativeBinarySpec testSubject, String executable, List<String> params, String phase, int timeout) {
def execFile = new File(executable)
def outDir = new File(testSubject.buildTask.project.buildDir, "tests/${testSubject.name}/run")
outDir.mkdirs()
def outPath = new File(outDir, "${phase}.log")
def cmdParams = [];
cmdParams << execFile.absolutePath
cmdParams.addAll(params)
def execDir = execFile.parentFile
def pb = new ProcessBuilder(cmdParams).redirectErrorStream(true).directory(execDir)
if (!GradleCppUtils.windows) {
pb.environment().put('LD_LIBRARY_PATH', '.')
}
def sout = new StringBuffer()
long startTime = System.currentTimeMillis()
def p = pb.start()
p.consumeProcessOutput(sout, sout)
p.waitForOrKill(timeout * 1000)
long endTime = System.currentTimeMillis()
int exitVal = p.exitValue()
outPath.withWriter('UTF-8') { writer ->
writer.write(sout.toString())
}
return new TestExecStatus(
exitCode: exitVal,
successful: (exitVal == 0),
output: sout.toString(),
durationMsec: endTime - startTime,
cmdLine: cmdParams.join(' '),
execDir: execDir.absolutePath
)
}
static void dumpTestExecStatus(TestExecStatus stat) {
if (!stat) {
println "Execution of test executable failed"
}
println "Test executable command: ${stat.cmdLine}"
println "Test executable run directury: ${stat.execDir}"
println "Test executable exit code: ${stat.exitCode}"
println "Test executable output BEGIN"
println stat.output
println "Test executable output END"
}
static void attachTestTaskToCppLibrary(NativeBinarySpec libBin, NativeBinarySpec testExecBin) {
Project p = libBin.buildTask.project
def libBinImpl = libBin as AbstractNativeBinarySpec
def libLinkTask = GradleCppUtils.getLinkTask(libBin)
def testExecLinkTask = GradleCppUtils.getLinkTask(testExecBin)
// collect all output files from library and test executable
def depFiles = []
depFiles.addAll(libLinkTask.outputs.files.files)
depFiles.addAll(testExecLinkTask.outputs.files.files)
//create 'tests' task
def testTaskName = libBinImpl.namingScheme.getTaskName('unitTest')
def testTask = p.task(testTaskName, { Task testTask ->
//output dir
def testResDir = new File(p.buildDir, "tests/${libBin.name}")
//inputs/outputs for up-to-date check
testTask.outputs.dir testResDir
testTask.inputs.files depFiles
//dependencies on library and test executable
testTask.dependsOn libLinkTask
testTask.dependsOn testExecLinkTask
// binary build depends on unit test
libBin.buildTask.dependsOn testTask
// extra project-specific dependencies
def testDepsTask = p.tasks.findByName('testDeps')
if (testDepsTask != null) {
testTask.dependsOn testDepsTask
}
// task actions
testTask.doLast {
//temporary file that store info about all tests (XML)
File allTests = File.createTempFile('j4s-testinfo', 'data')
allTests.deleteOnExit()
//fill file with test info
print "Fetching test info..."
def getTestsStatus = runTestExecutable(libBin, testExecBin.executableFile.absolutePath, ['-writeTestInfo', allTests.absolutePath], '__getTests', 5000)
if (!getTestsStatus.successful) {
println " Failed"
dumpTestExecStatus(getTestsStatus)
throw new GradleException("Unable to fetch test names")
}
println " OK"
getTestsStatus = null // allow GC to collect it
// parse the test info file
def root = new XmlSlurper().parse(allTests)
// run all tests
println "Running ${root.test.size()} tests..."
TeamCityIntegration.suiteStarted("unitTests.${libBin.name}")
int failCount = 0;
root.test.list().each { testInfo ->
def testName = '' + testInfo.@name.text()
def testGroup = '' + testInfo.@group.text()
def testTimeout = ('' + testInfo.@timeout.text()) as int
if (!TeamCityIntegration.writeOutput) {
print " ${testGroup}-${testName}..."
System.out.flush()
}
TeamCityIntegration.testStarted("${testGroup}-${testName}")
def testExecStatus = runTestExecutable(libBin, testExecBin.executableFile.absolutePath, ['-runTest', testGroup, testName], "${testGroup}-${testName}", testTimeout)
if (!testExecStatus.successful) {
if (!TeamCityIntegration.writeOutput) {
println " Failed"
}
TeamCityIntegration.testFailed("${testGroup}-${testName}", "test executable return code is ${testExecStatus.exitCode}", "test executable return code is ${testExecStatus.exitCode}")
dumpTestExecStatus(testExecStatus)
failCount++
} else {
if (!TeamCityIntegration.writeOutput) {
println " OK"
}
}
TeamCityIntegration.testStdOut("${testGroup}-${testName}", testExecStatus.output)
TeamCityIntegration.testFinished("${testGroup}-${testName}", testExecStatus.durationMsec)
}
TeamCityIntegration.suiteFinished("unitTests.${libBin.name}")
if (failCount) {
throw new GradleException("CPP unit tests: ${failCount} tests failed");
}
}
})
}
}

View File

@ -0,0 +1,17 @@
package gradlecpp
import org.gradle.api.Plugin
import org.gradle.api.Project
class RehldsPlayTestPlugin implements Plugin<Project> {
@Override
void apply(Project project) {
project.configurations {
rehlds_playtest_image
}
project.dependencies {
rehlds_playtest_image 'rehlds.testimg:testimg:0.2'
}
}
}

View File

@ -0,0 +1,80 @@
package gradlecpp
import gradlecpp.teamcity.TeamCityIntegration
import org.apache.commons.lang.SystemUtils
import org.gradle.api.DefaultTask
import org.gradle.api.file.FileCollection
import org.gradle.api.tasks.TaskAction
import org.gradle.nativeplatform.NativeBinarySpec
import rehlds.testdemo.RehldsDemoRunner
import rehlds.testdemo.RehldsTestParser
class RehldsPlayTestTask extends DefaultTask {
def FileCollection testDemos
def Closure postExtractAction
def File rehldsImageRoot
def File rehldsTestLogs
def NativeBinarySpec testFor
@TaskAction
def doPlay() {
if (!SystemUtils.IS_OS_WINDOWS) {
return
}
if (!testDemos) {
println 'RehldsPlayTestTask: no demos attached to the testDemos property'
}
rehldsImageRoot.mkdirs()
rehldsTestLogs.mkdirs()
def demoRunner = new RehldsDemoRunner(this.project.configurations.rehlds_playtest_image.getFiles(), rehldsImageRoot, postExtractAction)
println "Preparing engine..."
demoRunner.prepareEngine()
println "Running ${testDemos.getFiles().size()} ReHLDS test demos..."
TeamCityIntegration.suiteStarted("rehldsDemo.${testFor.name}")
int failCount = 0;
testDemos.getFiles().each { f ->
def testInfo = RehldsTestParser.parseTestInfo(f)
TeamCityIntegration.testStarted(testInfo.testName)
if (!TeamCityIntegration.writeOutput) {
print "Running ReHLDS test demo ${testInfo.testName} "
System.out.flush()
}
def testRes = demoRunner.runTest(testInfo, rehldsTestLogs)
if (testRes.success) {
if (!TeamCityIntegration.writeOutput) {
println ' OK'
}
} else {
TeamCityIntegration.testFailed(testInfo.testName, "Exit code: ${testRes.returnCode}", "Exit code: ${testRes.returnCode}")
if (!TeamCityIntegration.writeOutput) {
println ' Failed'
println "ReHLDS testdemo ${testInfo.testName} playback failed. Exit status is ${testRes.returnCode}."
println "Dumping console output:"
println testRes.hldsConsoleOutput
}
failCount++
}
TeamCityIntegration.testStdOut(testInfo.testName, testRes.hldsConsoleOutput)
TeamCityIntegration.testFinished(testInfo.testName, testRes.duration)
}
TeamCityIntegration.suiteFinished("rehldsDemo.${testFor.name}")
if (failCount) {
throw new RuntimeException("Rehlds testdemos: failed ${failCount} tests")
}
}
}

View File

@ -0,0 +1,38 @@
package gradlecpp
import org.apache.velocity.Template
import org.apache.velocity.VelocityContext
import org.apache.velocity.app.Velocity
import org.joda.time.format.DateTimeFormat
class VelocityUtils {
static {
Properties p = new Properties();
p.setProperty("resource.loader", "class");
p.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
p.setProperty("class.resource.loader.path", "");
p.setProperty("input.encoding", "UTF-8");
p.setProperty("output.encoding", "UTF-8");
Velocity.init(p);
}
static String renderTemplate(File tplFile, Map<String, ? extends Object> ctx) {
Template tpl = Velocity.getTemplate(tplFile.absolutePath)
if (!tpl) {
throw new RuntimeException("Failed to load velocity template ${tplFile.absolutePath}: not found")
}
def velocityContext = new VelocityContext(ctx)
velocityContext.put("_DateTimeFormat", DateTimeFormat)
def sw = new StringWriter()
tpl.merge(velocityContext, sw)
return sw.toString()
}
}

View File

@ -0,0 +1,84 @@
package gradlecpp.teamcity
import groovy.transform.CompileStatic
class TeamCityIntegration {
static final String flowId = System.getenv('TEAMCITY_PROCESS_FLOW_ID')
static final boolean underTeamcity = System.getenv('TEAMCITY_PROJECT_NAME')
static boolean writeOutput = underTeamcity
@CompileStatic
private static String escape(String s) {
StringBuilder sb = new StringBuilder((int)(s.length() * 1.2));
for (char c in s.chars) {
switch (c) {
case '\n': sb.append('|n'); break;
case '\r': sb.append('|r'); break;
case '\'': sb.append('|\''); break;
case '|': sb.append('||'); break;
case ']': sb.append('|]'); break;
default: sb.append(c);
}
}
return sb.toString()
}
@CompileStatic
static void writeMessage(String name, Map params) {
if (!writeOutput) return
StringBuilder sb = new StringBuilder()
sb.append('##teamcity[').append(name)
params.each { e ->
if (e.value != null) {
sb.append(' ').append('' + e.key).append('=\'').append(escape('' + e.value)).append('\'')
}
}
sb.append(']')
println sb.toString()
}
static void suiteStarted(String suiteName) {
writeMessage('testSuiteStarted', [name: suiteName, flowId: flowId ?: null])
}
static void suiteFinished(String suiteName) {
writeMessage('testSuiteFinished', [name: suiteName, flowId: flowId ?: null])
}
static void testStarted(String testName) {
writeMessage('testStarted', [name: testName, flowId: flowId ?: null])
}
static void testStdOut(String testName, String output) {
writeMessage('testStdOut', [name: testName, out: output, flowId: flowId ?: null])
}
static void testFinished(String testName, long durationMs) {
writeMessage('testFinished', [
name: testName,
flowId: flowId ?: null,
duration: (durationMs >= 0) ? durationMs : null
])
}
static void testFailed(String testName, String message, String details) {
writeMessage('testFailed', [
name: testName,
flowId: flowId ?: null,
message: message,
details: details
])
}
static void testIgnored(String testName, String message) {
writeMessage('testIgnored', [
name: testName,
flowId: flowId ?: null,
message: message,
])
}
}

View File

@ -0,0 +1,81 @@
package rehlds.testdemo
import dirsync.builder.FileSystemTreeBuilder
import dirsync.merger.FileTreeComparator
import dirsync.merger.FileTreeDiffApplier
import dirsync.model.tree.DirectoryNode
import dirsync.model.tree.FSMapper
import dirsync.model.tree.ZipData
import dirsync.model.tree.ZipTreeMapper
class RehldsDemoRunner {
ZipTreeMapper rehldsImage = new ZipTreeMapper()
File rootDir
DirectoryNode<ZipData> engineImageTree
Closure postExtract
static class TestResult {
boolean success
int returnCode
String hldsConsoleOutput
long duration
}
RehldsDemoRunner(Collection<File> engineImageZips, File rootDir, Closure postExtract) {
this.rootDir = rootDir
engineImageZips.each { f ->
rehldsImage.addZipArchive(f.absolutePath)
}
engineImageTree = rehldsImage.buildFileTree()
this.postExtract = postExtract
}
void prepareEngine() {
def existingTree = FileSystemTreeBuilder.buildFileSystemTree(rootDir)
def cmds = FileTreeComparator.mergeTrees(engineImageTree, existingTree)
FSMapper fsMapper = new FSMapper(rootDir)
FileTreeDiffApplier.applyDiffs(cmds, rehldsImage, fsMapper)
if (postExtract != null) {
postExtract.run()
}
}
TestResult runTest(RehldsTestInfo info, File testLogDir) {
long startTime = System.currentTimeMillis()
prepareEngine()
def outPath = new File(testLogDir, "${info.testName}_run.log")
def cmdParams = []
cmdParams << new File(rootDir, 'hlds.exe').absolutePath
cmdParams.addAll(info.hldsArgs)
if (info.rehldsExtraArgs) {
cmdParams.addAll(info.rehldsExtraArgs)
}
cmdParams << '--rehlds-test-play' << info.testBinFile.absolutePath
def pb = new ProcessBuilder(cmdParams).redirectErrorStream(true).directory(rootDir)
def sout = new StringBuffer()
def p = pb.start()
p.consumeProcessOutput(sout, sout)
p.waitForOrKill(info.timeoutSeconds * 1000)
int exitVal = p.exitValue()
outPath.withWriter('UTF-8') { writer ->
writer.write(sout.toString())
}
long endTime = System.currentTimeMillis()
return new TestResult(
success: (exitVal == 777),
returnCode: exitVal,
hldsConsoleOutput: sout.toString(),
duration: endTime - startTime
)
}
}

View File

@ -0,0 +1,9 @@
package rehlds.testdemo
class RehldsTestInfo {
String testName
List<String> hldsArgs
String rehldsExtraArgs
int timeoutSeconds
File testBinFile
}

View File

@ -0,0 +1,63 @@
package rehlds.testdemo
import groovy.util.slurpersupport.GPathResult
import org.apache.commons.io.IOUtils
import java.util.zip.ZipFile
class RehldsTestParser {
static final String REHLDS_TEST_METAINFO_FILE = 'rehlds_test_metainfo.xml'
static RehldsTestInfo parseTestInfo(File testArchive) {
def zf = new ZipFile(testArchive);
try {
def metaInfoEntry = zf.getEntry(REHLDS_TEST_METAINFO_FILE)
if (metaInfoEntry == null) {
throw new RuntimeException("Unable to open ${REHLDS_TEST_METAINFO_FILE} in ${testArchive.absolutePath}")
}
GPathResult metaInfo = null
zf.getInputStream(metaInfoEntry).withStream { InputStream ins ->
metaInfo = new XmlSlurper().parse(ins)
}
RehldsTestInfo testInfo = new RehldsTestInfo(
testName: metaInfo.name.text(),
hldsArgs: metaInfo.runArgs.arg.list().collect { it.text().trim() },
timeoutSeconds: metaInfo.timeout.text() as int
)
//validate testInfo
if (!testInfo.testName) {
throw new RuntimeException("Error parsing ${testArchive.absolutePath}: test name is not specified")
}
if (!testInfo.hldsArgs) {
throw new RuntimeException("Error parsing ${testArchive.absolutePath}: run arguments are not specified")
}
if (testInfo.timeoutSeconds <= 0) {
throw new RuntimeException("Error parsing ${testArchive.absolutePath}: bad timeout")
}
def testBinName = testInfo.testName + '.bin'
def testBinEntry = zf.getEntry(testBinName)
if (testBinEntry == null) {
throw new RuntimeException("Error parsing ${testArchive.absolutePath}: test binary ${testBinName} not found inside archive")
}
testInfo.testBinFile = File.createTempFile(testBinName, 'rehlds')
testInfo.testBinFile.deleteOnExit()
zf.getInputStream(testBinEntry).withStream { InputStream ins ->
testInfo.testBinFile.withOutputStream { OutputStream os ->
IOUtils.copy(ins, os)
}
}
return testInfo
} finally {
try { zf.close() } catch (Exception ignored) { }
}
}
}

View File

@ -0,0 +1,12 @@
package versioning
import groovy.transform.CompileStatic
import groovy.transform.TypeChecked
import org.joda.time.DateTime
@CompileStatic @TypeChecked
class GitInfo {
DateTime lastCommitDate
String branch
String tag
}

View File

@ -0,0 +1,41 @@
package versioning
import groovy.transform.CompileStatic
import groovy.transform.TypeChecked
import org.eclipse.jgit.lib.ObjectId
import org.eclipse.jgit.lib.Repository
import org.eclipse.jgit.revwalk.RevWalk
import org.eclipse.jgit.storage.file.FileRepositoryBuilder
import org.joda.time.DateTime
import org.joda.time.DateTimeZone
@CompileStatic @TypeChecked
class GitVersioner {
static GitInfo versionForDir(String dir) {
versionForDir(new File(dir))
}
static GitInfo versionForDir(File dir) {
FileRepositoryBuilder builder = new FileRepositoryBuilder()
Repository repo = builder.setWorkTree(dir)
.findGitDir()
.build()
ObjectId head = repo.resolve('HEAD')
if (!head) {
return null
}
def commit = new RevWalk(repo).parseCommit(head)
def branch = repo.getBranch()
def commitDate = new DateTime(1000L * commit.commitTime, DateTimeZone.UTC)
String tag = repo.tags.find { kv -> kv.value.objectId == commit.id }?.key
return new GitInfo(
lastCommitDate: commitDate,
branch: branch,
tag: tag
)
}
}

View File

@ -0,0 +1,35 @@
package versioning
import groovy.transform.CompileStatic
import groovy.transform.ToString
import groovy.transform.TypeChecked
import org.joda.time.DateTime
@CompileStatic @TypeChecked
@ToString(includeNames = true)
class RehldsVersionInfo {
int majorVersion
int minorVersion
Integer maintenanceVersion
String suffix
DateTime lastCommitDate
String format(String versionSeparator, String suffixSeparator, boolean includeSuffix) {
StringBuilder sb = new StringBuilder()
sb.append(majorVersion).append(versionSeparator).append(minorVersion)
if (maintenanceVersion != null) {
sb.append(versionSeparator).append(maintenanceVersion)
}
if (suffix && includeSuffix) {
sb.append(suffixSeparator).append(suffix)
}
return sb.toString()
}
String asMavenVersion() {
format('.', '-', true)
}
}

View File

@ -0,0 +1,44 @@
package dirsync.builder
import org.junit.Test
import java.io.File
import dirsync.builder.ZipTreeBuilder
import java.util.zip.ZipEntry
import java.util.zip.ZipFile
import java.util.zip.ZipOutputStream;
import static org.junit.Assert.*;
class ZipTreeBuilderTest {
@Test
void test1() {
File zipFile = File.createTempFile('ZipTreeBuilderTest', 'zip')
zipFile.deleteOnExit()
new ZipOutputStream(zipFile.newDataOutputStream()).withStream { ZipOutputStream zos ->
zos.putNextEntry(new ZipEntry('aRootFile1.txt'))
zos.write(65) //'A'
zos.putNextEntry(new ZipEntry('dir1/'))
zos.putNextEntry(new ZipEntry('dir1/dir2/'))
zos.putNextEntry(new ZipEntry('dir1/dir2/d1d2f1.txt'))
zos.write(65); zos.write(66) //'AB'
zos.putNextEntry(new ZipEntry('dir1/d1f1.txt'))
zos.write(65); zos.write(66); zos.write(67) //'ABC'
zos.putNextEntry(new ZipEntry('zRootFile2.txt'))
zos.write(65); zos.write(66); zos.write(67); zos.write(68) //'ABCD'
}
ZipFile zf = new ZipFile(zipFile.absolutePath)
def tree = ZipTreeBuilder.buildForZipArchive(zipFile.absolutePath, zf)
assert tree.childNodes.size() == 3
}
}

75
dep/bzip2/build.gradle Normal file
View File

@ -0,0 +1,75 @@
import org.doomedsociety.gradlecpp.cfg.ToolchainConfigUtils
import org.doomedsociety.gradlecpp.msvc.MsvcToolchainConfig
import org.doomedsociety.gradlecpp.toolchain.icc.Icc
import org.doomedsociety.gradlecpp.toolchain.icc.IccCompilerPlugin
import org.gradle.nativeplatform.NativeBinarySpec
import org.gradle.nativeplatform.NativeLibrarySpec
import org.gradle.nativeplatform.toolchain.VisualCpp
apply plugin: 'c'
apply plugin: IccCompilerPlugin
void setupToolchain(NativeBinarySpec b) {
def cfg = rootProject.createToolchainConfig(b)
if (cfg instanceof MsvcToolchainConfig) {
cfg.compilerOptions.pchConfig = new MsvcToolchainConfig.PrecompiledHeadersConfig(
enabled: true,
pchHeader: 'bzlib_private.h',
pchSourceSet: 'bz2_pch'
)
}
ToolchainConfigUtils.apply(project, cfg, b)
}
model {
buildTypes {
debug
release
}
platforms {
x86 {
architecture "x86"
}
}
toolChains {
visualCpp(VisualCpp) {
}
icc(Icc) {
}
}
components {
bzip2(NativeLibrarySpec) {
targetPlatform 'x86'
sources {
bz2_main(CSourceSet) {
source {
srcDir "src"
include "**/*.c"
exclude "precompiled.c"
}
exportedHeaders {
srcDir "include"
}
}
bz2_pch(CSourceSet) {
source {
srcDir "src"
include "precompiled.c"
}
exportedHeaders {
srcDir "include"
}
}
}
binaries.all { NativeBinarySpec b -> project.setupToolchain(b) }
}
}
}

View File

@ -0,0 +1,282 @@
/*-------------------------------------------------------------*/
/*--- Public header file for the library. ---*/
/*--- bzlib.h ---*/
/*-------------------------------------------------------------*/
/* ------------------------------------------------------------------
This file is part of bzip2/libbzip2, a program and library for
lossless, block-sorting data compression.
bzip2/libbzip2 version 1.0.6 of 6 September 2010
Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org>
Please read the WARNING, DISCLAIMER and PATENTS sections in the
README file.
This program is released under the terms of the license contained
in the file LICENSE.
------------------------------------------------------------------ */
#ifndef _BZLIB_H
#define _BZLIB_H
#ifdef __cplusplus
extern "C" {
#endif
#define BZ_RUN 0
#define BZ_FLUSH 1
#define BZ_FINISH 2
#define BZ_OK 0
#define BZ_RUN_OK 1
#define BZ_FLUSH_OK 2
#define BZ_FINISH_OK 3
#define BZ_STREAM_END 4
#define BZ_SEQUENCE_ERROR (-1)
#define BZ_PARAM_ERROR (-2)
#define BZ_MEM_ERROR (-3)
#define BZ_DATA_ERROR (-4)
#define BZ_DATA_ERROR_MAGIC (-5)
#define BZ_IO_ERROR (-6)
#define BZ_UNEXPECTED_EOF (-7)
#define BZ_OUTBUFF_FULL (-8)
#define BZ_CONFIG_ERROR (-9)
typedef
struct {
char *next_in;
unsigned int avail_in;
unsigned int total_in_lo32;
unsigned int total_in_hi32;
char *next_out;
unsigned int avail_out;
unsigned int total_out_lo32;
unsigned int total_out_hi32;
void *state;
void *(*bzalloc)(void *,int,int);
void (*bzfree)(void *,void *);
void *opaque;
}
bz_stream;
#ifndef BZ_IMPORT
#define BZ_EXPORT
#endif
#ifndef BZ_NO_STDIO
/* Need a definitition for FILE */
#include <stdio.h>
#endif
#ifdef _WIN32
# include <windows.h>
# ifdef small
/* windows.h define small to char */
# undef small
# endif
# ifdef BZ_EXPORT
# define BZ_API(func) WINAPI func
# define BZ_EXTERN extern
# else
/* import windows dll dynamically */
# define BZ_API(func) (WINAPI * func)
# define BZ_EXTERN
# endif
#else
# define BZ_API(func) func
# define BZ_EXTERN extern
#endif
/*-- Core (low-level) library functions --*/
BZ_EXTERN int BZ_API(BZ2_bzCompressInit) (
bz_stream* strm,
int blockSize100k,
int verbosity,
int workFactor
);
BZ_EXTERN int BZ_API(BZ2_bzCompress) (
bz_stream* strm,
int action
);
BZ_EXTERN int BZ_API(BZ2_bzCompressEnd) (
bz_stream* strm
);
BZ_EXTERN int BZ_API(BZ2_bzDecompressInit) (
bz_stream *strm,
int verbosity,
int small
);
BZ_EXTERN int BZ_API(BZ2_bzDecompress) (
bz_stream* strm
);
BZ_EXTERN int BZ_API(BZ2_bzDecompressEnd) (
bz_stream *strm
);
/*-- High(er) level library functions --*/
#ifndef BZ_NO_STDIO
#define BZ_MAX_UNUSED 5000
typedef void BZFILE;
BZ_EXTERN BZFILE* BZ_API(BZ2_bzReadOpen) (
int* bzerror,
FILE* f,
int verbosity,
int small,
void* unused,
int nUnused
);
BZ_EXTERN void BZ_API(BZ2_bzReadClose) (
int* bzerror,
BZFILE* b
);
BZ_EXTERN void BZ_API(BZ2_bzReadGetUnused) (
int* bzerror,
BZFILE* b,
void** unused,
int* nUnused
);
BZ_EXTERN int BZ_API(BZ2_bzRead) (
int* bzerror,
BZFILE* b,
void* buf,
int len
);
BZ_EXTERN BZFILE* BZ_API(BZ2_bzWriteOpen) (
int* bzerror,
FILE* f,
int blockSize100k,
int verbosity,
int workFactor
);
BZ_EXTERN void BZ_API(BZ2_bzWrite) (
int* bzerror,
BZFILE* b,
void* buf,
int len
);
BZ_EXTERN void BZ_API(BZ2_bzWriteClose) (
int* bzerror,
BZFILE* b,
int abandon,
unsigned int* nbytes_in,
unsigned int* nbytes_out
);
BZ_EXTERN void BZ_API(BZ2_bzWriteClose64) (
int* bzerror,
BZFILE* b,
int abandon,
unsigned int* nbytes_in_lo32,
unsigned int* nbytes_in_hi32,
unsigned int* nbytes_out_lo32,
unsigned int* nbytes_out_hi32
);
#endif
/*-- Utility functions --*/
BZ_EXTERN int BZ_API(BZ2_bzBuffToBuffCompress) (
char* dest,
unsigned int* destLen,
char* source,
unsigned int sourceLen,
int blockSize100k,
int verbosity,
int workFactor
);
BZ_EXTERN int BZ_API(BZ2_bzBuffToBuffDecompress) (
char* dest,
unsigned int* destLen,
char* source,
unsigned int sourceLen,
int small,
int verbosity
);
/*--
Code contributed by Yoshioka Tsuneo (tsuneo@rr.iij4u.or.jp)
to support better zlib compatibility.
This code is not _officially_ part of libbzip2 (yet);
I haven't tested it, documented it, or considered the
threading-safeness of it.
If this code breaks, please contact both Yoshioka and me.
--*/
BZ_EXTERN const char * BZ_API(BZ2_bzlibVersion) (
void
);
#ifndef BZ_NO_STDIO
BZ_EXTERN BZFILE * BZ_API(BZ2_bzopen) (
const char *path,
const char *mode
);
BZ_EXTERN BZFILE * BZ_API(BZ2_bzdopen) (
int fd,
const char *mode
);
BZ_EXTERN int BZ_API(BZ2_bzread) (
BZFILE* b,
void* buf,
int len
);
BZ_EXTERN int BZ_API(BZ2_bzwrite) (
BZFILE* b,
void* buf,
int len
);
BZ_EXTERN int BZ_API(BZ2_bzflush) (
BZFILE* b
);
BZ_EXTERN void BZ_API(BZ2_bzclose) (
BZFILE* b
);
BZ_EXTERN const char * BZ_API(BZ2_bzerror) (
BZFILE *b,
int *errnum
);
#endif
#ifdef __cplusplus
}
#endif
#endif
/*-------------------------------------------------------------*/
/*--- end bzlib.h ---*/
/*-------------------------------------------------------------*/

View File

@ -0,0 +1,157 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug Swds Play|Win32">
<Configuration>Debug Swds Play</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug Swds|Win32">
<Configuration>Debug Swds</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{792DF067-9904-4579-99B9-46C17277ADE3}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>bzip2</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug Swds|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug Swds Play|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug Swds|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug Swds Play|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup />
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>$(ProjectDir)..\include\</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<PrecompiledHeaderFile>bzlib_private.h</PrecompiledHeaderFile>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug Swds|Win32'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>$(ProjectDir)..\include\</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<PrecompiledHeaderFile>bzlib_private.h</PrecompiledHeaderFile>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug Swds Play|Win32'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>$(ProjectDir)..\include\</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<PrecompiledHeaderFile>bzlib_private.h</PrecompiledHeaderFile>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>Use</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>$(ProjectDir)..\include\</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<PrecompiledHeaderFile>bzlib_private.h</PrecompiledHeaderFile>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<Text Include="ReadMe.txt" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\src\blocksort.c" />
<ClCompile Include="..\src\bzlib.c" />
<ClCompile Include="..\src\compress.c" />
<ClCompile Include="..\src\crctable.c" />
<ClCompile Include="..\src\decompress.c" />
<ClCompile Include="..\src\huffman.c" />
<ClCompile Include="..\src\precompiled.c">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug Swds|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug Swds Play|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
</ClCompile>
<ClCompile Include="..\src\randtable.c" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\src\bzlib_private.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,51 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<Text Include="ReadMe.txt" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\src\blocksort.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\src\bzlib.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\src\compress.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\src\crctable.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\src\decompress.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\src\huffman.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\src\randtable.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\src\precompiled.c">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\src\bzlib_private.h">
<Filter>Source Files</Filter>
</ClInclude>
</ItemGroup>
</Project>

1094
dep/bzip2/src/blocksort.c Normal file

File diff suppressed because it is too large Load Diff

1580
dep/bzip2/src/bzlib.c Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,509 @@
/*-------------------------------------------------------------*/
/*--- Private header file for the library. ---*/
/*--- bzlib_private.h ---*/
/*-------------------------------------------------------------*/
/* ------------------------------------------------------------------
This file is part of bzip2/libbzip2, a program and library for
lossless, block-sorting data compression.
bzip2/libbzip2 version 1.0.6 of 6 September 2010
Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org>
Please read the WARNING, DISCLAIMER and PATENTS sections in the
README file.
This program is released under the terms of the license contained
in the file LICENSE.
------------------------------------------------------------------ */
#ifndef _BZLIB_PRIVATE_H
#define _BZLIB_PRIVATE_H
#include <stdlib.h>
#ifndef BZ_NO_STDIO
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#endif
#include "bzip2/bzlib.h"
/*-- General stuff. --*/
#define BZ_VERSION "1.0.6, 6-Sept-2010"
typedef char Char;
typedef unsigned char Bool;
typedef unsigned char UChar;
typedef int Int32;
typedef unsigned int UInt32;
typedef short Int16;
typedef unsigned short UInt16;
#define True ((Bool)1)
#define False ((Bool)0)
#ifndef __GNUC__
#define __inline__ /* */
#endif
#ifndef BZ_NO_STDIO
extern void BZ2_bz__AssertH__fail ( int errcode );
#define AssertH(cond,errcode) \
{ if (!(cond)) BZ2_bz__AssertH__fail ( errcode ); }
#if BZ_DEBUG
#define AssertD(cond,msg) \
{ if (!(cond)) { \
fprintf ( stderr, \
"\n\nlibbzip2(debug build): internal error\n\t%s\n", msg );\
exit(1); \
}}
#else
#define AssertD(cond,msg) /* */
#endif
#define VPrintf0(zf) \
fprintf(stderr,zf)
#define VPrintf1(zf,za1) \
fprintf(stderr,zf,za1)
#define VPrintf2(zf,za1,za2) \
fprintf(stderr,zf,za1,za2)
#define VPrintf3(zf,za1,za2,za3) \
fprintf(stderr,zf,za1,za2,za3)
#define VPrintf4(zf,za1,za2,za3,za4) \
fprintf(stderr,zf,za1,za2,za3,za4)
#define VPrintf5(zf,za1,za2,za3,za4,za5) \
fprintf(stderr,zf,za1,za2,za3,za4,za5)
#else
extern void bz_internal_error ( int errcode );
#define AssertH(cond,errcode) \
{ if (!(cond)) bz_internal_error ( errcode ); }
#define AssertD(cond,msg) do { } while (0)
#define VPrintf0(zf) do { } while (0)
#define VPrintf1(zf,za1) do { } while (0)
#define VPrintf2(zf,za1,za2) do { } while (0)
#define VPrintf3(zf,za1,za2,za3) do { } while (0)
#define VPrintf4(zf,za1,za2,za3,za4) do { } while (0)
#define VPrintf5(zf,za1,za2,za3,za4,za5) do { } while (0)
#endif
#define BZALLOC(nnn) (strm->bzalloc)(strm->opaque,(nnn),1)
#define BZFREE(ppp) (strm->bzfree)(strm->opaque,(ppp))
/*-- Header bytes. --*/
#define BZ_HDR_B 0x42 /* 'B' */
#define BZ_HDR_Z 0x5a /* 'Z' */
#define BZ_HDR_h 0x68 /* 'h' */
#define BZ_HDR_0 0x30 /* '0' */
/*-- Constants for the back end. --*/
#define BZ_MAX_ALPHA_SIZE 258
#define BZ_MAX_CODE_LEN 23
#define BZ_RUNA 0
#define BZ_RUNB 1
#define BZ_N_GROUPS 6
#define BZ_G_SIZE 50
#define BZ_N_ITERS 4
#define BZ_MAX_SELECTORS (2 + (900000 / BZ_G_SIZE))
/*-- Stuff for randomising repetitive blocks. --*/
extern Int32 BZ2_rNums[512];
#define BZ_RAND_DECLS \
Int32 rNToGo; \
Int32 rTPos \
#define BZ_RAND_INIT_MASK \
s->rNToGo = 0; \
s->rTPos = 0 \
#define BZ_RAND_MASK ((s->rNToGo == 1) ? 1 : 0)
#define BZ_RAND_UPD_MASK \
if (s->rNToGo == 0) { \
s->rNToGo = BZ2_rNums[s->rTPos]; \
s->rTPos++; \
if (s->rTPos == 512) s->rTPos = 0; \
} \
s->rNToGo--;
/*-- Stuff for doing CRCs. --*/
extern UInt32 BZ2_crc32Table[256];
#define BZ_INITIALISE_CRC(crcVar) \
{ \
crcVar = 0xffffffffL; \
}
#define BZ_FINALISE_CRC(crcVar) \
{ \
crcVar = ~(crcVar); \
}
#define BZ_UPDATE_CRC(crcVar,cha) \
{ \
crcVar = (crcVar << 8) ^ \
BZ2_crc32Table[(crcVar >> 24) ^ \
((UChar)cha)]; \
}
/*-- States and modes for compression. --*/
#define BZ_M_IDLE 1
#define BZ_M_RUNNING 2
#define BZ_M_FLUSHING 3
#define BZ_M_FINISHING 4
#define BZ_S_OUTPUT 1
#define BZ_S_INPUT 2
#define BZ_N_RADIX 2
#define BZ_N_QSORT 12
#define BZ_N_SHELL 18
#define BZ_N_OVERSHOOT (BZ_N_RADIX + BZ_N_QSORT + BZ_N_SHELL + 2)
/*-- Structure holding all the compression-side stuff. --*/
typedef
struct {
/* pointer back to the struct bz_stream */
bz_stream* strm;
/* mode this stream is in, and whether inputting */
/* or outputting data */
Int32 mode;
Int32 state;
/* remembers avail_in when flush/finish requested */
UInt32 avail_in_expect;
/* for doing the block sorting */
UInt32* arr1;
UInt32* arr2;
UInt32* ftab;
Int32 origPtr;
/* aliases for arr1 and arr2 */
UInt32* ptr;
UChar* block;
UInt16* mtfv;
UChar* zbits;
/* for deciding when to use the fallback sorting algorithm */
Int32 workFactor;
/* run-length-encoding of the input */
UInt32 state_in_ch;
Int32 state_in_len;
BZ_RAND_DECLS;
/* input and output limits and current posns */
Int32 nblock;
Int32 nblockMAX;
Int32 numZ;
Int32 state_out_pos;
/* map of bytes used in block */
Int32 nInUse;
Bool inUse[256];
UChar unseqToSeq[256];
/* the buffer for bit stream creation */
UInt32 bsBuff;
Int32 bsLive;
/* block and combined CRCs */
UInt32 blockCRC;
UInt32 combinedCRC;
/* misc administratium */
Int32 verbosity;
Int32 blockNo;
Int32 blockSize100k;
/* stuff for coding the MTF values */
Int32 nMTF;
Int32 mtfFreq [BZ_MAX_ALPHA_SIZE];
UChar selector [BZ_MAX_SELECTORS];
UChar selectorMtf[BZ_MAX_SELECTORS];
UChar len [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
Int32 code [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
Int32 rfreq [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
/* second dimension: only 3 needed; 4 makes index calculations faster */
UInt32 len_pack[BZ_MAX_ALPHA_SIZE][4];
}
EState;
/*-- externs for compression. --*/
extern void
BZ2_blockSort ( EState* );
extern void
BZ2_compressBlock ( EState*, Bool );
extern void
BZ2_bsInitWrite ( EState* );
extern void
BZ2_hbAssignCodes ( Int32*, UChar*, Int32, Int32, Int32 );
extern void
BZ2_hbMakeCodeLengths ( UChar*, Int32*, Int32, Int32 );
/*-- states for decompression. --*/
#define BZ_X_IDLE 1
#define BZ_X_OUTPUT 2
#define BZ_X_MAGIC_1 10
#define BZ_X_MAGIC_2 11
#define BZ_X_MAGIC_3 12
#define BZ_X_MAGIC_4 13
#define BZ_X_BLKHDR_1 14
#define BZ_X_BLKHDR_2 15
#define BZ_X_BLKHDR_3 16
#define BZ_X_BLKHDR_4 17
#define BZ_X_BLKHDR_5 18
#define BZ_X_BLKHDR_6 19
#define BZ_X_BCRC_1 20
#define BZ_X_BCRC_2 21
#define BZ_X_BCRC_3 22
#define BZ_X_BCRC_4 23
#define BZ_X_RANDBIT 24
#define BZ_X_ORIGPTR_1 25
#define BZ_X_ORIGPTR_2 26
#define BZ_X_ORIGPTR_3 27
#define BZ_X_MAPPING_1 28
#define BZ_X_MAPPING_2 29
#define BZ_X_SELECTOR_1 30
#define BZ_X_SELECTOR_2 31
#define BZ_X_SELECTOR_3 32
#define BZ_X_CODING_1 33
#define BZ_X_CODING_2 34
#define BZ_X_CODING_3 35
#define BZ_X_MTF_1 36
#define BZ_X_MTF_2 37
#define BZ_X_MTF_3 38
#define BZ_X_MTF_4 39
#define BZ_X_MTF_5 40
#define BZ_X_MTF_6 41
#define BZ_X_ENDHDR_2 42
#define BZ_X_ENDHDR_3 43
#define BZ_X_ENDHDR_4 44
#define BZ_X_ENDHDR_5 45
#define BZ_X_ENDHDR_6 46
#define BZ_X_CCRC_1 47
#define BZ_X_CCRC_2 48
#define BZ_X_CCRC_3 49
#define BZ_X_CCRC_4 50
/*-- Constants for the fast MTF decoder. --*/
#define MTFA_SIZE 4096
#define MTFL_SIZE 16
/*-- Structure holding all the decompression-side stuff. --*/
typedef
struct {
/* pointer back to the struct bz_stream */
bz_stream* strm;
/* state indicator for this stream */
Int32 state;
/* for doing the final run-length decoding */
UChar state_out_ch;
Int32 state_out_len;
Bool blockRandomised;
BZ_RAND_DECLS;
/* the buffer for bit stream reading */
UInt32 bsBuff;
Int32 bsLive;
/* misc administratium */
Int32 blockSize100k;
Bool smallDecompress;
Int32 currBlockNo;
Int32 verbosity;
/* for undoing the Burrows-Wheeler transform */
Int32 origPtr;
UInt32 tPos;
Int32 k0;
Int32 unzftab[256];
Int32 nblock_used;
Int32 cftab[257];
Int32 cftabCopy[257];
/* for undoing the Burrows-Wheeler transform (FAST) */
UInt32 *tt;
/* for undoing the Burrows-Wheeler transform (SMALL) */
UInt16 *ll16;
UChar *ll4;
/* stored and calculated CRCs */
UInt32 storedBlockCRC;
UInt32 storedCombinedCRC;
UInt32 calculatedBlockCRC;
UInt32 calculatedCombinedCRC;
/* map of bytes used in block */
Int32 nInUse;
Bool inUse[256];
Bool inUse16[16];
UChar seqToUnseq[256];
/* for decoding the MTF values */
UChar mtfa [MTFA_SIZE];
Int32 mtfbase[256 / MTFL_SIZE];
UChar selector [BZ_MAX_SELECTORS];
UChar selectorMtf[BZ_MAX_SELECTORS];
UChar len [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
Int32 limit [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
Int32 base [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
Int32 perm [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
Int32 minLens[BZ_N_GROUPS];
/* save area for scalars in the main decompress code */
Int32 save_i;
Int32 save_j;
Int32 save_t;
Int32 save_alphaSize;
Int32 save_nGroups;
Int32 save_nSelectors;
Int32 save_EOB;
Int32 save_groupNo;
Int32 save_groupPos;
Int32 save_nextSym;
Int32 save_nblockMAX;
Int32 save_nblock;
Int32 save_es;
Int32 save_N;
Int32 save_curr;
Int32 save_zt;
Int32 save_zn;
Int32 save_zvec;
Int32 save_zj;
Int32 save_gSel;
Int32 save_gMinlen;
Int32* save_gLimit;
Int32* save_gBase;
Int32* save_gPerm;
}
DState;
/*-- Macros for decompression. --*/
#define BZ_GET_FAST(cccc) \
/* c_tPos is unsigned, hence test < 0 is pointless. */ \
if (s->tPos >= (UInt32)100000 * (UInt32)s->blockSize100k) return True; \
s->tPos = s->tt[s->tPos]; \
cccc = (UChar)(s->tPos & 0xff); \
s->tPos >>= 8;
#define BZ_GET_FAST_C(cccc) \
/* c_tPos is unsigned, hence test < 0 is pointless. */ \
if (c_tPos >= (UInt32)100000 * (UInt32)ro_blockSize100k) return True; \
c_tPos = c_tt[c_tPos]; \
cccc = (UChar)(c_tPos & 0xff); \
c_tPos >>= 8;
#define SET_LL4(i,n) \
{ if (((i) & 0x1) == 0) \
s->ll4[(i) >> 1] = (s->ll4[(i) >> 1] & 0xf0) | (n); else \
s->ll4[(i) >> 1] = (s->ll4[(i) >> 1] & 0x0f) | ((n) << 4); \
}
#define GET_LL4(i) \
((((UInt32)(s->ll4[(i) >> 1])) >> (((i) << 2) & 0x4)) & 0xF)
#define SET_LL(i,n) \
{ s->ll16[i] = (UInt16)(n & 0x0000ffff); \
SET_LL4(i, n >> 16); \
}
#define GET_LL(i) \
(((UInt32)s->ll16[i]) | (GET_LL4(i) << 16))
#define BZ_GET_SMALL(cccc) \
/* c_tPos is unsigned, hence test < 0 is pointless. */ \
if (s->tPos >= (UInt32)100000 * (UInt32)s->blockSize100k) return True; \
cccc = BZ2_indexIntoF ( s->tPos, s->cftab ); \
s->tPos = GET_LL(s->tPos);
/*-- externs for decompression. --*/
extern Int32
BZ2_indexIntoF ( Int32, Int32* );
extern Int32
BZ2_decompress ( DState* );
extern void
BZ2_hbCreateDecodeTables ( Int32*, Int32*, Int32*, UChar*,
Int32, Int32, Int32 );
#endif
/*-- BZ_NO_STDIO seems to make NULL disappear on some platforms. --*/
#ifdef BZ_NO_STDIO
#ifndef NULL
#define NULL 0
#endif
#endif
/*-------------------------------------------------------------*/
/*--- end bzlib_private.h ---*/
/*-------------------------------------------------------------*/

672
dep/bzip2/src/compress.c Normal file
View File

@ -0,0 +1,672 @@
/*-------------------------------------------------------------*/
/*--- Compression machinery (not incl block sorting) ---*/
/*--- compress.c ---*/
/*-------------------------------------------------------------*/
/* ------------------------------------------------------------------
This file is part of bzip2/libbzip2, a program and library for
lossless, block-sorting data compression.
bzip2/libbzip2 version 1.0.6 of 6 September 2010
Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org>
Please read the WARNING, DISCLAIMER and PATENTS sections in the
README file.
This program is released under the terms of the license contained
in the file LICENSE.
------------------------------------------------------------------ */
/* CHANGES
0.9.0 -- original version.
0.9.0a/b -- no changes in this file.
0.9.0c -- changed setting of nGroups in sendMTFValues()
so as to do a bit better on small files
*/
#include "bzlib_private.h"
/*---------------------------------------------------*/
/*--- Bit stream I/O ---*/
/*---------------------------------------------------*/
/*---------------------------------------------------*/
void BZ2_bsInitWrite ( EState* s )
{
s->bsLive = 0;
s->bsBuff = 0;
}
/*---------------------------------------------------*/
static
void bsFinishWrite ( EState* s )
{
while (s->bsLive > 0) {
s->zbits[s->numZ] = (UChar)(s->bsBuff >> 24);
s->numZ++;
s->bsBuff <<= 8;
s->bsLive -= 8;
}
}
/*---------------------------------------------------*/
#define bsNEEDW(nz) \
{ \
while (s->bsLive >= 8) { \
s->zbits[s->numZ] \
= (UChar)(s->bsBuff >> 24); \
s->numZ++; \
s->bsBuff <<= 8; \
s->bsLive -= 8; \
} \
}
/*---------------------------------------------------*/
static
__inline__
void bsW ( EState* s, Int32 n, UInt32 v )
{
bsNEEDW ( n );
s->bsBuff |= (v << (32 - s->bsLive - n));
s->bsLive += n;
}
/*---------------------------------------------------*/
static
void bsPutUInt32 ( EState* s, UInt32 u )
{
bsW ( s, 8, (u >> 24) & 0xffL );
bsW ( s, 8, (u >> 16) & 0xffL );
bsW ( s, 8, (u >> 8) & 0xffL );
bsW ( s, 8, u & 0xffL );
}
/*---------------------------------------------------*/
static
void bsPutUChar ( EState* s, UChar c )
{
bsW( s, 8, (UInt32)c );
}
/*---------------------------------------------------*/
/*--- The back end proper ---*/
/*---------------------------------------------------*/
/*---------------------------------------------------*/
static
void makeMaps_e ( EState* s )
{
Int32 i;
s->nInUse = 0;
for (i = 0; i < 256; i++)
if (s->inUse[i]) {
s->unseqToSeq[i] = s->nInUse;
s->nInUse++;
}
}
/*---------------------------------------------------*/
static
void generateMTFValues ( EState* s )
{
UChar yy[256];
Int32 i, j;
Int32 zPend;
Int32 wr;
Int32 EOB;
/*
After sorting (eg, here),
s->arr1 [ 0 .. s->nblock-1 ] holds sorted order,
and
((UChar*)s->arr2) [ 0 .. s->nblock-1 ]
holds the original block data.
The first thing to do is generate the MTF values,
and put them in
((UInt16*)s->arr1) [ 0 .. s->nblock-1 ].
Because there are strictly fewer or equal MTF values
than block values, ptr values in this area are overwritten
with MTF values only when they are no longer needed.
The final compressed bitstream is generated into the
area starting at
(UChar*) (&((UChar*)s->arr2)[s->nblock])
These storage aliases are set up in bzCompressInit(),
except for the last one, which is arranged in
compressBlock().
*/
UInt32* ptr = s->ptr;
UChar* block = s->block;
UInt16* mtfv = s->mtfv;
makeMaps_e ( s );
EOB = s->nInUse+1;
for (i = 0; i <= EOB; i++) s->mtfFreq[i] = 0;
wr = 0;
zPend = 0;
for (i = 0; i < s->nInUse; i++) yy[i] = (UChar) i;
for (i = 0; i < s->nblock; i++) {
UChar ll_i;
AssertD ( wr <= i, "generateMTFValues(1)" );
j = ptr[i]-1; if (j < 0) j += s->nblock;
ll_i = s->unseqToSeq[block[j]];
AssertD ( ll_i < s->nInUse, "generateMTFValues(2a)" );
if (yy[0] == ll_i) {
zPend++;
} else {
if (zPend > 0) {
zPend--;
while (True) {
if (zPend & 1) {
mtfv[wr] = BZ_RUNB; wr++;
s->mtfFreq[BZ_RUNB]++;
} else {
mtfv[wr] = BZ_RUNA; wr++;
s->mtfFreq[BZ_RUNA]++;
}
if (zPend < 2) break;
zPend = (zPend - 2) / 2;
};
zPend = 0;
}
{
register UChar rtmp;
register UChar* ryy_j;
register UChar rll_i;
rtmp = yy[1];
yy[1] = yy[0];
ryy_j = &(yy[1]);
rll_i = ll_i;
while ( rll_i != rtmp ) {
register UChar rtmp2;
ryy_j++;
rtmp2 = rtmp;
rtmp = *ryy_j;
*ryy_j = rtmp2;
};
yy[0] = rtmp;
j = ryy_j - &(yy[0]);
mtfv[wr] = j+1; wr++; s->mtfFreq[j+1]++;
}
}
}
if (zPend > 0) {
zPend--;
while (True) {
if (zPend & 1) {
mtfv[wr] = BZ_RUNB; wr++;
s->mtfFreq[BZ_RUNB]++;
} else {
mtfv[wr] = BZ_RUNA; wr++;
s->mtfFreq[BZ_RUNA]++;
}
if (zPend < 2) break;
zPend = (zPend - 2) / 2;
};
zPend = 0;
}
mtfv[wr] = EOB; wr++; s->mtfFreq[EOB]++;
s->nMTF = wr;
}
/*---------------------------------------------------*/
#define BZ_LESSER_ICOST 0
#define BZ_GREATER_ICOST 15
static
void sendMTFValues ( EState* s )
{
Int32 v, t, i, j, gs, ge, totc, bt, bc, iter;
Int32 nSelectors, alphaSize, minLen, maxLen, selCtr;
Int32 nGroups, nBytes;
/*--
UChar len [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
is a global since the decoder also needs it.
Int32 code[BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
Int32 rfreq[BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
are also globals only used in this proc.
Made global to keep stack frame size small.
--*/
UInt16 cost[BZ_N_GROUPS];
Int32 fave[BZ_N_GROUPS];
UInt16* mtfv = s->mtfv;
if (s->verbosity >= 3)
VPrintf3( " %d in block, %d after MTF & 1-2 coding, "
"%d+2 syms in use\n",
s->nblock, s->nMTF, s->nInUse );
alphaSize = s->nInUse+2;
for (t = 0; t < BZ_N_GROUPS; t++)
for (v = 0; v < alphaSize; v++)
s->len[t][v] = BZ_GREATER_ICOST;
/*--- Decide how many coding tables to use ---*/
AssertH ( s->nMTF > 0, 3001 );
if (s->nMTF < 200) nGroups = 2; else
if (s->nMTF < 600) nGroups = 3; else
if (s->nMTF < 1200) nGroups = 4; else
if (s->nMTF < 2400) nGroups = 5; else
nGroups = 6;
/*--- Generate an initial set of coding tables ---*/
{
Int32 nPart, remF, tFreq, aFreq;
nPart = nGroups;
remF = s->nMTF;
gs = 0;
while (nPart > 0) {
tFreq = remF / nPart;
ge = gs-1;
aFreq = 0;
while (aFreq < tFreq && ge < alphaSize-1) {
ge++;
aFreq += s->mtfFreq[ge];
}
if (ge > gs
&& nPart != nGroups && nPart != 1
&& ((nGroups-nPart) % 2 == 1)) {
aFreq -= s->mtfFreq[ge];
ge--;
}
if (s->verbosity >= 3)
VPrintf5( " initial group %d, [%d .. %d], "
"has %d syms (%4.1f%%)\n",
nPart, gs, ge, aFreq,
(100.0 * (float)aFreq) / (float)(s->nMTF) );
for (v = 0; v < alphaSize; v++)
if (v >= gs && v <= ge)
s->len[nPart-1][v] = BZ_LESSER_ICOST; else
s->len[nPart-1][v] = BZ_GREATER_ICOST;
nPart--;
gs = ge+1;
remF -= aFreq;
}
}
/*---
Iterate up to BZ_N_ITERS times to improve the tables.
---*/
for (iter = 0; iter < BZ_N_ITERS; iter++) {
for (t = 0; t < nGroups; t++) fave[t] = 0;
for (t = 0; t < nGroups; t++)
for (v = 0; v < alphaSize; v++)
s->rfreq[t][v] = 0;
/*---
Set up an auxiliary length table which is used to fast-track
the common case (nGroups == 6).
---*/
if (nGroups == 6) {
for (v = 0; v < alphaSize; v++) {
s->len_pack[v][0] = (s->len[1][v] << 16) | s->len[0][v];
s->len_pack[v][1] = (s->len[3][v] << 16) | s->len[2][v];
s->len_pack[v][2] = (s->len[5][v] << 16) | s->len[4][v];
}
}
nSelectors = 0;
totc = 0;
gs = 0;
while (True) {
/*--- Set group start & end marks. --*/
if (gs >= s->nMTF) break;
ge = gs + BZ_G_SIZE - 1;
if (ge >= s->nMTF) ge = s->nMTF-1;
/*--
Calculate the cost of this group as coded
by each of the coding tables.
--*/
for (t = 0; t < nGroups; t++) cost[t] = 0;
if (nGroups == 6 && 50 == ge-gs+1) {
/*--- fast track the common case ---*/
register UInt32 cost01, cost23, cost45;
register UInt16 icv;
cost01 = cost23 = cost45 = 0;
# define BZ_ITER(nn) \
icv = mtfv[gs+(nn)]; \
cost01 += s->len_pack[icv][0]; \
cost23 += s->len_pack[icv][1]; \
cost45 += s->len_pack[icv][2]; \
BZ_ITER(0); BZ_ITER(1); BZ_ITER(2); BZ_ITER(3); BZ_ITER(4);
BZ_ITER(5); BZ_ITER(6); BZ_ITER(7); BZ_ITER(8); BZ_ITER(9);
BZ_ITER(10); BZ_ITER(11); BZ_ITER(12); BZ_ITER(13); BZ_ITER(14);
BZ_ITER(15); BZ_ITER(16); BZ_ITER(17); BZ_ITER(18); BZ_ITER(19);
BZ_ITER(20); BZ_ITER(21); BZ_ITER(22); BZ_ITER(23); BZ_ITER(24);
BZ_ITER(25); BZ_ITER(26); BZ_ITER(27); BZ_ITER(28); BZ_ITER(29);
BZ_ITER(30); BZ_ITER(31); BZ_ITER(32); BZ_ITER(33); BZ_ITER(34);
BZ_ITER(35); BZ_ITER(36); BZ_ITER(37); BZ_ITER(38); BZ_ITER(39);
BZ_ITER(40); BZ_ITER(41); BZ_ITER(42); BZ_ITER(43); BZ_ITER(44);
BZ_ITER(45); BZ_ITER(46); BZ_ITER(47); BZ_ITER(48); BZ_ITER(49);
# undef BZ_ITER
cost[0] = cost01 & 0xffff; cost[1] = cost01 >> 16;
cost[2] = cost23 & 0xffff; cost[3] = cost23 >> 16;
cost[4] = cost45 & 0xffff; cost[5] = cost45 >> 16;
} else {
/*--- slow version which correctly handles all situations ---*/
for (i = gs; i <= ge; i++) {
UInt16 icv = mtfv[i];
for (t = 0; t < nGroups; t++) cost[t] += s->len[t][icv];
}
}
/*--
Find the coding table which is best for this group,
and record its identity in the selector table.
--*/
bc = 999999999; bt = -1;
for (t = 0; t < nGroups; t++)
if (cost[t] < bc) { bc = cost[t]; bt = t; };
totc += bc;
fave[bt]++;
s->selector[nSelectors] = bt;
nSelectors++;
/*--
Increment the symbol frequencies for the selected table.
--*/
if (nGroups == 6 && 50 == ge-gs+1) {
/*--- fast track the common case ---*/
# define BZ_ITUR(nn) s->rfreq[bt][ mtfv[gs+(nn)] ]++
BZ_ITUR(0); BZ_ITUR(1); BZ_ITUR(2); BZ_ITUR(3); BZ_ITUR(4);
BZ_ITUR(5); BZ_ITUR(6); BZ_ITUR(7); BZ_ITUR(8); BZ_ITUR(9);
BZ_ITUR(10); BZ_ITUR(11); BZ_ITUR(12); BZ_ITUR(13); BZ_ITUR(14);
BZ_ITUR(15); BZ_ITUR(16); BZ_ITUR(17); BZ_ITUR(18); BZ_ITUR(19);
BZ_ITUR(20); BZ_ITUR(21); BZ_ITUR(22); BZ_ITUR(23); BZ_ITUR(24);
BZ_ITUR(25); BZ_ITUR(26); BZ_ITUR(27); BZ_ITUR(28); BZ_ITUR(29);
BZ_ITUR(30); BZ_ITUR(31); BZ_ITUR(32); BZ_ITUR(33); BZ_ITUR(34);
BZ_ITUR(35); BZ_ITUR(36); BZ_ITUR(37); BZ_ITUR(38); BZ_ITUR(39);
BZ_ITUR(40); BZ_ITUR(41); BZ_ITUR(42); BZ_ITUR(43); BZ_ITUR(44);
BZ_ITUR(45); BZ_ITUR(46); BZ_ITUR(47); BZ_ITUR(48); BZ_ITUR(49);
# undef BZ_ITUR
} else {
/*--- slow version which correctly handles all situations ---*/
for (i = gs; i <= ge; i++)
s->rfreq[bt][ mtfv[i] ]++;
}
gs = ge+1;
}
if (s->verbosity >= 3) {
VPrintf2 ( " pass %d: size is %d, grp uses are ",
iter+1, totc/8 );
for (t = 0; t < nGroups; t++)
VPrintf1 ( "%d ", fave[t] );
VPrintf0 ( "\n" );
}
/*--
Recompute the tables based on the accumulated frequencies.
--*/
/* maxLen was changed from 20 to 17 in bzip2-1.0.3. See
comment in huffman.c for details. */
for (t = 0; t < nGroups; t++)
BZ2_hbMakeCodeLengths ( &(s->len[t][0]), &(s->rfreq[t][0]),
alphaSize, 17 /*20*/ );
}
AssertH( nGroups < 8, 3002 );
AssertH( nSelectors < 32768 &&
nSelectors <= (2 + (900000 / BZ_G_SIZE)),
3003 );
/*--- Compute MTF values for the selectors. ---*/
{
UChar pos[BZ_N_GROUPS], ll_i, tmp2, tmp;
for (i = 0; i < nGroups; i++) pos[i] = i;
for (i = 0; i < nSelectors; i++) {
ll_i = s->selector[i];
j = 0;
tmp = pos[j];
while ( ll_i != tmp ) {
j++;
tmp2 = tmp;
tmp = pos[j];
pos[j] = tmp2;
};
pos[0] = tmp;
s->selectorMtf[i] = j;
}
};
/*--- Assign actual codes for the tables. --*/
for (t = 0; t < nGroups; t++) {
minLen = 32;
maxLen = 0;
for (i = 0; i < alphaSize; i++) {
if (s->len[t][i] > maxLen) maxLen = s->len[t][i];
if (s->len[t][i] < minLen) minLen = s->len[t][i];
}
AssertH ( !(maxLen > 17 /*20*/ ), 3004 );
AssertH ( !(minLen < 1), 3005 );
BZ2_hbAssignCodes ( &(s->code[t][0]), &(s->len[t][0]),
minLen, maxLen, alphaSize );
}
/*--- Transmit the mapping table. ---*/
{
Bool inUse16[16];
for (i = 0; i < 16; i++) {
inUse16[i] = False;
for (j = 0; j < 16; j++)
if (s->inUse[i * 16 + j]) inUse16[i] = True;
}
nBytes = s->numZ;
for (i = 0; i < 16; i++)
if (inUse16[i]) bsW(s,1,1); else bsW(s,1,0);
for (i = 0; i < 16; i++)
if (inUse16[i])
for (j = 0; j < 16; j++) {
if (s->inUse[i * 16 + j]) bsW(s,1,1); else bsW(s,1,0);
}
if (s->verbosity >= 3)
VPrintf1( " bytes: mapping %d, ", s->numZ-nBytes );
}
/*--- Now the selectors. ---*/
nBytes = s->numZ;
bsW ( s, 3, nGroups );
bsW ( s, 15, nSelectors );
for (i = 0; i < nSelectors; i++) {
for (j = 0; j < s->selectorMtf[i]; j++) bsW(s,1,1);
bsW(s,1,0);
}
if (s->verbosity >= 3)
VPrintf1( "selectors %d, ", s->numZ-nBytes );
/*--- Now the coding tables. ---*/
nBytes = s->numZ;
for (t = 0; t < nGroups; t++) {
Int32 curr = s->len[t][0];
bsW ( s, 5, curr );
for (i = 0; i < alphaSize; i++) {
while (curr < s->len[t][i]) { bsW(s,2,2); curr++; /* 10 */ };
while (curr > s->len[t][i]) { bsW(s,2,3); curr--; /* 11 */ };
bsW ( s, 1, 0 );
}
}
if (s->verbosity >= 3)
VPrintf1 ( "code lengths %d, ", s->numZ-nBytes );
/*--- And finally, the block data proper ---*/
nBytes = s->numZ;
selCtr = 0;
gs = 0;
while (True) {
if (gs >= s->nMTF) break;
ge = gs + BZ_G_SIZE - 1;
if (ge >= s->nMTF) ge = s->nMTF-1;
AssertH ( s->selector[selCtr] < nGroups, 3006 );
if (nGroups == 6 && 50 == ge-gs+1) {
/*--- fast track the common case ---*/
UInt16 mtfv_i;
UChar* s_len_sel_selCtr
= &(s->len[s->selector[selCtr]][0]);
Int32* s_code_sel_selCtr
= &(s->code[s->selector[selCtr]][0]);
# define BZ_ITAH(nn) \
mtfv_i = mtfv[gs+(nn)]; \
bsW ( s, \
s_len_sel_selCtr[mtfv_i], \
s_code_sel_selCtr[mtfv_i] )
BZ_ITAH(0); BZ_ITAH(1); BZ_ITAH(2); BZ_ITAH(3); BZ_ITAH(4);
BZ_ITAH(5); BZ_ITAH(6); BZ_ITAH(7); BZ_ITAH(8); BZ_ITAH(9);
BZ_ITAH(10); BZ_ITAH(11); BZ_ITAH(12); BZ_ITAH(13); BZ_ITAH(14);
BZ_ITAH(15); BZ_ITAH(16); BZ_ITAH(17); BZ_ITAH(18); BZ_ITAH(19);
BZ_ITAH(20); BZ_ITAH(21); BZ_ITAH(22); BZ_ITAH(23); BZ_ITAH(24);
BZ_ITAH(25); BZ_ITAH(26); BZ_ITAH(27); BZ_ITAH(28); BZ_ITAH(29);
BZ_ITAH(30); BZ_ITAH(31); BZ_ITAH(32); BZ_ITAH(33); BZ_ITAH(34);
BZ_ITAH(35); BZ_ITAH(36); BZ_ITAH(37); BZ_ITAH(38); BZ_ITAH(39);
BZ_ITAH(40); BZ_ITAH(41); BZ_ITAH(42); BZ_ITAH(43); BZ_ITAH(44);
BZ_ITAH(45); BZ_ITAH(46); BZ_ITAH(47); BZ_ITAH(48); BZ_ITAH(49);
# undef BZ_ITAH
} else {
/*--- slow version which correctly handles all situations ---*/
for (i = gs; i <= ge; i++) {
bsW ( s,
s->len [s->selector[selCtr]] [mtfv[i]],
s->code [s->selector[selCtr]] [mtfv[i]] );
}
}
gs = ge+1;
selCtr++;
}
AssertH( selCtr == nSelectors, 3007 );
if (s->verbosity >= 3)
VPrintf1( "codes %d\n", s->numZ-nBytes );
}
/*---------------------------------------------------*/
void BZ2_compressBlock ( EState* s, Bool is_last_block )
{
if (s->nblock > 0) {
BZ_FINALISE_CRC ( s->blockCRC );
s->combinedCRC = (s->combinedCRC << 1) | (s->combinedCRC >> 31);
s->combinedCRC ^= s->blockCRC;
if (s->blockNo > 1) s->numZ = 0;
if (s->verbosity >= 2)
VPrintf4( " block %d: crc = 0x%08x, "
"combined CRC = 0x%08x, size = %d\n",
s->blockNo, s->blockCRC, s->combinedCRC, s->nblock );
BZ2_blockSort ( s );
}
s->zbits = (UChar*) (&((UChar*)s->arr2)[s->nblock]);
/*-- If this is the first block, create the stream header. --*/
if (s->blockNo == 1) {
BZ2_bsInitWrite ( s );
bsPutUChar ( s, BZ_HDR_B );
bsPutUChar ( s, BZ_HDR_Z );
bsPutUChar ( s, BZ_HDR_h );
bsPutUChar ( s, (UChar)(BZ_HDR_0 + s->blockSize100k) );
}
if (s->nblock > 0) {
bsPutUChar ( s, 0x31 ); bsPutUChar ( s, 0x41 );
bsPutUChar ( s, 0x59 ); bsPutUChar ( s, 0x26 );
bsPutUChar ( s, 0x53 ); bsPutUChar ( s, 0x59 );
/*-- Now the block's CRC, so it is in a known place. --*/
bsPutUInt32 ( s, s->blockCRC );
/*--
Now a single bit indicating (non-)randomisation.
As of version 0.9.5, we use a better sorting algorithm
which makes randomisation unnecessary. So always set
the randomised bit to 'no'. Of course, the decoder
still needs to be able to handle randomised blocks
so as to maintain backwards compatibility with
older versions of bzip2.
--*/
bsW(s,1,0);
bsW ( s, 24, s->origPtr );
generateMTFValues ( s );
sendMTFValues ( s );
}
/*-- If this is the last block, add the stream trailer. --*/
if (is_last_block) {
bsPutUChar ( s, 0x17 ); bsPutUChar ( s, 0x72 );
bsPutUChar ( s, 0x45 ); bsPutUChar ( s, 0x38 );
bsPutUChar ( s, 0x50 ); bsPutUChar ( s, 0x90 );
bsPutUInt32 ( s, s->combinedCRC );
if (s->verbosity >= 2)
VPrintf1( " final combined CRC = 0x%08x\n ", s->combinedCRC );
bsFinishWrite ( s );
}
}
/*-------------------------------------------------------------*/
/*--- end compress.c ---*/
/*-------------------------------------------------------------*/

104
dep/bzip2/src/crctable.c Normal file
View File

@ -0,0 +1,104 @@
/*-------------------------------------------------------------*/
/*--- Table for doing CRCs ---*/
/*--- crctable.c ---*/
/*-------------------------------------------------------------*/
/* ------------------------------------------------------------------
This file is part of bzip2/libbzip2, a program and library for
lossless, block-sorting data compression.
bzip2/libbzip2 version 1.0.6 of 6 September 2010
Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org>
Please read the WARNING, DISCLAIMER and PATENTS sections in the
README file.
This program is released under the terms of the license contained
in the file LICENSE.
------------------------------------------------------------------ */
#include "bzlib_private.h"
/*--
I think this is an implementation of the AUTODIN-II,
Ethernet & FDDI 32-bit CRC standard. Vaguely derived
from code by Rob Warnock, in Section 51 of the
comp.compression FAQ.
--*/
UInt32 BZ2_crc32Table[256] = {
/*-- Ugly, innit? --*/
0x00000000L, 0x04c11db7L, 0x09823b6eL, 0x0d4326d9L,
0x130476dcL, 0x17c56b6bL, 0x1a864db2L, 0x1e475005L,
0x2608edb8L, 0x22c9f00fL, 0x2f8ad6d6L, 0x2b4bcb61L,
0x350c9b64L, 0x31cd86d3L, 0x3c8ea00aL, 0x384fbdbdL,
0x4c11db70L, 0x48d0c6c7L, 0x4593e01eL, 0x4152fda9L,
0x5f15adacL, 0x5bd4b01bL, 0x569796c2L, 0x52568b75L,
0x6a1936c8L, 0x6ed82b7fL, 0x639b0da6L, 0x675a1011L,
0x791d4014L, 0x7ddc5da3L, 0x709f7b7aL, 0x745e66cdL,
0x9823b6e0L, 0x9ce2ab57L, 0x91a18d8eL, 0x95609039L,
0x8b27c03cL, 0x8fe6dd8bL, 0x82a5fb52L, 0x8664e6e5L,
0xbe2b5b58L, 0xbaea46efL, 0xb7a96036L, 0xb3687d81L,
0xad2f2d84L, 0xa9ee3033L, 0xa4ad16eaL, 0xa06c0b5dL,
0xd4326d90L, 0xd0f37027L, 0xddb056feL, 0xd9714b49L,
0xc7361b4cL, 0xc3f706fbL, 0xceb42022L, 0xca753d95L,
0xf23a8028L, 0xf6fb9d9fL, 0xfbb8bb46L, 0xff79a6f1L,
0xe13ef6f4L, 0xe5ffeb43L, 0xe8bccd9aL, 0xec7dd02dL,
0x34867077L, 0x30476dc0L, 0x3d044b19L, 0x39c556aeL,
0x278206abL, 0x23431b1cL, 0x2e003dc5L, 0x2ac12072L,
0x128e9dcfL, 0x164f8078L, 0x1b0ca6a1L, 0x1fcdbb16L,
0x018aeb13L, 0x054bf6a4L, 0x0808d07dL, 0x0cc9cdcaL,
0x7897ab07L, 0x7c56b6b0L, 0x71159069L, 0x75d48ddeL,
0x6b93dddbL, 0x6f52c06cL, 0x6211e6b5L, 0x66d0fb02L,
0x5e9f46bfL, 0x5a5e5b08L, 0x571d7dd1L, 0x53dc6066L,
0x4d9b3063L, 0x495a2dd4L, 0x44190b0dL, 0x40d816baL,
0xaca5c697L, 0xa864db20L, 0xa527fdf9L, 0xa1e6e04eL,
0xbfa1b04bL, 0xbb60adfcL, 0xb6238b25L, 0xb2e29692L,
0x8aad2b2fL, 0x8e6c3698L, 0x832f1041L, 0x87ee0df6L,
0x99a95df3L, 0x9d684044L, 0x902b669dL, 0x94ea7b2aL,
0xe0b41de7L, 0xe4750050L, 0xe9362689L, 0xedf73b3eL,
0xf3b06b3bL, 0xf771768cL, 0xfa325055L, 0xfef34de2L,
0xc6bcf05fL, 0xc27dede8L, 0xcf3ecb31L, 0xcbffd686L,
0xd5b88683L, 0xd1799b34L, 0xdc3abdedL, 0xd8fba05aL,
0x690ce0eeL, 0x6dcdfd59L, 0x608edb80L, 0x644fc637L,
0x7a089632L, 0x7ec98b85L, 0x738aad5cL, 0x774bb0ebL,
0x4f040d56L, 0x4bc510e1L, 0x46863638L, 0x42472b8fL,
0x5c007b8aL, 0x58c1663dL, 0x558240e4L, 0x51435d53L,
0x251d3b9eL, 0x21dc2629L, 0x2c9f00f0L, 0x285e1d47L,
0x36194d42L, 0x32d850f5L, 0x3f9b762cL, 0x3b5a6b9bL,
0x0315d626L, 0x07d4cb91L, 0x0a97ed48L, 0x0e56f0ffL,
0x1011a0faL, 0x14d0bd4dL, 0x19939b94L, 0x1d528623L,
0xf12f560eL, 0xf5ee4bb9L, 0xf8ad6d60L, 0xfc6c70d7L,
0xe22b20d2L, 0xe6ea3d65L, 0xeba91bbcL, 0xef68060bL,
0xd727bbb6L, 0xd3e6a601L, 0xdea580d8L, 0xda649d6fL,
0xc423cd6aL, 0xc0e2d0ddL, 0xcda1f604L, 0xc960ebb3L,
0xbd3e8d7eL, 0xb9ff90c9L, 0xb4bcb610L, 0xb07daba7L,
0xae3afba2L, 0xaafbe615L, 0xa7b8c0ccL, 0xa379dd7bL,
0x9b3660c6L, 0x9ff77d71L, 0x92b45ba8L, 0x9675461fL,
0x8832161aL, 0x8cf30badL, 0x81b02d74L, 0x857130c3L,
0x5d8a9099L, 0x594b8d2eL, 0x5408abf7L, 0x50c9b640L,
0x4e8ee645L, 0x4a4ffbf2L, 0x470cdd2bL, 0x43cdc09cL,
0x7b827d21L, 0x7f436096L, 0x7200464fL, 0x76c15bf8L,
0x68860bfdL, 0x6c47164aL, 0x61043093L, 0x65c52d24L,
0x119b4be9L, 0x155a565eL, 0x18197087L, 0x1cd86d30L,
0x029f3d35L, 0x065e2082L, 0x0b1d065bL, 0x0fdc1becL,
0x3793a651L, 0x3352bbe6L, 0x3e119d3fL, 0x3ad08088L,
0x2497d08dL, 0x2056cd3aL, 0x2d15ebe3L, 0x29d4f654L,
0xc5a92679L, 0xc1683bceL, 0xcc2b1d17L, 0xc8ea00a0L,
0xd6ad50a5L, 0xd26c4d12L, 0xdf2f6bcbL, 0xdbee767cL,
0xe3a1cbc1L, 0xe760d676L, 0xea23f0afL, 0xeee2ed18L,
0xf0a5bd1dL, 0xf464a0aaL, 0xf9278673L, 0xfde69bc4L,
0x89b8fd09L, 0x8d79e0beL, 0x803ac667L, 0x84fbdbd0L,
0x9abc8bd5L, 0x9e7d9662L, 0x933eb0bbL, 0x97ffad0cL,
0xafb010b1L, 0xab710d06L, 0xa6322bdfL, 0xa2f33668L,
0xbcb4666dL, 0xb8757bdaL, 0xb5365d03L, 0xb1f740b4L
};
/*-------------------------------------------------------------*/
/*--- end crctable.c ---*/
/*-------------------------------------------------------------*/

646
dep/bzip2/src/decompress.c Normal file
View File

@ -0,0 +1,646 @@
/*-------------------------------------------------------------*/
/*--- Decompression machinery ---*/
/*--- decompress.c ---*/
/*-------------------------------------------------------------*/
/* ------------------------------------------------------------------
This file is part of bzip2/libbzip2, a program and library for
lossless, block-sorting data compression.
bzip2/libbzip2 version 1.0.6 of 6 September 2010
Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org>
Please read the WARNING, DISCLAIMER and PATENTS sections in the
README file.
This program is released under the terms of the license contained
in the file LICENSE.
------------------------------------------------------------------ */
#include "bzlib_private.h"
/*---------------------------------------------------*/
static
void makeMaps_d ( DState* s )
{
Int32 i;
s->nInUse = 0;
for (i = 0; i < 256; i++)
if (s->inUse[i]) {
s->seqToUnseq[s->nInUse] = i;
s->nInUse++;
}
}
/*---------------------------------------------------*/
#define RETURN(rrr) \
{ retVal = rrr; goto save_state_and_return; };
#define GET_BITS(lll,vvv,nnn) \
case lll: s->state = lll; \
while (True) { \
if (s->bsLive >= nnn) { \
UInt32 v; \
v = (s->bsBuff >> \
(s->bsLive-nnn)) & ((1 << nnn)-1); \
s->bsLive -= nnn; \
vvv = v; \
break; \
} \
if (s->strm->avail_in == 0) RETURN(BZ_OK); \
s->bsBuff \
= (s->bsBuff << 8) | \
((UInt32) \
(*((UChar*)(s->strm->next_in)))); \
s->bsLive += 8; \
s->strm->next_in++; \
s->strm->avail_in--; \
s->strm->total_in_lo32++; \
if (s->strm->total_in_lo32 == 0) \
s->strm->total_in_hi32++; \
}
#define GET_UCHAR(lll,uuu) \
GET_BITS(lll,uuu,8)
#define GET_BIT(lll,uuu) \
GET_BITS(lll,uuu,1)
/*---------------------------------------------------*/
#define GET_MTF_VAL(label1,label2,lval) \
{ \
if (groupPos == 0) { \
groupNo++; \
if (groupNo >= nSelectors) \
RETURN(BZ_DATA_ERROR); \
groupPos = BZ_G_SIZE; \
gSel = s->selector[groupNo]; \
gMinlen = s->minLens[gSel]; \
gLimit = &(s->limit[gSel][0]); \
gPerm = &(s->perm[gSel][0]); \
gBase = &(s->base[gSel][0]); \
} \
groupPos--; \
zn = gMinlen; \
GET_BITS(label1, zvec, zn); \
while (1) { \
if (zn > 20 /* the longest code */) \
RETURN(BZ_DATA_ERROR); \
if (zvec <= gLimit[zn]) break; \
zn++; \
GET_BIT(label2, zj); \
zvec = (zvec << 1) | zj; \
}; \
if (zvec - gBase[zn] < 0 \
|| zvec - gBase[zn] >= BZ_MAX_ALPHA_SIZE) \
RETURN(BZ_DATA_ERROR); \
lval = gPerm[zvec - gBase[zn]]; \
}
/*---------------------------------------------------*/
Int32 BZ2_decompress ( DState* s )
{
UChar uc;
Int32 retVal;
Int32 minLen, maxLen;
bz_stream* strm = s->strm;
/* stuff that needs to be saved/restored */
Int32 i;
Int32 j;
Int32 t;
Int32 alphaSize;
Int32 nGroups;
Int32 nSelectors;
Int32 EOB;
Int32 groupNo;
Int32 groupPos;
Int32 nextSym;
Int32 nblockMAX;
Int32 nblock;
Int32 es;
Int32 N;
Int32 curr;
Int32 zt;
Int32 zn;
Int32 zvec;
Int32 zj;
Int32 gSel;
Int32 gMinlen;
Int32* gLimit;
Int32* gBase;
Int32* gPerm;
if (s->state == BZ_X_MAGIC_1) {
/*initialise the save area*/
s->save_i = 0;
s->save_j = 0;
s->save_t = 0;
s->save_alphaSize = 0;
s->save_nGroups = 0;
s->save_nSelectors = 0;
s->save_EOB = 0;
s->save_groupNo = 0;
s->save_groupPos = 0;
s->save_nextSym = 0;
s->save_nblockMAX = 0;
s->save_nblock = 0;
s->save_es = 0;
s->save_N = 0;
s->save_curr = 0;
s->save_zt = 0;
s->save_zn = 0;
s->save_zvec = 0;
s->save_zj = 0;
s->save_gSel = 0;
s->save_gMinlen = 0;
s->save_gLimit = NULL;
s->save_gBase = NULL;
s->save_gPerm = NULL;
}
/*restore from the save area*/
i = s->save_i;
j = s->save_j;
t = s->save_t;
alphaSize = s->save_alphaSize;
nGroups = s->save_nGroups;
nSelectors = s->save_nSelectors;
EOB = s->save_EOB;
groupNo = s->save_groupNo;
groupPos = s->save_groupPos;
nextSym = s->save_nextSym;
nblockMAX = s->save_nblockMAX;
nblock = s->save_nblock;
es = s->save_es;
N = s->save_N;
curr = s->save_curr;
zt = s->save_zt;
zn = s->save_zn;
zvec = s->save_zvec;
zj = s->save_zj;
gSel = s->save_gSel;
gMinlen = s->save_gMinlen;
gLimit = s->save_gLimit;
gBase = s->save_gBase;
gPerm = s->save_gPerm;
retVal = BZ_OK;
switch (s->state) {
GET_UCHAR(BZ_X_MAGIC_1, uc);
if (uc != BZ_HDR_B) RETURN(BZ_DATA_ERROR_MAGIC);
GET_UCHAR(BZ_X_MAGIC_2, uc);
if (uc != BZ_HDR_Z) RETURN(BZ_DATA_ERROR_MAGIC);
GET_UCHAR(BZ_X_MAGIC_3, uc)
if (uc != BZ_HDR_h) RETURN(BZ_DATA_ERROR_MAGIC);
GET_BITS(BZ_X_MAGIC_4, s->blockSize100k, 8)
if (s->blockSize100k < (BZ_HDR_0 + 1) ||
s->blockSize100k > (BZ_HDR_0 + 9)) RETURN(BZ_DATA_ERROR_MAGIC);
s->blockSize100k -= BZ_HDR_0;
if (s->smallDecompress) {
s->ll16 = BZALLOC( s->blockSize100k * 100000 * sizeof(UInt16) );
s->ll4 = BZALLOC(
((1 + s->blockSize100k * 100000) >> 1) * sizeof(UChar)
);
if (s->ll16 == NULL || s->ll4 == NULL) RETURN(BZ_MEM_ERROR);
} else {
s->tt = BZALLOC( s->blockSize100k * 100000 * sizeof(Int32) );
if (s->tt == NULL) RETURN(BZ_MEM_ERROR);
}
GET_UCHAR(BZ_X_BLKHDR_1, uc);
if (uc == 0x17) goto endhdr_2;
if (uc != 0x31) RETURN(BZ_DATA_ERROR);
GET_UCHAR(BZ_X_BLKHDR_2, uc);
if (uc != 0x41) RETURN(BZ_DATA_ERROR);
GET_UCHAR(BZ_X_BLKHDR_3, uc);
if (uc != 0x59) RETURN(BZ_DATA_ERROR);
GET_UCHAR(BZ_X_BLKHDR_4, uc);
if (uc != 0x26) RETURN(BZ_DATA_ERROR);
GET_UCHAR(BZ_X_BLKHDR_5, uc);
if (uc != 0x53) RETURN(BZ_DATA_ERROR);
GET_UCHAR(BZ_X_BLKHDR_6, uc);
if (uc != 0x59) RETURN(BZ_DATA_ERROR);
s->currBlockNo++;
if (s->verbosity >= 2)
VPrintf1 ( "\n [%d: huff+mtf ", s->currBlockNo );
s->storedBlockCRC = 0;
GET_UCHAR(BZ_X_BCRC_1, uc);
s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);
GET_UCHAR(BZ_X_BCRC_2, uc);
s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);
GET_UCHAR(BZ_X_BCRC_3, uc);
s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);
GET_UCHAR(BZ_X_BCRC_4, uc);
s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);
GET_BITS(BZ_X_RANDBIT, s->blockRandomised, 1);
s->origPtr = 0;
GET_UCHAR(BZ_X_ORIGPTR_1, uc);
s->origPtr = (s->origPtr << 8) | ((Int32)uc);
GET_UCHAR(BZ_X_ORIGPTR_2, uc);
s->origPtr = (s->origPtr << 8) | ((Int32)uc);
GET_UCHAR(BZ_X_ORIGPTR_3, uc);
s->origPtr = (s->origPtr << 8) | ((Int32)uc);
if (s->origPtr < 0)
RETURN(BZ_DATA_ERROR);
if (s->origPtr > 10 + 100000*s->blockSize100k)
RETURN(BZ_DATA_ERROR);
/*--- Receive the mapping table ---*/
for (i = 0; i < 16; i++) {
GET_BIT(BZ_X_MAPPING_1, uc);
if (uc == 1)
s->inUse16[i] = True; else
s->inUse16[i] = False;
}
for (i = 0; i < 256; i++) s->inUse[i] = False;
for (i = 0; i < 16; i++)
if (s->inUse16[i])
for (j = 0; j < 16; j++) {
GET_BIT(BZ_X_MAPPING_2, uc);
if (uc == 1) s->inUse[i * 16 + j] = True;
}
makeMaps_d ( s );
if (s->nInUse == 0) RETURN(BZ_DATA_ERROR);
alphaSize = s->nInUse+2;
/*--- Now the selectors ---*/
GET_BITS(BZ_X_SELECTOR_1, nGroups, 3);
if (nGroups < 2 || nGroups > 6) RETURN(BZ_DATA_ERROR);
GET_BITS(BZ_X_SELECTOR_2, nSelectors, 15);
if (nSelectors < 1) RETURN(BZ_DATA_ERROR);
for (i = 0; i < nSelectors; i++) {
j = 0;
while (True) {
GET_BIT(BZ_X_SELECTOR_3, uc);
if (uc == 0) break;
j++;
if (j >= nGroups) RETURN(BZ_DATA_ERROR);
}
s->selectorMtf[i] = j;
}
/*--- Undo the MTF values for the selectors. ---*/
{
UChar pos[BZ_N_GROUPS], tmp, v;
for (v = 0; v < nGroups; v++) pos[v] = v;
for (i = 0; i < nSelectors; i++) {
v = s->selectorMtf[i];
tmp = pos[v];
while (v > 0) { pos[v] = pos[v-1]; v--; }
pos[0] = tmp;
s->selector[i] = tmp;
}
}
/*--- Now the coding tables ---*/
for (t = 0; t < nGroups; t++) {
GET_BITS(BZ_X_CODING_1, curr, 5);
for (i = 0; i < alphaSize; i++) {
while (True) {
if (curr < 1 || curr > 20) RETURN(BZ_DATA_ERROR);
GET_BIT(BZ_X_CODING_2, uc);
if (uc == 0) break;
GET_BIT(BZ_X_CODING_3, uc);
if (uc == 0) curr++; else curr--;
}
s->len[t][i] = curr;
}
}
/*--- Create the Huffman decoding tables ---*/
for (t = 0; t < nGroups; t++) {
minLen = 32;
maxLen = 0;
for (i = 0; i < alphaSize; i++) {
if (s->len[t][i] > maxLen) maxLen = s->len[t][i];
if (s->len[t][i] < minLen) minLen = s->len[t][i];
}
BZ2_hbCreateDecodeTables (
&(s->limit[t][0]),
&(s->base[t][0]),
&(s->perm[t][0]),
&(s->len[t][0]),
minLen, maxLen, alphaSize
);
s->minLens[t] = minLen;
}
/*--- Now the MTF values ---*/
EOB = s->nInUse+1;
nblockMAX = 100000 * s->blockSize100k;
groupNo = -1;
groupPos = 0;
for (i = 0; i <= 255; i++) s->unzftab[i] = 0;
/*-- MTF init --*/
{
Int32 ii, jj, kk;
kk = MTFA_SIZE-1;
for (ii = 256 / MTFL_SIZE - 1; ii >= 0; ii--) {
for (jj = MTFL_SIZE-1; jj >= 0; jj--) {
s->mtfa[kk] = (UChar)(ii * MTFL_SIZE + jj);
kk--;
}
s->mtfbase[ii] = kk + 1;
}
}
/*-- end MTF init --*/
nblock = 0;
GET_MTF_VAL(BZ_X_MTF_1, BZ_X_MTF_2, nextSym);
while (True) {
if (nextSym == EOB) break;
if (nextSym == BZ_RUNA || nextSym == BZ_RUNB) {
es = -1;
N = 1;
do {
/* Check that N doesn't get too big, so that es doesn't
go negative. The maximum value that can be
RUNA/RUNB encoded is equal to the block size (post
the initial RLE), viz, 900k, so bounding N at 2
million should guard against overflow without
rejecting any legitimate inputs. */
if (N >= 2*1024*1024) RETURN(BZ_DATA_ERROR);
if (nextSym == BZ_RUNA) es = es + (0+1) * N; else
if (nextSym == BZ_RUNB) es = es + (1+1) * N;
N = N * 2;
GET_MTF_VAL(BZ_X_MTF_3, BZ_X_MTF_4, nextSym);
}
while (nextSym == BZ_RUNA || nextSym == BZ_RUNB);
es++;
uc = s->seqToUnseq[ s->mtfa[s->mtfbase[0]] ];
s->unzftab[uc] += es;
if (s->smallDecompress)
while (es > 0) {
if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);
s->ll16[nblock] = (UInt16)uc;
nblock++;
es--;
}
else
while (es > 0) {
if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);
s->tt[nblock] = (UInt32)uc;
nblock++;
es--;
};
continue;
} else {
if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);
/*-- uc = MTF ( nextSym-1 ) --*/
{
Int32 ii, jj, kk, pp, lno, off;
UInt32 nn;
nn = (UInt32)(nextSym - 1);
if (nn < MTFL_SIZE) {
/* avoid general-case expense */
pp = s->mtfbase[0];
uc = s->mtfa[pp+nn];
while (nn > 3) {
Int32 z = pp+nn;
s->mtfa[(z) ] = s->mtfa[(z)-1];
s->mtfa[(z)-1] = s->mtfa[(z)-2];
s->mtfa[(z)-2] = s->mtfa[(z)-3];
s->mtfa[(z)-3] = s->mtfa[(z)-4];
nn -= 4;
}
while (nn > 0) {
s->mtfa[(pp+nn)] = s->mtfa[(pp+nn)-1]; nn--;
};
s->mtfa[pp] = uc;
} else {
/* general case */
lno = nn / MTFL_SIZE;
off = nn % MTFL_SIZE;
pp = s->mtfbase[lno] + off;
uc = s->mtfa[pp];
while (pp > s->mtfbase[lno]) {
s->mtfa[pp] = s->mtfa[pp-1]; pp--;
};
s->mtfbase[lno]++;
while (lno > 0) {
s->mtfbase[lno]--;
s->mtfa[s->mtfbase[lno]]
= s->mtfa[s->mtfbase[lno-1] + MTFL_SIZE - 1];
lno--;
}
s->mtfbase[0]--;
s->mtfa[s->mtfbase[0]] = uc;
if (s->mtfbase[0] == 0) {
kk = MTFA_SIZE-1;
for (ii = 256 / MTFL_SIZE-1; ii >= 0; ii--) {
for (jj = MTFL_SIZE-1; jj >= 0; jj--) {
s->mtfa[kk] = s->mtfa[s->mtfbase[ii] + jj];
kk--;
}
s->mtfbase[ii] = kk + 1;
}
}
}
}
/*-- end uc = MTF ( nextSym-1 ) --*/
s->unzftab[s->seqToUnseq[uc]]++;
if (s->smallDecompress)
s->ll16[nblock] = (UInt16)(s->seqToUnseq[uc]); else
s->tt[nblock] = (UInt32)(s->seqToUnseq[uc]);
nblock++;
GET_MTF_VAL(BZ_X_MTF_5, BZ_X_MTF_6, nextSym);
continue;
}
}
/* Now we know what nblock is, we can do a better sanity
check on s->origPtr.
*/
if (s->origPtr < 0 || s->origPtr >= nblock)
RETURN(BZ_DATA_ERROR);
/*-- Set up cftab to facilitate generation of T^(-1) --*/
/* Check: unzftab entries in range. */
for (i = 0; i <= 255; i++) {
if (s->unzftab[i] < 0 || s->unzftab[i] > nblock)
RETURN(BZ_DATA_ERROR);
}
/* Actually generate cftab. */
s->cftab[0] = 0;
for (i = 1; i <= 256; i++) s->cftab[i] = s->unzftab[i-1];
for (i = 1; i <= 256; i++) s->cftab[i] += s->cftab[i-1];
/* Check: cftab entries in range. */
for (i = 0; i <= 256; i++) {
if (s->cftab[i] < 0 || s->cftab[i] > nblock) {
/* s->cftab[i] can legitimately be == nblock */
RETURN(BZ_DATA_ERROR);
}
}
/* Check: cftab entries non-descending. */
for (i = 1; i <= 256; i++) {
if (s->cftab[i-1] > s->cftab[i]) {
RETURN(BZ_DATA_ERROR);
}
}
s->state_out_len = 0;
s->state_out_ch = 0;
BZ_INITIALISE_CRC ( s->calculatedBlockCRC );
s->state = BZ_X_OUTPUT;
if (s->verbosity >= 2) VPrintf0 ( "rt+rld" );
if (s->smallDecompress) {
/*-- Make a copy of cftab, used in generation of T --*/
for (i = 0; i <= 256; i++) s->cftabCopy[i] = s->cftab[i];
/*-- compute the T vector --*/
for (i = 0; i < nblock; i++) {
uc = (UChar)(s->ll16[i]);
SET_LL(i, s->cftabCopy[uc]);
s->cftabCopy[uc]++;
}
/*-- Compute T^(-1) by pointer reversal on T --*/
i = s->origPtr;
j = GET_LL(i);
do {
Int32 tmp = GET_LL(j);
SET_LL(j, i);
i = j;
j = tmp;
}
while (i != s->origPtr);
s->tPos = s->origPtr;
s->nblock_used = 0;
if (s->blockRandomised) {
BZ_RAND_INIT_MASK;
BZ_GET_SMALL(s->k0); s->nblock_used++;
BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK;
} else {
BZ_GET_SMALL(s->k0); s->nblock_used++;
}
} else {
/*-- compute the T^(-1) vector --*/
for (i = 0; i < nblock; i++) {
uc = (UChar)(s->tt[i] & 0xff);
s->tt[s->cftab[uc]] |= (i << 8);
s->cftab[uc]++;
}
s->tPos = s->tt[s->origPtr] >> 8;
s->nblock_used = 0;
if (s->blockRandomised) {
BZ_RAND_INIT_MASK;
BZ_GET_FAST(s->k0); s->nblock_used++;
BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK;
} else {
BZ_GET_FAST(s->k0); s->nblock_used++;
}
}
RETURN(BZ_OK);
endhdr_2:
GET_UCHAR(BZ_X_ENDHDR_2, uc);
if (uc != 0x72) RETURN(BZ_DATA_ERROR);
GET_UCHAR(BZ_X_ENDHDR_3, uc);
if (uc != 0x45) RETURN(BZ_DATA_ERROR);
GET_UCHAR(BZ_X_ENDHDR_4, uc);
if (uc != 0x38) RETURN(BZ_DATA_ERROR);
GET_UCHAR(BZ_X_ENDHDR_5, uc);
if (uc != 0x50) RETURN(BZ_DATA_ERROR);
GET_UCHAR(BZ_X_ENDHDR_6, uc);
if (uc != 0x90) RETURN(BZ_DATA_ERROR);
s->storedCombinedCRC = 0;
GET_UCHAR(BZ_X_CCRC_1, uc);
s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);
GET_UCHAR(BZ_X_CCRC_2, uc);
s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);
GET_UCHAR(BZ_X_CCRC_3, uc);
s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);
GET_UCHAR(BZ_X_CCRC_4, uc);
s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);
s->state = BZ_X_IDLE;
RETURN(BZ_STREAM_END);
default: AssertH ( False, 4001 );
}
AssertH ( False, 4002 );
save_state_and_return:
s->save_i = i;
s->save_j = j;
s->save_t = t;
s->save_alphaSize = alphaSize;
s->save_nGroups = nGroups;
s->save_nSelectors = nSelectors;
s->save_EOB = EOB;
s->save_groupNo = groupNo;
s->save_groupPos = groupPos;
s->save_nextSym = nextSym;
s->save_nblockMAX = nblockMAX;
s->save_nblock = nblock;
s->save_es = es;
s->save_N = N;
s->save_curr = curr;
s->save_zt = zt;
s->save_zn = zn;
s->save_zvec = zvec;
s->save_zj = zj;
s->save_gSel = gSel;
s->save_gMinlen = gMinlen;
s->save_gLimit = gLimit;
s->save_gBase = gBase;
s->save_gPerm = gPerm;
return retVal;
}
/*-------------------------------------------------------------*/
/*--- end decompress.c ---*/
/*-------------------------------------------------------------*/

205
dep/bzip2/src/huffman.c Normal file
View File

@ -0,0 +1,205 @@
/*-------------------------------------------------------------*/
/*--- Huffman coding low-level stuff ---*/
/*--- huffman.c ---*/
/*-------------------------------------------------------------*/
/* ------------------------------------------------------------------
This file is part of bzip2/libbzip2, a program and library for
lossless, block-sorting data compression.
bzip2/libbzip2 version 1.0.6 of 6 September 2010
Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org>
Please read the WARNING, DISCLAIMER and PATENTS sections in the
README file.
This program is released under the terms of the license contained
in the file LICENSE.
------------------------------------------------------------------ */
#include "bzlib_private.h"
/*---------------------------------------------------*/
#define WEIGHTOF(zz0) ((zz0) & 0xffffff00)
#define DEPTHOF(zz1) ((zz1) & 0x000000ff)
#define MYMAX(zz2,zz3) ((zz2) > (zz3) ? (zz2) : (zz3))
#define ADDWEIGHTS(zw1,zw2) \
(WEIGHTOF(zw1)+WEIGHTOF(zw2)) | \
(1 + MYMAX(DEPTHOF(zw1),DEPTHOF(zw2)))
#define UPHEAP(z) \
{ \
Int32 zz, tmp; \
zz = z; tmp = heap[zz]; \
while (weight[tmp] < weight[heap[zz >> 1]]) { \
heap[zz] = heap[zz >> 1]; \
zz >>= 1; \
} \
heap[zz] = tmp; \
}
#define DOWNHEAP(z) \
{ \
Int32 zz, yy, tmp; \
zz = z; tmp = heap[zz]; \
while (True) { \
yy = zz << 1; \
if (yy > nHeap) break; \
if (yy < nHeap && \
weight[heap[yy+1]] < weight[heap[yy]]) \
yy++; \
if (weight[tmp] < weight[heap[yy]]) break; \
heap[zz] = heap[yy]; \
zz = yy; \
} \
heap[zz] = tmp; \
}
/*---------------------------------------------------*/
void BZ2_hbMakeCodeLengths ( UChar *len,
Int32 *freq,
Int32 alphaSize,
Int32 maxLen )
{
/*--
Nodes and heap entries run from 1. Entry 0
for both the heap and nodes is a sentinel.
--*/
Int32 nNodes, nHeap, n1, n2, i, j, k;
Bool tooLong;
Int32 heap [ BZ_MAX_ALPHA_SIZE + 2 ];
Int32 weight [ BZ_MAX_ALPHA_SIZE * 2 ];
Int32 parent [ BZ_MAX_ALPHA_SIZE * 2 ];
for (i = 0; i < alphaSize; i++)
weight[i+1] = (freq[i] == 0 ? 1 : freq[i]) << 8;
while (True) {
nNodes = alphaSize;
nHeap = 0;
heap[0] = 0;
weight[0] = 0;
parent[0] = -2;
for (i = 1; i <= alphaSize; i++) {
parent[i] = -1;
nHeap++;
heap[nHeap] = i;
UPHEAP(nHeap);
}
AssertH( nHeap < (BZ_MAX_ALPHA_SIZE+2), 2001 );
while (nHeap > 1) {
n1 = heap[1]; heap[1] = heap[nHeap]; nHeap--; DOWNHEAP(1);
n2 = heap[1]; heap[1] = heap[nHeap]; nHeap--; DOWNHEAP(1);
nNodes++;
parent[n1] = parent[n2] = nNodes;
weight[nNodes] = ADDWEIGHTS(weight[n1], weight[n2]);
parent[nNodes] = -1;
nHeap++;
heap[nHeap] = nNodes;
UPHEAP(nHeap);
}
AssertH( nNodes < (BZ_MAX_ALPHA_SIZE * 2), 2002 );
tooLong = False;
for (i = 1; i <= alphaSize; i++) {
j = 0;
k = i;
while (parent[k] >= 0) { k = parent[k]; j++; }
len[i-1] = j;
if (j > maxLen) tooLong = True;
}
if (! tooLong) break;
/* 17 Oct 04: keep-going condition for the following loop used
to be 'i < alphaSize', which missed the last element,
theoretically leading to the possibility of the compressor
looping. However, this count-scaling step is only needed if
one of the generated Huffman code words is longer than
maxLen, which up to and including version 1.0.2 was 20 bits,
which is extremely unlikely. In version 1.0.3 maxLen was
changed to 17 bits, which has minimal effect on compression
ratio, but does mean this scaling step is used from time to
time, enough to verify that it works.
This means that bzip2-1.0.3 and later will only produce
Huffman codes with a maximum length of 17 bits. However, in
order to preserve backwards compatibility with bitstreams
produced by versions pre-1.0.3, the decompressor must still
handle lengths of up to 20. */
for (i = 1; i <= alphaSize; i++) {
j = weight[i] >> 8;
j = 1 + (j / 2);
weight[i] = j << 8;
}
}
}
/*---------------------------------------------------*/
void BZ2_hbAssignCodes ( Int32 *code,
UChar *length,
Int32 minLen,
Int32 maxLen,
Int32 alphaSize )
{
Int32 n, vec, i;
vec = 0;
for (n = minLen; n <= maxLen; n++) {
for (i = 0; i < alphaSize; i++)
if (length[i] == n) { code[i] = vec; vec++; };
vec <<= 1;
}
}
/*---------------------------------------------------*/
void BZ2_hbCreateDecodeTables ( Int32 *limit,
Int32 *base,
Int32 *perm,
UChar *length,
Int32 minLen,
Int32 maxLen,
Int32 alphaSize )
{
Int32 pp, i, j, vec;
pp = 0;
for (i = minLen; i <= maxLen; i++)
for (j = 0; j < alphaSize; j++)
if (length[j] == i) { perm[pp] = j; pp++; };
for (i = 0; i < BZ_MAX_CODE_LEN; i++) base[i] = 0;
for (i = 0; i < alphaSize; i++) base[length[i]+1]++;
for (i = 1; i < BZ_MAX_CODE_LEN; i++) base[i] += base[i-1];
for (i = 0; i < BZ_MAX_CODE_LEN; i++) limit[i] = 0;
vec = 0;
for (i = minLen; i <= maxLen; i++) {
vec += (base[i+1] - base[i]);
limit[i] = vec-1;
vec <<= 1;
}
for (i = minLen + 1; i <= maxLen; i++)
base[i] = ((limit[i-1] + 1) << 1) - base[i];
}
/*-------------------------------------------------------------*/
/*--- end huffman.c ---*/
/*-------------------------------------------------------------*/

View File

@ -0,0 +1 @@
#include "bzlib_private.h"

84
dep/bzip2/src/randtable.c Normal file
View File

@ -0,0 +1,84 @@
/*-------------------------------------------------------------*/
/*--- Table for randomising repetitive blocks ---*/
/*--- randtable.c ---*/
/*-------------------------------------------------------------*/
/* ------------------------------------------------------------------
This file is part of bzip2/libbzip2, a program and library for
lossless, block-sorting data compression.
bzip2/libbzip2 version 1.0.6 of 6 September 2010
Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org>
Please read the WARNING, DISCLAIMER and PATENTS sections in the
README file.
This program is released under the terms of the license contained
in the file LICENSE.
------------------------------------------------------------------ */
#include "bzlib_private.h"
/*---------------------------------------------*/
Int32 BZ2_rNums[512] = {
619, 720, 127, 481, 931, 816, 813, 233, 566, 247,
985, 724, 205, 454, 863, 491, 741, 242, 949, 214,
733, 859, 335, 708, 621, 574, 73, 654, 730, 472,
419, 436, 278, 496, 867, 210, 399, 680, 480, 51,
878, 465, 811, 169, 869, 675, 611, 697, 867, 561,
862, 687, 507, 283, 482, 129, 807, 591, 733, 623,
150, 238, 59, 379, 684, 877, 625, 169, 643, 105,
170, 607, 520, 932, 727, 476, 693, 425, 174, 647,
73, 122, 335, 530, 442, 853, 695, 249, 445, 515,
909, 545, 703, 919, 874, 474, 882, 500, 594, 612,
641, 801, 220, 162, 819, 984, 589, 513, 495, 799,
161, 604, 958, 533, 221, 400, 386, 867, 600, 782,
382, 596, 414, 171, 516, 375, 682, 485, 911, 276,
98, 553, 163, 354, 666, 933, 424, 341, 533, 870,
227, 730, 475, 186, 263, 647, 537, 686, 600, 224,
469, 68, 770, 919, 190, 373, 294, 822, 808, 206,
184, 943, 795, 384, 383, 461, 404, 758, 839, 887,
715, 67, 618, 276, 204, 918, 873, 777, 604, 560,
951, 160, 578, 722, 79, 804, 96, 409, 713, 940,
652, 934, 970, 447, 318, 353, 859, 672, 112, 785,
645, 863, 803, 350, 139, 93, 354, 99, 820, 908,
609, 772, 154, 274, 580, 184, 79, 626, 630, 742,
653, 282, 762, 623, 680, 81, 927, 626, 789, 125,
411, 521, 938, 300, 821, 78, 343, 175, 128, 250,
170, 774, 972, 275, 999, 639, 495, 78, 352, 126,
857, 956, 358, 619, 580, 124, 737, 594, 701, 612,
669, 112, 134, 694, 363, 992, 809, 743, 168, 974,
944, 375, 748, 52, 600, 747, 642, 182, 862, 81,
344, 805, 988, 739, 511, 655, 814, 334, 249, 515,
897, 955, 664, 981, 649, 113, 974, 459, 893, 228,
433, 837, 553, 268, 926, 240, 102, 654, 459, 51,
686, 754, 806, 760, 493, 403, 415, 394, 687, 700,
946, 670, 656, 610, 738, 392, 760, 799, 887, 653,
978, 321, 576, 617, 626, 502, 894, 679, 243, 440,
680, 879, 194, 572, 640, 724, 926, 56, 204, 700,
707, 151, 457, 449, 797, 195, 791, 558, 945, 679,
297, 59, 87, 824, 713, 663, 412, 693, 342, 606,
134, 108, 571, 364, 631, 212, 174, 643, 304, 329,
343, 97, 430, 751, 497, 314, 983, 374, 822, 928,
140, 206, 73, 263, 980, 736, 876, 478, 430, 305,
170, 514, 364, 692, 829, 82, 855, 953, 676, 246,
369, 970, 294, 750, 807, 827, 150, 790, 288, 923,
804, 378, 215, 828, 592, 281, 565, 555, 710, 82,
896, 831, 547, 261, 524, 462, 293, 465, 502, 56,
661, 821, 976, 991, 658, 869, 905, 758, 745, 193,
768, 550, 608, 933, 378, 286, 215, 979, 792, 961,
61, 688, 793, 644, 986, 403, 106, 366, 905, 644,
372, 567, 466, 434, 645, 210, 389, 550, 919, 135,
780, 773, 635, 389, 707, 100, 626, 958, 165, 504,
920, 176, 193, 713, 857, 265, 203, 50, 668, 108,
645, 990, 626, 197, 510, 357, 358, 850, 858, 364,
936, 638
};
/*-------------------------------------------------------------*/
/*--- end randtable.c ---*/
/*-------------------------------------------------------------*/

View File

@ -0,0 +1,60 @@
import org.doomedsociety.gradlecpp.cfg.ToolchainConfigUtils
import org.doomedsociety.gradlecpp.msvc.MsvcToolchainConfig
import org.doomedsociety.gradlecpp.toolchain.icc.Icc
import org.doomedsociety.gradlecpp.toolchain.icc.IccCompilerPlugin
import org.gradle.nativeplatform.NativeBinarySpec
import org.gradle.nativeplatform.NativeLibrarySpec
apply plugin: 'cpp'
apply plugin: IccCompilerPlugin
void setupToolchain(NativeBinarySpec b) {
def cfg = rootProject.createToolchainConfig(b)
ToolchainConfigUtils.apply(project, cfg, b)
}
model {
buildTypes {
debug
release
}
platforms {
x86 {
architecture "x86"
}
}
toolChains {
visualCpp(VisualCpp) {
}
icc(Icc) {
}
}
components {
cppunitlite(NativeLibrarySpec) {
targetPlatform 'x86'
sources {
cppul_main(CppSourceSet) {
source {
srcDir "src"
include "**/*.cpp"
}
exportedHeaders {
srcDir "include"
}
}
}
binaries.all { NativeBinarySpec b ->
project.setupToolchain(b)
}
}
}
}

View File

@ -0,0 +1,18 @@
#pragma once
#include "Failure.h"
class Assertions {
public:
static void StringEquals(std::string message, std::string expected, std::string actual, const char* fileName, long lineNumber);
static void StringEquals(std::string message, const char* expected, const char* actual, const char* fileName, long lineNumber);
static void ConditionFailed(std::string message, std::string condition, const char* fileName, long lineNumber);
static void LongEquals(std::string message, long expected, long actual, const char* fileName, long lineNumber);
static void UInt32Equals(std::string message, unsigned int expected, unsigned int actual, const char* fileName, long lineNumber);
static void CharEquals(std::string message, char expected, char actual, const char* fileName, long lineNumber);
};

View File

@ -0,0 +1,53 @@
#pragma once
#include <exception>
#include <sstream>
class TestFailException : public std::exception {
public:
TestFailException(std::string message, std::string fileName, long lineNumber) {
std::stringstream ss;
ss << message << " at " << fileName << " line " << lineNumber;
this->message = ss.str();
this->fileName = fileName;
this->lineNumber = lineNumber;
}
virtual ~TestFailException() throw() {
}
std::string message;
std::string fileName;
long lineNumber;
virtual const char * what() const throw() {
return message.c_str();
}
};
class Failure {
public:
Failure (TestFailException &e, std::string testName) {
this->testName = testName;
this->message = e.message;
this->fileName = e.fileName;
this->lineNumber = e.lineNumber;
}
Failure (std::string message, std::string testName) {
this->testName = testName;
this->message = message;
}
std::string testName;
std::string message;
std::string fileName;
long lineNumber;
};

View File

@ -0,0 +1,9 @@
#pragma once
class GradleAdapter {
public:
int writeAllTestsInfoToFile(const char* fname);
int runTest(const char* groupName, const char* testName);
int runAllTests();
int testsEntryPoint(int argc, char* argv[]);
};

View File

@ -0,0 +1,84 @@
#pragma once
#include "Failure.h"
#include "TestResult.h"
#include "Assertions.h"
#include <cmath>
#include <string>
#include <sstream>
class Test
{
public:
Test (const char* testName, const char* group, int timeout);
virtual void runInternal () = 0;
void setNext(Test *test);
Test *getNext () const;
void run(TestResult& result);
const char* getName() {
return name_.c_str();
}
const char* getGroup() {
return group_.c_str();
}
int getTimeout() {
return timeout_;
}
protected:
std::string name_;
std::string group_;
Test *next_;
int timeout_;
};
#define TEST(testName, testGroup, testTimeout)\
class testGroup##testName##Test : public Test \
{ public: testGroup##testName##Test () : Test (#testName , #testGroup , testTimeout) {} \
void runInternal (); } \
testGroup##testName##Instance; \
void testGroup##testName##Test::runInternal()
#define CHECK(msg, condition) { if (!(condition)) { Assertions::ConditionFailed(msg,#condition, __FILE__, __LINE__); \
} \
}
#define ZSTR_EQUAL(msg,expected,actual) { \
Assertions::StringEquals((msg), (expected), (actual), __FILE__, __LINE__); \
}
#define LONGS_EQUAL(msg,expected,actual)\
{ Assertions::LongEquals(msg,expected, actual, __FILE__, __LINE__); }
#define UINT32_EQUALS(msg,expected,actual)\
{ Assertions::UInt32Equals(msg,expected, actual, __FILE__, __LINE__); }
#define CHARS_EQUAL(msg,expected,actual)\
{ Assertions::CharEquals(msg,expected, actual, __FILE__, __LINE__); }
#define DOUBLES_EQUAL(expected,actual,threshold)\
{ double actualTemp = actual; \
double expectedTemp = expected; \
if (fabs ((expectedTemp)-(actualTemp)) > threshold) \
{ result_.addFailure (Failure (name_, __FILE__, __LINE__, \
StringFrom((double)expectedTemp), StringFrom((double)actualTemp))); return; } }
#define FAIL(text) \
{ throw TestFailException(text, std::string(__FILE__), __LINE__);}

View File

@ -0,0 +1,18 @@
///////////////////////////////////////////////////////////////////////////////
//
// TESTHARNESS.H
//
// The primary include file for the framework.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef TESTHARNESS_H
#define TESTHARNESS_H
#include "Test.h"
#include "TestResult.h"
#include "Failure.h"
#include "TestRegistry.h"
#endif

View File

@ -0,0 +1,32 @@
///////////////////////////////////////////////////////////////////////////////
//
// TESTREGISTRY.H
//
// TestRegistry is a singleton collection of all the tests to run in a system.
//
///////////////////////////////////////////////////////////////////////////////
#pragma once
class Test;
class TestResult;
class TestRegistry
{
public:
static void addTest (Test *test);
static void runAllTests (TestResult& result);
static Test* getFirstTest();
private:
static TestRegistry& instance ();
void add (Test *test);
void run (TestResult& result);
Test *tests;
};

View File

@ -0,0 +1,18 @@
#pragma once
class Failure;
class TestResult
{
public:
TestResult ();
virtual void testsStarted ();
virtual void addFailure (const Failure& failure);
virtual void testsEnded ();
int getFailureCount() {
return failureCount;
}
private:
int failureCount;
};

View File

@ -0,0 +1,156 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug Swds Play|Win32">
<Configuration>Debug Swds Play</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug Swds|Win32">
<Configuration>Debug Swds</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\include\cppunitlite\Assertions.h" />
<ClInclude Include="..\include\cppunitlite\Failure.h" />
<ClInclude Include="..\include\cppunitlite\GradleAdapter.h" />
<ClInclude Include="..\include\cppunitlite\Test.h" />
<ClInclude Include="..\include\cppunitlite\TestHarness.h" />
<ClInclude Include="..\include\cppunitlite\TestRegistry.h" />
<ClInclude Include="..\include\cppunitlite\TestResult.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\src\Assertions.cpp" />
<ClCompile Include="..\src\GradleAdapter.cpp" />
<ClCompile Include="..\src\Test.cpp" />
<ClCompile Include="..\src\TestRegistry.cpp" />
<ClCompile Include="..\src\TestResult.cpp" />
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{CEB94F7C-E459-4673-AABB-36E2074396C0}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>cppunitlite</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug Swds|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug Swds Play|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug Swds|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug Swds Play|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup />
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_CRT_SECURE_NO_WARNINGS;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<AdditionalIncludeDirectories>$(ProjectDir)..\include\</AdditionalIncludeDirectories>
<CompileAs>CompileAsCpp</CompileAs>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug Swds|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_CRT_SECURE_NO_WARNINGS;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<AdditionalIncludeDirectories>$(ProjectDir)..\include\</AdditionalIncludeDirectories>
<CompileAs>CompileAsCpp</CompileAs>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug Swds Play|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_CRT_SECURE_NO_WARNINGS;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<AdditionalIncludeDirectories>$(ProjectDir)..\include\</AdditionalIncludeDirectories>
<CompileAs>CompileAsCpp</CompileAs>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;_CRT_SECURE_NO_WARNINGS;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<AdditionalIncludeDirectories>$(ProjectDir)..\include\</AdditionalIncludeDirectories>
<TreatWarningAsError>false</TreatWarningAsError>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,51 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="include">
<UniqueIdentifier>{f9e9a344-81ba-4669-a9a5-a9abe81561f8}</UniqueIdentifier>
</Filter>
<Filter Include="src">
<UniqueIdentifier>{93df47a7-64d0-4a1a-8fcc-4f5dfa6d9086}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\include\cppunitlite\Assertions.h">
<Filter>include</Filter>
</ClInclude>
<ClInclude Include="..\include\cppunitlite\Failure.h">
<Filter>include</Filter>
</ClInclude>
<ClInclude Include="..\include\cppunitlite\Test.h">
<Filter>include</Filter>
</ClInclude>
<ClInclude Include="..\include\cppunitlite\TestHarness.h">
<Filter>include</Filter>
</ClInclude>
<ClInclude Include="..\include\cppunitlite\TestRegistry.h">
<Filter>include</Filter>
</ClInclude>
<ClInclude Include="..\include\cppunitlite\TestResult.h">
<Filter>include</Filter>
</ClInclude>
<ClInclude Include="..\include\cppunitlite\GradleAdapter.h">
<Filter>include</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\src\Assertions.cpp">
<Filter>src</Filter>
</ClCompile>
<ClCompile Include="..\src\Test.cpp">
<Filter>src</Filter>
</ClCompile>
<ClCompile Include="..\src\TestRegistry.cpp">
<Filter>src</Filter>
</ClCompile>
<ClCompile Include="..\src\TestResult.cpp">
<Filter>src</Filter>
</ClCompile>
<ClCompile Include="..\src\GradleAdapter.cpp">
<Filter>src</Filter>
</ClCompile>
</ItemGroup>
</Project>

View File

@ -0,0 +1,56 @@
#include "cppunitlite/Assertions.h"
#include <stdio.h>
#include <string.h>
#include <sstream>
void Assertions::StringEquals(std::string message, std::string expected, std::string actual, const char* fileName, long lineNumber) {
if (expected != actual) {
std::stringstream ss;
ss << message << " (expected '" << expected << "', got '" << actual << "')";
throw TestFailException(ss.str(), std::string(fileName), lineNumber);
}
}
void Assertions::StringEquals(std::string message, const char* expected, const char* actual, const char* fileName, long lineNumber) {
if (expected == NULL) {
std::stringstream ss;
ss << message << " (expected '" << expected << "', got NULL";
throw TestFailException(ss.str(), std::string(fileName), lineNumber);
}
if (strcmp(expected, actual)) {
std::stringstream ss;
ss << message << " (expected '" << expected << "', got '" << actual << "')";
throw TestFailException(ss.str(), std::string(fileName), lineNumber);
}
}
void Assertions::ConditionFailed(std::string message, std::string condition, const char* fileName, long lineNumber) {
std::stringstream ss;
ss << message << " (condition failed: " << condition << ")";
throw TestFailException(ss.str(), std::string(fileName), lineNumber);
}
void Assertions::LongEquals(std::string message, long expected, long actual, const char* fileName, long lineNumber) {
if (expected != actual) {
std::stringstream ss;
ss << message << " (expected '" << expected << "', got '" << actual << "')";
throw TestFailException(ss.str(), std::string(fileName), lineNumber);
}
}
void Assertions::UInt32Equals(std::string message, unsigned int expected, unsigned int actual, const char* fileName, long lineNumber) {
if (expected != actual) {
std::stringstream ss;
ss << message << " (expected '" << expected << "', got '" << actual << "')";
throw TestFailException(ss.str(), std::string(fileName), lineNumber);
}
}
void Assertions::CharEquals(std::string message, char expected, char actual, const char* fileName, long lineNumber) {
if (expected != actual) {
std::stringstream ss;
ss << message << " (expected '" << expected << "', got '" << actual << "')";
throw TestFailException(ss.str(), std::string(fileName), lineNumber);
}
}

View File

@ -0,0 +1,98 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cppunitlite/GradleAdapter.h"
#include "cppunitlite/Test.h"
#include "cppunitlite/TestRegistry.h"
int GradleAdapter::writeAllTestsInfoToFile(const char* fname) {
FILE* outFile = fopen(fname, "w");
if (outFile == NULL) {
return 1;
}
fprintf(outFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
fprintf(outFile, "<tests>\n");
Test* curTest = TestRegistry::getFirstTest();
while (curTest != NULL) {
fprintf(outFile, "<test ");
fprintf(outFile, " name=\"%s\" ", curTest->getName());
fprintf(outFile, " group=\"%s\" ", curTest->getGroup());
fprintf(outFile, " timeout=\"%d\" ", curTest->getTimeout());
fprintf(outFile, "/>\n");
curTest = curTest->getNext();
}
fprintf(outFile, "</tests>\n");
fclose(outFile);
return 0;
}
int GradleAdapter::runTest(const char* groupName, const char* testName) {
Test* curTest = TestRegistry::getFirstTest();
while (curTest != NULL && strcmp(groupName, curTest->getGroup()) && strcmp(testName, curTest->getGroup())) {
curTest = curTest->getNext();
}
if (curTest == NULL) {
printf("Test group='%s' name='%s' not found\n", groupName, testName);
return 2;
}
TestResult result;
curTest->run(result);
if (result.getFailureCount()) {
return 1;
}
else {
return 0;
}
}
int GradleAdapter::runAllTests() {
Test* curTest = TestRegistry::getFirstTest();
while (curTest != NULL) {
TestResult result;
curTest->run(result);
if (result.getFailureCount()) {
return 1;
}
curTest = curTest->getNext();
}
printf("There were no test failures\n");
return 0;
}
int GradleAdapter::testsEntryPoint(int argc, char* argv[]) {
if (argc < 2 || !strcmp(argv[1], "-all")) {
return runAllTests();
}
if (!strcmp(argv[1], "-writeTestInfo")) {
if (argc != 3) {
printf("-writeTestInfo requires file name\n");
}
return writeAllTestsInfoToFile(argv[2]);
}
if (!strcmp(argv[1], "-runTest")) {
if (argc != 4) {
printf("-runTest requires group name and test name\n");
}
return runTest(argv[2], argv[3]);
}
printf("Bad argument specified\n");
return 1;
}

View File

@ -0,0 +1,41 @@
#include "cppunitlite/Test.h"
#include "cppunitlite/TestRegistry.h"
#include "cppunitlite/Failure.h"
#include <exception>
#include <sstream>
Test::Test (const char* testName, const char* testGroup, int timeout)
: name_ (testName), group_ (testGroup), timeout_(timeout)
{
TestRegistry::addTest (this);
}
Test *Test::getNext() const
{
return next_;
}
void Test::setNext(Test *test)
{
next_ = test;
}
void Test::run(TestResult &result) {
try {
runInternal();
} catch (TestFailException *e) {
result.addFailure(Failure(*e, name_));
} catch (std::exception &e) {
std::stringstream ss;
ss << "unexpected exception " << e.what();
result.addFailure(Failure(ss.str(), name_));
} catch (...) {
result.addFailure(Failure("unknown exception", name_));
}
}

View File

@ -0,0 +1,50 @@
#include "cppunitlite/Test.h"
#include "cppunitlite/TestResult.h"
#include "cppunitlite/TestRegistry.h"
void TestRegistry::addTest (Test *test)
{
instance ().add (test);
}
void TestRegistry::runAllTests (TestResult& result)
{
instance ().run (result);
}
Test* TestRegistry::getFirstTest() {
return instance().tests;
}
TestRegistry& TestRegistry::instance ()
{
static TestRegistry registry;
return registry;
}
void TestRegistry::add (Test *test)
{
if (tests == 0) {
tests = test;
return;
}
test->setNext (tests);
tests = test;
}
void TestRegistry::run (TestResult& result)
{
result.testsStarted ();
for (Test *test = tests; test != 0; test = test->getNext ())
test->run (result);
result.testsEnded ();
}

View File

@ -0,0 +1,36 @@
#include "cppunitlite/TestResult.h"
#include "cppunitlite/Failure.h"
#include <sstream>
#include <iostream>
TestResult::TestResult ()
: failureCount (0)
{
}
void TestResult::testsStarted ()
{
}
void TestResult::addFailure (const Failure& failure) {
std::stringstream ss;
ss << "Failure in test '" << failure.testName << "' :" << failure.message;
std::cout << ss.str() << std::endl;
failureCount++;
}
void TestResult::testsEnded () {
std::stringstream ss;
if (failureCount > 0) {
ss << "There were " << failureCount << " failures";
} else {
ss << "There were no test failures";
}
std::cout << ss.str() << std::endl;
}

2
gradle.properties Normal file
View File

@ -0,0 +1,2 @@
majorVersion=0
minorVersion=2

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,6 @@
#Sat May 02 13:29:15 BRT 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.4-rc-2-all.zip

164
gradlew vendored Normal file
View File

@ -0,0 +1,164 @@
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# For Cygwin, ensure paths are in UNIX format before anything is touched.
if $cygwin ; then
[ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
fi
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >&-
APP_HOME="`pwd -P`"
cd "$SAVED" >&-
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"

90
gradlew.bat vendored Normal file
View File

@ -0,0 +1,90 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

88
msvc/ReHLDS.sln Normal file
View File

@ -0,0 +1,88 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.30501.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ReHLDS", "..\rehlds\msvc\ReHLDS.vcxproj", "{70A2B904-B7DB-4C48-8DE0-AF567360D572}"
ProjectSection(ProjectDependencies) = postProject
{792DF067-9904-4579-99B9-46C17277ADE3} = {792DF067-9904-4579-99B9-46C17277ADE3}
{CEB94F7C-E459-4673-AABB-36E2074396C0} = {CEB94F7C-E459-4673-AABB-36E2074396C0}
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cppunitlite", "..\dep\cppunitlite\msvc\cppunitlite.vcxproj", "{CEB94F7C-E459-4673-AABB-36E2074396C0}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "bzip2", "..\dep\bzip2\msvc\bzip2.vcxproj", "{792DF067-9904-4579-99B9-46C17277ADE3}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "gradle", "gradle", "{FFC337A9-D58C-4D62-B8BB-A54DD4E4DF41}"
ProjectSection(SolutionItems) = preProject
..\build.gradle = ..\build.gradle
..\gradle.properties = ..\gradle.properties
..\settings.gradle = ..\settings.gradle
..\shared.gradle = ..\shared.gradle
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug Play|Win32 = Debug Play|Win32
Debug Record|Win32 = Debug Record|Win32
Debug Swds Play|Win32 = Debug Swds Play|Win32
Debug Swds|Win32 = Debug Swds|Win32
Debug|Win32 = Debug|Win32
Release Play|Win32 = Release Play|Win32
Release|Win32 = Release|Win32
Tests|Win32 = Tests|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{70A2B904-B7DB-4C48-8DE0-AF567360D572}.Debug Play|Win32.ActiveCfg = Debug Play|Win32
{70A2B904-B7DB-4C48-8DE0-AF567360D572}.Debug Play|Win32.Build.0 = Debug Play|Win32
{70A2B904-B7DB-4C48-8DE0-AF567360D572}.Debug Record|Win32.ActiveCfg = Debug Record|Win32
{70A2B904-B7DB-4C48-8DE0-AF567360D572}.Debug Record|Win32.Build.0 = Debug Record|Win32
{70A2B904-B7DB-4C48-8DE0-AF567360D572}.Debug Swds Play|Win32.ActiveCfg = Debug Swds Play|Win32
{70A2B904-B7DB-4C48-8DE0-AF567360D572}.Debug Swds Play|Win32.Build.0 = Debug Swds Play|Win32
{70A2B904-B7DB-4C48-8DE0-AF567360D572}.Debug Swds|Win32.ActiveCfg = Debug Swds|Win32
{70A2B904-B7DB-4C48-8DE0-AF567360D572}.Debug Swds|Win32.Build.0 = Debug Swds|Win32
{70A2B904-B7DB-4C48-8DE0-AF567360D572}.Debug|Win32.ActiveCfg = Debug|Win32
{70A2B904-B7DB-4C48-8DE0-AF567360D572}.Debug|Win32.Build.0 = Debug|Win32
{70A2B904-B7DB-4C48-8DE0-AF567360D572}.Release Play|Win32.ActiveCfg = Release Play|Win32
{70A2B904-B7DB-4C48-8DE0-AF567360D572}.Release Play|Win32.Build.0 = Release Play|Win32
{70A2B904-B7DB-4C48-8DE0-AF567360D572}.Release|Win32.ActiveCfg = Release|Win32
{70A2B904-B7DB-4C48-8DE0-AF567360D572}.Release|Win32.Build.0 = Release|Win32
{70A2B904-B7DB-4C48-8DE0-AF567360D572}.Tests|Win32.ActiveCfg = Tests|Win32
{70A2B904-B7DB-4C48-8DE0-AF567360D572}.Tests|Win32.Build.0 = Tests|Win32
{CEB94F7C-E459-4673-AABB-36E2074396C0}.Debug Play|Win32.ActiveCfg = Debug|Win32
{CEB94F7C-E459-4673-AABB-36E2074396C0}.Debug Play|Win32.Build.0 = Debug|Win32
{CEB94F7C-E459-4673-AABB-36E2074396C0}.Debug Record|Win32.ActiveCfg = Debug|Win32
{CEB94F7C-E459-4673-AABB-36E2074396C0}.Debug Record|Win32.Build.0 = Debug|Win32
{CEB94F7C-E459-4673-AABB-36E2074396C0}.Debug Swds Play|Win32.ActiveCfg = Debug|Win32
{CEB94F7C-E459-4673-AABB-36E2074396C0}.Debug Swds Play|Win32.Build.0 = Debug|Win32
{CEB94F7C-E459-4673-AABB-36E2074396C0}.Debug Swds|Win32.ActiveCfg = Debug|Win32
{CEB94F7C-E459-4673-AABB-36E2074396C0}.Debug Swds|Win32.Build.0 = Debug|Win32
{CEB94F7C-E459-4673-AABB-36E2074396C0}.Debug|Win32.ActiveCfg = Debug|Win32
{CEB94F7C-E459-4673-AABB-36E2074396C0}.Debug|Win32.Build.0 = Debug|Win32
{CEB94F7C-E459-4673-AABB-36E2074396C0}.Release Play|Win32.ActiveCfg = Release|Win32
{CEB94F7C-E459-4673-AABB-36E2074396C0}.Release Play|Win32.Build.0 = Release|Win32
{CEB94F7C-E459-4673-AABB-36E2074396C0}.Release|Win32.ActiveCfg = Release|Win32
{CEB94F7C-E459-4673-AABB-36E2074396C0}.Release|Win32.Build.0 = Release|Win32
{CEB94F7C-E459-4673-AABB-36E2074396C0}.Tests|Win32.ActiveCfg = Debug|Win32
{CEB94F7C-E459-4673-AABB-36E2074396C0}.Tests|Win32.Build.0 = Debug|Win32
{792DF067-9904-4579-99B9-46C17277ADE3}.Debug Play|Win32.ActiveCfg = Debug|Win32
{792DF067-9904-4579-99B9-46C17277ADE3}.Debug Play|Win32.Build.0 = Debug|Win32
{792DF067-9904-4579-99B9-46C17277ADE3}.Debug Record|Win32.ActiveCfg = Debug|Win32
{792DF067-9904-4579-99B9-46C17277ADE3}.Debug Record|Win32.Build.0 = Debug|Win32
{792DF067-9904-4579-99B9-46C17277ADE3}.Debug Swds Play|Win32.ActiveCfg = Debug|Win32
{792DF067-9904-4579-99B9-46C17277ADE3}.Debug Swds Play|Win32.Build.0 = Debug|Win32
{792DF067-9904-4579-99B9-46C17277ADE3}.Debug Swds|Win32.ActiveCfg = Debug|Win32
{792DF067-9904-4579-99B9-46C17277ADE3}.Debug Swds|Win32.Build.0 = Debug|Win32
{792DF067-9904-4579-99B9-46C17277ADE3}.Debug|Win32.ActiveCfg = Debug|Win32
{792DF067-9904-4579-99B9-46C17277ADE3}.Debug|Win32.Build.0 = Debug|Win32
{792DF067-9904-4579-99B9-46C17277ADE3}.Release Play|Win32.ActiveCfg = Release|Win32
{792DF067-9904-4579-99B9-46C17277ADE3}.Release Play|Win32.Build.0 = Release|Win32
{792DF067-9904-4579-99B9-46C17277ADE3}.Release|Win32.ActiveCfg = Release|Win32
{792DF067-9904-4579-99B9-46C17277ADE3}.Release|Win32.Build.0 = Release|Win32
{792DF067-9904-4579-99B9-46C17277ADE3}.Tests|Win32.ActiveCfg = Debug|Win32
{792DF067-9904-4579-99B9-46C17277ADE3}.Tests|Win32.Build.0 = Debug|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

132
publish.gradle Normal file
View File

@ -0,0 +1,132 @@
import org.doomedsociety.gradlecpp.GradleCppUtils
import org.apache.commons.io.FilenameUtils
void _copyFileToDir(String from, String to) {
def dst = new File(project.file(to), FilenameUtils.getName(from))
GradleCppUtils.copyFile(project.file(from), dst, false)
}
void _copyFile(String from, String to) {
GradleCppUtils.copyFile(project.file(from), project.file(to), false)
}
task publishPrepareFiles << {
def pubRootDir = project.file('publish/publishRoot')
if (pubRootDir.exists()) {
if (!pubRootDir.deleteDir()) {
throw new RuntimeException("Failed to delete ${pubRootDir}")
}
}
pubRootDir.mkdirs()
//bugfixed binaries
project.file('publish/publishRoot/bin/bugfixed').mkdirs()
_copyFileToDir('publish/releaseRehldsFixes/swds.dll', 'publish/publishRoot/bin/bugfixed/')
_copyFileToDir('publish/releaseRehldsFixes/swds.pdb', 'publish/publishRoot/bin/bugfixed/')
_copyFile('publish/releaseRehldsFixes/libengine_i486.so', 'publish/publishRoot/bin/bugfixed/engine_i486.so')
//pure binaries
project.file('publish/publishRoot/bin/pure').mkdirs()
_copyFileToDir('publish/releaseRehldsNofixes/swds.dll', 'publish/publishRoot/bin/pure/')
_copyFileToDir('publish/releaseRehldsNofixes/swds.pdb', 'publish/publishRoot/bin/pure/')
_copyFile('publish/releaseRehldsNofixes/libengine_i486.so', 'publish/publishRoot/bin/pure/engine_i486.so')
//hlsdk
project.file('publish/publishRoot/hlsdk').mkdirs()
copy {
from 'rehlds/common'
into 'publish/publishRoot/hlsdk/common'
}
copy {
from 'rehlds/dlls'
into 'publish/publishRoot/hlsdk/dlls'
}
copy {
from 'rehlds/pm_shared'
into 'publish/publishRoot/hlsdk/pm_shared'
}
copy {
from 'rehlds/public'
into 'publish/publishRoot/hlsdk/public'
include 'interface.h', 'interface.cpp'
}
copy {
from 'rehlds/public/rehlds'
into 'publish/publishRoot/hlsdk/engine'
}
}
task publishPackage(type: Zip, dependsOn: 'publishPrepareFiles') {
baseName = "rehlds-dist-${project.version}"
destinationDir file('publish')
from 'publish/publishRoot'
}
publishing {
publications {
maven(MavenPublication) {
version project.version
artifact publishPackage
pom.withXml {
asNode().children().last() + {
resolveStrategy = DELEGATE_FIRST
name project.name
description project.description
//url github
//scm {
// url "${github}.git"
// connection "scm:git:${github}.git"
//}
/*
licenses {
license {
name 'The Apache Software License, Version 2.0'
url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
distribution 'repo'
}
}
developers {
developer {
id 'dreamstalker'
name 'dreamstalker'
}
}
*/
}
}
}
}
}
Properties repoCreds = new Properties()
if (file('repo_creds.properties').exists()) {
println 'Loading maven repo credentials'
file('repo_creds.properties').withReader('UTF-8', { Reader r ->
repoCreds.load(r)
})
}
publishing {
repositories {
maven {
if (project.version.contains('SNAPSHOT')) {
url "http://nexus.rehlds.org/nexus/content/repositories/rehlds-snapshots/"
} else {
url "http://nexus.rehlds.org/nexus/content/repositories/rehlds-releases/"
}
credentials {
username repoCreds.getProperty('username')
password repoCreds.getProperty('password')
}
}
}
}
task doPublish {
dependsOn 'publishPackage'
if (repoCreds.getProperty('username') && repoCreds.getProperty('password')) {
dependsOn 'publish'
}
}

382
rehlds/build.gradle Normal file
View File

@ -0,0 +1,382 @@
import gradlecpp.RehldsPlayTestPlugin
import gradlecpp.RehldsPlayTestTask
import gradlecpp.VelocityUtils
import org.doomedsociety.gradlecpp.GradleCppUtils
import org.doomedsociety.gradlecpp.LazyNativeDepSet
import org.doomedsociety.gradlecpp.cfg.ToolchainConfig
import org.doomedsociety.gradlecpp.cfg.ToolchainConfigUtils
import org.doomedsociety.gradlecpp.gcc.GccToolchainConfig
import org.doomedsociety.gradlecpp.msvc.EnhancedInstructionsSet
import org.doomedsociety.gradlecpp.msvc.FloatingPointModel
import org.doomedsociety.gradlecpp.msvc.MsvcToolchainConfig
import org.doomedsociety.gradlecpp.toolchain.icc.Icc
import org.doomedsociety.gradlecpp.toolchain.icc.IccCompilerPlugin
import org.gradle.language.cpp.CppSourceSet
import org.gradle.nativeplatform.NativeBinarySpec
import org.gradle.nativeplatform.NativeExecutableSpec
import org.gradle.nativeplatform.NativeLibrarySpec
import org.gradle.nativeplatform.SharedLibraryBinarySpec
import rehlds.testdemo.RehldsDemoRunner
import versioning.RehldsVersionInfo
import org.apache.commons.io.FilenameUtils
apply plugin: 'cpp'
apply plugin: IccCompilerPlugin
apply plugin: RehldsPlayTestPlugin
apply plugin: gradlecpp.CppUnitTestPlugin
repositories {
maven {
url 'http://nexus.rehlds.org/nexus/content/repositories/rehlds-releases/'
}
}
configurations {
rehlds_tests
}
dependencies {
rehlds_tests 'rehlds.testdemos:hl-phys-single1:1.1'
rehlds_tests 'rehlds.testdemos:crossfire-1-multiplayer-1:1.1'
rehlds_tests 'rehlds.testdemos:cstrike-muliplayer-1:1.1'
rehlds_tests 'rehlds.testdemos:shooting-hl-1:1.1'
}
project.ext.dep_bzip2 = project(':dep/bzip2')
project.ext.dep_cppunitlite = project(':dep/cppunitlite')
void createIntergrationTestTask(NativeBinarySpec b) {
boolean rehldsFixes = b.flavor.name.contains('rehldsFixes')
if (!(b instanceof SharedLibraryBinarySpec)) return
if (!GradleCppUtils.windows) return
if (rehldsFixes) return
def libLinkTask = GradleCppUtils.getLinkTask(b)
String unitTestTask = b.hasProperty('cppUnitTestTask') ? b.cppUnitTestTask : null
def depFiles = []
depFiles.addAll(libLinkTask.outputs.files.files)
def demoItgTestTask = project.tasks.create(b.namingScheme.getTaskName('demoItgTest'), RehldsPlayTestTask)
demoItgTestTask.with {
rehldsImageRoot = new File(project.projectDir, '_rehldsTestImg')
rehldsTestLogs = new File(this.project.buildDir, "_rehldsTestLogs/${b.name}")
testDemos = project.configurations.rehlds_tests
testFor = b
//inputs/outputs for up-to-date check
inputs.files depFiles
inputs.files testDemos.files
outputs.dir rehldsTestLogs
//dependencies on library and test executable
dependsOn libLinkTask
if (unitTestTask) {
dependsOn unitTestTask
}
postExtractAction {
def binaryOutFile = GradleCppUtils.getBinaryOutputFile(b)
GradleCppUtils.copyFile(binaryOutFile, new File(rehldsImageRoot, binaryOutFile.name), true)
}
}
b.buildTask.dependsOn demoItgTestTask
}
void setupUnitTests(NativeBinarySpec bin) {
boolean unitTestExecutable = bin.component.name.endsWith('_tests')
if (!unitTestExecutable) return
GradleCppUtils.getLinkTask(bin).doLast {
String srcPath = '' + projectDir + (GradleCppUtils.windows ? '/lib/steam_api.dll' : '/lib/linux32/libsteam_api.so')
String dstPath = bin.executableFile.parent + (GradleCppUtils.windows ? '/steam_api.dll' : '/libsteam_api.so')
GradleCppUtils.copyFile(srcPath, dstPath, true)
}
}
void postEvaluate(NativeBinarySpec b) {
// attach generateAppVersion task to all 'compile source' tasks
GradleCppUtils.getCompileTasks(b).each { Task t ->
t.dependsOn project.generateAppVersion
}
setupUnitTests(b)
createIntergrationTestTask(b)
}
void setupToolchain(NativeBinarySpec b) {
boolean unitTestExecutable = b.component.name.endsWith('_tests')
boolean swdsLib = b.name.toLowerCase().contains('swds')
boolean rehldsFixes = b.flavor.name.contains('rehldsFixes')
ToolchainConfig cfg = rootProject.createToolchainConfig(b)
cfg.projectInclude(project, '', '/public/rehlds', '/engine', '/common', '/pm_shared', '/rehlds', '/testsuite', '/hookers', '/public')
cfg.projectInclude(dep_bzip2, '/include')
if (unitTestExecutable) {
cfg.projectInclude(dep_cppunitlite, '/include')
b.lib LazyNativeDepSet.create(dep_cppunitlite, 'cppunitlite', b.buildType.name, true)
}
b.lib LazyNativeDepSet.create(dep_bzip2, 'bzip2', b.buildType.name, true)
cfg.singleDefines 'USE_BREAKPAD_HANDLER', 'DEDICATED', 'SWDS', 'REHLDS_SELF'
if (cfg instanceof MsvcToolchainConfig) {
cfg.compilerOptions.pchConfig = new MsvcToolchainConfig.PrecompiledHeadersConfig(
enabled: true,
pchHeader: 'precompiled.h',
pchSourceSet: 'rehlds_pch'
)
cfg.singleDefines('_CRT_SECURE_NO_WARNINGS')
if (!rehldsFixes) {
cfg.compilerOptions.floatingPointModel = FloatingPointModel.PRECISE
cfg.compilerOptions.enhancedInstructionsSet = EnhancedInstructionsSet.DISABLED
}
if (swdsLib) {
cfg.linkerOptions.randomizedBaseAddress = false
cfg.linkerOptions.baseAddress = '0x4970000'
}
cfg.projectLibpath(project, '/lib')
cfg.extraLibs 'steam_api.lib', 'psapi.lib', 'ws2_32.lib', 'kernel32.lib', 'user32.lib', 'advapi32.lib'
} else if (cfg instanceof GccToolchainConfig) {
cfg.compilerOptions.pchConfig = new GccToolchainConfig.PrecompilerHeaderOptions(
enabled: true,
pchSourceSet: 'rehlds_pch'
)
cfg.compilerOptions.languageStandard = 'c++0x'
cfg.defines([
'_stricmp': 'strcasecmp',
'_strnicmp': 'strncasecmp',
'_strdup': 'strdup',
'_unlink': 'unlink',
'_vsnprintf': 'vsnprintf',
])
cfg.compilerOptions.args '-Qoption,cpp,--treat_func_as_string_literal_cpp'
cfg.projectLibpath(project, '/lib/linux32')
cfg.extraLibs 'dl', 'm', 'stdc++', 'steam_api'
}
if (!unitTestExecutable && !swdsLib) {
cfg.singleDefines 'HOOK_ENGINE'
}
if (rehldsFixes) {
cfg.singleDefines 'REHLDS_FIXES', 'REHLDS_CHECKS'
}
ToolchainConfigUtils.apply(project, cfg, b)
GradleCppUtils.onTasksCreated(project, 'postEvaluate', {
postEvaluate(b)
})
}
class RehldsSrc {
static void rehlds_src(def h) {
h.rehlds_src(CppSourceSet) {
source {
srcDirs "engine", "rehlds", "public", "version"
if (GradleCppUtils.windows) srcDirs "testsuite"
include "**/*.cpp"
exclude "precompiled.cpp"
exclude GradleCppUtils.windows ? "tier0/platform_linux.cpp" : "tier0/platform_win32.cpp"
}
source {
srcDirs "hookers"
include "**/*.cpp"
exclude "6132_hooker.cpp", "hooker.cpp", "main.cpp", "main_swds.cpp"
if (!GradleCppUtils.windows) exclude "rehlds_debug.cpp"
}
}
}
static void rehlds_pch(def h) {
h.rehlds_pch(CppSourceSet) {
source {
srcDirs "rehlds"
include "precompiled.cpp"
}
}
}
static void rehlds_hooker_src(def h) {
h.rehlds_hooker_src(CppSourceSet) {
source {
srcDirs "hookers"
include "6132_hooker.cpp", "hooker.cpp"
}
}
}
static void rehlds_hooker_main_src(def h) {
h.rehlds_hooker_main_src(CppSourceSet) {
source {
srcDirs "hookers"
include "main.cpp"
}
}
}
static void rehlds_swds_main_src(def h) {
h.rehlds_swds_main_src(CppSourceSet) {
source {
srcDirs "hookers"
include "main_swds.cpp"
}
}
}
static void rehlds_tests_src(def h) {
h.rehlds_tests_src(CppSourceSet) {
source {
srcDir "unittests"
include "**/*.cpp"
}
}
}
}
model {
buildTypes {
debug
release
}
platforms {
x86 {
architecture "x86"
}
}
toolChains {
visualCpp(VisualCpp) {
}
icc(Icc) {
}
}
flavors {
rehldsNofixes
rehldsFixes
}
components {
rehlds_hooker_engine(NativeLibrarySpec) {
targetPlatform 'x86'
baseName 'FileSystem_Stdio'
sources {
RehldsSrc.rehlds_pch(it)
RehldsSrc.rehlds_src(it)
RehldsSrc.rehlds_hooker_src(it)
RehldsSrc.rehlds_hooker_main_src(it)
}
binaries.all { NativeBinarySpec b -> project.setupToolchain(b) }
}
rehlds_swds_engine(NativeLibrarySpec) {
targetPlatform 'x86'
baseName GradleCppUtils.windows ? 'swds' : 'engine_i486'
sources {
RehldsSrc.rehlds_pch(it)
RehldsSrc.rehlds_src(it)
RehldsSrc.rehlds_swds_main_src(it)
}
binaries.all { NativeBinarySpec b -> project.setupToolchain(b) }
}
rehlds_hooker_engine_tests(NativeExecutableSpec) {
targetPlatform 'x86'
sources {
RehldsSrc.rehlds_pch(it)
RehldsSrc.rehlds_src(it)
RehldsSrc.rehlds_tests_src(it)
}
binaries.all { NativeBinarySpec b -> project.setupToolchain(b) }
}
rehlds_swds_engine_tests(NativeExecutableSpec) {
targetPlatform 'x86'
sources {
RehldsSrc.rehlds_pch(it)
RehldsSrc.rehlds_src(it)
RehldsSrc.rehlds_tests_src(it)
}
binaries.all { NativeBinarySpec b -> project.setupToolchain(b) }
}
}
}
task buildRelease {
dependsOn binaries.withType(SharedLibraryBinarySpec).matching { SharedLibraryBinarySpec blib ->
blib.buildable && blib.buildType.name == 'release'
}
}
task prepareDevEnvTests {
def rehldsTests = new File(project.projectDir, '_dev/testDemos')
inputs.files configurations.rehlds_tests.files
outputs.dir rehldsTests
doLast {
rehldsTests.mkdirs()
configurations.rehlds_tests.files.each { File f ->
def t = zipTree(f)
copy {
into new File(rehldsTests, FilenameUtils.getBaseName(f.absolutePath))
from t
}
}
}
}
task prepareDevEnvEngine << {
['_dev/rehlds', '_dev/rehlds_swds'].each { engineDir ->
def rehldsImage = new File(project.projectDir, engineDir)
rehldsImage.mkdirs()
def demoRunner = new RehldsDemoRunner(project.configurations.rehlds_playtest_image.getFiles(), rehldsImage, null)
demoRunner.prepareEngine()
}
}
task prepareDevEnv {
dependsOn prepareDevEnvEngine, prepareDevEnvTests
}
task clean << {
project.file('version/appversion.h').delete()
}
task generateAppVersion {
RehldsVersionInfo verInfo = (RehldsVersionInfo) rootProject.rehldsVersionInfo
def tplFile = project.file('version/appversion.vm')
def renderedFile = project.file('version/appversion.h')
inputs.file tplFile
inputs.file project.file('gradle.properties')
outputs.file renderedFile
inputs.property('version', verInfo.asMavenVersion())
inputs.property('lastCommitDate', verInfo.lastCommitDate.toString())
doLast {
def templateCtx = [
verInfo : verInfo
]
def content = VelocityUtils.renderTemplate(tplFile, templateCtx)
renderedFile.delete()
renderedFile.write(content, 'utf-8')
}
}

View File

@ -0,0 +1,13 @@
#pragma once
#include "maintypes.h"
#include "interface.h"
class IGameServerData : public IBaseInterface {
public:
virtual ~IGameServerData() { };
virtual void WriteDataRequest(const void *buffer, int bufferSize) = 0;
virtual int ReadDataResponse(void *data, int len) = 0;
};

201
rehlds/common/Sequence.h Normal file
View File

@ -0,0 +1,201 @@
//---------------------------------------------------------------------------
//
// S c r i p t e d S e q u e n c e s
//
//---------------------------------------------------------------------------
#ifndef _INCLUDE_SEQUENCE_H_
#define _INCLUDE_SEQUENCE_H_
#ifndef _DEF_BYTE_
typedef unsigned char byte;
#endif
//---------------------------------------------------------------------------
// client_textmessage_t
//---------------------------------------------------------------------------
typedef struct client_textmessage_s
{
int effect;
byte r1, g1, b1, a1; // 2 colors for effects
byte r2, g2, b2, a2;
float x;
float y;
float fadein;
float fadeout;
float holdtime;
float fxtime;
const char *pName;
const char *pMessage;
} client_textmessage_t;
//--------------------------------------------------------------------------
// sequenceDefaultBits_e
//
// Enumerated list of possible modifiers for a command. This enumeration
// is used in a bitarray controlling what modifiers are specified for a command.
//---------------------------------------------------------------------------
enum sequenceModifierBits
{
SEQUENCE_MODIFIER_EFFECT_BIT = (1 << 1),
SEQUENCE_MODIFIER_POSITION_BIT = (1 << 2),
SEQUENCE_MODIFIER_COLOR_BIT = (1 << 3),
SEQUENCE_MODIFIER_COLOR2_BIT = (1 << 4),
SEQUENCE_MODIFIER_FADEIN_BIT = (1 << 5),
SEQUENCE_MODIFIER_FADEOUT_BIT = (1 << 6),
SEQUENCE_MODIFIER_HOLDTIME_BIT = (1 << 7),
SEQUENCE_MODIFIER_FXTIME_BIT = (1 << 8),
SEQUENCE_MODIFIER_SPEAKER_BIT = (1 << 9),
SEQUENCE_MODIFIER_LISTENER_BIT = (1 << 10),
SEQUENCE_MODIFIER_TEXTCHANNEL_BIT = (1 << 11),
};
typedef enum sequenceModifierBits sequenceModifierBits_e ;
//---------------------------------------------------------------------------
// sequenceCommandEnum_e
//
// Enumerated sequence command types.
//---------------------------------------------------------------------------
enum sequenceCommandEnum_
{
SEQUENCE_COMMAND_ERROR = -1,
SEQUENCE_COMMAND_PAUSE = 0,
SEQUENCE_COMMAND_FIRETARGETS,
SEQUENCE_COMMAND_KILLTARGETS,
SEQUENCE_COMMAND_TEXT,
SEQUENCE_COMMAND_SOUND,
SEQUENCE_COMMAND_GOSUB,
SEQUENCE_COMMAND_SENTENCE,
SEQUENCE_COMMAND_REPEAT,
SEQUENCE_COMMAND_SETDEFAULTS,
SEQUENCE_COMMAND_MODIFIER,
SEQUENCE_COMMAND_POSTMODIFIER,
SEQUENCE_COMMAND_NOOP,
SEQUENCE_MODIFIER_EFFECT,
SEQUENCE_MODIFIER_POSITION,
SEQUENCE_MODIFIER_COLOR,
SEQUENCE_MODIFIER_COLOR2,
SEQUENCE_MODIFIER_FADEIN,
SEQUENCE_MODIFIER_FADEOUT,
SEQUENCE_MODIFIER_HOLDTIME,
SEQUENCE_MODIFIER_FXTIME,
SEQUENCE_MODIFIER_SPEAKER,
SEQUENCE_MODIFIER_LISTENER,
SEQUENCE_MODIFIER_TEXTCHANNEL,
};
typedef enum sequenceCommandEnum_ sequenceCommandEnum_e;
//---------------------------------------------------------------------------
// sequenceCommandType_e
//
// Typeerated sequence command types.
//---------------------------------------------------------------------------
enum sequenceCommandType_
{
SEQUENCE_TYPE_COMMAND,
SEQUENCE_TYPE_MODIFIER,
};
typedef enum sequenceCommandType_ sequenceCommandType_e;
//---------------------------------------------------------------------------
// sequenceCommandMapping_s
//
// A mapping of a command enumerated-value to its name.
//---------------------------------------------------------------------------
typedef struct sequenceCommandMapping_ sequenceCommandMapping_s;
struct sequenceCommandMapping_
{
sequenceCommandEnum_e commandEnum;
const char* commandName;
sequenceCommandType_e commandType;
};
//---------------------------------------------------------------------------
// sequenceCommandLine_s
//
// Structure representing a single command (usually 1 line) from a
// .SEQ file entry.
//---------------------------------------------------------------------------
typedef struct sequenceCommandLine_ sequenceCommandLine_s;
struct sequenceCommandLine_
{
int commandType; // Specifies the type of command
client_textmessage_t clientMessage; // Text HUD message struct
char* speakerName; // Targetname of speaking entity
char* listenerName; // Targetname of entity being spoken to
char* soundFileName; // Name of sound file to play
char* sentenceName; // Name of sentences.txt to play
char* fireTargetNames; // List of targetnames to fire
char* killTargetNames; // List of targetnames to remove
float delay; // Seconds 'till next command
int repeatCount; // If nonzero, reset execution pointer to top of block (N times, -1 = infinite)
int textChannel; // Display channel on which text message is sent
int modifierBitField; // Bit field to specify what clientmessage fields are valid
sequenceCommandLine_s* nextCommandLine; // Next command (linked list)
};
//---------------------------------------------------------------------------
// sequenceEntry_s
//
// Structure representing a single command (usually 1 line) from a
// .SEQ file entry.
//---------------------------------------------------------------------------
typedef struct sequenceEntry_ sequenceEntry_s;
struct sequenceEntry_
{
char* fileName; // Name of sequence file without .SEQ extension
char* entryName; // Name of entry label in file
sequenceCommandLine_s* firstCommand; // Linked list of commands in entry
sequenceEntry_s* nextEntry; // Next loaded entry
qboolean isGlobal; // Is entry retained over level transitions?
};
//---------------------------------------------------------------------------
// sentenceEntry_s
// Structure representing a single sentence of a group from a .SEQ
// file entry. Sentences are identical to entries in sentences.txt, but
// can be unique per level and are loaded/unloaded with the level.
//---------------------------------------------------------------------------
typedef struct sentenceEntry_ sentenceEntry_s;
struct sentenceEntry_
{
char* data; // sentence data (ie "We have hostiles" )
sentenceEntry_s* nextEntry; // Next loaded entry
qboolean isGlobal; // Is entry retained over level transitions?
unsigned int index; // this entry's position in the file.
};
//--------------------------------------------------------------------------
// sentenceGroupEntry_s
// Structure representing a group of sentences found in a .SEQ file.
// A sentence group is defined by all sentences with the same name, ignoring
// the number at the end of the sentence name. Groups enable a sentence
// to be picked at random across a group.
//--------------------------------------------------------------------------
typedef struct sentenceGroupEntry_ sentenceGroupEntry_s;
struct sentenceGroupEntry_
{
char* groupName; // name of the group (ie CT_ALERT )
unsigned int numSentences; // number of sentences in group
sentenceEntry_s* firstSentence; // head of linked list of sentences in group
sentenceGroupEntry_s* nextEntry; // next loaded group
};
//---------------------------------------------------------------------------
// Function declarations
//---------------------------------------------------------------------------
sequenceEntry_s* SequenceGet( const char* fileName, const char* entryName );
void Sequence_ParseFile( const char* fileName, qboolean isGlobal );
void Sequence_OnLevelLoad( const char* mapName );
sentenceEntry_s* SequencePickSentence( const char *groupName, int pickMethod, int *picked );
#endif // _INCLUDE_SEQUENCE_H_

703
rehlds/common/SteamCommon.h Normal file
View File

@ -0,0 +1,703 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
/*
** The copyright to the contents herein is the property of Valve Corporation.
** The contents may be used and/or copied only with the written permission of
** Valve, or in accordance with the terms and conditions stipulated in
** the agreement/contract under which the contents have been supplied.
**
*******************************************************************************
**
** Contents:
**
** Common types used in the Steam DLL interface.
**
** This file is distributed to Steam application developers.
**
**
**
*******************************************************************************/
#ifndef INCLUDED_STEAM_COMMON_STEAMCOMMON_H
#define INCLUDED_STEAM_COMMON_STEAMCOMMON_H
#if defined(_MSC_VER) && (_MSC_VER > 1000)
#pragma once
#endif
#ifdef __cplusplus
extern "C"
{
#endif
/* Applications should not define STEAM_EXPORTS. */
#if defined ( _WIN32 )
#ifdef STEAM_EXPORTS
#define STEAM_API __declspec(dllexport)
#else
#define STEAM_API __declspec(dllimport)
#endif
#define STEAM_CALL __cdecl
#else
#define STEAM_API /* */
#define STEAM_CALL /* */
#endif
typedef void (STEAM_CALL *KeyValueIteratorCallback_t )(const char *Key, const char *Val, void *pvParam);
/******************************************************************************
**
** Exported macros and constants
**
******************************************************************************/
/* DEPRECATED -- these are ignored now, all API access is granted on SteamStartup */
#define STEAM_USING_FILESYSTEM (0x00000001)
#define STEAM_USING_LOGGING (0x00000002)
#define STEAM_USING_USERID (0x00000004)
#define STEAM_USING_ACCOUNT (0x00000008)
#define STEAM_USING_ALL (0x0000000f)
/* END DEPRECATED */
#define STEAM_MAX_PATH (255)
#define STEAM_QUESTION_MAXLEN (255)
#define STEAM_SALT_SIZE (8)
#define STEAM_PROGRESS_PERCENT_SCALE (0x00001000)
/* These are maximum significant string lengths, excluding nul-terminator. */
#define STEAM_CARD_NUMBER_SIZE (17)
#define STEAM_CARD_HOLDERNAME_SIZE (100)
#define STEAM_CARD_EXPYEAR_SIZE (4)
#define STEAM_CARD_EXPMONTH_SIZE (2)
#define STEAM_CARD_CVV2_SIZE (5)
#define STEAM_BILLING_ADDRESS1_SIZE (128)
#define STEAM_BILLING_ADDRESS2_SIZE (128)
#define STEAM_BILLING_CITY_SIZE (50)
#define STEAM_BILLING_ZIP_SIZE (16)
#define STEAM_BILLING_STATE_SIZE (32)
#define STEAM_BILLING_COUNTRY_SIZE (32)
#define STEAM_BILLING_PHONE_SIZE (20)
#define STEAM_BILLING_EMAIL_ADDRESS_SIZE (100)
#define STEAM_TYPE_OF_PROOF_OF_PURCHASE_SIZE (20)
#define STEAM_PROOF_OF_PURCHASE_TOKEN_SIZE (200)
#define STEAM_EXTERNAL_ACCOUNTNAME_SIZE (100)
#define STEAM_EXTERNAL_ACCOUNTPASSWORD_SIZE (80)
#define STEAM_BILLING_CONFIRMATION_CODE_SIZE (22)
#define STEAM_BILLING_CARD_APPROVAL_CODE_SIZE (100)
#define STEAM_BILLING_TRANS_DATE_SIZE (9) // mm/dd/yy
#define STEAM_BILLING_TRANS_TIME_SIZE (9) // hh:mm:ss
/******************************************************************************
**
** Scalar type and enumerated type definitions.
**
******************************************************************************/
typedef unsigned int SteamHandle_t;
typedef void * SteamUserIDTicketValidationHandle_t;
typedef unsigned int SteamCallHandle_t;
#if defined(_MSC_VER)
typedef unsigned __int64 SteamUnsigned64_t;
#else
typedef unsigned long long SteamUnsigned64_t;
#endif
typedef enum
{
eSteamSeekMethodSet = 0,
eSteamSeekMethodCur = 1,
eSteamSeekMethodEnd = 2
} ESteamSeekMethod;
typedef enum
{
eSteamBufferMethodFBF = 0,
eSteamBufferMethodNBF = 1
} ESteamBufferMethod;
typedef enum
{
eSteamErrorNone = 0,
eSteamErrorUnknown = 1,
eSteamErrorLibraryNotInitialized = 2,
eSteamErrorLibraryAlreadyInitialized = 3,
eSteamErrorConfig = 4,
eSteamErrorContentServerConnect = 5,
eSteamErrorBadHandle = 6,
eSteamErrorHandlesExhausted = 7,
eSteamErrorBadArg = 8,
eSteamErrorNotFound = 9,
eSteamErrorRead = 10,
eSteamErrorEOF = 11,
eSteamErrorSeek = 12,
eSteamErrorCannotWriteNonUserConfigFile = 13,
eSteamErrorCacheOpen = 14,
eSteamErrorCacheRead = 15,
eSteamErrorCacheCorrupted = 16,
eSteamErrorCacheWrite = 17,
eSteamErrorCacheSession = 18,
eSteamErrorCacheInternal = 19,
eSteamErrorCacheBadApp = 20,
eSteamErrorCacheVersion = 21,
eSteamErrorCacheBadFingerPrint = 22,
eSteamErrorNotFinishedProcessing = 23,
eSteamErrorNothingToDo = 24,
eSteamErrorCorruptEncryptedUserIDTicket = 25,
eSteamErrorSocketLibraryNotInitialized = 26,
eSteamErrorFailedToConnectToUserIDTicketValidationServer = 27,
eSteamErrorBadProtocolVersion = 28,
eSteamErrorReplayedUserIDTicketFromClient = 29,
eSteamErrorReceiveResultBufferTooSmall = 30,
eSteamErrorSendFailed = 31,
eSteamErrorReceiveFailed = 32,
eSteamErrorReplayedReplyFromUserIDTicketValidationServer = 33,
eSteamErrorBadSignatureFromUserIDTicketValidationServer = 34,
eSteamErrorValidationStalledSoAborted = 35,
eSteamErrorInvalidUserIDTicket = 36,
eSteamErrorClientLoginRateTooHigh = 37,
eSteamErrorClientWasNeverValidated = 38,
eSteamErrorInternalSendBufferTooSmall = 39,
eSteamErrorInternalReceiveBufferTooSmall = 40,
eSteamErrorUserTicketExpired = 41,
eSteamErrorCDKeyAlreadyInUseOnAnotherClient = 42,
eSteamErrorNotLoggedIn = 101,
eSteamErrorAlreadyExists = 102,
eSteamErrorAlreadySubscribed = 103,
eSteamErrorNotSubscribed = 104,
eSteamErrorAccessDenied = 105,
eSteamErrorFailedToCreateCacheFile = 106,
eSteamErrorCallStalledSoAborted = 107,
eSteamErrorEngineNotRunning = 108,
eSteamErrorEngineConnectionLost = 109,
eSteamErrorLoginFailed = 110,
eSteamErrorAccountPending = 111,
eSteamErrorCacheWasMissingRetry = 112,
eSteamErrorLocalTimeIncorrect = 113,
eSteamErrorCacheNeedsDecryption = 114,
eSteamErrorAccountDisabled = 115,
eSteamErrorCacheNeedsRepair = 116,
eSteamErrorRebootRequired = 117,
eSteamErrorNetwork = 200,
eSteamErrorOffline = 201
} ESteamError;
typedef enum
{
eNoDetailedErrorAvailable,
eStandardCerrno,
eWin32LastError,
eWinSockLastError,
eDetailedPlatformErrorCount
} EDetailedPlatformErrorType;
typedef enum /* Filter elements returned by SteamFind{First,Next} */
{
eSteamFindLocalOnly, /* limit search to local filesystem */
eSteamFindRemoteOnly, /* limit search to remote repository */
eSteamFindAll /* do not limit search (duplicates allowed) */
} ESteamFindFilter;
/******************************************************************************
**
** Exported structure and complex type definitions.
**
******************************************************************************/
typedef struct
{
ESteamError eSteamError;
EDetailedPlatformErrorType eDetailedErrorType;
int nDetailedErrorCode;
char szDesc[STEAM_MAX_PATH];
} TSteamError;
typedef struct
{
int bIsDir; /* If non-zero, element is a directory; if zero, element is a file */
unsigned int uSizeOrCount; /* If element is a file, this contains size of file in bytes */
int bIsLocal; /* If non-zero, reported item is a standalone element on local filesystem */
char cszName[STEAM_MAX_PATH]; /* Base element name (no path) */
long lLastAccessTime; /* Seconds since 1/1/1970 (like time_t) when element was last accessed */
long lLastModificationTime; /* Seconds since 1/1/1970 (like time_t) when element was last modified */
long lCreationTime; /* Seconds since 1/1/1970 (like time_t) when element was created */
} TSteamElemInfo;
typedef struct
{
unsigned int uNumSubscriptions;
unsigned int uMaxNameChars;
unsigned int uMaxApps;
} TSteamSubscriptionStats;
typedef struct
{
unsigned int uNumApps;
unsigned int uMaxNameChars;
unsigned int uMaxInstallDirNameChars;
unsigned int uMaxVersionLabelChars;
unsigned int uMaxLaunchOptions;
unsigned int uMaxLaunchOptionDescChars;
unsigned int uMaxLaunchOptionCmdLineChars;
unsigned int uMaxNumIcons;
unsigned int uMaxIconSize;
unsigned int uMaxDependencies;
} TSteamAppStats;
typedef struct
{
char *szLabel;
unsigned int uMaxLabelChars;
unsigned int uVersionId;
int bIsNotAvailable;
} TSteamAppVersion;
typedef struct
{
char *szDesc;
unsigned int uMaxDescChars;
char *szCmdLine;
unsigned int uMaxCmdLineChars;
unsigned int uIndex;
unsigned int uIconIndex;
int bNoDesktopShortcut;
int bNoStartMenuShortcut;
int bIsLongRunningUnattended;
} TSteamAppLaunchOption;
typedef struct
{
char *szName;
unsigned int uMaxNameChars;
char *szLatestVersionLabel;
unsigned int uMaxLatestVersionLabelChars;
char *szCurrentVersionLabel;
unsigned int uMaxCurrentVersionLabelChars;
char *szInstallDirName;
unsigned int uMaxInstallDirNameChars;
unsigned int uId;
unsigned int uLatestVersionId;
unsigned int uCurrentVersionId;
unsigned int uMinCacheFileSizeMB;
unsigned int uMaxCacheFileSizeMB;
unsigned int uNumLaunchOptions;
unsigned int uNumIcons;
unsigned int uNumVersions;
unsigned int uNumDependencies;
} TSteamApp;
typedef enum
{
eNoCost = 0,
eBillOnceOnly = 1,
eBillMonthly = 2,
eProofOfPrepurchaseOnly = 3,
eGuestPass = 4,
eHardwarePromo = 5,
eNumBillingTypes,
} EBillingType;
typedef struct
{
char *szName;
unsigned int uMaxNameChars;
unsigned int *puAppIds;
unsigned int uMaxAppIds;
unsigned int uId;
unsigned int uNumApps;
EBillingType eBillingType;
unsigned int uCostInCents;
unsigned int uNumDiscounts;
int bIsPreorder;
int bRequiresShippingAddress;
unsigned int uDomesticShippingCostInCents;
unsigned int uInternationalShippingCostInCents;
bool bIsCyberCafeSubscription;
unsigned int uGameCode;
char szGameCodeDesc[STEAM_MAX_PATH];
bool bIsDisabled;
bool bRequiresCD;
unsigned int uTerritoryCode;
bool bIsSteam3Subscription;
} TSteamSubscription;
typedef struct
{
char szName[STEAM_MAX_PATH];
unsigned int uDiscountInCents;
unsigned int uNumQualifiers;
} TSteamSubscriptionDiscount;
typedef struct
{
char szName[STEAM_MAX_PATH];
unsigned int uRequiredSubscription;
int bIsDisqualifier;
} TSteamDiscountQualifier;
typedef struct TSteamProgress
{
int bValid; /* non-zero if call provides progress info */
unsigned int uPercentDone; /* 0 to 100 * STEAM_PROGRESS_PERCENT_SCALE if bValid */
char szProgress[STEAM_MAX_PATH]; /* additional progress info */
} TSteamProgress;
typedef enum
{
eSteamNotifyTicketsWillExpire,
eSteamNotifyAccountInfoChanged,
eSteamNotifyContentDescriptionChanged,
eSteamNotifyPleaseShutdown,
eSteamNotifyNewContentServer,
eSteamNotifySubscriptionStatusChanged,
eSteamNotifyContentServerConnectionLost,
eSteamNotifyCacheLoadingCompleted,
eSteamNotifyCacheNeedsDecryption,
eSteamNotifyCacheNeedsRepair
} ESteamNotificationCallbackEvent;
typedef void(*SteamNotificationCallback_t)(ESteamNotificationCallbackEvent eEvent, unsigned int nData);
typedef char SteamPersonalQuestion_t[ STEAM_QUESTION_MAXLEN + 1 ];
typedef struct
{
unsigned char uchSalt[STEAM_SALT_SIZE];
} SteamSalt_t;
typedef enum
{
eVisa = 1,
eMaster = 2,
eAmericanExpress = 3,
eDiscover = 4,
eDinnersClub = 5,
eJCB = 6
} ESteamPaymentCardType;
typedef struct
{
ESteamPaymentCardType eCardType;
char szCardNumber[ STEAM_CARD_NUMBER_SIZE +1 ];
char szCardHolderName[ STEAM_CARD_HOLDERNAME_SIZE + 1];
char szCardExpYear[ STEAM_CARD_EXPYEAR_SIZE + 1 ];
char szCardExpMonth[ STEAM_CARD_EXPMONTH_SIZE+ 1 ];
char szCardCVV2[ STEAM_CARD_CVV2_SIZE + 1 ];
char szBillingAddress1[ STEAM_BILLING_ADDRESS1_SIZE + 1 ];
char szBillingAddress2[ STEAM_BILLING_ADDRESS2_SIZE + 1 ];
char szBillingCity[ STEAM_BILLING_CITY_SIZE + 1 ];
char szBillingZip[ STEAM_BILLING_ZIP_SIZE + 1 ];
char szBillingState[ STEAM_BILLING_STATE_SIZE + 1 ];
char szBillingCountry[ STEAM_BILLING_COUNTRY_SIZE + 1 ];
char szBillingPhone[ STEAM_BILLING_PHONE_SIZE + 1 ];
char szBillingEmailAddress[ STEAM_BILLING_EMAIL_ADDRESS_SIZE + 1 ];
unsigned int uExpectedCostInCents;
unsigned int uExpectedTaxInCents;
/* If the TSteamSubscription says that shipping info is required, */
/* then the following fields must be filled out. */
/* If szShippingName is empty, then assumes so are the rest. */
char szShippingName[ STEAM_CARD_HOLDERNAME_SIZE + 1];
char szShippingAddress1[ STEAM_BILLING_ADDRESS1_SIZE + 1 ];
char szShippingAddress2[ STEAM_BILLING_ADDRESS2_SIZE + 1 ];
char szShippingCity[ STEAM_BILLING_CITY_SIZE + 1 ];
char szShippingZip[ STEAM_BILLING_ZIP_SIZE + 1 ];
char szShippingState[ STEAM_BILLING_STATE_SIZE + 1 ];
char szShippingCountry[ STEAM_BILLING_COUNTRY_SIZE + 1 ];
char szShippingPhone[ STEAM_BILLING_PHONE_SIZE + 1 ];
unsigned int uExpectedShippingCostInCents;
} TSteamPaymentCardInfo;
typedef struct
{
char szTypeOfProofOfPurchase[ STEAM_TYPE_OF_PROOF_OF_PURCHASE_SIZE + 1 ];
/* A ProofOfPurchase token is not necessarily a nul-terminated string; it may be binary data
(perhaps encrypted). Hence we need a length and an array of bytes. */
unsigned int uLengthOfBinaryProofOfPurchaseToken;
char cBinaryProofOfPurchaseToken[ STEAM_PROOF_OF_PURCHASE_TOKEN_SIZE + 1 ];
} TSteamPrepurchaseInfo;
typedef struct
{
char szAccountName[ STEAM_EXTERNAL_ACCOUNTNAME_SIZE + 1 ];
char szPassword[ STEAM_EXTERNAL_ACCOUNTPASSWORD_SIZE + 1 ];
} TSteamExternalBillingInfo;
typedef enum
{
ePaymentCardInfo = 1,
ePrepurchasedInfo = 2,
eAccountBillingInfo = 3,
eExternalBillingInfo = 4, /* indirect billing via ISP etc (not supported yet) */
ePaymentCardReceipt = 5,
ePrepurchaseReceipt = 6,
eEmptyReceipt = 7
} ESteamSubscriptionBillingInfoType;
typedef struct
{
ESteamSubscriptionBillingInfoType eBillingInfoType;
union {
TSteamPaymentCardInfo PaymentCardInfo;
TSteamPrepurchaseInfo PrepurchaseInfo;
TSteamExternalBillingInfo ExternalBillingInfo;
char bUseAccountBillingInfo;
};
} TSteamSubscriptionBillingInfo;
typedef enum
{
/* Subscribed */
eSteamSubscriptionOK = 0, /* Subscribed */
eSteamSubscriptionPending = 1, /* Awaiting transaction completion */
eSteamSubscriptionPreorder = 2, /* Is currently a pre-order */
eSteamSubscriptionPrepurchaseTransferred = 3, /* hop to this account */
/* Unusbscribed */
eSteamSubscriptionPrepurchaseInvalid = 4, /* Invalid cd-key */
eSteamSubscriptionPrepurchaseRejected = 5, /* hopped out / banned / etc */
eSteamSubscriptionPrepurchaseRevoked = 6, /* hop away from this account */
eSteamSubscriptionPaymentCardDeclined = 7, /* CC txn declined */
eSteamSubscriptionCancelledByUser = 8, /* Cancelled by client */
eSteamSubscriptionCancelledByVendor = 9, /* Cancelled by us */
eSteamSubscriptionPaymentCardUseLimit = 10, /* Card used too many times, potential fraud */
eSteamSubscriptionPaymentCardAlert = 11, /* Got a "pick up card" or the like from bank */
eSteamSubscriptionFailed = 12, /* Other Error in subscription data or transaction failed/lost */
eSteamSubscriptionPaymentCardAVSFailure = 13, /* Card failed Address Verification check */
eSteamSubscriptionPaymentCardInsufficientFunds = 14, /* Card failed due to insufficient funds */
eSteamSubscriptionRestrictedCountry = 15 /* The subscription is not available in the user's country */
} ESteamSubscriptionStatus;
typedef struct
{
ESteamPaymentCardType eCardType;
char szCardLastFourDigits[ 4 + 1 ];
char szCardHolderName[ STEAM_CARD_HOLDERNAME_SIZE + 1];
char szBillingAddress1[ STEAM_BILLING_ADDRESS1_SIZE + 1 ];
char szBillingAddress2[ STEAM_BILLING_ADDRESS2_SIZE + 1 ];
char szBillingCity[ STEAM_BILLING_CITY_SIZE + 1 ];
char szBillingZip[ STEAM_BILLING_ZIP_SIZE + 1 ];
char szBillingState[ STEAM_BILLING_STATE_SIZE + 1 ];
char szBillingCountry[ STEAM_BILLING_COUNTRY_SIZE + 1 ];
// The following are only available after the subscription leaves "pending" status
char szCardApprovalCode[ STEAM_BILLING_CARD_APPROVAL_CODE_SIZE + 1];
char szTransDate[ STEAM_BILLING_TRANS_DATE_SIZE + 1]; /* mm/dd/yy */
char szTransTime[ STEAM_BILLING_TRANS_TIME_SIZE + 1]; /* hh:mm:ss */
unsigned int uPriceWithoutTax;
unsigned int uTaxAmount;
unsigned int uShippingCost;
} TSteamPaymentCardReceiptInfo;
typedef struct
{
char szTypeOfProofOfPurchase[ STEAM_TYPE_OF_PROOF_OF_PURCHASE_SIZE + 1 ];
} TSteamPrepurchaseReceiptInfo;
typedef struct
{
ESteamSubscriptionStatus eStatus;
ESteamSubscriptionStatus ePreviousStatus;
ESteamSubscriptionBillingInfoType eReceiptInfoType;
char szConfirmationCode[ STEAM_BILLING_CONFIRMATION_CODE_SIZE + 1];
union {
TSteamPaymentCardReceiptInfo PaymentCardReceiptInfo;
TSteamPrepurchaseReceiptInfo PrepurchaseReceiptInfo;
};
} TSteamSubscriptionReceipt;
typedef enum
{
ePhysicalBytesReceivedThisSession = 1,
eAppReadyToLaunchStatus = 2,
eAppPreloadStatus = 3,
eAppEntireDepot = 4,
eCacheBytesPresent = 5
} ESteamAppUpdateStatsQueryType;
typedef struct
{
SteamUnsigned64_t uBytesTotal;
SteamUnsigned64_t uBytesPresent;
} TSteamUpdateStats;
typedef enum
{
eSteamUserAdministrator = 0x00000001, /* May subscribe, unsubscribe, etc */
eSteamUserDeveloper = 0x00000002, /* Steam or App developer */
eSteamUserCyberCafe = 0x00000004 /* CyberCafe, school, etc -- UI should ask for password */
/* before allowing logout, unsubscribe, etc */
} ESteamUserTypeFlags;
typedef enum
{
eSteamAccountStatusDefault = 0x00000000,
eSteamAccountStatusEmailVerified = 0x00000001,
/* Note: Mask value 0x2 is reserved for future use. (Some, but not all, public accounts already have this set.) */
eSteamAccountDisabled = 0x00000004
} ESteamAccountStatusBitFields ;
typedef enum
{
eSteamBootstrapperError = -1,
eSteamBootstrapperDontCheckForUpdate = 0,
eSteamBootstrapperCheckForUpdateAndRerun = 7
} ESteamBootStrapperClientAppResult;
typedef enum
{
eSteamOnline = 0,
eSteamOffline = 1,
eSteamNoAuthMode = 2,
eSteamBillingOffline = 3
} eSteamOfflineStatus;
typedef struct
{
int eOfflineNow;
int eOfflineNextSession;
} TSteamOfflineStatus;
typedef struct
{
unsigned int uAppId;
int bIsSystemDefined;
char szMountPath[STEAM_MAX_PATH];
} TSteamAppDependencyInfo;
typedef enum
{
eSteamOpenFileRegular = 0x0,
eSteamOpenFileIgnoreLocal = 0x1,
eSteamOpenFileChecksumReads = 0x2
} ESteamOpenFileFlags;
typedef enum
{
eSteamValveCDKeyValidationServer = 0,
eSteamHalfLifeMasterServer = 1,
eSteamFriendsServer = 2,
eSteamCSERServer = 3,
eSteamHalfLife2MasterServer = 4,
eSteamRDKFMasterServer = 5,
eMaxServerTypes = 6
} ESteamServerType;
/******************************************************************************
**
** More exported constants
**
******************************************************************************/
#ifdef __cplusplus
const SteamHandle_t STEAM_INVALID_HANDLE = 0;
const SteamCallHandle_t STEAM_INVALID_CALL_HANDLE = 0;
const SteamUserIDTicketValidationHandle_t STEAM_INACTIVE_USERIDTICKET_VALIDATION_HANDLE = 0;
const unsigned int STEAM_USE_LATEST_VERSION = 0xFFFFFFFF;
#else
#define STEAM_INVALID_HANDLE ((SteamHandle_t)(0))
#define STEAM_INVALID_CALL_HANDLE ((SteamCallHandle_t)(0))
#define STEAM_INACTIVE_USERIDTICKET_VALIDATION_HANDLE ((SteamUserIDTicketValidationHandle_t)(0))
#define STEAM_USE_LATEST_VERSION (0xFFFFFFFFu);
#endif
/******************************************************************************
** Each Steam instance (licensed Steam Service Provider) has a unique SteamInstanceID_t.
**
** Each Steam instance as its own DB of users.
** Each user in the DB has a unique SteamLocalUserID_t (a serial number, with possible
** rare gaps in the sequence).
**
******************************************************************************/
typedef unsigned short SteamInstanceID_t; // MUST be 16 bits
#if defined ( _WIN32 )
typedef unsigned __int64 SteamLocalUserID_t; // MUST be 64 bits
#else
typedef unsigned long long SteamLocalUserID_t; // MUST be 64 bits
#endif
/******************************************************************************
**
** Applications need to be able to authenticate Steam users from ANY instance.
** So a SteamIDTicket contains SteamGlobalUserID, which is a unique combination of
** instance and user id.
**
** SteamLocalUserID is an unsigned 64-bit integer.
** For platforms without 64-bit int support, we provide access via a union that splits it into
** high and low unsigned 32-bit ints. Such platforms will only need to compare LocalUserIDs
** for equivalence anyway - not perform arithmetic with them.
**
********************************************************************************/
typedef struct
{
unsigned int Low32bits;
unsigned int High32bits;
} TSteamSplitLocalUserID;
typedef struct
{
SteamInstanceID_t m_SteamInstanceID;
union
{
SteamLocalUserID_t As64bits;
TSteamSplitLocalUserID Split;
} m_SteamLocalUserID;
} TSteamGlobalUserID;
#ifdef __cplusplus
}
#endif
#endif

62
rehlds/common/beamdef.h Normal file
View File

@ -0,0 +1,62 @@
/***
*
* Copyright (c) 1996-2002, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#if !defined ( BEAMDEFH )
#define BEAMDEFH
#ifdef _WIN32
#pragma once
#endif
#define FBEAM_STARTENTITY 0x00000001
#define FBEAM_ENDENTITY 0x00000002
#define FBEAM_FADEIN 0x00000004
#define FBEAM_FADEOUT 0x00000008
#define FBEAM_SINENOISE 0x00000010
#define FBEAM_SOLID 0x00000020
#define FBEAM_SHADEIN 0x00000040
#define FBEAM_SHADEOUT 0x00000080
#define FBEAM_STARTVISIBLE 0x10000000 // Has this client actually seen this beam's start entity yet?
#define FBEAM_ENDVISIBLE 0x20000000 // Has this client actually seen this beam's end entity yet?
#define FBEAM_ISACTIVE 0x40000000
#define FBEAM_FOREVER 0x80000000
typedef struct beam_s BEAM;
struct beam_s
{
BEAM *next;
int type;
int flags;
vec3_t source;
vec3_t target;
vec3_t delta;
float t; // 0 .. 1 over lifetime of beam
float freq;
float die;
float width;
float amplitude;
float r, g, b;
float brightness;
float speed;
float frameRate;
float frame;
int segments;
int startEntity;
int endEntity;
int modelIndex;
int frameCount;
struct model_s *pFollowModel;
struct particle_s *particles;
};
#endif

115
rehlds/common/cl_entity.h Normal file
View File

@ -0,0 +1,115 @@
/***
*
* Copyright (c) 1996-2002, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
// cl_entity.h
#if !defined( CL_ENTITYH )
#define CL_ENTITYH
#ifdef _WIN32
#pragma once
#endif
typedef struct efrag_s
{
struct mleaf_s *leaf;
struct efrag_s *leafnext;
struct cl_entity_s *entity;
struct efrag_s *entnext;
} efrag_t;
typedef struct
{
byte mouthopen; // 0 = mouth closed, 255 = mouth agape
byte sndcount; // counter for running average
int sndavg; // running average
} mouth_t;
typedef struct
{
float prevanimtime;
float sequencetime;
byte prevseqblending[2];
vec3_t prevorigin;
vec3_t prevangles;
int prevsequence;
float prevframe;
byte prevcontroller[4];
byte prevblending[2];
} latchedvars_t;
typedef struct
{
// Time stamp for this movement
float animtime;
vec3_t origin;
vec3_t angles;
} position_history_t;
typedef struct cl_entity_s cl_entity_t;
#define HISTORY_MAX 64 // Must be power of 2
#define HISTORY_MASK ( HISTORY_MAX - 1 )
#if !defined( ENTITY_STATEH )
#include "entity_state.h"
#endif
#if !defined( PROGS_H )
#include "progs.h"
#endif
struct cl_entity_s
{
int index; // Index into cl_entities ( should match actual slot, but not necessarily )
qboolean player; // True if this entity is a "player"
entity_state_t baseline; // The original state from which to delta during an uncompressed message
entity_state_t prevstate; // The state information from the penultimate message received from the server
entity_state_t curstate; // The state information from the last message received from server
int current_position; // Last received history update index
position_history_t ph[ HISTORY_MAX ]; // History of position and angle updates for this player
mouth_t mouth; // For synchronizing mouth movements.
latchedvars_t latched; // Variables used by studio model rendering routines
// Information based on interplocation, extrapolation, prediction, or just copied from last msg received.
//
float lastmove;
// Actual render position and angles
vec3_t origin;
vec3_t angles;
// Attachment points
vec3_t attachment[4];
// Other entity local information
int trivial_accept;
struct model_s *model; // cl.model_precache[ curstate.modelindes ]; all visible entities have a model
struct efrag_s *efrag; // linked list of efrags
struct mnode_s *topnode; // for bmodels, first world node that splits bmodel, or NULL if not split
float syncbase; // for client-side animations -- used by obsolete alias animation system, remove?
int visframe; // last frame this entity was found in an active leaf
colorVec cvFloorColor;
};
#endif // !CL_ENTITYH

340
rehlds/common/com_model.h Normal file
View File

@ -0,0 +1,340 @@
//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================
// com_model.h
#pragma once
#define STUDIO_RENDER 1
#define STUDIO_EVENTS 2
//#define MAX_MODEL_NAME 64
//#define MAX_MAP_HULLS 4
//#define MIPLEVELS 4
//#define NUM_AMBIENTS 4 // automatic ambient sounds
//#define MAXLIGHTMAPS 4
#define PLANE_ANYZ 5
#define ALIAS_Z_CLIP_PLANE 5
// flags in finalvert_t.flags
#define ALIAS_LEFT_CLIP 0x0001
#define ALIAS_TOP_CLIP 0x0002
#define ALIAS_RIGHT_CLIP 0x0004
#define ALIAS_BOTTOM_CLIP 0x0008
#define ALIAS_Z_CLIP 0x0010
#define ALIAS_ONSEAM 0x0020
#define ALIAS_XY_CLIP_MASK 0x000F
#define ZISCALE ((float)0x8000)
#define CACHE_SIZE 32 // used to align key data structures
//typedef enum
//{
// mod_brush,
// mod_sprite,
// mod_alias,
// mod_studio
//} modtype_t;
// must match definition in modelgen.h
//#ifndef SYNCTYPE_T
//#define SYNCTYPE_T
//
//typedef enum
//{
// ST_SYNC=0,
// ST_RAND
//} synctype_t;
//
//#endif
//typedef struct
//{
// float mins[3], maxs[3];
// float origin[3];
// int headnode[MAX_MAP_HULLS];
// int visleafs; // not including the solid leaf 0
// int firstface, numfaces;
//} dmodel_t;
// plane_t structure
//typedef struct mplane_s
//{
// vec3_t normal; // surface normal
// float dist; // closest appoach to origin
// byte type; // for texture axis selection and fast side tests
// byte signbits; // signx + signy<<1 + signz<<1
// byte pad[2];
//} mplane_t;
//typedef struct
//{
// vec3_t position;
//} mvertex_t;
//typedef struct
//{
// unsigned short v[2];
// unsigned int cachededgeoffset;
//} medge_t;
//typedef struct texture_s
//{
// char name[16];
// unsigned width, height;
// int anim_total; // total tenths in sequence ( 0 = no)
// int anim_min, anim_max; // time for this frame min <=time< max
// struct texture_s *anim_next; // in the animation sequence
// struct texture_s *alternate_anims; // bmodels in frame 1 use these
// unsigned offsets[MIPLEVELS]; // four mip maps stored
// unsigned paloffset;
//} texture_t;
//typedef struct
//{
// float vecs[2][4]; // [s/t] unit vectors in world space.
// // [i][3] is the s/t offset relative to the origin.
// // s or t = dot(3Dpoint,vecs[i])+vecs[i][3]
// float mipadjust; // ?? mipmap limits for very small surfaces
// texture_t *texture;
// int flags; // sky or slime, no lightmap or 256 subdivision
//} mtexinfo_t;
//typedef struct mnode_s
//{
// // common with leaf
// int contents; // 0, to differentiate from leafs
// int visframe; // node needs to be traversed if current
//
// short minmaxs[6]; // for bounding box culling
//
// struct mnode_s *parent;
//
// // node specific
// mplane_t *plane;
// struct mnode_s *children[2];
//
// unsigned short firstsurface;
// unsigned short numsurfaces;
//} mnode_t;
//typedef struct msurface_s msurface_t;
//typedef struct decal_s decal_t;
// JAY: Compress this as much as possible
//struct decal_s
//{
// decal_t *pnext; // linked list for each surface
// msurface_t *psurface; // Surface id for persistence / unlinking
// short dx; // Offsets into surface texture (in texture coordinates, so we don't need floats)
// short dy;
// short texture; // Decal texture
// byte scale; // Pixel scale
// byte flags; // Decal flags
//
// short entityIndex; // Entity this is attached to
//};
//typedef struct mleaf_s
//{
// // common with node
// int contents; // wil be a negative contents number
// int visframe; // node needs to be traversed if current
//
// short minmaxs[6]; // for bounding box culling
//
// struct mnode_s *parent;
//
// // leaf specific
// byte *compressed_vis;
// struct efrag_s *efrags;
//
// msurface_t **firstmarksurface;
// int nummarksurfaces;
// int key; // BSP sequence number for leaf's contents
// byte ambient_sound_level[NUM_AMBIENTS];
//} mleaf_t;
//struct msurface_s
//{
// int visframe; // should be drawn when node is crossed
//
// int dlightframe; // last frame the surface was checked by an animated light
// int dlightbits; // dynamically generated. Indicates if the surface illumination
// // is modified by an animated light.
//
// mplane_t *plane; // pointer to shared plane
// int flags; // see SURF_ #defines
//
// int firstedge; // look up in model->surfedges[], negative numbers
// int numedges; // are backwards edges
//
// // surface generation data
// struct surfcache_s *cachespots[MIPLEVELS];
//
// short texturemins[2]; // smallest s/t position on the surface.
// short extents[2]; // ?? s/t texture size, 1..256 for all non-sky surfaces
//
// mtexinfo_t *texinfo;
//
// // lighting info
// byte styles[MAXLIGHTMAPS]; // index into d_lightstylevalue[] for animated lights
// // no one surface can be effected by more than 4
// // animated lights.
// color24 *samples;
//
// decal_t *pdecals;
//};
//typedef struct
//{
// int planenum;
// short children[2]; // negative numbers are contents
//} dclipnode_t;
//typedef struct hull_s
//{
// dclipnode_t *clipnodes;
// mplane_t *planes;
// int firstclipnode;
// int lastclipnode;
// vec3_t clip_mins;
// vec3_t clip_maxs;
//} hull_t;
typedef struct cache_user_s
{
void *data;
} cache_user_t;
//typedef struct model_s
//{
// char name[ MAX_MODEL_NAME ];
// qboolean needload; // bmodels and sprites don't cache normally
//
// modtype_t type;
// int numframes;
// synctype_t synctype;
//
// int flags;
//
// //
// // volume occupied by the model
// //
// vec3_t mins, maxs;
// float radius;
//
// //
// // brush model
// //
// int firstmodelsurface, nummodelsurfaces;
//
// int numsubmodels;
// dmodel_t *submodels;
//
// int numplanes;
// mplane_t *planes;
//
// int numleafs; // number of visible leafs, not counting 0
// struct mleaf_s *leafs;
//
// int numvertexes;
// mvertex_t *vertexes;
//
// int numedges;
// medge_t *edges;
//
// int numnodes;
// mnode_t *nodes;
//
// int numtexinfo;
// mtexinfo_t *texinfo;
//
// int numsurfaces;
// msurface_t *surfaces;
//
// int numsurfedges;
// int *surfedges;
//
// int numclipnodes;
// dclipnode_t *clipnodes;
//
// int nummarksurfaces;
// msurface_t **marksurfaces;
//
// hull_t hulls[MAX_MAP_HULLS];
//
// int numtextures;
// texture_t **textures;
//
// byte *visdata;
//
// color24 *lightdata;
//
// char *entities;
//
// //
// // additional model data
// //
// cache_user_t cache; // only access through Mod_Extradata
//
//} model_t;
//typedef vec_t vec4_t[4];
typedef struct alight_s
{
int ambientlight; // clip at 128
int shadelight; // clip at 192 - ambientlight
vec3_t color;
float *plightvec;
} alight_t;
typedef struct auxvert_s
{
float fv[3]; // viewspace x, y
} auxvert_t;
#include "custom.h"
//#define MAX_SCOREBOARDNAME 32
// Defined in client.h differently
//typedef struct player_info_s
//{
// // User id on server
// int userid;
//
// // User info string
// char userinfo[ MAX_INFO_STRING ];
//
// // Name
// char name[ MAX_SCOREBOARDNAME ];
//
// // Spectator or not, unused
// int spectator;
//
// int ping;
// int packet_loss;
//
// // skin information
// char model[MAX_QPATH];
// int topcolor;
// int bottomcolor;
//
// // last frame rendered
// int renderframe;
//
// // Gait frame estimation
// int gaitsequence;
// float gaitframe;
// float gaityaw;
// vec3_t prevgaitorigin;
//
// customization_t customdata;
//} player_info_t;

View File

@ -0,0 +1,38 @@
/***
*
* Copyright (c) 1996-2002, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#if !defined( CON_NPRINTH )
#define CON_NPRINTH
#ifdef _WIN32
#pragma once
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef struct con_nprint_s
{
int index; // Row #
float time_to_live; // # of seconds before it dissappears
float color[ 3 ]; // RGB colors ( 0.0 -> 1.0 scale )
} con_nprint_t;
void Con_NPrintf( int idx, const char *fmt, ... );
void Con_NXPrintf( struct con_nprint_s *info, const char *fmt, ... );
#ifdef __cplusplus
}
#endif
#endif

791
rehlds/common/const.h Normal file
View File

@ -0,0 +1,791 @@
/***
*
* Copyright (c) 1996-2002, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#ifndef CONST_H
#define CONST_H
#ifdef _WIN32
#pragma once
#endif
//
// Constants shared by the engine and dlls
// This header file included by engine files and DLL files.
// Most came from server.h
// edict->flags
#define FL_FLY (1<<0) // Changes the SV_Movestep() behavior to not need to be on ground
#define FL_SWIM (1<<1) // Changes the SV_Movestep() behavior to not need to be on ground (but stay in water)
#define FL_CONVEYOR (1<<2)
#define FL_CLIENT (1<<3)
#define FL_INWATER (1<<4)
#define FL_MONSTER (1<<5)
#define FL_GODMODE (1<<6)
#define FL_NOTARGET (1<<7)
#define FL_SKIPLOCALHOST (1<<8) // Don't send entity to local host, it's predicting this entity itself
#define FL_ONGROUND (1<<9) // At rest / on the ground
#define FL_PARTIALGROUND (1<<10) // not all corners are valid
#define FL_WATERJUMP (1<<11) // player jumping out of water
#define FL_FROZEN (1<<12) // Player is frozen for 3rd person camera
#define FL_FAKECLIENT (1<<13) // JAC: fake client, simulated server side; don't send network messages to them
#define FL_DUCKING (1<<14) // Player flag -- Player is fully crouched
#define FL_FLOAT (1<<15) // Apply floating force to this entity when in water
#define FL_GRAPHED (1<<16) // worldgraph has this ent listed as something that blocks a connection
// UNDONE: Do we need these?
#define FL_IMMUNE_WATER (1<<17)
#define FL_IMMUNE_SLIME (1<<18)
#define FL_IMMUNE_LAVA (1<<19)
#define FL_PROXY (1<<20) // This is a spectator proxy
#define FL_ALWAYSTHINK (1<<21) // Brush model flag -- call think every frame regardless of nextthink - ltime (for constantly changing velocity/path)
#define FL_BASEVELOCITY (1<<22) // Base velocity has been applied this frame (used to convert base velocity into momentum)
#define FL_MONSTERCLIP (1<<23) // Only collide in with monsters who have FL_MONSTERCLIP set
#define FL_ONTRAIN (1<<24) // Player is _controlling_ a train, so movement commands should be ignored on client during prediction.
#define FL_WORLDBRUSH (1<<25) // Not moveable/removeable brush entity (really part of the world, but represented as an entity for transparency or something)
#define FL_SPECTATOR (1<<26) // This client is a spectator, don't run touch functions, etc.
#define FL_CUSTOMENTITY (1<<29) // This is a custom entity
#define FL_KILLME (1<<30) // This entity is marked for death -- This allows the engine to kill ents at the appropriate time
#define FL_DORMANT (1<<31) // Entity is dormant, no updates to client
// Engine edict->spawnflags
#define SF_NOTINDEATHMATCH 0x0800 // Do not spawn when deathmatch and loading entities from a file
// Goes into globalvars_t.trace_flags
#define FTRACE_SIMPLEBOX (1<<0) // Traceline with a simple box
// walkmove modes
#define WALKMOVE_NORMAL 0 // normal walkmove
#define WALKMOVE_WORLDONLY 1 // doesn't hit ANY entities, no matter what the solid type
#define WALKMOVE_CHECKONLY 2 // move, but don't touch triggers
// edict->movetype values
#define MOVETYPE_NONE 0 // never moves
//#define MOVETYPE_ANGLENOCLIP 1
//#define MOVETYPE_ANGLECLIP 2
#define MOVETYPE_WALK 3 // Player only - moving on the ground
#define MOVETYPE_STEP 4 // gravity, special edge handling -- monsters use this
#define MOVETYPE_FLY 5 // No gravity, but still collides with stuff
#define MOVETYPE_TOSS 6 // gravity/collisions
#define MOVETYPE_PUSH 7 // no clip to world, push and crush
#define MOVETYPE_NOCLIP 8 // No gravity, no collisions, still do velocity/avelocity
#define MOVETYPE_FLYMISSILE 9 // extra size to monsters
#define MOVETYPE_BOUNCE 10 // Just like Toss, but reflect velocity when contacting surfaces
#define MOVETYPE_BOUNCEMISSILE 11 // bounce w/o gravity
#define MOVETYPE_FOLLOW 12 // track movement of aiment
#define MOVETYPE_PUSHSTEP 13 // BSP model that needs physics/world collisions (uses nearest hull for world collision)
// edict->solid values
// NOTE: Some movetypes will cause collisions independent of SOLID_NOT/SOLID_TRIGGER when the entity moves
// SOLID only effects OTHER entities colliding with this one when they move - UGH!
#define SOLID_NOT 0 // no interaction with other objects
#define SOLID_TRIGGER 1 // touch on edge, but not blocking
#define SOLID_BBOX 2 // touch on edge, block
#define SOLID_SLIDEBOX 3 // touch on edge, but not an onground
#define SOLID_BSP 4 // bsp clip, touch on edge, block
// edict->deadflag values
#define DEAD_NO 0 // alive
#define DEAD_DYING 1 // playing death animation or still falling off of a ledge waiting to hit ground
#define DEAD_DEAD 2 // dead. lying still.
#define DEAD_RESPAWNABLE 3
#define DEAD_DISCARDBODY 4
#define DAMAGE_NO 0
#define DAMAGE_YES 1
#define DAMAGE_AIM 2
// entity effects
#define EF_BRIGHTFIELD 1 // swirling cloud of particles
#define EF_MUZZLEFLASH 2 // single frame ELIGHT on entity attachment 0
#define EF_BRIGHTLIGHT 4 // DLIGHT centered at entity origin
#define EF_DIMLIGHT 8 // player flashlight
#define EF_INVLIGHT 16 // get lighting from ceiling
#define EF_NOINTERP 32 // don't interpolate the next frame
#define EF_LIGHT 64 // rocket flare glow sprite
#define EF_NODRAW 128 // don't draw entity
#define EF_NIGHTVISION 256 // player nightvision
#define EF_SNIPERLASER 512 // sniper laser effect
#define EF_FIBERCAMERA 1024// fiber camera
// entity flags
#define EFLAG_SLERP 1 // do studio interpolation of this entity
//
// temp entity events
//
#define TE_BEAMPOINTS 0 // beam effect between two points
// coord coord coord (start position)
// coord coord coord (end position)
// short (sprite index)
// byte (starting frame)
// byte (frame rate in 0.1's)
// byte (life in 0.1's)
// byte (line width in 0.1's)
// byte (noise amplitude in 0.01's)
// byte,byte,byte (color)
// byte (brightness)
// byte (scroll speed in 0.1's)
#define TE_BEAMENTPOINT 1 // beam effect between point and entity
// short (start entity)
// coord coord coord (end position)
// short (sprite index)
// byte (starting frame)
// byte (frame rate in 0.1's)
// byte (life in 0.1's)
// byte (line width in 0.1's)
// byte (noise amplitude in 0.01's)
// byte,byte,byte (color)
// byte (brightness)
// byte (scroll speed in 0.1's)
#define TE_GUNSHOT 2 // particle effect plus ricochet sound
// coord coord coord (position)
#define TE_EXPLOSION 3 // additive sprite, 2 dynamic lights, flickering particles, explosion sound, move vertically 8 pps
// coord coord coord (position)
// short (sprite index)
// byte (scale in 0.1's)
// byte (framerate)
// byte (flags)
//
// The Explosion effect has some flags to control performance/aesthetic features:
#define TE_EXPLFLAG_NONE 0 // all flags clear makes default Half-Life explosion
#define TE_EXPLFLAG_NOADDITIVE 1 // sprite will be drawn opaque (ensure that the sprite you send is a non-additive sprite)
#define TE_EXPLFLAG_NODLIGHTS 2 // do not render dynamic lights
#define TE_EXPLFLAG_NOSOUND 4 // do not play client explosion sound
#define TE_EXPLFLAG_NOPARTICLES 8 // do not draw particles
#define TE_TAREXPLOSION 4 // Quake1 "tarbaby" explosion with sound
// coord coord coord (position)
#define TE_SMOKE 5 // alphablend sprite, move vertically 30 pps
// coord coord coord (position)
// short (sprite index)
// byte (scale in 0.1's)
// byte (framerate)
#define TE_TRACER 6 // tracer effect from point to point
// coord, coord, coord (start)
// coord, coord, coord (end)
#define TE_LIGHTNING 7 // TE_BEAMPOINTS with simplified parameters
// coord, coord, coord (start)
// coord, coord, coord (end)
// byte (life in 0.1's)
// byte (width in 0.1's)
// byte (amplitude in 0.01's)
// short (sprite model index)
#define TE_BEAMENTS 8
// short (start entity)
// short (end entity)
// short (sprite index)
// byte (starting frame)
// byte (frame rate in 0.1's)
// byte (life in 0.1's)
// byte (line width in 0.1's)
// byte (noise amplitude in 0.01's)
// byte,byte,byte (color)
// byte (brightness)
// byte (scroll speed in 0.1's)
#define TE_SPARKS 9 // 8 random tracers with gravity, ricochet sprite
// coord coord coord (position)
#define TE_LAVASPLASH 10 // Quake1 lava splash
// coord coord coord (position)
#define TE_TELEPORT 11 // Quake1 teleport splash
// coord coord coord (position)
#define TE_EXPLOSION2 12 // Quake1 colormaped (base palette) particle explosion with sound
// coord coord coord (position)
// byte (starting color)
// byte (num colors)
#define TE_BSPDECAL 13 // Decal from the .BSP file
// coord, coord, coord (x,y,z), decal position (center of texture in world)
// short (texture index of precached decal texture name)
// short (entity index)
// [optional - only included if previous short is non-zero (not the world)] short (index of model of above entity)
#define TE_IMPLOSION 14 // tracers moving toward a point
// coord, coord, coord (position)
// byte (radius)
// byte (count)
// byte (life in 0.1's)
#define TE_SPRITETRAIL 15 // line of moving glow sprites with gravity, fadeout, and collisions
// coord, coord, coord (start)
// coord, coord, coord (end)
// short (sprite index)
// byte (count)
// byte (life in 0.1's)
// byte (scale in 0.1's)
// byte (velocity along vector in 10's)
// byte (randomness of velocity in 10's)
#define TE_BEAM 16 // obsolete
#define TE_SPRITE 17 // additive sprite, plays 1 cycle
// coord, coord, coord (position)
// short (sprite index)
// byte (scale in 0.1's)
// byte (brightness)
#define TE_BEAMSPRITE 18 // A beam with a sprite at the end
// coord, coord, coord (start position)
// coord, coord, coord (end position)
// short (beam sprite index)
// short (end sprite index)
#define TE_BEAMTORUS 19 // screen aligned beam ring, expands to max radius over lifetime
// coord coord coord (center position)
// coord coord coord (axis and radius)
// short (sprite index)
// byte (starting frame)
// byte (frame rate in 0.1's)
// byte (life in 0.1's)
// byte (line width in 0.1's)
// byte (noise amplitude in 0.01's)
// byte,byte,byte (color)
// byte (brightness)
// byte (scroll speed in 0.1's)
#define TE_BEAMDISK 20 // disk that expands to max radius over lifetime
// coord coord coord (center position)
// coord coord coord (axis and radius)
// short (sprite index)
// byte (starting frame)
// byte (frame rate in 0.1's)
// byte (life in 0.1's)
// byte (line width in 0.1's)
// byte (noise amplitude in 0.01's)
// byte,byte,byte (color)
// byte (brightness)
// byte (scroll speed in 0.1's)
#define TE_BEAMCYLINDER 21 // cylinder that expands to max radius over lifetime
// coord coord coord (center position)
// coord coord coord (axis and radius)
// short (sprite index)
// byte (starting frame)
// byte (frame rate in 0.1's)
// byte (life in 0.1's)
// byte (line width in 0.1's)
// byte (noise amplitude in 0.01's)
// byte,byte,byte (color)
// byte (brightness)
// byte (scroll speed in 0.1's)
#define TE_BEAMFOLLOW 22 // create a line of decaying beam segments until entity stops moving
// short (entity:attachment to follow)
// short (sprite index)
// byte (life in 0.1's)
// byte (line width in 0.1's)
// byte,byte,byte (color)
// byte (brightness)
#define TE_GLOWSPRITE 23
// coord, coord, coord (pos) short (model index) byte (scale / 10)
#define TE_BEAMRING 24 // connect a beam ring to two entities
// short (start entity)
// short (end entity)
// short (sprite index)
// byte (starting frame)
// byte (frame rate in 0.1's)
// byte (life in 0.1's)
// byte (line width in 0.1's)
// byte (noise amplitude in 0.01's)
// byte,byte,byte (color)
// byte (brightness)
// byte (scroll speed in 0.1's)
#define TE_STREAK_SPLASH 25 // oriented shower of tracers
// coord coord coord (start position)
// coord coord coord (direction vector)
// byte (color)
// short (count)
// short (base speed)
// short (ramdon velocity)
#define TE_BEAMHOSE 26 // obsolete
#define TE_DLIGHT 27 // dynamic light, effect world, minor entity effect
// coord, coord, coord (pos)
// byte (radius in 10's)
// byte byte byte (color)
// byte (brightness)
// byte (life in 10's)
// byte (decay rate in 10's)
#define TE_ELIGHT 28 // point entity light, no world effect
// short (entity:attachment to follow)
// coord coord coord (initial position)
// coord (radius)
// byte byte byte (color)
// byte (life in 0.1's)
// coord (decay rate)
#define TE_TEXTMESSAGE 29
// short 1.2.13 x (-1 = center)
// short 1.2.13 y (-1 = center)
// byte Effect 0 = fade in/fade out
// 1 is flickery credits
// 2 is write out (training room)
// 4 bytes r,g,b,a color1 (text color)
// 4 bytes r,g,b,a color2 (effect color)
// ushort 8.8 fadein time
// ushort 8.8 fadeout time
// ushort 8.8 hold time
// optional ushort 8.8 fxtime (time the highlight lags behing the leading text in effect 2)
// string text message (512 chars max sz string)
#define TE_LINE 30
// coord, coord, coord startpos
// coord, coord, coord endpos
// short life in 0.1 s
// 3 bytes r, g, b
#define TE_BOX 31
// coord, coord, coord boxmins
// coord, coord, coord boxmaxs
// short life in 0.1 s
// 3 bytes r, g, b
#define TE_KILLBEAM 99 // kill all beams attached to entity
// short (entity)
#define TE_LARGEFUNNEL 100
// coord coord coord (funnel position)
// short (sprite index)
// short (flags)
#define TE_BLOODSTREAM 101 // particle spray
// coord coord coord (start position)
// coord coord coord (spray vector)
// byte (color)
// byte (speed)
#define TE_SHOWLINE 102 // line of particles every 5 units, dies in 30 seconds
// coord coord coord (start position)
// coord coord coord (end position)
#define TE_BLOOD 103 // particle spray
// coord coord coord (start position)
// coord coord coord (spray vector)
// byte (color)
// byte (speed)
#define TE_DECAL 104 // Decal applied to a brush entity (not the world)
// coord, coord, coord (x,y,z), decal position (center of texture in world)
// byte (texture index of precached decal texture name)
// short (entity index)
#define TE_FIZZ 105 // create alpha sprites inside of entity, float upwards
// short (entity)
// short (sprite index)
// byte (density)
#define TE_MODEL 106 // create a moving model that bounces and makes a sound when it hits
// coord, coord, coord (position)
// coord, coord, coord (velocity)
// angle (initial yaw)
// short (model index)
// byte (bounce sound type)
// byte (life in 0.1's)
#define TE_EXPLODEMODEL 107 // spherical shower of models, picks from set
// coord, coord, coord (origin)
// coord (velocity)
// short (model index)
// short (count)
// byte (life in 0.1's)
#define TE_BREAKMODEL 108 // box of models or sprites
// coord, coord, coord (position)
// coord, coord, coord (size)
// coord, coord, coord (velocity)
// byte (random velocity in 10's)
// short (sprite or model index)
// byte (count)
// byte (life in 0.1 secs)
// byte (flags)
#define TE_GUNSHOTDECAL 109 // decal and ricochet sound
// coord, coord, coord (position)
// short (entity index???)
// byte (decal???)
#define TE_SPRITE_SPRAY 110 // spay of alpha sprites
// coord, coord, coord (position)
// coord, coord, coord (velocity)
// short (sprite index)
// byte (count)
// byte (speed)
// byte (noise)
#define TE_ARMOR_RICOCHET 111 // quick spark sprite, client ricochet sound.
// coord, coord, coord (position)
// byte (scale in 0.1's)
#define TE_PLAYERDECAL 112 // ???
// byte (playerindex)
// coord, coord, coord (position)
// short (entity???)
// byte (decal number???)
// [optional] short (model index???)
#define TE_BUBBLES 113 // create alpha sprites inside of box, float upwards
// coord, coord, coord (min start position)
// coord, coord, coord (max start position)
// coord (float height)
// short (model index)
// byte (count)
// coord (speed)
#define TE_BUBBLETRAIL 114 // create alpha sprites along a line, float upwards
// coord, coord, coord (min start position)
// coord, coord, coord (max start position)
// coord (float height)
// short (model index)
// byte (count)
// coord (speed)
#define TE_BLOODSPRITE 115 // spray of opaque sprite1's that fall, single sprite2 for 1..2 secs (this is a high-priority tent)
// coord, coord, coord (position)
// short (sprite1 index)
// short (sprite2 index)
// byte (color)
// byte (scale)
#define TE_WORLDDECAL 116 // Decal applied to the world brush
// coord, coord, coord (x,y,z), decal position (center of texture in world)
// byte (texture index of precached decal texture name)
#define TE_WORLDDECALHIGH 117 // Decal (with texture index > 256) applied to world brush
// coord, coord, coord (x,y,z), decal position (center of texture in world)
// byte (texture index of precached decal texture name - 256)
#define TE_DECALHIGH 118 // Same as TE_DECAL, but the texture index was greater than 256
// coord, coord, coord (x,y,z), decal position (center of texture in world)
// byte (texture index of precached decal texture name - 256)
// short (entity index)
#define TE_PROJECTILE 119 // Makes a projectile (like a nail) (this is a high-priority tent)
// coord, coord, coord (position)
// coord, coord, coord (velocity)
// short (modelindex)
// byte (life)
// byte (owner) projectile won't collide with owner (if owner == 0, projectile will hit any client).
#define TE_SPRAY 120 // Throws a shower of sprites or models
// coord, coord, coord (position)
// coord, coord, coord (direction)
// short (modelindex)
// byte (count)
// byte (speed)
// byte (noise)
// byte (rendermode)
#define TE_PLAYERSPRITES 121 // sprites emit from a player's bounding box (ONLY use for players!)
// byte (playernum)
// short (sprite modelindex)
// byte (count)
// byte (variance) (0 = no variance in size) (10 = 10% variance in size)
#define TE_PARTICLEBURST 122 // very similar to lavasplash.
// coord (origin)
// short (radius)
// byte (particle color)
// byte (duration * 10) (will be randomized a bit)
#define TE_FIREFIELD 123 // makes a field of fire.
// coord (origin)
// short (radius) (fire is made in a square around origin. -radius, -radius to radius, radius)
// short (modelindex)
// byte (count)
// byte (flags)
// byte (duration (in seconds) * 10) (will be randomized a bit)
//
// to keep network traffic low, this message has associated flags that fit into a byte:
#define TEFIRE_FLAG_ALLFLOAT 1 // all sprites will drift upwards as they animate
#define TEFIRE_FLAG_SOMEFLOAT 2 // some of the sprites will drift upwards. (50% chance)
#define TEFIRE_FLAG_LOOP 4 // if set, sprite plays at 15 fps, otherwise plays at whatever rate stretches the animation over the sprite's duration.
#define TEFIRE_FLAG_ALPHA 8 // if set, sprite is rendered alpha blended at 50% else, opaque
#define TEFIRE_FLAG_PLANAR 16 // if set, all fire sprites have same initial Z instead of randomly filling a cube.
#define TEFIRE_FLAG_ADDITIVE 32 // if set, sprite is rendered non-opaque with additive
#define TE_PLAYERATTACHMENT 124 // attaches a TENT to a player (this is a high-priority tent)
// byte (entity index of player)
// coord (vertical offset) ( attachment origin.z = player origin.z + vertical offset )
// short (model index)
// short (life * 10 );
#define TE_KILLPLAYERATTACHMENTS 125 // will expire all TENTS attached to a player.
// byte (entity index of player)
#define TE_MULTIGUNSHOT 126 // much more compact shotgun message
// This message is used to make a client approximate a 'spray' of gunfire.
// Any weapon that fires more than one bullet per frame and fires in a bit of a spread is
// a good candidate for MULTIGUNSHOT use. (shotguns)
//
// NOTE: This effect makes the client do traces for each bullet, these client traces ignore
// entities that have studio models.Traces are 4096 long.
//
// coord (origin)
// coord (origin)
// coord (origin)
// coord (direction)
// coord (direction)
// coord (direction)
// coord (x noise * 100)
// coord (y noise * 100)
// byte (count)
// byte (bullethole decal texture index)
#define TE_USERTRACER 127 // larger message than the standard tracer, but allows some customization.
// coord (origin)
// coord (origin)
// coord (origin)
// coord (velocity)
// coord (velocity)
// coord (velocity)
// byte ( life * 10 )
// byte ( color ) this is an index into an array of color vectors in the engine. (0 - )
// byte ( length * 10 )
#define MSG_BROADCAST 0 // unreliable to all
#define MSG_ONE 1 // reliable to one (msg_entity)
#define MSG_ALL 2 // reliable to all
#define MSG_INIT 3 // write to the init string
#define MSG_PVS 4 // Ents in PVS of org
#define MSG_PAS 5 // Ents in PAS of org
#define MSG_PVS_R 6 // Reliable to PVS
#define MSG_PAS_R 7 // Reliable to PAS
#define MSG_ONE_UNRELIABLE 8 // Send to one client, but don't put in reliable stream, put in unreliable datagram ( could be dropped )
#define MSG_SPEC 9 // Sends to all spectator proxies
// contents of a spot in the world
#define CONTENTS_EMPTY -1
#define CONTENTS_SOLID -2
#define CONTENTS_WATER -3
#define CONTENTS_SLIME -4
#define CONTENTS_LAVA -5
#define CONTENTS_SKY -6
/* These additional contents constants are defined in bspfile.h
#define CONTENTS_ORIGIN -7 // removed at csg time
#define CONTENTS_CLIP -8 // changed to contents_solid
#define CONTENTS_CURRENT_0 -9
#define CONTENTS_CURRENT_90 -10
#define CONTENTS_CURRENT_180 -11
#define CONTENTS_CURRENT_270 -12
#define CONTENTS_CURRENT_UP -13
#define CONTENTS_CURRENT_DOWN -14
#define CONTENTS_TRANSLUCENT -15
*/
#define CONTENTS_LADDER -16
#define CONTENT_FLYFIELD -17
#define CONTENT_GRAVITY_FLYFIELD -18
#define CONTENT_FOG -19
#define CONTENT_EMPTY -1
#define CONTENT_SOLID -2
#define CONTENT_WATER -3
#define CONTENT_SLIME -4
#define CONTENT_LAVA -5
#define CONTENT_SKY -6
// channels
#define CHAN_AUTO 0
#define CHAN_WEAPON 1
#define CHAN_VOICE 2
#define CHAN_ITEM 3
#define CHAN_BODY 4
#define CHAN_STREAM 5 // allocate stream channel from the static or dynamic area
#define CHAN_STATIC 6 // allocate channel from the static area
#define CHAN_NETWORKVOICE_BASE 7 // voice data coming across the network
#define CHAN_NETWORKVOICE_END 500 // network voice data reserves slots (CHAN_NETWORKVOICE_BASE through CHAN_NETWORKVOICE_END).
#define CHAN_BOT 501 // channel used for bot chatter.
// attenuation values
#define ATTN_NONE 0
#define ATTN_NORM (float)0.8
#define ATTN_IDLE (float)2
#define ATTN_STATIC (float)1.25
// pitch values
#define PITCH_NORM 100 // non-pitch shifted
#define PITCH_LOW 95 // other values are possible - 0-255, where 255 is very high
#define PITCH_HIGH 120
// volume values
#define VOL_NORM 1.0
// plats
#define PLAT_LOW_TRIGGER 1
// Trains
#define SF_TRAIN_WAIT_RETRIGGER 1
#define SF_TRAIN_START_ON 4 // Train is initially moving
#define SF_TRAIN_PASSABLE 8 // Train is not solid -- used to make water trains
// buttons
#ifndef IN_BUTTONS_H
#include "in_buttons.h"
#endif
// Break Model Defines
#define BREAK_TYPEMASK 0x4F
#define BREAK_GLASS 0x01
#define BREAK_METAL 0x02
#define BREAK_FLESH 0x04
#define BREAK_WOOD 0x08
#define BREAK_SMOKE 0x10
#define BREAK_TRANS 0x20
#define BREAK_CONCRETE 0x40
#define BREAK_2 0x80
// Colliding temp entity sounds
#define BOUNCE_GLASS BREAK_GLASS
#define BOUNCE_METAL BREAK_METAL
#define BOUNCE_FLESH BREAK_FLESH
#define BOUNCE_WOOD BREAK_WOOD
#define BOUNCE_SHRAP 0x10
#define BOUNCE_SHELL 0x20
#define BOUNCE_CONCRETE BREAK_CONCRETE
#define BOUNCE_SHOTSHELL 0x80
// Temp entity bounce sound types
#define TE_BOUNCE_NULL 0
#define TE_BOUNCE_SHELL 1
#define TE_BOUNCE_SHOTSHELL 2
// Rendering constants
enum
{
kRenderNormal, // src
kRenderTransColor, // c*a+dest*(1-a)
kRenderTransTexture, // src*a+dest*(1-a)
kRenderGlow, // src*a+dest -- No Z buffer checks
kRenderTransAlpha, // src*srca+dest*(1-srca)
kRenderTransAdd, // src*a+dest
};
enum
{
kRenderFxNone = 0,
kRenderFxPulseSlow,
kRenderFxPulseFast,
kRenderFxPulseSlowWide,
kRenderFxPulseFastWide,
kRenderFxFadeSlow,
kRenderFxFadeFast,
kRenderFxSolidSlow,
kRenderFxSolidFast,
kRenderFxStrobeSlow,
kRenderFxStrobeFast,
kRenderFxStrobeFaster,
kRenderFxFlickerSlow,
kRenderFxFlickerFast,
kRenderFxNoDissipation,
kRenderFxDistort, // Distort/scale/translate flicker
kRenderFxHologram, // kRenderFxDistort + distance fade
kRenderFxDeadPlayer, // kRenderAmt is the player index
kRenderFxExplode, // Scale up really big!
kRenderFxGlowShell, // Glowing Shell
kRenderFxClampMinScale, // Keep this sprite from getting very small (SPRITES only!)
kRenderFxLightMultiplier, //CTM !!!CZERO added to tell the studiorender that the value in iuser2 is a lightmultiplier
};
typedef unsigned int func_t;
typedef unsigned int string_t;
typedef unsigned char byte;
typedef unsigned short word;
#define _DEF_BYTE_
#undef true
#undef false
#ifndef __cplusplus
typedef enum {false, true} qboolean;
#else
typedef int qboolean;
#endif
typedef struct
{
byte r, g, b;
} color24;
typedef struct
{
unsigned r, g, b, a;
} colorVec;
#ifdef _WIN32
#pragma pack(push,2)
#endif
typedef struct
{
unsigned short r, g, b, a;
} PackedColorVec;
#ifdef _WIN32
#pragma pack(pop)
#endif
typedef struct link_s
{
struct link_s *prev, *next;
} link_t;
typedef struct edict_s edict_t;
typedef struct
{
vec3_t normal;
float dist;
} plane_t;
typedef struct
{
qboolean allsolid; // if true, plane is not valid
qboolean startsolid; // if true, the initial point was in a solid area
qboolean inopen, inwater;
float fraction; // time completed, 1.0 = didn't hit anything
vec3_t endpos; // final position
plane_t plane; // surface normal at impact
edict_t * ent; // entity the surface is on
int hitgroup; // 0 == generic, non zero is specific body part
} trace_t;
#endif // CONST_H

55
rehlds/common/crc.h Normal file
View File

@ -0,0 +1,55 @@
/***
*
* Copyright (c) 1996-2002, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
/* crc.h */
#pragma once
#include "quakedef.h"
// MD5 Hash
typedef struct
{
unsigned int buf[4];
unsigned int bits[2];
unsigned char in[64];
} MD5Context_t;
typedef unsigned int CRC32_t;
#ifdef __cplusplus
extern "C"
{
#endif
void CRC32_Init(CRC32_t *pulCRC);
CRC32_t CRC32_Final(CRC32_t pulCRC);
void CRC32_ProcessByte(CRC32_t *pulCRC, unsigned char ch);
void CRC32_ProcessBuffer(CRC32_t *pulCRC, void *pBuffer, int nBuffer);
NOXREF BOOL CRC_File(CRC32_t *crcvalue, char *pszFileName);
#ifdef __cplusplus
}
#endif
byte COM_BlockSequenceCRCByte(byte *base, int length, int sequence);
int CRC_MapFile(CRC32_t *crcvalue, char *pszFileName);
void MD5Init(MD5Context_t *ctx);
void MD5Update(MD5Context_t *ctx, const unsigned char *buf, unsigned int len);
void MD5Final(unsigned char digest[16], MD5Context_t *ctx);
void MD5Transform(unsigned int buf[4], const unsigned int in[16]);
BOOL MD5_Hash_File(unsigned char digest[16], char *pszFileName, BOOL bUsefopen, BOOL bSeed, unsigned int seed[4]);
char *MD5_Print(unsigned char hash[16]);

39
rehlds/common/cvardef.h Normal file
View File

@ -0,0 +1,39 @@
/***
*
* Copyright (c) 1996-2002, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#ifndef CVARDEF_H
#define CVARDEF_H
#define FCVAR_ARCHIVE (1<<0) // set to cause it to be saved to vars.rc
#define FCVAR_USERINFO (1<<1) // changes the client's info string
#define FCVAR_SERVER (1<<2) // notifies players when changed
#define FCVAR_EXTDLL (1<<3) // defined by external DLL
#define FCVAR_CLIENTDLL (1<<4) // defined by the client dll
#define FCVAR_PROTECTED (1<<5) // It's a server cvar, but we don't send the data since it's a password, etc. Sends 1 if it's not bland/zero, 0 otherwise as value
#define FCVAR_SPONLY (1<<6) // This cvar cannot be changed by clients connected to a multiplayer server.
#define FCVAR_PRINTABLEONLY (1<<7) // This cvar's string cannot contain unprintable characters ( e.g., used for player name etc ).
#define FCVAR_UNLOGGED (1<<8) // If this is a FCVAR_SERVER, don't log changes to the log file / console if we are creating a log
#define FCVAR_NOEXTRAWHITEPACE (1<<9) // strip trailing/leading white space from this cvar
typedef struct cvar_s
{
char *name;
char *string;
int flags;
float value;
struct cvar_s *next;
} cvar_t;
#endif // CVARDEF_H

31
rehlds/common/demo_api.h Normal file
View File

@ -0,0 +1,31 @@
/***
*
* Copyright (c) 1996-2002, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#if !defined ( DEMO_APIH )
#define DEMO_APIH
#ifdef _WIN32
#pragma once
#endif
typedef struct demo_api_s
{
int ( *IsRecording ) ( void );
int ( *IsPlayingback ) ( void );
int ( *IsTimeDemo ) ( void );
void ( *WriteBuffer ) ( int size, unsigned char *buffer );
} demo_api_t;
extern demo_api_t demoapi;
#endif

View File

@ -0,0 +1,38 @@
//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================
// director_cmds.h
// sub commands for svc_director
#define DRC_ACTIVE 0 // tells client that he's an spectator and will get director command
#define DRC_STATUS 1 // send status infos about proxy
#define DRC_CAMERA 2 // set the actual director camera position
#define DRC_EVENT 3 // informs the dircetor about ann important game event
#define DRC_FLAG_PRIO_MASK 0x0F // priorities between 0 and 15 (15 most important)
#define DRC_FLAG_SIDE (1<<4)
#define DRC_FLAG_DRAMATIC (1<<5)
// commands of the director API function CallDirectorProc(...)
#define DRCAPI_NOP 0 // no operation
#define DRCAPI_ACTIVE 1 // de/acivates director mode in engine
#define DRCAPI_STATUS 2 // request proxy information
#define DRCAPI_SETCAM 3 // set camera n to given position and angle
#define DRCAPI_GETCAM 4 // request camera n position and angle
#define DRCAPI_DIRPLAY 5 // set director time and play with normal speed
#define DRCAPI_DIRFREEZE 6 // freeze directo at this time
#define DRCAPI_SETVIEWMODE 7 // overview or 4 cameras
#define DRCAPI_SETOVERVIEWPARAMS 8 // sets parameter for overview mode
#define DRCAPI_SETFOCUS 9 // set the camera which has the input focus
#define DRCAPI_GETTARGETS 10 // queries engine for player list
#define DRCAPI_SETVIEWPOINTS 11 // gives engine all waypoints

33
rehlds/common/dlight.h Normal file
View File

@ -0,0 +1,33 @@
/***
*
* Copyright (c) 1996-2002, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#if !defined ( DLIGHTH )
#define DLIGHTH
#ifdef _WIN32
#pragma once
#endif
typedef struct dlight_s
{
vec3_t origin;
float radius;
color24 color;
float die; // stop lighting after this time
float decay; // drop this each second
float minlight; // don't add when contributing less
int key;
qboolean dark; // subtracts light instead of adding
} dlight_t;
#endif

23
rehlds/common/dll_state.h Normal file
View File

@ -0,0 +1,23 @@
//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================
//DLL State Flags
#define DLL_INACTIVE 0 // no dll
#define DLL_ACTIVE 1 // dll is running
#define DLL_PAUSED 2 // dll is paused
#define DLL_CLOSE 3 // closing down dll
#define DLL_TRANS 4 // Level Transition
// DLL Pause reasons
#define DLL_NORMAL 0 // User hit Esc or something.
#define DLL_QUIT 4 // Quit now
#define DLL_RESTART 5 // Switch to launcher for linux, does a quit but returns 1
// DLL Substate info ( not relevant )
#define ENG_NORMAL (1<<0)

View File

@ -0,0 +1,197 @@
/***
*
* Copyright (c) 1996-2002, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#ifndef ENTITY_STATE_H
#define ENTITY_STATE_H
#ifdef _WIN32
#pragma once
#endif
#include "const.h"
// For entityType below
#define ENTITY_NORMAL (1<<0)
#define ENTITY_BEAM (1<<1)
// Entity state is used for the baseline and for delta compression of a packet of
// entities that is sent to a client.
typedef struct entity_state_s entity_state_t;
struct entity_state_s
{
// Fields which are filled in by routines outside of delta compression
int entityType;
// Index into cl_entities array for this entity.
int number;
float msg_time;
// Message number last time the player/entity state was updated.
int messagenum;
// Fields which can be transitted and reconstructed over the network stream
vec3_t origin;
vec3_t angles;
int modelindex;
int sequence;
float frame;
int colormap;
short skin;
short solid;
int effects;
float scale;
byte eflags;
// Render information
int rendermode;
int renderamt;
color24 rendercolor;
int renderfx;
int movetype;
float animtime;
float framerate;
int body;
byte controller[4];
byte blending[4];
vec3_t velocity;
// Send bbox down to client for use during prediction.
vec3_t mins;
vec3_t maxs;
int aiment;
// If owned by a player, the index of that player ( for projectiles ).
int owner;
// Friction, for prediction.
float friction;
// Gravity multiplier
float gravity;
// PLAYER SPECIFIC
int team;
int playerclass;
int health;
qboolean spectator;
int weaponmodel;
int gaitsequence;
// If standing on conveyor, e.g.
vec3_t basevelocity;
// Use the crouched hull, or the regular player hull.
int usehull;
// Latched buttons last time state updated.
int oldbuttons;
// -1 = in air, else pmove entity number
int onground;
int iStepLeft;
// How fast we are falling
float flFallVelocity;
float fov;
int weaponanim;
// Parametric movement overrides
vec3_t startpos;
vec3_t endpos;
float impacttime;
float starttime;
// For mods
int iuser1;
int iuser2;
int iuser3;
int iuser4;
float fuser1;
float fuser2;
float fuser3;
float fuser4;
vec3_t vuser1;
vec3_t vuser2;
vec3_t vuser3;
vec3_t vuser4;
};
#include "pm_info.h"
typedef struct clientdata_s
{
vec3_t origin;
vec3_t velocity;
int viewmodel;
vec3_t punchangle;
int flags;
int waterlevel;
int watertype;
vec3_t view_ofs;
float health;
int bInDuck;
int weapons; // remove?
int flTimeStepSound;
int flDuckTime;
int flSwimTime;
int waterjumptime;
float maxspeed;
float fov;
int weaponanim;
int m_iId;
int ammo_shells;
int ammo_nails;
int ammo_cells;
int ammo_rockets;
float m_flNextAttack;
int tfstate;
int pushmsec;
int deadflag;
char physinfo[ MAX_PHYSINFO_STRING ];
// For mods
int iuser1;
int iuser2;
int iuser3;
int iuser4;
float fuser1;
float fuser2;
float fuser3;
float fuser4;
vec3_t vuser1;
vec3_t vuser2;
vec3_t vuser3;
vec3_t vuser4;
} clientdata_t;
#include "weaponinfo.h"
typedef struct local_state_s
{
entity_state_t playerstate;
clientdata_t client;
weapon_data_t weapondata[ 64 ];
} local_state_t;
#endif // ENTITY_STATE_H

View File

@ -0,0 +1,26 @@
/***
*
* Copyright (c) 1996-2002, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
// entity_types.h
#if !defined( ENTITY_TYPESH )
#define ENTITY_TYPESH
#define ET_NORMAL 0
#define ET_PLAYER 1
#define ET_TEMPENTITY 2
#define ET_BEAM 3
// BMODEL or SPRITE that was split across BSP nodes
#define ET_FRAGMENTED 4
#endif // !ENTITY_TYPESH

27
rehlds/common/enums.h Normal file
View File

@ -0,0 +1,27 @@
/***
*
* Copyright (c) 2009, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#ifndef ENUMS_H
#define ENUMS_H
typedef enum netsrc_s
{
NS_CLIENT,
NS_SERVER,
NS_MULTICAST // xxxMO
} netsrc_t;
#endif

51
rehlds/common/event_api.h Normal file
View File

@ -0,0 +1,51 @@
/***
*
* Copyright (c) 1996-2002, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#if !defined ( EVENT_APIH )
#define EVENT_APIH
#ifdef _WIN32
#pragma once
#endif
#define EVENT_API_VERSION 1
typedef struct event_api_s
{
int version;
void ( *EV_PlaySound ) ( int ent, float *origin, int channel, const char *sample, float volume, float attenuation, int fFlags, int pitch );
void ( *EV_StopSound ) ( int ent, int channel, const char *sample );
int ( *EV_FindModelIndex )( const char *pmodel );
int ( *EV_IsLocal ) ( int playernum );
int ( *EV_LocalPlayerDucking ) ( void );
void ( *EV_LocalPlayerViewheight ) ( float * );
void ( *EV_LocalPlayerBounds ) ( int hull, float *mins, float *maxs );
int ( *EV_IndexFromTrace) ( struct pmtrace_s *pTrace );
struct physent_s *( *EV_GetPhysent ) ( int idx );
void ( *EV_SetUpPlayerPrediction ) ( int dopred, int bIncludeLocalClient );
void ( *EV_PushPMStates ) ( void );
void ( *EV_PopPMStates ) ( void );
void ( *EV_SetSolidPlayers ) (int playernum);
void ( *EV_SetTraceHull ) ( int hull );
void ( *EV_PlayerTrace ) ( float *start, float *end, int traceFlags, int ignore_pe, struct pmtrace_s *tr );
void ( *EV_WeaponAnimation ) ( int sequence, int body );
unsigned short ( *EV_PrecacheEvent ) ( int type, const char* psz );
void ( *EV_PlaybackEvent ) ( int flags, const struct edict_s *pInvoker, unsigned short eventindex, float delay, float *origin, float *angles, float fparam1, float fparam2, int iparam1, int iparam2, int bparam1, int bparam2 );
const char *( *EV_TraceTexture ) ( int ground, float *vstart, float *vend );
void ( *EV_StopAllSounds ) ( int entnum, int entchannel );
void ( *EV_KillEvents ) ( int entnum, const char *eventname );
} event_api_t;
extern event_api_t eventapi;
#endif

View File

@ -0,0 +1,50 @@
/***
*
* Copyright (c) 1996-2002, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#if !defined( EVENT_ARGSH )
#define EVENT_ARGSH
#ifdef _WIN32
#pragma once
#endif
// Event was invoked with stated origin
#define FEVENT_ORIGIN ( 1<<0 )
// Event was invoked with stated angles
#define FEVENT_ANGLES ( 1<<1 )
typedef struct event_args_s
{
int flags;
// Transmitted
int entindex;
float origin[3];
float angles[3];
float velocity[3];
int ducking;
float fparam1;
float fparam2;
int iparam1;
int iparam2;
int bparam1;
int bparam2;
} event_args_t;
#endif

View File

@ -0,0 +1,47 @@
/***
*
* Copyright (c) 1996-2002, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#if !defined( EVENT_FLAGSH )
#define EVENT_FLAGSH
#ifdef _WIN32
#pragma once
#endif
// Skip local host for event send.
#define FEV_NOTHOST (1<<0)
// Send the event reliably. You must specify the origin and angles and use
// PLAYBACK_EVENT_FULL for this to work correctly on the server for anything
// that depends on the event origin/angles. I.e., the origin/angles are not
// taken from the invoking edict for reliable events.
#define FEV_RELIABLE (1<<1)
// Don't restrict to PAS/PVS, send this event to _everybody_ on the server ( useful for stopping CHAN_STATIC
// sounds started by client event when client is not in PVS anymore ( hwguy in TFC e.g. ).
#define FEV_GLOBAL (1<<2)
// If this client already has one of these events in its queue, just update the event instead of sending it as a duplicate
//
#define FEV_UPDATE (1<<3)
// Only send to entity specified as the invoker
#define FEV_HOSTONLY (1<<4)
// Only send if the event was created on the server.
#define FEV_SERVER (1<<5)
// Only issue event client side ( from shared code )
#define FEV_CLIENT (1<<6)
#endif

61
rehlds/common/hltv.h Normal file
View File

@ -0,0 +1,61 @@
//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================
// hltv.h
// all shared consts between server, clients and proxy
#ifndef HLTV_H
#define HLTV_H
#define TYPE_CLIENT 0 // client is a normal HL client (default)
#define TYPE_PROXY 1 // client is another proxy
#define TYPE_COMMENTATOR 3 // client is a commentator
#define TYPE_DEMO 4 // client is a demo file
// sub commands of svc_hltv:
#define HLTV_ACTIVE 0 // tells client that he's an spectator and will get director commands
#define HLTV_STATUS 1 // send status infos about proxy
#define HLTV_LISTEN 2 // tell client to listen to a multicast stream
// director command types:
#define DRC_CMD_NONE 0 // NULL director command
#define DRC_CMD_START 1 // start director mode
#define DRC_CMD_EVENT 2 // informs about director command
#define DRC_CMD_MODE 3 // switches camera modes
#define DRC_CMD_CAMERA 4 // set fixed camera
#define DRC_CMD_TIMESCALE 5 // sets time scale
#define DRC_CMD_MESSAGE 6 // send HUD centerprint
#define DRC_CMD_SOUND 7 // plays a particular sound
#define DRC_CMD_STATUS 8 // HLTV broadcast status
#define DRC_CMD_BANNER 9 // set GUI banner
#define DRC_CMD_STUFFTEXT 10 // like the normal svc_stufftext but as director command
#define DRC_CMD_CHASE 11 // chase a certain player
#define DRC_CMD_INEYE 12 // view player through own eyes
#define DRC_CMD_MAP 13 // show overview map
#define DRC_CMD_CAMPATH 14 // define camera waypoint
#define DRC_CMD_WAYPOINTS 15 // start moving camera, inetranl message
#define DRC_CMD_LAST 15
// DRC_CMD_EVENT event flags
#define DRC_FLAG_PRIO_MASK 0x0F // priorities between 0 and 15 (15 most important)
#define DRC_FLAG_SIDE (1<<4) //
#define DRC_FLAG_DRAMATIC (1<<5) // is a dramatic scene
#define DRC_FLAG_SLOWMOTION (1<<6) // would look good in SloMo
#define DRC_FLAG_FACEPLAYER (1<<7) // player is doning something (reload/defuse bomb etc)
#define DRC_FLAG_INTRO (1<<8) // is a introduction scene
#define DRC_FLAG_FINAL (1<<9) // is a final scene
#define DRC_FLAG_NO_RANDOM (1<<10) // don't randomize event data
// DRC_CMD_WAYPOINT flags
#define DRC_FLAG_STARTPATH 1 // end with speed 0.0
#define DRC_FLAG_SLOWSTART 2 // start with speed 0.0
#define DRC_FLAG_SLOWEND 4 // end with speed 0.0
#endif // HLTV_H

View File

@ -0,0 +1,38 @@
/***
*
* Copyright (c) 1996-2002, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#ifndef IN_BUTTONS_H
#define IN_BUTTONS_H
#ifdef _WIN32
#pragma once
#endif
#define IN_ATTACK (1 << 0)
#define IN_JUMP (1 << 1)
#define IN_DUCK (1 << 2)
#define IN_FORWARD (1 << 3)
#define IN_BACK (1 << 4)
#define IN_USE (1 << 5)
#define IN_CANCEL (1 << 6)
#define IN_LEFT (1 << 7)
#define IN_RIGHT (1 << 8)
#define IN_MOVELEFT (1 << 9)
#define IN_MOVERIGHT (1 << 10)
#define IN_ATTACK2 (1 << 11)
#define IN_RUN (1 << 12)
#define IN_RELOAD (1 << 13)
#define IN_ALT1 (1 << 14)
#define IN_SCORE (1 << 15) // Used by client.dll for when scoreboard is held down
#endif // IN_BUTTONS_H

View File

@ -0,0 +1,38 @@
//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================
#ifndef IVOICETWEAK_H
#define IVOICETWEAK_H
#ifdef _WIN32
#pragma once
#endif
// These provide access to the voice controls.
typedef enum
{
MicrophoneVolume=0, // values 0-1.
OtherSpeakerScale, // values 0-1. Scales how loud other players are.
MicBoost, // 20 db gain to voice input
} VoiceTweakControl;
typedef struct IVoiceTweak_s
{
// These turn voice tweak mode on and off. While in voice tweak mode, the user's voice is echoed back
// without sending to the server.
int (*StartVoiceTweakMode)(); // Returns 0 on error.
void (*EndVoiceTweakMode)();
// Get/set control values.
void (*SetControlFloat)(VoiceTweakControl iControl, float value);
float (*GetControlFloat)(VoiceTweakControl iControl);
int (*GetSpeakingVolume)();
} IVoiceTweak;
#endif // IVOICETWEAK_H

44
rehlds/common/kbutton.h Normal file
View File

@ -0,0 +1,44 @@
/*
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game Engine ("HL
* Engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL Engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef KBUTTON_H
#define KBUTTON_H
#ifdef _WIN32
#pragma once
#endif
/* <31b2a> ../common/kbutton.h:7 */
typedef struct kbutton_s
{
int down[2];
int state;
} kbutton_t;
#endif // KBUTTON_H

49
rehlds/common/mathlib.h Normal file
View File

@ -0,0 +1,49 @@
/***
*
* Copyright (c) 1996-2002, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#pragma once
/* <42b7f> ../common/mathlib.h:3 */
typedef float vec_t;
/* <42b91> ../common/mathlib.h:6 */
typedef vec_t vec3_t[3];
/* <80013> ../common/mathlib.h:8 */
typedef vec_t vec4_t[4];
/* <42bac> ../common/mathlib.h:18 */
typedef int fixed16_t; /* size: 4 */
/* <42bb7> ../common/mathlib.h:60 */
typedef union DLONG_u
{
int i[2];
double d;
float f;
} DLONG;
#define M_PI 3.14159265358979323846
#ifndef max
#define max(a,b) (((a) > (b)) ? (a) : (b))
#endif
#ifndef min
#define min(a,b) (((a) < (b)) ? (a) : (b))
#endif
#define clamp(val, min, max) (((val) > (max)) ? (max) : (((val) < (min)) ? (min) : (val)))

99
rehlds/common/net_api.h Normal file
View File

@ -0,0 +1,99 @@
//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================
#if !defined( NET_APIH )
#define NET_APIH
#ifdef _WIN32
#pragma once
#endif
#if !defined ( NETADRH )
#include "netadr.h"
#endif
#define NETAPI_REQUEST_SERVERLIST ( 0 ) // Doesn't need a remote address
#define NETAPI_REQUEST_PING ( 1 )
#define NETAPI_REQUEST_RULES ( 2 )
#define NETAPI_REQUEST_PLAYERS ( 3 )
#define NETAPI_REQUEST_DETAILS ( 4 )
// Set this flag for things like broadcast requests, etc. where the engine should not
// kill the request hook after receiving the first response
#define FNETAPI_MULTIPLE_RESPONSE ( 1<<0 )
typedef void ( *net_api_response_func_t ) ( struct net_response_s *response );
#define NET_SUCCESS ( 0 )
#define NET_ERROR_TIMEOUT ( 1<<0 )
#define NET_ERROR_PROTO_UNSUPPORTED ( 1<<1 )
#define NET_ERROR_UNDEFINED ( 1<<2 )
typedef struct net_adrlist_s
{
struct net_adrlist_s *next;
netadr_t remote_address;
} net_adrlist_t;
typedef struct net_response_s
{
// NET_SUCCESS or an error code
int error;
// Context ID
int context;
// Type
int type;
// Server that is responding to the request
netadr_t remote_address;
// Response RTT ping time
double ping;
// Key/Value pair string ( separated by backlash \ characters )
// WARNING: You must copy this buffer in the callback function, because it is freed
// by the engine right after the call!!!!
// ALSO: For NETAPI_REQUEST_SERVERLIST requests, this will be a pointer to a linked list of net_adrlist_t's
void *response;
} net_response_t;
typedef struct net_status_s
{
// Connected to remote server? 1 == yes, 0 otherwise
int connected;
// Client's IP address
netadr_t local_address;
// Address of remote server
netadr_t remote_address;
// Packet Loss ( as a percentage )
int packet_loss;
// Latency, in seconds ( multiply by 1000.0 to get milliseconds )
double latency;
// Connection time, in seconds
double connection_time;
// Rate setting ( for incoming data )
double rate;
} net_status_t;
typedef struct net_api_s
{
// APIs
void ( *InitNetworking )( void );
void ( *Status ) ( struct net_status_s *status );
void ( *SendRequest) ( int context, int request, int flags, double timeout, struct netadr_s *remote_address, net_api_response_func_t response );
void ( *CancelRequest ) ( int context );
void ( *CancelAllRequests ) ( void );
char *( *AdrToString ) ( struct netadr_s *a );
int ( *CompareAdr ) ( struct netadr_s *a, struct netadr_s *b );
int ( *StringToAdr ) ( char *s, struct netadr_s *a );
const char *( *ValueForKey ) ( const char *s, const char *key );
void ( *RemoveKey ) ( char *s, const char *key );
void ( *SetValueForKey ) (char *s, const char *key, const char *value, int maxsize );
} net_api_t;
extern net_api_t netapi;
#endif // NET_APIH

40
rehlds/common/netadr.h Normal file
View File

@ -0,0 +1,40 @@
/***
*
* Copyright (c) 1996-2002, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
// netadr.h
#ifndef NETADR_H
#define NETADR_H
#ifdef _WIN32
#pragma once
#endif
typedef enum
{
NA_UNUSED,
NA_LOOPBACK,
NA_BROADCAST,
NA_IP,
NA_IPX,
NA_BROADCAST_IPX,
} netadrtype_t;
typedef struct netadr_s
{
netadrtype_t type;
unsigned char ip[4];
unsigned char ipx[10];
unsigned short port;
} netadr_t;
#endif // NETADR_H

16
rehlds/common/nowin.h Normal file
View File

@ -0,0 +1,16 @@
//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================
#ifndef INC_NOWIN_H
#define INC_NOWIN_H
#ifndef _WIN32
#include <unistd.h>
#include <sys/types.h>
#endif //!_WIN32
#endif //INC_NOWIN_H

259
rehlds/common/parsemsg.cpp Normal file
View File

@ -0,0 +1,259 @@
/***
*
* Copyright (c) 1999, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
//
// parsemsg.cpp
//
//--------------------------------------------------------------------------------------------------------------
#include "parsemsg.h"
#include <port.h>
typedef unsigned char byte;
#define true 1
static byte *gpBuf;
static int giSize;
static int giRead;
static int giBadRead;
int READ_OK( void )
{
return !giBadRead;
}
void BEGIN_READ( void *buf, int size )
{
giRead = 0;
giBadRead = 0;
giSize = size;
gpBuf = (byte*)buf;
}
int READ_CHAR( void )
{
int c;
if (giRead + 1 > giSize)
{
giBadRead = true;
return -1;
}
c = (signed char)gpBuf[giRead];
giRead++;
return c;
}
int READ_BYTE( void )
{
int c;
if (giRead+1 > giSize)
{
giBadRead = true;
return -1;
}
c = (unsigned char)gpBuf[giRead];
giRead++;
return c;
}
int READ_SHORT( void )
{
int c;
if (giRead+2 > giSize)
{
giBadRead = true;
return -1;
}
c = (short)( gpBuf[giRead] + ( gpBuf[giRead+1] << 8 ) );
giRead += 2;
return c;
}
int READ_WORD( void )
{
return READ_SHORT();
}
int READ_LONG( void )
{
int c;
if (giRead+4 > giSize)
{
giBadRead = true;
return -1;
}
c = gpBuf[giRead] + (gpBuf[giRead + 1] << 8) + (gpBuf[giRead + 2] << 16) + (gpBuf[giRead + 3] << 24);
giRead += 4;
return c;
}
float READ_FLOAT( void )
{
union
{
byte b[4];
float f;
int l;
} dat;
dat.b[0] = gpBuf[giRead];
dat.b[1] = gpBuf[giRead+1];
dat.b[2] = gpBuf[giRead+2];
dat.b[3] = gpBuf[giRead+3];
giRead += 4;
// dat.l = LittleLong (dat.l);
return dat.f;
}
char* READ_STRING( void )
{
static char string[2048];
int l,c;
string[0] = 0;
l = 0;
do
{
if ( giRead+1 > giSize )
break; // no more characters
c = READ_CHAR();
if (c == -1 || c == 0)
break;
string[l] = c;
l++;
} while (l < sizeof(string)-1);
string[l] = 0;
return string;
}
float READ_COORD( void )
{
return (float)(READ_SHORT() * (1.0/8));
}
float READ_ANGLE( void )
{
return (float)(READ_CHAR() * (360.0/256));
}
float READ_HIRESANGLE( void )
{
return (float)(READ_SHORT() * (360.0/65536));
}
//--------------------------------------------------------------------------------------------------------------
BufferWriter::BufferWriter()
{
Init( NULL, 0 );
}
//--------------------------------------------------------------------------------------------------------------
BufferWriter::BufferWriter( unsigned char *buffer, int bufferLen )
{
Init( buffer, bufferLen );
}
//--------------------------------------------------------------------------------------------------------------
void BufferWriter::Init( unsigned char *buffer, int bufferLen )
{
m_overflow = false;
m_buffer = buffer;
m_remaining = bufferLen;
m_overallLength = bufferLen;
}
//--------------------------------------------------------------------------------------------------------------
void BufferWriter::WriteByte( unsigned char data )
{
if (!m_buffer || !m_remaining)
{
m_overflow = true;
return;
}
*m_buffer = data;
++m_buffer;
--m_remaining;
}
//--------------------------------------------------------------------------------------------------------------
void BufferWriter::WriteLong( int data )
{
if (!m_buffer || m_remaining < 4)
{
m_overflow = true;
return;
}
m_buffer[0] = data&0xff;
m_buffer[1] = (data>>8)&0xff;
m_buffer[2] = (data>>16)&0xff;
m_buffer[3] = data>>24;
m_buffer += 4;
m_remaining -= 4;
}
//--------------------------------------------------------------------------------------------------------------
void BufferWriter::WriteString( const char *str )
{
if (!m_buffer || !m_remaining)
{
m_overflow = true;
return;
}
if (!str)
str = "";
int len = strlen(str)+1;
if ( len > m_remaining )
{
m_overflow = true;
str = "";
len = 1;
}
strcpy((char *)m_buffer, str);
m_remaining -= len;
m_buffer += len;
}
//--------------------------------------------------------------------------------------------------------------
int BufferWriter::GetSpaceUsed()
{
return m_overallLength - m_remaining;
}
//--------------------------------------------------------------------------------------------------------------

Some files were not shown because too many files have changed in this diff Show More